mirror of
https://github.com/ZHANGTIANYAO1/teamspeak-music-bot.git
synced 2026-12-01 02:12:50 +08:00
Compare commits
112
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fc4d472685 | ||
|
|
b0393b42b2 | ||
|
|
de6b050646 | ||
|
|
20ad2d44a7 | ||
|
|
2db8c4cc05 | ||
|
|
f965b70c22 | ||
|
|
135ff0ae0e | ||
|
|
d130652279 | ||
|
|
e5470b6b78 | ||
|
|
5c2a9468bd | ||
|
|
afb1cd7c14 | ||
|
|
0adf21c566 | ||
|
|
23b36e2019 | ||
|
|
d0e1422af7 | ||
|
|
1b57af6722 | ||
|
|
fbc12aa11b | ||
|
|
8ec3dcc405 | ||
|
|
bd03cb1c59 | ||
|
|
5c05eae530 | ||
|
|
c72cd4f233 | ||
|
|
dc2659628e | ||
|
|
ad5568187d | ||
|
|
cb01cd3049 | ||
|
|
db3b6b2f66 | ||
|
|
d34e249f8a | ||
|
|
6546bbd830 | ||
|
|
a33fdc1aab | ||
|
|
b25cdba161 | ||
|
|
90a4d80958 | ||
|
|
a47917afb1 | ||
|
|
17b092f2e4 | ||
|
|
0360088710 | ||
|
|
ea05787cb7 | ||
|
|
84e04ee2d2 | ||
|
|
406ecda7d7 | ||
|
|
4ee1e6f812 | ||
|
|
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 | ||
|
|
17008ae52e | ||
|
|
6f165b5e88 | ||
|
|
7ee8b6f986 | ||
|
|
7896c9c9bf | ||
|
|
a0f0b49a4e | ||
|
|
c26998d296 | ||
|
|
8d750d19b0 | ||
|
|
28c128d0c9 | ||
|
|
e5879ea106 | ||
|
|
44a1457baa | ||
|
|
a4c0239a59 | ||
|
|
5258ba951b | ||
|
|
d16aca2ba6 | ||
|
|
9bcddb1881 | ||
|
|
cf83916f39 | ||
|
|
f8b03acca3 | ||
|
|
b9c79c8138 | ||
|
|
79fb8443be | ||
|
|
c904190912 | ||
|
|
41b81a6193 | ||
|
|
f495ca0ff4 | ||
|
|
bdb33df89d | ||
|
|
3423bf502c | ||
|
|
b6ad536bb7 | ||
|
|
af4ca56fd3 | ||
|
|
bf7858db74 | ||
|
|
e4eea8276a | ||
|
|
aab8a004ae | ||
|
|
87fca6d8b7 | ||
|
|
c7b1268281 | ||
|
|
b942a4726e | ||
|
|
ad728a3a04 | ||
|
|
c51d311ab6 | ||
|
|
ac4a12d8bd | ||
|
|
07ad861ecf | ||
|
|
88e6b5a691 | ||
|
|
6b82df4e50 | ||
|
|
faf6ac09ec | ||
|
|
8ff51ea6e0 | ||
|
|
3c0e8df763 | ||
|
|
2ea02f54d9 | ||
|
|
1407cadf7b | ||
|
|
9fd1b39092 |
No files matched your search
@@ -42,7 +42,7 @@
|
||||
- **完整播放控制** — 播放/暂停/上一首/下一首/进度跳转/音量调节
|
||||
- **四种播放模式** — 顺序播放/循环播放/随机播放/随机循环
|
||||
- **实时歌词同步** — 歌词滚动显示,支持翻译歌词,服务端帧计数精确同步
|
||||
- **歌单管理** — 推荐歌单/我的歌单/每日推荐/私人FM,点击播放全部;私人 FM 支持网易云、**QQ 音乐雷达推荐**(`!fm -q`)与**酷狗私人电台**(`!fm -k`)。网易云、QQ、酷狗均提供登录后的推荐歌单 / 每日推荐 / 我的歌单
|
||||
- **歌单管理** — 推荐歌单/我的歌单/每日推荐/私人FM,点击播放全部;私人 FM 支持网易云、**QQ 音乐雷达推荐**(`!fm -q`)与**酷狗私人电台**(`!fm -k`)。网易云、QQ、酷狗均提供登录后的推荐歌单 / 每日推荐 / 我的歌单。多人共用时,每个网页端用户可在 **设置 → 账户** 扫码绑定**自己的网易云账号**,之后他在网页端开启的网易云私人 FM 按他自己的口味推荐(未绑定则用机器人的共享账号;TS 聊天里的 `!fm` 仍用共享账号)
|
||||
- **音质选择** — 标准(128k) / 较高(192k) / 极高(320k) / 无损(FLAC) / Hi-Res / 超清母带
|
||||
- **B站视频音频提取** — 搜索B站视频,自动提取DASH最高码率音频流播放
|
||||
- **B站热门推荐** — 首页展示B站热门视频和个性化推荐(登录后更准确)
|
||||
@@ -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,14 +135,65 @@ ports:
|
||||
|
||||
</details>
|
||||
|
||||
### 方式四:Linux 一键安装
|
||||
#### 无法访问 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 下有两个脚本,按需二选一:
|
||||
|
||||
| | `scripts/install.sh`(一键安装 + 系统服务) | `scripts/setup.sh`(只安装构建) |
|
||||
|---|---|---|
|
||||
| 适合 | 想开箱即用、开机自启的服务器 | 想自己决定怎么常驻(screen / tmux / pm2 / 自写服务)的用户,或 macOS |
|
||||
| Node.js | 没有或版本过低时**自动安装 Node 22 LTS**(apt / yum / pacman) | **不会安装**,需先自行装好 Node 22.12+ |
|
||||
| 系统依赖 | 自动安装构建工具(和 FFmpeg,作为内置 FFmpeg 的后备) | 不安装,只提示 |
|
||||
| 安装位置 | 构建后复制到 `/opt/tsmusicbot`(重装时保留 `data/`) | 就在当前项目目录 |
|
||||
| 系统服务 | 自动配置 systemd 服务 `tsmusicbot` 并开机自启 | **不配置服务**,完成后自己 `npm start` |
|
||||
| 需要 root | 是(`sudo`) | 否 |
|
||||
|
||||
两者共用同一套安装逻辑:`install.sh` 会调用 `setup.sh` 完成依赖安装、国内网络镜像切换、原生模块校验和构建,然后再复制文件、配置服务。
|
||||
|
||||
**一键安装 + systemd 服务:**
|
||||
|
||||
```bash
|
||||
chmod +x scripts/install.sh
|
||||
sudo ./scripts/install.sh
|
||||
# 之后:systemctl status|restart|stop tsmusicbot,日志:journalctl -u tsmusicbot -f
|
||||
```
|
||||
|
||||
自动安装 Node.js 和依赖,配置 systemd 服务,支持开机自启。
|
||||
**只安装构建(不装 Node、不配服务):**
|
||||
|
||||
```bash
|
||||
bash scripts/setup.sh
|
||||
npm start
|
||||
```
|
||||
|
||||
## 更新升级
|
||||
|
||||
@@ -281,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` 中,更新不会丢失。
|
||||
@@ -326,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 页面说明
|
||||
|
||||
| 页面 | 功能 |
|
||||
@@ -364,6 +425,7 @@ sudo systemctl start tsmusicbot
|
||||
| `!mode <seq\|loop\|random\|rloop>` | 切换播放模式 |
|
||||
| `!playlist <歌单名或ID>` | 加载歌单(支持名称模糊搜索和 ID;Jellyfin 歌单 GUID 也可直接粘贴) |
|
||||
| `!playlist -q <歌单名>` | 从 QQ 音乐搜索并加载歌单 |
|
||||
| `!playlist <歌单链接>` | 直接粘贴网易云 / QQ 音乐 / YouTube 歌单链接加载,平台由链接自动识别,无需加 `-q` 等标志;也可直接粘贴 App 的分享文案或短链(`163cn.tv`、`c6.y.qq.com`) |
|
||||
| `!album <专辑名或ID>` | 加载专辑(支持名称搜索 / 数字 ID / Jellyfin GUID) |
|
||||
| `!artist <歌手名>` | 按歌手循环播放(支持 `-j`/`-n`/`-q`/`-k`/`-b`/`-y`) |
|
||||
| `!fm` | 私人 FM(默认网易云,自动续播) |
|
||||
@@ -440,6 +502,52 @@ sudo systemctl start tsmusicbot
|
||||
|
||||
聊天命令、WebUI、REST API 三种入口的改动都会被持久化。播放队列、当前歌曲、进度、`!fm` / `!artist` 等临时播放状态仍为一次性状态,重启后不保留(`!fm` / `!artist` 内部临时切换的随机 / 循环也**不会**覆盖你用 `!mode` 显式保存的偏好)。
|
||||
|
||||
## REST API(API Key)
|
||||
|
||||
除浏览器 session 登录外,REST API 还支持用 **API Key** 调用,便于脚本、Home Assistant 等外部集成。
|
||||
|
||||
### 创建 Key
|
||||
|
||||
登录 WebUI → 设置页 → 「API 密钥」→ 输入名称 → 生成。明文**只在创建时显示一次**(形如 `tsmb_xxxxx…`),之后只能看到前缀;可随时在设置页吊销。Key 的权限与所属账户一致:管理员拥有全部权限,成员只能操作被授权的机器人、使用被授予的能力(播放控制 / 队列管理等)。每位用户最多创建 20 个 Key。
|
||||
|
||||
### 调用方式
|
||||
|
||||
两种请求头任选其一:
|
||||
|
||||
```
|
||||
Authorization: Bearer tsmb_xxxxxxxxxxxx
|
||||
X-API-Key: tsmb_xxxxxxxxxxxx
|
||||
```
|
||||
|
||||
> 修改类请求(POST/PUT/DELETE)无需 CSRF Origin 头;WebSocket 推送(`/ws`)暂不支持 API Key,仅限浏览器 session。
|
||||
|
||||
### 常用端点示例
|
||||
|
||||
```bash
|
||||
# 机器人列表(拿到 botId)
|
||||
curl -H "Authorization: Bearer $KEY" http://127.0.0.1:3000/api/bot
|
||||
|
||||
# 当前队列 + 播放状态
|
||||
curl -H "Authorization: Bearer $KEY" http://127.0.0.1:3000/api/player/<botId>/queue
|
||||
|
||||
# 点歌(搜索文本 + 平台:netease/qq/bilibili/youtube/kugou/jellyfin/local)
|
||||
curl -X POST -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
|
||||
-d '{"query":"周杰伦 晴天","platform":"netease"}' \
|
||||
http://127.0.0.1:3000/api/player/<botId>/play
|
||||
|
||||
# 搜索歌曲(拿 song id / song 对象)
|
||||
curl -H "Authorization: Bearer $KEY" \
|
||||
"http://127.0.0.1:3000/api/music/search?q=晴天&platform=netease"
|
||||
|
||||
# 播放控制
|
||||
curl -X POST -H "X-API-Key: $KEY" http://127.0.0.1:3000/api/player/<botId>/pause
|
||||
curl -X POST -H "X-API-Key: $KEY" http://127.0.0.1:3000/api/player/<botId>/next
|
||||
curl -X POST -H "X-API-Key: $KEY" -H "Content-Type: application/json" \
|
||||
-d '{"volume":50}' http://127.0.0.1:3000/api/player/<botId>/volume
|
||||
```
|
||||
|
||||
全部端点、参数与返回值见 **[docs/API.md](docs/API.md)**。认证失败返回 `401 {"error":"invalid api key"}`,越权返回 `403`。
|
||||
|
||||
## 项目架构
|
||||
|
||||
```
|
||||
@@ -495,6 +603,7 @@ teamspeak-music-bot/
|
||||
├── scripts/ # 部署脚本
|
||||
│ ├── setup.bat # Windows 首次安装
|
||||
│ ├── start.bat # Windows 启动脚本
|
||||
│ ├── setup.sh # Linux/macOS 首次安装(只安装构建)
|
||||
│ ├── install.sh # Linux 一键安装 + systemd 服务
|
||||
│ └── docker/ # Docker 部署文件
|
||||
│ ├── Dockerfile
|
||||
@@ -514,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) |
|
||||
@@ -796,6 +905,10 @@ OAuth 相关端点:`/api/spotify/login`、`/api/spotify/callback`、`/api/spot
|
||||
|
||||
## 常见问题
|
||||
|
||||
**点歌时提示网易云 `-460` 或酷狗 `20028` 怎么办?**
|
||||
|
||||
网易云 `-460` 表示上游拒绝本次取流,可稍后用同一首歌重试。酷狗 `20028` 表示平台要求验证,请在酷狗检查账号状态。自动切歌时,机器人会在本次切歌中跳过要求验证或已限制请求的音源,并尝试队列里的其他音源。反馈时提供机器人版本、音源、歌曲 ID、时间点和错误码即可。
|
||||
|
||||
**Q:支持 TeamSpeak 6 Server 吗?**
|
||||
A:支持。本项目内置 TS3/TS6 双协议支持,连接时会自动检测服务器类型。如果自动检测失败(例如 Query 端口被防火墙屏蔽),可以在创建机器人时手动指定 `serverProtocol: "ts6"`。TS6 Server 的 HTTP Query API(端口 10080)也已适配,需要时可配置 `ts6ApiKey`。
|
||||
|
||||
@@ -818,7 +931,7 @@ A:使用 `!move <频道名>` 命令,或在设置页面创建机器人时指
|
||||
A:可以。在设置页面创建多个实例,分别连接不同的 TS 服务器或频道。
|
||||
|
||||
**Q:端口 3200 被占用?**
|
||||
A:QQ 音乐 API 启动时会监听 `config.json` 里的 `qqMusicApiPort`(默认 **3200**),客户端也用同一个端口发请求,二者始终一致。如果之前的进程还在运行,程序会自动复用。如需改端口,改 `qqMusicApiPort` 后重启即可;如需重启可手动结束 `node` 进程。
|
||||
A:QQ 音乐 API 使用 `config.json` 的 `qqMusicApiPort`(默认 **3200**)。程序会验证已在该端口监听的 QQ 音乐 API,再复用它。如果端口被 WebUI、端口转发或其他服务占用,请将 `qqMusicApiPort` 改为另一个空闲端口并重启。
|
||||
|
||||
**Q:日志里 `baseURL` 是 3200,但 QQ API 实际监听在 3300?(二维码不弹)**
|
||||
A:这是**旧版本**(或过期的 `latest` Docker 镜像)才有的问题:早期实现用的上游包默认端口是 3300,而客户端 `baseURL` 已经是 3200,两边对不上,取二维码时就 `ECONNREFUSED 127.0.0.1:3200`。当前版本已把内嵌 QQ 音乐 API **强制绑定到 `qqMusicApiPort`(默认 3200)**,并在启动前把上游包读取的 `PORT` 环境变量对齐到该端口,二者不可能再错位。修复方法:**拉取最新镜像并重启**(`docker compose pull && docker compose up -d`),或用 `npm ci && npm run build` 更新到最新代码。启动后可在日志里确认那行 `QQ Music API started`,其 `port` 字段就是实际监听端口。
|
||||
@@ -846,7 +959,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-无鉴权版本升级重要)。
|
||||
@@ -884,7 +997,105 @@ 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.13.0:本地视频上传播放 / 头像上传时机
|
||||
### 最新版本 — v1.16.1 播放、续播与队列修复
|
||||
|
||||
- B 站长视频中断后优先尝试其他 CDN。网易云、QQ 音乐和酷狗的完整曲目提前断流时,机器人会在有限次数内刷新地址,从已播位置续播。停止、切歌和断开连接会取消旧曲目的恢复。
|
||||
- 网页加载空歌单、预检失败或选择无效队列位置时会保留原播放。进度条会跟随实际音频进度,切歌失败会显示原因。更新机器人头像时结束的短曲也能正常推进队列。
|
||||
- QQ 音乐使用内嵌 API 支持的歌曲 MID 和音质参数。批量预检会区分上游错误与确实不可播的曲目,启动时也会识别 QQ 端口被其他服务占用。酷狗要求验证时会显示平台错误码。
|
||||
- 机器人只会因听众进入自己所在的频道而恢复自动暂停的播放。混合队列遇到音源限制时,会继续尝试其他音源。
|
||||
|
||||
### 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` 等回退节点的请求头和断点定位,避免续播时从头下载、解码长视频。
|
||||
- B站提前结束后,获取新播放地址失败会在 1 秒、2 秒后重试,单次恢复最多查询 3 次;期间的切歌、停止、暂停和断开连接均会保留用户意图。诊断日志不记录原始地址或凭据。
|
||||
- 语音发送异常不再被静默忽略:短暂失败后可继续发送;连续失败 2 秒后暂停,保留曲目与进度。处理网络或连接问题后可手动继续播放,持续故障日志有输出上限。
|
||||
- 开启“频道无人时自动暂停”后,过期的频道人数查询和旧连接的空闲定时器不会再错误暂停或断开当前播放。
|
||||
- 修复重连期间旧频道查询和 DNS 结果覆盖新连接的竞态,避免已经连接的机器人被旧请求移回频道或记录错误的服务器地址。
|
||||
|
||||
无配置或数据库迁移。此版本修复了已复现的故障路径;[#161](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/issues/161) 中新分支“67 分钟视频播到 37 分钟停止”的现场原因仍缺少停止时日志,尚未确认。
|
||||
|
||||
### v1.15.1:长视频播放阻塞与音乐 API 日志隐私修复
|
||||
|
||||
- 持续读取 FFmpeg 的 stderr,并关闭周期性进度输出,避免错误输出管道写满后卡住音频解码。直接 URL 播放和 Windows 临时文件播放均已处理。
|
||||
- FFmpeg 异常退出和播放停滞日志增加限长、脱敏的诊断摘要;移除 URL 查询参数、用户凭据和认证头,PowerShell 下载失败日志采用同样的处理。
|
||||
- 内置网易云 / QQ 音乐 API 在独立子进程运行,隔离依赖直接输出的原始请求和响应日志,避免其中的 Cookie 等凭据进入机器人控制台日志。仍保留服务启动和退出的安全诊断;独立部署或已占用端口的外部 API 需自行管理日志。
|
||||
|
||||
无配置或数据库迁移。此补丁修复了已复现的管道阻塞;[#161](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/issues/161) 中“67 分钟视频播到 37 分钟停止”的现场原因仍缺少停止时日志,尚未确认。
|
||||
|
||||
### v1.15.0:歌手页面 / REST API / TS6 Profile 与 B站续播修复
|
||||
|
||||
**歌手搜索与页面([PR #175](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/pull/175),感谢 [@zzstar101](https://github.com/zzstar101))**
|
||||
|
||||
- 网易云 / QQ 音乐支持搜索歌手、查看歌手介绍、热门歌曲和专辑,并播放或随机播放歌手曲目(最多 500 首)。搜索历史按音源保存在当前浏览器。
|
||||
- 歌手播放与单曲播放共用播放锁,避免同时点播时实际歌曲与队列不一致。QQ 曲目目录在上游查询失败时不缓存降级结果,不再因 50 张专辑的限制提前截断歌曲。
|
||||
- 歌手页面的迟到请求不会覆盖新页面;访客的随机播放按钮同时遵守歌手播放与模式切换权限。
|
||||
|
||||
**REST API([PR #173](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/pull/173),感谢 [@senlinjun](https://github.com/senlinjun))**
|
||||
|
||||
- 在设置页创建、查看和撤销 API Key;脚本可用 Bearer 或 X-API-Key 调用已有 REST 端点,权限和可控机器人范围继承所属用户。完整说明见 [REST API 文档](docs/API.md)。
|
||||
- 修复管理员撤销他人 Key 时的审计对象。修改或重置密码会撤销该用户的全部 API Key,外部集成需要重新生成凭据。
|
||||
|
||||
**TS6 Profile([PR #174](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/pull/174),感谢 [@razaxq](https://github.com/razaxq))**
|
||||
|
||||
- 昵称和 Away 状态通过真实音乐客户端更新,描述通过明确的客户端 ID 更新,避免修改 HTTP ServerQuery 客户端。
|
||||
- 频道描述写入和移动后的清理使用相同权限路径;重连后丢弃旧会话请求,权限不足时可靠降级。
|
||||
|
||||
**B站长视频续播([#161](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/issues/161),[PR #170](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/pull/170))**
|
||||
|
||||
- 优先使用稳定 CDN 镜像;流提前结束时重新解析地址并从当前进度续播,连续无进展重试有次数限制。
|
||||
- 播放结束和恢复请求按播放会话校验,旧请求不会跳过新曲,也不会覆盖同一曲目的新一轮播放。
|
||||
- 恢复地址查询期间暂停会保留暂停状态;恢复播放不会重复发起查询,查询失败后仍可按重试上限继续恢复。
|
||||
|
||||
数据库自动新增 API Key 表,保留已有用户和设置。自动化测试只收集源码,排除旧的编译测试副本。
|
||||
|
||||
### v1.14.0:歌单链接直接播放 / 每人绑定自己的网易云私人FM / B站分P
|
||||
|
||||
处理了 5 个社区反馈的 issue。**没有配置变化,升级无需任何操作**;数据库会自动新增一张表(存放用户自己绑定的网易云账号),原有数据不受影响。
|
||||
|
||||
**`!playlist` 直接粘贴歌单链接([#160](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/issues/160),[PR #169](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/pull/169),感谢 [@JiaxiangACE](https://github.com/JiaxiangACE))**
|
||||
|
||||
- `!playlist <歌单链接>` 支持网易云 / QQ 音乐 / YouTube 歌单链接,**平台由链接自动识别**:以前 QQ 链接不加 `-q` 会被拿去网易云查,YouTube 的 `?list=` 链接会被当成歌单名去搜索,现在都能直接用。
|
||||
- App 里「分享」复制出来的整段文案、以及短链(`163cn.tv`、`c6.y.qq.com`)也能直接粘贴。短链只会访问这两个域名,不会去请求任意用户给的地址。
|
||||
- 歌单名和纯数字 ID 的用法不变。
|
||||
|
||||
**每个网页端用户绑定自己的网易云账号听私人FM([#164](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/issues/164),[PR #171](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/pull/171),感谢 [@xxmod](https://github.com/xxmod))**
|
||||
|
||||
- 多人共用一个机器人时,私人FM以前永远按机器人登录的那一个账号推荐。现在每个成员可以在 **设置 → 账户** 扫码绑定自己的网易云账号,之后他在网页端开启的网易云私人FM按他自己的口味推荐;未绑定的人照旧使用共享账号。
|
||||
- 绑定的登录只保存在服务器上,从不回传给浏览器,也**不会**顶掉机器人的共享登录;删除用户时一并清除。游客不能绑定。
|
||||
- TS 聊天里的 `!fm` 仍使用共享账号(聊天里的 TS 用户和网页账号没有对应关系)。
|
||||
|
||||
**机器人被移动后,原频道描述不再残留([#159](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/issues/159),[PR #168](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/pull/168),感谢 [@Almighty-ap](https://github.com/Almighty-ap))**
|
||||
|
||||
- 开启「更新频道描述」时,把机器人拖到别的频道后,原频道会一直停留在当时的歌曲信息。现在机器人被移动时会清空原频道描述,并把正在播放的信息写到新频道。
|
||||
|
||||
**Linux 安装脚本([#165](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/issues/165),[PR #172](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/pull/172),感谢 [@XuVIIJay](https://github.com/XuVIIJay))**
|
||||
|
||||
- `scripts/install.sh` 以前仍在安装已不再支持的 Node 20,现在按发行版(apt / yum / pacman)安装 Node 22 LTS,并复用 `setup.sh` 完成依赖安装、国内镜像切换、原生模块校验和构建。重复运行(升级)时会先停服务、替换构建产物,**保留 `data/`**。
|
||||
- README 的「Linux 安装脚本」一节说明了 `install.sh`(一键安装 + systemd 开机自启)和 `setup.sh`(只安装构建、不装 Node、不配服务)的区别和适用场景。
|
||||
|
||||
**B站分P视频([PR #166](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/pull/166),感谢 [@xxmod](https://github.com/xxmod))**
|
||||
|
||||
- 分P视频以前只能播放第一P,且时长显示为整个视频的总时长。现在网页端播放多P视频时会弹出选择框选P;TS 里 `!play` 播放第一P。
|
||||
|
||||
### v1.13.0:本地视频上传播放 / 头像上传时机
|
||||
|
||||
处理了 2 个社区反馈的 issue。**没有配置变化,升级无需任何操作**;原有的本地音频上传行为完全不变。
|
||||
|
||||
@@ -1103,7 +1314,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 许可) |
|
||||
|
||||
|
||||
+376
@@ -0,0 +1,376 @@
|
||||
# REST API 参考
|
||||
|
||||
本文档列出机器人对外提供的全部 REST API 端点、参数与返回。所有端点均支持两种认证方式(见下),除单独标注「仅浏览器 session」的端点外。
|
||||
|
||||
## 通用约定
|
||||
|
||||
### 认证
|
||||
|
||||
```
|
||||
Authorization: Bearer tsmb_xxxxxxxxxxxx
|
||||
# 或
|
||||
X-API-Key: tsmb_xxxxxxxxxxxx
|
||||
```
|
||||
|
||||
Key 在 WebUI 设置页创建,权限与所属账户一致。除标注「仅浏览器 session」的端点外,API Key 与浏览器 session(cookie)使用相同的账户权限。
|
||||
|
||||
管理员 API Key 保留完整的 REST 管理权限,包括 `/api/users` 的创建用户、重置密码与权限变更;因此也可以创建新的可登录账户。`/api/keys` 的 session 限制只约束直接密钥管理,不能作为管理员 Key 的权限隔离措施。
|
||||
|
||||
### 密钥吊销与密码变更
|
||||
|
||||
API Key 没有自动到期时间,可在设置页随时吊销。删除账户会同时删除其全部 Key。成功修改自己的密码或由管理员重置密码,都会吊销该账户的全部 Key;依赖这些 Key 的外部集成需要重新生成并更新凭据。失败的密码变更不会吊销 Key。
|
||||
|
||||
修改自己的密码会保留当前浏览器 session,使其余 session 失效。管理员重置其他账户的密码会使目标账户的全部 session 失效;重置自己的密码时同样保留当前浏览器 session。
|
||||
|
||||
### 错误格式
|
||||
|
||||
所有错误返回统一为 JSON `{ "error": "..." }`:
|
||||
|
||||
| 状态码 | 含义 |
|
||||
|--------|------|
|
||||
| 400 | 参数缺失或格式错误 |
|
||||
| 401 | 未认证 / API Key 无效(`invalid api key`) |
|
||||
| 403 | 无权限(能力不足、机器人未授权、API Key 试图管理 Key 等) |
|
||||
| 404 | 资源不存在 |
|
||||
| 409 | 冲突(如收藏已存在、Key 数量达上限) |
|
||||
| 500 | 服务器内部错误 |
|
||||
|
||||
### 权限模型
|
||||
|
||||
| 标注 | 含义 |
|
||||
|------|------|
|
||||
| 公开 | 无需认证 |
|
||||
| 已认证 | 任意登录用户 / 有效 API Key |
|
||||
| 非游客 | API Key 用户恒满足(guest session 除外) |
|
||||
| `player.control` / `player.queue` / `bot.manage` / `platform.auth` / `quality` | 需要账户持有对应能力;管理员恒通过 |
|
||||
| 机器人访问 | 成员只能操作被授予的机器人(账户权限中的 bot 范围),管理员不限 |
|
||||
| 管理员 | 仅 `role=admin` |
|
||||
|
||||
### 平台(platform)取值
|
||||
|
||||
`netease` / `qq` / `bilibili` / `youtube` / `kugou` / `jellyfin` / `local` / `spotify`
|
||||
|
||||
省略 `platform` 时使用设置页配置的默认音源;已禁用的音源返回 `400 音源未启用`。
|
||||
|
||||
### 点歌归属
|
||||
|
||||
`/play`、`/add`、`/play-*`、`/add-*` 等入队端点会把 `requestedBy` 记为 Key 所属账户的用户名,队列与播放历史中可见。
|
||||
|
||||
---
|
||||
|
||||
## 数据模型
|
||||
|
||||
```ts
|
||||
// 歌曲(搜索结果 / 队列元素)
|
||||
interface Song {
|
||||
id: string; // 平台内歌曲 id
|
||||
name: string;
|
||||
artist: string;
|
||||
album: string;
|
||||
duration: number; // 秒
|
||||
coverUrl: string;
|
||||
platform: Platform;
|
||||
vip?: boolean; // VIP/版权受限(仅试听)
|
||||
}
|
||||
|
||||
// 队列中的歌曲(Song + 归属;url 仅播放时内部解析,不出现在响应里)
|
||||
interface QueuedSong extends Omit<Song, "vip"> {
|
||||
requestedBy?: string;
|
||||
}
|
||||
|
||||
interface Album { id: string; name: string; artist: string; coverUrl: string; songCount: number; platform: Platform }
|
||||
interface Playlist { id: string; name: string; coverUrl: string; songCount: number; platform: Platform }
|
||||
|
||||
// 机器人实时状态
|
||||
interface BotStatus {
|
||||
id: string;
|
||||
name: string;
|
||||
connected: boolean;
|
||||
playing: boolean;
|
||||
paused: boolean;
|
||||
currentSong: QueuedSong | null;
|
||||
queueSize: number;
|
||||
volume: number; // 0-100
|
||||
playMode: "seq" | "loop" | "random" | "rloop";
|
||||
elapsed: number; // 当前曲目已播秒数
|
||||
effectiveDuration?: number; // 当前曲实际播放时长(试听片段=试听秒数)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 公开端点(无需认证)
|
||||
|
||||
### GET /api/health
|
||||
|
||||
```json
|
||||
{ "status": "ok", "version": "0.1.0" }
|
||||
```
|
||||
|
||||
### GET /api/config/public-url
|
||||
|
||||
```json
|
||||
{ "publicUrl": "https://bot.example.com" } // 未配置时为 null
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 机器人管理 /api/bot
|
||||
|
||||
| 方法 | 路径 | 权限 | 说明 |
|
||||
|------|------|------|------|
|
||||
| GET | `/api/bot` | 已认证 | 机器人列表(成员只返回被授权的) |
|
||||
| GET | `/api/bot/settings` | 非游客 | 全局行为设置 |
|
||||
| POST | `/api/bot/settings` | `bot.manage` | 保存全局设置(部分合并) |
|
||||
| POST | `/api/bot` | `bot.manage` | 创建机器人 |
|
||||
| GET | `/api/bot/:id` | 机器人访问 | 单个机器人状态 |
|
||||
| PUT | `/api/bot/:id` | `bot.manage` + 机器人访问 | 更新连接配置 |
|
||||
| DELETE | `/api/bot/:id` | `bot.manage` + 机器人访问 | 删除机器人 |
|
||||
| POST | `/api/bot/:id/start` | `bot.manage` + 机器人访问 | 连接服务器 |
|
||||
| POST | `/api/bot/:id/stop` | `bot.manage` + 机器人访问 | 断开连接 |
|
||||
| GET | `/api/bot/:id/config` | `bot.manage` + 机器人访问 | 保存的连接配置(不含 identity/TS6 key) |
|
||||
| GET / PUT / DELETE | `/api/bot/:id/avatar` | `bot.manage` + 机器人访问 | 自定义头像 |
|
||||
|
||||
### GET /api/bot
|
||||
|
||||
```json
|
||||
{ "bots": [ { "id": "…", "name": "客厅bot", "connected": true, "playing": true, "paused": false,
|
||||
"currentSong": { "…": "QueuedSong" }, "queueSize": 3, "volume": 75,
|
||||
"playMode": "seq", "elapsed": 42.5, "effectiveDuration": 269 } ] }
|
||||
```
|
||||
|
||||
### POST /api/bot
|
||||
|
||||
```json
|
||||
// 请求体(name、serverAddress、nickname 必填;serverPort 默认 9987)
|
||||
{ "name": "客厅bot", "serverAddress": "ts.example.com", "serverPort": 9987,
|
||||
"nickname": "♪ 音乐机器人", "defaultChannel": "音乐频道", "channelId": "12",
|
||||
"channelPassword": "", "serverPassword": "", "autoStart": true }
|
||||
// 201 返回 BotStatus
|
||||
```
|
||||
|
||||
### PUT /api/bot/:id
|
||||
|
||||
请求体字段同上(全部可选),返回 `{ "success": true }`。连接相关修改需重启机器人(`stop` 后 `start`)生效。
|
||||
|
||||
### POST /api/bot/settings(部分合并,未传的字段不变)
|
||||
|
||||
```json
|
||||
{
|
||||
"idleTimeoutMinutes": 30, // 空闲自动断开,0=不启用
|
||||
"autoPauseOnEmpty": true, // 频道无人自动暂停
|
||||
"localAudioEnabled": true, // 本地音频
|
||||
"voiceDucking": { "enabled": true, "volumePercent": 20 },
|
||||
"savedQueuesEnabled": true,
|
||||
"playKeepsQueue": false, // !play 是否保留队列
|
||||
"adminGroups": [6],
|
||||
"enabledProviders": ["netease","qq","bilibili","youtube","kugou"],
|
||||
"defaultPlatform": "netease", // null/"" 清除
|
||||
"guestMode": { "enabled": false, "bots": "all", "permissions": { "…": true } },
|
||||
"spotify": { "enabled": false, "clientId": "…", "clientSecret": "…", "backend": "auto", "bitrate": 160, "deviceName": "…" },
|
||||
"jellyfin": { "serverUrl": "…", "authMode": "userpass", "username": "…", "password": "…" }
|
||||
}
|
||||
// 返回:与 GET /settings 相同结构(spotify.clientSecret / jellyfin.password 永不回传,仅 hasClientSecret / hasPassword 布尔)
|
||||
```
|
||||
|
||||
### PUT /api/bot/:id/avatar
|
||||
|
||||
请求体 `{ "dataUrl": "data:image/png;base64,…" }`(png/jpeg/webp,≤200KB),返回 `{ "path": "avatars/xx.png" }`。
|
||||
|
||||
---
|
||||
|
||||
## 播放控制 /api/player/:botId
|
||||
|
||||
以下所有端点都要求机器人访问权限;标注能力的管理类操作还需对应能力。`{ "message": "…" }` 为命令执行回执文本(与聊天命令回执一致),失败时 message 中带原因或返回 4xx/5xx。
|
||||
|
||||
### 播放入口
|
||||
|
||||
| 方法 | 路径 | 能力 | 请求体 | 返回 |
|
||||
|------|------|------|--------|------|
|
||||
| POST | `/play` | `player.control` | `{ query, platform? }`(搜索文本) | `{ message }` |
|
||||
| POST | `/add` | `player.queue` | `{ query, platform? }` | `{ message }` |
|
||||
| POST | `/play-song` | `player.control` | `{ song }`(Song 对象,清空队列播放) | `{ ok, message }` |
|
||||
| POST | `/play-now-song` | `player.control` | `{ song }`(插入当前曲后立即播放,保留队列) | `{ ok, message }` |
|
||||
| POST | `/play-next-song` | `player.control` | `{ song }`(插播下一首;空闲时直接播放) | `{ ok, message }` |
|
||||
| POST | `/add-song` | `player.queue` | `{ song }`(入队;空闲时立即播放) | `{ message }` |
|
||||
| POST | `/add-by-id` | `player.queue` | `{ songId, platform? }` | `{ message }` |
|
||||
| POST | `/play-playlist` | `player.control` | `{ playlistId, platform? }`(清队列载入歌单) | `{ ok, message }` |
|
||||
| POST | `/play-album` | `player.control` | `{ albumId, platform? }`(清队列载入专辑) | `{ ok, message }` |
|
||||
| POST | `/playlist` | `player.queue` | `{ playlistId, platform? }`(追加整个歌单) | `{ message }` |
|
||||
| POST | `/fm` | `player.control` | `{ platform? }`(私人 FM 模式) | `{ ok, message }` |
|
||||
|
||||
`/play` 与 `/add` 接受搜索文本,内部按 `platform` 调对应音源搜索并播放/入队第一个结果;`/play-song` 系列接受 `/api/music` 返回的完整 Song 对象。B站多P视频的 Song `id` 形如 `BVxxxx?p=2`(见 `/api/music/bilibili/parts`),传对应分P的 id 即播放该分P。
|
||||
|
||||
`/fm` 的平台为网易时,若调用者账户已绑定个人网易账号(见 `/api/me/music`),FM 曲目按**个人账号**的口味推荐;未绑定则使用机器人共享登录。
|
||||
|
||||
### 播放器控制
|
||||
|
||||
| 方法 | 路径 | 能力 | 请求体 | 返回 |
|
||||
|------|------|------|--------|------|
|
||||
| POST | `/pause` | `player.control` | — | `{ message }` |
|
||||
| POST | `/resume` | `player.control` | — | `{ message }` |
|
||||
| POST | `/next` | `player.control` | — | `{ message }` |
|
||||
| POST | `/prev` | `player.control` | — | `{ message }` |
|
||||
| POST | `/stop` | `player.control` | — | `{ message }` |
|
||||
| POST | `/clear` | `player.queue` | — | `{ message }` |
|
||||
| POST | `/volume` | `player.control` | `{ volume: 0-100 }` | `{ message }` |
|
||||
| POST | `/mode` | `player.control` | `{ mode: "seq"|"loop"|"random"|"rloop" }` | `{ message }` |
|
||||
| POST | `/seek` | `player.control` | `{ position: 秒 }` | `{ message, seekOffset }` |
|
||||
| POST | `/play-at` | `player.control` | `{ index: 队列下标 }` | `{ message }`,越界 400 |
|
||||
|
||||
### 状态与队列
|
||||
|
||||
| 方法 | 路径 | 返回 |
|
||||
|------|------|------|
|
||||
| GET | `/queue` | `{ queue: QueuedSong[], status: BotStatus }` |
|
||||
| GET | `/elapsed` | `{ elapsed: 42.5 }` |
|
||||
| DELETE | `/queue/:index` | `{ message }`(移除指定下标,能力 `player.queue`) |
|
||||
| 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`) |
|
||||
|
||||
ProfileConfig:`{ avatarEnabled, descriptionEnabled, nicknameEnabled, awayStatusEnabled, channelDescEnabled, nowPlayingMsgEnabled }`(机器人头像/昵称/频道描述等自动更新开关)。
|
||||
|
||||
---
|
||||
|
||||
## 音乐数据 /api/music
|
||||
|
||||
除特别标注外均为「已认证」;`platform` 为可选 query 参数。
|
||||
|
||||
| 方法 | 路径 | 参数 | 返回 |
|
||||
|------|------|------|------|
|
||||
| GET | `/search` | `q`(必填)、`platform`、`limit`(默认 20)、`offset`(默认 0) | `{ songs, albums, playlists }` |
|
||||
| GET | `/search/all` | `q`(必填)、`limit` | 各音源合并的 `{ songs, albums, playlists }`(不含 spotify) |
|
||||
| GET | `/song/:id` | `platform` | Song 对象,无则 404 |
|
||||
| GET | `/album/:id` | `platform` | `{ songs: Song[] }` |
|
||||
| GET | `/playlist/:id` | `platform` | `{ songs: Song[] }` |
|
||||
| GET | `/playlist/:id/detail` | `platform` | `{ playlist: { id, name, description, coverUrl, songCount } }`(音源不支持时 501) |
|
||||
| GET | `/lyrics/:id` | `platform` | `{ lyrics }` |
|
||||
| GET | `/recommend/playlists` | `platform` | `{ playlists }` |
|
||||
| GET | `/recommend/songs` | `platform` | `{ songs }`(每日推荐;非游客) |
|
||||
| GET | `/personal/fm` | `platform` | `{ songs }`(私人 FM;非游客) |
|
||||
| GET | `/user/playlists` | `platform` | `{ playlists }`(当前登录音源账号的歌单;非游客) |
|
||||
| GET | `/bilibili/popular` | `limit`(默认 20) | `{ songs }` |
|
||||
| GET | `/bilibili/parts` | `bvid`(BV 号或视频链接) | `{ bvid, title, coverUrl, artist, parts }`(无此视频 404) |
|
||||
| GET | `/providers` | — | `{ enabled: Platform[], default: Platform }` |
|
||||
| GET | `/quality` | — | `{ netease, qq, bilibili, local, kugou, spotify, jellyfin }` |
|
||||
| POST | `/quality` | `{ quality, platform? }`(能力 `quality`;省略 platform 时对所有音源生效) | `{ success, quality }` |
|
||||
|
||||
### Jellyfin 音乐库
|
||||
|
||||
| 方法 | 路径 | 参数 | 返回 |
|
||||
|------|------|------|------|
|
||||
| GET | `/jellyfin/latest-albums` | `limit`(默认 12) | `{ albums }` |
|
||||
| GET | `/jellyfin/most-played` | `limit`(默认 12) | `{ songs }` |
|
||||
| GET | `/jellyfin/favorites` | `limit`(默认 100) | `{ songs }`(非游客) |
|
||||
| GET | `/jellyfin/genres` | `limit`(默认 30) | `{ genres: [{ id, name }] }` |
|
||||
| GET | `/jellyfin/genre/:id/songs` | `limit`(默认 100) | `{ songs }` |
|
||||
|
||||
### 本地音频上传
|
||||
|
||||
`POST /api/music/local/upload` — 能力 `player.queue`。请求体为**原始音频文件**(audio/* 或 video/*,≤500MB,非 multipart;文件名放 `x-filename` 请求头)。返回 `{ song }`;本地音频关闭时 403。
|
||||
|
||||
```bash
|
||||
curl -X POST -H "X-API-Key: $KEY" -H "x-filename: theme.mp3" \
|
||||
-H "Content-Type: application/octet-stream" \
|
||||
--data-binary @theme.mp3 http://127.0.0.1:3000/api/music/local/upload
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 收藏 /api/favorites(非游客,仅本人数据)
|
||||
|
||||
| 方法 | 路径 | 参数 | 返回 |
|
||||
|------|------|------|------|
|
||||
| GET | `/` | — | `{ favorites: [{ id, platform, playlistId, name, coverUrl, songCount, createdAt }] }` |
|
||||
| POST | `/` | `{ platform, playlistId, name, coverUrl?, songCount? }` | `{ success: true }`;已收藏 409 |
|
||||
| GET | `/check` | `platform`、`playlistId` | `{ favorited: bool }` |
|
||||
| DELETE | `/:id` | 收藏记录 id | `{ success: true }` |
|
||||
|
||||
---
|
||||
|
||||
## 保存的队列 /api/saved-queues(非游客;需在设置页开启「保存队列」)
|
||||
|
||||
所有权:私有为本人,`shared: true` 保存到共享桶;列表返回本人的+共享的;他人私有队列 404。
|
||||
|
||||
| 方法 | 路径 | 参数 | 返回 |
|
||||
|------|------|------|------|
|
||||
| GET | `/` | — | `{ queues: [{ id, ownerId, name, songCount, createdAt, updatedAt }] }` |
|
||||
| POST | `/` | `{ botId, name, shared? }`(快照该 bot 当前队列,同名覆盖) | `{ queue }`;队列空 400 |
|
||||
| POST | `/:id/load` | `{ botId, mode?: "replace"(默认)|"append" }` | `{ ok, loaded, mode }` |
|
||||
| DELETE | `/:id` | — | `{ ok: true }` |
|
||||
|
||||
---
|
||||
|
||||
## 平台账号 /api/auth
|
||||
|
||||
| 方法 | 路径 | 权限 | 参数 | 返回 |
|
||||
|------|------|------|------|------|
|
||||
| GET | `/status` | 非游客 | `platform` | `{ platform, loggedIn, nickname?, avatarUrl? }` |
|
||||
| POST | `/qrcode` | `platform.auth` | `{ platform }`(netease/qq/bilibili/kugou) | `{ qrUrl, qrImg?(base64 data URL), key }` |
|
||||
| GET | `/qrcode/status` | 非游客 | `key`、`platform` | `{ status: "waiting"|"scanned"|"confirmed"|"expired" }`;confirmed 自动持久化登录态 |
|
||||
| POST | `/jellyfin/test` | `platform.auth` | `{ serverUrl?, authMode?, username?, password?, apiKey?, userId? }`(空字段回退已存配置) | `{ ok, serverName?, version?, error? }` |
|
||||
| POST | `/sms/send` | `platform.auth` | `{ phone }`(网易手机号登录) | `{ success }` |
|
||||
| POST | `/sms/verify` | `platform.auth` | `{ phone, code }` | `{ success }` |
|
||||
| POST | `/cookie` | `platform.auth` | `{ platform, cookie }`(不支持 youtube/jellyfin) | `{ success: true }` |
|
||||
|
||||
## Spotify /api/spotify(配置 Spotify OAuth 后挂载)
|
||||
|
||||
| 方法 | 路径 | 权限 | 返回 |
|
||||
|------|------|------|------|
|
||||
| GET | `/login` | `platform.auth` | `{ url }`(accounts.spotify.com 授权页,浏览器打开) |
|
||||
| GET | `/callback` | — | OAuth 回调,重定向回 WebUI(浏览器流程,脚本无需调用) |
|
||||
| GET | `/status` | 非游客 | `{ authorized, backend, deviceName, binaryAvailable }` |
|
||||
|
||||
---
|
||||
|
||||
## 个人音乐账号 /api/me/music(非游客,仅本人数据)
|
||||
|
||||
绑定**自己的**网易账号,让 `POST /api/player/:botId/fm` 按个人口味推荐;cookie 只存服务端,任何接口都不会回传。与 `/api/auth` 的机器人共享登录互不影响。
|
||||
|
||||
| 方法 | 路径 | 参数 | 返回 |
|
||||
|------|------|------|------|
|
||||
| GET | `/netease/status` | — | `{ linked, loggedIn, nickname?, avatarUrl? }` |
|
||||
| POST | `/netease/qrcode` | — | `{ qrUrl, qrImg?(base64 data URL), key }`(个人绑定专用二维码) |
|
||||
| GET | `/netease/qrcode/status` | `key` | `{ status: "waiting"|"scanned"|"confirmed"|"expired" }`;confirmed 后自动绑定到当前账户 |
|
||||
| DELETE | `/netease` | — | `{ ok: true }`(解除绑定) |
|
||||
|
||||
---
|
||||
|
||||
## API 密钥管理 /api/keys(仅浏览器 session)
|
||||
|
||||
API Key **不能直接调用这些密钥管理端点**(403);游客 session 也被拒绝。浏览器登录后调用。管理员 Key 仍保留上文所述的用户管理权限。
|
||||
|
||||
| 方法 | 路径 | 参数 | 返回 |
|
||||
|------|------|------|------|
|
||||
| GET | `/` | `?all=1`(管理员可看全部,含 username) | `{ keys: [{ id, userId, username?, name, keyPrefix, createdAt, lastUsedAt }] }` |
|
||||
| POST | `/` | `{ name: "1-64字符" }` | `201 { key: {...}, rawKey: "tsmb_…" }`(明文仅此一次);达上限 409 |
|
||||
| DELETE | `/:id` | — | `{ success: true }`(仅本人;管理员可删任意) |
|
||||
|
||||
---
|
||||
|
||||
## 用户管理 /api/users(管理员)
|
||||
|
||||
| 方法 | 路径 | 参数 | 返回 |
|
||||
|------|------|------|------|
|
||||
| GET | `/` | — | `{ users: [{ id, username, createdAt, role }] }` |
|
||||
| POST | `/` | `{ username, password(≥8位), role: "admin"|"member" }` | `201 { id, username, role }`;重名 409 |
|
||||
| DELETE | `/:id` | — | `204`(级联删除其 session 与 API Key) |
|
||||
| POST | `/:id/reset-password` | `{ newPassword }` | `204`(该用户的 API Key 全部失效,session 按上文密码变更规则处理) |
|
||||
| PATCH | `/:id/role` | `{ role: "admin"|"member" }` | `204`(不能降级最后一个管理员) |
|
||||
| GET | `/:id/permissions` | — | `{ capabilities: string[], bots: "all" | string[] }` |
|
||||
| PUT | `/:id/permissions` | `{ capabilities, bots: "all"|string[] }` | `{ success: true }` |
|
||||
|
||||
## 操作审计 /api/audit(管理员)
|
||||
|
||||
| 方法 | 路径 | 参数 | 返回 |
|
||||
|------|------|------|------|
|
||||
| GET | `/` | `limit`(1-500,默认 100)、`offset`(默认 0) | `{ entries: [{ id, timestamp, actorId, actorUsername, targetUserId, targetUsername, action }] }` |
|
||||
|
||||
action 取值:`admin.first_created`、`user.created`、`user.deleted`、`user.password_reset`、`user.password_changed`、`user.role_changed`、`user.permissions_changed`、`api_key.created`、`api_key.deleted`。
|
||||
|
||||
## 会话 /api/session(仅浏览器,API Key 不可用)
|
||||
|
||||
会话登录本身无法用 API Key 完成:`GET /needs-setup`、`POST /setup`、`POST /login`、`POST /guest`、`POST /logout`、`GET /me`、`POST /change-password` 均基于 cookie。`/login` 有每 IP 每分钟 5 次、`/setup` 3 次的限流。
|
||||
@@ -0,0 +1,102 @@
|
||||
# PR integration and v1.15.0 implementation plan
|
||||
|
||||
> For agentic workers: use the parallel implementation and independent review tools. Steps use checkbox syntax.
|
||||
|
||||
**Goal:** Fix the reviewed defects in PRs #170, #173, #174 and #175, merge the tested result into main, and publish the next release.
|
||||
|
||||
**Architecture:** Retain each original PR head in merge history. Fix independent modules in parallel with exclusive file ownership. Push the final integration only after source tests, builds and independent review pass.
|
||||
|
||||
**Tech Stack:** Node.js, TypeScript, Vitest, Express, Vue, TeamSpeak client SDK, GitHub Actions.
|
||||
|
||||
**Spec:** User requests in this chat: review every open PR, merge safe fixes/enhancements into main and test; then merge and publish a new version; then explicitly fix the reported defects.
|
||||
|
||||
## Global constraints
|
||||
|
||||
- Preserve inherited work; checkout is clean at 87fca6d8b7b770e1e01f8891059c99d53705cc08.
|
||||
- Do not introduce new dependencies or change music-provider authorization.
|
||||
- Preserve API key role/capability inheritance. Password rotation must revoke the user's keys.
|
||||
- Match repository release convention: application package version remains 0.1.0; release tags identify shipped versions.
|
||||
- Source tests exclude generated dist/** and web/dist/**.
|
||||
- Do not force-push or rewrite original contributor history.
|
||||
|
||||
## Review focus
|
||||
|
||||
- A pending new playback request must survive an older EOF continuation.
|
||||
- Artist playback and single-song playback must serialize their queue mutations.
|
||||
- Transient QQ singer/album failures must not poison successful catalog caching.
|
||||
- Channel movement and reconnect must use the correct session and clear through the same permission path.
|
||||
- Credential revocation must audit the actual key owner and ordinary password changes must revoke keys.
|
||||
|
||||
### Task 1: Integrate original PR history
|
||||
|
||||
Files: src/bot/instance.test.ts (resolve #170 overlap by preserving both test suites).
|
||||
|
||||
- [x] Verify open PR heads remain the audited SHAs.
|
||||
- [x] Create a release integration branch from origin/main.
|
||||
- [x] Merge #173, #174, #175 and #170 with merge commits; resolve the instance test conflict by retaining both independent additions.
|
||||
|
||||
### Task 2: Correct artist playback and QQ catalogs
|
||||
|
||||
Owner files: src/music/qq.ts, src/music/qq.test.ts, src/web/api/player.ts, src/web/api/play-artist.test.ts.
|
||||
|
||||
- [x] Port the four review probes from ../.pr-review-20261003/175/review/review-artist-regressions.test.ts into repository tests.
|
||||
- [x] Run npm test -- src/music/qq.test.ts src/web/api/play-artist.test.ts and observe the known failures.
|
||||
- [x] Use bot.runExclusive for the stop/queue mutation/play sequence. Preserve permission middleware.
|
||||
- [x] Return a failure sentinel for failed singer lookup or malformed/nonzero album-search results; do not cache degradation.
|
||||
- [x] Scan albums until the 500-song ceiling or complete catalog; preserve hasMore/total correctness, avoid the silent 50-album limit.
|
||||
- [x] Re-run focused tests and report changed files and result.
|
||||
|
||||
### Task 3: Correct TS6 profile lifecycle
|
||||
|
||||
Owner files: src/bot/profile.ts, src/bot/profile.test.ts, src/ts-protocol/http-query.ts, optionally src/ts-protocol/client.ts and a related focused protocol test if checked self updates need it.
|
||||
|
||||
- [x] Port the three reviewer probes from ../.pr-review-20261003/174/src/bot/review-174.test.ts into profile tests.
|
||||
- [x] Confirm they fail before production changes.
|
||||
- [x] Clear old channel descriptions through checked HTTP channelEdit for TS6 and preserve TS3's working behavior.
|
||||
- [x] Fence client-list resolution and post-write remembered-channel state by generation/connection identity.
|
||||
- [x] Use a checked full-client self clientupdate that reports permission failures; never update HTTP ServerQuery self.
|
||||
- [x] Update old channel-description mocks to reflect checked TS3 writes without weakening assertions.
|
||||
- [x] Run profile/protocol tests and typecheck; report changes.
|
||||
|
||||
### Task 4: Correct API-key lifecycle and documentation
|
||||
|
||||
Owner files: src/data/api-keys.ts, src/data/api-keys.test.ts, src/web/api/api-keys.ts, src/web/api/api-keys.test.ts, src/web/api/session.ts, src/web/api/session.test.ts, src/web/server.ts, docs/API.md.
|
||||
|
||||
- [x] Test administrator revocation auditing the member owner and ordinary password changes invalidating old keys.
|
||||
- [x] Run the tests and observe the failures.
|
||||
- [x] Snapshot the key owner before deletion and use that owner in the audit target fields.
|
||||
- [x] Thread the API key store into the browser session router and revoke all keys after a successful self-service password change; preserve the active browser session convention.
|
||||
- [x] Keep documented administrator REST authority. Qualify the no-self-replication claim to direct /api/keys management; do not remove administrator /api/users functionality silently.
|
||||
- [x] Add Content-Type: application/octet-stream to the curl upload example.
|
||||
- [x] Run the focused auth/session/key suites; report changes.
|
||||
|
||||
### Task 5: Correct EOF/recovery ordering
|
||||
|
||||
Owner files: src/bot/instance.ts, src/bot/instance.test.ts. Do not change the artist route owned by Task 2.
|
||||
|
||||
- [x] Turn the independent actual-handler probe into repository tests using the existing setupPlayerEvents fixture; avoid runtime source transpilation.
|
||||
- [x] Confirm normal NetEase/Bilibili EOF can currently advance a pending replacement.
|
||||
- [x] Fence every delayed fallback by the ending song and playback session, including failed recovery; preserve immediate ordinary EOF ordering where practical.
|
||||
- [x] Verify stop, skip, restart of the same queue song, pause, null URL and failed lookup do not clobber a newer playback session.
|
||||
- [x] Run instance/player/Bilibili tests and report results.
|
||||
|
||||
### Task 6: Review, verify and release
|
||||
|
||||
Owner files: README.md changelog; release notes kept outside the repository for gh --notes-file.
|
||||
|
||||
- [x] Independently review every correction and the integrated changes; resolve substantive findings, including paused recovery, malformed QQ rows, and artist UI permissions/response ordering.
|
||||
- [x] Run npm test (generated outputs excluded by vitest.config.ts) and npm run build sequentially; repeat affected verification after final review fixes.
|
||||
- [x] Update the README changelog and prepare release notes with contributor credits, changes, migration notes and verified test results.
|
||||
- [ ] Confirm main has not moved, integrate the tested branch and push main without force.
|
||||
- [ ] Verify all four GitHub PRs show merged and point at the integrated history.
|
||||
- [ ] Create and push v1.15.0 (or the user's chosen version), create the GitHub release, and inspect the Docker publish workflow to completion.
|
||||
- [ ] Report the release URL, test totals and Docker publishing result. State that live TeamSpeak/music-provider integration was not exercised.
|
||||
|
||||
## Final local evidence (2026-10-03)
|
||||
|
||||
- All four audited PR heads were unchanged on GitHub before publishing.
|
||||
- Every correction passed independent review; no malicious behavior was found.
|
||||
- After the final artist UI corrections, `npm test` passed 79 source test files and all 1283 tests.
|
||||
- `npm run build` passed backend TypeScript, Vue type checking and production bundling.
|
||||
- `npm run check:native` passed. Compiled Vue component probes verified artist permission combinations and late-response ordering.
|
||||
- Live TeamSpeak servers and music-provider playback were not exercised. Publishing evidence is recorded in the GitHub release and its Docker workflow.
|
||||
Generated
+26
-15
@@ -1,16 +1,16 @@
|
||||
{
|
||||
"name": "tsmusicbot",
|
||||
"version": "0.1.0",
|
||||
"version": "1.16.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "tsmusicbot",
|
||||
"version": "0.1.0",
|
||||
"version": "1.16.1",
|
||||
"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.1",
|
||||
"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",
|
||||
|
||||
+67
-25
@@ -1,6 +1,16 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
#
|
||||
# TSMusicBot Installer (Linux, systemd)
|
||||
# - Installs system packages and Node.js 22 LTS
|
||||
# - Runs scripts/setup.sh to install dependencies, verify native binaries and build
|
||||
# - Copies the build to /opt/tsmusicbot and registers a systemd service (auto-start on boot)
|
||||
#
|
||||
# Only want to build and run it yourself (no Node install, no service)?
|
||||
# Use scripts/setup.sh instead — see README「Linux 安装脚本」.
|
||||
#
|
||||
|
||||
echo "╔══════════════════════════════════════╗"
|
||||
echo "║ TSMusicBot Installer ║"
|
||||
echo "╚══════════════════════════════════════╝"
|
||||
@@ -11,6 +21,9 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
|
||||
INSTALL_DIR="/opt/tsmusicbot"
|
||||
SERVICE_NAME="tsmusicbot"
|
||||
# Node LTS line to install when a supported Node is missing. Keep in sync with
|
||||
# package.json "engines" and the floor check in setup.sh (#152).
|
||||
NODE_LTS_MAJOR=22
|
||||
|
||||
# Verify we're in a valid project directory
|
||||
if [ ! -f "$PROJECT_DIR/package.json" ]; then
|
||||
@@ -28,42 +41,66 @@ else
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "[1/6] Installing system dependencies..."
|
||||
# Supported: 22.12+ or 24+ (odd majors are excluded by better-sqlite3 and vitest).
|
||||
node_supported() {
|
||||
command -v node &> /dev/null &&
|
||||
node -e 'const v=process.versions.node.split(".").map(Number); process.exit((v[0]===22&&v[1]>=12)||v[0]>=24?0:1)'
|
||||
}
|
||||
|
||||
echo "[1/5] Installing system dependencies..."
|
||||
case $OS in
|
||||
ubuntu|debian)
|
||||
sudo apt-get update -qq
|
||||
sudo apt-get install -y -qq curl build-essential python3
|
||||
sudo apt-get install -y -qq curl ca-certificates build-essential python3 ffmpeg
|
||||
;;
|
||||
centos|rhel|fedora)
|
||||
centos|rhel|fedora|rocky|almalinux)
|
||||
sudo yum install -y curl gcc gcc-c++ make python3
|
||||
;;
|
||||
arch|manjaro)
|
||||
sudo pacman -S --noconfirm curl base-devel python
|
||||
sudo pacman -S --noconfirm --needed curl base-devel python ffmpeg
|
||||
;;
|
||||
*)
|
||||
echo "Unsupported OS: $OS. Please install Node.js 20, build tools, and FFmpeg manually."
|
||||
echo "Unsupported OS: $OS. Please install Node.js ${NODE_LTS_MAJOR}.12+ and build tools manually."
|
||||
;;
|
||||
esac
|
||||
|
||||
echo "[2/6] Installing Node.js 20 LTS..."
|
||||
if ! command -v node &> /dev/null || [[ $(node -v | cut -d. -f1 | tr -d 'v') -lt 20 ]]; then
|
||||
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
|
||||
sudo apt-get install -y -qq nodejs 2>/dev/null || sudo yum install -y nodejs 2>/dev/null
|
||||
fi
|
||||
echo "Node.js $(node -v) installed"
|
||||
|
||||
echo "[3/6] Installing dependencies..."
|
||||
cd "$PROJECT_DIR"
|
||||
npm install
|
||||
if [ -d "$PROJECT_DIR/web/package.json" ] || [ -f "$PROJECT_DIR/web/package.json" ]; then
|
||||
(cd "$PROJECT_DIR/web" && npm install)
|
||||
echo "[2/5] Installing Node.js ${NODE_LTS_MAJOR} LTS..."
|
||||
if node_supported; then
|
||||
echo "Node.js $(node -v) already installed"
|
||||
else
|
||||
case $OS in
|
||||
ubuntu|debian)
|
||||
curl -fsSL "https://deb.nodesource.com/setup_${NODE_LTS_MAJOR}.x" | sudo -E bash -
|
||||
sudo apt-get install -y -qq nodejs
|
||||
;;
|
||||
centos|rhel|fedora|rocky|almalinux)
|
||||
curl -fsSL "https://rpm.nodesource.com/setup_${NODE_LTS_MAJOR}.x" | sudo bash -
|
||||
sudo yum install -y nodejs
|
||||
;;
|
||||
arch|manjaro)
|
||||
sudo pacman -S --noconfirm --needed nodejs npm
|
||||
;;
|
||||
esac
|
||||
if ! node_supported; then
|
||||
echo "Error: Node.js 22.12+ (or 24+) is required, found: $(node -v 2>/dev/null || echo none)."
|
||||
echo "Install it from https://nodejs.org/ (or https://nodejs.cn/) and re-run this script."
|
||||
exit 1
|
||||
fi
|
||||
echo "Node.js $(node -v) installed"
|
||||
fi
|
||||
|
||||
echo "[4/6] Building project..."
|
||||
npm run build
|
||||
echo "[3/5] Installing dependencies and building (scripts/setup.sh)..."
|
||||
bash "$SCRIPT_DIR/setup.sh"
|
||||
|
||||
echo "[5/6] Copying to $INSTALL_DIR..."
|
||||
echo "[4/5] Copying to $INSTALL_DIR..."
|
||||
# Stop a running copy before replacing its files (re-install / upgrade).
|
||||
if systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null; then
|
||||
sudo systemctl stop "$SERVICE_NAME"
|
||||
fi
|
||||
sudo mkdir -p "$INSTALL_DIR"
|
||||
# Replace build output wholesale so files removed upstream don't linger.
|
||||
# data/ (config, database, cookies) is never touched.
|
||||
sudo rm -rf "$INSTALL_DIR/dist" "$INSTALL_DIR/node_modules" "$INSTALL_DIR/web/dist"
|
||||
sudo cp -r "$PROJECT_DIR/dist" "$INSTALL_DIR/"
|
||||
sudo cp -r "$PROJECT_DIR/node_modules" "$INSTALL_DIR/"
|
||||
sudo cp "$PROJECT_DIR/package.json" "$INSTALL_DIR/"
|
||||
@@ -72,13 +109,18 @@ if [ -d "$PROJECT_DIR/web/dist" ]; then
|
||||
sudo mkdir -p "$INSTALL_DIR/web"
|
||||
sudo cp -r "$PROJECT_DIR/web/dist" "$INSTALL_DIR/web/"
|
||||
fi
|
||||
# yt-dlp is looked up in bin/ next to dist/ before falling back to PATH
|
||||
if [ -d "$PROJECT_DIR/bin" ]; then
|
||||
sudo cp -r "$PROJECT_DIR/bin" "$INSTALL_DIR/"
|
||||
fi
|
||||
# Copy scripts for future use
|
||||
sudo mkdir -p "$INSTALL_DIR/scripts"
|
||||
sudo cp -r "$PROJECT_DIR/scripts/"* "$INSTALL_DIR/scripts/" 2>/dev/null || true
|
||||
# Create data directory
|
||||
sudo mkdir -p "$INSTALL_DIR/data"
|
||||
|
||||
echo "[6/6] Creating systemd service..."
|
||||
echo "[5/5] Creating systemd service..."
|
||||
NODE_BIN="$(command -v node)"
|
||||
sudo tee /etc/systemd/system/${SERVICE_NAME}.service > /dev/null <<EOL
|
||||
[Unit]
|
||||
Description=TSMusicBot - TeamSpeak Music Bot
|
||||
@@ -88,7 +130,7 @@ After=network.target
|
||||
Type=simple
|
||||
User=root
|
||||
WorkingDirectory=${INSTALL_DIR}
|
||||
ExecStart=/usr/bin/node ${INSTALL_DIR}/dist/index.js
|
||||
ExecStart=${NODE_BIN} ${INSTALL_DIR}/dist/index.js
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
Environment=NODE_ENV=production
|
||||
@@ -99,15 +141,15 @@ EOL
|
||||
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable ${SERVICE_NAME}
|
||||
sudo systemctl start ${SERVICE_NAME}
|
||||
sudo systemctl restart ${SERVICE_NAME}
|
||||
|
||||
echo ""
|
||||
echo "╔══════════════════════════════════════╗"
|
||||
echo "║ TSMusicBot installed and running! ║"
|
||||
echo "║ ║"
|
||||
echo "║ WebUI: http://localhost:3000 ║"
|
||||
echo "║ WebUI: http://localhost:3000 ║"
|
||||
echo "║ ║"
|
||||
echo "║ Commands: ║"
|
||||
echo "║ Commands: ║"
|
||||
echo "║ systemctl status tsmusicbot ║"
|
||||
echo "║ systemctl restart tsmusicbot ║"
|
||||
echo "║ systemctl stop tsmusicbot ║"
|
||||
|
||||
+1
-1
@@ -21,7 +21,7 @@ echo ""
|
||||
|
||||
# ---- Check Node.js ----
|
||||
if ! command -v node &>/dev/null; then
|
||||
echo "[ERROR] Node.js not found. Please install Node.js 20+ from https://nodejs.org"
|
||||
echo "[ERROR] Node.js not found. Please install Node.js 22.12+ LTS from https://nodejs.org"
|
||||
echo " or https://nodejs.cn/ (China mirror)."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { PassThrough } from "node:stream";
|
||||
import { collectFfmpegDiagnostics } from "./ffmpeg-diagnostics.js";
|
||||
|
||||
async function finish(stream: PassThrough): Promise<void> {
|
||||
const ended = new Promise<void>((resolve) => stream.once("end", resolve));
|
||||
stream.end();
|
||||
await ended;
|
||||
}
|
||||
|
||||
describe("bounded FFmpeg diagnostics", () => {
|
||||
for (const [label, line, expected] of [
|
||||
["an apostrophe in the real FFmpeg URL error format", "Error opening input file http://127.0.0.1:9/audio?filename=artist's-song&api_key=quoted-secret.", "Error opening input file [URL omitted]"],
|
||||
["a space in URL userinfo", 'Error opening input file https://user:space secret@cdn.example/audio?token=space-secret.', "Error opening input file [URL omitted]"],
|
||||
["multiple URLs", 'Error opening inputs https://cdn.example/a?filename=artist\'s-song&key=first-secret and https://cdn.example/b?token=second-secret', "Error opening inputs [URL omitted]"],
|
||||
["quotes and spaces in a request target", "GET /audio?filename=artist's song&api_key=request-secret HTTP/1.1", "GET /audio?[query omitted]"],
|
||||
["an apostrophe in a Bearer value", "Token rejected Bearer prefix'quoted bearer-secret", "Token rejected Bearer [omitted]"],
|
||||
]) {
|
||||
it(`omits the entire sensitive suffix after ${label}`, async () => {
|
||||
const stream = new PassThrough();
|
||||
const diagnostics = collectFfmpegDiagnostics(stream);
|
||||
stream.write(line + "\n");
|
||||
await finish(stream);
|
||||
expect(diagnostics.getTail()).toBe(expected);
|
||||
});
|
||||
}
|
||||
|
||||
for (const splitDelimiter of [false, true]) {
|
||||
it(`omits folded authentication values with ${splitDelimiter ? "chunk-split" : "intact"} CRLF`, async () => {
|
||||
const stream = new PassThrough();
|
||||
const diagnostics = collectFfmpegDiagnostics(stream);
|
||||
stream.write(`Authorization: Basic header-secret\r${splitDelimiter ? "" : "\n"}`);
|
||||
if (splitDelimiter) stream.write("\n");
|
||||
stream.write(" continuation-secret\r\nHTTP error 401\r\n");
|
||||
await finish(stream);
|
||||
expect(diagnostics.getTail()).toContain("HTTP error 401");
|
||||
expect(diagnostics.getTail()).not.toContain("header-secret");
|
||||
expect(diagnostics.getTail()).not.toContain("continuation-secret");
|
||||
});
|
||||
}
|
||||
|
||||
it("redacts URLs and headers split across arbitrary byte and UTF-8 boundaries", async () => {
|
||||
const stream = new PassThrough();
|
||||
const diagnostics = collectFfmpegDiagnostics(stream);
|
||||
const payload = Buffer.from("解码失败 https://user:user-secret@cdn.example/audio?token=query-secret#fragment-secret\rCookie: cookie-secret\nAuthorization: Bearer bearer-secret\nGET /audio?token=request-secret HTTP/1.1\nfinal error");
|
||||
for (const byte of payload) stream.write(Buffer.from([byte]));
|
||||
await finish(stream);
|
||||
expect(diagnostics.getTail()).toContain("解码失败");
|
||||
expect(diagnostics.getTail()).toContain("final error");
|
||||
for (const secret of ["user-secret", "query-secret", "fragment-secret", "cookie-secret", "bearer-secret", "request-secret"]) {
|
||||
expect(diagnostics.getTail()).not.toContain(secret);
|
||||
}
|
||||
});
|
||||
|
||||
it("omits oversized raw lines without retaining an unsafe credential suffix", async () => {
|
||||
const stream = new PassThrough();
|
||||
const diagnostics = collectFfmpegDiagnostics(stream);
|
||||
stream.write("Cookie: " + "x".repeat(100000));
|
||||
stream.write("oversized-secret\r\n folded-oversized-secret\r\nHTTP error 403\n");
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(diagnostics.getTail()).toContain("HTTP error 403");
|
||||
expect(diagnostics.getTail()).not.toContain("oversized-secret");
|
||||
stream.write("decoder warning\n".repeat(10000));
|
||||
stream.write("last useful error\n");
|
||||
await finish(stream);
|
||||
expect(diagnostics.getTail().length).toBeLessThanOrEqual(4096);
|
||||
expect(diagnostics.getTail()).toContain("last useful error");
|
||||
expect(diagnostics.getTail()).not.toContain("oversized-secret");
|
||||
});
|
||||
|
||||
it("withholds an incomplete credential line until it can be safely sanitized", async () => {
|
||||
const stream = new PassThrough();
|
||||
const diagnostics = collectFfmpegDiagnostics(stream);
|
||||
stream.write("decoder warning\nhttps://user:partial-secret@");
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(diagnostics.getTail()).toContain("decoder warning");
|
||||
expect(diagnostics.getTail()).not.toContain("partial-secret");
|
||||
stream.write("cdn.example/audio?token=last-secret");
|
||||
await finish(stream);
|
||||
expect(diagnostics.getTail()).not.toContain("partial-secret");
|
||||
expect(diagnostics.getTail()).not.toContain("last-secret");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
import type { Readable } from "node:stream";
|
||||
import { StringDecoder } from "node:string_decoder";
|
||||
|
||||
const MAX_LINE_CHARS = 2048;
|
||||
const MAX_TAIL_CHARS = 4096;
|
||||
|
||||
export interface FfmpegDiagnostics {
|
||||
getTail(): string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drain independently of the PCM pipe: unread stderr can block FFmpeg even
|
||||
* when stdout is being consumed. Keep only complete, sanitized lines. Never
|
||||
* retain a suffix of an oversized raw line: it may have lost its URL/header
|
||||
* prefix and would no longer be possible to redact safely.
|
||||
*/
|
||||
export function collectFfmpegDiagnostics(stderr: Readable | null): FfmpegDiagnostics {
|
||||
let tail = "";
|
||||
let pending = "";
|
||||
let discardLine = false;
|
||||
let suppressHeaderContinuation = false;
|
||||
let previousCR = false;
|
||||
const decoder = new StringDecoder("utf8");
|
||||
|
||||
const append = (text: string): void => {
|
||||
if (text) previousCR = false;
|
||||
if (discardLine) return;
|
||||
if (pending.length + text.length > MAX_LINE_CHARS) {
|
||||
pending = "";
|
||||
discardLine = true;
|
||||
return;
|
||||
}
|
||||
pending += text;
|
||||
};
|
||||
|
||||
const finishLine = (): void => {
|
||||
if (discardLine) {
|
||||
tail = (tail + "[oversized diagnostic line omitted]\n").slice(-MAX_TAIL_CHARS);
|
||||
// An omitted line may be an authentication header. Omit folded values.
|
||||
suppressHeaderContinuation = true;
|
||||
} else if (pending) {
|
||||
const line = pending
|
||||
.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "")
|
||||
.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, "");
|
||||
const authHeader = /\b(?:cookie|set-cookie|authorization|proxy-authorization)\s*[:=]/i.test(line);
|
||||
if (authHeader || (suppressHeaderContinuation && /^\s/.test(line))) {
|
||||
tail = (tail + "[authentication header omitted]\n").slice(-MAX_TAIL_CHARS);
|
||||
suppressHeaderContinuation = true;
|
||||
} else {
|
||||
suppressHeaderContinuation = false;
|
||||
const sanitized = line
|
||||
// URLs and credentials can contain quotes or spaces. Keep the error
|
||||
// prefix only; guessing a closing delimiter could expose a suffix.
|
||||
.replace(/\b[a-z][a-z\d+.-]*:\/\/[\s\S]*/i, "[URL omitted]")
|
||||
// FFmpeg can also print a request target without the scheme/host.
|
||||
.replace(/\?[\s\S]*/, "?[query omitted]")
|
||||
.replace(/\bBearer\s+[\s\S]*/i, "Bearer [omitted]");
|
||||
tail = (tail + sanitized + "\n").slice(-MAX_TAIL_CHARS);
|
||||
}
|
||||
} else {
|
||||
suppressHeaderContinuation = false;
|
||||
}
|
||||
pending = "";
|
||||
discardLine = false;
|
||||
};
|
||||
|
||||
const consume = (text: string): void => {
|
||||
const separators = /[\r\n]/g;
|
||||
let start = 0;
|
||||
for (let match = separators.exec(text); match; match = separators.exec(text)) {
|
||||
append(text.slice(start, match.index));
|
||||
if (match[0] === "\n" && previousCR) {
|
||||
previousCR = false;
|
||||
} else {
|
||||
finishLine();
|
||||
previousCR = match[0] === "\r";
|
||||
}
|
||||
start = match.index + 1;
|
||||
}
|
||||
append(text.slice(start));
|
||||
};
|
||||
|
||||
stderr?.on("data", (chunk: Buffer) => consume(decoder.write(chunk)));
|
||||
stderr?.on("end", () => {
|
||||
consume(decoder.end());
|
||||
finishLine();
|
||||
});
|
||||
// Resume explicitly as attaching a listener does not resume an already
|
||||
// paused Readable. No player pause/backpressure operation touches stderr.
|
||||
stderr?.resume();
|
||||
|
||||
return { getTail: () => tail.trimEnd() };
|
||||
}
|
||||
+420
-5
@@ -2,10 +2,20 @@ import { describe, it, expect, vi } from "vitest";
|
||||
import { mkdtempSync, writeFileSync, existsSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { Readable } from "node:stream";
|
||||
import { Readable, PassThrough } from "node:stream";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import pino from "pino";
|
||||
import { buildFfmpegArgs, shouldUsePowerShellDownload, cleanupTempDir, shouldEndOnStall, volumeToFactor, AudioPlayer } from "./player.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
|
||||
// Only replace process creation in the regression cases below. Their pipes,
|
||||
// write callbacks and backpressure are real OS resources, rather than mocks.
|
||||
vi.mock("node:child_process", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("node:child_process")>();
|
||||
return { ...actual, spawn: vi.fn(actual.spawn) };
|
||||
});
|
||||
|
||||
function getHeadersArg(args: string[]): string {
|
||||
const idx = args.indexOf("-headers");
|
||||
if (idx === -1) return "";
|
||||
@@ -30,12 +40,59 @@ describe("buildFfmpegArgs", () => {
|
||||
expect(headers).toContain("User-Agent: Mozilla/5.0");
|
||||
});
|
||||
|
||||
it.each([
|
||||
"https://bilivideo.com/audio.m4s",
|
||||
"https://upos-sz-mirrorcos.bilivideo.com/audio.m4s",
|
||||
"https://bilivideo.cn/audio.m4s",
|
||||
"https://cn-example-live-01.bilivideo.cn/audio.m4s",
|
||||
"https://bilibili.com/audio.m4s",
|
||||
"https://www.bilibili.com/audio.m4s",
|
||||
"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) => {
|
||||
const args = buildFfmpegArgs(url, 2220);
|
||||
const headers = getHeadersArg(args);
|
||||
expect(headers).toContain("Referer: https://www.bilibili.com");
|
||||
expect(headers).toContain("User-Agent: Mozilla/5.0");
|
||||
expect(args[args.indexOf("-ss") + 1]).toBe("2220");
|
||||
expect(args.indexOf("-ss")).toBeLessThan(args.indexOf("-i"));
|
||||
expect(args.lastIndexOf("-ss")).toBe(args.indexOf("-ss"));
|
||||
expect(args).toContain("-reconnect_at_eof");
|
||||
});
|
||||
|
||||
it.each([
|
||||
"https://bilivideo.com.evil.example/audio.m4s",
|
||||
"https://evilbilivideo.com/audio.m4s",
|
||||
"https://bilivideo.cn.evil.example/audio.m4s",
|
||||
"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) => {
|
||||
const args = buildFfmpegArgs(url, 2220);
|
||||
expect(args).not.toContain("-headers");
|
||||
expect(args.indexOf("-ss")).toBeGreaterThan(args.indexOf("-i"));
|
||||
});
|
||||
|
||||
it("does not set custom headers for unknown URLs", () => {
|
||||
const url = "https://example.com/song.mp3";
|
||||
const args = buildFfmpegArgs(url, 0);
|
||||
expect(args).not.toContain("-headers");
|
||||
});
|
||||
|
||||
it("disables periodic progress stats for both network and file inputs", () => {
|
||||
for (const input of ["https://example.com/song.mp3", "C:/temp/song.audio"]) {
|
||||
expect(buildFfmpegArgs(input, 0)).toContain("-nostats");
|
||||
}
|
||||
});
|
||||
|
||||
it("includes resilient reconnect flags for all URLs", () => {
|
||||
const args = buildFfmpegArgs("https://example.com/song.mp3", 0);
|
||||
expect(args).toContain("-reconnect");
|
||||
@@ -55,13 +112,21 @@ describe("buildFfmpegArgs", () => {
|
||||
expect(idx).toBeLessThan(args.indexOf("-i")); // input options must precede -i
|
||||
});
|
||||
|
||||
it("inserts -ss before -i when seekSeconds > 0", () => {
|
||||
it("inserts -ss after -i when seekSeconds > 0", () => {
|
||||
const args = buildFfmpegArgs("https://example.com/song.mp3", 42);
|
||||
const ssIdx = args.indexOf("-ss");
|
||||
const iIdx = args.indexOf("-i");
|
||||
expect(ssIdx).toBeGreaterThan(-1);
|
||||
expect(args[ssIdx + 1]).toBe("42");
|
||||
expect(ssIdx).toBeLessThan(iIdx);
|
||||
expect(ssIdx).toBeGreaterThan(iIdx);
|
||||
});
|
||||
|
||||
it("seeks B站 streams input-side (before -i) so a resume jumps via Range instead of re-downloading (#161)", () => {
|
||||
const args = buildFfmpegArgs("https://upos-sz-mirrorcos.bilivideo.com/audio.m4s", 3600);
|
||||
const ssIdx = args.indexOf("-ss");
|
||||
expect(args[ssIdx + 1]).toBe("3600");
|
||||
expect(ssIdx).toBeLessThan(args.indexOf("-i"));
|
||||
expect(args.lastIndexOf("-ss")).toBe(ssIdx); // only one -ss
|
||||
});
|
||||
|
||||
it("does not insert -ss when seekSeconds is 0", () => {
|
||||
@@ -216,6 +281,249 @@ const silentLogger = {
|
||||
},
|
||||
} as unknown as Logger;
|
||||
|
||||
describe("AudioPlayer FFmpeg stderr handling", () => {
|
||||
const producer = `
|
||||
const pressure = 'decoder diagnostic\\n'.repeat(180000);
|
||||
process.stderr.write(pressure, () => {
|
||||
process.stderr.write('HTTP error 403 for https://user:password@cdn.example/audio?token=signed-secret#fragment-secret\\n');
|
||||
process.stderr.write('Cookie: cookie-secret\\nAuthorization: Bearer bearer-secret\\n');
|
||||
process.stderr.write('final decoder failure', () => {
|
||||
process.stdout.write(Buffer.alloc(7680), () => process.exit(1));
|
||||
});
|
||||
});
|
||||
`;
|
||||
|
||||
function recordedLogger() {
|
||||
const records: Array<{ level: string; fields: Record<string, unknown>; message: string }> = [];
|
||||
const capture = (level: string) => (fields: Record<string, unknown>, message: string) => {
|
||||
records.push({ level, fields, message });
|
||||
};
|
||||
return {
|
||||
records,
|
||||
logger: { ...silentLogger, info: capture("info"), warn: capture("warn") } as unknown as Logger,
|
||||
};
|
||||
}
|
||||
|
||||
async function pipeProducer(script: string) {
|
||||
const actual = await vi.importActual<typeof import("node:child_process")>("node:child_process");
|
||||
let child!: ChildProcess;
|
||||
let requestedArgs: readonly string[] = [];
|
||||
let closed!: Promise<number | null>;
|
||||
vi.mocked(spawn).mockImplementationOnce((_command, args, options) => {
|
||||
requestedArgs = args ?? [];
|
||||
child = actual.spawn(process.execPath, ["-e", script], options);
|
||||
closed = new Promise((resolve) => child.once("close", resolve));
|
||||
return child;
|
||||
});
|
||||
return {
|
||||
get child() { return child; },
|
||||
get args() { return requestedArgs; },
|
||||
get closed() { return closed; },
|
||||
};
|
||||
}
|
||||
|
||||
for (const path of ["URL", "temp file"] as const) {
|
||||
it(`drains the ${path} child stderr so a large diagnostic write cannot block PCM output`, async () => {
|
||||
const { records, logger } = recordedLogger();
|
||||
const producerProcess = await pipeProducer(producer);
|
||||
const player = new AudioPlayer(logger);
|
||||
let frameCount = 0;
|
||||
player.on("frame", () => frameCount++);
|
||||
let deadline: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
if (path === "URL") {
|
||||
player.play("https://cdn.example/audio?token=input-secret");
|
||||
} else {
|
||||
// The real downloader marks playing before calling this file path.
|
||||
const internal = player as unknown as {
|
||||
state: string;
|
||||
spawnFfmpegFromFile(file: string, seek: number, session: number): void;
|
||||
};
|
||||
internal.state = "playing";
|
||||
internal.spawnFfmpegFromFile("downloaded.audio", 0, player.getPlaybackSessionId());
|
||||
}
|
||||
const outcome = await Promise.race([
|
||||
producerProcess.closed,
|
||||
new Promise<string>((resolve) => {
|
||||
deadline = setTimeout(() => resolve("stderr blocked audio output"), 1500);
|
||||
}),
|
||||
]);
|
||||
expect(outcome).toBe(1);
|
||||
expect(producerProcess.args).toContain("-nostats");
|
||||
await vi.waitFor(() => expect(frameCount).toBeGreaterThan(0));
|
||||
const exit = records.find((record) => record.message === "FFmpeg exited");
|
||||
expect(exit?.fields.stderr).toContain("final decoder failure");
|
||||
expect(exit?.fields.stderr).toContain("HTTP error 403");
|
||||
const logged = JSON.stringify(records);
|
||||
for (const secret of ["password", "signed-secret", "fragment-secret", "cookie-secret", "bearer-secret", "input-secret"]) {
|
||||
expect(logged).not.toContain(secret);
|
||||
}
|
||||
expect(String(exit?.fields.stderr).length).toBeLessThanOrEqual(4096);
|
||||
} finally {
|
||||
if (deadline) clearTimeout(deadline);
|
||||
player.stop();
|
||||
if (producerProcess.child.exitCode === null) producerProcess.child.kill("SIGKILL");
|
||||
await producerProcess.closed;
|
||||
}
|
||||
});
|
||||
|
||||
it(`does not expose the ${path} input credentials through serialized spawn errors`, async () => {
|
||||
const actual = await vi.importActual<typeof import("node:child_process")>("node:child_process");
|
||||
let child!: ChildProcess;
|
||||
let closed!: Promise<void>;
|
||||
vi.mocked(spawn).mockImplementationOnce((_command, args, options) => {
|
||||
child = actual.spawn(join(tmpdir(), "tsbot-ffmpeg-does-not-exist"), args, options);
|
||||
closed = new Promise((resolve) => child.once("close", () => resolve()));
|
||||
return child;
|
||||
});
|
||||
const player = new AudioPlayer(silentLogger);
|
||||
const emitted = new Promise<Error>((resolve) => player.once("error", resolve));
|
||||
try {
|
||||
const input = "https://user:spawn-password@cdn.example/audio?token=spawn-secret";
|
||||
if (path === "URL") {
|
||||
player.play(input);
|
||||
} else {
|
||||
(player as unknown as { spawnFfmpegFromFile(file: string, seek: number, session: number): void })
|
||||
.spawnFfmpegFromFile(input, 0, player.getPlaybackSessionId());
|
||||
}
|
||||
const error = await emitted;
|
||||
expect(error).toBeInstanceOf(Error);
|
||||
expect(error.message).toContain("ENOENT");
|
||||
const serialized = JSON.stringify(pino.stdSerializers.err(error));
|
||||
expect(serialized).not.toContain("spawn-secret");
|
||||
expect(serialized).not.toContain("spawn-password");
|
||||
await closed;
|
||||
} finally {
|
||||
player.stop();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
it("logs intentional stop signals at info level", async () => {
|
||||
const { records, logger } = recordedLogger();
|
||||
const producerProcess = await pipeProducer("process.stdout.write(Buffer.from([0])); setInterval(() => {}, 1000);");
|
||||
const player = new AudioPlayer(logger);
|
||||
try {
|
||||
player.play("https://cdn.example/audio");
|
||||
await new Promise<void>((resolve) => producerProcess.child.stdout!.once("data", () => resolve()));
|
||||
player.stop();
|
||||
await producerProcess.closed;
|
||||
const exit = records.find((record) => record.message === "FFmpeg exited");
|
||||
expect(exit?.level).toBe("info");
|
||||
} finally {
|
||||
player.stop();
|
||||
if (producerProcess.child.exitCode === null) producerProcess.child.kill("SIGKILL");
|
||||
await producerProcess.closed;
|
||||
}
|
||||
});
|
||||
|
||||
it("reports a sanitized diagnostic tail when a child exits from an unexpected signal", async () => {
|
||||
const { records, logger } = recordedLogger();
|
||||
const child = Object.assign(new EventEmitter(), {
|
||||
pid: undefined,
|
||||
stdout: new PassThrough(),
|
||||
stderr: new PassThrough(),
|
||||
});
|
||||
vi.mocked(spawn).mockReturnValueOnce(child as unknown as ChildProcess);
|
||||
const player = new AudioPlayer(logger);
|
||||
try {
|
||||
player.play("https://cdn.example/audio");
|
||||
child.stderr.write("decoder crashed for https://cdn.example/audio?token=signal-secret");
|
||||
const ended = new Promise<void>((resolve) => child.stderr.once("end", resolve));
|
||||
child.stderr.end();
|
||||
await ended;
|
||||
child.emit("exit", null, "SIGSEGV");
|
||||
child.emit("close", null, "SIGSEGV");
|
||||
const exit = records.find((record) => record.message === "FFmpeg exited");
|
||||
expect(exit?.level).toBe("warn");
|
||||
expect(exit?.fields.signal).toBe("SIGSEGV");
|
||||
expect(exit?.fields.stderr).toContain("decoder crashed");
|
||||
expect(JSON.stringify(records)).not.toContain("signal-secret");
|
||||
} finally {
|
||||
player.stop();
|
||||
child.stdout.destroy();
|
||||
child.stderr.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps draining an old child's stderr without mixing its late diagnostics or exit into a new session", async () => {
|
||||
const { records, logger } = recordedLogger();
|
||||
const makeChild = () => Object.assign(new EventEmitter(), {
|
||||
pid: undefined,
|
||||
stdout: new PassThrough(),
|
||||
stderr: new PassThrough(),
|
||||
});
|
||||
const oldChild = makeChild();
|
||||
const newChild = makeChild();
|
||||
vi.mocked(spawn)
|
||||
.mockReturnValueOnce(oldChild as unknown as ChildProcess)
|
||||
.mockReturnValueOnce(newChild as unknown as ChildProcess);
|
||||
const player = new AudioPlayer(logger);
|
||||
try {
|
||||
player.play("https://cdn.example/old");
|
||||
const oldSession = player.getPlaybackSessionId();
|
||||
player.play("https://cdn.example/new");
|
||||
const newSession = player.getPlaybackSessionId();
|
||||
oldChild.stderr.write("old late decoder failure https://cdn.example/old?token=old-secret\n".repeat(1000));
|
||||
newChild.stderr.write("new decoder failure\n");
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(oldChild.stderr.readableLength).toBe(0);
|
||||
oldChild.emit("exit", 1, null);
|
||||
oldChild.stderr.end();
|
||||
oldChild.emit("close", 1, null);
|
||||
expect(player.getState()).toBe("playing");
|
||||
vi.useFakeTimers();
|
||||
const internal = player as unknown as { frameLoopRunning: boolean; startFrameLoop(): void };
|
||||
internal.frameLoopRunning = false;
|
||||
internal.startFrameLoop();
|
||||
vi.advanceTimersByTime(6000);
|
||||
const stall = records.find((record) => record.message === "FFmpeg stopped outputting data, ending track");
|
||||
expect(stall?.fields.sessionId).toBe(newSession);
|
||||
expect(stall?.fields.stderr).toContain("new decoder failure");
|
||||
expect(stall?.fields.stderr).not.toContain("old late decoder failure");
|
||||
const oldExit = records.find((record) => record.message === "FFmpeg exited");
|
||||
expect(oldExit?.fields.sessionId).toBe(oldSession);
|
||||
expect(JSON.stringify(records)).not.toContain("old-secret");
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
player.stop();
|
||||
oldChild.stdout.destroy();
|
||||
oldChild.stderr.destroy();
|
||||
newChild.stdout.destroy();
|
||||
newChild.stderr.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
it("includes the current child's sanitized diagnostic tail when the stall watchdog ends playback", async () => {
|
||||
const { records, logger } = recordedLogger();
|
||||
const producerProcess = await pipeProducer(`
|
||||
process.stderr.write('HTTP error 403: https://cdn.example/audio?token=stall-secret\\n');
|
||||
process.stdout.write(Buffer.from([0]));
|
||||
setInterval(() => {}, 1000);
|
||||
`);
|
||||
const player = new AudioPlayer(logger);
|
||||
try {
|
||||
player.play("https://cdn.example/audio");
|
||||
await new Promise<void>((resolve) => producerProcess.child.stdout!.once("data", () => resolve()));
|
||||
vi.useFakeTimers();
|
||||
// Restart scheduling under the test clock, without changing EOF state.
|
||||
const internal = player as unknown as { frameLoopRunning: boolean; startFrameLoop(): void };
|
||||
internal.frameLoopRunning = false;
|
||||
internal.startFrameLoop();
|
||||
vi.advanceTimersByTime(6000);
|
||||
const stall = records.find((record) => record.message === "FFmpeg stopped outputting data, ending track");
|
||||
expect(stall?.fields.stderr).toContain("HTTP error 403");
|
||||
expect(JSON.stringify(records)).not.toContain("stall-secret");
|
||||
expect(player.getState()).toBe("idle");
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
player.stop();
|
||||
if (producerProcess.child.exitCode === null) producerProcess.child.kill("SIGKILL");
|
||||
await producerProcess.closed;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function applyPlayerVolume(player: AudioPlayer, pcm: Buffer): Buffer {
|
||||
return (
|
||||
player as unknown as { applyVolume(input: Buffer): Buffer }
|
||||
@@ -558,7 +866,7 @@ describe("AudioPlayer stall/EOF end-detection is gated on playing state (R3-4)",
|
||||
// PCM frame (unknown duration -> isNearEnd forced true). startFrameLoop() runs
|
||||
// the genuine loop; no real process is spawned (fake ffmpeg has no pid, so the
|
||||
// end path never touches forceCleanup/process.kill).
|
||||
function makeStalledPlaying(): AudioPlayer {
|
||||
function makeStalledPlaying(duration = 0): AudioPlayer {
|
||||
const player = new AudioPlayer(silentLogger);
|
||||
const p = player as unknown as {
|
||||
ffmpeg: unknown;
|
||||
@@ -570,7 +878,7 @@ describe("AudioPlayer stall/EOF end-detection is gated on playing state (R3-4)",
|
||||
startFrameLoop(): void;
|
||||
};
|
||||
p.ffmpeg = { pid: undefined }; // live ffmpeg, but delivers no PCM
|
||||
p.currentSongDuration = 0; // unknown duration -> isNearEnd === true
|
||||
p.currentSongDuration = duration;
|
||||
p.pcmBuffer = Buffer.alloc(0); // always < one PCM frame
|
||||
p.emptyFrameAttempts = 0;
|
||||
p.framesPlayed = 0;
|
||||
@@ -579,6 +887,113 @@ describe("AudioPlayer stall/EOF end-detection is gated on playing state (R3-4)",
|
||||
return player;
|
||||
}
|
||||
|
||||
it.each([0, 4020])("keeps emitting one full PCM frame per tick beyond 60 seconds with duration %s", (duration) => {
|
||||
vi.useFakeTimers(FAKE_TIMER_OPTS);
|
||||
const player = makeStalledPlaying(duration);
|
||||
let ended = 0;
|
||||
let frames = 0;
|
||||
player.on("trackEnd", () => ended++);
|
||||
player.on("frame", () => frames++);
|
||||
try {
|
||||
const internal = player as unknown as { pcmBuffer: Buffer };
|
||||
const frame = Buffer.alloc(FRAME_BYTES);
|
||||
for (let tick = 0; tick < 3100; tick++) {
|
||||
internal.pcmBuffer = frame;
|
||||
vi.advanceTimersByTime(20);
|
||||
}
|
||||
expect(frames).toBe(3100);
|
||||
expect(player.getElapsed()).toBe(62);
|
||||
expect(ended).toBe(0);
|
||||
expect(player.getState()).toBe("playing");
|
||||
} finally {
|
||||
player.stop();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("resets the true-underrun budget after a successful frame even when no PCM reserve remains", () => {
|
||||
vi.useFakeTimers(FAKE_TIMER_OPTS);
|
||||
const player = makeStalledPlaying();
|
||||
let ended = 0;
|
||||
player.on("trackEnd", () => ended++);
|
||||
try {
|
||||
vi.advanceTimersByTime(20 * 249);
|
||||
(player as unknown as { pcmBuffer: Buffer }).pcmBuffer = Buffer.alloc(FRAME_BYTES);
|
||||
vi.advanceTimersByTime(20);
|
||||
expect(ended).toBe(0);
|
||||
expect(player.getElapsed()).toBe(0.02);
|
||||
vi.advanceTimersByTime(20 * 249);
|
||||
expect(ended).toBe(0);
|
||||
vi.advanceTimersByTime(20);
|
||||
expect(ended).toBe(1);
|
||||
expect(player.getState()).toBe("idle");
|
||||
} finally {
|
||||
player.stop();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("still ends a genuine far-from-end stall after 60 seconds without a frame", () => {
|
||||
vi.useFakeTimers(FAKE_TIMER_OPTS);
|
||||
const player = makeStalledPlaying(4020);
|
||||
let ended = 0;
|
||||
player.on("trackEnd", () => ended++);
|
||||
try {
|
||||
vi.advanceTimersByTime(59980);
|
||||
expect(ended).toBe(0);
|
||||
expect(player.getState()).toBe("playing");
|
||||
vi.advanceTimersByTime(20);
|
||||
expect(ended).toBe(1);
|
||||
expect(player.getState()).toBe("idle");
|
||||
} finally {
|
||||
player.stop();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("still emits natural EOF after delivering the final buffered frame", () => {
|
||||
vi.useFakeTimers(FAKE_TIMER_OPTS);
|
||||
const player = makeStalledPlaying(4020);
|
||||
let ended = 0;
|
||||
let frames = 0;
|
||||
player.on("trackEnd", () => ended++);
|
||||
player.on("frame", () => frames++);
|
||||
try {
|
||||
Object.assign(player, { ffmpeg: null, pcmBuffer: Buffer.alloc(FRAME_BYTES) });
|
||||
vi.advanceTimersByTime(20);
|
||||
expect(frames).toBe(1);
|
||||
expect(ended).toBe(1);
|
||||
expect(player.getState()).toBe("idle");
|
||||
} finally {
|
||||
player.stop();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("does not count a consumed frame as successful when the encoder throws", () => {
|
||||
vi.useFakeTimers(FAKE_TIMER_OPTS);
|
||||
const player = makeStalledPlaying(4020);
|
||||
const failure = new Error("offline encoder failure");
|
||||
const errors: Error[] = [];
|
||||
let frames = 0;
|
||||
player.on("error", error => errors.push(error));
|
||||
player.on("frame", () => frames++);
|
||||
try {
|
||||
Object.assign(player, {
|
||||
pcmBuffer: Buffer.alloc(FRAME_BYTES),
|
||||
encoder: { encode() { throw failure; } },
|
||||
});
|
||||
vi.advanceTimersByTime(20);
|
||||
expect(errors).toEqual([failure]);
|
||||
expect(frames).toBe(0);
|
||||
expect(player.getElapsed()).toBe(0);
|
||||
expect((player as unknown as { emptyFrameAttempts: number }).emptyFrameAttempts).toBe(1);
|
||||
} finally {
|
||||
player.stop();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("does NOT emit trackEnd (and stays paused) when a stalled unknown-duration stream is paused past the stall threshold", () => {
|
||||
vi.useFakeTimers(FAKE_TIMER_OPTS);
|
||||
try {
|
||||
|
||||
+186
-32
@@ -7,6 +7,7 @@ import { join } from "node:path";
|
||||
import { createOpusEncoder, PCM_FRAME_BYTES, type Encoder } from "./encoder.js";
|
||||
import type { Readable } from "node:stream";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { collectFfmpegDiagnostics, type FfmpegDiagnostics } from "./ffmpeg-diagnostics.js";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const ffmpegPath: string | null = require("ffmpeg-static");
|
||||
@@ -52,6 +53,17 @@ export function getFfmpegCommand(): string {
|
||||
return resolvedFfmpeg;
|
||||
}
|
||||
|
||||
function safeFfmpegSpawnError(err: Error): Error {
|
||||
// Node spawn errors include spawnargs; Pino's Error serializer copies them,
|
||||
// including the signed input URL. Preserve a known OS category only.
|
||||
const allowedCodes = new Set(["ENOENT", "EACCES", "EPERM", "ENOEXEC", "EMFILE", "ENFILE", "ENOMEM", "EAGAIN", "EINVAL"]);
|
||||
const code = (err as NodeJS.ErrnoException).code;
|
||||
const safeCode = typeof code === "string" && allowedCodes.has(code) ? code : undefined;
|
||||
const safeError = new Error(`FFmpeg failed to start${safeCode ? ` (${safeCode})` : ""}`);
|
||||
if (safeCode) Object.assign(safeError, { code: safeCode });
|
||||
return safeError;
|
||||
}
|
||||
|
||||
const BROWSER_UA =
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
|
||||
|
||||
@@ -74,10 +86,23 @@ export function cleanupTempDir(dir: string): void {
|
||||
}
|
||||
|
||||
export function buildFfmpegArgs(url: string, seekSeconds: number): string[] {
|
||||
const args: string[] = [];
|
||||
const isHttp = /^https?:\/\//i.test(url);
|
||||
const args: string[] = ["-nostats"];
|
||||
let httpHostname: string | null = null;
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
if (parsed.protocol === "http:" || parsed.protocol === "https:") {
|
||||
httpHostname = parsed.hostname.toLowerCase().replace(/\.$/, "");
|
||||
}
|
||||
} catch {
|
||||
// Local paths and malformed URLs must not inherit CDN-specific options.
|
||||
}
|
||||
const isHttp = httpHostname !== null;
|
||||
const isBilibili = httpHostname !== null &&
|
||||
["bilivideo.com", "bilivideo.cn", "bilibili.com", "szbdyd.com", "mountaintoys.cn"].some(
|
||||
domain => httpHostname === domain || httpHostname.endsWith(`.${domain}`),
|
||||
);
|
||||
|
||||
if (isHttp && (url.includes("bilivideo") || url.includes("bilibili"))) {
|
||||
if (isBilibili) {
|
||||
args.push(
|
||||
"-headers",
|
||||
`Referer: https://www.bilibili.com\r\nUser-Agent: ${BROWSER_UA}\r\n`,
|
||||
@@ -103,8 +128,16 @@ export function buildFfmpegArgs(url: string, seekSeconds: number): string[] {
|
||||
"-reconnect_on_http_error", "4xx,5xx",
|
||||
);
|
||||
}
|
||||
if (seekSeconds > 0) args.push("-ss", String(seekSeconds));
|
||||
args.push("-i", url, "-f", "s16le", "-ar", "48000", "-ac", "2", "-acodec", "pcm_s16le", "-");
|
||||
// B站's CDN serves Range requests, so seek input-side: FFmpeg jumps straight
|
||||
// to the byte offset. Output-side seek would download and decode everything
|
||||
// before the target first — minutes for a resume deep into a 3-hour video
|
||||
// (#161), long enough to trip the stall watchdog.
|
||||
const inputSideSeek = isBilibili;
|
||||
if (seekSeconds > 0 && inputSideSeek) args.push("-ss", String(seekSeconds));
|
||||
args.push("-i", url);
|
||||
// Output-side seek (after -i): works on CDNs that reject Range/keyframe seeks (NetEase music.126.net).
|
||||
if (seekSeconds > 0 && !inputSideSeek) args.push("-ss", String(seekSeconds));
|
||||
args.push("-f", "s16le", "-ar", "48000", "-ac", "2", "-acodec", "pcm_s16le", "-");
|
||||
|
||||
return args;
|
||||
}
|
||||
@@ -158,6 +191,8 @@ const FRAME_DURATION_MS = 20;
|
||||
|
||||
export class AudioPlayer extends EventEmitter {
|
||||
private ffmpeg: ChildProcess | null = null;
|
||||
private ffmpegDiagnostics: FfmpegDiagnostics | null = null;
|
||||
private readonly intentionalCleanup = new WeakSet<ChildProcess>();
|
||||
private encoder: Encoder;
|
||||
private state: PlayerState = "idle";
|
||||
private volume = 75;
|
||||
@@ -171,6 +206,14 @@ export class AudioPlayer extends EventEmitter {
|
||||
private duckingRampStartedAt = 0;
|
||||
private duckingRampDurationMs = 0;
|
||||
private pcmBuffer: Buffer = Buffer.alloc(0);
|
||||
private transitionSilence = false;
|
||||
private pauseFrames = 0;
|
||||
private resumeSilenceFrames = 0;
|
||||
private stopAfterPauseTail = false;
|
||||
private transportRampStart: number | null = null;
|
||||
private transportRampEnd: number | null = null;
|
||||
private transportRampFrom = 1;
|
||||
private transportRampTo = 1;
|
||||
private logger: Logger;
|
||||
private frameLoopRunning = false;
|
||||
private nextFrameTime = 0;
|
||||
@@ -221,7 +264,7 @@ export class AudioPlayer extends EventEmitter {
|
||||
|
||||
play(url: string, seekSeconds = 0, songDuration = 0): void {
|
||||
// 1. 停止当前所有播放,自增 sessionId 屏蔽旧回调 (
|
||||
this.stop();
|
||||
this.stop(true);
|
||||
|
||||
const currentSessionId = this.sessionId;
|
||||
this.currentUrl = url;
|
||||
@@ -235,7 +278,7 @@ export class AudioPlayer extends EventEmitter {
|
||||
|
||||
if (this.consecutiveFailures >= AudioPlayer.MAX_CONSECUTIVE_FAILURES) {
|
||||
this.logger.error({ failures: this.consecutiveFailures }, "FFmpeg failures limit reached");
|
||||
this.state = "idle";
|
||||
this.stop();
|
||||
this.emit("error", new Error("ffmpeg unavailable"));
|
||||
return;
|
||||
}
|
||||
@@ -249,6 +292,9 @@ export class AudioPlayer extends EventEmitter {
|
||||
|
||||
const ffmpegBin = getFfmpegCommand();
|
||||
this.ffmpeg = spawn(ffmpegBin, args, { stdio: ["ignore", "pipe", "pipe"] });
|
||||
const child = this.ffmpeg;
|
||||
const diagnostics = collectFfmpegDiagnostics(child.stderr);
|
||||
this.ffmpegDiagnostics = diagnostics;
|
||||
|
||||
const currentPid = this.ffmpeg.pid;
|
||||
if (currentPid) {
|
||||
@@ -271,7 +317,6 @@ export class AudioPlayer extends EventEmitter {
|
||||
|
||||
this.ffmpeg.on("exit", (code, signal) => {
|
||||
if (currentPid) globalActivePids.delete(currentPid);
|
||||
this.logger.info({ pid: currentPid, code, signal }, "FFmpeg exited");
|
||||
|
||||
// 只有当前会话的进程结束才置空变量
|
||||
if (this.sessionId === currentSessionId) {
|
||||
@@ -279,11 +324,21 @@ export class AudioPlayer extends EventEmitter {
|
||||
}
|
||||
});
|
||||
|
||||
// close follows stderr's end, so final unterminated diagnostics are ready.
|
||||
this.ffmpeg.on("close", (code, signal) => {
|
||||
const context = { pid: currentPid, sessionId: currentSessionId, code, signal };
|
||||
if (!this.intentionalCleanup.has(child) && ((typeof code === "number" && code !== 0) || signal !== null)) {
|
||||
this.logger.warn({ ...context, stderr: diagnostics.getTail() }, "FFmpeg exited");
|
||||
} else {
|
||||
this.logger.info(context, "FFmpeg exited");
|
||||
}
|
||||
});
|
||||
|
||||
this.ffmpeg.on("error", (err) => {
|
||||
if (this.sessionId === currentSessionId) {
|
||||
this.spawnFailed = true;
|
||||
this.consecutiveFailures++;
|
||||
this.emit("error", err);
|
||||
this.emit("error", safeFfmpegSpawnError(err));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -323,10 +378,7 @@ export class AudioPlayer extends EventEmitter {
|
||||
);
|
||||
this.downloader = ps;
|
||||
|
||||
let stderrTail = "";
|
||||
ps.stderr!.on("data", (chunk: Buffer) => {
|
||||
stderrTail = (stderrTail + chunk.toString()).slice(-500);
|
||||
});
|
||||
const diagnostics = collectFfmpegDiagnostics(ps.stderr);
|
||||
|
||||
ps.on("exit", (code, signal) => {
|
||||
if (this.sessionId !== sessionId) {
|
||||
@@ -335,7 +387,6 @@ export class AudioPlayer extends EventEmitter {
|
||||
}
|
||||
this.downloader = null;
|
||||
if (code !== 0) {
|
||||
this.logger.warn({ code, signal, stderr: stderrTail }, "PowerShell download failed");
|
||||
this.spawnFailed = true;
|
||||
this.consecutiveFailures++;
|
||||
this.state = "idle";
|
||||
@@ -347,6 +398,12 @@ export class AudioPlayer extends EventEmitter {
|
||||
this.spawnFfmpegFromFile(tempFile, seekSeconds, sessionId);
|
||||
});
|
||||
|
||||
ps.on("close", (code, signal) => {
|
||||
if (!this.intentionalCleanup.has(ps) && ((typeof code === "number" && code !== 0) || signal !== null)) {
|
||||
this.logger.warn({ pid: ps.pid, sessionId, code, signal, stderr: diagnostics.getTail() }, "PowerShell download failed");
|
||||
}
|
||||
});
|
||||
|
||||
ps.on("error", (err) => {
|
||||
if (this.sessionId !== sessionId) return;
|
||||
this.downloader = null;
|
||||
@@ -377,6 +434,9 @@ export class AudioPlayer extends EventEmitter {
|
||||
const args = buildFfmpegArgs(tempFile, seekSeconds);
|
||||
const ffmpegBin = getFfmpegCommand();
|
||||
this.ffmpeg = spawn(ffmpegBin, args, { stdio: ["ignore", "pipe", "pipe"] });
|
||||
const child = this.ffmpeg;
|
||||
const diagnostics = collectFfmpegDiagnostics(child.stderr);
|
||||
this.ffmpegDiagnostics = diagnostics;
|
||||
|
||||
const currentPid = this.ffmpeg.pid;
|
||||
if (currentPid) {
|
||||
@@ -396,7 +456,6 @@ export class AudioPlayer extends EventEmitter {
|
||||
|
||||
this.ffmpeg.on("exit", (code, signal) => {
|
||||
if (currentPid) globalActivePids.delete(currentPid);
|
||||
this.logger.info({ pid: currentPid, code, signal }, "FFmpeg exited");
|
||||
if (this.sessionId === sessionId) {
|
||||
this.ffmpeg = null;
|
||||
if (this.currentTempDir === tempDirToCleanup) this.currentTempDir = null;
|
||||
@@ -404,11 +463,20 @@ export class AudioPlayer extends EventEmitter {
|
||||
if (tempDirToCleanup) cleanupTempDir(tempDirToCleanup);
|
||||
});
|
||||
|
||||
this.ffmpeg.on("close", (code, signal) => {
|
||||
const context = { pid: currentPid, sessionId, code, signal };
|
||||
if (!this.intentionalCleanup.has(child) && ((typeof code === "number" && code !== 0) || signal !== null)) {
|
||||
this.logger.warn({ ...context, stderr: diagnostics.getTail() }, "FFmpeg exited");
|
||||
} else {
|
||||
this.logger.info(context, "FFmpeg exited");
|
||||
}
|
||||
});
|
||||
|
||||
this.ffmpeg.on("error", (err) => {
|
||||
if (this.sessionId === sessionId) {
|
||||
this.spawnFailed = true;
|
||||
this.consecutiveFailures++;
|
||||
this.emit("error", err);
|
||||
this.emit("error", safeFfmpegSpawnError(err));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -437,7 +505,7 @@ export class AudioPlayer extends EventEmitter {
|
||||
playPcmStream(readable: Readable, opts: { onExternalEnd?: () => void } = {}): void {
|
||||
// 1. Fence current playback: stop() bumps sessionId, clears pcmBuffer, kills
|
||||
// any ffmpeg, and DETACHES (never destroys) any prior external stream.
|
||||
this.stop();
|
||||
this.stop(true);
|
||||
|
||||
const currentSessionId = this.sessionId;
|
||||
this.externalMode = true;
|
||||
@@ -527,13 +595,33 @@ export class AudioPlayer extends EventEmitter {
|
||||
this.onExternalEnd = null;
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
stopWithFade(): void {
|
||||
if (this.externalMode || this.state === "idle") {
|
||||
this.stop();
|
||||
return;
|
||||
}
|
||||
this.stopAfterPauseTail = true;
|
||||
if (this.state === "playing") {
|
||||
this.pauseFrames = 9;
|
||||
this.setTransportRamp(0, 0, 5);
|
||||
this.state = "paused";
|
||||
} else if (this.pauseFrames === 0) {
|
||||
this.stop();
|
||||
}
|
||||
}
|
||||
|
||||
stop(keepAlive = false): void {
|
||||
const wasRunning = this.frameLoopRunning;
|
||||
const deadline = this.nextFrameTime;
|
||||
this.transitionSilence = keepAlive;
|
||||
this.stopAfterPauseTail = false;
|
||||
// 3. 递增 ID 是最有效的逻辑“隔离墙”
|
||||
this.sessionId++;
|
||||
this.frameLoopRunning = false;
|
||||
|
||||
// 立即清空缓冲区,确保切歌瞬间静音 (
|
||||
this.pcmBuffer = Buffer.alloc(0);
|
||||
this.ffmpegDiagnostics = null;
|
||||
|
||||
if (this.ffmpeg) {
|
||||
const procToKill = this.ffmpeg;
|
||||
@@ -548,6 +636,7 @@ export class AudioPlayer extends EventEmitter {
|
||||
if (this.downloader) {
|
||||
const ps = this.downloader;
|
||||
this.downloader = null;
|
||||
this.intentionalCleanup.add(ps);
|
||||
try { ps.kill("SIGTERM"); } catch { /* already gone */ }
|
||||
}
|
||||
|
||||
@@ -568,9 +657,21 @@ export class AudioPlayer extends EventEmitter {
|
||||
this.seekOffset = 0;
|
||||
this.framesPlayed = 0;
|
||||
this.healthyFrames = 0;
|
||||
this.pauseFrames = 0;
|
||||
this.resumeSilenceFrames = 0;
|
||||
this.transportRampStart = null;
|
||||
this.transportRampEnd = null;
|
||||
this.transportRampFrom = 1;
|
||||
this.transportRampTo = 1;
|
||||
if (keepAlive) {
|
||||
this.frameLoopRunning = true;
|
||||
this.nextFrameTime = wasRunning ? Math.max(performance.now(), deadline - FRAME_DURATION_MS) : performance.now();
|
||||
this.scheduleNextFrame();
|
||||
}
|
||||
}
|
||||
|
||||
private forceCleanup(proc: ChildProcess, pid: number): void {
|
||||
this.intentionalCleanup.add(proc);
|
||||
if (!globalActivePids.has(pid)) return;
|
||||
|
||||
try {
|
||||
@@ -611,8 +712,27 @@ export class AudioPlayer extends EventEmitter {
|
||||
// 这里的校验能防止旧的定时器回调处理新 Session 的逻辑 (
|
||||
if (loopSessionId !== this.sessionId || !this.frameLoopRunning) return;
|
||||
|
||||
if (this.state === "playing") this.sendNextFrame();
|
||||
else if (this.state === "paused") this.nextFrameTime = performance.now();
|
||||
const framesBeforeTick = this.framesPlayed;
|
||||
if (this.state === "paused") {
|
||||
if (this.pauseFrames > 0) {
|
||||
this.pauseFrames--;
|
||||
if (this.pauseFrames > 3) this.sendNextFrame();
|
||||
else this.emitSilenceFrame(false);
|
||||
} else {
|
||||
this.nextFrameTime = performance.now();
|
||||
if (this.stopAfterPauseTail) {
|
||||
this.stop();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (this.state === "idle" && this.transitionSilence) this.emitSilenceFrame(false);
|
||||
else if (this.state === "playing" && this.resumeSilenceFrames > 0) {
|
||||
this.resumeSilenceFrames--;
|
||||
this.emitSilenceFrame(false);
|
||||
}
|
||||
else if (this.state === "playing") this.sendNextFrame();
|
||||
const frameSent = this.framesPlayed > framesBeforeTick;
|
||||
|
||||
// 检测pcmBuffer不足PCM_FRAME_BYTES导致连续循环卡死:
|
||||
// 条件1: FFmpeg仍在运行但缓冲区不足一帧,且连续多次无法获取数据
|
||||
@@ -632,7 +752,9 @@ export class AudioPlayer extends EventEmitter {
|
||||
// unknown-duration stream would auto-advance ~5s later. Because the if is
|
||||
// now false while paused, the else resets emptyFrameAttempts to 0, so a
|
||||
// resumed healthy stream starts fresh and never ends instantly.
|
||||
if (this.state === "playing" && !this.externalMode && this.ffmpeg !== null && this.pcmBuffer.length < PCM_FRAME_BYTES) {
|
||||
// A healthy paced source can supply exactly one frame per tick, leaving
|
||||
// no reserve after sendNextFrame. Count only ticks without emitted audio.
|
||||
if (this.state === "playing" && !this.externalMode && !frameSent && this.ffmpeg !== null && this.pcmBuffer.length < PCM_FRAME_BYTES) {
|
||||
this.emptyFrameAttempts++;
|
||||
|
||||
// End the track when FFmpeg has gone silent: quickly if we're near the
|
||||
@@ -655,6 +777,7 @@ export class AudioPlayer extends EventEmitter {
|
||||
duration: this.currentSongDuration,
|
||||
remaining: Math.round(this.currentSongDuration - elapsed),
|
||||
nearEnd: isNearEnd,
|
||||
stderr: this.ffmpegDiagnostics?.getTail() ?? "",
|
||||
}, "FFmpeg stopped outputting data, ending track");
|
||||
this.frameLoopRunning = false;
|
||||
// The outer gate guarantees state==="playing" here, so no !=="idle"
|
||||
@@ -680,7 +803,7 @@ export class AudioPlayer extends EventEmitter {
|
||||
|
||||
// R3-4: likewise gated on state==="playing" — a drained/EOF'd stream must
|
||||
// not emit trackEnd while paused; end-detection resumes on resume().
|
||||
if (this.state === "playing" && !this.externalMode && !this.ffmpeg && this.pcmBuffer.length < PCM_FRAME_BYTES) {
|
||||
if (this.state === "playing" && !this.externalMode && !this.ffmpeg && !this.downloader && this.pcmBuffer.length < PCM_FRAME_BYTES) {
|
||||
this.frameLoopRunning = false;
|
||||
// Outer gate guarantees state==="playing"; end directly (no !=="idle" guard).
|
||||
this.state = "idle";
|
||||
@@ -696,12 +819,12 @@ export class AudioPlayer extends EventEmitter {
|
||||
|
||||
private sendNextFrame(): void {
|
||||
if (this.pcmBuffer.length < PCM_FRAME_BYTES) {
|
||||
// External mode: the sidecar PCM stream is long-lived and must NOT end on
|
||||
// a transient underrun. Emit an encoded silence frame so the 20ms voice
|
||||
// timeline stays continuous instead of returning (which would desync TS).
|
||||
if (this.externalMode) this.emitSilenceFrame();
|
||||
// Keep the voice timeline continuous while the source is preparing/stalled.
|
||||
// URL silence must not advance elapsed time or hide the stall watchdog.
|
||||
if (this.externalMode || this.ffmpeg || this.downloader || this.transitionSilence) this.emitSilenceFrame(this.externalMode);
|
||||
return;
|
||||
}
|
||||
this.transitionSilence = false;
|
||||
const pcmFrame = this.pcmBuffer.subarray(0, PCM_FRAME_BYTES);
|
||||
this.pcmBuffer = this.pcmBuffer.subarray(PCM_FRAME_BYTES);
|
||||
|
||||
@@ -730,11 +853,11 @@ export class AudioPlayer extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
private emitSilenceFrame(): void {
|
||||
private emitSilenceFrame(advanceTimeline = true): void {
|
||||
try {
|
||||
const opusFrame = this.encoder.encode(Buffer.alloc(PCM_FRAME_BYTES));
|
||||
this.emit("frame", opusFrame);
|
||||
this.framesPlayed++;
|
||||
if (advanceTimeline) this.framesPlayed++;
|
||||
} catch (err) {
|
||||
this.emit("error", err as Error);
|
||||
}
|
||||
@@ -745,8 +868,10 @@ export class AudioPlayer extends EventEmitter {
|
||||
const now = performance.now();
|
||||
const startDuckingGain = this.duckingGainAt(now);
|
||||
const endDuckingGain = this.duckingGainAt(now + FRAME_DURATION_MS);
|
||||
const startFactor = baseFactor * startDuckingGain;
|
||||
const endFactor = baseFactor * endDuckingGain;
|
||||
const startTransportGain = this.transportGainAt(now);
|
||||
const endTransportGain = this.transportGainAt(now + FRAME_DURATION_MS);
|
||||
const startFactor = baseFactor * startDuckingGain * startTransportGain;
|
||||
const endFactor = baseFactor * endDuckingGain * endTransportGain;
|
||||
|
||||
if (startFactor >= 1 && endFactor >= 1) {
|
||||
return Buffer.from(pcm);
|
||||
@@ -776,6 +901,25 @@ export class AudioPlayer extends EventEmitter {
|
||||
return out;
|
||||
}
|
||||
|
||||
private setTransportRamp(target: number, delayFrames = 0, durationFrames = 3): void {
|
||||
const now = performance.now();
|
||||
const from = this.transportGainAt(now);
|
||||
this.transportRampStart = now + FRAME_DURATION_MS * delayFrames;
|
||||
this.transportRampEnd = this.transportRampStart + FRAME_DURATION_MS * durationFrames;
|
||||
this.transportRampFrom = from;
|
||||
this.transportRampTo = target;
|
||||
}
|
||||
|
||||
private transportGainAt(at: number): number {
|
||||
if (this.transportRampStart === null || this.transportRampEnd === null) return this.transportRampTo;
|
||||
const progress = Math.max(0, Math.min(1, (at - this.transportRampStart) / (this.transportRampEnd - this.transportRampStart)));
|
||||
if (progress >= 1) {
|
||||
this.transportRampStart = null;
|
||||
this.transportRampEnd = null;
|
||||
}
|
||||
return this.transportRampFrom + (this.transportRampTo - this.transportRampFrom) * progress;
|
||||
}
|
||||
|
||||
private duckingGainAt(at: number): number {
|
||||
if (this.duckingRampDurationMs <= 0) return this.duckingTargetGain;
|
||||
|
||||
@@ -800,11 +944,19 @@ export class AudioPlayer extends EventEmitter {
|
||||
// transport is delegated to the SpotifyController by the caller (Task 7).
|
||||
if (this.externalMode) return;
|
||||
if (this.currentUrl && Number.isFinite(seconds) && seconds >= 0) {
|
||||
const paused = this.state === "paused";
|
||||
this.play(this.currentUrl, seconds, this.currentSongDuration);
|
||||
if (paused && this.state === "playing") this.pause();
|
||||
}
|
||||
}
|
||||
pause(): void { if (this.state === "playing") this.state = "paused"; }
|
||||
resume(): void { if (this.state === "paused") { this.state = "playing"; this.nextFrameTime = performance.now(); } }
|
||||
pause(): void {
|
||||
if (this.state === "playing") {
|
||||
this.pauseFrames = 9;
|
||||
this.setTransportRamp(0, 0, 5);
|
||||
this.state = "paused";
|
||||
}
|
||||
}
|
||||
resume(): void { if (this.state === "paused") { this.pauseFrames = 0; this.resumeSilenceFrames = 3; this.setTransportRamp(1, 3, 5); this.state = "playing"; } }
|
||||
resetFailures(): void { this.consecutiveFailures = 0; }
|
||||
setVolume(vol: number): void { this.volume = Math.max(0, Math.min(100, vol)); }
|
||||
getVolume(): number { return this.volume; }
|
||||
@@ -825,6 +977,8 @@ export class AudioPlayer extends EventEmitter {
|
||||
}
|
||||
getDuckingGain(): number { return this.duckingGainAt(performance.now()); }
|
||||
getState(): PlayerState { return this.state; }
|
||||
/** Changes on stop or a new play/seek, so asynchronous recovery can be fenced. */
|
||||
getPlaybackSessionId(): number { return this.sessionId; }
|
||||
// True only while attached to an external (Spotify sidecar) PCM stream. Used
|
||||
// by the orchestrator to decide whether to re-attach: stop() detaches (sets
|
||||
// externalMode=false) so this is false after any player.stop().
|
||||
|
||||
+2
-16
@@ -42,22 +42,8 @@ export function decideOccupancyAction(
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a client-presence push event (a `clientEnter`) should trigger an
|
||||
* auto-resume, WITHOUT consulting a clientlist query.
|
||||
*
|
||||
* Why event-driven: the full-client `clientlist`/`channellist` commands time
|
||||
* out whenever ≥2 clients are connected to the server (a library limitation) —
|
||||
* which is exactly the moment a listener returns. So occupancy cannot be
|
||||
* re-queried to confirm the return; we must act on the push event itself.
|
||||
* This is sound because the bot only ever auto-pauses while it is alone on the
|
||||
* server (the sole state in which the occupancy query succeeds and pause
|
||||
* fires). Therefore, while `autoPaused` is true, the only way occupancy can
|
||||
* return is a fresh connection — delivered reliably as `clientEnter`.
|
||||
*
|
||||
* Gating on `autoPaused` (not merely "paused") guarantees we never revive a
|
||||
* track the user paused by hand, and makes the bot's own `clientEnter` at
|
||||
* connect a no-op (autoPaused is cleared to false on connect). This predicate
|
||||
* NEVER pauses — pause stays on the authoritative clientlist path.
|
||||
* Whether a confirmed arrival in the bot's channel should resume playback.
|
||||
* An arrival does not resume a pause requested manually.
|
||||
*/
|
||||
export function shouldResumeOnReturn(
|
||||
autoPaused: boolean,
|
||||
|
||||
@@ -0,0 +1,577 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { BotInstance } from "./instance.js";
|
||||
import { AudioPlayer } from "../audio/player.js";
|
||||
import { PlayQueue } from "../audio/queue.js";
|
||||
import type { Platform, SongUrlRequestOptions } from "../music/provider.js";
|
||||
import { BiliBiliProvider } from "../music/bilibili.js";
|
||||
import { ManagedVoiceClientRegistry } from "./managed-voice-clients.js";
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>(done => { resolve = done; });
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
async function flush() {
|
||||
await new Promise<void>(resolve => setImmediate(resolve));
|
||||
}
|
||||
|
||||
function makeBot() {
|
||||
const queue = new PlayQueue();
|
||||
queue.add({ id: "BV1example", name: "Long", artist: "A", album: "", coverUrl: "", platform: "bilibili", duration: 10_000, url: "old" });
|
||||
queue.playAt(0);
|
||||
const player = new EventEmitter() as any;
|
||||
player.state = "idle";
|
||||
player.sessionId = 1;
|
||||
player.elapsed = 1000;
|
||||
player.getState = AudioPlayer.prototype.getState;
|
||||
player.getPlaybackSessionId = AudioPlayer.prototype.getPlaybackSessionId;
|
||||
player.getElapsed = () => player.elapsed;
|
||||
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" })) };
|
||||
const tsClient = new EventEmitter() as any;
|
||||
tsClient.getClientsInChannel = vi.fn(async () => [{ id: 1 }, { id: 2 }]);
|
||||
tsClient.getClientId = () => 1;
|
||||
tsClient.getChannelId = () => 3n;
|
||||
tsClient.sendVoiceData = vi.fn();
|
||||
tsClient.connect = vi.fn(async () => { tsClient.emit("connected"); });
|
||||
tsClient.disconnect = vi.fn(() => { tsClient.emit("disconnected"); });
|
||||
tsClient.getResolvedVoiceEndpoint = () => null;
|
||||
const spotifyController = new EventEmitter() as any;
|
||||
spotifyController.stop = vi.fn();
|
||||
const bot = Object.assign(Object.create(BotInstance.prototype), {
|
||||
id: "bot", name: "Bot", queue, player, tsClient, provider, spotifyController,
|
||||
connected: true, disconnectEmitted: false, effectiveDuration: 10_000,
|
||||
streamRecovery: null, lifecycleGeneration: 0, occupancyRequest: 0,
|
||||
config: { autoPauseOnEmpty: true, idleTimeoutMinutes: 1 }, autoPaused: false,
|
||||
idleTimer: null, snapshotTimer: null, currentSourceIsSpotify: false,
|
||||
localProvider: {}, voiceDucking: { reset: vi.fn(), removeSpeaker: vi.fn() },
|
||||
managedVoiceClients: new ManagedVoiceClientRegistry(),
|
||||
configuredVoiceServerScope: { host: "localhost", voicePort: 9987 },
|
||||
profileManager: { onConnect: vi.fn(), onChannelMoved: vi.fn(async () => {}) },
|
||||
unregisterManagedVoiceClient: vi.fn(), registerManagedVoiceClient: vi.fn(),
|
||||
restoreQueueFromSnapshot: vi.fn(async () => {}), _startJellyfinReportPoller: vi.fn(),
|
||||
logger: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() },
|
||||
emit: vi.fn(), getProviderFor: () => provider,
|
||||
playNext: vi.fn(async () => { const next = queue.next(); if (!next) queue.clear(); return !!next; }),
|
||||
}) as any;
|
||||
bot.setupPlayerEvents();
|
||||
bot.setupTsEvents();
|
||||
return bot;
|
||||
}
|
||||
|
||||
function cancel(bot: any, action: string) {
|
||||
if (action === "disconnect") bot.disconnect();
|
||||
else if (action === "stop") { bot.queue.clear(); bot.player.stop(); }
|
||||
else if (action === "skip") { if (!bot.queue.next()) bot.queue.clear(); bot.player.stop(); }
|
||||
else if (action === "replace") {
|
||||
bot.queue.clear();
|
||||
bot.queue.add({ id: "other", name: "Other", artist: "A", album: "", coverUrl: "", platform: "bilibili", duration: 10_000 });
|
||||
bot.queue.playAt(0);
|
||||
bot.player.play("replacement", 0);
|
||||
} else { bot.player.sessionId++; bot.player.state = "idle"; }
|
||||
}
|
||||
|
||||
function makeMusicBot(platform: Platform = "netease") {
|
||||
const bot = makeBot();
|
||||
bot.queue.clear();
|
||||
bot.queue.add({
|
||||
id: "music", name: "Music", artist: "A", album: "", coverUrl: "",
|
||||
platform, duration: 240, url: "https://cdn.test/old.wav",
|
||||
});
|
||||
bot.queue.playAt(0);
|
||||
bot.player.elapsed = 60.28;
|
||||
bot.effectiveDuration = 240;
|
||||
bot.provider.getSongUrl.mockResolvedValue({ url: "https://cdn.test/new.wav" });
|
||||
return bot;
|
||||
}
|
||||
|
||||
beforeEach(() => vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }));
|
||||
afterEach(() => { vi.clearAllTimers(); vi.useRealTimers(); });
|
||||
|
||||
describe("finite music CDN recovery", () => {
|
||||
it.each(["netease", "qq", "kugou"] as const)("resumes %s at the real playback position", async platform => {
|
||||
const bot = makeMusicBot(platform);
|
||||
bot.player.emit("trackEnd");
|
||||
await flush();
|
||||
expect(bot.player.play).toHaveBeenCalledWith("https://cdn.test/new.wav", 60.28, 240);
|
||||
expect(bot.playNext).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["netease", "higher"],
|
||||
["qq", "320"],
|
||||
] as const)("renews %s with its successful %s quality only for that song", async (platform, fallback) => {
|
||||
const bot = makeMusicBot(platform);
|
||||
const song = bot.queue.current();
|
||||
bot.voteSkipUsers = new Set();
|
||||
bot.database = { addPlayHistory: vi.fn() };
|
||||
bot.provider.getFallbackQualities = () => [fallback];
|
||||
bot.provider.getSongUrl.mockImplementation(async (id: string, quality?: string, options?: SongUrlRequestOptions) => {
|
||||
if (id === song.id && quality !== fallback) return null;
|
||||
return { url: options?.refresh ? "https://cdn.test/renewed.wav" : "https://cdn.test/initial.wav" };
|
||||
});
|
||||
|
||||
const initial = bot.resolveAndPlay(song);
|
||||
await vi.advanceTimersByTimeAsync(120);
|
||||
await expect(initial).resolves.toBe(true);
|
||||
|
||||
bot.player.state = "idle";
|
||||
bot.player.elapsed = 60.28;
|
||||
bot.player.emit("trackEnd");
|
||||
await flush();
|
||||
expect(bot.provider.getSongUrl).toHaveBeenLastCalledWith(song.id, fallback, { refresh: true });
|
||||
expect(bot.player.play).toHaveBeenLastCalledWith("https://cdn.test/renewed.wav", 60.28, 240);
|
||||
expect(bot.provider.getSongUrl).toHaveBeenCalledTimes(3);
|
||||
|
||||
bot.player.state = "idle";
|
||||
bot.player.emit("trackEnd");
|
||||
await flush();
|
||||
expect(bot.provider.getSongUrl).toHaveBeenLastCalledWith(song.id, fallback, { refresh: true });
|
||||
expect(bot.provider.getSongUrl).toHaveBeenCalledTimes(4);
|
||||
|
||||
// A different queue entry may carry a cached URL, but it has no prior
|
||||
// quality evidence even when the URL happens to match.
|
||||
const next = { ...song, id: "another" };
|
||||
bot.queue.add(next);
|
||||
bot.queue.playAt(1);
|
||||
bot.player.state = "idle";
|
||||
bot.player.emit("trackEnd");
|
||||
await flush();
|
||||
expect(bot.provider.getSongUrl).toHaveBeenLastCalledWith(next.id, undefined, { refresh: true });
|
||||
});
|
||||
|
||||
it.each(["preview", "zero progress", "infinite duration", "local URL"])("does not recover %s streams", async condition => {
|
||||
const bot = makeMusicBot();
|
||||
if (condition === "preview") {
|
||||
const song = bot.queue.current();
|
||||
bot.currentStream = { song, url: song.url, isTrial: true };
|
||||
}
|
||||
if (condition === "zero progress") bot.player.elapsed = 0;
|
||||
if (condition === "infinite duration") bot.effectiveDuration = Infinity;
|
||||
if (condition === "local URL") bot.queue.current().url = "file:///example.wav";
|
||||
bot.player.emit("trackEnd");
|
||||
await flush();
|
||||
expect(bot.provider.getSongUrl).not.toHaveBeenCalled();
|
||||
expect(bot.playNext).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("does not resume a full track into a preview URL", async () => {
|
||||
const bot = makeMusicBot("qq");
|
||||
bot.provider.getSongUrl.mockResolvedValue({ url: "https://cdn.test/preview.wav", trialDuration: 30 });
|
||||
bot.player.emit("trackEnd");
|
||||
await flush();
|
||||
expect(bot.provider.getSongUrl).toHaveBeenCalledTimes(1);
|
||||
expect(bot.player.play).not.toHaveBeenCalled();
|
||||
expect(bot.playNext).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("advances after exhausting the resume budget at the same position", async () => {
|
||||
const bot = makeMusicBot("qq");
|
||||
for (let i = 0; i < 4; i++) {
|
||||
bot.player.state = "idle";
|
||||
bot.player.emit("trackEnd");
|
||||
await flush();
|
||||
}
|
||||
expect(bot.player.play).toHaveBeenCalledTimes(3);
|
||||
expect(bot.playNext).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it.each(["stop", "disconnect"])("does not use a fresh URL after %s", async action => {
|
||||
const bot = makeMusicBot("kugou");
|
||||
const lookup = deferred<{ url: string }>();
|
||||
bot.provider.getSongUrl.mockReturnValueOnce(lookup.promise);
|
||||
bot.player.emit("trackEnd");
|
||||
await flush();
|
||||
expect(bot.provider.getSongUrl).toHaveBeenCalledTimes(1);
|
||||
cancel(bot, action);
|
||||
lookup.resolve({ url: "https://cdn.test/stale.wav" });
|
||||
await flush();
|
||||
expect(bot.player.play).not.toHaveBeenCalled();
|
||||
expect(bot.playNext).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Bilibili recovery retries transient URL failures", () => {
|
||||
it("rotates to untried CDN hosts after a long stream ends repeatedly at the same point", async () => {
|
||||
const bot = makeBot();
|
||||
const song = bot.queue.current();
|
||||
song.url = "https://upos-primary.bilivideo.com/audio.m4s?deadline=1";
|
||||
bot.player.elapsed = 2220;
|
||||
bot.effectiveDuration = 4020;
|
||||
song.duration = 4020;
|
||||
const primary = "https://upos-primary.bilivideo.com/audio.m4s?deadline=2";
|
||||
const backup = "https://upos-backup.bilivideo.com/audio.m4s?deadline=2";
|
||||
const edge = "https://fixture.szbdyd.com/audio.m4s?deadline=2";
|
||||
const provider = new BiliBiliProvider() as any;
|
||||
provider.cidCache.set(song.id, 42);
|
||||
provider.api = {
|
||||
get: vi.fn(async () => ({
|
||||
data: { data: { dash: { audio: [{ bandwidth: 192000, baseUrl: primary, backupUrl: [edge, backup] }] } } },
|
||||
})),
|
||||
};
|
||||
bot.getProviderFor = () => provider;
|
||||
|
||||
bot.player.emit("trackEnd");
|
||||
await flush();
|
||||
expect(bot.player.play).toHaveBeenLastCalledWith(backup, 2220, 4020);
|
||||
|
||||
bot.player.state = "idle";
|
||||
bot.player.emit("trackEnd");
|
||||
await flush();
|
||||
expect(bot.player.play).toHaveBeenLastCalledWith(edge, 2220, 4020);
|
||||
|
||||
// Once playback advances, a previously failed host can be used again.
|
||||
bot.player.elapsed += 31;
|
||||
bot.player.state = "idle";
|
||||
bot.player.emit("trackEnd");
|
||||
await flush();
|
||||
expect(bot.player.play).toHaveBeenLastCalledWith(primary, 2251, 4020);
|
||||
expect(bot.queue.current()).toBe(song);
|
||||
expect(bot.playNext).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps the same queue and seek through a null lookup, then resumes after one second", async () => {
|
||||
const bot = makeBot();
|
||||
const song = bot.queue.current();
|
||||
bot.provider.getSongUrl.mockResolvedValueOnce(null).mockResolvedValue({ url: "fresh" });
|
||||
bot.player.emit("trackEnd");
|
||||
await flush();
|
||||
expect(bot.queue.current()).toBe(song);
|
||||
expect(bot.playNext).not.toHaveBeenCalled();
|
||||
await vi.advanceTimersByTimeAsync(999);
|
||||
expect(bot.player.play).not.toHaveBeenCalled();
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(bot.player.play).toHaveBeenCalledWith("fresh", 1000, 10_000);
|
||||
expect(bot.queue.current()).toBe(song);
|
||||
expect(bot.provider.getSongUrl.mock.calls.map((args: unknown[]) => args[0])).toEqual(["BV1example", "BV1example"]);
|
||||
expect(bot.streamRecovery.attempts).toBe(1);
|
||||
});
|
||||
|
||||
it("retries a throw and null at one and two seconds without logging the sensitive exception", async () => {
|
||||
const bot = makeBot();
|
||||
const secret = "SYNTHETIC_SIGNED_URL_AND_COOKIE";
|
||||
bot.provider.getSongUrl.mockRejectedValueOnce(new Error(`https://cdn.invalid/?token=${secret}`))
|
||||
.mockResolvedValueOnce(null).mockResolvedValue({ url: "fresh" });
|
||||
bot.player.emit("trackEnd");
|
||||
await flush();
|
||||
expect(bot.playNext).not.toHaveBeenCalled();
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(bot.player.play).not.toHaveBeenCalled();
|
||||
await vi.advanceTimersByTimeAsync(1999);
|
||||
expect(bot.provider.getSongUrl).toHaveBeenCalledTimes(2);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(bot.player.play).toHaveBeenCalledWith("fresh", 1000, 10_000);
|
||||
const logs = JSON.stringify(bot.logger.warn.mock.calls, (_key, value) => value instanceof Error ? { message: value.message, stack: value.stack } : value);
|
||||
expect(logs).not.toContain(secret);
|
||||
expect(bot.logger.warn.mock.calls.map((args: any[]) => args[0])).toContainEqual(expect.objectContaining({
|
||||
platform: "bilibili", sessionId: 1, lookupAttempt: 1, reason: "lookup-error",
|
||||
}));
|
||||
expect(bot.playNext).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["null", "throw"])("advances only after three exhausted %s lookups", async failure => {
|
||||
const bot = makeBot();
|
||||
if (failure === "null") bot.provider.getSongUrl.mockResolvedValue(null);
|
||||
else bot.provider.getSongUrl.mockRejectedValue(new Error("temporary"));
|
||||
bot.player.emit("trackEnd");
|
||||
await flush();
|
||||
expect(bot.playNext).not.toHaveBeenCalled();
|
||||
await vi.advanceTimersByTimeAsync(2999);
|
||||
expect(bot.playNext).not.toHaveBeenCalled();
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(bot.provider.getSongUrl).toHaveBeenCalledTimes(3);
|
||||
expect(bot.player.play).not.toHaveBeenCalled();
|
||||
expect(bot.playNext).toHaveBeenCalledTimes(1);
|
||||
expect(bot.queue.current()).toBeNull();
|
||||
});
|
||||
|
||||
it.each(["skip", "stop", "replace", "restart", "disconnect"])("does not retry or advance after %s during backoff", async action => {
|
||||
const bot = makeBot();
|
||||
bot.provider.getSongUrl.mockResolvedValueOnce(null).mockResolvedValue({ url: "fresh" });
|
||||
bot.player.emit("trackEnd");
|
||||
await flush();
|
||||
cancel(bot, action);
|
||||
bot.player.play.mockClear();
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(bot.provider.getSongUrl).toHaveBeenCalledTimes(1);
|
||||
expect(bot.player.play).not.toHaveBeenCalled();
|
||||
expect(bot.playNext).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["skip", "stop", "replace", "restart", "disconnect"])("does not write a late retry result after %s", async action => {
|
||||
const bot = makeBot();
|
||||
const retry = deferred<{ url: string }>();
|
||||
bot.provider.getSongUrl.mockResolvedValueOnce(null).mockReturnValueOnce(retry.promise);
|
||||
bot.player.emit("trackEnd");
|
||||
await flush();
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(bot.provider.getSongUrl).toHaveBeenCalledTimes(2);
|
||||
cancel(bot, action);
|
||||
bot.player.play.mockClear();
|
||||
retry.resolve({ url: "stale" });
|
||||
await flush();
|
||||
expect(bot.player.play).not.toHaveBeenCalled();
|
||||
expect(bot.playNext).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("cancels a backoff when a new connection lifecycle begins", async () => {
|
||||
const bot = makeBot();
|
||||
bot.provider.getSongUrl.mockResolvedValueOnce(null).mockResolvedValue({ url: "stale" });
|
||||
bot.player.emit("trackEnd");
|
||||
await flush();
|
||||
await bot.connect();
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(bot.provider.getSongUrl).toHaveBeenCalledTimes(1);
|
||||
expect(bot.player.play).not.toHaveBeenCalled();
|
||||
expect(bot.playNext).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows pause intent in the snapshot during backoff and pauses the recovered stream", async () => {
|
||||
const bot = makeBot();
|
||||
bot.provider.getSongUrl.mockResolvedValueOnce(null).mockResolvedValue({ url: "fresh" });
|
||||
bot.player.emit("trackEnd");
|
||||
await flush();
|
||||
bot.cmdPause();
|
||||
expect(bot.getStatus().paused).toBe(true);
|
||||
expect(bot.player.getState()).toBe("idle");
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(bot.player.getState()).toBe("paused");
|
||||
expect(bot.playNext).not.toHaveBeenCalled();
|
||||
bot.cmdResume();
|
||||
expect(bot.getStatus().paused).toBe(false);
|
||||
expect(bot.player.getState()).toBe("playing");
|
||||
expect(bot.player.play).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("retains a paused exhausted recovery until explicit resume retries", async () => {
|
||||
const bot = makeBot();
|
||||
bot.provider.getSongUrl.mockResolvedValue(null);
|
||||
bot.player.emit("trackEnd");
|
||||
bot.cmdPause();
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(bot.playNext).not.toHaveBeenCalled();
|
||||
expect(bot.getStatus().paused).toBe(true);
|
||||
bot.provider.getSongUrl.mockResolvedValue({ url: "fresh" });
|
||||
bot.cmdResume();
|
||||
await flush();
|
||||
expect(bot.player.getState()).toBe("playing");
|
||||
expect(bot.player.play).toHaveBeenCalledWith("fresh", 1000, 10_000);
|
||||
expect(bot.playNext).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("coalesces duplicate ends throughout a lookup and its backoff", async () => {
|
||||
const bot = makeBot();
|
||||
const lookup = deferred<{ url: string } | null>();
|
||||
bot.provider.getSongUrl.mockReturnValueOnce(lookup.promise).mockResolvedValue({ url: "fresh" });
|
||||
bot.player.emit("trackEnd");
|
||||
bot.player.emit("trackEnd");
|
||||
lookup.resolve(null);
|
||||
await flush();
|
||||
bot.player.emit("trackEnd");
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(bot.provider.getSongUrl).toHaveBeenCalledTimes(2);
|
||||
expect(bot.player.play).toHaveBeenCalledTimes(1);
|
||||
expect(bot.streamRecovery.attempts).toBe(1);
|
||||
expect(bot.playNext).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("an exhausted end cannot advance over an explicit paused-recovery retry already started", async () => {
|
||||
const bot = makeBot();
|
||||
const song = bot.queue.current();
|
||||
const retry = deferred<{ url: string }>();
|
||||
bot.provider.getSongUrl.mockResolvedValueOnce(null).mockResolvedValueOnce(null)
|
||||
.mockResolvedValueOnce(null).mockReturnValueOnce(retry.promise);
|
||||
const recover = bot.resumeInterruptedStream.bind(bot);
|
||||
let first = true;
|
||||
bot.resumeInterruptedStream = () => {
|
||||
const result = recover();
|
||||
if (first) { first = false; result.then(() => bot.cmdResume()); }
|
||||
return result;
|
||||
};
|
||||
bot.player.emit("trackEnd");
|
||||
bot.cmdPause();
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(bot.provider.getSongUrl).toHaveBeenCalledTimes(4);
|
||||
expect(bot.queue.current()).toBe(song);
|
||||
expect(bot.playNext).not.toHaveBeenCalled();
|
||||
retry.resolve({ url: "fresh" });
|
||||
await flush();
|
||||
expect(bot.player.getState()).toBe("playing");
|
||||
});
|
||||
|
||||
it("lookup retries do not consume the three actual decoder resume attempts", async () => {
|
||||
const bot = makeBot();
|
||||
for (let attempt = 0; attempt < 3; attempt++) {
|
||||
bot.provider.getSongUrl.mockResolvedValueOnce(null).mockResolvedValueOnce({ url: `fresh-${attempt}` });
|
||||
bot.player.state = "idle";
|
||||
bot.player.emit("trackEnd");
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(bot.queue.current()?.id).toBe("BV1example");
|
||||
}
|
||||
bot.player.state = "idle";
|
||||
bot.player.emit("trackEnd");
|
||||
await flush();
|
||||
expect(bot.player.play).toHaveBeenCalledTimes(3);
|
||||
expect(bot.provider.getSongUrl).toHaveBeenCalledTimes(6);
|
||||
expect(bot.playNext).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("occupancy responses belong to the current request and connection", () => {
|
||||
it("ignores an older alone response after a newer occupied response", async () => {
|
||||
const bot = makeBot();
|
||||
bot.player.state = "playing";
|
||||
const older = deferred<any[]>(), newer = deferred<any[]>();
|
||||
bot.tsClient.getClientsInChannel.mockReturnValueOnce(older.promise).mockReturnValueOnce(newer.promise);
|
||||
const first = bot.refreshOccupancy(), second = bot.refreshOccupancy();
|
||||
newer.resolve([{ id: 1 }, { id: 2 }]);
|
||||
await second;
|
||||
older.resolve([{ id: 1 }]);
|
||||
await first;
|
||||
expect(bot.player.getState()).toBe("playing");
|
||||
expect(bot.autoPaused).toBe(false);
|
||||
expect(bot.idleTimer).toBeNull();
|
||||
});
|
||||
|
||||
it.each(["clientEnter", "clientLeave", "clientMoved"])("a newer %s event invalidates a pending response even if its new query fails", async event => {
|
||||
const bot = makeBot();
|
||||
bot.player.state = "playing";
|
||||
const older = deferred<any[]>();
|
||||
bot.tsClient.getClientsInChannel.mockReturnValueOnce(older.promise).mockResolvedValueOnce([]);
|
||||
const first = bot.refreshOccupancy();
|
||||
bot.tsClient.emit(event, { id: 2, channelID: 3n, targetChannelID: 3n });
|
||||
await flush();
|
||||
older.resolve([{ id: 1 }]);
|
||||
await first;
|
||||
expect(bot.player.getState()).toBe("playing");
|
||||
expect(bot.autoPaused).toBe(false);
|
||||
expect(bot.idleTimer).toBeNull();
|
||||
});
|
||||
|
||||
it("does not resume for a client entering another channel", async () => {
|
||||
const bot = makeBot();
|
||||
bot.player.state = "paused";
|
||||
bot.autoPaused = true;
|
||||
bot.tsClient.getClientsInChannel.mockResolvedValue([]);
|
||||
bot.tsClient.emit("clientEnter", { id: 2, channelID: 4n });
|
||||
await flush();
|
||||
expect(bot.player.getState()).toBe("paused");
|
||||
expect(bot.autoPaused).toBe(true);
|
||||
});
|
||||
|
||||
it("resumes when a listener moves into the channel and the occupancy query fails", async () => {
|
||||
const bot = makeBot();
|
||||
bot.player.state = "paused";
|
||||
bot.autoPaused = true;
|
||||
bot.tsClient.getClientsInChannel.mockResolvedValue([]);
|
||||
bot.tsClient.emit("clientMoved", { id: 2, targetChannelID: 3n });
|
||||
await flush();
|
||||
expect(bot.player.getState()).toBe("playing");
|
||||
expect(bot.autoPaused).toBe(false);
|
||||
});
|
||||
|
||||
it("a listener's return cannot be undone by an earlier alone response", async () => {
|
||||
const bot = makeBot();
|
||||
bot.player.state = "paused";
|
||||
bot.autoPaused = true;
|
||||
const older = deferred<any[]>(), newer = deferred<any[]>();
|
||||
bot.tsClient.getClientsInChannel.mockReturnValueOnce(older.promise).mockReturnValueOnce(newer.promise);
|
||||
const first = bot.refreshOccupancy();
|
||||
bot.tsClient.emit("clientEnter", { id: 2, channelID: 3n });
|
||||
expect(bot.player.getState()).toBe("playing");
|
||||
older.resolve([{ id: 1 }]);
|
||||
await first;
|
||||
expect(bot.player.getState()).toBe("playing");
|
||||
expect(bot.autoPaused).toBe(false);
|
||||
newer.resolve([]);
|
||||
await flush();
|
||||
});
|
||||
|
||||
it.each([false, true])("ignores a response from before disconnect (reconnected=%s)", async reconnect => {
|
||||
const bot = makeBot();
|
||||
const older = deferred<any[]>();
|
||||
bot.tsClient.getClientsInChannel.mockReturnValueOnce(older.promise);
|
||||
const first = bot.refreshOccupancy();
|
||||
bot.disconnect();
|
||||
if (reconnect) { await bot.connect(); bot.player.state = "playing"; }
|
||||
older.resolve([{ id: 1 }]);
|
||||
await first;
|
||||
expect(bot.idleTimer).toBeNull();
|
||||
expect(bot.autoPaused).toBe(false);
|
||||
expect(bot.player.getState()).toBe(reconnect ? "playing" : "idle");
|
||||
});
|
||||
|
||||
it("does not let an old lifecycle's poll timer query after reconnect", async () => {
|
||||
const bot = makeBot();
|
||||
bot._startIdlePoller();
|
||||
bot.disconnect();
|
||||
await bot.connect();
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
expect(bot.tsClient.getClientsInChannel).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("does not apply or reschedule an old pending poll after reconnect", async () => {
|
||||
const bot = makeBot();
|
||||
const oldPoll = deferred<any[]>();
|
||||
bot.tsClient.getClientsInChannel.mockReturnValueOnce(oldPoll.promise);
|
||||
bot._startIdlePoller();
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
bot.disconnect();
|
||||
await bot.connect();
|
||||
bot.player.state = "playing";
|
||||
oldPoll.resolve([{ id: 1 }]);
|
||||
await flush();
|
||||
expect(bot.player.getState()).toBe("playing");
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
expect(bot.tsClient.getClientsInChannel).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("does not disconnect a new connection when an old idle deadline expires", async () => {
|
||||
const bot = makeBot();
|
||||
bot.player.state = "playing";
|
||||
bot.tsClient.getClientsInChannel.mockResolvedValueOnce([{ id: 1 }]).mockResolvedValue([]);
|
||||
await bot.refreshOccupancy();
|
||||
bot.tsClient.emit("disconnected");
|
||||
await bot.connect();
|
||||
bot.player.state = "playing";
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
expect(bot.connected).toBe(true);
|
||||
expect(bot.tsClient.disconnect).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("cancels an old idle deadline before awaiting a new handshake", async () => {
|
||||
const bot = makeBot();
|
||||
const handshake = deferred<void>();
|
||||
bot.tsClient.getClientsInChannel.mockResolvedValue([{ id: 1 }]);
|
||||
await bot.refreshOccupancy();
|
||||
bot.tsClient.connect.mockReturnValue(handshake.promise);
|
||||
const connecting = bot.connect();
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
handshake.resolve(undefined);
|
||||
await expect(connecting).resolves.toBeUndefined();
|
||||
expect(bot.connected).toBe(true);
|
||||
expect(bot.tsClient.disconnect).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("still pauses for a fresh authoritative alone response and ignores unknown occupancy", async () => {
|
||||
const bot = makeBot();
|
||||
bot.player.state = "playing";
|
||||
bot.tsClient.getClientsInChannel.mockResolvedValueOnce([]).mockResolvedValueOnce([{ id: 1 }]);
|
||||
await bot.refreshOccupancy();
|
||||
expect(bot.player.getState()).toBe("playing");
|
||||
await bot.refreshOccupancy();
|
||||
expect(bot.player.getState()).toBe("paused");
|
||||
expect(bot.autoPaused).toBe(true);
|
||||
expect(bot.idleTimer).not.toBeNull();
|
||||
});
|
||||
});
|
||||
+819
-4
@@ -1,14 +1,15 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { BotInstance, COMMAND_DENIED_MESSAGE, spotifyPortsForBotId } from "./instance.js";
|
||||
import type { BotInstanceOptions } from "./instance.js";
|
||||
import { PlayQueue, PlayMode } from "../audio/queue.js";
|
||||
import { PlayQueue, PlayMode, type QueuedSong } from "../audio/queue.js";
|
||||
import { AudioPlayer } from "../audio/player.js";
|
||||
import { createDatabase, SHARED_QUEUE_OWNER } from "../data/database.js";
|
||||
import { parseCommand } from "./commands.js";
|
||||
import type { TS3TextMessage } from "../ts-protocol/client.js";
|
||||
import type { SpotifyController } from "../music/spotify/controller.js";
|
||||
import type { SpotifyOAuth } from "../music/spotify/spotify-oauth.js";
|
||||
import type { MusicProvider } from "../music/provider.js";
|
||||
import type { MusicProvider, PlayFailure } from "../music/provider.js";
|
||||
import type { BotDatabase } from "../data/database.js";
|
||||
import type { AvatarStore } from "../data/avatars.js";
|
||||
import type { BotConfig } from "../data/config.js";
|
||||
@@ -133,6 +134,9 @@ describe("BotInstance voice-ducking lifecycle integration", () => {
|
||||
return {
|
||||
disconnectEmitted: false,
|
||||
connected: false,
|
||||
lifecycleGeneration: 0,
|
||||
idleTimer: null,
|
||||
_cancelIdleTimer: (BotInstance.prototype as any)._cancelIdleTimer,
|
||||
tsClient: {
|
||||
connect: vi.fn(() => connectPromise),
|
||||
getResolvedVoiceEndpoint: vi.fn(() => ({ host: "203.0.113.20", port: 12000 })),
|
||||
@@ -392,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;
|
||||
@@ -457,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,
|
||||
@@ -483,6 +502,117 @@ 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();
|
||||
});
|
||||
|
||||
it.each(["netease", "spotify"])("keeps %s playback successful when saving history fails", async platform => {
|
||||
const player = makePlayer();
|
||||
const url = platform === "spotify" ? "spotify:track:abc" : "https://example.com/track";
|
||||
const ctx = makeResolveCtx({ controller: makeController(), player, url });
|
||||
ctx.database.addPlayHistory.mockImplementation(() => { throw new Error("Database temporarily unavailable"); });
|
||||
|
||||
expect(await resolveAndPlay.call(ctx, { ...spotifySong(), platform })).toBe(true);
|
||||
expect(player.getState()).toBe("playing");
|
||||
expect(ctx.emit).toHaveBeenCalledWith("stateChange");
|
||||
expect(ctx.syncProfileToSong).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("advances again when a track ends during a slow profile upload", async () => {
|
||||
const player = Object.assign(new EventEmitter(), makePlayer(), {
|
||||
getPlaybackSessionId: vi.fn(() => 1),
|
||||
});
|
||||
const ctx = makeResolveCtx({ controller: makeController(), player, url: "https://example.com/track" });
|
||||
const queue = new PlayQueue();
|
||||
for (const id of ["previous", "short", "following"]) {
|
||||
queue.add({ ...spotifySong(), id, platform: "netease" });
|
||||
}
|
||||
queue.play();
|
||||
ctx.queue = queue;
|
||||
ctx.resumeInterruptedStream = vi.fn(async () => false);
|
||||
ctx.resolveAndPlay = resolveAndPlay.bind(ctx);
|
||||
ctx.playNext = playNext.bind(ctx);
|
||||
ctx.sweepLocalAudio = vi.fn();
|
||||
ctx.spotifyController = Object.assign(new EventEmitter(), { on: EventEmitter.prototype.on });
|
||||
const profileStarted = deferred();
|
||||
const finishProfile = deferred();
|
||||
ctx.syncProfileToSong.mockImplementationOnce(() => {
|
||||
profileStarted.resolve();
|
||||
return finishProfile.promise;
|
||||
});
|
||||
setupPlayerEvents.call(ctx);
|
||||
|
||||
const advancing = ctx.playNext();
|
||||
await profileStarted.promise;
|
||||
try {
|
||||
player.stop();
|
||||
player.emit("trackEnd");
|
||||
await new Promise<void>(resolve => setImmediate(resolve));
|
||||
expect(queue.current()?.id).toBe("following");
|
||||
} finally {
|
||||
finishProfile.resolve();
|
||||
await advancing;
|
||||
}
|
||||
});
|
||||
|
||||
it("reports the reason when the next track cannot be started", async () => {
|
||||
const current = { ...spotifySong(), id: "next", platform: "netease" };
|
||||
const ctx = {
|
||||
connected: true,
|
||||
queue: { current: () => current },
|
||||
playNext: async (_maxRetries: number, report?: (failure: { message: string }) => void) => {
|
||||
report?.({ message: "网易云暂时拒绝播放请求(-460),请稍后重试" });
|
||||
return false;
|
||||
},
|
||||
};
|
||||
expect(await BotInstance.prototype.skipToNext.call(ctx as unknown as BotInstance)).toEqual({
|
||||
ok: false,
|
||||
message: expect.stringContaining("-460"),
|
||||
});
|
||||
});
|
||||
|
||||
describe("queue advancement after a provider-wide failure", () => {
|
||||
it.each([
|
||||
["netease", "risk_control"],
|
||||
["kugou", "provider_verification_required"],
|
||||
] as const)("skips queued %s tracks without spending retries for other sources", async (platform, code) => {
|
||||
const queue = new PlayQueue();
|
||||
for (let i = 0; i < 8; i++) queue.add({ ...spotifySong(), id: String(i), platform });
|
||||
const available = { ...spotifySong(), id: "available", platform: "qq" as const };
|
||||
queue.add(available);
|
||||
const ctx = {
|
||||
connected: true,
|
||||
queue,
|
||||
player: makePlayer(),
|
||||
voteSkipUsers: new Set<string>(),
|
||||
resolveAndPlay: vi.fn(async (track: QueuedSong, onFailure: (failure: PlayFailure) => void) => {
|
||||
if (track.platform === "qq") return true;
|
||||
onFailure({ platform, songId: track.id, code, message: "Provider unavailable" });
|
||||
return false;
|
||||
}),
|
||||
profileManager: { onSongChange: vi.fn(async () => {}) },
|
||||
sweepLocalAudio: vi.fn(),
|
||||
emit: vi.fn(),
|
||||
};
|
||||
|
||||
expect(await playNext.call(ctx)).toBe(true);
|
||||
expect(ctx.resolveAndPlay.mock.calls.map(([track]) => track.id)).toEqual(["0", "available"]);
|
||||
expect(queue.current()?.id).toBe("available");
|
||||
});
|
||||
});
|
||||
|
||||
describe("BotInstance.resolveAndPlay — Spotify routing (C4)", () => {
|
||||
it("routes a spotify song to controller.playTrack + player.playPcmStream, not player.play", async () => {
|
||||
const controller = makeController();
|
||||
@@ -1267,6 +1397,7 @@ const playSingleSong = BotInstance.prototype.playSingleSong as (
|
||||
this: unknown,
|
||||
song: unknown,
|
||||
requesterName?: string,
|
||||
onFailure?: (failure: PlayFailure, currentTrackContinues?: boolean) => void,
|
||||
) => Promise<boolean>;
|
||||
const loadSavedQueue = BotInstance.prototype.loadSavedQueue as (
|
||||
this: unknown,
|
||||
@@ -1309,7 +1440,10 @@ describe("BotInstance.playSingleSong / playKeepsQueue (#119)", () => {
|
||||
isSameSong,
|
||||
disableFmMode: vi.fn(),
|
||||
sweepLocalAudio: vi.fn(),
|
||||
resolveAndPlay: vi.fn(async () => true),
|
||||
resolveAndPlay: vi.fn(async (_song, _onFailure, commitQueue?: () => void) => {
|
||||
commitQueue?.();
|
||||
return true;
|
||||
}),
|
||||
} as any;
|
||||
}
|
||||
|
||||
@@ -1343,6 +1477,93 @@ describe("BotInstance.playSingleSong / playKeepsQueue (#119)", () => {
|
||||
expect(ctx.queue.list().map((s: any) => s.id)).toEqual(["b"]);
|
||||
expect(ctx.queue.current()?.id).toBe("b");
|
||||
});
|
||||
|
||||
it.each([
|
||||
[false, "new"], [false, "old"], [true, "new"], [true, "old"],
|
||||
] as const)("retains the current queue and stream after a failed direct start (keep=%s, requested=%s)", async (keep, id) => {
|
||||
const ctx = makeCtx(keep);
|
||||
const current = song119("old");
|
||||
ctx.queue.add(current);
|
||||
ctx.queue.add(song119("following"));
|
||||
ctx.queue.play();
|
||||
ctx.player._play();
|
||||
ctx.player.getPlaybackSessionId = () => 3;
|
||||
ctx.resolveAndPlay.mockImplementation(async (_track: QueuedSong, onFailure?: (failure: PlayFailure) => void) => {
|
||||
onFailure?.({ platform: "netease", songId: id, code: "unknown", message: "No URL" });
|
||||
return false;
|
||||
});
|
||||
const failure = vi.fn();
|
||||
|
||||
expect(await playSingleSong.call(ctx, song119(id), "alice", failure)).toBe(false);
|
||||
expect(ctx.queue.current()).toBe(current);
|
||||
expect(ctx.queue.list().map((song: QueuedSong) => song.id)).toEqual(["old", "following"]);
|
||||
expect(ctx.player.stop).not.toHaveBeenCalled();
|
||||
expect(ctx.disableFmMode).not.toHaveBeenCalled();
|
||||
expect(ctx.sweepLocalAudio).not.toHaveBeenCalled();
|
||||
expect(failure).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ message: "No URL" }), id === "old");
|
||||
});
|
||||
|
||||
function makeRealStartCtx() {
|
||||
const queue = new PlayQueue();
|
||||
queue.add(song119("old"));
|
||||
queue.add(song119("following"));
|
||||
queue.play();
|
||||
const player = Object.assign(new EventEmitter(), makePlayer(), {
|
||||
resetFailures: vi.fn(), getPlaybackSessionId: () => 1,
|
||||
});
|
||||
const ctx = Object.assign(makeResolveCtx({ controller: makeController(), player, url: "" }), {
|
||||
queue, player, withRequester, isSameSong, disableFmMode: vi.fn(),
|
||||
sweepLocalAudio: vi.fn(), spotifyController: new EventEmitter(),
|
||||
resumeInterruptedStream: async () => false,
|
||||
});
|
||||
ctx.playNext = BotInstance.prototype.playNext.bind(ctx);
|
||||
ctx.resolveAndPlay = BotInstance.prototype.resolveAndPlay.bind(ctx);
|
||||
setupPlayerEvents.call(ctx);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
it("looks up a successful direct play once and commits the queue before status publication", async () => {
|
||||
const ctx = makeRealStartCtx();
|
||||
const getSongUrl = vi.fn(async () => ({ url: "https://example.test/new.mp3" }));
|
||||
ctx.getProviderFor.mockReturnValue({ platform: "netease", getSongUrl });
|
||||
ctx.emit.mockImplementation((event: string) => {
|
||||
if (event === "stateChange") expect(ctx.queue.current()?.id).toBe("new");
|
||||
});
|
||||
|
||||
expect(await playSingleSong.call(ctx, song119("new"), "alice")).toBe(true);
|
||||
expect(getSongUrl).toHaveBeenCalledTimes(1);
|
||||
expect(ctx.queue.current()).toMatchObject({ id: "new", requestedBy: "alice", url: "https://example.test/new.mp3" });
|
||||
expect(ctx.emit).toHaveBeenCalledExactlyOnceWith("stateChange");
|
||||
});
|
||||
|
||||
it("lets the current track end normally during an unresolved direct request", async () => {
|
||||
const ctx = makeRealStartCtx();
|
||||
ctx.player.play("https://example.test/old.mp3");
|
||||
ctx.player.play.mockClear();
|
||||
const lookupStarted = deferred();
|
||||
const directLookup = deferred<{ url: string }>();
|
||||
const getSongUrl = vi.fn(async (id: string) => {
|
||||
if (id === "new") {
|
||||
lookupStarted.resolve();
|
||||
return directLookup.promise;
|
||||
}
|
||||
return { url: "https://example.test/following.mp3" };
|
||||
});
|
||||
ctx.getProviderFor.mockReturnValue({ platform: "netease", getSongUrl });
|
||||
const request = playSingleSong.call(ctx, song119("new"));
|
||||
await lookupStarted.promise;
|
||||
expect(ctx.queue.current()?.id).toBe("old");
|
||||
expect(ctx.player.getState()).toBe("playing");
|
||||
ctx.player.stop();
|
||||
ctx.player.emit("trackEnd");
|
||||
await new Promise<void>(resolve => setImmediate(resolve));
|
||||
directLookup.resolve({ url: "https://example.test/stale.mp3" });
|
||||
|
||||
expect(await request).toBe(false);
|
||||
expect(ctx.queue.current()?.id).toBe("following");
|
||||
expect(getSongUrl.mock.calls.map(([id]) => id)).toEqual(["new", "following"]);
|
||||
expect(ctx.player.play).toHaveBeenCalledExactlyOnceWith("https://example.test/following.mp3", 0, 1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("BotInstance.loadSavedQueue (#119)", () => {
|
||||
@@ -1538,3 +1759,597 @@ 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",
|
||||
name: "测试视频 - P1 分P1",
|
||||
artist: "UP主",
|
||||
album: "",
|
||||
duration: 100, // P1 duration
|
||||
coverUrl: "",
|
||||
platform: "bilibili" as const,
|
||||
};
|
||||
const mockBili = {
|
||||
platform: "bilibili" as const,
|
||||
search: vi.fn().mockResolvedValue({
|
||||
songs: [{
|
||||
id: "BV1multiP",
|
||||
name: "测试视频",
|
||||
artist: "UP主",
|
||||
album: "",
|
||||
duration: 300, // total duration in search
|
||||
coverUrl: "",
|
||||
platform: "bilibili",
|
||||
}],
|
||||
albums: [],
|
||||
playlists: [],
|
||||
}),
|
||||
getSongDetail: vi.fn().mockResolvedValue(multiPSongDetail),
|
||||
getSongUrl: vi.fn().mockResolvedValue({ url: "http://audio.test" }),
|
||||
};
|
||||
|
||||
const ctx = {
|
||||
config: { commandPrefix: "!" },
|
||||
lastSearchResults: [] as any[],
|
||||
getProvider: () => mockBili,
|
||||
getProviderFor: () => mockBili,
|
||||
};
|
||||
|
||||
const res = await (BotInstance.prototype as any).resolvePlayQuery.call(ctx, {
|
||||
name: "play",
|
||||
args: "测试视频",
|
||||
rawArgs: ["测试视频"],
|
||||
flags: new Set(),
|
||||
});
|
||||
|
||||
expect(res.song).toBeDefined();
|
||||
expect(res.song.id).toBe("BV1multiP?p=1");
|
||||
expect(res.song.name).toBe("测试视频 - P1 分P1");
|
||||
expect(res.song.duration).toBe(100);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe("cmdPlaylist with a playlist link (#160)", () => {
|
||||
const cmdPlaylist = (BotInstance.prototype as any).cmdPlaylist as (
|
||||
this: unknown, cmd: { name: string; args: string; rawArgs: string[]; flags: Set<string> },
|
||||
) => Promise<string>;
|
||||
|
||||
function makeCtx() {
|
||||
const song = { id: "s1", name: "Song", artist: "A", album: "B", duration: 1, coverUrl: "" };
|
||||
const makeProvider = (platform: string) => ({
|
||||
platform,
|
||||
search: vi.fn().mockResolvedValue({ songs: [], playlists: [] }),
|
||||
getPlaylistSongs: vi.fn().mockResolvedValue([song]),
|
||||
});
|
||||
const providers: Record<string, any> = {
|
||||
netease: makeProvider("netease"),
|
||||
qq: makeProvider("qq"),
|
||||
youtube: makeProvider("youtube"),
|
||||
};
|
||||
const queued: any[] = [];
|
||||
return {
|
||||
providers,
|
||||
queued,
|
||||
getProvider: vi.fn(() => providers.netease),
|
||||
getProviderFor: vi.fn((p: string) => providers[p]),
|
||||
assertProviderEnabled: vi.fn(),
|
||||
extractId: (BotInstance.prototype as any).extractId,
|
||||
looksLikeCollectionId: (BotInstance.prototype as any).looksLikeCollectionId,
|
||||
player: { stop: vi.fn() },
|
||||
queue: { clear: vi.fn(), add: (s: any) => queued.push(s), play: () => queued[0] },
|
||||
disableFmMode: vi.fn(),
|
||||
withRequester: (s: any) => s,
|
||||
resolveAndPlay: vi.fn(async () => true),
|
||||
sweepLocalAudio: vi.fn(),
|
||||
emit: vi.fn(),
|
||||
};
|
||||
}
|
||||
const cmd = (args: string, flags: string[] = []) =>
|
||||
({ name: "playlist", args, rawArgs: args.split(" "), flags: new Set(flags) });
|
||||
|
||||
it("routes a QQ playlist link to QQ even without -q (default is NetEase)", async () => {
|
||||
const ctx = makeCtx();
|
||||
const reply = await cmdPlaylist.call(ctx, cmd("[URL]https://y.qq.com/n/ryqq/playlist/8052190267[/URL]"));
|
||||
expect(ctx.providers.qq.getPlaylistSongs).toHaveBeenCalledWith("8052190267");
|
||||
expect(ctx.providers.netease.getPlaylistSongs).not.toHaveBeenCalled();
|
||||
expect(ctx.queued[0].platform).toBe("qq");
|
||||
expect(reply).toMatch(/^Loaded 1 songs/);
|
||||
});
|
||||
|
||||
it("loads a YouTube playlist link by its list id instead of name-searching the URL", async () => {
|
||||
const ctx = makeCtx();
|
||||
await cmdPlaylist.call(ctx, cmd("https://www.youtube.com/playlist?list=PLabc123"));
|
||||
expect(ctx.providers.youtube.getPlaylistSongs).toHaveBeenCalledWith("PLabc123");
|
||||
expect(ctx.providers.netease.search).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reports a refused first track instead of announcing playback", async () => {
|
||||
const ctx = makeCtx();
|
||||
ctx.resolveAndPlay.mockResolvedValue(false);
|
||||
expect(await cmdPlaylist.call(ctx, cmd("2829883282"))).toBe("Cannot play: Song");
|
||||
});
|
||||
|
||||
it("checks the link's platform is enabled", async () => {
|
||||
const ctx = makeCtx();
|
||||
ctx.assertProviderEnabled.mockImplementation(() => { throw new Error("音源未启用:qq"); });
|
||||
await expect(cmdPlaylist.call(ctx, cmd("https://y.qq.com/n/ryqq/playlist/1"))).rejects.toThrow("音源未启用");
|
||||
});
|
||||
|
||||
it("keeps the old behavior for a bare id", async () => {
|
||||
const ctx = makeCtx();
|
||||
await cmdPlaylist.call(ctx, cmd("2829883282"));
|
||||
expect(ctx.providers.netease.getPlaylistSongs).toHaveBeenCalledWith("2829883282");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resumeInterruptedStream — long B站 streams dying mid-play (#161)", () => {
|
||||
beforeEach(() => vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }));
|
||||
afterEach(() => { vi.clearAllTimers(); vi.useRealTimers(); });
|
||||
const resumeInterruptedStream = (BotInstance.prototype as any).resumeInterruptedStream as (
|
||||
this: unknown,
|
||||
) => Promise<boolean>;
|
||||
|
||||
function makeCtx(opts: { platform?: string; elapsed?: number; duration?: number; url?: string | null } = {}) {
|
||||
const song: any = {
|
||||
id: "BV1abc", name: "Long", artist: "A", album: "", coverUrl: "",
|
||||
platform: opts.platform ?? "bilibili", duration: opts.duration ?? 10_000, url: "old",
|
||||
};
|
||||
let elapsed = opts.elapsed ?? 1000;
|
||||
let state: "idle" | "playing" = "idle";
|
||||
const provider = {
|
||||
getSongUrl: vi.fn(async () => (opts.url === null ? null : { url: opts.url ?? "https://fresh.test/a.m4s" })),
|
||||
};
|
||||
const ctx: any = {
|
||||
song,
|
||||
provider,
|
||||
connected: true,
|
||||
lifecycleGeneration: 0,
|
||||
effectiveDuration: song.duration,
|
||||
streamRecovery: null,
|
||||
queue: { current: vi.fn(() => song) },
|
||||
player: {
|
||||
getElapsed: vi.fn(() => elapsed),
|
||||
getState: vi.fn(() => state),
|
||||
getPlaybackSessionId: vi.fn(() => 1),
|
||||
play: vi.fn(() => { state = "playing"; }),
|
||||
},
|
||||
getProviderFor: vi.fn(() => provider),
|
||||
logger: { warn: vi.fn(), info: vi.fn() },
|
||||
emit: vi.fn(),
|
||||
setElapsed: (v: number) => { elapsed = v; state = "idle"; },
|
||||
};
|
||||
return ctx;
|
||||
}
|
||||
|
||||
it("re-resolves the URL and resumes at the current position when a B站 stream ends early", async () => {
|
||||
const ctx = makeCtx({ elapsed: 1000, duration: 10_000 });
|
||||
expect(await resumeInterruptedStream.call(ctx)).toBe(true);
|
||||
expect(ctx.provider.getSongUrl).toHaveBeenCalledExactlyOnceWith("BV1abc", undefined, { avoidHosts: new Set() });
|
||||
expect(ctx.player.play).toHaveBeenCalledWith("https://fresh.test/a.m4s", 1000, 10_000);
|
||||
expect(ctx.song.url).toBe("https://fresh.test/a.m4s");
|
||||
});
|
||||
|
||||
it("does nothing near the real end of the track (normal EOF)", async () => {
|
||||
const ctx = makeCtx({ elapsed: 9_990, duration: 10_000 });
|
||||
expect(await resumeInterruptedStream.call(ctx)).toBe(false);
|
||||
expect(ctx.provider.getSongUrl).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does nothing for other platforms or an unknown duration", async () => {
|
||||
expect(await resumeInterruptedStream.call(makeCtx({ platform: "netease" }))).toBe(false);
|
||||
const unknown = makeCtx({ duration: 0 });
|
||||
unknown.effectiveDuration = 0;
|
||||
expect(await resumeInterruptedStream.call(unknown)).toBe(false);
|
||||
});
|
||||
|
||||
it("gives up after 3 attempts that make no progress, then lets the queue advance", async () => {
|
||||
const ctx = makeCtx({ elapsed: 1000 });
|
||||
for (let i = 0; i < 3; i++) {
|
||||
ctx.setElapsed(1000);
|
||||
expect(await resumeInterruptedStream.call(ctx)).toBe(true);
|
||||
}
|
||||
ctx.setElapsed(1000);
|
||||
expect(await resumeInterruptedStream.call(ctx)).toBe(false);
|
||||
expect(ctx.player.play).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it("resets the attempt budget once a resume actually plays on for a while", async () => {
|
||||
const ctx = makeCtx({ elapsed: 1000 });
|
||||
for (let i = 0; i < 3; i++) {
|
||||
ctx.setElapsed(1000);
|
||||
await resumeInterruptedStream.call(ctx);
|
||||
}
|
||||
ctx.setElapsed(2000); // the last resume played ~16 more minutes
|
||||
expect(await resumeInterruptedStream.call(ctx)).toBe(true);
|
||||
});
|
||||
|
||||
it("falls through to advancing when no fresh URL can be fetched", async () => {
|
||||
const ctx = makeCtx({ url: null });
|
||||
const recovery = resumeInterruptedStream.call(ctx);
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(await recovery).toBe(false);
|
||||
expect(ctx.provider.getSongUrl).toHaveBeenCalledTimes(3);
|
||||
expect(ctx.player.play).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not clobber a different track the user started while the URL was resolving", async () => {
|
||||
const ctx = makeCtx();
|
||||
ctx.provider.getSongUrl.mockImplementation(async () => {
|
||||
ctx.queue.current.mockReturnValue({ id: "other" }); // user ran !next meanwhile
|
||||
return { url: "https://fresh.test/a.m4s" };
|
||||
});
|
||||
expect(await resumeInterruptedStream.call(ctx)).toBe(true); // handled: don't advance again
|
||||
expect(ctx.player.play).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("BotInstance trackEnd — stale playback sessions", () => {
|
||||
beforeEach(() => vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }));
|
||||
afterEach(() => { vi.clearAllTimers(); vi.useRealTimers(); });
|
||||
function makeEndedCtx(platform = "bilibili", duration = 10_000) {
|
||||
const song = {
|
||||
id: "ended", name: "Ended", artist: "A", album: "", coverUrl: "",
|
||||
platform, duration, url: "old",
|
||||
};
|
||||
let current: any = song;
|
||||
const player = new EventEmitter() as any;
|
||||
player.state = "idle";
|
||||
player.sessionId = 1;
|
||||
player.getState = AudioPlayer.prototype.getState;
|
||||
player.getElapsed = () => 1000;
|
||||
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[] = [];
|
||||
const ctx: any = {
|
||||
song, provider, player, connected: true, effectiveDuration: duration,
|
||||
lifecycleGeneration: 0,
|
||||
streamRecovery: null, queue: { current: () => current },
|
||||
spotifyController: new EventEmitter(), tsClient: { sendVoiceData: vi.fn() },
|
||||
logger: { warn: vi.fn(), debug: vi.fn(), error: vi.fn() }, emit: vi.fn(),
|
||||
getProviderFor: () => provider,
|
||||
playNext: vi.fn(async () => { advances.push(current?.id ?? "empty"); return true; }),
|
||||
replace: () => { current = { ...song, id: "replacement" }; player.sessionId++; player.state = "playing"; },
|
||||
stop: () => { current = null; player.sessionId++; player.state = "idle"; },
|
||||
restartSameSong: () => { player.sessionId++; player.state = "idle"; },
|
||||
pause: () => cmdPause.call(ctx),
|
||||
resume: () => cmdResume.call(ctx),
|
||||
advances,
|
||||
};
|
||||
ctx.resumeInterruptedStream = (BotInstance.prototype as any).resumeInterruptedStream.bind(ctx);
|
||||
setupPlayerEvents.call(ctx);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
async function flushEvents() {
|
||||
await new Promise<void>(resolve => setImmediate(resolve));
|
||||
}
|
||||
|
||||
it.each(["netease", "bilibili"])("an old normal %s EOF never skips a pending replacement", async platform => {
|
||||
const ctx = makeEndedCtx(platform, 1000);
|
||||
const replacement = Promise.resolve().then(() => ctx.replace());
|
||||
ctx.player.emit("trackEnd");
|
||||
await replacement;
|
||||
await flushEvents();
|
||||
expect(ctx.advances).not.toContain("replacement");
|
||||
});
|
||||
|
||||
it("normal EOF still advances the ending track when no replacement arrives", async () => {
|
||||
const ctx = makeEndedCtx("netease", 1000);
|
||||
ctx.player.emit("trackEnd");
|
||||
await flushEvents();
|
||||
expect(ctx.advances).toEqual(["ended"]);
|
||||
});
|
||||
|
||||
it("a failed recovery never advances a replacement", async () => {
|
||||
const ctx = makeEndedCtx();
|
||||
const lookup = deferred<{ url: string }>();
|
||||
ctx.provider.getSongUrl.mockReturnValue(lookup.promise);
|
||||
ctx.player.emit("trackEnd");
|
||||
ctx.replace();
|
||||
lookup.reject(new Error("temporary lookup failure"));
|
||||
await flushEvents();
|
||||
expect(ctx.advances).toEqual([]);
|
||||
});
|
||||
|
||||
it.each(["stop", "restartSameSong"])("recovery does not overwrite playback after %s", async action => {
|
||||
const ctx = makeEndedCtx();
|
||||
const lookup = deferred<{ url: string }>();
|
||||
ctx.provider.getSongUrl.mockReturnValue(lookup.promise);
|
||||
ctx.player.emit("trackEnd");
|
||||
ctx[action]();
|
||||
lookup.resolve({ url: "fresh" });
|
||||
await flushEvents();
|
||||
expect(ctx.player.play).not.toHaveBeenCalled();
|
||||
expect(ctx.advances).toEqual([]);
|
||||
});
|
||||
|
||||
it("pause during an idle URL lookup is honored by recovered playback, then resume continues", async () => {
|
||||
const ctx = makeEndedCtx();
|
||||
const lookup = deferred<{ url: string }>();
|
||||
ctx.provider.getSongUrl.mockReturnValue(lookup.promise);
|
||||
ctx.player.emit("trackEnd");
|
||||
ctx.pause();
|
||||
expect(ctx.player.getState()).toBe("idle"); // actual AudioPlayer.pause cannot pause idle
|
||||
lookup.resolve({ url: "fresh" });
|
||||
await flushEvents();
|
||||
expect(ctx.player.play).toHaveBeenCalledWith("fresh", 1000, 10_000);
|
||||
expect(ctx.player.getState()).toBe("paused");
|
||||
expect(ctx.advances).toEqual([]);
|
||||
ctx.resume();
|
||||
expect(ctx.player.getState()).toBe("playing");
|
||||
expect(ctx.player.play).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("resume before a paused recovery lookup completes lets the fresh stream play", async () => {
|
||||
const ctx = makeEndedCtx();
|
||||
const lookup = deferred<{ url: string }>();
|
||||
ctx.provider.getSongUrl.mockReturnValue(lookup.promise);
|
||||
ctx.player.emit("trackEnd");
|
||||
ctx.pause();
|
||||
ctx.resume();
|
||||
lookup.resolve({ url: "fresh" });
|
||||
await flushEvents();
|
||||
expect(ctx.player.getState()).toBe("playing");
|
||||
expect(ctx.advances).toEqual([]);
|
||||
expect(ctx.provider.getSongUrl).toHaveBeenCalledTimes(1);
|
||||
expect(ctx.streamRecovery?.attempts).toBe(1);
|
||||
});
|
||||
|
||||
it("resume during a pending lookup cannot start a failing duplicate and skip the song", async () => {
|
||||
const ctx = makeEndedCtx();
|
||||
const lookup = deferred<{ url: string }>();
|
||||
ctx.provider.getSongUrl.mockReturnValueOnce(lookup.promise).mockResolvedValue(null);
|
||||
ctx.player.emit("trackEnd");
|
||||
ctx.pause();
|
||||
ctx.resume();
|
||||
await flushEvents();
|
||||
expect(ctx.advances).toEqual([]);
|
||||
expect(ctx.provider.getSongUrl).toHaveBeenCalledTimes(1);
|
||||
lookup.resolve({ url: "fresh" });
|
||||
await flushEvents();
|
||||
expect(ctx.player.getState()).toBe("playing");
|
||||
expect(ctx.streamRecovery?.attempts).toBe(1);
|
||||
});
|
||||
|
||||
it("pause while a recovery lookup fails prevents automatic queue advancement", async () => {
|
||||
const ctx = makeEndedCtx();
|
||||
const lookup = deferred<{ url: string }>();
|
||||
ctx.provider.getSongUrl.mockReturnValue(lookup.promise);
|
||||
ctx.player.emit("trackEnd");
|
||||
ctx.pause();
|
||||
lookup.reject(new Error("temporary lookup failure"));
|
||||
await flushEvents();
|
||||
expect(ctx.advances).toEqual([]);
|
||||
});
|
||||
|
||||
it("resume while a paused failed lookup waits for retry continues after its backoff", async () => {
|
||||
const ctx = makeEndedCtx();
|
||||
const lookup = deferred<{ url: string }>();
|
||||
ctx.provider.getSongUrl.mockReturnValue(lookup.promise);
|
||||
ctx.player.emit("trackEnd");
|
||||
ctx.pause();
|
||||
lookup.reject(new Error("temporary lookup failure"));
|
||||
await flushEvents();
|
||||
ctx.provider.getSongUrl.mockResolvedValue({ url: "recovered" });
|
||||
ctx.resume();
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(ctx.player.getState()).toBe("playing");
|
||||
expect(ctx.player.play).toHaveBeenCalledWith("recovered", 1000, 10_000);
|
||||
expect(ctx.advances).toEqual([]);
|
||||
});
|
||||
|
||||
it("a same-song restart cannot inherit pause intent from an older rejected lookup", async () => {
|
||||
const ctx = makeEndedCtx();
|
||||
const lookup = deferred<{ url: string }>();
|
||||
ctx.provider.getSongUrl.mockReturnValue(lookup.promise);
|
||||
ctx.player.emit("trackEnd");
|
||||
ctx.pause();
|
||||
ctx.restartSameSong();
|
||||
lookup.reject(new Error("temporary lookup failure"));
|
||||
await flushEvents();
|
||||
ctx.provider.getSongUrl.mockResolvedValue({ url: "new-recovery" });
|
||||
ctx.player.emit("trackEnd");
|
||||
await flushEvents();
|
||||
expect(ctx.player.getState()).toBe("playing");
|
||||
expect(ctx.advances).toEqual([]);
|
||||
});
|
||||
|
||||
it("a failed recovery cannot advance a newer session of the same queue song", async () => {
|
||||
const ctx = makeEndedCtx();
|
||||
const lookup = deferred<{ url: string }>();
|
||||
ctx.provider.getSongUrl.mockReturnValue(lookup.promise);
|
||||
ctx.player.emit("trackEnd");
|
||||
ctx.restartSameSong();
|
||||
lookup.reject(new Error("temporary lookup failure"));
|
||||
await flushEvents();
|
||||
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 () => {}),
|
||||
_resumeIfReturning: vi.fn(),
|
||||
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);
|
||||
});
|
||||
});
|
||||
+605
-192
File diff suppressed because it is too large.
Load diff
@@ -1,5 +1,6 @@
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import { BotProfileManager } from "./profile.js";
|
||||
import { TS6HttpQuery } from "../ts-protocol/http-query.js";
|
||||
import type { TS3Client } from "../ts-protocol/client.js";
|
||||
import type { QueuedSong } from "../audio/queue.js";
|
||||
|
||||
@@ -14,6 +15,9 @@ function makeMockTs(): TS3Client & {
|
||||
get clearCalls() { return clears; },
|
||||
getHost: () => "127.0.0.1",
|
||||
getHttpQuery: () => null,
|
||||
getClientId: () => 17,
|
||||
getChannelId: () => 5n,
|
||||
execCommand: vi.fn().mockResolvedValue(undefined),
|
||||
fileTransferInitUpload: vi.fn().mockResolvedValue({}),
|
||||
uploadFileData: vi.fn().mockImplementation(async (_h: any, _i: any, stream: any) => {
|
||||
const chunks: Buffer[] = [];
|
||||
@@ -202,3 +206,231 @@ describe("BotProfileManager loadCustomAvatar (pre-connect load, #148)", () => {
|
||||
expect(ts.uploadCalls[0].equals(Buffer.from([2, 2]))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("BotProfileManager channel description follows the bot (#159)", () => {
|
||||
const cfgChannelDesc = { ...cfgOff, channelDescEnabled: true };
|
||||
let ts: ReturnType<typeof makeMockTs> & { cid: bigint };
|
||||
let channelEdits: () => string[];
|
||||
|
||||
beforeEach(() => {
|
||||
ts = makeMockTs() as any;
|
||||
ts.cid = 5n;
|
||||
(ts as any).getChannelId = () => ts.cid;
|
||||
channelEdits = () =>
|
||||
(ts.execCommand as any).mock.calls
|
||||
.map((c: any[]) => c[0] as string)
|
||||
.filter((cmd: string) => cmd.startsWith("channeledit"));
|
||||
});
|
||||
|
||||
it("clears the old channel and fills the new one when moved while playing", async () => {
|
||||
const pm = new BotProfileManager(ts as any, noopLogger, cfgChannelDesc, "Bot");
|
||||
await pm.onSongChange(fakeSong);
|
||||
expect(channelEdits()).toEqual([
|
||||
expect.stringMatching(/^channeledit cid=5 channel_description=\S+/),
|
||||
]);
|
||||
|
||||
ts.cid = 9n;
|
||||
await pm.onChannelMoved(9n);
|
||||
|
||||
const edits = channelEdits();
|
||||
expect(edits[1]).toBe("channeledit cid=5 channel_description=");
|
||||
expect(edits[2]).toMatch(/^channeledit cid=9 channel_description=\S+/);
|
||||
});
|
||||
|
||||
it("stopping after a move clears the channel the bot is in now, not the old one", async () => {
|
||||
const pm = new BotProfileManager(ts as any, noopLogger, cfgChannelDesc, "Bot");
|
||||
await pm.onSongChange(fakeSong);
|
||||
ts.cid = 9n;
|
||||
await pm.onChannelMoved(9n);
|
||||
await pm.onSongChange(null);
|
||||
expect(channelEdits().at(-1)).toBe("channeledit cid=9 channel_description=");
|
||||
});
|
||||
|
||||
it("a move while idle touches no channel description", async () => {
|
||||
const pm = new BotProfileManager(ts as any, noopLogger, cfgChannelDesc, "Bot");
|
||||
ts.cid = 9n;
|
||||
await pm.onChannelMoved(9n);
|
||||
expect(channelEdits()).toEqual([]);
|
||||
});
|
||||
|
||||
it("a move is ignored when the channel description feature is off", async () => {
|
||||
const pm = new BotProfileManager(ts as any, noopLogger, cfgOff, "Bot");
|
||||
await pm.onSongChange(fakeSong);
|
||||
ts.cid = 9n;
|
||||
await pm.onChannelMoved(9n);
|
||||
expect(channelEdits()).toEqual([]);
|
||||
});
|
||||
|
||||
it("an event for the channel the description is already in is a no-op", async () => {
|
||||
const pm = new BotProfileManager(ts as any, noopLogger, cfgChannelDesc, "Bot");
|
||||
await pm.onSongChange(fakeSong);
|
||||
await pm.onChannelMoved(5n);
|
||||
expect(channelEdits()).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (error: Error) => void;
|
||||
const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej; });
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
function makeHttpProfile(partial: Partial<typeof cfgOff> = {}) {
|
||||
const ts = makeMockTs() as any;
|
||||
const state = { clid: 17, cid: 5n };
|
||||
const descriptions = new Map<number, string>();
|
||||
const http = new TS6HttpQuery({ host: "127.0.0.1", port: 10080 });
|
||||
const request = vi.spyOn(http, "request").mockImplementation(async (_method, path, body) => {
|
||||
if (path.includes("clientlist")) {
|
||||
return { status: 200, body: { body: [{ clid: String(state.clid), cid: String(state.cid) }], status: { code: 0, message: "ok" } } };
|
||||
}
|
||||
if (path.includes("channeledit")) descriptions.set(Number(body!.cid), String(body!.channel_description));
|
||||
return { status: 200, body: { status: { code: 0, message: "ok" } } };
|
||||
});
|
||||
ts.getHttpQuery = () => http;
|
||||
ts.getClientId = () => state.clid;
|
||||
ts.getChannelId = () => state.cid;
|
||||
const logger: any = { child: () => logger, info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() };
|
||||
const pm = new BotProfileManager(ts, logger, { ...cfgOff, ...partial }, "Bot");
|
||||
return { pm, ts, state, http, request, descriptions, logger };
|
||||
}
|
||||
|
||||
describe("BotProfileManager checked TS6 profile lifecycle", () => {
|
||||
it("clears the old channel through HTTP Query when moved, even without full-client edit permission", async () => {
|
||||
const { pm, ts, state, descriptions } = makeHttpProfile({ channelDescEnabled: true });
|
||||
ts.execCommand.mockRejectedValue(new Error("insufficient client permissions"));
|
||||
await pm.onSongChange(fakeSong);
|
||||
expect(descriptions.get(5)).toContain("X - Y");
|
||||
state.cid = 9n;
|
||||
await pm.onChannelMoved(9n);
|
||||
expect(descriptions.get(5)).toBe("");
|
||||
expect(descriptions.get(9)).toContain("X - Y");
|
||||
expect(ts.sendCommandNoWait).not.toHaveBeenCalled();
|
||||
expect(ts.execCommand).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("discards an old client-list reply after reconnect", async () => {
|
||||
const { pm, state, request } = makeHttpProfile({ channelDescEnabled: true });
|
||||
state.cid = 0n;
|
||||
const lookup = deferred<any>();
|
||||
request.mockImplementationOnce(() => lookup.promise);
|
||||
const update = pm.onSongChange(fakeSong);
|
||||
await flush();
|
||||
state.clid = 21;
|
||||
state.cid = 9n;
|
||||
pm.onConnect();
|
||||
lookup.resolve({ status: 200, body: { body: [{ clid: "17", cid: "5" }], status: { code: 0, message: "ok" } } });
|
||||
await update;
|
||||
expect(request.mock.calls.filter((call) => call[1].includes("channeledit"))).toEqual([]);
|
||||
await pm.onSongChange(null);
|
||||
expect(request).toHaveBeenLastCalledWith("POST", "/1/channeledit?sid=1", { cid: 9, channel_description: "" });
|
||||
});
|
||||
|
||||
it("does not restore the previous remembered channel when a write completes after reconnect", async () => {
|
||||
const { pm, state, request } = makeHttpProfile({ channelDescEnabled: true });
|
||||
const write = deferred<any>();
|
||||
request.mockImplementationOnce(() => write.promise);
|
||||
const update = pm.onSongChange(fakeSong);
|
||||
await flush();
|
||||
state.clid = 21;
|
||||
state.cid = 9n;
|
||||
pm.onConnect();
|
||||
write.resolve({ status: 200, body: { status: { code: 0, message: "ok" } } });
|
||||
await update;
|
||||
await pm.onSongChange(null);
|
||||
expect(request).toHaveBeenLastCalledWith("POST", "/1/channeledit?sid=1", { cid: 9, channel_description: "" });
|
||||
});
|
||||
|
||||
it("discards a pending channel lookup when playback stops", async () => {
|
||||
const { pm, ts, request, descriptions } = makeHttpProfile({ channelDescEnabled: true });
|
||||
ts.getChannelId = () => 0n;
|
||||
const lookup = deferred<any>();
|
||||
request.mockImplementationOnce(() => lookup.promise);
|
||||
const update = pm.onSongChange(fakeSong);
|
||||
await flush();
|
||||
await pm.onSongChange(null);
|
||||
lookup.resolve({ status: 200, body: { body: [{ clid: "17", cid: "5" }], status: { code: 0, message: "ok" } } });
|
||||
await update;
|
||||
expect(descriptions.get(5)).toBe("");
|
||||
});
|
||||
|
||||
it("discards a pending channel lookup when the bot is moved", async () => {
|
||||
const { pm, ts, request, descriptions } = makeHttpProfile({ channelDescEnabled: true });
|
||||
ts.getChannelId = () => 0n;
|
||||
const lookup = deferred<any>();
|
||||
request.mockImplementationOnce(() => lookup.promise);
|
||||
const update = pm.onSongChange(fakeSong);
|
||||
await flush();
|
||||
await pm.onChannelMoved(9n);
|
||||
lookup.resolve({ status: 200, body: { body: [{ clid: "17", cid: "5" }], status: { code: 0, message: "ok" } } });
|
||||
await update;
|
||||
expect(descriptions.has(5)).toBe(false);
|
||||
expect(descriptions.get(9)).toContain("X - Y");
|
||||
});
|
||||
|
||||
it("does not disable the new connection after an old write returns a permission failure", async () => {
|
||||
const { pm, state, request } = makeHttpProfile({ channelDescEnabled: true });
|
||||
const write = deferred<any>();
|
||||
request.mockImplementationOnce(() => write.promise);
|
||||
const update = pm.onSongChange(fakeSong);
|
||||
await flush();
|
||||
state.clid = 21;
|
||||
state.cid = 9n;
|
||||
pm.onConnect();
|
||||
write.resolve({ status: 403, body: { status: { code: 2568, message: "insufficient client permissions" } } });
|
||||
await update;
|
||||
await pm.onSongChange(fakeSong);
|
||||
expect(request).toHaveBeenLastCalledWith("POST", "/1/channeledit?sid=1", { cid: 9, channel_description: "♪ 正在播放: X - Y\n专辑: Z\n平台: netease" });
|
||||
});
|
||||
|
||||
it("resolves an unknown channel and sends raw newlines with one targeted description update", async () => {
|
||||
const { pm, ts, state, request } = makeHttpProfile({ channelDescEnabled: true, descriptionEnabled: true });
|
||||
ts.getChannelId = () => 0n;
|
||||
state.cid = 5n;
|
||||
await pm.onSongChange(fakeSong);
|
||||
expect(request.mock.calls.filter((call) => call[1].includes("clientedit"))).toEqual([
|
||||
["POST", "/1/clientedit?sid=1", { clid: 17, client_description: "X - Y [Z]" }],
|
||||
]);
|
||||
expect(request).toHaveBeenLastCalledWith("POST", "/1/channeledit?sid=1", { cid: 5, channel_description: "♪ 正在播放: X - Y\n专辑: Z\n平台: netease" });
|
||||
expect(ts.execCommand).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not resolve or write a disconnected client", async () => {
|
||||
const { pm, state, request } = makeHttpProfile({ channelDescEnabled: true, descriptionEnabled: true });
|
||||
state.clid = 0;
|
||||
state.cid = 0n;
|
||||
await pm.onSongChange(fakeSong);
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reports HTTP lookup permission errors once and retries after reconnect", async () => {
|
||||
const { pm, ts, request } = makeHttpProfile({ channelDescEnabled: true });
|
||||
ts.getChannelId = () => 0n;
|
||||
request.mockResolvedValue({ status: 403, body: { status: { code: 2568, message: "insufficient client permissions" } } });
|
||||
await pm.onSongChange(fakeSong);
|
||||
await pm.onSongChange(fakeSong);
|
||||
expect(request).toHaveBeenCalledTimes(1);
|
||||
pm.onConnect();
|
||||
await pm.onSongChange(fakeSong);
|
||||
expect(request).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("checks self clientupdate permission responses and retries only after reconnect", async () => {
|
||||
const { pm, ts, request, logger } = makeHttpProfile({ nicknameEnabled: true, awayStatusEnabled: true });
|
||||
const commands: string[] = [];
|
||||
ts.execCommand.mockImplementation(async (command: string) => {
|
||||
commands.push(command);
|
||||
throw new Error("insufficient client permissions (error id=2568)");
|
||||
});
|
||||
await pm.onSongChange(null);
|
||||
await pm.onSongChange(null);
|
||||
expect(commands).toHaveLength(1);
|
||||
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();
|
||||
await pm.onSongChange(null);
|
||||
expect(commands).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
+216
-72
@@ -13,6 +13,13 @@ const AVATAR_MAX_BYTES = 200 * 1024;
|
||||
/** Timeout for file-transfer operations (upload / delete). */
|
||||
const FILE_TRANSFER_TIMEOUT_MS = 6000;
|
||||
|
||||
interface ProfileUpdateContext {
|
||||
generation: number;
|
||||
channelGeneration: number;
|
||||
clientId: number;
|
||||
httpQuery: ReturnType<TS3Client["getHttpQuery"]>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Manages the bot's TeamSpeak presence (avatar, description, nickname,
|
||||
* away status, channel description, now-playing messages).
|
||||
@@ -32,6 +39,13 @@ export class BotProfileManager {
|
||||
* pushed immediately (idle) or wait for the next stop event (playing).
|
||||
*/
|
||||
private currentSong: QueuedSong | null = null;
|
||||
/**
|
||||
* Channel whose description currently holds our now-playing text, or null
|
||||
* if we have not written one. Remembered so that when the bot is moved we
|
||||
* can still clean up the channel it was taken out of (#159) — by then
|
||||
* getChannelId() already reports the new channel.
|
||||
*/
|
||||
private channelDescCid: bigint | null = null;
|
||||
|
||||
/** Per-feature permission-denied flags. Reset on reconnect. */
|
||||
private permDenied = {
|
||||
@@ -50,6 +64,8 @@ export class BotProfileManager {
|
||||
* the generation changed, a newer update has superseded them.
|
||||
*/
|
||||
private generation = 0;
|
||||
/** Channel moves supersede channel writes without cancelling avatar work. */
|
||||
private channelGeneration = 0;
|
||||
|
||||
constructor(
|
||||
tsClient: TS3Client,
|
||||
@@ -112,20 +128,25 @@ export class BotProfileManager {
|
||||
*/
|
||||
async onSongChange(song: QueuedSong | null): Promise<void> {
|
||||
const gen = ++this.generation;
|
||||
this.channelGeneration++;
|
||||
this.currentSong = song;
|
||||
const context = this.createUpdateContext();
|
||||
|
||||
// 1. Avatar first — file transfer uses its own response tracker and
|
||||
// must run before sendCommandNoWait calls whose orphaned responses
|
||||
// could confuse the command matcher.
|
||||
await this.updateAvatar(song?.coverUrl ?? null, gen);
|
||||
if (this.generation !== gen) return; // superseded
|
||||
if (!this.isCurrentUpdate(context)) return;
|
||||
|
||||
// 2. Combined clientupdate (nickname + away in one fire-and-forget)
|
||||
await this.updateClientProperties(song);
|
||||
// 2. Checked clientupdate sent by the visible client itself.
|
||||
await this.updateClientProperties(song, context);
|
||||
if (!this.isCurrentUpdate(context)) return;
|
||||
// 3. Description (clientedit on TS3, httpQuery on TS6)
|
||||
await this.updateDescription(song);
|
||||
// 4. Channel description (fire-and-forget channeledit)
|
||||
await this.updateChannelDescription(song);
|
||||
await this.updateDescription(song, context);
|
||||
if (!this.isCurrentUpdate(context)) return;
|
||||
// 4. Checked channel description update.
|
||||
await this.updateChannelDescription(song, context);
|
||||
if (!this.isCurrentUpdate(context)) return;
|
||||
// 5. Now-playing chat message
|
||||
if (song) await this.sendNowPlayingMessage(song);
|
||||
}
|
||||
@@ -133,7 +154,10 @@ export class BotProfileManager {
|
||||
/** Reset permission-denied flags and bump generation on new connection. */
|
||||
onConnect(): void {
|
||||
this.generation++;
|
||||
this.channelGeneration++;
|
||||
this.currentSong = null;
|
||||
// Channel ids are per-server; never carry one across a (re)connect.
|
||||
this.channelDescCid = null;
|
||||
this.permDenied = {
|
||||
avatar: false,
|
||||
description: false,
|
||||
@@ -150,6 +174,32 @@ export class BotProfileManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the bot itself has been moved to another channel (#159).
|
||||
* Clears the now-playing text from the channel it left and, if a song is
|
||||
* playing, writes it to the channel it is in now.
|
||||
*/
|
||||
async onChannelMoved(newChannelId: bigint): Promise<void> {
|
||||
if (!this.config.channelDescEnabled || this.permDenied.channelDesc) return;
|
||||
const oldChannelId = this.channelDescCid;
|
||||
if (oldChannelId === newChannelId) return;
|
||||
this.channelGeneration++;
|
||||
const context = this.createUpdateContext();
|
||||
const song = this.currentSong;
|
||||
try {
|
||||
if (oldChannelId !== null) {
|
||||
if (!await this.writeChannelDescription(oldChannelId, "", context)) return;
|
||||
this.channelDescCid = null;
|
||||
}
|
||||
} catch (err) {
|
||||
if (this.isCurrentChannelUpdate(context)) this.handleFeatureError("channelDesc", err);
|
||||
return;
|
||||
}
|
||||
if (song) {
|
||||
await this.updateChannelDescription(song, context, newChannelId);
|
||||
}
|
||||
}
|
||||
|
||||
getConfig(): ProfileConfig {
|
||||
return { ...this.config };
|
||||
}
|
||||
@@ -252,53 +302,56 @@ export class BotProfileManager {
|
||||
}
|
||||
}
|
||||
|
||||
private async updateDescription(song: QueuedSong | null): Promise<void> {
|
||||
private async updateDescription(song: QueuedSong | null, context: ProfileUpdateContext): Promise<void> {
|
||||
if (!this.config.descriptionEnabled || this.permDenied.description) return;
|
||||
if (!this.isCurrentUpdate(context)) return;
|
||||
|
||||
try {
|
||||
const text = song
|
||||
? `${song.name} - ${song.artist} [${song.album}]`
|
||||
: "";
|
||||
const httpQuery = this.tsClient.getHttpQuery();
|
||||
|
||||
const clid = context.clientId;
|
||||
if (clid <= 0) return;
|
||||
|
||||
const httpQuery = context.httpQuery;
|
||||
|
||||
if (httpQuery) {
|
||||
// TS6 HTTP API: send the raw (unescaped) text. clientUpdate
|
||||
// throws HttpQueryError on non-2xx so a silent 400/403 cannot
|
||||
// be misreported as success.
|
||||
const result = await httpQuery.clientUpdate({ client_description: text });
|
||||
this.logger.info({ status: result.status }, "Description updated");
|
||||
// IMPORTANT:
|
||||
// clientUpdate() would modify the HTTP Query/serveradmin client.
|
||||
// Explicitly edit the real visible music client instead.
|
||||
const result = await httpQuery.clientEdit(clid, {
|
||||
client_description: text,
|
||||
});
|
||||
if (!this.isCurrentUpdate(context)) return;
|
||||
|
||||
this.logger.info(
|
||||
{ status: result.status, clid },
|
||||
"Description updated",
|
||||
);
|
||||
} else {
|
||||
// clientupdate rejects client_description (error 1538).
|
||||
// Use clientedit on our own clid instead — this is what
|
||||
// TS3AudioBot does via TSLib's ChangeDescription().
|
||||
const clid = this.tsClient.getClientId();
|
||||
if (clid <= 0) return;
|
||||
// Use a 5s timeout — if clientedit hangs, don't block the
|
||||
// remaining profile updates (channeledit, now-playing msg).
|
||||
await this.withTimeout(
|
||||
this.tsClient.execCommand(
|
||||
`clientedit clid=${clid} client_description=${escapeTS3(text)}`,
|
||||
),
|
||||
5000,
|
||||
);
|
||||
this.logger.info("Description updated");
|
||||
if (!this.isCurrentUpdate(context)) return;
|
||||
|
||||
this.logger.info({ clid }, "Description updated");
|
||||
}
|
||||
} catch (err) {
|
||||
this.handleFeatureError("description", err);
|
||||
if (this.isCurrentUpdate(context)) this.handleFeatureError("description", err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build and send a single `clientupdate` command that sets nickname
|
||||
* and away status together, avoiding multiple round-trips that can
|
||||
* cause command-queue timeouts on the TS3 protocol.
|
||||
*
|
||||
* Values are collected as raw strings/numbers. The TS6 HTTP path
|
||||
* forwards them as JSON (the server expects real spaces, not `\s`);
|
||||
* the TS3 wire path escapes them on the fly. Previously the code
|
||||
* escaped upfront and then split the escaped string to build the
|
||||
* JSON body, so TS6 received literal backslashes and silently
|
||||
* rejected the update.
|
||||
* and away status together. The full client sends this command on both
|
||||
* TS3 and TS6, with a return code so permission failures are observable.
|
||||
*/
|
||||
private async updateClientProperties(song: QueuedSong | null): Promise<void> {
|
||||
private async updateClientProperties(song: QueuedSong | null, context: ProfileUpdateContext): Promise<void> {
|
||||
if (!this.isCurrentUpdate(context) || context.clientId <= 0) return;
|
||||
const rawProps: Record<string, string | number> = {};
|
||||
|
||||
// --- Nickname ---
|
||||
@@ -319,39 +372,38 @@ export class BotProfileManager {
|
||||
rawProps.client_away = 0;
|
||||
} else {
|
||||
rawProps.client_away = 1;
|
||||
rawProps.client_away_message = "\u7B49\u5F85\u64AD\u653E";
|
||||
rawProps.client_away_message = "等待播放";
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.keys(rawProps).length === 0) return;
|
||||
|
||||
try {
|
||||
const httpQuery = this.tsClient.getHttpQuery();
|
||||
if (httpQuery) {
|
||||
// TS6: send raw values as JSON. Throws HttpQueryError on 4xx/5xx.
|
||||
const result = await httpQuery.clientUpdate(rawProps);
|
||||
this.logger.info(
|
||||
{ status: result.status, props: Object.keys(rawProps) },
|
||||
"Client properties updated (nickname + away)",
|
||||
);
|
||||
} else {
|
||||
// TS3 wire protocol: escape string values inline.
|
||||
// sendCommandNoWait: the TS3 full-client protocol often
|
||||
// doesn't return a timely error response for clientupdate,
|
||||
// causing execCommand to time out after 10s.
|
||||
const parts = Object.entries(rawProps).map(([k, v]) =>
|
||||
typeof v === "string" ? `${k}=${escapeTS3(v)}` : `${k}=${v}`,
|
||||
);
|
||||
await this.tsClient.sendCommandNoWait(`clientupdate ${parts.join(" ")}`);
|
||||
this.logger.info(
|
||||
{ props: Object.keys(rawProps) },
|
||||
"Client properties updated (nickname + away)",
|
||||
);
|
||||
}
|
||||
// clientupdate modifies whichever connection sends the command.
|
||||
// Therefore it must be sent by the real full client, NOT HTTP Query.
|
||||
const parts = Object.entries(rawProps).map(([key, value]) =>
|
||||
typeof value === "string"
|
||||
? `${key}=${escapeTS3(value)}`
|
||||
: `${key}=${value}`,
|
||||
);
|
||||
|
||||
await this.withTimeout(
|
||||
this.tsClient.execCommand(`clientupdate ${parts.join(" ")}`),
|
||||
5000,
|
||||
);
|
||||
if (!this.isCurrentUpdate(context)) return;
|
||||
|
||||
this.logger.info(
|
||||
{
|
||||
clid: context.clientId,
|
||||
props: Object.keys(rawProps),
|
||||
},
|
||||
"Client properties updated (nickname + away)",
|
||||
);
|
||||
} catch (err) {
|
||||
// Flag both features on permission error
|
||||
this.handleFeatureError("nickname", err);
|
||||
this.handleFeatureError("awayStatus", err);
|
||||
if (!this.isCurrentUpdate(context)) return;
|
||||
if (rawProps.client_nickname !== undefined) this.handleFeatureError("nickname", err);
|
||||
if (rawProps.client_away !== undefined) this.handleFeatureError("awayStatus", err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -400,33 +452,106 @@ export class BotProfileManager {
|
||||
return str.slice(0, end) + ellipsis;
|
||||
}
|
||||
|
||||
private async updateChannelDescription(song: QueuedSong | null): Promise<void> {
|
||||
private async updateChannelDescription(
|
||||
song: QueuedSong | null,
|
||||
context: ProfileUpdateContext,
|
||||
targetChannelId?: bigint,
|
||||
): Promise<void> {
|
||||
if (!this.config.channelDescEnabled || this.permDenied.channelDesc) return;
|
||||
if (!this.isCurrentChannelUpdate(context) || context.clientId <= 0) return;
|
||||
|
||||
try {
|
||||
const channelId = this.tsClient.getChannelId();
|
||||
if (channelId === 0n) return; // unknown channel
|
||||
// A stop already knows which channel to clear if a write succeeded.
|
||||
// Avoid a needless client-list lookup that could prevent that cleanup.
|
||||
let channelId = !song && this.channelDescCid !== null
|
||||
? this.channelDescCid
|
||||
: targetChannelId ?? this.tsClient.getChannelId();
|
||||
|
||||
// TS6 full-client may report channelID() as 0 even after the
|
||||
// visible music client has already joined a channel.
|
||||
// Fall back to HTTP Query and resolve our real clid -> cid.
|
||||
if (channelId === 0n) {
|
||||
const httpQuery = context.httpQuery;
|
||||
const clid = context.clientId;
|
||||
|
||||
if (httpQuery && clid > 0) {
|
||||
const result = await httpQuery.clientList();
|
||||
if (!this.isCurrentChannelUpdate(context)) return;
|
||||
|
||||
const payload = result.body as {
|
||||
body?: Array<Record<string, string>>;
|
||||
};
|
||||
|
||||
const me = payload?.body?.find(
|
||||
(client) => Number(client.clid) === clid,
|
||||
);
|
||||
|
||||
if (me?.cid) {
|
||||
channelId = BigInt(me.cid);
|
||||
|
||||
this.logger.info(
|
||||
{
|
||||
clid,
|
||||
cid: channelId.toString(),
|
||||
},
|
||||
"Resolved channel ID via HTTP Query",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!song) {
|
||||
await this.tsClient.sendCommandNoWait(
|
||||
`channeledit cid=${channelId} channel_description=`,
|
||||
);
|
||||
if (channelId <= 0n) return;
|
||||
if (await this.writeChannelDescription(channelId, "", context)) this.channelDescCid = null;
|
||||
return;
|
||||
}
|
||||
|
||||
if (channelId <= 0n) return;
|
||||
|
||||
const lines = [
|
||||
`\u266A \u6B63\u5728\u64AD\u653E: ${song.name} - ${song.artist}`, // ♪ 正在播放:
|
||||
`\u4E13\u8F91: ${song.album}`, // 专辑:
|
||||
`\u5E73\u53F0: ${song.platform}`, // 平台:
|
||||
`♪ 正在播放: ${song.name} - ${song.artist}`,
|
||||
`专辑: ${song.album}`,
|
||||
`平台: ${song.platform}`,
|
||||
];
|
||||
const desc = lines.join("\\n");
|
||||
await this.tsClient.sendCommandNoWait(
|
||||
`channeledit cid=${channelId} channel_description=${escapeTS3(desc)}`,
|
||||
);
|
||||
|
||||
// HTTP Query uses a normal JSON string, so use real newlines here.
|
||||
const desc = lines.join("\n");
|
||||
|
||||
if (await this.writeChannelDescription(channelId, desc, context)) this.channelDescCid = channelId;
|
||||
} catch (err) {
|
||||
this.handleFeatureError("channelDesc", err);
|
||||
if (this.isCurrentChannelUpdate(context)) this.handleFeatureError("channelDesc", err);
|
||||
}
|
||||
}
|
||||
|
||||
/** Both move cleanup and ordinary writes use the same checked transport. */
|
||||
private async writeChannelDescription(
|
||||
channelId: bigint,
|
||||
description: string,
|
||||
context: ProfileUpdateContext,
|
||||
): Promise<boolean> {
|
||||
if (!this.isCurrentChannelUpdate(context)) return false;
|
||||
let status: number | undefined;
|
||||
if (context.httpQuery) {
|
||||
const result = await context.httpQuery.channelEdit(Number(channelId), {
|
||||
channel_description: description,
|
||||
});
|
||||
status = result.status;
|
||||
} else {
|
||||
await this.withTimeout(
|
||||
this.tsClient.execCommand(
|
||||
`channeledit cid=${channelId} channel_description=${escapeTS3(description)}`,
|
||||
),
|
||||
5000,
|
||||
);
|
||||
}
|
||||
if (!this.isCurrentChannelUpdate(context)) return false;
|
||||
this.logger.info(
|
||||
{ status, cid: channelId.toString() },
|
||||
description ? "Channel description updated" : "Channel description cleared",
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
private async sendNowPlayingMessage(song: QueuedSong): Promise<void> {
|
||||
if (!this.config.nowPlayingMsgEnabled || this.permDenied.nowPlayingMsg) return;
|
||||
try {
|
||||
@@ -439,6 +564,25 @@ export class BotProfileManager {
|
||||
|
||||
// --- Helpers ---
|
||||
|
||||
private createUpdateContext(): ProfileUpdateContext {
|
||||
return {
|
||||
generation: this.generation,
|
||||
channelGeneration: this.channelGeneration,
|
||||
clientId: this.tsClient.getClientId(),
|
||||
httpQuery: this.tsClient.getHttpQuery(),
|
||||
};
|
||||
}
|
||||
|
||||
private isCurrentUpdate(context: ProfileUpdateContext): boolean {
|
||||
return context.generation === this.generation &&
|
||||
context.clientId === this.tsClient.getClientId() &&
|
||||
context.httpQuery === this.tsClient.getHttpQuery();
|
||||
}
|
||||
|
||||
private isCurrentChannelUpdate(context: ProfileUpdateContext): boolean {
|
||||
return this.isCurrentUpdate(context) && context.channelGeneration === this.channelGeneration;
|
||||
}
|
||||
|
||||
/**
|
||||
* Append CDN resize parameters to get a thumbnail suitable for TS3 avatars.
|
||||
* NetEase and QQ Music CDNs support URL-based image resizing.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { parseSongRef, parseSelectionIndex } from "./song-ref.js";
|
||||
import { parseSongRef, parseSelectionIndex, parsePlaylistRef, findShareShortLink, resolveShareLink } from "./song-ref.js";
|
||||
|
||||
describe("parseSongRef (#90 exact-song selection)", () => {
|
||||
it("returns null for a plain search term", () => {
|
||||
@@ -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)", () => {
|
||||
@@ -120,3 +148,65 @@ describe("parseSelectionIndex (#90 pick from last search)", () => {
|
||||
expect(parseSelectionIndex("")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("parsePlaylistRef (#160 play a playlist from its link)", () => {
|
||||
it("returns null for a playlist name or a bare id (caller keeps its old logic)", () => {
|
||||
expect(parsePlaylistRef("华语经典")).toBeNull();
|
||||
expect(parsePlaylistRef("2829883282")).toBeNull();
|
||||
expect(parsePlaylistRef("")).toBeNull();
|
||||
});
|
||||
|
||||
it("parses NetEase playlist URLs (web, hash route, mobile share)", () => {
|
||||
expect(parsePlaylistRef("https://music.163.com/playlist?id=2829883282")).toEqual({ id: "2829883282", platform: "netease" });
|
||||
expect(parsePlaylistRef("https://music.163.com/#/playlist?id=2829883282")).toEqual({ id: "2829883282", platform: "netease" });
|
||||
expect(parsePlaylistRef("https://y.music.163.com/m/playlist?id=2829883282&userid=77&creatorId=77")).toEqual({ id: "2829883282", platform: "netease" });
|
||||
expect(parsePlaylistRef("https://music.163.com/playlist/2829883282")).toEqual({ id: "2829883282", platform: "netease" });
|
||||
});
|
||||
|
||||
it("does not mistake a NetEase userid= for the playlist id", () => {
|
||||
expect(parsePlaylistRef("https://music.163.com/playlist?userid=77&id=123")).toEqual({ id: "123", platform: "netease" });
|
||||
});
|
||||
|
||||
it("parses QQ Music playlist URLs", () => {
|
||||
expect(parsePlaylistRef("https://y.qq.com/n/ryqq/playlist/8052190267")).toEqual({ id: "8052190267", platform: "qq" });
|
||||
expect(parsePlaylistRef("https://i.y.qq.com/n2/m/share/details/taoge.html?platform=11&appshare=android_qq&hosteuin=abc&id=8052190267&appversion=13")).toEqual({ id: "8052190267", platform: "qq" });
|
||||
});
|
||||
|
||||
it("parses YouTube playlist URLs by their list= id", () => {
|
||||
expect(parsePlaylistRef("https://www.youtube.com/playlist?list=PLx0sYbCqOb8TBPRdmBHs5Iftvv9TPboYG")).toEqual({ id: "PLx0sYbCqOb8TBPRdmBHs5Iftvv9TPboYG", platform: "youtube" });
|
||||
expect(parsePlaylistRef("https://youtu.be/abc?list=PLabc-_1")).toEqual({ id: "PLabc-_1", platform: "youtube" });
|
||||
});
|
||||
|
||||
it("unwraps the [URL] BBCode the TeamSpeak client adds to pasted links", () => {
|
||||
expect(parsePlaylistRef("[URL]https://y.qq.com/n/ryqq/playlist/8052190267[/URL]")).toEqual({ id: "8052190267", platform: "qq" });
|
||||
});
|
||||
|
||||
it("finds the link inside an app's share text", () => {
|
||||
expect(parsePlaylistRef("分享某人创建的歌单「深夜」: https://y.music.163.com/m/playlist?id=123&userid=77 (来自@网易云音乐)")).toEqual({ id: "123", platform: "netease" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("findShareShortLink (#160)", () => {
|
||||
it("finds NetEase and QQ app short links, even inside share text or BBCode", () => {
|
||||
expect(findShareShortLink("歌单「深夜」: https://163cn.tv/Abc123 (来自@网易云音乐)")).toBe("https://163cn.tv/Abc123");
|
||||
expect(findShareShortLink("[URL]https://c6.y.qq.com/base/fcgi-bin/u?__=AbCd12[/URL]")).toBe("https://c6.y.qq.com/base/fcgi-bin/u?__=AbCd12");
|
||||
});
|
||||
|
||||
it("ignores every other host, so we never fetch arbitrary user-supplied URLs", () => {
|
||||
expect(findShareShortLink("https://evil.example/163cn.tv/Abc")).toBeNull();
|
||||
expect(findShareShortLink("http://127.0.0.1:8080/x")).toBeNull();
|
||||
expect(findShareShortLink("华语经典")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveShareLink (#160)", () => {
|
||||
it("returns the redirect target", async () => {
|
||||
const get = async () => ({ status: 302, location: "https://music.163.com/playlist?id=123" });
|
||||
expect(await resolveShareLink("https://163cn.tv/Abc", get)).toBe("https://music.163.com/playlist?id=123");
|
||||
});
|
||||
|
||||
it("returns null when there is no redirect or the request fails", async () => {
|
||||
expect(await resolveShareLink("https://163cn.tv/Abc", async () => ({ status: 200, location: undefined }))).toBeNull();
|
||||
expect(await resolveShareLink("https://163cn.tv/Abc", async () => { throw new Error("boom"); })).toBeNull();
|
||||
});
|
||||
});
|
||||
+86
-1
@@ -1,3 +1,5 @@
|
||||
import axios from "axios";
|
||||
|
||||
/**
|
||||
* Parsing helpers for picking an EXACT song in a !play / !add / !playnext query,
|
||||
* so same-name songs can be disambiguated instead of always getting the single
|
||||
@@ -67,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
|
||||
@@ -98,3 +104,82 @@ export function parseSelectionIndex(raw: string): number | null {
|
||||
const n = parseInt(m[1], 10);
|
||||
return Number.isFinite(n) && n > 0 ? n : null;
|
||||
}
|
||||
|
||||
export interface PlaylistRef {
|
||||
id: string;
|
||||
platform: "netease" | "qq" | "youtube";
|
||||
}
|
||||
|
||||
/** Drop the [URL]…[/URL] BBCode the TeamSpeak client wraps around pasted links. */
|
||||
function stripUrlBBCode(text: string): string {
|
||||
return text.replace(/\[\/?url(?:=[^\]]*)?\]/gi, " ");
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect a playlist URL (#160) — a web link, or the full link inside an app's
|
||||
* share text. The platform comes from the URL, so a QQ link works without
|
||||
* `-q`. Returns `null` for anything else (a playlist name or bare id), which
|
||||
* the caller handles as before.
|
||||
*/
|
||||
export function parsePlaylistRef(raw: string): PlaylistRef | null {
|
||||
const q = stripUrlBBCode(raw ?? "").trim();
|
||||
if (!q) return null;
|
||||
|
||||
if (/music\.163\.com/i.test(q)) {
|
||||
const m = /[?&#/]id=(\d+)/.exec(q) ?? /\/playlist\/(\d+)/.exec(q);
|
||||
if (m) return { id: m[1], platform: "netease" };
|
||||
}
|
||||
|
||||
if (/y\.qq\.com/i.test(q)) {
|
||||
const m = /\/playlist\/(\d+)/.exec(q) ?? /[?&](?:id|disstid)=(\d+)/.exec(q);
|
||||
if (m) return { id: m[1], platform: "qq" };
|
||||
}
|
||||
|
||||
if (/youtube\.com|youtu\.be/i.test(q)) {
|
||||
const m = /[?&]list=([\w-]+)/.exec(q);
|
||||
if (m) return { id: m[1], platform: "youtube" };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a NetEase (163cn.tv) or QQ Music (c6.y.qq.com/base/fcgi-bin/u) share
|
||||
* short link — what the phone apps copy. Only these hosts are recognized so
|
||||
* the bot never fetches an arbitrary user-supplied URL.
|
||||
*/
|
||||
export function findShareShortLink(raw: string): string | null {
|
||||
const q = stripUrlBBCode(raw ?? "");
|
||||
const m =
|
||||
/https?:\/\/163cn\.(?:tv|link)\/[0-9A-Za-z]+/i.exec(q) ??
|
||||
/https?:\/\/c\d*\.y\.qq\.com\/base\/fcgi-bin\/u\?__=[0-9A-Za-z]+/i.exec(q);
|
||||
return m ? m[0] : null;
|
||||
}
|
||||
|
||||
type RedirectGet = (url: string) => Promise<{ status: number; location: string | undefined }>;
|
||||
|
||||
const redirectGet: RedirectGet = async (url) => {
|
||||
const res = await axios.get(url, {
|
||||
maxRedirects: 0,
|
||||
timeout: 5000,
|
||||
validateStatus: () => true,
|
||||
responseType: "stream",
|
||||
});
|
||||
res.data?.destroy?.();
|
||||
const location = res.headers.location;
|
||||
return { status: res.status, location: typeof location === "string" ? location : undefined };
|
||||
};
|
||||
|
||||
/** Follow a share short link one hop. Returns the target URL, or null. */
|
||||
export async function resolveShareLink(
|
||||
url: string,
|
||||
get: RedirectGet = redirectGet,
|
||||
): Promise<string | null> {
|
||||
try {
|
||||
const { status, location } = await get(url);
|
||||
if (status < 300 || status >= 400 || !location) return null;
|
||||
return new URL(location, url).toString();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,554 @@
|
||||
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("stops immediately when the provider asks the user to verify", async () => {
|
||||
const error = new SongUrlUnavailable({
|
||||
platform: "kugou", songId: "song", code: "provider_verification_required", message: "Verification required",
|
||||
});
|
||||
const resolve = vi.fn(async () => { throw error; });
|
||||
const onExhausted = vi.fn();
|
||||
const { sleep, delays } = recordingSleep();
|
||||
|
||||
expect(await resolveUrlWithRetry({ retries: 5, fallbacks: ["standard"], resolve, onExhausted, sleep })).toBeNull();
|
||||
expect(resolve).toHaveBeenCalledTimes(1);
|
||||
expect(delays).toEqual([]);
|
||||
expect(onExhausted).toHaveBeenCalledExactlyOnceWith({ error, quality: undefined });
|
||||
});
|
||||
|
||||
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,194 @@
|
||||
import { RiskControlError, SongUrlUnavailable } from "../music/provider.js";
|
||||
import type { PlayFailureCode, SongUrlResult } from "../music/provider.js";
|
||||
|
||||
/** These failures apply to the provider for the current queue transition. */
|
||||
export function blocksProviderForAdvance(code: PlayFailureCode | undefined): boolean {
|
||||
return code === "risk_control" || code === "provider_verification_required";
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 });
|
||||
if (error instanceof SongUrlUnavailable && error.failure.code === "provider_verification_required") break;
|
||||
// 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;
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { EventEmitter } from "node:events";
|
||||
import pino from "pino";
|
||||
import { BotInstance } from "./instance.js";
|
||||
import { AudioPlayer } from "../audio/player.js";
|
||||
import { PlayQueue } from "../audio/queue.js";
|
||||
import { PCM_FRAME_BYTES } from "../audio/encoder.js";
|
||||
import { TS3Client } from "../ts-protocol/client.js";
|
||||
|
||||
function makeHarness(platform: "bilibili" | "spotify" = "bilibili") {
|
||||
const logger = pino({ level: "silent" });
|
||||
const player = new AudioPlayer(logger);
|
||||
const queue = new PlayQueue();
|
||||
queue.add({ id: "offline-fixture", name: "67-minute fixture", artist: "fixture", album: "", coverUrl: "", platform, duration: 4020 });
|
||||
queue.play();
|
||||
Object.assign(player, { state: "playing", framesPlayed: 111000 });
|
||||
const tsClient = new TS3Client({ host: "localhost", port: 9987, queryPort: 10011, nickname: "OfflineFixture" }, logger);
|
||||
let sidecarPauses = 0;
|
||||
const bot = Object.assign(new EventEmitter(), {
|
||||
logger, player, queue, tsClient, connected: true, autoPaused: true,
|
||||
streamRecovery: null, lifecycleGeneration: 0,
|
||||
spotifyController: Object.assign(new EventEmitter(), { pause: async () => { sidecarPauses++; } }),
|
||||
});
|
||||
const methods = BotInstance.prototype as unknown as {
|
||||
setupTsEvents(this: typeof bot): void;
|
||||
cmdPause(this: typeof bot): string;
|
||||
};
|
||||
Object.assign(bot, { cmdPause: methods.cmdPause });
|
||||
methods.setupTsEvents.call(bot);
|
||||
return { bot, player, queue, tsClient, sidecarPauses: () => sidecarPauses };
|
||||
}
|
||||
|
||||
afterEach(() => { vi.clearAllTimers(); vi.restoreAllMocks(); vi.useRealTimers(); });
|
||||
|
||||
describe("BotInstance persistent voice send failure", () => {
|
||||
it.each(["bilibili", "spotify"] as const)("pauses %s while retaining the song and playback position", platform => {
|
||||
const h = makeHarness(platform);
|
||||
const song = h.queue.current();
|
||||
let changes = 0;
|
||||
h.bot.on("stateChange", () => changes++);
|
||||
try {
|
||||
h.tsClient.emit("voiceSendFailed", { code: "ERR_SOCKET_DGRAM_NOT_RUNNING", consecutiveFailures: 100, durationMs: 2000 });
|
||||
expect(h.player.getState()).toBe("paused");
|
||||
expect(h.player.getElapsed()).toBe(2220);
|
||||
expect(h.queue.current()).toBe(song);
|
||||
expect(h.queue.size()).toBe(1);
|
||||
expect(h.bot.autoPaused).toBe(false);
|
||||
expect(changes).toBe(1);
|
||||
expect(h.sidecarPauses()).toBe(platform === "spotify" ? 1 : 0);
|
||||
h.tsClient.emit("voiceSendFailed", { consecutiveFailures: 200, durationMs: 4000 });
|
||||
expect(changes).toBe(1);
|
||||
} finally { h.player.stop(); }
|
||||
});
|
||||
|
||||
it("stops the actual audio scheduler from advancing elapsed after terminal transmission failure", () => {
|
||||
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance"] });
|
||||
const h = makeHarness();
|
||||
const internal = h.player as unknown as { startFrameLoop(): void };
|
||||
let frames = 0;
|
||||
h.player.on("frame", () => frames++);
|
||||
Object.assign(h.player, { framesPlayed: 0, ffmpeg: { pid: undefined }, pcmBuffer: Buffer.alloc(PCM_FRAME_BYTES * 250), currentSongDuration: 4020 });
|
||||
try {
|
||||
internal.startFrameLoop();
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(frames).toBe(50);
|
||||
h.tsClient.emit("voiceSendFailed", { consecutiveFailures: 100, durationMs: 2000 });
|
||||
vi.advanceTimersByTime(3000);
|
||||
// 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(); }
|
||||
});
|
||||
|
||||
it("lets transient failure recover without pausing and does not auto-resume a user pause", () => {
|
||||
const h = makeHarness();
|
||||
try {
|
||||
h.tsClient.emit("voiceSendFailure", { consecutiveFailures: 1, durationMs: 0 });
|
||||
h.tsClient.emit("voiceSendRecovered", { consecutiveFailures: 1, durationMs: 20 });
|
||||
expect(h.player.getState()).toBe("playing");
|
||||
h.player.pause();
|
||||
h.tsClient.emit("voiceSendRecovered", { consecutiveFailures: 1, durationMs: 20 });
|
||||
expect(h.player.getState()).toBe("paused");
|
||||
} finally { h.player.stop(); }
|
||||
});
|
||||
|
||||
it("preserves pause intent when terminal failure occurs during a pending fresh URL lookup", async () => {
|
||||
const h = makeHarness();
|
||||
Object.assign(h.player, { state: "idle" });
|
||||
let resolve!: (result: { url: string }) => void;
|
||||
const lookup = new Promise<{ url: string }>(done => { resolve = done; });
|
||||
Object.assign(h.bot, { getProviderFor: () => ({ getSongUrl: () => lookup }) });
|
||||
// Isolate only process creation; the actual stop, seek, state, session,
|
||||
// recovery method and pause method remain in use.
|
||||
vi.spyOn(h.player, "play").mockImplementation((_url, seek, duration) => {
|
||||
h.player.stop();
|
||||
Object.assign(h.player, { state: "playing", seekOffset: seek, currentSongDuration: duration });
|
||||
});
|
||||
const resume = (BotInstance.prototype as unknown as { resumeInterruptedStream(this: typeof h.bot): Promise<boolean> }).resumeInterruptedStream;
|
||||
const recovery = resume.call(h.bot);
|
||||
try {
|
||||
h.tsClient.emit("voiceSendFailed", { code: "EPIPE", consecutiveFailures: 100, durationMs: 2000 });
|
||||
resolve({ url: "https://offline.invalid/fresh.m4s" });
|
||||
expect(await recovery).toBe(true);
|
||||
expect(h.player.getState()).toBe("paused");
|
||||
expect(h.player.getElapsed()).toBe(2220);
|
||||
expect(h.queue.current()?.id).toBe("offline-fixture");
|
||||
} finally { h.player.stop(); }
|
||||
});
|
||||
|
||||
it("pauses again if manual resume encounters the same persistent voice fault", () => {
|
||||
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance", "Date"] });
|
||||
const h = makeHarness();
|
||||
let accepted = 0;
|
||||
Object.assign(h.tsClient, { client: { sendVoice() {
|
||||
if (accepted++ > 0) throw Object.assign(new Error("offline fixture"), { code: "EPIPE" });
|
||||
} } });
|
||||
const setupPlayerEvents = (BotInstance.prototype as unknown as { setupPlayerEvents(this: typeof h.bot): void }).setupPlayerEvents;
|
||||
setupPlayerEvents.call(h.bot);
|
||||
Object.assign(h.player, { framesPlayed: 0, ffmpeg: { pid: undefined }, pcmBuffer: Buffer.alloc(PCM_FRAME_BYTES * 250), currentSongDuration: 4020 });
|
||||
try {
|
||||
(h.player as unknown as { startFrameLoop(): void }).startFrameLoop();
|
||||
vi.advanceTimersByTime(2100);
|
||||
expect(h.player.getState()).toBe("paused");
|
||||
const pausedAt = h.player.getElapsed();
|
||||
h.player.resume();
|
||||
vi.advanceTimersByTime(40);
|
||||
expect(h.player.getState()).toBe("paused");
|
||||
expect(h.player.getElapsed()).toBeLessThanOrEqual(pausedAt + 0.02);
|
||||
expect(h.queue.current()?.id).toBe("offline-fixture");
|
||||
} finally { h.player.stop(); }
|
||||
});
|
||||
|
||||
it("ignores terminal notifications when disconnected or already idle", () => {
|
||||
const h = makeHarness();
|
||||
try {
|
||||
h.bot.connected = false;
|
||||
h.tsClient.emit("voiceSendFailed", { consecutiveFailures: 100, durationMs: 2000 });
|
||||
expect(h.player.getState()).toBe("playing");
|
||||
h.bot.connected = true;
|
||||
h.player.stop();
|
||||
h.tsClient.emit("voiceSendFailed", { consecutiveFailures: 100, durationMs: 2000 });
|
||||
expect(h.player.getState()).toBe("idle");
|
||||
} finally { h.player.stop(); }
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
|
||||
import { createHash } from "node:crypto";
|
||||
import { createDatabase, type BotDatabase } from "./database.js";
|
||||
import { createUserStore, type UserStore } from "./users.js";
|
||||
import {
|
||||
createApiKeyStore,
|
||||
type ApiKeyStore,
|
||||
MAX_API_KEYS_PER_USER,
|
||||
API_KEY_TOUCH_INTERVAL_MS,
|
||||
} from "./api-keys.js";
|
||||
|
||||
function sha256(key: string) {
|
||||
return createHash("sha256").update(key).digest("hex");
|
||||
}
|
||||
|
||||
describe("ApiKeyStore", () => {
|
||||
let botDb: BotDatabase;
|
||||
let users: UserStore;
|
||||
let keys: ApiKeyStore;
|
||||
let userId: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
botDb = createDatabase(":memory:");
|
||||
users = createUserStore(botDb.db);
|
||||
keys = createApiKeyStore(botDb.db);
|
||||
const u = await users.createUser("alice", "pw-alice", "admin");
|
||||
userId = u.id;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
botDb.close();
|
||||
});
|
||||
|
||||
it("create returns a tsmb_-prefixed raw key whose sha256 is stored, never the plaintext", () => {
|
||||
const created = keys.create(userId, "ci");
|
||||
expect(created).not.toBeNull();
|
||||
expect(created!.rawKey).toMatch(/^tsmb_[A-Za-z0-9_-]{40,}$/);
|
||||
const row = botDb.db.prepare("SELECT keyHash, keyPrefix FROM api_keys").get() as {
|
||||
keyHash: string;
|
||||
keyPrefix: string;
|
||||
};
|
||||
expect(row.keyHash).toBe(sha256(created!.rawKey));
|
||||
expect(row.keyHash).not.toContain(created!.rawKey);
|
||||
expect(created!.key.keyPrefix).toBe(created!.rawKey.slice(0, 12));
|
||||
});
|
||||
|
||||
it("validateAndTouch resolves the owner user for a fresh key", () => {
|
||||
const { rawKey } = keys.create(userId, "ci")!;
|
||||
const result = keys.validateAndTouch(rawKey);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.userId).toBe(userId);
|
||||
expect(result!.username).toBe("alice");
|
||||
expect(result!.role).toBe("admin");
|
||||
});
|
||||
|
||||
it("validateAndTouch returns null for an unknown or empty key", () => {
|
||||
keys.create(userId, "ci");
|
||||
expect(keys.validateAndTouch("tsmb_not-a-real-key")).toBeNull();
|
||||
expect(keys.validateAndTouch("")).toBeNull();
|
||||
});
|
||||
|
||||
it("delete removes the key so it no longer validates", () => {
|
||||
const { key, rawKey } = keys.create(userId, "ci")!;
|
||||
expect(keys.delete(key.id, userId)).toBe(true);
|
||||
expect(keys.validateAndTouch(rawKey)).toBeNull();
|
||||
});
|
||||
|
||||
it("delete with userId refuses to remove another user's key", async () => {
|
||||
const { key } = keys.create(userId, "ci")!;
|
||||
const other = await users.createUser("bob", "pw-bob", "member");
|
||||
expect(keys.delete(key.id, other.id)).toBe(false);
|
||||
expect(keys.delete(key.id)).toBe(true);
|
||||
});
|
||||
|
||||
it("keys of a deleted user stop validating", async () => {
|
||||
const { rawKey } = keys.create(userId, "ci")!;
|
||||
users.deleteUser(userId);
|
||||
expect(keys.validateAndTouch(rawKey)).toBeNull();
|
||||
});
|
||||
|
||||
it("enforces the per-user key cap", () => {
|
||||
for (let i = 0; i < MAX_API_KEYS_PER_USER; i++) {
|
||||
expect(keys.create(userId, `key-${i}`)).not.toBeNull();
|
||||
}
|
||||
expect(keys.create(userId, "one-too-many")).toBeNull();
|
||||
expect(keys.listForUser(userId)).toHaveLength(MAX_API_KEYS_PER_USER);
|
||||
});
|
||||
|
||||
it("touches lastUsedAt at most once per interval", () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date("2026-01-01T00:00:00Z"));
|
||||
const { rawKey } = keys.create(userId, "ci")!;
|
||||
keys.validateAndTouch(rawKey);
|
||||
const first = (botDb.db.prepare("SELECT lastUsedAt FROM api_keys").get() as { lastUsedAt: number }).lastUsedAt;
|
||||
vi.setSystemTime(new Date("2026-01-01T00:00:00Z").getTime() + 30_000);
|
||||
keys.validateAndTouch(rawKey);
|
||||
const second = (botDb.db.prepare("SELECT lastUsedAt FROM api_keys").get() as { lastUsedAt: number }).lastUsedAt;
|
||||
expect(second).toBe(first);
|
||||
vi.setSystemTime(new Date("2026-01-01T00:00:00Z").getTime() + API_KEY_TOUCH_INTERVAL_MS + 1000);
|
||||
keys.validateAndTouch(rawKey);
|
||||
const third = (botDb.db.prepare("SELECT lastUsedAt FROM api_keys").get() as { lastUsedAt: number }).lastUsedAt;
|
||||
expect(third).toBeGreaterThan(first);
|
||||
});
|
||||
|
||||
it("deleteAllForUser clears every key of that user", async () => {
|
||||
keys.create(userId, "a");
|
||||
keys.create(userId, "b");
|
||||
const other = await users.createUser("bob", "pw-bob", "member");
|
||||
keys.create(other.id, "c");
|
||||
keys.deleteAllForUser(userId);
|
||||
expect(keys.listForUser(userId)).toHaveLength(0);
|
||||
expect(keys.listForUser(other.id)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("listAll exposes usernames for admin views", async () => {
|
||||
keys.create(userId, "ci");
|
||||
const other = await users.createUser("bob", "pw-bob", "member");
|
||||
keys.create(other.id, "deploy");
|
||||
const all = keys.listAll();
|
||||
expect(all).toHaveLength(2);
|
||||
expect(all.map((k) => k.username).sort()).toEqual(["alice", "bob"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,137 @@
|
||||
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
||||
import type Database from "better-sqlite3";
|
||||
|
||||
export const MAX_API_KEYS_PER_USER = 20;
|
||||
export const API_KEY_TOUCH_INTERVAL_MS = 60 * 60 * 1000; // 1 hour
|
||||
/** Visible prefix stored for list views, e.g. "tsmb_a1b2c3d4". */
|
||||
export const API_KEY_PREFIX_LENGTH = 12;
|
||||
|
||||
export interface ApiKeyRow {
|
||||
id: string;
|
||||
userId: string;
|
||||
name: string;
|
||||
keyPrefix: string;
|
||||
createdAt: number;
|
||||
lastUsedAt: number | null;
|
||||
}
|
||||
|
||||
export interface ApiKeyWithUser extends ApiKeyRow {
|
||||
username: string;
|
||||
}
|
||||
|
||||
export interface ApiKeyValidation {
|
||||
keyId: string;
|
||||
userId: string;
|
||||
username: string;
|
||||
role: "admin" | "member";
|
||||
}
|
||||
|
||||
export interface CreatedApiKey {
|
||||
key: ApiKeyRow;
|
||||
/** Plaintext key — returned exactly once, at creation time. */
|
||||
rawKey: string;
|
||||
}
|
||||
|
||||
export interface ApiKeyStore {
|
||||
/** Returns null when the per-user key cap is reached. */
|
||||
create(userId: string, name: string): CreatedApiKey | null;
|
||||
findById(id: string): ApiKeyWithUser | null;
|
||||
listForUser(userId: string): ApiKeyRow[];
|
||||
listAll(): ApiKeyWithUser[];
|
||||
/** With userId, only deletes a key owned by that user. */
|
||||
delete(id: string, userId?: string): boolean;
|
||||
deleteAllForUser(userId: string): void;
|
||||
validateAndTouch(rawKey: string): ApiKeyValidation | null;
|
||||
}
|
||||
|
||||
function hashKey(rawKey: string): string {
|
||||
return createHash("sha256").update(rawKey).digest("hex");
|
||||
}
|
||||
|
||||
export function createApiKeyStore(db: Database.Database): ApiKeyStore {
|
||||
const insertStmt = db.prepare(
|
||||
"INSERT INTO api_keys (id, userId, name, keyHash, keyPrefix, createdAt, lastUsedAt) VALUES (?, ?, ?, ?, ?, ?, NULL)"
|
||||
);
|
||||
const selectForUserStmt = db.prepare(
|
||||
"SELECT id, userId, name, keyPrefix, createdAt, lastUsedAt FROM api_keys WHERE userId = ? ORDER BY createdAt DESC"
|
||||
);
|
||||
const selectAllStmt = db.prepare(
|
||||
`SELECT k.id, k.userId, k.name, k.keyPrefix, k.createdAt, k.lastUsedAt, u.username
|
||||
FROM api_keys k INNER JOIN users u ON u.id = k.userId
|
||||
ORDER BY k.createdAt DESC`
|
||||
);
|
||||
const selectByIdStmt = db.prepare(
|
||||
`SELECT k.id, k.userId, k.name, k.keyPrefix, k.createdAt, k.lastUsedAt, u.username
|
||||
FROM api_keys k INNER JOIN users u ON u.id = k.userId
|
||||
WHERE k.id = ?`
|
||||
);
|
||||
const deleteStmt = db.prepare("DELETE FROM api_keys WHERE id = ?");
|
||||
const deleteAllForUserStmt = db.prepare("DELETE FROM api_keys WHERE userId = ?");
|
||||
const countForUserStmt = db.prepare("SELECT COUNT(*) AS n FROM api_keys WHERE userId = ?");
|
||||
const validateStmt = db.prepare(
|
||||
`SELECT k.id, k.userId, k.lastUsedAt, u.username, u.role
|
||||
FROM api_keys k INNER JOIN users u ON u.id = k.userId
|
||||
WHERE k.keyHash = ?`
|
||||
);
|
||||
const touchStmt = db.prepare("UPDATE api_keys SET lastUsedAt = ? WHERE id = ?");
|
||||
|
||||
return {
|
||||
create(userId, name) {
|
||||
const count = (countForUserStmt.get(userId) as { n: number }).n;
|
||||
if (count >= MAX_API_KEYS_PER_USER) {
|
||||
return null;
|
||||
}
|
||||
const rawKey = `tsmb_${randomBytes(32).toString("base64url")}`;
|
||||
const row: ApiKeyRow = {
|
||||
id: randomUUID(),
|
||||
userId,
|
||||
name,
|
||||
keyPrefix: rawKey.slice(0, API_KEY_PREFIX_LENGTH),
|
||||
createdAt: Date.now(),
|
||||
lastUsedAt: null,
|
||||
};
|
||||
insertStmt.run(row.id, row.userId, row.name, hashKey(rawKey), row.keyPrefix, row.createdAt);
|
||||
return { key: row, rawKey };
|
||||
},
|
||||
|
||||
findById(id) {
|
||||
return (selectByIdStmt.get(id) as ApiKeyWithUser | undefined) ?? null;
|
||||
},
|
||||
|
||||
listForUser(userId) {
|
||||
return selectForUserStmt.all(userId) as ApiKeyRow[];
|
||||
},
|
||||
|
||||
listAll() {
|
||||
return selectAllStmt.all() as ApiKeyWithUser[];
|
||||
},
|
||||
|
||||
delete(id, userId) {
|
||||
const row = selectByIdStmt.get(id) as ApiKeyRow | undefined;
|
||||
if (!row) return false;
|
||||
if (userId !== undefined && row.userId !== userId) return false;
|
||||
deleteStmt.run(id);
|
||||
return true;
|
||||
},
|
||||
|
||||
deleteAllForUser(userId) {
|
||||
deleteAllForUserStmt.run(userId);
|
||||
},
|
||||
|
||||
validateAndTouch(rawKey) {
|
||||
if (!rawKey) return null;
|
||||
const row = validateStmt.get(hashKey(rawKey)) as
|
||||
| { id: string; userId: string; lastUsedAt: number | null; username: string; role: string }
|
||||
| undefined;
|
||||
if (!row) return null;
|
||||
// The reserved guest principal must never authenticate via API keys;
|
||||
// guest access is session-only by design.
|
||||
if (row.role !== "admin" && row.role !== "member") return null;
|
||||
const now = Date.now();
|
||||
if (row.lastUsedAt === null || now - row.lastUsedAt > API_KEY_TOUCH_INTERVAL_MS) {
|
||||
touchStmt.run(now, row.id);
|
||||
}
|
||||
return { keyId: row.id, userId: row.userId, username: row.username, role: row.role };
|
||||
},
|
||||
};
|
||||
}
|
||||
+3
-1
@@ -7,7 +7,9 @@ export type AuditAction =
|
||||
| "user.password_reset"
|
||||
| "user.password_changed"
|
||||
| "user.role_changed"
|
||||
| "user.permissions_changed";
|
||||
| "user.permissions_changed"
|
||||
| "api_key.created"
|
||||
| "api_key.deleted";
|
||||
|
||||
export interface AuditEntry {
|
||||
id: number;
|
||||
|
||||
@@ -274,6 +274,13 @@ describe("config", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("retains a numeric QQ bitrate saved by an older settings API", () => {
|
||||
const dir = makeTmpDir();
|
||||
const path = join(dir, "config.json");
|
||||
writeFileSync(path, JSON.stringify({ audioQuality: { qq: 128 } }));
|
||||
expect(loadConfig(path).audioQuality.qq).toBe("128");
|
||||
});
|
||||
|
||||
it("creates config file on save", () => {
|
||||
const dir = makeTmpDir();
|
||||
const path = join(dir, "sub", "config.json");
|
||||
|
||||
+43
-4
@@ -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
|
||||
@@ -432,15 +469,15 @@ export function loadConfig(path: string): BotConfig {
|
||||
? (rawDefault as GateableProvider)
|
||||
: null;
|
||||
|
||||
// audioQuality → per-provider strings; each field falls back to its default
|
||||
// when missing/blank/non-string (a hand-edited/legacy config must never smuggle
|
||||
// a non-string past the gate — the value is fed straight to provider.setQuality).
|
||||
// Normalize the two numeric QQ bitrates accepted by older settings APIs.
|
||||
// Other missing, blank or non-string qualities use provider defaults.
|
||||
const partialAq = (partial.audioQuality ?? {}) as Partial<AudioQualityConfig>;
|
||||
const coerceQuality = (v: unknown, fallback: string): string =>
|
||||
typeof v === "string" && v.trim() ? v : fallback;
|
||||
const qqQuality: unknown = partialAq.qq;
|
||||
const audioQuality: AudioQualityConfig = {
|
||||
netease: coerceQuality(partialAq.netease, defaults.audioQuality.netease),
|
||||
qq: coerceQuality(partialAq.qq, defaults.audioQuality.qq),
|
||||
qq: qqQuality === 128 || qqQuality === 320 ? String(qqQuality) : coerceQuality(qqQuality, defaults.audioQuality.qq),
|
||||
bilibili: coerceQuality(partialAq.bilibili, defaults.audioQuality.bilibili),
|
||||
kugou: coerceQuality(partialAq.kugou, defaults.audioQuality.kugou),
|
||||
jellyfin: coerceQuality(partialAq.jellyfin, defaults.audioQuality.jellyfin),
|
||||
@@ -456,7 +493,9 @@ export function loadConfig(path: string): BotConfig {
|
||||
audioQuality,
|
||||
enabledProviders,
|
||||
savedQueuesEnabled,
|
||||
perUserMusicAccounts,
|
||||
playKeepsQueue,
|
||||
playUrlRetries,
|
||||
voiceDucking,
|
||||
defaultPlatform: defaultPlatformPref,
|
||||
};
|
||||
|
||||
@@ -37,13 +37,35 @@ describe("database", () => {
|
||||
|
||||
const userCols = botDb.db.prepare("PRAGMA table_info(users)").all() as Array<{ name: string }>;
|
||||
const userColNames = userCols.map((c) => c.name).sort();
|
||||
expect(userColNames).toEqual(["createdAt", "id", "passwordHash", "role", "updatedAt", "username"]);
|
||||
expect(userColNames).toEqual(["accentColor", "createdAt", "id", "passwordHash", "role", "updatedAt", "username"]);
|
||||
|
||||
const sessionCols = botDb.db.prepare("PRAGMA table_info(sessions)").all() as Array<{ name: string }>;
|
||||
const sessionColNames = sessionCols.map((c) => c.name).sort();
|
||||
expect(sessionColNames).toEqual(["createdAt", "expiresAt", "id", "lastSeenAt", "userId"]);
|
||||
});
|
||||
|
||||
it("migrates existing accounts and preserves their accent across database reopen", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'tsmb-accent-'));
|
||||
const path = join(dir, 'test.db');
|
||||
let db = createDatabase(path);
|
||||
try {
|
||||
const user = await createUserStore(db.db).createUser('alice', 'test-password', 'member');
|
||||
db.db.exec('ALTER TABLE users DROP COLUMN accentColor');
|
||||
db.close();
|
||||
db = createDatabase(path);
|
||||
const users = createUserStore(db.db);
|
||||
expect(users.getAccentColor(user.id)).toBe('#335eea');
|
||||
users.setAccentColor(user.id, '#0891b2');
|
||||
db.close();
|
||||
db = createDatabase(path);
|
||||
expect(createUserStore(db.db).getAccentColor(user.id)).toBe('#0891b2');
|
||||
expect(createUserStore(db.db).findById(user.id)?.username).toBe('alice');
|
||||
} finally {
|
||||
db.close();
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("creates user_audit table on init", () => {
|
||||
const tables = botDb.db
|
||||
.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")
|
||||
@@ -345,3 +367,36 @@ describe("guest principal migration", () => {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe("user music cookies (#164)", () => {
|
||||
let botDb: BotDatabase;
|
||||
const addUser = (id: string) =>
|
||||
botDb.db
|
||||
.prepare("INSERT INTO users (id, username, passwordHash, createdAt, updatedAt, role) VALUES (?,?,?,?,?,?)")
|
||||
.run(id, id, "x", 0, 0, "member");
|
||||
|
||||
beforeEach(() => {
|
||||
botDb = createDatabase(":memory:");
|
||||
addUser("u1");
|
||||
addUser("u2");
|
||||
});
|
||||
afterEach(() => botDb.close());
|
||||
|
||||
it("stores, overwrites and deletes a cookie per user and platform", () => {
|
||||
expect(botDb.getUserMusicCookie("u1", "netease")).toBeNull();
|
||||
botDb.setUserMusicCookie("u1", "netease", "MUSIC_U=a");
|
||||
botDb.setUserMusicCookie("u1", "netease", "MUSIC_U=b");
|
||||
expect(botDb.getUserMusicCookie("u1", "netease")).toBe("MUSIC_U=b");
|
||||
expect(botDb.getUserMusicCookie("u2", "netease")).toBeNull();
|
||||
expect(botDb.getUserMusicCookie("u1", "qq")).toBeNull();
|
||||
expect(botDb.deleteUserMusicCookie("u1", "netease")).toBe(true);
|
||||
expect(botDb.deleteUserMusicCookie("u1", "netease")).toBe(false);
|
||||
expect(botDb.getUserMusicCookie("u1", "netease")).toBeNull();
|
||||
});
|
||||
|
||||
it("drops a user's cookies when the user is deleted", () => {
|
||||
botDb.setUserMusicCookie("u1", "netease", "MUSIC_U=a");
|
||||
botDb.db.prepare("DELETE FROM users WHERE id = ?").run("u1");
|
||||
expect(botDb.getUserMusicCookie("u1", "netease")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
@@ -144,6 +197,58 @@ export interface BotDatabase {
|
||||
removeFavorite(userId: string, playlistId: string, platform: string): boolean;
|
||||
getFavorites(userId: string): FavoritePlaylist[];
|
||||
isFavorited(userId: string, playlistId: string, platform: string): boolean;
|
||||
// Per-user music account cookies (#164).
|
||||
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[];
|
||||
@@ -206,6 +311,9 @@ function migrateSchema(db: Database.Database): void {
|
||||
if (!userColNames.includes("role")) {
|
||||
db.exec("ALTER TABLE users ADD COLUMN role TEXT NOT NULL DEFAULT 'admin'");
|
||||
}
|
||||
if (!userColNames.includes("accentColor")) {
|
||||
db.exec("ALTER TABLE users ADD COLUMN accentColor TEXT NOT NULL DEFAULT '#335eea'");
|
||||
}
|
||||
|
||||
const historyColumns = db.prepare("PRAGMA table_info(play_history)").all() as Array<{ name: string }>;
|
||||
const historyColNames = historyColumns.map((c) => c.name);
|
||||
@@ -268,6 +376,18 @@ function initTables(db: Database.Database): void {
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_userId ON sessions(userId);
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_expiresAt ON sessions(expiresAt);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS api_keys (
|
||||
id TEXT PRIMARY KEY,
|
||||
userId TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
keyHash TEXT NOT NULL UNIQUE,
|
||||
keyPrefix TEXT NOT NULL,
|
||||
createdAt INTEGER NOT NULL,
|
||||
lastUsedAt INTEGER,
|
||||
FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_api_keys_userId ON api_keys(userId);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_audit (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
timestamp INTEGER NOT NULL,
|
||||
@@ -328,6 +448,63 @@ function initTables(db: Database.Database): void {
|
||||
fmPlatform TEXT NOT NULL DEFAULT '',
|
||||
updatedAt TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
-- A web user's own music-platform login (#164), used for their personal
|
||||
-- FM instead of the bot's shared account. Secret: never sent to clients.
|
||||
CREATE TABLE IF NOT EXISTS user_music_cookies (
|
||||
userId TEXT NOT NULL,
|
||||
platform TEXT NOT NULL,
|
||||
cookie TEXT NOT NULL,
|
||||
updatedAt TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
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);
|
||||
`);
|
||||
}
|
||||
|
||||
@@ -386,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)
|
||||
@@ -453,6 +634,139 @@ export function createDatabase(dbPath: string): BotDatabase {
|
||||
SELECT 1 FROM favorite_playlists WHERE userId = ? AND playlistId = ? AND platform = ?
|
||||
`);
|
||||
|
||||
const selectUserMusicCookie = db.prepare(
|
||||
`SELECT cookie FROM user_music_cookies WHERE userId = ? AND platform = ?`,
|
||||
);
|
||||
const upsertUserMusicCookie = db.prepare(`
|
||||
INSERT INTO user_music_cookies (userId, platform, cookie) VALUES (?, ?, ?)
|
||||
ON CONFLICT(userId, platform) DO UPDATE SET cookie = excluded.cookie, updatedAt = datetime('now')
|
||||
`);
|
||||
const deleteUserMusicCookieStmt = db.prepare(
|
||||
`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[] => {
|
||||
@@ -525,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,
|
||||
@@ -634,6 +964,111 @@ export function createDatabase(dbPath: string): BotDatabase {
|
||||
return row !== undefined;
|
||||
},
|
||||
|
||||
getUserMusicCookie(userId, platform) {
|
||||
const row = selectUserMusicCookie.get(userId, platform) as { cookie: string } | undefined;
|
||||
return row?.cookie ?? null;
|
||||
},
|
||||
|
||||
setUserMusicCookie(userId, platform, cookie) {
|
||||
upsertUserMusicCookie.run(userId, platform, cookie);
|
||||
},
|
||||
|
||||
deleteUserMusicCookie(userId, platform) {
|
||||
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}`);
|
||||
|
||||
@@ -22,6 +22,8 @@ export interface UserRow {
|
||||
}
|
||||
|
||||
export interface UserStore {
|
||||
getAccentColor(userId: string): string;
|
||||
setAccentColor(userId: string, color: string): boolean;
|
||||
countUsers(): number;
|
||||
countAdmins(): number;
|
||||
createUser(username: string, password: string, role: UserRole): Promise<UserRow>;
|
||||
@@ -68,6 +70,12 @@ export function createUserStore(db: Database.Database): UserStore {
|
||||
const deleteUserStmt = db.prepare("DELETE FROM users WHERE id = ?");
|
||||
|
||||
return {
|
||||
getAccentColor(userId) {
|
||||
return (db.prepare("SELECT accentColor FROM users WHERE id = ?").get(userId) as { accentColor: string } | undefined)?.accentColor ?? "#335eea";
|
||||
},
|
||||
setAccentColor(userId, color) {
|
||||
return db.prepare("UPDATE users SET accentColor = ?, updatedAt = ? WHERE id = ? AND role != 'guest'").run(color, Date.now(), userId).changes > 0;
|
||||
},
|
||||
countUsers() {
|
||||
return (countStmt.get() as { n: number }).n;
|
||||
},
|
||||
|
||||
+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, apiServer.assertQqMusicApiPort);
|
||||
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,30 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
describe("application log errors", () => {
|
||||
it("preserves HTTP diagnostics while omitting Axios request and response data", () => {
|
||||
const child = spawnSync(process.execPath, [
|
||||
"--import", "tsx", "--input-type=module", "--eval", `
|
||||
import { AxiosError } from "axios";
|
||||
import { createLogger } from "./src/logger.ts";
|
||||
|
||||
const config = { params: { cookie: "sample-request-cookie" } };
|
||||
const response = { status: 400, data: { code: -460, cookie: "sample-response-cookie" } };
|
||||
const err = new AxiosError("sample-sensitive-url", "ERR_BAD_REQUEST", config, undefined, response);
|
||||
const log = createLogger().child({ component: "test" });
|
||||
log.warn({ err }, "Provider failed");
|
||||
log.error({ reason: err }, "Unhandled rejection");
|
||||
log.error(new Error("ordinary error"));
|
||||
`,
|
||||
], { cwd: fileURLToPath(new URL("..", import.meta.url)), encoding: "utf8" });
|
||||
|
||||
expect(child.status, child.stderr).toBe(0);
|
||||
const [provider, rejection, ordinary] = child.stdout.trim().split("\n").map(line => JSON.parse(line));
|
||||
const expected = { type: "AxiosError", code: "ERR_BAD_REQUEST", status: 400, upstreamCode: -460 };
|
||||
expect(provider.err).toMatchObject(expected);
|
||||
expect(rejection.reason).toMatchObject(expected);
|
||||
expect(child.stdout).not.toContain("sample-");
|
||||
expect(ordinary.err.message).toBe("ordinary error");
|
||||
});
|
||||
});
|
||||
+20
-2
@@ -1,12 +1,30 @@
|
||||
import pino from "pino";
|
||||
import { isAxiosError } from "axios";
|
||||
import { mkdirSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
export type Logger = pino.Logger;
|
||||
|
||||
function serializeHttpError(error: unknown): unknown {
|
||||
if (!isAxiosError<{ code?: unknown }>(error)) {
|
||||
return error instanceof Error ? pino.stdSerializers.err(error) : error;
|
||||
}
|
||||
const upstreamCode = error.response?.data?.code;
|
||||
return {
|
||||
type: "AxiosError",
|
||||
code: error.code,
|
||||
status: error.response?.status ?? error.status,
|
||||
upstreamCode: typeof upstreamCode === "number" ? upstreamCode : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
// Axios errors include the original request configuration and may contain
|
||||
// session cookies, authorization headers or secrets in the request URL.
|
||||
const serializers = { err: serializeHttpError, reason: serializeHttpError };
|
||||
|
||||
export function createLogger(logDir?: string): Logger {
|
||||
if (!logDir) {
|
||||
return pino({ level: "info" });
|
||||
return pino({ level: "info", serializers });
|
||||
}
|
||||
|
||||
mkdirSync(logDir, { recursive: true });
|
||||
@@ -32,5 +50,5 @@ export function createLogger(logDir?: string): Logger {
|
||||
console.error("Logger transport error:", err);
|
||||
});
|
||||
|
||||
return pino({ level: "debug" }, transport);
|
||||
return pino({ level: "debug", serializers }, transport);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { Server } from "node:http";
|
||||
import { closeEmbeddedApi, getSafeApiStartupError, startEmbeddedApi, type ApiChildMessage, type ApiProvider } from "./api-server-runtime.js";
|
||||
|
||||
const providerArg = process.argv[2];
|
||||
const port = Number(process.argv[3]);
|
||||
if ((providerArg !== "netease" && providerArg !== "qq") || !Number.isInteger(port) || port < 1 || port > 65535 || !process.send) process.exit(1);
|
||||
const provider = providerArg as ApiProvider;
|
||||
let server: Server | null = null;
|
||||
let stopping = false;
|
||||
|
||||
function shutdown(exitCode = 0): void {
|
||||
if (stopping) return;
|
||||
stopping = true;
|
||||
// Also covers a legacy auto-start listener and an import still in flight.
|
||||
const deadline = setTimeout(() => process.exit(exitCode), 1000);
|
||||
closeEmbeddedApi(server).finally(() => { clearTimeout(deadline); process.exit(exitCode); });
|
||||
}
|
||||
|
||||
function fail(error: unknown): void {
|
||||
if (stopping) return;
|
||||
const message: ApiChildMessage = { type: "error", provider, port, ...getSafeApiStartupError(error) };
|
||||
if (!process.connected) { shutdown(1); return; }
|
||||
try { process.send!(message, () => shutdown(1)); }
|
||||
catch { shutdown(1); }
|
||||
}
|
||||
|
||||
process.on("message", (message: unknown) => {
|
||||
if (message && typeof message === "object" && (message as { type?: unknown }).type === "stop") shutdown();
|
||||
});
|
||||
process.on("disconnect", () => shutdown());
|
||||
process.on("SIGTERM", () => shutdown());
|
||||
process.on("SIGINT", () => shutdown());
|
||||
process.on("uncaughtException", fail);
|
||||
process.on("unhandledRejection", fail);
|
||||
|
||||
startEmbeddedApi(provider, port).then((runtime) => {
|
||||
server = runtime.server;
|
||||
if (stopping || !process.connected) { shutdown(); return; }
|
||||
server?.on("error", fail);
|
||||
const message: ApiChildMessage = { type: "ready", provider, port };
|
||||
try { process.send!(message, (error) => { if (error) shutdown(1); }); }
|
||||
catch { shutdown(1); }
|
||||
}).catch(fail);
|
||||
@@ -0,0 +1,95 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { closeEmbeddedApi, getSafeApiStartupError, startEmbeddedApi } from "./api-server-runtime.js";
|
||||
|
||||
const state = vi.hoisted(() => ({ serveNcmApi: vi.fn(), qqExport: null as any, portFree: true }));
|
||||
vi.mock("NeteaseCloudMusicApi", () => ({ server: { serveNcmApi: state.serveNcmApi } }));
|
||||
vi.mock("@sansenjian/qq-music-api", () => ({ get default() { return state.qqExport; } }));
|
||||
vi.mock("node:net", async () => {
|
||||
const { EventEmitter } = await import("node:events");
|
||||
return { default: { createServer: () => {
|
||||
const probe = new EventEmitter() as EventEmitter & { close(done: () => void): void; listen(): void };
|
||||
probe.close = (done) => queueMicrotask(done);
|
||||
probe.listen = () => queueMicrotask(() => probe.emit(state.portFree ? "listening" : "error"));
|
||||
return probe;
|
||||
} } };
|
||||
});
|
||||
|
||||
class FakeServer extends EventEmitter {
|
||||
listening = false;
|
||||
close = vi.fn((done: () => void) => { this.listening = false; queueMicrotask(done); return this; });
|
||||
closeAllConnections = vi.fn();
|
||||
}
|
||||
|
||||
describe("embedded API runtime", () => {
|
||||
let server: FakeServer;
|
||||
let listen: ReturnType<typeof vi.fn>;
|
||||
let previousPort: string | undefined;
|
||||
beforeEach(() => {
|
||||
previousPort = process.env.PORT;
|
||||
server = new FakeServer();
|
||||
state.portFree = true;
|
||||
state.serveNcmApi.mockReset();
|
||||
state.serveNcmApi.mockResolvedValue({ server });
|
||||
listen = vi.fn(() => { queueMicrotask(() => { server.listening = true; server.emit("listening"); }); return server; });
|
||||
state.qqExport = { listen };
|
||||
});
|
||||
afterEach(() => { if (previousPort === undefined) delete process.env.PORT; else process.env.PORT = previousPort; vi.restoreAllMocks(); });
|
||||
|
||||
it("binds NetEase to loopback/configured port without version checks and waits for listening", async () => {
|
||||
let ready = false;
|
||||
const starting = startEmbeddedApi("netease", 39218).then((result) => { ready = true; return result; });
|
||||
await vi.waitFor(() => expect(server.listenerCount("listening")).toBe(1));
|
||||
expect(state.serveNcmApi).toHaveBeenCalledWith({ port: 39218, host: "127.0.0.1", checkVersion: false });
|
||||
expect(ready).toBe(false);
|
||||
server.listening = true; server.emit("listening");
|
||||
expect((await starting).server).toBe(server);
|
||||
});
|
||||
it("closes the HTTP server returned by NetEase rather than the Express app", async () => {
|
||||
server.listening = true;
|
||||
const runtime = await startEmbeddedApi("netease", 39218);
|
||||
await closeEmbeddedApi(runtime.server);
|
||||
expect(server.close).toHaveBeenCalledTimes(1);
|
||||
expect(server.closeAllConnections).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it("rejects failed listening and cleans up the startup handle", async () => {
|
||||
const starting = startEmbeddedApi("netease", 39218);
|
||||
const rejected = expect(starting).rejects.toMatchObject({ code: "EADDRINUSE" });
|
||||
await vi.waitFor(() => expect(server.listenerCount("error")).toBe(1));
|
||||
server.emit("error", Object.assign(new Error("bind failure"), { code: "EADDRINUSE" }));
|
||||
await rejected;
|
||||
expect(server.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it("binds QQ to its configured loopback port and restores injected PORT", async () => {
|
||||
process.env.PORT = "39999";
|
||||
expect((await startEmbeddedApi("qq", 39217)).server).toBe(server);
|
||||
expect(listen).toHaveBeenCalledWith(39217, "127.0.0.1");
|
||||
expect(process.env.PORT).toBe("39999");
|
||||
});
|
||||
it("restores an absent PORT and supports the legacy nested export", async () => {
|
||||
delete process.env.PORT; state.qqExport = { default: { listen } };
|
||||
await startEmbeddedApi("qq", 39217);
|
||||
expect(process.env.PORT).toBeUndefined();
|
||||
expect(listen).toHaveBeenCalledWith(39217, "127.0.0.1");
|
||||
});
|
||||
it("reuses a legacy module that auto-started on import without a duplicate listen", async () => {
|
||||
state.portFree = false;
|
||||
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(JSON.stringify({ data: { message: "no songmid" } }), {
|
||||
status: 400, headers: { "Content-Type": "application/json" },
|
||||
}));
|
||||
expect(await startEmbeddedApi("qq", 39217)).toEqual({ server: null });
|
||||
expect(listen).not.toHaveBeenCalled();
|
||||
});
|
||||
it("reports an occupied port if another service bound it during import", async () => {
|
||||
state.portFree = false;
|
||||
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("not QQ", { status: 200 }));
|
||||
await expect(startEmbeddedApi("qq", 39217)).rejects.toMatchObject({ code: "EADDRINUSE" });
|
||||
expect(listen).not.toHaveBeenCalled();
|
||||
});
|
||||
it("never reflects arbitrary startup message, stack or code values", () => {
|
||||
expect(getSafeApiStartupError({ message: "synthetic-credential", stack: "synthetic-credential", code: "synthetic-credential" })).toEqual({ category: "startup" });
|
||||
expect(getSafeApiStartupError({ code: "ERR_REQUIRE_ESM", message: "synthetic-credential" })).toEqual({ category: "esm", code: "ERR_REQUIRE_ESM" });
|
||||
expect(getSafeApiStartupError({ code: "EBADENGINE" })).toEqual({ category: "node-engine", code: "EBADENGINE" });
|
||||
expect(getSafeApiStartupError({ code: "EADDRINUSE" })).toEqual({ category: "port-in-use", code: "EADDRINUSE" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,127 @@
|
||||
import net from "node:net";
|
||||
import type { Server } from "node:http";
|
||||
|
||||
export type ApiProvider = "netease" | "qq";
|
||||
export type ApiStartupCategory = "esm" | "node-engine" | "port-in-use" | "startup" | "timeout" | "cancelled";
|
||||
export interface SafeApiStartupError { category: ApiStartupCategory; code?: string }
|
||||
export type ApiChildMessage =
|
||||
| { type: "ready"; provider: ApiProvider; port: number }
|
||||
| ({ type: "error"; provider: ApiProvider; port: number } & SafeApiStartupError);
|
||||
|
||||
const SAFE_ERROR_CODES = new Set(["ERR_REQUIRE_ESM", "EBADENGINE", "EADDRINUSE", "EACCES", "ENOENT", "MODULE_NOT_FOUND", "ERR_MODULE_NOT_FOUND"]);
|
||||
export function safeApiErrorCode(code: unknown): string | undefined {
|
||||
return typeof code === "string" && SAFE_ERROR_CODES.has(code) ? code : undefined;
|
||||
}
|
||||
|
||||
/** Classification may inspect a message locally, but IPC never contains it. */
|
||||
export function getSafeApiStartupError(err: unknown): SafeApiStartupError {
|
||||
const error = (err ?? {}) as { code?: unknown; message?: unknown };
|
||||
const code = safeApiErrorCode(error.code);
|
||||
const message = typeof error.message === "string" ? error.message : "";
|
||||
let category: ApiStartupCategory = "startup";
|
||||
if (code === "ERR_REQUIRE_ESM" || /ERR_REQUIRE_ESM|require\(\) of ES ?Module/i.test(message)) category = "esm";
|
||||
else if (code === "EBADENGINE" || /Unsupported engine|EBADENGINE|requires Node|Node\.js version/i.test(message)) category = "node-engine";
|
||||
else if (code === "EADDRINUSE") category = "port-in-use";
|
||||
return code ? { category, code } : { category };
|
||||
}
|
||||
|
||||
export function isApiPortFree(port: number): Promise<boolean> {
|
||||
return new Promise((resolve) => {
|
||||
const server = net.createServer();
|
||||
server.once("error", () => server.close(() => resolve(false)));
|
||||
server.once("listening", () => server.close(() => resolve(true)));
|
||||
server.listen(port, "127.0.0.1");
|
||||
});
|
||||
}
|
||||
|
||||
/** Identify the QQ wrapper without credentials or a request to QQ upstream. */
|
||||
export async function isQqMusicApi(port: number): Promise<boolean> {
|
||||
try {
|
||||
const response = await fetch(`http://127.0.0.1:${port}/getMusicPlay`, {
|
||||
redirect: "manual",
|
||||
signal: AbortSignal.timeout(2_000),
|
||||
});
|
||||
if (response.status !== 400 || !response.headers.get("content-type")?.includes("application/json")) {
|
||||
await response.body?.cancel();
|
||||
return false;
|
||||
}
|
||||
const reader = response.body?.getReader();
|
||||
if (!reader) return false;
|
||||
const buffer = Buffer.alloc(1024);
|
||||
let length = 0;
|
||||
try {
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
if (length + value.length > buffer.length) return false;
|
||||
buffer.set(value, length);
|
||||
length += value.length;
|
||||
}
|
||||
} finally {
|
||||
await reader.cancel();
|
||||
}
|
||||
return JSON.parse(buffer.toString("utf8", 0, length))?.data?.message === "no songmid";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function waitForListening(server: Server): Promise<void> {
|
||||
if (server.listening) return Promise.resolve();
|
||||
return new Promise((resolve, reject) => {
|
||||
const ready = () => { cleanup(); resolve(); };
|
||||
const failed = (error: Error) => { cleanup(); reject(error); };
|
||||
const cleanup = () => { server.off("listening", ready); server.off("error", failed); };
|
||||
server.once("listening", ready);
|
||||
server.once("error", failed);
|
||||
});
|
||||
}
|
||||
|
||||
export async function closeEmbeddedApi(server: Server | null): Promise<void> {
|
||||
if (!server) return;
|
||||
await new Promise<void>((resolve) => {
|
||||
try {
|
||||
server.close(() => resolve());
|
||||
server.closeAllConnections?.();
|
||||
} catch { resolve(); }
|
||||
});
|
||||
}
|
||||
|
||||
/** Only call in the isolated child: these dependencies write raw request URLs
|
||||
* and response cookies directly to console, outside the bot's logger. */
|
||||
export async function startEmbeddedApi(provider: ApiProvider, port: number): Promise<{ server: Server | null }> {
|
||||
let server: Server | null = null;
|
||||
try {
|
||||
if (provider === "netease") {
|
||||
const imported = await import("NeteaseCloudMusicApi") as any;
|
||||
const api = imported.server ?? imported.default?.server;
|
||||
const app = await api.serveNcmApi({ port, host: "127.0.0.1", checkVersion: false });
|
||||
server = app.server;
|
||||
if (!server) throw new Error("NetEase API did not expose its HTTP server");
|
||||
} else {
|
||||
const previousPort = process.env.PORT;
|
||||
process.env.PORT = String(port);
|
||||
let imported: any;
|
||||
try { imported = await import("@sansenjian/qq-music-api"); }
|
||||
finally {
|
||||
if (previousPort === undefined) delete process.env.PORT;
|
||||
else process.env.PORT = previousPort;
|
||||
}
|
||||
const candidate = imported.default ?? imported;
|
||||
const app = typeof candidate.listen === "function" ? candidate : candidate.default;
|
||||
if (!app || typeof app.listen !== "function") throw new Error("QQ API did not expose a Koa app");
|
||||
// Historical packages listened during import. Their listener remains
|
||||
// owned by this child and closes when the child exits.
|
||||
if (!(await isApiPortFree(port))) {
|
||||
if (await isQqMusicApi(port)) return { server: null };
|
||||
throw Object.assign(new Error("QQ Music API port is occupied"), { code: "EADDRINUSE" });
|
||||
}
|
||||
server = app.listen(port, "127.0.0.1");
|
||||
}
|
||||
await waitForListening(server!);
|
||||
return { server };
|
||||
} catch (error) {
|
||||
await closeEmbeddedApi(server);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
+182
-112
@@ -1,133 +1,203 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { EventEmitter } from "node:events";
|
||||
import type { ChildProcess } from "node:child_process";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { createApiServerManager, describeQqApiStartupError } from "./api-server.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
|
||||
// Record every listen() the QQ sidecar makes so we can assert it is always
|
||||
// pinned to the configured port (regression coverage for issue #122).
|
||||
const mockState = vi.hoisted(() => ({
|
||||
listenCalls: [] as Array<{ port: number; host: string }>,
|
||||
}));
|
||||
|
||||
vi.mock("@sansenjian/qq-music-api", () => {
|
||||
const app = {
|
||||
listen(port: number, host: string, cb?: () => void) {
|
||||
mockState.listenCalls.push({ port, host });
|
||||
const server = {
|
||||
address: () => ({ port, address: host, family: "IPv4" as const }),
|
||||
on() {
|
||||
return server;
|
||||
},
|
||||
close(done?: () => void) {
|
||||
done?.();
|
||||
},
|
||||
};
|
||||
// Real net/Koa fire the listening callback on a later tick, after the
|
||||
// caller has captured the returned server handle.
|
||||
if (cb) setImmediate(cb);
|
||||
return server;
|
||||
},
|
||||
};
|
||||
return { default: app };
|
||||
const state = vi.hoisted(() => ({ fork: vi.fn(), probes: [] as EventEmitter[], probeAutomatically: true, portFree: true, directImports: 0 }));
|
||||
vi.mock("node:child_process", () => ({ fork: state.fork }));
|
||||
vi.mock("node:net", async () => {
|
||||
const { EventEmitter } = await import("node:events");
|
||||
return { default: { createServer: () => {
|
||||
const probe = new EventEmitter() as EventEmitter & { close(done: () => void): void; listen(): void };
|
||||
probe.close = (done) => queueMicrotask(done);
|
||||
probe.listen = () => {
|
||||
state.probes.push(probe);
|
||||
if (state.probeAutomatically) queueMicrotask(() => probe.emit(state.portFree ? "listening" : "error"));
|
||||
};
|
||||
return probe;
|
||||
} } };
|
||||
});
|
||||
vi.mock("@sansenjian/qq-music-api", () => {
|
||||
state.directImports++;
|
||||
return { default: { listen: () => { throw new Error("sidecar imported in parent"); } } };
|
||||
});
|
||||
vi.mock("NeteaseCloudMusicApi", () => {
|
||||
state.directImports++;
|
||||
return { server: { serveNcmApi: () => { throw new Error("sidecar imported in parent"); } } };
|
||||
});
|
||||
|
||||
class FakeChild extends EventEmitter {
|
||||
connected = true;
|
||||
exitOnStop = true;
|
||||
send = vi.fn((message: { type: string }) => {
|
||||
if (message.type === "stop" && this.exitOnStop) queueMicrotask(() => this.finish(0, null));
|
||||
return true;
|
||||
});
|
||||
kill = vi.fn((signal: string = "SIGTERM") => { queueMicrotask(() => this.finish(null, signal)); return true; });
|
||||
finish(code: number | null, signal: string | null) { this.connected = false; this.emit("exit", code, signal); }
|
||||
}
|
||||
|
||||
describe("describeQqApiStartupError", () => {
|
||||
it("flags ERR_REQUIRE_ESM by error code with version-pin guidance", () => {
|
||||
const hint = describeQqApiStartupError({ code: "ERR_REQUIRE_ESM", message: "..." });
|
||||
expect(hint).toMatch(/ERR_REQUIRE_ESM/);
|
||||
expect(hint).toMatch(/~2\.4\.0/);
|
||||
expect(hint).toMatch(/~2\.2\.10/);
|
||||
it("retains ESM diagnostics by code and message", () => {
|
||||
expect(describeQqApiStartupError({ code: "ERR_REQUIRE_ESM" })).toMatch(/~2\.4\.0/);
|
||||
expect(describeQqApiStartupError(new Error("require() of ES Module is unsupported"))).toMatch(/ERR_REQUIRE_ESM/);
|
||||
});
|
||||
|
||||
it("flags ERR_REQUIRE_ESM by message when the code is absent", () => {
|
||||
const hint = describeQqApiStartupError(
|
||||
new Error("require() of ES Module .../@sansenjian/qq-music-api/dist/index.js not supported")
|
||||
);
|
||||
expect(hint).toMatch(/incompatible @sansenjian\/qq-music-api/);
|
||||
});
|
||||
|
||||
it("flags a Node engine mismatch with a Node-upgrade hint", () => {
|
||||
const hint = describeQqApiStartupError(new Error("Unsupported engine: requires Node >=20.17"));
|
||||
expect(hint).toMatch(/Node >=20\.17/);
|
||||
expect(hint).toMatch(/~2\.2\.10/);
|
||||
});
|
||||
|
||||
it("returns null for an unrelated startup error (falls back to the generic warning)", () => {
|
||||
expect(describeQqApiStartupError(new Error("EADDRINUSE: port in use"))).toBeNull();
|
||||
expect(describeQqApiStartupError(undefined)).toBeNull();
|
||||
expect(describeQqApiStartupError(null)).toBeNull();
|
||||
it("retains engine diagnostics and ignores unrelated failures", () => {
|
||||
expect(describeQqApiStartupError(new Error("Unsupported engine: requires Node >=20.17"))).toMatch(/Node >=20\.17/);
|
||||
expect(describeQqApiStartupError(new Error("EADDRINUSE"))).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// Regression coverage for issue #122: the QQ Music API sidecar must listen on
|
||||
// the same port the client base URL targets (config.qqMusicApiPort). A stale
|
||||
// build once bound 3300 while the client requested 3200, silently breaking the
|
||||
// QQ login QR / search flow with ECONNREFUSED on 127.0.0.1:3200.
|
||||
describe("createApiServerManager — QQ sidecar port binding", () => {
|
||||
const noopLogger = {
|
||||
info() {},
|
||||
warn() {},
|
||||
error() {},
|
||||
debug() {},
|
||||
trace() {},
|
||||
fatal() {},
|
||||
} as unknown as Logger;
|
||||
|
||||
describe("embedded API child lifecycle", () => {
|
||||
let children: FakeChild[];
|
||||
let logger: Logger;
|
||||
let manager: ReturnType<typeof createApiServerManager>;
|
||||
let automaticReady: boolean;
|
||||
const options = { neteasePort: 39218, qqMusicPort: 39217, neteaseEnabled: true, qqEnabled: true };
|
||||
const flush = async () => { for (let i = 0; i < 12; i++) await Promise.resolve(); };
|
||||
beforeEach(() => {
|
||||
mockState.listenCalls = [];
|
||||
vi.useRealTimers(); children = []; automaticReady = true;
|
||||
state.probes = []; state.portFree = true; state.probeAutomatically = true; state.fork.mockReset();
|
||||
state.fork.mockImplementation((_entry: string, args: string[]) => {
|
||||
const child = new FakeChild(); children.push(child);
|
||||
if (automaticReady) queueMicrotask(() => child.emit("message", { type: "ready", provider: args[0], port: Number(args[1]) }));
|
||||
return child as unknown as ChildProcess;
|
||||
});
|
||||
logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() } as unknown as Logger;
|
||||
manager = createApiServerManager(options, logger);
|
||||
});
|
||||
afterEach(async () => { manager.stop(); await flush(); vi.useRealTimers(); vi.restoreAllMocks(); });
|
||||
|
||||
it("listens on the configured qqMusicPort and exposes a matching base URL", async () => {
|
||||
const port = 39217; // uncommon port to avoid clashing with a real instance
|
||||
const manager = createApiServerManager(
|
||||
{ neteasePort: 39218, qqMusicPort: port, neteaseEnabled: false, qqEnabled: true },
|
||||
noopLogger
|
||||
);
|
||||
it("isolates both APIs with ignored stdio, configured ports and IPC", async () => {
|
||||
await manager.start();
|
||||
manager.stop();
|
||||
|
||||
expect(manager.getQQMusicBaseUrl()).toBe(`http://127.0.0.1:${port}`);
|
||||
expect(mockState.listenCalls).toEqual([{ port, host: "127.0.0.1" }]);
|
||||
expect(state.fork).toHaveBeenCalledTimes(2);
|
||||
expect(state.fork.mock.calls.map((call) => call[1])).toEqual([["netease", "39218"], ["qq", "39217"]]);
|
||||
for (const call of state.fork.mock.calls) {
|
||||
expect(String(call[0])).toMatch(/api-server-child\.ts$/);
|
||||
expect(call[2].stdio).toEqual(["ignore", "ignore", "ignore", "ipc"]);
|
||||
expect(call[2].execArgv).not.toContain("--eval");
|
||||
expect(call[2].execArgv).not.toContain("--input-type=module");
|
||||
}
|
||||
expect(state.directImports).toBe(0);
|
||||
expect(manager.getNeteaseBaseUrl()).toBe("http://127.0.0.1:39218");
|
||||
expect(manager.getQQMusicBaseUrl()).toBe("http://127.0.0.1:39217");
|
||||
});
|
||||
|
||||
it("follows qqMusicPort — not an injected PORT — and restores PORT afterwards", async () => {
|
||||
const port = 39219;
|
||||
const previous = process.env.PORT;
|
||||
// Simulate a hosting platform / compose file injecting a stray PORT that
|
||||
// must NOT leak into the QQ sidecar's chosen port.
|
||||
process.env.PORT = "39999";
|
||||
const manager = createApiServerManager(
|
||||
{ neteasePort: 39220, qqMusicPort: port, neteaseEnabled: false, qqEnabled: true },
|
||||
noopLogger
|
||||
);
|
||||
it("preserves provider gating and externally bound port reuse", async () => {
|
||||
manager = createApiServerManager({ ...options, neteaseEnabled: false, qqEnabled: false }, logger);
|
||||
await manager.start(); expect(state.probes).toHaveLength(0); expect(state.fork).not.toHaveBeenCalled();
|
||||
state.portFree = false;
|
||||
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(JSON.stringify({ data: { message: "no songmid" } }), {
|
||||
status: 400, headers: { "Content-Type": "application/json" },
|
||||
}));
|
||||
manager = createApiServerManager({ ...options, neteaseEnabled: false }, logger);
|
||||
await manager.start(); expect(state.fork).not.toHaveBeenCalled();
|
||||
expect(logger.info).toHaveBeenCalledWith({ port: 39217 }, expect.stringContaining("reusing"));
|
||||
});
|
||||
it("detects the wrong service on the QQ music port without assuming every occupied port is reusable", async () => {
|
||||
state.portFree = false;
|
||||
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("<html>WebUI</html>", { status: 200 }));
|
||||
manager = createApiServerManager({ ...options, neteaseEnabled: false }, logger);
|
||||
await manager.start();
|
||||
expect(state.fork).not.toHaveBeenCalled();
|
||||
expect(logger.error).toHaveBeenCalledWith({ provider: "qq", port: 39217, category: "port-in-use" }, expect.stringContaining("qqMusicApiPort"));
|
||||
expect(() => manager.assertQqMusicApiPort()).toThrow(expect.objectContaining({ code: "QQ_API_PORT_CONFLICT" }));
|
||||
});
|
||||
it("inherits tsx loader arguments without unrelated parent runner flags", async () => {
|
||||
const previous = process.execArgv;
|
||||
process.execArgv = ["--require", "C:\\app\\node_modules\\tsx\\dist\\preflight.cjs", "--import", "file:///app/node_modules/tsx/dist/loader.mjs", "--eval", "synthetic-evaluation", "--conditions", "vitest", "--input-type=module", "--inspect"];
|
||||
try {
|
||||
await manager.start();
|
||||
// The sidecar follows qqMusicPort, never the injected PORT.
|
||||
expect(mockState.listenCalls).toEqual([{ port, host: "127.0.0.1" }]);
|
||||
// The injected PORT is restored so nothing else in the process is affected.
|
||||
expect(process.env.PORT).toBe("39999");
|
||||
} finally {
|
||||
manager.stop();
|
||||
if (previous === undefined) delete process.env.PORT;
|
||||
else process.env.PORT = previous;
|
||||
}
|
||||
expect(state.fork.mock.calls[0][2].execArgv).toEqual(process.execArgv.slice(0, 4));
|
||||
} finally { process.execArgv = previous; }
|
||||
});
|
||||
|
||||
it("leaves an absent PORT env unset after importing the sidecar", async () => {
|
||||
const port = 39221;
|
||||
const previous = process.env.PORT;
|
||||
delete process.env.PORT;
|
||||
const manager = createApiServerManager(
|
||||
{ neteasePort: 39222, qqMusicPort: port, neteaseEnabled: false, qqEnabled: true },
|
||||
noopLogger
|
||||
);
|
||||
try {
|
||||
await manager.start();
|
||||
// Was unset before importing — must be unset again, no leaked override.
|
||||
expect(process.env.PORT).toBeUndefined();
|
||||
} finally {
|
||||
manager.stop();
|
||||
if (previous === undefined) delete process.env.PORT;
|
||||
else process.env.PORT = previous;
|
||||
it("does not duplicate concurrent or repeated starts", async () => {
|
||||
await Promise.all([manager.start(), manager.start()]); await manager.start();
|
||||
expect(state.fork).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
it("fences a stop during pending port preflight", async () => {
|
||||
state.probeAutomatically = false;
|
||||
const starting = manager.start(); await flush(); manager.stop();
|
||||
state.probes[0].emit("listening"); await starting;
|
||||
expect(state.fork).not.toHaveBeenCalled();
|
||||
});
|
||||
it("cancels a pending handshake and ignores its late ready", async () => {
|
||||
automaticReady = false;
|
||||
const starting = manager.start(); await flush(); expect(children).toHaveLength(1);
|
||||
manager.stop(); children[0].emit("message", { type: "ready", provider: "netease", port: 39218 }); await starting;
|
||||
expect(children[0].send).toHaveBeenCalledWith({ type: "stop" }, expect.any(Function));
|
||||
expect(state.fork).toHaveBeenCalledTimes(1);
|
||||
expect(logger.info).not.toHaveBeenCalledWith({ port: 39218 }, "NetEase Cloud Music API started");
|
||||
});
|
||||
it("waits for a cancelled preflight to release its probe before restart", async () => {
|
||||
state.probeAutomatically = false;
|
||||
const first = manager.start(); await flush(); manager.stop();
|
||||
const restarting = manager.start(); await flush();
|
||||
expect(state.probes).toHaveLength(1);
|
||||
state.probeAutomatically = true; state.probes[0].emit("listening");
|
||||
await Promise.all([first, restarting]);
|
||||
expect(state.fork).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
it("waits for old children to exit before restart", async () => {
|
||||
await manager.start(); children.forEach((child) => { child.exitOnStop = false; }); manager.stop();
|
||||
const restarting = manager.start(); await flush(); expect(state.fork).toHaveBeenCalledTimes(2);
|
||||
children.slice(0, 2).forEach((child) => child.finish(0, null)); await restarting;
|
||||
expect(state.fork).toHaveBeenCalledTimes(4);
|
||||
});
|
||||
it("reports unexpected post-ready exits with safe fields", async () => {
|
||||
await manager.start(); children[1].finish(7, "SIGTERM");
|
||||
expect(logger.error).toHaveBeenCalledWith({ provider: "qq", port: 39217, code: 7, signal: "SIGTERM" }, expect.stringContaining("exited unexpectedly"));
|
||||
});
|
||||
it("retains static QQ diagnostics and discards arbitrary IPC fields", async () => {
|
||||
automaticReady = false; manager = createApiServerManager({ ...options, neteaseEnabled: false }, logger);
|
||||
const starting = manager.start(); await flush();
|
||||
children[0].emit("message", { type: "error", provider: "qq", port: 39217, category: "esm", code: "ERR_REQUIRE_ESM", message: "synthetic-credential", stack: "synthetic-credential" }); await starting;
|
||||
expect(logger.error).toHaveBeenCalledWith({ provider: "qq", port: 39217, category: "esm", code: "ERR_REQUIRE_ESM" }, expect.stringContaining("ERR_REQUIRE_ESM"));
|
||||
expect(JSON.stringify([...(logger.error as ReturnType<typeof vi.fn>).mock.calls, ...(logger.warn as ReturnType<typeof vi.fn>).mock.calls])).not.toContain("synthetic-credential");
|
||||
expect(children[0].send).toHaveBeenCalledWith({ type: "stop" }, expect.any(Function));
|
||||
});
|
||||
it("ignores a ready message for a different provider or port", async () => {
|
||||
automaticReady = false; manager = createApiServerManager({ ...options, neteaseEnabled: false }, logger);
|
||||
const starting = manager.start(); await flush();
|
||||
children[0].emit("message", { type: "ready", provider: "netease", port: 39217 });
|
||||
children[0].emit("message", { type: "ready", provider: "qq", port: 39999 });
|
||||
await flush();
|
||||
expect(logger.info).not.toHaveBeenCalledWith({ port: 39217 }, "QQ Music API started");
|
||||
children[0].emit("message", { type: "ready", provider: "qq", port: 39217 }); await starting;
|
||||
expect(logger.info).toHaveBeenCalledWith({ port: 39217 }, "QQ Music API started");
|
||||
});
|
||||
it("cleans up a failed fork that closes without an exit event", async () => {
|
||||
automaticReady = false; manager = createApiServerManager({ ...options, neteaseEnabled: false }, logger);
|
||||
const starting = manager.start(); await flush();
|
||||
children[0].emit("error", Object.assign(new Error("synthetic-credential"), { code: "ENOENT" }));
|
||||
children[0].emit("close", null, null); await starting;
|
||||
expect(logger.error).toHaveBeenCalledWith({ provider: "qq", port: 39217, category: "startup", code: "ENOENT" }, expect.stringContaining("start"));
|
||||
automaticReady = true; await manager.start();
|
||||
expect(state.fork).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
it("times out and terminates a silent child", async () => {
|
||||
vi.useFakeTimers(); automaticReady = false; manager = createApiServerManager({ ...options, neteaseEnabled: false }, logger);
|
||||
const starting = manager.start(); await flush(); await vi.advanceTimersByTimeAsync(30000); await starting;
|
||||
expect(logger.error).toHaveBeenCalledWith({ provider: "qq", port: 39217, category: "timeout" }, expect.stringContaining("start"));
|
||||
expect(children[0].send).toHaveBeenCalledWith({ type: "stop" }, expect.any(Function));
|
||||
});
|
||||
it("forces shutdown if a child ignores stop", async () => {
|
||||
vi.useFakeTimers(); await manager.start(); children.forEach((child) => { child.exitOnStop = false; }); manager.stop();
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
expect(children.every((child) => child.kill.mock.calls.length > 0)).toBe(true);
|
||||
expect(logger.error).not.toHaveBeenCalled();
|
||||
});
|
||||
it("escalates to SIGKILL if stop and SIGTERM are ignored", async () => {
|
||||
vi.useFakeTimers(); await manager.start();
|
||||
for (const child of children) {
|
||||
child.exitOnStop = false;
|
||||
child.kill.mockImplementation((signal: string = "SIGTERM") => {
|
||||
if (signal === "SIGKILL") queueMicrotask(() => child.finish(null, signal));
|
||||
return true;
|
||||
});
|
||||
}
|
||||
manager.stop(); await vi.advanceTimersByTimeAsync(2000);
|
||||
expect(children.every((child) => child.kill.mock.calls.some(([signal]) => signal === "SIGKILL"))).toBe(true);
|
||||
expect(logger.error).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+180
-177
@@ -1,213 +1,216 @@
|
||||
import net from "node:net";
|
||||
import { fork, type ChildProcess } from "node:child_process";
|
||||
import type { Logger } from "../logger.js";
|
||||
import type { Server } from "node:http";
|
||||
import { getSafeApiStartupError, isApiPortFree, isQqMusicApi, safeApiErrorCode, type ApiProvider, type SafeApiStartupError } from "./api-server-runtime.js";
|
||||
|
||||
export interface ApiServerOptions {
|
||||
neteasePort: number;
|
||||
qqMusicPort: number;
|
||||
/** Provider gating (#enabledProviders): when false, the corresponding
|
||||
* embedded sidecar API server is never started and its port never bound. */
|
||||
neteaseEnabled?: boolean;
|
||||
qqEnabled?: boolean;
|
||||
}
|
||||
|
||||
export interface ApiServerManager {
|
||||
start(): Promise<void>;
|
||||
stop(): void;
|
||||
getNeteaseBaseUrl(): string;
|
||||
getQQMusicBaseUrl(): string;
|
||||
assertQqMusicApiPort(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify a QQ Music API (@sansenjian/qq-music-api) startup failure into
|
||||
* actionable operator guidance, or null when it isn't a recognised
|
||||
* dependency/runtime mismatch. Exported for testing.
|
||||
*
|
||||
* Background: the package became ESM in 2.3.x. A loose `^` range could pull an
|
||||
* ESM-only build (2.3.0/2.3.1) that throws ERR_REQUIRE_ESM, or a 2.4.x build
|
||||
* that needs Node >=20.17 — either way the embedded server never binds, so
|
||||
* every QQ request fails downstream with ECONNREFUSED on the API port.
|
||||
*/
|
||||
export function describeQqApiStartupError(err: unknown): string | null {
|
||||
const e = (err ?? {}) as { code?: string; message?: string };
|
||||
const code = String(e.code ?? "");
|
||||
const msg = String(e.message ?? "");
|
||||
if (code === "ERR_REQUIRE_ESM" || /ERR_REQUIRE_ESM|require\(\) of ES ?Module/i.test(msg)) {
|
||||
return (
|
||||
"an incompatible @sansenjian/qq-music-api build is installed (ERR_REQUIRE_ESM). " +
|
||||
"Pin it to ~2.4.0 (needs Node >=20.17) or ~2.2.10 in package.json, then reinstall"
|
||||
);
|
||||
}
|
||||
if (/Unsupported engine|EBADENGINE|requires Node|Node\.js version/i.test(msg)) {
|
||||
return "@sansenjian/qq-music-api 2.4.x requires Node >=20.17 (or >=22.9) — upgrade Node, or pin the package to ~2.2.10";
|
||||
}
|
||||
const { category } = getSafeApiStartupError(err);
|
||||
if (category === "esm") return "an incompatible @sansenjian/qq-music-api build is installed (ERR_REQUIRE_ESM). Pin it to ~2.4.0 (needs Node >=20.17) or ~2.2.10 in package.json, then reinstall";
|
||||
if (category === "node-engine") return "@sansenjian/qq-music-api 2.4.x requires Node >=20.17 (or >=22.9) — upgrade Node, or pin the package to ~2.2.10";
|
||||
return null;
|
||||
}
|
||||
|
||||
function isPortFree(port: number): Promise<boolean> {
|
||||
return new Promise((resolve) => {
|
||||
const server = net.createServer();
|
||||
server.once("error", () => {
|
||||
server.close(() => resolve(false));
|
||||
});
|
||||
server.once("listening", () => {
|
||||
server.close(() => resolve(true));
|
||||
});
|
||||
server.listen(port, "127.0.0.1");
|
||||
});
|
||||
/** Carry only tsx loader arguments into a source child. CLI evaluation,
|
||||
* inspector and test-runner flags have unrelated meanings in a fork. */
|
||||
function childExecArgv(source: boolean): string[] {
|
||||
if (!source) return [];
|
||||
const args: string[] = [];
|
||||
for (let i = 0; i < process.execArgv.length; i++) {
|
||||
const arg = process.execArgv[i];
|
||||
if (arg === "--import" || arg === "--require" || arg === "-r") {
|
||||
const value = process.execArgv[++i];
|
||||
if (value && (value === "tsx" || /[/\\]tsx[/\\]/.test(value))) args.push(arg, value);
|
||||
} else if (arg.startsWith("--import=") && (arg === "--import=tsx" || /[/\\]tsx[/\\]/.test(arg))) args.push(arg);
|
||||
}
|
||||
return args.length ? args : ["--import", "tsx"];
|
||||
}
|
||||
|
||||
export function createApiServerManager(
|
||||
options: ApiServerOptions,
|
||||
logger: Logger
|
||||
): ApiServerManager {
|
||||
let neteaseServer: Server | null = null;
|
||||
let qqMusicServer: Server | null = null;
|
||||
class StartupFailure extends Error {
|
||||
constructor(readonly details: SafeApiStartupError) { super("Embedded music API startup failed"); }
|
||||
}
|
||||
interface ManagedChild {
|
||||
child: ChildProcess;
|
||||
stop(): Promise<void>;
|
||||
}
|
||||
const STARTUP_TIMEOUT_MS = 15000;
|
||||
const ERROR_CATEGORIES = new Set(["esm", "node-engine", "port-in-use", "startup"]);
|
||||
|
||||
const neteaseBaseUrl = `http://127.0.0.1:${options.neteasePort}`;
|
||||
const qqMusicBaseUrl = `http://127.0.0.1:${options.qqMusicPort}`;
|
||||
export function createApiServerManager(options: ApiServerOptions, logger: Logger): ApiServerManager {
|
||||
const children = new Map<ApiProvider, ManagedChild>();
|
||||
let generation = 0;
|
||||
let starting: Promise<void> | null = null;
|
||||
let stopping: Promise<void> = Promise.resolve();
|
||||
let qqPortConflict = false;
|
||||
|
||||
function reportQqPortConflict(port: number): void {
|
||||
qqPortConflict = true;
|
||||
logger.error({ provider: "qq", port, category: "port-in-use" },
|
||||
"QQ Music API port is occupied by another service. Free the port or set qqMusicApiPort to an unused port and restart.");
|
||||
}
|
||||
|
||||
function launch(provider: ApiProvider, port: number, launchGeneration: number): Promise<void> {
|
||||
const source = import.meta.url.endsWith(".ts");
|
||||
const entry = new URL(source ? "./api-server-child.ts" : "./api-server-child.js", import.meta.url);
|
||||
const child = fork(entry, [provider, String(port)], {
|
||||
stdio: ["ignore", "ignore", "ignore", "ipc"],
|
||||
execArgv: childExecArgv(source),
|
||||
});
|
||||
let ready = false;
|
||||
let expectedExit = false;
|
||||
let settled = false;
|
||||
let hasExited = false;
|
||||
let startupTimer: ReturnType<typeof setTimeout>;
|
||||
let terminateTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
let killTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
let resolveExit!: () => void;
|
||||
const exited = new Promise<void>((resolve) => { resolveExit = resolve; });
|
||||
let resolveStart!: () => void;
|
||||
let rejectStart!: (error: StartupFailure) => void;
|
||||
const started = new Promise<void>((resolve, reject) => { resolveStart = resolve; rejectStart = reject; });
|
||||
const settle = (error?: SafeApiStartupError) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(startupTimer);
|
||||
if (error) rejectStart(new StartupFailure(error)); else resolveStart();
|
||||
};
|
||||
const record: ManagedChild = {
|
||||
child,
|
||||
stop() {
|
||||
if (expectedExit) return exited;
|
||||
expectedExit = true;
|
||||
settle({ category: "cancelled" });
|
||||
if (children.get(provider) === record) children.delete(provider);
|
||||
stopping = Promise.all([stopping, exited]).then(() => {});
|
||||
if (hasExited) return exited;
|
||||
try {
|
||||
if (child.connected) child.send({ type: "stop" }, (error) => { if (error) child.kill("SIGTERM"); });
|
||||
else child.kill("SIGTERM");
|
||||
} catch { child.kill("SIGTERM"); }
|
||||
terminateTimer = setTimeout(() => child.kill("SIGTERM"), 1000);
|
||||
killTimer = setTimeout(() => child.kill("SIGKILL"), 2000);
|
||||
terminateTimer.unref(); killTimer.unref();
|
||||
return exited;
|
||||
},
|
||||
};
|
||||
children.set(provider, record);
|
||||
child.on("message", (message: unknown) => {
|
||||
if (!message || typeof message !== "object" || expectedExit || launchGeneration !== generation) return;
|
||||
const data = message as Record<string, unknown>;
|
||||
if (data.provider !== provider || data.port !== port) return;
|
||||
if (data.type === "ready") { ready = true; settle(); }
|
||||
else if (data.type === "error" && typeof data.category === "string" && ERROR_CATEGORIES.has(data.category)) {
|
||||
const code = safeApiErrorCode(data.code);
|
||||
const details: SafeApiStartupError = { category: data.category as SafeApiStartupError["category"], ...(code ? { code } : {}) };
|
||||
if (!ready) settle(details);
|
||||
else logger.error({ provider, port, ...details }, "Embedded music API reported a runtime failure");
|
||||
void record.stop();
|
||||
}
|
||||
});
|
||||
child.on("error", (error) => {
|
||||
if (expectedExit) return;
|
||||
const details = getSafeApiStartupError(error);
|
||||
if (!ready) settle(details);
|
||||
else logger.error({ provider, port, ...details }, "Embedded music API child failed");
|
||||
void record.stop();
|
||||
});
|
||||
const onExit = (code: number | null, signal: NodeJS.Signals | null) => {
|
||||
if (hasExited) return;
|
||||
hasExited = true;
|
||||
clearTimeout(startupTimer); clearTimeout(terminateTimer); clearTimeout(killTimer);
|
||||
if (children.get(provider) === record) children.delete(provider);
|
||||
if (!expectedExit) {
|
||||
if (ready) logger.error({ provider, port, code, signal }, "Embedded music API exited unexpectedly");
|
||||
else settle({ category: "startup" });
|
||||
}
|
||||
resolveExit();
|
||||
};
|
||||
child.once("exit", onExit);
|
||||
// A failed fork emits close without exit.
|
||||
child.once("close", onExit);
|
||||
startupTimer = setTimeout(() => { settle({ category: "timeout" }); void record.stop(); }, STARTUP_TIMEOUT_MS);
|
||||
return started;
|
||||
}
|
||||
|
||||
return {
|
||||
async start(): Promise<void> {
|
||||
// Provider gating: with the jellyfin-only default config neither legacy
|
||||
// sidecar starts, so ports 3001/3200 are never opened.
|
||||
if (options.neteaseEnabled === false && options.qqEnabled === false) {
|
||||
logger.info("NetEase/QQ providers disabled — embedded music API servers not started");
|
||||
return;
|
||||
}
|
||||
logger.info("Starting embedded music API servers...");
|
||||
|
||||
// Start NetEase Cloud Music API
|
||||
if (options.neteaseEnabled !== false) {
|
||||
try {
|
||||
const portFree = await isPortFree(options.neteasePort);
|
||||
if (!portFree) {
|
||||
logger.info(
|
||||
{ port: options.neteasePort },
|
||||
"NetEase API port already in use — reusing existing instance"
|
||||
);
|
||||
} else {
|
||||
const ncmModule = await import("NeteaseCloudMusicApi") as any;
|
||||
const serverObj = ncmModule.server ?? ncmModule.default?.server;
|
||||
const app = await serverObj.serveNcmApi({ port: options.neteasePort });
|
||||
neteaseServer = app;
|
||||
logger.info(
|
||||
{ port: options.neteasePort },
|
||||
"NetEase Cloud Music API started"
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Failed to start NetEase Cloud Music API");
|
||||
start(): Promise<void> {
|
||||
if (starting) return starting;
|
||||
const startGeneration = generation;
|
||||
const run = async () => {
|
||||
await stopping;
|
||||
if (startGeneration !== generation) return;
|
||||
if (options.neteaseEnabled === false && options.qqEnabled === false) {
|
||||
logger.info("NetEase/QQ providers disabled — embedded music API servers not started"); return;
|
||||
}
|
||||
}
|
||||
|
||||
// Start QQ Music API. Older versions auto-started on import; the
|
||||
// current fork (2.2.11+) only listens when run as `require.main`,
|
||||
// so we explicitly call .listen() on the imported Koa app and keep
|
||||
// the server handle for clean shutdown.
|
||||
if (options.qqEnabled === false) return;
|
||||
try {
|
||||
const portFree = await isPortFree(options.qqMusicPort);
|
||||
if (!portFree) {
|
||||
logger.info(
|
||||
{ port: options.qqMusicPort },
|
||||
"QQ Music API port already in use — reusing existing instance"
|
||||
);
|
||||
} else {
|
||||
// Pin the upstream server to the configured port before importing.
|
||||
// The package derives its default port from process.env.PORT (falling
|
||||
// back to 3200) and, in some historical versions, auto-started that
|
||||
// server as an import side effect. Aligning PORT with qqMusicApiPort
|
||||
// guarantees the sidecar can never bind a different port than the one
|
||||
// the client base URL (getQQMusicBaseUrl) targets — the root cause of
|
||||
// issue #122, where an old build listened on 3300 while the client
|
||||
// requested 3200. Restore the previous value right after import so we
|
||||
// never leak the override into the rest of the process (e.g. the web
|
||||
// server or the NetEase sidecar, which also read PORT as a fallback).
|
||||
const prevPortEnv = process.env.PORT;
|
||||
process.env.PORT = String(options.qqMusicPort);
|
||||
let qqModule: any;
|
||||
logger.info("Starting embedded music API servers...");
|
||||
const providers: Array<{ provider: ApiProvider; port: number; enabled: boolean; name: string }> = [
|
||||
{ provider: "netease", port: options.neteasePort, enabled: options.neteaseEnabled !== false, name: "NetEase Cloud Music" },
|
||||
{ provider: "qq", port: options.qqMusicPort, enabled: options.qqEnabled !== false, name: "QQ Music" },
|
||||
];
|
||||
for (const { provider, port, enabled, name } of providers) {
|
||||
if (startGeneration !== generation) return;
|
||||
if (!enabled || children.has(provider)) continue;
|
||||
try {
|
||||
qqModule = (await import("@sansenjian/qq-music-api")) as any;
|
||||
} finally {
|
||||
if (prevPortEnv === undefined) delete process.env.PORT;
|
||||
else process.env.PORT = prevPortEnv;
|
||||
}
|
||||
// The module's export structure varies between versions:
|
||||
// 2.2.11+: default → Koa app (has .listen)
|
||||
// 2.2.10: default → wrapper object whose .default is the Koa app
|
||||
// older: module itself may be the Koa app
|
||||
const candidate = qqModule.default ?? qqModule;
|
||||
const koaApp = typeof candidate.listen === "function"
|
||||
? candidate
|
||||
: candidate.default ?? null;
|
||||
if (koaApp && typeof koaApp.listen === "function") {
|
||||
// A version that auto-started on import has already bound the
|
||||
// configured port (thanks to the PORT alignment above); reuse it
|
||||
// rather than racing a second listen that would fail EADDRINUSE.
|
||||
const stillFree = await isPortFree(options.qqMusicPort);
|
||||
if (!stillFree) {
|
||||
logger.info(
|
||||
{ port: options.qqMusicPort },
|
||||
"QQ Music API already listening on the configured port (auto-started on import) — reusing embedded instance"
|
||||
);
|
||||
} else {
|
||||
qqMusicServer = await new Promise<Server>((resolve, reject) => {
|
||||
const srv = koaApp.listen(options.qqMusicPort, "127.0.0.1", () =>
|
||||
resolve(srv)
|
||||
);
|
||||
srv.on("error", reject);
|
||||
});
|
||||
// Log the port actually bound (read from the socket) rather than
|
||||
// the requested one, so operators can spot a mismatch in the logs.
|
||||
const addr = qqMusicServer.address();
|
||||
const boundPort =
|
||||
addr && typeof addr === "object" && addr !== null
|
||||
? addr.port
|
||||
: options.qqMusicPort;
|
||||
logger.info(
|
||||
{ port: boundPort },
|
||||
"QQ Music API started"
|
||||
);
|
||||
const free = await isApiPortFree(port);
|
||||
if (startGeneration !== generation) return;
|
||||
if (!free) {
|
||||
if (provider === "qq") {
|
||||
const compatible = await isQqMusicApi(port);
|
||||
if (startGeneration !== generation) return;
|
||||
if (!compatible) { reportQqPortConflict(port); continue; }
|
||||
qqPortConflict = false;
|
||||
}
|
||||
logger.info({ port }, `${provider === "netease" ? "NetEase" : "QQ Music"} API port already in use — reusing existing instance`);
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
logger.warn("QQ Music API module does not expose a Koa app");
|
||||
await launch(provider, port, startGeneration);
|
||||
if (startGeneration !== generation) return;
|
||||
if (provider === "qq") qqPortConflict = false;
|
||||
logger.info({ port }, `${name} API started`);
|
||||
} catch (error) {
|
||||
if (startGeneration !== generation) return;
|
||||
const details = error instanceof StartupFailure ? error.details : getSafeApiStartupError(error);
|
||||
if (details.category === "cancelled") return;
|
||||
if (provider === "qq" && details.category === "port-in-use") { reportQqPortConflict(port); continue; }
|
||||
const hint = provider === "qq" ? describeQqApiStartupError(details.category === "esm" ? { code: "ERR_REQUIRE_ESM" } : details.category === "node-engine" ? { code: "EBADENGINE" } : {}) : null;
|
||||
logger.error({ provider, port, ...details }, hint ? `QQ Music API failed to start — ${hint}. QQ features (search/play/login) will be unavailable until fixed; port ${port} is down.` : `Failed to start ${name} API`);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
const hint = describeQqApiStartupError(err);
|
||||
if (hint) {
|
||||
logger.error(
|
||||
{ err },
|
||||
`QQ Music API failed to start — ${hint}. QQ features (search/play/login) will be unavailable until fixed; port ${options.qqMusicPort} is down.`
|
||||
);
|
||||
} else {
|
||||
logger.warn(
|
||||
{ err },
|
||||
"QQ Music API not available — QQ Music features may be limited"
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
const promise = run();
|
||||
starting = promise;
|
||||
void promise.finally(() => { if (starting === promise) starting = null; });
|
||||
return promise;
|
||||
},
|
||||
|
||||
stop(): void {
|
||||
generation++;
|
||||
const pendingStart = starting;
|
||||
starting = null;
|
||||
logger.info("Stopping music API servers");
|
||||
if (neteaseServer && typeof (neteaseServer as any).close === "function") {
|
||||
(neteaseServer as any).close();
|
||||
}
|
||||
neteaseServer = null;
|
||||
if (qqMusicServer && typeof (qqMusicServer as any).close === "function") {
|
||||
(qqMusicServer as any).close();
|
||||
}
|
||||
qqMusicServer = null;
|
||||
const retiring = [...children.values()];
|
||||
children.clear();
|
||||
// A cancelled preflight still owns a temporary listening socket until
|
||||
// its callback closes it. Restart must wait for that work as well.
|
||||
stopping = Promise.all([stopping, pendingStart, ...retiring.map((record) => record.stop())]).then(() => {});
|
||||
},
|
||||
|
||||
getNeteaseBaseUrl(): string {
|
||||
return neteaseBaseUrl;
|
||||
},
|
||||
|
||||
getQQMusicBaseUrl(): string {
|
||||
return qqMusicBaseUrl;
|
||||
getNeteaseBaseUrl: () => `http://127.0.0.1:${options.neteasePort}`,
|
||||
getQQMusicBaseUrl: () => `http://127.0.0.1:${options.qqMusicPort}`,
|
||||
assertQqMusicApiPort(): void {
|
||||
if (qqPortConflict) {
|
||||
throw Object.assign(new Error("QQ Music API port conflict; check qqMusicApiPort"), { code: "QQ_API_PORT_CONFLICT" });
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
},
|
||||
};
|
||||
}
|
||||
+172
-1
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { BiliBiliProvider } from "./bilibili.js";
|
||||
import { BiliBiliProvider, pickStableAudioUrl } from "./bilibili.js";
|
||||
|
||||
describe("BiliBiliProvider.search pagination", () => {
|
||||
function mockProvider() {
|
||||
@@ -37,3 +37,174 @@ describe("BiliBiliProvider.search pagination", () => {
|
||||
expect(searchParams(get).page).toBe("1");
|
||||
});
|
||||
});
|
||||
|
||||
describe("BiliBiliProvider multi-P support", () => {
|
||||
it("parseBilibiliId extracts bvid and page correctly", async () => {
|
||||
const { parseBilibiliId } = await import("./bilibili.js");
|
||||
expect(parseBilibiliId("BV1yxHQeYEuE")).toEqual({ bvid: "BV1yxHQeYEuE", page: 1 });
|
||||
expect(parseBilibiliId("BV1yxHQeYEuE?p=3")).toEqual({ bvid: "BV1yxHQeYEuE", page: 3 });
|
||||
expect(parseBilibiliId("BV1yxHQeYEuE:p2")).toEqual({ bvid: "BV1yxHQeYEuE", page: 2 });
|
||||
expect(parseBilibiliId("https://www.bilibili.com/video/BV1yxHQeYEuE?p=5")).toEqual({
|
||||
bvid: "BV1yxHQeYEuE",
|
||||
page: 5,
|
||||
});
|
||||
expect(parseBilibiliId("some-other-id")).toEqual({ bvid: "some-other-id", page: 1 });
|
||||
});
|
||||
|
||||
function mockViewProvider(viewData: any, playUrlData?: any) {
|
||||
const p = new BiliBiliProvider();
|
||||
const get = vi.fn().mockImplementation((url: string, opts?: any) => {
|
||||
if (url === "/x/web-interface/view") {
|
||||
return Promise.resolve({ data: { data: viewData } });
|
||||
}
|
||||
if (url === "/x/player/playurl") {
|
||||
return Promise.resolve({ data: { data: playUrlData ?? {} } });
|
||||
}
|
||||
return Promise.resolve({ data: {} });
|
||||
});
|
||||
(p as any).buvidInitialized = true;
|
||||
(p as any).api = { get };
|
||||
return { p, get };
|
||||
}
|
||||
|
||||
const multiPViewData = {
|
||||
bvid: "BV1multiP",
|
||||
title: "测试多P教程",
|
||||
pic: "http://i0.hdslb.com/bfs/archive/test.jpg",
|
||||
duration: 300, // 总时长 300 秒 (120 + 180)
|
||||
owner: { name: "UP主测试" },
|
||||
pages: [
|
||||
{ cid: 10001, page: 1, part: "第一讲 入门", duration: 120 },
|
||||
{ cid: 10002, page: 2, part: "第二讲 进阶", duration: 180 },
|
||||
],
|
||||
};
|
||||
|
||||
const singlePViewData = {
|
||||
bvid: "BV1singleP",
|
||||
title: "测试单P视频",
|
||||
pic: "http://i0.hdslb.com/bfs/archive/single.jpg",
|
||||
duration: 200,
|
||||
owner: { name: "UP主测试" },
|
||||
pages: [
|
||||
{ cid: 20001, page: 1, part: "测试单P视频", duration: 200 },
|
||||
],
|
||||
};
|
||||
|
||||
it("getSongDetail for single-P video returns total duration and clean bvid", async () => {
|
||||
const { p } = mockViewProvider(singlePViewData);
|
||||
const song = await p.getSongDetail("BV1singleP");
|
||||
expect(song).not.toBeNull();
|
||||
expect(song!.id).toBe("BV1singleP");
|
||||
expect(song!.name).toBe("测试单P视频");
|
||||
expect(song!.duration).toBe(200);
|
||||
expect(song!.platform).toBe("bilibili");
|
||||
});
|
||||
|
||||
it("getSongDetail for multi-P video without ?p defaults to P1 with P1 duration", async () => {
|
||||
const { p } = mockViewProvider(multiPViewData);
|
||||
const song = await p.getSongDetail("BV1multiP");
|
||||
expect(song).not.toBeNull();
|
||||
expect(song!.id).toBe("BV1multiP?p=1");
|
||||
expect(song!.name).toBe("测试多P教程 - P1 第一讲 入门");
|
||||
expect(song!.duration).toBe(120); // P1 独立时长,而非总时长 300!
|
||||
expect(song!.platform).toBe("bilibili");
|
||||
});
|
||||
|
||||
it("getSongDetail for multi-P video with ?p=2 returns P2 with P2 duration", async () => {
|
||||
const { p } = mockViewProvider(multiPViewData);
|
||||
const song = await p.getSongDetail("BV1multiP?p=2");
|
||||
expect(song).not.toBeNull();
|
||||
expect(song!.id).toBe("BV1multiP?p=2");
|
||||
expect(song!.name).toBe("测试多P教程 - P2 第二讲 进阶");
|
||||
expect(song!.duration).toBe(180); // P2 独立时长
|
||||
expect(song!.platform).toBe("bilibili");
|
||||
});
|
||||
|
||||
it("getVideoParts returns all parts with duration and cid", async () => {
|
||||
const { p } = mockViewProvider(multiPViewData);
|
||||
const partsResult = await p.getVideoParts("BV1multiP");
|
||||
expect(partsResult).not.toBeNull();
|
||||
expect(partsResult!.bvid).toBe("BV1multiP");
|
||||
expect(partsResult!.title).toBe("测试多P教程");
|
||||
expect(partsResult!.parts).toHaveLength(2);
|
||||
expect(partsResult!.parts[0]).toEqual({
|
||||
part: 1,
|
||||
cid: 10001,
|
||||
title: "第一讲 入门",
|
||||
duration: 120,
|
||||
});
|
||||
expect(partsResult!.parts[1]).toEqual({
|
||||
part: 2,
|
||||
cid: 10002,
|
||||
title: "第二讲 进阶",
|
||||
duration: 180,
|
||||
});
|
||||
});
|
||||
|
||||
it("getSongUrl requests playurl with correct cid for specific part", async () => {
|
||||
const playUrlResponse = {
|
||||
dash: {
|
||||
audio: [
|
||||
{ bandwidth: 64000, baseUrl: "http://audio.64k.test" },
|
||||
{ bandwidth: 320000, baseUrl: "http://audio.320k.test" },
|
||||
],
|
||||
},
|
||||
};
|
||||
const { p, get } = mockViewProvider(multiPViewData, playUrlResponse);
|
||||
|
||||
const result = await p.getSongUrl("BV1multiP?p=2");
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.url).toBe("http://audio.320k.test");
|
||||
|
||||
const playurlCall = get.mock.calls.find((c: any[]) => c[0] === "/x/player/playurl");
|
||||
expect(playurlCall).toBeTruthy();
|
||||
expect(playurlCall![1].params.cid).toBe(10002); // 准确传入 P2 的 cid
|
||||
expect(playurlCall![1].params.bvid).toBe("BV1multiP"); // 纯净 bvid
|
||||
});
|
||||
});
|
||||
|
||||
describe("pickStableAudioUrl (#161 long streams dying mid-play)", () => {
|
||||
const pcdn = "https://xy1x2x3x4xy.mcdn.bilivideo.cn:4483/upgcxcode/1/2/3/3-1-30280.m4s?e=x&deadline=1";
|
||||
const szbdyd = "https://cn-hk-eq-01-01.szbdyd.com/upgcxcode/1/2/3/3-1-30280.m4s?deadline=1";
|
||||
const upos = "https://upos-sz-mirrorcos.bilivideo.com/upgcxcode/1/2/3/3-1-30280.m4s?deadline=1";
|
||||
const upos2 = "https://upos-sz-mirror08c.bilivideo.com/upgcxcode/1/2/3/3-1-30280.m4s?deadline=1";
|
||||
|
||||
it("prefers an upos/cos mirror over a PCDN baseUrl", () => {
|
||||
expect(pickStableAudioUrl({ baseUrl: pcdn, backupUrl: [szbdyd, upos] })).toBe(upos);
|
||||
});
|
||||
|
||||
it("keeps the baseUrl when it is already a stable host", () => {
|
||||
expect(pickStableAudioUrl({ baseUrl: upos, backupUrl: [upos2] })).toBe(upos);
|
||||
});
|
||||
|
||||
it("accepts the snake_case field names", () => {
|
||||
expect(pickStableAudioUrl({ base_url: pcdn, backup_url: [upos2] })).toBe(upos2);
|
||||
});
|
||||
|
||||
it("falls back to the baseUrl when every candidate is PCDN", () => {
|
||||
expect(pickStableAudioUrl({ baseUrl: pcdn, backupUrl: [szbdyd] })).toBe(pcdn);
|
||||
});
|
||||
|
||||
it("allows a refreshed URL from the same host if no alternative is available", () => {
|
||||
const host = new URL(upos).hostname;
|
||||
expect(pickStableAudioUrl({ baseUrl: upos }, new Set([host]))).toBe(upos);
|
||||
});
|
||||
|
||||
it("returns undefined when there is no url at all", () => {
|
||||
expect(pickStableAudioUrl({})).toBeUndefined();
|
||||
});
|
||||
|
||||
it("getSongUrl returns the stable mirror of the best stream", async () => {
|
||||
const p = new BiliBiliProvider();
|
||||
(p as any).cidCache.set("BV1abc", 42);
|
||||
(p as any).api = {
|
||||
get: vi.fn().mockResolvedValue({
|
||||
data: { data: { dash: { audio: [
|
||||
{ bandwidth: 64000, baseUrl: "https://upos-sz-mirrorcos.bilivideo.com/low.m4s" },
|
||||
{ bandwidth: 320000, baseUrl: pcdn, backupUrl: [upos] },
|
||||
] } } },
|
||||
}),
|
||||
};
|
||||
expect((await p.getSongUrl("BV1abc"))?.url).toBe(upos);
|
||||
});
|
||||
});
|
||||
+164
-14
@@ -1,8 +1,10 @@
|
||||
import { normalizeCookie } from "./cookie-normalize.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import axios, { type AxiosInstance } from "axios";
|
||||
import type {
|
||||
MusicProvider,
|
||||
Song,
|
||||
SongUrlRequestOptions,
|
||||
SongUrlResult,
|
||||
Playlist,
|
||||
LyricLine,
|
||||
@@ -27,6 +29,66 @@ const WBI_MIXIN_KEY_ENC_TAB = [
|
||||
|
||||
const WBI_KEY_TTL_MS = 6 * 60 * 60 * 1000; // wbi keys rotate ~daily; refresh every 6h
|
||||
|
||||
export interface BiliVideoPart {
|
||||
part: number;
|
||||
cid: number;
|
||||
title: string;
|
||||
duration: number;
|
||||
}
|
||||
|
||||
export interface BiliVideoPartsResult {
|
||||
bvid: string;
|
||||
title: string;
|
||||
coverUrl: string;
|
||||
artist: string;
|
||||
parts: BiliVideoPart[];
|
||||
}
|
||||
|
||||
/**
|
||||
* PCDN / P2P edge hosts (xy*.mcdn.bilivideo.cn:<port>, *.szbdyd.com). Their
|
||||
* sessions get cut mid-file, which kills long streams partway (#89, #161),
|
||||
* and a reconnect to the same host rarely recovers.
|
||||
*/
|
||||
const BILI_PCDN_HOST = /\.mcdn\.bilivideo\.cn$|\.szbdyd\.com$/i;
|
||||
|
||||
/**
|
||||
* Pick the audio URL least likely to die mid-stream: the first upos/cos
|
||||
* mirror among baseUrl + backupUrl. When recovering, exhaust untried hosts
|
||||
* before reusing a failed host whose newly signed URL may still work.
|
||||
*/
|
||||
export function pickStableAudioUrl(stream: {
|
||||
baseUrl?: string;
|
||||
base_url?: string;
|
||||
backupUrl?: string[];
|
||||
backup_url?: string[];
|
||||
}, avoidHosts?: ReadonlySet<string>): string | undefined {
|
||||
const primary = stream.baseUrl ?? stream.base_url;
|
||||
const candidates = [primary, ...(stream.backupUrl ?? stream.backup_url ?? [])]
|
||||
.filter((url): url is string => typeof url === "string" && url.length > 0)
|
||||
.map((url) => ({ url, host: URL.parse(url)?.hostname.replace(/\.$/, "") }));
|
||||
const stable = candidates.filter(({ host }) => host && !BILI_PCDN_HOST.test(host));
|
||||
const isUntried = ({ host }: (typeof candidates)[number]) => host && !avoidHosts?.has(host);
|
||||
|
||||
return stable.find(isUntried)?.url ?? candidates.find(isUntried)?.url ?? stable[0]?.url ?? primary;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析带有分P信息的 B站 ID 或 URL。
|
||||
* 支持形如 "BVxxxx", "BVxxxx?p=2", "BVxxxx:p2" 以及完整 URL 等格式,默认 page 为 1。
|
||||
*/
|
||||
export function parseBilibiliId(songId: string): { bvid: string; page: number } {
|
||||
const str = (songId ?? "").trim();
|
||||
const bvMatch = str.match(/BV[0-9A-Za-z]+/i);
|
||||
if (!bvMatch) {
|
||||
return { bvid: str, page: 1 };
|
||||
}
|
||||
const bvid = bvMatch[0];
|
||||
const pageMatch = str.match(/[?&]p=(\d+)|:p?(\d+)/i);
|
||||
const pageStr = pageMatch ? (pageMatch[1] ?? pageMatch[2]) : undefined;
|
||||
const page = pageStr ? parseInt(pageStr, 10) : 1;
|
||||
return { bvid, page: Math.max(1, page) };
|
||||
}
|
||||
|
||||
export class BiliBiliProvider implements MusicProvider {
|
||||
readonly platform = "bilibili" as const;
|
||||
private api: AxiosInstance;
|
||||
@@ -192,18 +254,41 @@ export class BiliBiliProvider implements MusicProvider {
|
||||
}
|
||||
|
||||
async getSongDetail(songId: string): Promise<Song | null> {
|
||||
const { bvid, page } = parseBilibiliId(songId);
|
||||
try {
|
||||
const res = await this.api.get("/x/web-interface/view", {
|
||||
params: { bvid: songId },
|
||||
params: { bvid },
|
||||
headers: this.cookieHeaders,
|
||||
});
|
||||
|
||||
const data = res.data?.data;
|
||||
if (!data) return null;
|
||||
|
||||
// Cache cid for later audio URL fetching
|
||||
if (data.pages?.[0]?.cid) {
|
||||
this.cidCache.set(songId, data.pages[0].cid);
|
||||
const pages = data.pages ?? [];
|
||||
// 缓存所有分P的 cid 映射
|
||||
for (const p of pages) {
|
||||
this.cidCache.set(`${bvid}?p=${p.page}`, p.cid);
|
||||
}
|
||||
if (pages[0]?.cid) {
|
||||
this.cidCache.set(bvid, pages[0].cid);
|
||||
}
|
||||
|
||||
const targetPage = pages.find((p: any) => p.page === page) ?? pages[0];
|
||||
|
||||
// 若为多P视频,返回对应分P的名称与独立时长
|
||||
if (pages.length > 1 && targetPage) {
|
||||
const partTitle = targetPage.part && targetPage.part !== data.title
|
||||
? `${data.title} - P${targetPage.page} ${targetPage.part}`
|
||||
: `${data.title} (P${targetPage.page})`;
|
||||
return {
|
||||
id: `${bvid}?p=${targetPage.page}`,
|
||||
name: partTitle,
|
||||
artist: data.owner?.name ?? "",
|
||||
album: "",
|
||||
duration: targetPage.duration ?? 0,
|
||||
coverUrl: this.normalizeCover(data.pic ?? ""),
|
||||
platform: "bilibili" as const,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -211,7 +296,7 @@ export class BiliBiliProvider implements MusicProvider {
|
||||
name: data.title ?? "",
|
||||
artist: data.owner?.name ?? "",
|
||||
album: "",
|
||||
duration: data.duration ?? 0,
|
||||
duration: targetPage?.duration ?? data.duration ?? 0,
|
||||
coverUrl: this.normalizeCover(data.pic ?? ""),
|
||||
platform: "bilibili" as const,
|
||||
};
|
||||
@@ -220,9 +305,47 @@ export class BiliBiliProvider implements MusicProvider {
|
||||
}
|
||||
}
|
||||
|
||||
/** 获取视频所有分P列表 */
|
||||
async getVideoParts(bvid: string): Promise<BiliVideoPartsResult | null> {
|
||||
const { bvid: cleanBvid } = parseBilibiliId(bvid);
|
||||
try {
|
||||
const res = await this.api.get("/x/web-interface/view", {
|
||||
params: { bvid: cleanBvid },
|
||||
headers: this.cookieHeaders,
|
||||
});
|
||||
|
||||
const data = res.data?.data;
|
||||
if (!data) return null;
|
||||
|
||||
const pages = data.pages ?? [];
|
||||
for (const p of pages) {
|
||||
this.cidCache.set(`${cleanBvid}?p=${p.page}`, p.cid);
|
||||
}
|
||||
if (pages[0]?.cid) {
|
||||
this.cidCache.set(cleanBvid, pages[0].cid);
|
||||
}
|
||||
|
||||
return {
|
||||
bvid: cleanBvid,
|
||||
title: data.title ?? "",
|
||||
coverUrl: this.normalizeCover(data.pic ?? ""),
|
||||
artist: data.owner?.name ?? "",
|
||||
parts: pages.map((p: any) => ({
|
||||
part: p.page,
|
||||
cid: p.cid,
|
||||
title: p.part ?? `P${p.page}`,
|
||||
duration: p.duration ?? 0,
|
||||
})),
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Get CID for a bvid, using cache when available */
|
||||
private async getCid(bvid: string): Promise<number | null> {
|
||||
const cached = this.cidCache.get(bvid);
|
||||
private async getCid(bvid: string, page = 1): Promise<number | null> {
|
||||
const key = page > 1 ? `${bvid}?p=${page}` : bvid;
|
||||
const cached = this.cidCache.get(key) ?? (page === 1 ? this.cidCache.get(`${bvid}?p=1`) : undefined);
|
||||
if (cached) return cached;
|
||||
|
||||
// Limit cache size to prevent unbounded growth
|
||||
@@ -231,20 +354,26 @@ export class BiliBiliProvider implements MusicProvider {
|
||||
if (firstKey) this.cidCache.delete(firstKey);
|
||||
}
|
||||
|
||||
const detail = await this.getSongDetail(bvid);
|
||||
const songId = page > 1 ? `${bvid}?p=${page}` : bvid;
|
||||
const detail = await this.getSongDetail(songId);
|
||||
if (!detail) return null;
|
||||
return this.cidCache.get(bvid) ?? null;
|
||||
return this.cidCache.get(key) ?? this.cidCache.get(`${bvid}?p=${page}`) ?? this.cidCache.get(bvid) ?? null;
|
||||
}
|
||||
|
||||
async getSongUrl(songId: string, _quality?: string): Promise<SongUrlResult | null> {
|
||||
const cid = await this.getCid(songId);
|
||||
async getSongUrl(
|
||||
songId: string,
|
||||
_quality?: string,
|
||||
options?: SongUrlRequestOptions,
|
||||
): Promise<SongUrlResult | null> {
|
||||
const { bvid, page } = parseBilibiliId(songId);
|
||||
const cid = await this.getCid(bvid, page);
|
||||
if (!cid) return null;
|
||||
|
||||
try {
|
||||
const res = await this.api.get("/x/player/playurl", {
|
||||
params: {
|
||||
cid,
|
||||
bvid: songId,
|
||||
bvid,
|
||||
fnval: 16, // DASH format
|
||||
},
|
||||
headers: this.cookieHeaders,
|
||||
@@ -258,7 +387,7 @@ export class BiliBiliProvider implements MusicProvider {
|
||||
(b.bandwidth ?? 0) > (a.bandwidth ?? 0) ? b : a
|
||||
);
|
||||
|
||||
const biliUrl = best.baseUrl ?? best.base_url;
|
||||
const biliUrl = pickStableAudioUrl(best, options?.avoidHosts);
|
||||
return biliUrl ? { url: biliUrl } : null;
|
||||
} catch {
|
||||
return null;
|
||||
@@ -335,7 +464,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;
|
||||
}
|
||||
@@ -2,6 +2,31 @@ import { describe, it, expect, vi } from "vitest";
|
||||
import { mapKugouSong, mapKugouSongs, mapKugouAlbums, mapKugouPlaylist, mapKugouPlaylists, krcToLrc, KugouProvider } from "./kugou.js";
|
||||
import { parseLyrics } from "./netease.js";
|
||||
|
||||
describe("KugouProvider.getSongUrl failure diagnostics", () => {
|
||||
const id = "b3a52a7a958bf0aed0efbba2e9a818b7|32100650|966846";
|
||||
const provider = () => {
|
||||
const p = new KugouProvider();
|
||||
p.setCookie("dfid=test-device");
|
||||
return { bot: p, http: p as unknown as { request: (...args: unknown[]) => Promise<unknown> } };
|
||||
};
|
||||
|
||||
it("distinguishes a provider verification response from a missing stream", async () => {
|
||||
const { bot, http } = provider();
|
||||
vi.spyOn(http, "request").mockResolvedValue({ status: 0, errcode: 20028 });
|
||||
await expect(bot.getSongUrl(id)).rejects.toMatchObject({
|
||||
failure: { code: "provider_verification_required", upstream: { code: 20028 } },
|
||||
});
|
||||
});
|
||||
|
||||
it("carries only safe status fields on a failed HTTP request", async () => {
|
||||
const { bot, http } = provider();
|
||||
vi.spyOn(http, "request").mockRejectedValue({ response: { status: 503, data: { hidden: "test-cookie" } } });
|
||||
await expect(bot.getSongUrl(id)).rejects.toMatchObject({
|
||||
failure: { code: "upstream_request_failed", upstream: { httpStatus: 503 } },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("mapKugouSongs", () => {
|
||||
it("maps the mobile-search song shape to a Song with platform 'kugou'", () => {
|
||||
// Shape captured live from mobilecdn.kugou.com/api/v3/search/song.
|
||||
|
||||
+56
-12
@@ -11,14 +11,14 @@
|
||||
* VERIFICATION NOTE: search and lyrics were verified live during development.
|
||||
* The play-URL endpoint (`/v5/url`) is gated by Kugou's risk-control and may
|
||||
* return `errcode 20028 "本次请求需要验证"` from flagged (datacenter) IPs even
|
||||
* for free songs; on such hosts a logged-in session (QR login below) and/or a
|
||||
* residential IP is required. QR login and VIP audio could not be verified in
|
||||
* the build environment.
|
||||
* for free songs. Surface explicit verification requests to the operator.
|
||||
*/
|
||||
import { normalizeCookie } from "./cookie-normalize.js";
|
||||
import axios, { type AxiosInstance } from "axios";
|
||||
import crypto from "node:crypto";
|
||||
import zlib from "node:zlib";
|
||||
import { parseLyrics } from "./netease.js";
|
||||
import { playbackRequestFailure, SongUrlUnavailable } from "./provider.js";
|
||||
import type {
|
||||
Album,
|
||||
AuthStatus,
|
||||
@@ -442,7 +442,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 +470,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";
|
||||
@@ -639,8 +662,9 @@ export class KugouProvider implements MusicProvider {
|
||||
if (!hash) return null;
|
||||
await this.ensureDfid();
|
||||
const q = quality ? (QUALITY_MAP[quality] ?? this.quality) : this.quality;
|
||||
let data;
|
||||
try {
|
||||
const data = await this.request({
|
||||
data = await this.request({
|
||||
method: "GET",
|
||||
url: "/v5/url",
|
||||
xRouter: "trackercdn.kugou.com",
|
||||
@@ -668,14 +692,34 @@ export class KugouProvider implements MusicProvider {
|
||||
clientver: 11430,
|
||||
},
|
||||
});
|
||||
const urls: string[] = Array.isArray(data?.url) ? data.url : [];
|
||||
const backup: string[] = Array.isArray(data?.backupUrl) ? data.backupUrl : [];
|
||||
const url = urls.find(Boolean) || backup.find(Boolean);
|
||||
if (!url) return null;
|
||||
return { url };
|
||||
} catch {
|
||||
return null;
|
||||
} catch (error) {
|
||||
const responseData = (error as { response?: { data?: unknown } } | null)?.response?.data;
|
||||
throw this.kugouVerificationFailure(songId, responseData) ?? playbackRequestFailure(this.platform, songId, error);
|
||||
}
|
||||
const verification = this.kugouVerificationFailure(songId, data);
|
||||
if (verification) throw verification;
|
||||
const urls: unknown[] = Array.isArray(data?.url) ? data.url : [];
|
||||
const backup: unknown[] = Array.isArray(data?.backupUrl) ? data.backupUrl : [];
|
||||
const url = [...urls, ...backup].find((value): value is string => typeof value === "string" && value.length > 0);
|
||||
if (url) return { url };
|
||||
throw new SongUrlUnavailable({
|
||||
platform: this.platform,
|
||||
songId,
|
||||
code: "unknown",
|
||||
message: "酷狗未返回播放地址",
|
||||
});
|
||||
}
|
||||
|
||||
private kugouVerificationFailure(songId: string, data: unknown): SongUrlUnavailable | undefined {
|
||||
const code = (data as { errcode?: unknown } | null)?.errcode;
|
||||
if (code !== 20028 && code !== "20028") return;
|
||||
return new SongUrlUnavailable({
|
||||
platform: this.platform,
|
||||
songId,
|
||||
code: "provider_verification_required",
|
||||
message: "酷狗要求完成验证(20028),请在酷狗检查账号状态",
|
||||
upstream: { code: 20028 },
|
||||
});
|
||||
}
|
||||
|
||||
async getSongDetail(songId: string): Promise<Song | null> {
|
||||
|
||||
+420
-1
@@ -1,5 +1,75 @@
|
||||
import { once } from "node:events";
|
||||
import { createServer } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { parseLyrics, mapNeteaseAlbums, mapNeteaseSongs, parseNeteaseTrial, NeteaseProvider } from "./netease.js";
|
||||
import { normalizeCookie } from "./cookie-normalize.js";
|
||||
import { RiskControlError, SongUrlUnavailable } from "./provider.js";
|
||||
import {
|
||||
parseLyrics,
|
||||
mapNeteaseAlbums,
|
||||
mapNeteaseSongs,
|
||||
mapNeteaseArtists,
|
||||
parseNeteaseTrial,
|
||||
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", () => {
|
||||
@@ -138,4 +208,353 @@ describe("NeteaseProvider.search pagination", () => {
|
||||
expect(callByType(get, 1000).offset).toBe(0);
|
||||
expect(callByType(get, 10).offset).toBe(0);
|
||||
});
|
||||
|
||||
it("requests artists (type=100) and returns them alongside songs/albums/playlists", async () => {
|
||||
const p = new NeteaseProvider("http://x");
|
||||
const get = vi.fn(async (_path: string, cfg: any) => ({
|
||||
data:
|
||||
cfg.params.type === 100
|
||||
? { result: { artists: [{ id: 6452, name: "Adele", picUrl: "http://p/1.jpg", musicSize: 120 }] } }
|
||||
: { result: { songs: [], playlists: [], albums: [] } },
|
||||
}));
|
||||
(p as any).api = { get };
|
||||
|
||||
const res = await p.search("adele", 20, 0);
|
||||
|
||||
expect(callByType(get, 100).limit).toBe(20);
|
||||
expect(callByType(get, 100).offset).toBe(0);
|
||||
expect(res.artists).toEqual([
|
||||
{
|
||||
id: "6452",
|
||||
name: "Adele",
|
||||
avatarUrl: "http://p/1.jpg",
|
||||
aliases: [],
|
||||
songCount: 120,
|
||||
albumCount: undefined,
|
||||
platform: "netease",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("mapNeteaseArtists (artist search + detail)", () => {
|
||||
it("maps cloudsearch type=100 artist entries", () => {
|
||||
const out = mapNeteaseArtists([
|
||||
{
|
||||
id: 6452,
|
||||
name: "Adele",
|
||||
picUrl: "http://p/1.jpg",
|
||||
alias: ["阿黛尔"],
|
||||
musicSize: 120,
|
||||
albumSize: 9,
|
||||
},
|
||||
]);
|
||||
expect(out).toEqual([
|
||||
{
|
||||
id: "6452",
|
||||
name: "Adele",
|
||||
avatarUrl: "http://p/1.jpg",
|
||||
aliases: ["阿黛尔"],
|
||||
songCount: 120,
|
||||
albumCount: 9,
|
||||
platform: "netease",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("falls back to img1v1Url/alia and drops non-string or empty aliases", () => {
|
||||
const out = mapNeteaseArtists([
|
||||
{ id: 1, name: "X", img1v1Url: "http://p/2.jpg", alia: ["a", "", null, 3] },
|
||||
]);
|
||||
expect(out[0].avatarUrl).toBe("http://p/2.jpg");
|
||||
expect(out[0].aliases).toEqual(["a"]);
|
||||
expect(out[0].songCount).toBeUndefined();
|
||||
expect(out[0].albumCount).toBeUndefined();
|
||||
});
|
||||
|
||||
it("returns [] for empty/null input", () => {
|
||||
expect(mapNeteaseArtists([])).toEqual([]);
|
||||
expect(mapNeteaseArtists(null as any)).toEqual([]);
|
||||
expect(mapNeteaseArtists(undefined as any)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("NeteaseProvider per-user login (#164)", () => {
|
||||
function withGet(p: NeteaseProvider, impl: (path: string, cfg: any) => any) {
|
||||
const get = vi.fn(async (path: string, cfg: any) => ({ data: impl(path, cfg) }));
|
||||
(p as any).api = { get, defaults: { baseURL: "http://127.0.0.1:3001" } };
|
||||
return get;
|
||||
}
|
||||
|
||||
it("pollQrLogin returns the cookie without touching the shared account", async () => {
|
||||
const p = new NeteaseProvider("http://127.0.0.1:3001");
|
||||
p.setCookie("MUSIC_U=shared");
|
||||
withGet(p, () => ({ code: 803, cookie: "MUSIC_U=personal" }));
|
||||
expect(await p.pollQrLogin("k")).toEqual({ status: "confirmed", cookie: "MUSIC_U=personal" });
|
||||
expect(p.getCookie()).toBe("MUSIC_U=shared");
|
||||
});
|
||||
|
||||
it("pollQrLogin maps the waiting / scanned / expired codes", async () => {
|
||||
const p = new NeteaseProvider("http://127.0.0.1:3001");
|
||||
let code = 801;
|
||||
withGet(p, () => ({ code }));
|
||||
expect(await p.pollQrLogin("k")).toEqual({ status: "waiting" });
|
||||
code = 802;
|
||||
expect(await p.pollQrLogin("k")).toEqual({ status: "scanned" });
|
||||
code = 800;
|
||||
expect(await p.pollQrLogin("k")).toEqual({ status: "expired" });
|
||||
});
|
||||
|
||||
it("checkQrCodeStatus still stores the cookie on the shared provider (admin login)", async () => {
|
||||
const p = new NeteaseProvider("http://127.0.0.1:3001");
|
||||
withGet(p, () => ({ code: 803, cookie: "MUSIC_U=admin" }));
|
||||
expect(await p.checkQrCodeStatus("k")).toBe("confirmed");
|
||||
expect(p.getCookie()).toBe("MUSIC_U=admin");
|
||||
});
|
||||
|
||||
it("withCookie gives a view that fetches FM with the other account's cookie", async () => {
|
||||
const p = new NeteaseProvider("http://127.0.0.1:3001");
|
||||
p.setCookie("MUSIC_U=shared");
|
||||
const personal = p.withCookie("MUSIC_U=personal");
|
||||
const get = withGet(personal, () => ({ data: [] }));
|
||||
await personal.getPersonalFm();
|
||||
expect(get.mock.calls[0][1].params.cookie).toBe("MUSIC_U=personal");
|
||||
expect(p.getCookie()).toBe("MUSIC_U=shared");
|
||||
expect(personal.platform).toBe("netease");
|
||||
});
|
||||
});
|
||||
|
||||
describe("NeteaseProvider.getArtistAllSongs (全部歌曲 paging)", () => {
|
||||
const rawSongs = [
|
||||
{ id: 1, name: "A", artists: [{ name: "X" }], album: { name: "Al" }, duration: 200000, fee: 0 },
|
||||
{ id: 2, name: "B", artists: [{ name: "X" }], album: { name: "Al" }, duration: 100000, fee: 0 },
|
||||
];
|
||||
|
||||
function withGet(p: NeteaseProvider, impl: (path: string, cfg: any) => any) {
|
||||
const get = vi.fn(async (path: string, cfg: any) => ({ data: impl(path, cfg) }));
|
||||
(p as any).api = { get };
|
||||
return get;
|
||||
}
|
||||
|
||||
it("pages /artist/songs with order=hot and reports total/hasMore", async () => {
|
||||
const p = new NeteaseProvider("http://x");
|
||||
const get = withGet(p, () => ({ songs: rawSongs, total: 345, more: true }));
|
||||
|
||||
const page = await p.getArtistAllSongs("46487", 50, 50);
|
||||
|
||||
expect(get).toHaveBeenCalledTimes(1);
|
||||
expect(get.mock.calls[0][0]).toBe("/artist/songs");
|
||||
expect(get.mock.calls[0][1].params).toMatchObject({
|
||||
id: "46487",
|
||||
limit: 50,
|
||||
offset: 50,
|
||||
order: "hot",
|
||||
});
|
||||
expect(page.songs.map((s) => s.id)).toEqual(["1", "2"]);
|
||||
expect(page.total).toBe(345);
|
||||
expect(page.hasMore).toBe(true);
|
||||
});
|
||||
|
||||
it("derives hasMore from total when the upstream omits `more`", async () => {
|
||||
const p = new NeteaseProvider("http://x");
|
||||
withGet(p, (_path, cfg) => ({
|
||||
songs: rawSongs.slice(cfg.params.offset, cfg.params.offset + cfg.params.limit),
|
||||
total: 2,
|
||||
}));
|
||||
|
||||
expect((await p.getArtistAllSongs("1", 0, 1)).hasMore).toBe(true);
|
||||
expect((await p.getArtistAllSongs("1", 1, 1)).hasMore).toBe(false);
|
||||
});
|
||||
|
||||
it("clamps limit to 100, offset to >= 0, and derives a total when absent", async () => {
|
||||
const p = new NeteaseProvider("http://x");
|
||||
const get = withGet(p, () => ({ songs: rawSongs }));
|
||||
|
||||
const page = await p.getArtistAllSongs("1", -5, 500);
|
||||
|
||||
expect(get.mock.calls[0][1].params).toMatchObject({ limit: 100, offset: 0 });
|
||||
expect(page.total).toBe(2);
|
||||
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);
|
||||
});
|
||||
|
||||
it("requests a new sidecar cache key for interruption recovery", async () => {
|
||||
const get = vi.fn(async (_url: string, _config: unknown) => ({
|
||||
data: { data: [{ url: "http://cdn.example/track.mp3" }] },
|
||||
}));
|
||||
const provider = providerWithApi(get);
|
||||
await provider.getSongUrl("1");
|
||||
await provider.getSongUrl("1", undefined, { refresh: true });
|
||||
expect(get.mock.calls[0][1]).not.toHaveProperty("params.timestamp");
|
||||
expect(get.mock.calls[1][1]).toMatchObject({ params: { id: "1", timestamp: expect.any(Number) } });
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 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 });
|
||||
});
|
||||
});
|
||||
+271
-17
@@ -1,8 +1,12 @@
|
||||
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,
|
||||
SongUrlResult,
|
||||
SongUrlRequestOptions,
|
||||
Playlist,
|
||||
PlaylistDetail,
|
||||
LyricLine,
|
||||
@@ -10,6 +14,9 @@ import type {
|
||||
QrCodeResult,
|
||||
AuthStatus,
|
||||
Album,
|
||||
Artist,
|
||||
ArtistDetail,
|
||||
ArtistSongPage,
|
||||
} from "./provider.js";
|
||||
|
||||
export function parseLyrics(lrc: string, tlyric?: string): LyricLine[] {
|
||||
@@ -69,6 +76,21 @@ export function mapNeteaseAlbums(raw: any[] | null | undefined): Album[] {
|
||||
}));
|
||||
}
|
||||
|
||||
export function mapNeteaseArtists(raw: any[] | null | undefined): Artist[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
return raw.map((a: any) => ({
|
||||
id: String(a.id),
|
||||
name: a.name ?? "",
|
||||
avatarUrl: a.picUrl ?? a.img1v1Url ?? "",
|
||||
aliases: (a.alias ?? a.alia ?? []).filter(
|
||||
(x: unknown): x is string => typeof x === "string" && x.length > 0
|
||||
),
|
||||
songCount: a.musicSize ?? undefined,
|
||||
albumCount: a.albumSize ?? undefined,
|
||||
platform: "netease",
|
||||
}));
|
||||
}
|
||||
|
||||
export function mapNeteaseSongs(raw: any[] | null | undefined): Song[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
return raw.map((s: any) => ({
|
||||
@@ -96,6 +118,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 },
|
||||
@@ -106,13 +206,38 @@ 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;
|
||||
private cookie = "";
|
||||
private quality = "exhigh";
|
||||
private readonly baseUrl: string;
|
||||
|
||||
constructor(baseUrl: string) {
|
||||
this.baseUrl = baseUrl;
|
||||
this.api = axios.create({
|
||||
baseURL: baseUrl,
|
||||
timeout: 10000,
|
||||
@@ -135,7 +260,7 @@ export class NeteaseProvider implements MusicProvider {
|
||||
// /cloudsearch supports offset for every type. Songs, playlists (type 1000)
|
||||
// and albums (type 10) are all limit/offset-driven so the web can page past
|
||||
// the first page (playlists/albums were previously hardcoded to limit: 10).
|
||||
const [songRes, playlistRes, albumRes] = await Promise.all([
|
||||
const [songRes, playlistRes, albumRes, artistRes] = await Promise.all([
|
||||
this.api.get("/cloudsearch", {
|
||||
params: { keywords: query, type: 1, limit, offset, ...this.cookieParams },
|
||||
}),
|
||||
@@ -151,6 +276,9 @@ export class NeteaseProvider implements MusicProvider {
|
||||
this.api.get("/cloudsearch", {
|
||||
params: { keywords: query, type: 10, limit, offset, ...this.cookieParams },
|
||||
}),
|
||||
this.api.get("/cloudsearch", {
|
||||
params: { keywords: query, type: 100, limit, offset, ...this.cookieParams },
|
||||
}),
|
||||
]);
|
||||
|
||||
const songs: Song[] = mapNeteaseSongs(songRes.data?.result?.songs);
|
||||
@@ -167,20 +295,59 @@ export class NeteaseProvider implements MusicProvider {
|
||||
|
||||
const albums = mapNeteaseAlbums(albumRes.data?.result?.albums);
|
||||
|
||||
return { songs, playlists, albums };
|
||||
const artists = mapNeteaseArtists(artistRes.data?.result?.artists);
|
||||
|
||||
return { songs, playlists, albums, artists };
|
||||
}
|
||||
|
||||
async getSongUrl(songId: string, quality?: string): Promise<SongUrlResult | null> {
|
||||
async getSongUrl(songId: string, quality?: string, options?: SongUrlRequestOptions): 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,
|
||||
// The embedded sidecar caches successful responses for two minutes.
|
||||
...(options?.refresh && { timestamp: Date.now() }),
|
||||
},
|
||||
});
|
||||
} 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 },
|
||||
@@ -215,6 +382,69 @@ export class NeteaseProvider implements MusicProvider {
|
||||
return mapNeteaseSongs(res.data?.songs);
|
||||
}
|
||||
|
||||
async getArtistDetail(artistId: string): Promise<ArtistDetail | null> {
|
||||
// /artists returns { artist, hotSongs }; the hot songs are fetched
|
||||
// separately via /artist/songs (order=hot) so the artist page's three
|
||||
// upstream calls stay independent of each other.
|
||||
const res = await this.api.get("/artists", {
|
||||
params: { id: artistId, ...this.cookieParams },
|
||||
});
|
||||
const a = res.data?.artist;
|
||||
if (!a) return null;
|
||||
return {
|
||||
...mapNeteaseArtists([a])[0],
|
||||
description: a.briefDesc ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
async getArtistSongs(artistId: string, limit = 50): Promise<Song[]> {
|
||||
const res = await this.api.get("/artist/songs", {
|
||||
params: {
|
||||
id: artistId,
|
||||
limit,
|
||||
offset: 0,
|
||||
order: "hot",
|
||||
...this.cookieParams,
|
||||
},
|
||||
});
|
||||
return mapNeteaseSongs(res.data?.songs);
|
||||
}
|
||||
|
||||
async getArtistAlbums(artistId: string, limit = 20): Promise<Album[]> {
|
||||
const res = await this.api.get("/artist/album", {
|
||||
params: { id: artistId, limit, offset: 0, ...this.cookieParams },
|
||||
});
|
||||
return mapNeteaseAlbums(res.data?.hotAlbums);
|
||||
}
|
||||
|
||||
/**
|
||||
* Full catalogue page for the artist page's "全部歌曲" list: /artist/songs
|
||||
* supports real offset paging (Adele reports total 345 with more=true, and
|
||||
* offset=50/100/150 each return a fresh slice of 50). order=hot keeps the page
|
||||
* ordering identical to getArtistSongs so the hot preview and the full list
|
||||
* are one continuous ranking.
|
||||
*/
|
||||
async getArtistAllSongs(artistId: string, offset = 0, limit = 50): Promise<ArtistSongPage> {
|
||||
const safeOffset = Math.max(0, Math.trunc(offset) || 0);
|
||||
const safeLimit = Math.max(1, Math.min(Math.trunc(limit) || 50, 100));
|
||||
const res = await this.api.get("/artist/songs", {
|
||||
params: {
|
||||
id: artistId,
|
||||
limit: safeLimit,
|
||||
offset: safeOffset,
|
||||
order: "hot",
|
||||
...this.cookieParams,
|
||||
},
|
||||
});
|
||||
const songs = mapNeteaseSongs(res.data?.songs);
|
||||
const reported = Number(res.data?.total);
|
||||
const total = Number.isFinite(reported) && reported > 0 ? reported : safeOffset + songs.length;
|
||||
const more = res.data?.more;
|
||||
const hasMore =
|
||||
typeof more === "boolean" ? more : safeOffset + songs.length < total;
|
||||
return { songs, total, hasMore };
|
||||
}
|
||||
|
||||
async getLyrics(songId: string): Promise<LyricLine[]> {
|
||||
const res = await this.api.get("/lyric", {
|
||||
params: { id: songId, ...this.cookieParams },
|
||||
@@ -243,25 +473,47 @@ export class NeteaseProvider implements MusicProvider {
|
||||
async checkQrCodeStatus(
|
||||
key: string
|
||||
): Promise<"waiting" | "scanned" | "confirmed" | "expired"> {
|
||||
const { status, cookie } = await this.pollQrLogin(key);
|
||||
if (cookie) this.cookie = cookie;
|
||||
return status;
|
||||
}
|
||||
|
||||
/**
|
||||
* Poll a QR login and hand back the resulting cookie WITHOUT storing it on
|
||||
* this provider — for a web user linking their own account (#164), which
|
||||
* must never replace the bot's shared login.
|
||||
*/
|
||||
async pollQrLogin(
|
||||
key: string
|
||||
): Promise<{ status: "waiting" | "scanned" | "confirmed" | "expired"; cookie?: string }> {
|
||||
const res = await this.api.get("/login/qr/check", {
|
||||
params: { key, timestamp: Date.now() },
|
||||
});
|
||||
const code = res.data?.code;
|
||||
switch (code) {
|
||||
switch (res.data?.code) {
|
||||
case 801:
|
||||
return "waiting";
|
||||
return { status: "waiting" };
|
||||
case 802:
|
||||
return "scanned";
|
||||
return { status: "scanned" };
|
||||
case 803:
|
||||
if (res.data?.cookie) {
|
||||
this.cookie = res.data.cookie;
|
||||
}
|
||||
return "confirmed";
|
||||
return res.data?.cookie
|
||||
? { status: "confirmed", cookie: res.data.cookie }
|
||||
: { status: "confirmed" };
|
||||
default:
|
||||
return "expired";
|
||||
return { status: "expired" };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A provider for the same API server logged in as another account (#164):
|
||||
* a web user's personal FM uses their own taste instead of the shared login.
|
||||
*/
|
||||
withCookie(cookie: string): NeteaseProvider {
|
||||
const view = new NeteaseProvider(this.baseUrl);
|
||||
view.setQuality(this.quality);
|
||||
view.setCookie(cookie);
|
||||
return view;
|
||||
}
|
||||
|
||||
async sendSmsCode(phone: string): Promise<boolean> {
|
||||
const res = await this.api.get("/captcha/sent", {
|
||||
params: { phone },
|
||||
@@ -280,7 +532,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 {
|
||||
|
||||
+170
-1
@@ -34,6 +34,106 @@ 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"
|
||||
/** The upstream HTTP request failed or the expected API was unreachable. */
|
||||
| "upstream_request_failed"
|
||||
/** The music service explicitly asked the user to complete verification. */
|
||||
| "provider_verification_required"
|
||||
/** 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;
|
||||
/** Selected non-secret diagnostic fields. Logs only, never shown directly. */
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/** Preserve typed status for troubleshooting without forwarding request or response data. */
|
||||
export function playbackRequestFailure(
|
||||
platform: "qq" | "kugou",
|
||||
songId: string,
|
||||
error: unknown,
|
||||
): SongUrlUnavailable {
|
||||
const raw = error as { code?: unknown; response?: { status?: unknown } } | null;
|
||||
const status = raw?.response?.status;
|
||||
const httpStatus = typeof status === "number" && Number.isInteger(status) && status >= 100 && status < 600
|
||||
? status : undefined;
|
||||
const name = platform === "qq" ? "QQ 音乐 API" : "酷狗";
|
||||
const message = httpStatus ? `${name}播放请求失败(HTTP ${httpStatus})`
|
||||
: raw?.code === "QQ_API_PORT_CONFLICT" && platform === "qq" ? "QQ 音乐 API 端口被其他服务占用,请检查 qqMusicApiPort"
|
||||
: raw?.code === "ECONNREFUSED" && platform === "qq" ? "无法连接 QQ 音乐 API,请检查服务启动与端口"
|
||||
: raw?.code === "ECONNABORTED" || raw?.code === "ETIMEDOUT" ? `${name}播放请求超时`
|
||||
: `${name}播放请求失败,请检查服务与网络连接`;
|
||||
return new SongUrlUnavailable({
|
||||
platform,
|
||||
songId,
|
||||
code: "upstream_request_failed",
|
||||
message,
|
||||
upstream: httpStatus ? { httpStatus } : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
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 +142,7 @@ export interface Playlist {
|
||||
platform: Platform;
|
||||
}
|
||||
|
||||
|
||||
export interface PlaylistDetail {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -59,6 +160,34 @@ export interface Album {
|
||||
platform: Platform;
|
||||
}
|
||||
|
||||
/** An artist / singer entity. Only sources with a real artist concept expose
|
||||
* these (NetEase, QQ); the others simply never return `SearchResult.artists`
|
||||
* and leave the optional provider methods unimplemented. */
|
||||
export interface Artist {
|
||||
id: string;
|
||||
name: string;
|
||||
avatarUrl: string;
|
||||
platform: Platform;
|
||||
/** Alternate names / romanizations (NetEase alias, QQ other_name). */
|
||||
aliases?: string[];
|
||||
songCount?: number;
|
||||
albumCount?: number;
|
||||
}
|
||||
|
||||
export interface ArtistDetail extends Artist {
|
||||
/** Short biography, when the source provides one. */
|
||||
description?: string;
|
||||
}
|
||||
|
||||
/** One page of an artist's COMPLETE catalogue (the "全部歌曲" list), as opposed
|
||||
* to `getArtistSongs`, which only ever returns the hot top-N. */
|
||||
export interface ArtistSongPage {
|
||||
songs: Song[];
|
||||
/** Total tracks the source reports for this artist (best effort). */
|
||||
total: number;
|
||||
hasMore: boolean;
|
||||
}
|
||||
|
||||
export interface LyricLine {
|
||||
time: number; // seconds
|
||||
text: string;
|
||||
@@ -69,6 +198,8 @@ export interface SearchResult {
|
||||
songs: Song[];
|
||||
playlists: Playlist[];
|
||||
albums: Album[];
|
||||
/** Present only for sources with an artist entity (NetEase, QQ). */
|
||||
artists?: Artist[];
|
||||
}
|
||||
|
||||
export interface QrCodeResult {
|
||||
@@ -83,11 +214,18 @@ export interface AuthStatus {
|
||||
avatarUrl?: string;
|
||||
}
|
||||
|
||||
export interface SongUrlRequestOptions {
|
||||
/** CDN hosts that already failed around this playback position (where supported). */
|
||||
avoidHosts?: ReadonlySet<string>;
|
||||
/** Resolve after an interruption without reusing a cached playback URL. */
|
||||
refresh?: boolean;
|
||||
}
|
||||
|
||||
export interface MusicProvider {
|
||||
readonly platform: Platform;
|
||||
|
||||
search(query: string, limit?: number, offset?: number): Promise<SearchResult>;
|
||||
getSongUrl(songId: string, quality?: string): Promise<SongUrlResult | null>;
|
||||
getSongUrl(songId: string, quality?: string, options?: SongUrlRequestOptions): Promise<SongUrlResult | null>;
|
||||
setQuality(quality: string): void;
|
||||
getQuality(): string;
|
||||
getSongDetail(songId: string): Promise<Song | null>;
|
||||
@@ -104,8 +242,39 @@ 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[]>;
|
||||
getPlaylistDetail?(playlistId: string): Promise<PlaylistDetail | null>;
|
||||
getArtistDetail?(artistId: string): Promise<ArtistDetail | null>;
|
||||
/** The artist's most popular tracks, best-first. */
|
||||
getArtistSongs?(artistId: string, limit?: number): Promise<Song[]>;
|
||||
/** One page of the artist's full catalogue, best-first. Sources that can only
|
||||
* expose a fixed top-N list leave this unimplemented (the route then 501s and
|
||||
* the web hides the "全部歌曲" section). */
|
||||
getArtistAllSongs?(
|
||||
artistId: string,
|
||||
offset?: number,
|
||||
limit?: number
|
||||
): Promise<ArtistSongPage>;
|
||||
getArtistAlbums?(artistId: string, limit?: number): Promise<Album[]>;
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
+554
-1
@@ -8,7 +8,95 @@ vi.mock("axios", () => ({
|
||||
default: { create: () => ({ get: mockGet, post: mockPost }) },
|
||||
}));
|
||||
|
||||
import { mapQqAlbums, mapQqSongs, parseQqTrial, QQMusicProvider } from "./qq.js";
|
||||
import { mapQqAlbums, mapQqArtists, mapQqSongs, parseQqTrial, QQMusicProvider } from "./qq.js";
|
||||
|
||||
describe("QQ playback sidecar contract", () => {
|
||||
beforeEach(() => {
|
||||
mockGet.mockReset();
|
||||
});
|
||||
|
||||
it("maps app playback quality to the installed sidecar format", async () => {
|
||||
const provider = new QQMusicProvider("http://127.0.0.1:3200");
|
||||
provider.setQuality("lossless");
|
||||
mockGet.mockResolvedValue({ data: { data: { playUrl: { abc: { url: "https://example.com/audio" } } } } });
|
||||
await expect(provider.getSongUrl("abc")).resolves.toMatchObject({ url: "https://example.com/audio" });
|
||||
expect(mockGet).toHaveBeenLastCalledWith("/getMusicPlay", { params: expect.objectContaining({ songmid: "abc", quality: "flac" }) });
|
||||
});
|
||||
|
||||
it.each([320, "320"])("accepts QQ quality %j from the settings API", async (quality) => {
|
||||
const provider = new QQMusicProvider("http://127.0.0.1:3200");
|
||||
provider.setQuality(quality);
|
||||
expect(provider.getQuality()).toBe("320");
|
||||
mockGet.mockResolvedValue({ data: { data: { playUrl: { abc: { url: "https://example.com/audio" } } } } });
|
||||
await provider.getSongUrl("abc");
|
||||
expect(mockGet).toHaveBeenLastCalledWith("/getMusicPlay", { params: expect.objectContaining({ quality: "320" }) });
|
||||
});
|
||||
|
||||
it("resolves a numeric ID to a MID before asking the sidecar for playback", async () => {
|
||||
const provider = new QQMusicProvider("http://127.0.0.1:3200");
|
||||
mockGet.mockResolvedValueOnce({ data: { response: { songinfo: { data: { track_info: { mid: "abc" } } } } } });
|
||||
mockGet.mockResolvedValueOnce({ data: { data: { playUrl: { abc: { url: "https://example.com/audio" } } } } });
|
||||
await expect(provider.getSongUrl("12345")).resolves.toMatchObject({ url: "https://example.com/audio" });
|
||||
expect(mockGet).toHaveBeenNthCalledWith(1, "/getSongInfo", { params: expect.objectContaining({ songid: "12345" }) });
|
||||
expect(mockGet).toHaveBeenNthCalledWith(2, "/getMusicPlay", { params: expect.objectContaining({ songmid: "abc" }) });
|
||||
});
|
||||
|
||||
it("separates a broken sidecar from a track without a URL", async () => {
|
||||
const provider = new QQMusicProvider("http://127.0.0.1:3200");
|
||||
mockGet.mockRejectedValue({ response: { status: 502, data: { hidden: "test-cookie" } } });
|
||||
await expect(provider.getSongUrl("abc")).rejects.toMatchObject({
|
||||
failure: { code: "upstream_request_failed", upstream: { httpStatus: 502 } },
|
||||
});
|
||||
expect(mockGet).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("keeps tracks playable at a supported fallback quality during batch preflight", async () => {
|
||||
const provider = new QQMusicProvider("http://127.0.0.1:3200");
|
||||
provider.setQuality("exhigh");
|
||||
mockGet.mockResolvedValueOnce({ data: { data: { playUrl: { abc: { url: "https://example.com/audio1" }, def: { url: "" } } } } });
|
||||
mockGet.mockResolvedValueOnce({ data: { data: { playUrl: { def: { url: "https://example.com/audio2" } } } } });
|
||||
await expect(provider.getPlayableSongIds(["abc", "def"])).resolves.toEqual(new Set(["abc", "def"]));
|
||||
expect(mockGet).toHaveBeenNthCalledWith(2, "/getMusicPlay", { params: expect.objectContaining({ songmid: "def", quality: "128" }) });
|
||||
});
|
||||
|
||||
it.each([{}, { abc: { url: "" } }, { abc: { url: "" }, def: { url: 17 } }])(
|
||||
"does not interpret incomplete or unconfirmed HTTP 200 play maps as unavailable",
|
||||
async (playUrl) => {
|
||||
const provider = new QQMusicProvider("http://127.0.0.1:3200");
|
||||
provider.setQuality("128");
|
||||
mockGet.mockResolvedValue({ status: 200, data: { data: { playUrl } } });
|
||||
await expect(provider.getPlayableSongIds(["abc", "def"])).resolves.toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
it("does not treat an upstream error inside HTTP 200 as a final no-URL result", async () => {
|
||||
const provider = new QQMusicProvider("http://127.0.0.1:3200");
|
||||
provider.setQuality("128");
|
||||
mockGet.mockResolvedValue({ status: 200, data: { data: { code: 0, req_0: { code: 502 }, playUrl: { abc: { url: "" } } } } });
|
||||
await expect(provider.getPlayableSongIds(["abc"])).resolves.toBeNull();
|
||||
await expect(provider.getSongUrl("abc")).rejects.toMatchObject({
|
||||
failure: { code: "upstream_request_failed", upstream: { code: 502 } },
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts a fully confirmed no-play result and a numeric HTTP envelope success code", async () => {
|
||||
const provider = new QQMusicProvider("http://127.0.0.1:3200");
|
||||
provider.setQuality("128");
|
||||
mockGet.mockResolvedValue({ status: 200, data: { code: 200, data: {
|
||||
code: "0", req_0: { code: 0, data: { midurlinfo: [{ songmid: "abc", purl: "" }] } }, playUrl: { abc: { url: "" } },
|
||||
} } });
|
||||
await expect(provider.getPlayableSongIds(["abc"])).resolves.toEqual(new Set());
|
||||
});
|
||||
|
||||
it("stops playback before sending a request when the sidecar port is occupied by another service", async () => {
|
||||
const guard = () => { throw Object.assign(new Error("QQ sidecar port conflict"), { code: "QQ_API_PORT_CONFLICT" }); };
|
||||
const provider = new QQMusicProvider("http://127.0.0.1:3200", undefined, guard);
|
||||
await expect(provider.getSongUrl("abc")).rejects.toMatchObject({
|
||||
failure: { code: "upstream_request_failed", message: expect.stringContaining("端口") },
|
||||
});
|
||||
expect(mockGet).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("QQ adapter", () => {
|
||||
it("mapQqSongs maps QQMusicApi-style song entries", () => {
|
||||
@@ -171,4 +259,469 @@ describe("QQMusicProvider.search pagination", () => {
|
||||
expect(songCall, "expected a client_search_cp song call").toBeTruthy();
|
||||
expect(songCall![1].params.p).toBe(2);
|
||||
});
|
||||
|
||||
it("adds the singer sub-request (search_type 1) to the same musicu batch", async () => {
|
||||
musicuOk();
|
||||
const p = new QQMusicProvider("http://x");
|
||||
await p.search("周杰伦", 20, 0);
|
||||
|
||||
const d = musicuReqData();
|
||||
expect(d.req_artist.param.search_type).toBe(1);
|
||||
expect(d.req_artist.param.num_per_page).toBe(20);
|
||||
expect(d.req_artist.param.page_num).toBe(1);
|
||||
});
|
||||
|
||||
it("returns singers even when the song list is empty (no client_search_cp fallback)", async () => {
|
||||
mockGet.mockImplementation(async (url: string) => {
|
||||
if (url === "/cgi-bin/musicu.fcg") {
|
||||
return {
|
||||
data: {
|
||||
req_0: { data: { body: { song: { list: [] } } } },
|
||||
req_album: { data: { body: { album: { list: [] } } } },
|
||||
req_playlist: { data: { body: { songlist: { list: [] } } } },
|
||||
req_artist: {
|
||||
data: { body: { singer: { list: [{ singerMID: "m1", singerName: "Adele", songNum: 88 }] } } },
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
return { data: {} };
|
||||
});
|
||||
const p = new QQMusicProvider("http://x");
|
||||
const res = await p.search("Adele", 20, 0);
|
||||
|
||||
expect(res.songs).toEqual([]);
|
||||
expect(res.artists).toEqual([
|
||||
{
|
||||
id: "m1",
|
||||
name: "Adele",
|
||||
avatarUrl: "https://y.gtimg.cn/music/photo_new/T001R500x500M000m1.jpg",
|
||||
songCount: 88,
|
||||
albumCount: undefined,
|
||||
platform: "qq",
|
||||
},
|
||||
]);
|
||||
expect(mockGet.mock.calls.some((c: any[]) => c[0] === "/soso/fcgi-bin/client_search_cp")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("mapQqArtists (singer search + detail)", () => {
|
||||
it("maps singer list entries and builds the 500px portrait from the MID", () => {
|
||||
const out = mapQqArtists([
|
||||
{
|
||||
singerMID: "abc",
|
||||
singerName: "周杰伦",
|
||||
singerPic: "http://y.gtimg.cn/music/photo_new/T001R150x150M000abc_11.jpg",
|
||||
songNum: 500,
|
||||
albumNum: 30,
|
||||
},
|
||||
]);
|
||||
expect(out).toEqual([
|
||||
{
|
||||
id: "abc",
|
||||
name: "周杰伦",
|
||||
avatarUrl: "https://y.gtimg.cn/music/photo_new/T001R500x500M000abc.jpg",
|
||||
songCount: 500,
|
||||
albumCount: 30,
|
||||
platform: "qq",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("falls back to the given picture when no MID is present", () => {
|
||||
const out = mapQqArtists([
|
||||
{ singerID: 42, singerName: "Y", singerPic: "https://y.gtimg.cn/music/photo_new/x.jpg" },
|
||||
]);
|
||||
expect(out).toEqual([
|
||||
{
|
||||
id: "42",
|
||||
name: "Y",
|
||||
avatarUrl: "https://y.gtimg.cn/music/photo_new/x.jpg",
|
||||
songCount: undefined,
|
||||
albumCount: undefined,
|
||||
platform: "qq",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("drops entries without an id or name and tolerates empty input", () => {
|
||||
expect(mapQqArtists([{ singerName: "no id" }, { singerMID: "x" }])).toEqual([]);
|
||||
expect(mapQqArtists([])).toEqual([]);
|
||||
expect(mapQqArtists(null as any)).toEqual([]);
|
||||
expect(mapQqArtists(undefined as any)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("QQMusicProvider.getArtistAllSongs (album aggregation)", () => {
|
||||
beforeEach(() => {
|
||||
mockGet.mockReset();
|
||||
});
|
||||
|
||||
function songRaw(mid: string, title: string) {
|
||||
return { mid, title, singer: [{ name: "Adele" }], album: { mid: "al1", name: "Album" }, interval: 200 };
|
||||
}
|
||||
|
||||
it("does not cache a hot-only catalogue when the singer lookup for the album scan fails", async () => {
|
||||
let singerCalls = 0;
|
||||
mockGet.mockImplementation(async (url: string, cfg: any) => {
|
||||
if (url === "/getAlbumInfo") {
|
||||
return { data: { response: { data: { list: [songRaw("album-track", "Album track")] } } } };
|
||||
}
|
||||
if (url !== "/cgi-bin/musicu.fcg") return { data: {} };
|
||||
const data = JSON.parse(cfg.params.data);
|
||||
if (data.req_0) {
|
||||
if (++singerCalls === 2) throw new Error("temporary singer lookup failure");
|
||||
return { data: { req_0: { data: { singer_info: { mid: "m1", name: "Adele" }, songlist: [songRaw("hot", "Hot")] } } } };
|
||||
}
|
||||
const list = data.req_album.param.page_num === 1 ? [{ albumMID: "al1", singerMID: "m1" }] : [];
|
||||
return { data: { req_album: { data: { body: { album: { list } } } } } };
|
||||
});
|
||||
const provider = new QQMusicProvider("http://x");
|
||||
expect((await provider.getArtistAllSongs("m1")).songs.map((s) => s.id)).toEqual(["hot"]);
|
||||
expect((await provider.getArtistAllSongs("m1")).songs.map((s) => s.id)).toEqual(["hot", "album-track"]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ code: 0, req_album: { code: 2000 } },
|
||||
{ code: 500, req_album: { data: { body: { album: { list: [] } } } } },
|
||||
{ req_album: { data: { body: {} } } },
|
||||
{ req_album: { data: { body: { album: { list: {} } } } } },
|
||||
])("does not cache logical or malformed album-search failure %#", async (failedResponse) => {
|
||||
let failed = true;
|
||||
mockGet.mockImplementation(async (url: string, cfg: any) => {
|
||||
if (url === "/getAlbumInfo") return { data: { response: { data: { list: [songRaw("album-track", "Album track")] } } } };
|
||||
if (url !== "/cgi-bin/musicu.fcg") return { data: {} };
|
||||
const data = JSON.parse(cfg.params.data);
|
||||
if (data.req_0) return { data: { req_0: { data: { singer_info: { mid: "m1", name: "Adele" }, songlist: [songRaw("hot", "Hot")] } } } };
|
||||
if (failed) return { data: failedResponse };
|
||||
const list = data.req_album.param.page_num === 1 ? [{ albumMID: "al1", singerMID: "m1" }] : [];
|
||||
return { data: { code: 0, req_album: { code: 0, data: { body: { album: { list } } } } } };
|
||||
});
|
||||
const provider = new QQMusicProvider("http://x");
|
||||
const degraded = await provider.getArtistAllSongs("m1");
|
||||
expect(degraded.songs.map((s) => s.id)).toEqual(["hot"]);
|
||||
failed = false;
|
||||
expect((await provider.getArtistAllSongs("m1")).songs.map((s) => s.id)).toEqual(["hot", "album-track"]);
|
||||
});
|
||||
|
||||
it("includes more than 50 short albums when the catalogue is below the 500-song ceiling", async () => {
|
||||
mockCatalogue({
|
||||
hot: [songRaw("hot", "Hot")],
|
||||
albumSearch: (page) => Array.from({ length: page === 1 ? 50 : page === 2 ? 10 : 0 }, (_, i) => ({ albumMID: `al${(page - 1) * 50 + i}`, singerMID: "m1" })),
|
||||
albumSongs: Object.fromEntries(Array.from({ length: 60 }, (_, i) => [`al${i}`, [songRaw(`s${i}`, `${i}`)]])),
|
||||
});
|
||||
const result = await new QQMusicProvider("http://x").getArtistAllSongs("m1", 0, 100);
|
||||
expect(result.songs).toHaveLength(61);
|
||||
expect(result.total).toBe(61);
|
||||
expect(result.hasMore).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ response: { code: 2000, data: { list: [] } } },
|
||||
{ response: { data: {} } },
|
||||
{ response: { data: { list: [{}] } } },
|
||||
{ response: { data: { list: [{ mid: "" }] } } },
|
||||
{ response: { data: { list: [{ mid: " " }] } } },
|
||||
{ response: { data: { list: [{ mid: {} }] } } },
|
||||
])("does not cache a catalogue after a logical or malformed album-song failure %#", async (failedResponse) => {
|
||||
let failed = true;
|
||||
mockGet.mockImplementation(async (url: string, cfg: any) => {
|
||||
if (url === "/getAlbumInfo") return { data: failed ? failedResponse : { response: { data: { list: [songRaw("album-track", "Album track")] } } } };
|
||||
if (url !== "/cgi-bin/musicu.fcg") return { data: {} };
|
||||
const data = JSON.parse(cfg.params.data);
|
||||
if (data.req_0) return { data: { req_0: { data: { singer_info: { mid: "m1", name: "Adele" }, songlist: [songRaw("hot", "Hot")] } } } };
|
||||
const list = data.req_album.param.page_num === 1 ? [{ albumMID: "al1", singerMID: "m1" }] : [];
|
||||
return { data: { req_album: { data: { body: { album: { list } } } } } };
|
||||
});
|
||||
const provider = new QQMusicProvider("http://x");
|
||||
expect((await provider.getArtistAllSongs("m1")).songs.map((s) => s.id)).toEqual(["hot"]);
|
||||
failed = false;
|
||||
expect((await provider.getArtistAllSongs("m1")).songs.map((s) => s.id)).toEqual(["hot", "album-track"]);
|
||||
});
|
||||
|
||||
it("does not cache a catalogue whose hot-song rows contain no song identifier", async () => {
|
||||
let failed = true;
|
||||
mockGet.mockImplementation(async (url: string, cfg: any) => {
|
||||
if (url === "/getAlbumInfo") return { data: { response: { data: { list: [songRaw("album-track", "Album track")] } } } };
|
||||
if (url !== "/cgi-bin/musicu.fcg") return { data: {} };
|
||||
const data = JSON.parse(cfg.params.data);
|
||||
if (data.req_0) return { data: { req_0: { data: { singer_info: { mid: "m1", name: "Adele" }, songlist: failed ? [{}] : [songRaw("hot", "Hot")] } } } };
|
||||
const list = data.req_album.param.page_num === 1 ? [{ albumMID: "al1", singerMID: "m1" }] : [];
|
||||
return { data: { req_album: { data: { body: { album: { list } } } } } };
|
||||
});
|
||||
const provider = new QQMusicProvider("http://x");
|
||||
await provider.getArtistAllSongs("m1");
|
||||
failed = false;
|
||||
const recovered = await provider.getArtistAllSongs("m1");
|
||||
expect(recovered.songs.map((s) => s.id)).toEqual(["hot", "album-track"]);
|
||||
expect(recovered.hasMore).toBe(false);
|
||||
});
|
||||
|
||||
it("bounds a large catalogue at 500 unique songs while reporting remaining tracks", async () => {
|
||||
mockCatalogue({
|
||||
hot: [songRaw("hot", "Hot")],
|
||||
albumSearch: () => [{ albumMID: "al1", singerMID: "m1" }],
|
||||
albumSongs: { al1: Array.from({ length: 600 }, (_, i) => songRaw(`s${i}`, `${i}`)) },
|
||||
});
|
||||
const provider = new QQMusicProvider("http://x");
|
||||
const last = await provider.getArtistAllSongs("m1", 400, 100);
|
||||
expect(last.songs).toHaveLength(100);
|
||||
expect(last.hasMore).toBe(true);
|
||||
expect(last.total).toBeGreaterThan(500);
|
||||
expect((await provider.getArtistAllSongs("m1", 500, 100)).songs).toEqual([]);
|
||||
});
|
||||
|
||||
it("reports a complete catalogue of exactly 500 songs without an extra page", async () => {
|
||||
mockCatalogue({
|
||||
hot: [songRaw("hot", "Hot")],
|
||||
albumSearch: () => [{ albumMID: "al1", singerMID: "m1" }],
|
||||
albumSongs: { al1: Array.from({ length: 499 }, (_, i) => songRaw(`s${i}`, `${i}`)) },
|
||||
});
|
||||
const last = await new QQMusicProvider("http://x").getArtistAllSongs("m1", 400, 100);
|
||||
expect(last.total).toBe(500);
|
||||
expect(last.hasMore).toBe(false);
|
||||
});
|
||||
|
||||
it("does not treat a page without matching singers as the end of the search", async () => {
|
||||
mockCatalogue({
|
||||
hot: [songRaw("hot", "Hot")],
|
||||
albumSearch: (page) => page === 1
|
||||
? Array.from({ length: 50 }, (_, i) => ({ albumMID: `other${i}`, singerMID: "other" }))
|
||||
: page === 2 ? [{ albumMID: "al1", singerMID: "m1" }] : [],
|
||||
albumSongs: { al1: [songRaw("album-track", "Album track")] },
|
||||
});
|
||||
expect((await new QQMusicProvider("http://x").getArtistAllSongs("m1")).songs.map((s) => s.id)).toEqual(["hot", "album-track"]);
|
||||
});
|
||||
|
||||
it("leaves repeated search pages incomplete and retryable", async () => {
|
||||
mockCatalogue({
|
||||
hot: [songRaw("hot", "Hot")],
|
||||
albumSearch: () => Array.from({ length: 50 }, (_, i) => ({ albumMID: `al${i}`, singerMID: "m1" })),
|
||||
});
|
||||
const provider = new QQMusicProvider("http://x");
|
||||
expect((await provider.getArtistAllSongs("m1")).hasMore).toBe(true);
|
||||
mockCatalogue({ hot: [songRaw("hot", "Hot")], albumSearch: () => [] });
|
||||
const recovered = await provider.getArtistAllSongs("m1");
|
||||
expect(recovered.total).toBe(1);
|
||||
expect(recovered.hasMore).toBe(false);
|
||||
});
|
||||
|
||||
it("bounds endless search pages of empty albums and leaves the partial result uncached", async () => {
|
||||
let searchCalls = 0;
|
||||
mockCatalogue({
|
||||
hot: [songRaw("hot", "Hot")],
|
||||
albumSearch: (page) => {
|
||||
if (++searchCalls > 110) throw new Error("unbounded upstream scan");
|
||||
return Array.from({ length: 50 }, (_, i) => ({ albumMID: `al${page}-${i}`, singerMID: "m1" }));
|
||||
},
|
||||
});
|
||||
const provider = new QQMusicProvider("http://x");
|
||||
const partial = await provider.getArtistAllSongs("m1");
|
||||
expect(searchCalls).toBeLessThanOrEqual(100);
|
||||
expect(partial.hasMore).toBe(true);
|
||||
mockCatalogue({ hot: [songRaw("hot", "Hot")], albumSearch: () => [] });
|
||||
expect((await provider.getArtistAllSongs("m1")).hasMore).toBe(false);
|
||||
});
|
||||
|
||||
/** singer detail (top 50) + album search pages + per-album song lists. */
|
||||
function mockCatalogue(opts: {
|
||||
hot?: any[];
|
||||
albumSearch?: (page: number) => any[];
|
||||
albumSongs?: Record<string, any[]>;
|
||||
albumInfoFails?: boolean;
|
||||
}) {
|
||||
mockGet.mockImplementation(async (url: string, cfg: any) => {
|
||||
if (url === "/cgi-bin/musicu.fcg") {
|
||||
const data = JSON.parse(cfg.params.data);
|
||||
if (data.req_0) {
|
||||
return {
|
||||
data: {
|
||||
req_0: {
|
||||
data: {
|
||||
singer_info: { mid: "m1", name: "Adele" },
|
||||
total_song: 250,
|
||||
songlist: opts.hot ?? [],
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
const page = data.req_album?.param?.page_num ?? 1;
|
||||
return {
|
||||
data: {
|
||||
req_album: { data: { body: { album: { list: (opts.albumSearch ?? (() => []))(page) } } } },
|
||||
},
|
||||
};
|
||||
}
|
||||
if (url === "/getAlbumInfo") {
|
||||
if (opts.albumInfoFails) throw new Error("album down");
|
||||
return { data: { response: { data: { list: opts.albumSongs?.[cfg.params.albummid] ?? [] } } } };
|
||||
}
|
||||
return { data: {} };
|
||||
});
|
||||
}
|
||||
|
||||
it("merges the hot tracks with every album track, de-duplicated and paged", async () => {
|
||||
mockCatalogue({
|
||||
hot: [songRaw("s1", "Hot 1"), songRaw("s2", "Hot 2")],
|
||||
albumSearch: () => [
|
||||
{ albumMID: "al1", albumName: "A", singerMID: "m1" },
|
||||
{ albumMID: "al2", albumName: "B", singerMID: "m1" },
|
||||
{ albumMID: "other", albumName: "C", singerMID: "m9" },
|
||||
],
|
||||
albumSongs: {
|
||||
al1: [songRaw("s1", "Hot 1"), songRaw("s3", "Album 1")],
|
||||
al2: [songRaw("s4", "Album 2")],
|
||||
},
|
||||
});
|
||||
const p = new QQMusicProvider("http://x");
|
||||
|
||||
const page = await p.getArtistAllSongs("m1", 0, 10);
|
||||
|
||||
expect(page.songs.map((s) => s.id)).toEqual(["s1", "s2", "s3", "s4"]);
|
||||
expect(page.total).toBe(4);
|
||||
expect(page.hasMore).toBe(false);
|
||||
|
||||
// The unrelated album (singerMID m9) is never fetched.
|
||||
const albumCalls = mockGet.mock.calls.filter((c: any[]) => c[0] === "/getAlbumInfo");
|
||||
expect(albumCalls.map((c: any[]) => c[1].params.albummid).sort()).toEqual(["al1", "al2"]);
|
||||
// A short page exhausts the search without another upstream request.
|
||||
const searchPages = mockGet.mock.calls
|
||||
.filter((c: any[]) => c[0] === "/cgi-bin/musicu.fcg")
|
||||
.map((c: any[]) => JSON.parse(c[1].params.data).req_album?.param?.page_num)
|
||||
.filter(Boolean);
|
||||
expect(searchPages).toEqual([1]);
|
||||
});
|
||||
|
||||
it("slices pages with offset/limit and reports hasMore", async () => {
|
||||
mockCatalogue({
|
||||
hot: [songRaw("s1", "1"), songRaw("s2", "2"), songRaw("s3", "3")],
|
||||
albumSearch: () => [],
|
||||
});
|
||||
const p = new QQMusicProvider("http://x");
|
||||
|
||||
const first = await p.getArtistAllSongs("m1", 0, 2);
|
||||
expect(first.songs.map((s) => s.id)).toEqual(["s1", "s2"]);
|
||||
expect(first.total).toBe(3);
|
||||
expect(first.hasMore).toBe(true);
|
||||
|
||||
const second = await p.getArtistAllSongs("m1", 2, 2);
|
||||
expect(second.songs.map((s) => s.id)).toEqual(["s3"]);
|
||||
expect(second.hasMore).toBe(false);
|
||||
});
|
||||
|
||||
it("caches the assembled catalogue (one upstream sweep per singer)", async () => {
|
||||
mockCatalogue({
|
||||
hot: [songRaw("s1", "1")],
|
||||
albumSearch: () => [{ albumMID: "al1", albumName: "A", singerMID: "m1" }],
|
||||
albumSongs: { al1: [songRaw("s9", "9")] },
|
||||
});
|
||||
const p = new QQMusicProvider("http://x");
|
||||
|
||||
await p.getArtistAllSongs("m1", 0, 50);
|
||||
const callsAfterFirst = mockGet.mock.calls.length;
|
||||
const page = await p.getArtistAllSongs("m1", 0, 50);
|
||||
|
||||
expect(mockGet.mock.calls.length).toBe(callsAfterFirst);
|
||||
expect(page.songs.map((s) => s.id)).toEqual(["s1", "s9"]);
|
||||
});
|
||||
|
||||
it("degrades to the hot list when album lookups fail", async () => {
|
||||
mockCatalogue({
|
||||
hot: [songRaw("s1", "1")],
|
||||
albumSearch: () => [{ albumMID: "al1", albumName: "A", singerMID: "m1" }],
|
||||
albumInfoFails: true,
|
||||
});
|
||||
const p = new QQMusicProvider("http://x");
|
||||
|
||||
const page = await p.getArtistAllSongs("m1", 0, 50);
|
||||
|
||||
expect(page.songs.map((s) => s.id)).toEqual(["s1"]);
|
||||
expect(page.total).toBe(250);
|
||||
expect(page.hasMore).toBe(true);
|
||||
});
|
||||
|
||||
it("retries a failed album search once before giving up", async () => {
|
||||
let albumSearchCalls = 0;
|
||||
mockGet.mockImplementation(async (url: string, cfg: any) => {
|
||||
if (url === "/cgi-bin/musicu.fcg") {
|
||||
const data = JSON.parse(cfg.params.data);
|
||||
if (data.req_0) {
|
||||
return {
|
||||
data: {
|
||||
req_0: {
|
||||
data: { singer_info: { mid: "m1", name: "Adele" }, songlist: [songRaw("s1", "1")] },
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
albumSearchCalls++;
|
||||
if (albumSearchCalls === 1) throw new Error("blip");
|
||||
const list =
|
||||
data.req_album.param.page_num === 1
|
||||
? [{ albumMID: "al1", albumName: "A", singerMID: "m1" }]
|
||||
: [];
|
||||
return { data: { req_album: { data: { body: { album: { list } } } } } };
|
||||
}
|
||||
if (url === "/getAlbumInfo") {
|
||||
return { data: { response: { data: { list: [songRaw("s9", "9")] } } } };
|
||||
}
|
||||
return { data: {} };
|
||||
});
|
||||
const p = new QQMusicProvider("http://x");
|
||||
|
||||
const page = await p.getArtistAllSongs("m1", 0, 50);
|
||||
|
||||
const page1Calls = mockGet.mock.calls.filter((c: any[]) => {
|
||||
if (c[0] !== "/cgi-bin/musicu.fcg") return false;
|
||||
return JSON.parse(c[1].params.data).req_album?.param?.page_num === 1;
|
||||
}).length;
|
||||
expect(page1Calls).toBe(2);
|
||||
expect(page.songs.map((s) => s.id)).toEqual(["s1", "s9"]);
|
||||
});
|
||||
|
||||
it("does not cache a catalogue degraded by a failed album search", async () => {
|
||||
let albumSearchFails = true;
|
||||
mockGet.mockImplementation(async (url: string, cfg: any) => {
|
||||
if (url === "/cgi-bin/musicu.fcg") {
|
||||
const data = JSON.parse(cfg.params.data);
|
||||
if (data.req_0) {
|
||||
return {
|
||||
data: {
|
||||
req_0: {
|
||||
data: {
|
||||
singer_info: { mid: "m1", name: "Adele" },
|
||||
songlist: [songRaw("s1", "1")],
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
if (albumSearchFails) throw new Error("upstream hiccup");
|
||||
return {
|
||||
data: {
|
||||
req_album: {
|
||||
data: { body: { album: { list: [{ albumMID: "al1", albumName: "A", singerMID: "m1" }] } } },
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
if (url === "/getAlbumInfo") {
|
||||
return { data: { response: { data: { list: [songRaw("s9", "9")] } } } };
|
||||
}
|
||||
return { data: {} };
|
||||
});
|
||||
const p = new QQMusicProvider("http://x");
|
||||
|
||||
// The album search fails twice (call + retry) → hot list only, and the
|
||||
// degraded result must not be cached.
|
||||
const degraded = await p.getArtistAllSongs("m1", 0, 50);
|
||||
expect(degraded.songs.map((s) => s.id)).toEqual(["s1"]);
|
||||
expect(degraded.total).toBe(1);
|
||||
|
||||
albumSearchFails = false;
|
||||
const full = await p.getArtistAllSongs("m1", 0, 50);
|
||||
expect(full.songs.map((s) => s.id)).toEqual(["s1", "s9"]);
|
||||
expect(full.total).toBe(2);
|
||||
});
|
||||
});
|
||||
+458
-51
@@ -1,4 +1,6 @@
|
||||
import { normalizeCookie } from "./cookie-normalize.js";
|
||||
import axios, { type AxiosInstance } from "axios";
|
||||
import { playbackRequestFailure, SongUrlUnavailable } from "./provider.js";
|
||||
import type {
|
||||
MusicProvider,
|
||||
Song,
|
||||
@@ -10,8 +12,12 @@ import type {
|
||||
QrCodeResult,
|
||||
AuthStatus,
|
||||
Album,
|
||||
Artist,
|
||||
ArtistDetail,
|
||||
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:
|
||||
@@ -40,6 +46,92 @@ const qqFavApi = axios.create({
|
||||
headers: { referer: "https://y.qq.com/" },
|
||||
});
|
||||
|
||||
/** Formats supported by @sansenjian/qq-music-api 2.4's /getMusicPlay route. */
|
||||
function qqPlaybackQuality(quality: string): string {
|
||||
switch (quality) {
|
||||
case "exhigh": return "320";
|
||||
case "lossless":
|
||||
case "hires":
|
||||
case "jymaster": return "flac";
|
||||
case "320":
|
||||
case "flac":
|
||||
case "ape":
|
||||
case "m4a": return quality;
|
||||
default: return "128";
|
||||
}
|
||||
}
|
||||
|
||||
function isQqNumericId(value: string): boolean {
|
||||
return /^\d+$/.test(value);
|
||||
}
|
||||
|
||||
interface QqPlaybackReply {
|
||||
code?: unknown;
|
||||
data?: {
|
||||
code?: unknown;
|
||||
req_0?: { code?: unknown; data?: { midurlinfo?: unknown } };
|
||||
playUrl?: Record<string, { url?: unknown }>;
|
||||
};
|
||||
}
|
||||
|
||||
function readQqCode(raw: unknown): number | undefined {
|
||||
const code = typeof raw === "string" && /^-?\d+$/.test(raw) ? Number(raw) : raw;
|
||||
return typeof code === "number" && Number.isSafeInteger(code) ? code : undefined;
|
||||
}
|
||||
|
||||
function qqPlaybackErrorCode(reply?: QqPlaybackReply): number | undefined {
|
||||
const wrapper = readQqCode(reply?.code);
|
||||
if (wrapper !== undefined && wrapper !== 0 && wrapper !== 200) return wrapper;
|
||||
return [readQqCode(reply?.data?.code), readQqCode(reply?.data?.req_0?.code)]
|
||||
.find(code => code !== undefined && code !== 0);
|
||||
}
|
||||
|
||||
function confirmedQqMisses(reply: QqPlaybackReply): Set<string> {
|
||||
const request = reply.data?.req_0;
|
||||
const rows = request?.data?.midurlinfo;
|
||||
if (readQqCode(request?.code) !== 0 || !Array.isArray(rows)) return new Set();
|
||||
return new Set(rows.flatMap(row => typeof row?.songmid === "string" && row.purl === "" && !row.vkey ? [row.songmid] : []));
|
||||
}
|
||||
|
||||
/** True when a search_type=2 album search entry really belongs to this singer.
|
||||
* QQ fills singerMID for most albums; older entries only carry singer_list. */
|
||||
function isArtistAlbum(a: any, artistId: string): boolean {
|
||||
const mid = a?.singerMID ?? a?.singer_mid;
|
||||
if (mid) return String(mid) === artistId;
|
||||
const singers = a?.singer_list ?? a?.singer ?? [];
|
||||
return (
|
||||
Array.isArray(singers) &&
|
||||
singers.some((s: any) => String(s?.mid ?? s?.singerMID ?? "") === artistId)
|
||||
);
|
||||
}
|
||||
|
||||
/** Assembling a QQ singer's full catalogue costs one album-song request per
|
||||
* album, so the merged list is memoised per singer for a while. */
|
||||
const ARTIST_CATALOG_TTL_MS = 10 * 60 * 1000;
|
||||
const ARTIST_CATALOG_MAX_ENTRIES = 20;
|
||||
/** Bound pathological search responses even when every album is empty or all
|
||||
* tracks are duplicates. Hitting this guard is an incomplete, uncached scan. */
|
||||
const ARTIST_ALBUM_MAX_PAGES = 100;
|
||||
const ARTIST_ALBUM_CONCURRENCY = 5;
|
||||
const ARTIST_CATALOG_MAX_SONGS = 500;
|
||||
|
||||
interface ArtistCatalog {
|
||||
songs: Song[];
|
||||
total: number;
|
||||
incomplete: boolean;
|
||||
}
|
||||
|
||||
/** A malformed row must not disappear in the mapper and make an incomplete
|
||||
* artist catalogue look like a successful, cacheable empty album. */
|
||||
function isQqSongRow(raw: unknown): boolean {
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return false;
|
||||
const song = raw as Record<string, unknown>;
|
||||
const id = song.mid ?? song.songmid ?? song.songMID ?? song.id ?? song.songid ?? song.songId;
|
||||
return typeof id === "string"
|
||||
? id.trim().length > 0
|
||||
: typeof id === "number" && Number.isSafeInteger(id) && id > 0;
|
||||
}
|
||||
|
||||
export function mapQqSongs(raw: any[] | null | undefined): Song[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
return raw.map((s) => {
|
||||
@@ -91,6 +183,33 @@ export function mapQqAlbums(raw: any[] | null | undefined): Album[] {
|
||||
});
|
||||
}
|
||||
|
||||
/** QQ hands out http:// image URLs; the WebUI is often served over https. */
|
||||
function httpsImage(url: unknown): string {
|
||||
return typeof url === "string" ? url.replace(/^http:\/\//i, "https://") : "";
|
||||
}
|
||||
|
||||
export function mapQqArtists(raw: any[] | null | undefined): Artist[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
return raw
|
||||
.map((a) => {
|
||||
const id = String(a.singerMID ?? a.singer_mid ?? a.mid ?? a.singerID ?? a.singerId ?? "");
|
||||
const mid = a.singerMID ?? a.singer_mid ?? a.mid;
|
||||
return {
|
||||
id,
|
||||
name: a.singerName ?? a.name ?? "",
|
||||
// Search returns a 150px portrait; the MID builds the 500px one the
|
||||
// artist page wants, so prefer it and only fall back to the given URL.
|
||||
avatarUrl: mid
|
||||
? `https://y.gtimg.cn/music/photo_new/T001R500x500M000${mid}.jpg`
|
||||
: httpsImage(a.singerPic ?? a.pic),
|
||||
songCount: a.songNum ?? undefined,
|
||||
albumCount: a.albumNum ?? undefined,
|
||||
platform: "qq" as const,
|
||||
};
|
||||
})
|
||||
.filter((a) => a.id && a.name);
|
||||
}
|
||||
|
||||
function computeGtk(pSkey: string): number {
|
||||
let hash = 5381;
|
||||
for (let i = 0; i < pSkey.length; i++) {
|
||||
@@ -101,26 +220,47 @@ function computeGtk(pSkey: string): number {
|
||||
|
||||
export class QQMusicProvider implements MusicProvider {
|
||||
readonly platform = "qq" as const;
|
||||
private api: AxiosInstance;
|
||||
private cookie = "";
|
||||
private readonly sidecar: AxiosInstance;
|
||||
private legacyCookie = "";
|
||||
private quality = "exhigh";
|
||||
private radarPage = 1;
|
||||
|
||||
constructor(baseUrl: string) {
|
||||
this.api = axios.create({
|
||||
constructor(
|
||||
baseUrl: string,
|
||||
readonly managedSession?: QQManagedSession,
|
||||
private readonly assertSidecarPort?: () => void,
|
||||
) {
|
||||
this.sidecar = axios.create({
|
||||
baseURL: baseUrl,
|
||||
timeout: 10000,
|
||||
});
|
||||
}
|
||||
|
||||
setQuality(quality: string): void {
|
||||
this.quality = quality;
|
||||
private get api(): AxiosInstance {
|
||||
this.assertSidecarPort?.();
|
||||
return this.sidecar;
|
||||
}
|
||||
|
||||
private get cookie(): string {
|
||||
return this.managedSession?.getCookie() ?? this.legacyCookie;
|
||||
}
|
||||
|
||||
setQuality(quality: string | number): void {
|
||||
if (quality === 128 || quality === 320) this.quality = String(quality);
|
||||
else if (typeof quality === "string" && quality.trim()) this.quality = quality.trim();
|
||||
}
|
||||
|
||||
getQuality(): string {
|
||||
return this.quality;
|
||||
}
|
||||
|
||||
getFallbackQualities(): string[] {
|
||||
const primary = qqPlaybackQuality(this.quality);
|
||||
if (primary === "flac" || primary === "ape") return ["320", "128"];
|
||||
if (primary === "320") return ["128"];
|
||||
return [];
|
||||
}
|
||||
|
||||
private get cookieParams(): Record<string, string> {
|
||||
return this.cookie ? { cookie: this.cookie } : {};
|
||||
}
|
||||
@@ -195,6 +335,13 @@ export class QQMusicProvider implements MusicProvider {
|
||||
method: "DoSearchForQQMusicDesktop",
|
||||
param: { query, num_per_page: numPerPage, page_num: pageNum, search_type: 3 },
|
||||
},
|
||||
// search_type 1 = singers. Folded into the same batch so artist search
|
||||
// costs no extra round-trip.
|
||||
req_artist: {
|
||||
module: "music.search.SearchCgiService",
|
||||
method: "DoSearchForQQMusicDesktop",
|
||||
param: { query, num_per_page: numPerPage, page_num: pageNum, search_type: 1 },
|
||||
},
|
||||
});
|
||||
const res = await qqMusicuApi.get("/cgi-bin/musicu.fcg", {
|
||||
params: { format: "json", data: reqData },
|
||||
@@ -202,7 +349,11 @@ export class QQMusicProvider implements MusicProvider {
|
||||
|
||||
const songList: any[] =
|
||||
res.data?.req_0?.data?.body?.song?.list ?? [];
|
||||
if (songList.length === 0) return null;
|
||||
const artistList: any[] =
|
||||
res.data?.req_artist?.data?.body?.singer?.list ?? [];
|
||||
// Only fall back to the older client_search_cp path when the batch came
|
||||
// back completely empty — an artist-only hit is a real result.
|
||||
if (songList.length === 0 && artistList.length === 0) return null;
|
||||
|
||||
const songs = mapQqSongs(songList);
|
||||
|
||||
@@ -218,7 +369,7 @@ export class QQMusicProvider implements MusicProvider {
|
||||
platform: "qq" as const,
|
||||
}));
|
||||
|
||||
return { songs, playlists, albums };
|
||||
return { songs, playlists, albums, artists: mapQqArtists(artistList) };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
@@ -272,25 +423,37 @@ export class QQMusicProvider implements MusicProvider {
|
||||
}
|
||||
|
||||
async getSongUrl(songId: string, quality?: string): Promise<SongUrlResult | null> {
|
||||
const format = qqPlaybackQuality(quality ?? this.quality);
|
||||
try {
|
||||
const res = await this.api.get("/getMusicPlay", {
|
||||
params: { songmid: songId, quality: quality ?? this.quality, ...this.cookieParams },
|
||||
});
|
||||
const playUrl = res.data?.data?.playUrl?.[songId];
|
||||
if (playUrl?.url) return { url: playUrl.url, trialDuration: parseQqTrial(playUrl) };
|
||||
} catch {
|
||||
// try with songid
|
||||
try {
|
||||
const res = await this.api.get("/getMusicPlay", {
|
||||
params: { songid: songId, quality: quality ?? this.quality, ...this.cookieParams },
|
||||
});
|
||||
const playUrl = res.data?.data?.playUrl?.[songId];
|
||||
if (playUrl?.url) return { url: playUrl.url, trialDuration: parseQqTrial(playUrl) };
|
||||
} catch {
|
||||
// ignore
|
||||
const api = this.api;
|
||||
// The play endpoint only accepts MIDs. Old queues and explicit ID
|
||||
// requests can carry a numeric ID, which the metadata endpoint resolves.
|
||||
const songmid = isQqNumericId(songId) ? (await this.getSongDetail(songId))?.id : songId;
|
||||
if (!songmid || isQqNumericId(songmid)) {
|
||||
throw new SongUrlUnavailable({ platform: this.platform, songId, code: "unknown", message: "QQ 音乐未返回该曲目的 MID" });
|
||||
}
|
||||
const response = await api.get<QqPlaybackReply>("/getMusicPlay", {
|
||||
params: { songmid, quality: format, resType: "full", ...this.cookieParams },
|
||||
});
|
||||
const code = qqPlaybackErrorCode(response.data);
|
||||
if (code !== undefined) {
|
||||
throw new SongUrlUnavailable({
|
||||
platform: this.platform, songId, code: "upstream_request_failed", message: `QQ 音乐播放请求返回错误(${code})`,
|
||||
upstream: { code },
|
||||
});
|
||||
}
|
||||
const playUrl = response.data?.data?.playUrl?.[songmid];
|
||||
if (typeof playUrl?.url === "string" && playUrl.url) {
|
||||
return { url: playUrl.url, trialDuration: parseQqTrial(playUrl) };
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof SongUrlUnavailable) throw error;
|
||||
throw playbackRequestFailure(this.platform, songId, error);
|
||||
}
|
||||
return null;
|
||||
throw new SongUrlUnavailable({
|
||||
platform: this.platform, songId, code: "unknown",
|
||||
message: `QQ 音乐未返回播放地址(${format})`,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -304,37 +467,49 @@ export class QQMusicProvider implements MusicProvider {
|
||||
* the URL well under typical 8KB query-string limits and to keep per-
|
||||
* request latency bounded (~2-3s per 100 mids).
|
||||
*
|
||||
* Returns:
|
||||
* - non-null Set: authoritative result. Empty Set means all songs are
|
||||
* unplayable; non-empty means filter to those mids.
|
||||
* - null: every chunk failed. Caller should fall back to sequential
|
||||
* retry rather than treating as "all unplayable".
|
||||
* Check lower configured formats for MIDs missing from the first result.
|
||||
* Return null on an incomplete response so the caller can resolve tracks
|
||||
* normally instead of discarding unverified entries.
|
||||
*/
|
||||
async getPlayableSongIds(songIds: string[]): Promise<Set<string> | null> {
|
||||
if (songIds.length === 0) return new Set();
|
||||
if (songIds.some(isQqNumericId)) return null;
|
||||
|
||||
const CHUNK = 100; // ~14 chars/mid * 100 + commas ≈ 1.5KB
|
||||
const playable = new Set<string>();
|
||||
let allChunksFailed = true;
|
||||
const formats = [qqPlaybackQuality(this.quality), ...this.getFallbackQualities()];
|
||||
for (let i = 0; i < songIds.length; i += CHUNK) {
|
||||
const slice = songIds.slice(i, i + CHUNK);
|
||||
try {
|
||||
const res = await this.api.get("/getMusicPlay", {
|
||||
params: { songmid: slice.join(","), quality: this.quality, ...this.cookieParams },
|
||||
});
|
||||
const playUrlMap: Record<string, { url?: string }> | undefined =
|
||||
res.data?.data?.playUrl;
|
||||
if (!playUrlMap) continue; // chunk-level failure, try next
|
||||
allChunksFailed = false;
|
||||
for (const [mid, info] of Object.entries(playUrlMap)) {
|
||||
if (info?.url) playable.add(mid);
|
||||
let remaining = songIds.slice(i, i + CHUNK);
|
||||
const unconfirmed = new Set<string>();
|
||||
for (const quality of formats) {
|
||||
try {
|
||||
const res = await this.api.get<QqPlaybackReply>("/getMusicPlay", {
|
||||
params: { songmid: remaining.join(","), quality, resType: "full", ...this.cookieParams },
|
||||
});
|
||||
const playUrlMap = res.data?.data?.playUrl;
|
||||
if (qqPlaybackErrorCode(res.data) !== undefined || !playUrlMap ||
|
||||
remaining.some(mid => !Object.hasOwn(playUrlMap, mid) || typeof playUrlMap[mid]?.url !== "string")) return null;
|
||||
// The wrapper synthesizes empty URLs even if Tencent omitted a MID
|
||||
// or returned a transient error. Require an upstream row before
|
||||
// interpreting a blank URL as negative evidence for that quality.
|
||||
const confirmed = confirmedQqMisses(res.data);
|
||||
remaining = remaining.filter(mid => {
|
||||
if (!playUrlMap[mid].url) {
|
||||
if (!confirmed.has(mid)) unconfirmed.add(mid);
|
||||
return true;
|
||||
}
|
||||
unconfirmed.delete(mid);
|
||||
playable.add(mid);
|
||||
return false;
|
||||
});
|
||||
if (remaining.length === 0) break;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
} catch {
|
||||
// chunk-level failure — keep going so a transient error on one
|
||||
// chunk doesn't poison the whole batch.
|
||||
}
|
||||
if (unconfirmed.size > 0) return null;
|
||||
}
|
||||
return allChunksFailed ? null : playable;
|
||||
return playable;
|
||||
}
|
||||
|
||||
async getSongDetail(songId: string): Promise<Song | null> {
|
||||
@@ -346,9 +521,9 @@ export class QQMusicProvider implements MusicProvider {
|
||||
// stub is sufficient to let /play-by-id and /add-by-id flows succeed.
|
||||
try {
|
||||
const res = await this.api.get("/getSongInfo", {
|
||||
params: { songmid: songId, ...this.cookieParams },
|
||||
params: { ...(isQqNumericId(songId) ? { songid: songId } : { songmid: songId }), ...this.cookieParams },
|
||||
});
|
||||
const s = res.data?.response?.data;
|
||||
const s = res.data?.response?.songinfo?.data ?? res.data?.response?.data;
|
||||
if (s && s.track_info) {
|
||||
const t = s.track_info;
|
||||
return {
|
||||
@@ -397,11 +572,14 @@ export class QQMusicProvider implements MusicProvider {
|
||||
* caller can fall back to the minimal stub. */
|
||||
private async fetchSongDetailViaMusicu(songId: string): Promise<Song | null> {
|
||||
try {
|
||||
const numeric = isQqNumericId(songId);
|
||||
const song_id = Number(songId);
|
||||
if (numeric && (!Number.isSafeInteger(song_id) || song_id < 1)) return null;
|
||||
const reqData = JSON.stringify({
|
||||
req_0: {
|
||||
module: "music.pf_song_detail_svr",
|
||||
method: "get_song_detail_yqq",
|
||||
param: { song_mid: songId, song_type: 0 },
|
||||
param: { ...(numeric ? { song_id } : { song_mid: songId }), song_type: 0 },
|
||||
},
|
||||
});
|
||||
const res = await qqMusicuApi.get("/cgi-bin/musicu.fcg", {
|
||||
@@ -467,7 +645,214 @@ export class QQMusicProvider implements MusicProvider {
|
||||
const res = await this.api.get("/getAlbumInfo", {
|
||||
params: { albummid: albumId, ...this.cookieParams },
|
||||
});
|
||||
return mapQqSongs(res.data?.response?.data?.list ?? []);
|
||||
const response = res.data?.response;
|
||||
const list = response?.data?.list;
|
||||
if (
|
||||
(res.data?.code != null && Number(res.data.code) !== 0) ||
|
||||
(response?.code != null && Number(response.code) !== 0) ||
|
||||
!Array.isArray(list) || !list.every(isQqSongRow)
|
||||
) {
|
||||
throw new Error("QQ album-song lookup failed");
|
||||
}
|
||||
return mapQqSongs(list);
|
||||
}
|
||||
|
||||
/** music.web_singer_info_svr / get_singer_detail_info — singer info plus up
|
||||
* to `num` of their hottest songs (sort 5 = popularity). Returns null on any
|
||||
* failure so callers can degrade instead of throwing. */
|
||||
private async fetchSingerDetail(singerMid: string, num: number): Promise<any | null> {
|
||||
try {
|
||||
const reqData = JSON.stringify({
|
||||
req_0: {
|
||||
module: "music.web_singer_info_svr",
|
||||
method: "get_singer_detail_info",
|
||||
param: {
|
||||
singermid: singerMid,
|
||||
sort: 5,
|
||||
num: Math.max(1, Math.min(num, 50)),
|
||||
begin: 0,
|
||||
},
|
||||
},
|
||||
});
|
||||
const res = await qqMusicuApi.get("/cgi-bin/musicu.fcg", {
|
||||
params: { format: "json", data: reqData },
|
||||
});
|
||||
const response = res.data?.req_0;
|
||||
const data = response?.data;
|
||||
if (
|
||||
(res.data?.code != null && Number(res.data.code) !== 0) ||
|
||||
(response?.code != null && Number(response.code) !== 0) ||
|
||||
typeof data?.singer_info?.name !== "string" ||
|
||||
!data.singer_info.name ||
|
||||
!Array.isArray(data.songlist) || !data.songlist.every(isQqSongRow)
|
||||
) return null;
|
||||
return data;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async getArtistDetail(artistId: string): Promise<ArtistDetail | null> {
|
||||
const data = await this.fetchSingerDetail(artistId, 1);
|
||||
if (!data) return null;
|
||||
const info = data.singer_info ?? {};
|
||||
const mid = String(info.mid ?? artistId);
|
||||
if (!mid) return null;
|
||||
return {
|
||||
id: mid,
|
||||
name: info.name ?? "",
|
||||
avatarUrl: `https://y.gtimg.cn/music/photo_new/T001R500x500M000${mid}.jpg`,
|
||||
aliases: info.other_name ? [String(info.other_name)] : [],
|
||||
songCount: data.total_song ?? undefined,
|
||||
albumCount: data.total_album ?? undefined,
|
||||
platform: "qq" as const,
|
||||
description: data.singer_brief ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
async getArtistSongs(artistId: string, limit = 50): Promise<Song[]> {
|
||||
const data = await this.fetchSingerDetail(artistId, limit);
|
||||
return mapQqSongs(data?.songlist ?? []);
|
||||
}
|
||||
|
||||
/**
|
||||
* One page of the singer's full catalogue. get_singer_detail_info ignores its
|
||||
* `begin` parameter (begin=0/50/100 all return the same top 50 — verified
|
||||
* 2026-10) and QQ has no working singer-song-list endpoint, so the catalogue
|
||||
* is assembled from every album the singer owns: the hot 50 first (they rank
|
||||
* best) followed by the album tracks, de-duplicated by songmid.
|
||||
*/
|
||||
async getArtistAllSongs(artistId: string, offset = 0, limit = 50): Promise<ArtistSongPage> {
|
||||
const catalogue = await this.buildArtistCatalog(artistId);
|
||||
const safeOffset = Number.isFinite(offset) ? Math.max(0, Math.trunc(offset)) : 0;
|
||||
const safeLimit = Number.isFinite(limit) ? Math.max(1, Math.min(Math.trunc(limit) || 50, 100)) : 50;
|
||||
const songs = catalogue.songs.slice(safeOffset, safeOffset + safeLimit);
|
||||
return {
|
||||
songs,
|
||||
total: catalogue.total,
|
||||
hasMore: safeOffset + songs.length < catalogue.total || catalogue.incomplete,
|
||||
};
|
||||
}
|
||||
|
||||
/** Memoised full catalogues, keyed by singer MID (see ARTIST_CATALOG_TTL_MS). */
|
||||
private artistCatalog = new Map<string, { at: number; catalogue: ArtistCatalog }>();
|
||||
|
||||
private async buildArtistCatalog(artistId: string): Promise<ArtistCatalog> {
|
||||
const cached = this.artistCatalog.get(artistId);
|
||||
if (cached && Date.now() - cached.at < ARTIST_CATALOG_TTL_MS) return cached.catalogue;
|
||||
|
||||
const merged: Song[] = [];
|
||||
const seen = new Set<string>();
|
||||
const push = (song: Song) => {
|
||||
if (!song.id || seen.has(song.id)) return;
|
||||
seen.add(song.id);
|
||||
if (merged.length < ARTIST_CATALOG_MAX_SONGS) merged.push(song);
|
||||
};
|
||||
|
||||
const hot = await this.fetchSingerDetail(artistId, 50);
|
||||
for (const song of mapQqSongs(hot?.songlist)) push(song);
|
||||
const detail = await this.fetchSingerDetail(artistId, 1);
|
||||
const name = detail?.singer_info?.name;
|
||||
let failed = !hot || !detail;
|
||||
let complete = false;
|
||||
const albumIds = new Set<string>();
|
||||
const searchAlbumIds = new Set<string>();
|
||||
if (name) {
|
||||
for (let page = 1; page <= ARTIST_ALBUM_MAX_PAGES && merged.length < ARTIST_CATALOG_MAX_SONGS; page++) {
|
||||
const list = (await this.searchArtistAlbums(name, page, 50)) ?? (await this.searchArtistAlbums(name, page, 50));
|
||||
if (list === null) { failed = true; break; }
|
||||
if (list.length === 0) { complete = true; break; }
|
||||
const batchIds: string[] = [];
|
||||
let freshSearchEntries = 0;
|
||||
for (const entry of list) {
|
||||
const mid = String(entry?.albumMID ?? entry?.album_mid ?? "");
|
||||
if (!mid) { failed = true; continue; }
|
||||
if (!searchAlbumIds.has(mid)) { searchAlbumIds.add(mid); freshSearchEntries++; }
|
||||
if (isArtistAlbum(entry, artistId) && !albumIds.has(mid)) {
|
||||
albumIds.add(mid);
|
||||
batchIds.push(mid);
|
||||
}
|
||||
}
|
||||
// Repeated pages cannot prove exhaustion, but must not loop forever.
|
||||
if (freshSearchEntries === 0) { failed = true; break; }
|
||||
let fetchedAlbums = 0;
|
||||
for (let i = 0; i < batchIds.length && merged.length < ARTIST_CATALOG_MAX_SONGS; i += ARTIST_ALBUM_CONCURRENCY) {
|
||||
const batch = batchIds.slice(i, i + ARTIST_ALBUM_CONCURRENCY);
|
||||
const lists = await Promise.all(batch.map((mid) =>
|
||||
this.getAlbumSongs(mid).catch(() => { failed = true; return [] as Song[]; })
|
||||
));
|
||||
fetchedAlbums += batch.length;
|
||||
for (const songs of lists) for (const song of songs) push(song);
|
||||
}
|
||||
if (list.length < 50 && fetchedAlbums === batchIds.length && seen.size <= ARTIST_CATALOG_MAX_SONGS) { complete = true; break; }
|
||||
}
|
||||
}
|
||||
const incomplete = failed || !complete;
|
||||
const reported = Math.max(0, ...[hot?.total_song, detail?.total_song].map((n) => Number.isFinite(Number(n)) ? Math.trunc(Number(n)) : 0));
|
||||
const catalogue: ArtistCatalog = {
|
||||
songs: merged,
|
||||
total: incomplete ? Math.max(seen.size, reported, merged.length === ARTIST_CATALOG_MAX_SONGS ? ARTIST_CATALOG_MAX_SONGS + 1 : 0) : merged.length,
|
||||
incomplete,
|
||||
};
|
||||
// Cache complete catalogues and intentional 500-song truncation only.
|
||||
// Failure, repeated pages and an exhausted scan budget must remain retryable.
|
||||
if (!failed && (complete || merged.length === ARTIST_CATALOG_MAX_SONGS)) {
|
||||
if (this.artistCatalog.size >= ARTIST_CATALOG_MAX_ENTRIES) {
|
||||
const oldest = this.artistCatalog.keys().next().value;
|
||||
if (oldest !== undefined) this.artistCatalog.delete(oldest);
|
||||
}
|
||||
this.artistCatalog.set(artistId, { at: Date.now(), catalogue });
|
||||
}
|
||||
return catalogue;
|
||||
}
|
||||
|
||||
/** search_type=2 album search for a singer name — raw entries, null on failure. */
|
||||
private async searchArtistAlbums(
|
||||
name: string,
|
||||
pageNum: number,
|
||||
numPerPage: number
|
||||
): Promise<any[] | null> {
|
||||
try {
|
||||
const reqData = JSON.stringify({
|
||||
req_album: {
|
||||
module: "music.search.SearchCgiService",
|
||||
method: "DoSearchForQQMusicDesktop",
|
||||
param: {
|
||||
query: name,
|
||||
num_per_page: Math.max(10, Math.min(numPerPage, 50)),
|
||||
page_num: pageNum,
|
||||
search_type: 2,
|
||||
},
|
||||
},
|
||||
});
|
||||
const res = await qqMusicuApi.get("/cgi-bin/musicu.fcg", {
|
||||
params: { format: "json", data: reqData },
|
||||
});
|
||||
const response = res.data?.req_album;
|
||||
const list = response?.data?.body?.album?.list;
|
||||
if (
|
||||
(res.data?.code != null && Number(res.data.code) !== 0) ||
|
||||
(response?.code != null && Number(response.code) !== 0) ||
|
||||
!Array.isArray(list)
|
||||
) return null;
|
||||
return list;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async getArtistAlbums(artistId: string, limit = 20): Promise<Album[]> {
|
||||
// QQ has no working "albums for this singer MID" endpoint: the homepage tab
|
||||
// API returns a null AlbumList and music.web_singer_info_svr/get_singer_album
|
||||
// returns an empty list even with a logged-in cookie (verified 2026-10).
|
||||
// The album shelf is therefore built from the album search for the singer's
|
||||
// name, filtered down to entries whose singerMID actually matches.
|
||||
const detail = await this.fetchSingerDetail(artistId, 1);
|
||||
const name = detail?.singer_info?.name;
|
||||
if (!name) return [];
|
||||
const list = (await this.searchArtistAlbums(name, 1, limit)) ?? [];
|
||||
const mine = list.filter((a: any) => isArtistAlbum(a, artistId));
|
||||
return mapQqAlbums(mine).slice(0, limit);
|
||||
}
|
||||
|
||||
async getLyrics(songId: string): Promise<LyricLine[]> {
|
||||
@@ -481,6 +866,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
|
||||
@@ -500,6 +886,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";
|
||||
|
||||
@@ -521,7 +913,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";
|
||||
@@ -531,12 +923,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 guarded API server
|
||||
* — only the cookie differs, so the shared login keeps its own instance.
|
||||
*/
|
||||
withCookie(cookie: string): QQMusicProvider {
|
||||
const view = new QQMusicProvider(this.sidecar.defaults.baseURL ?? "", undefined, this.assertSidecarPort);
|
||||
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);
|
||||
}),
|
||||
|
||||
@@ -0,0 +1,362 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
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: FakeSdkClient | null; voiceFramesSent: number };
|
||||
|
||||
describe("TS3Client voice send failure lifecycle", () => {
|
||||
let client: TS3Client;
|
||||
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();
|
||||
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 = createClient();
|
||||
await client.connect();
|
||||
sdk = (client as unknown as Harness).client!;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
client.disconnect();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
vi.restoreAllMocks();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it.each([false, true])("reports a sanitized first failure after earlier accepted send=%s without throwing", (acceptedFirst) => {
|
||||
const send = vi.spyOn(sdk, "sendVoice").mockImplementation(() => {});
|
||||
if (acceptedFirst) client.sendVoiceData(Buffer.from([1]));
|
||||
const failures: Failure[] = [];
|
||||
client.on("voiceSendFailure", event => failures.push(event));
|
||||
send.mockImplementation(() => { throw Object.assign(new Error("https://user:password@host/?token=credential-secret"), { code: "ERR_SOCKET_DGRAM_NOT_RUNNING", spawnargs: ["credential-secret"] }); });
|
||||
|
||||
let result: unknown;
|
||||
expect(() => { result = client.sendVoiceData(Buffer.from([2])); }).not.toThrow();
|
||||
expect(result).toBe("retrying");
|
||||
expect(failures).toEqual([{ code: "ERR_SOCKET_DGRAM_NOT_RUNNING", consecutiveFailures: 1, durationMs: 0 }]);
|
||||
expect((client as unknown as Harness).voiceFramesSent).toBe(acceptedFirst ? 1 : 0);
|
||||
expect(records.filter(record => record.level === "warn")).toHaveLength(1);
|
||||
expect(JSON.stringify(records)).not.toContain("password");
|
||||
expect(JSON.stringify(records)).not.toContain("credential-secret");
|
||||
});
|
||||
|
||||
it.each([{ code: "credential-secret", message: "credential-secret" }, "credential-secret"])("omits untrusted error codes and primitive error text: %s", error => {
|
||||
const failures: Failure[] = [];
|
||||
client.on("voiceSendFailure", event => failures.push(event));
|
||||
vi.spyOn(sdk, "sendVoice").mockImplementation(() => { throw error; });
|
||||
client.sendVoiceData(Buffer.from([1]));
|
||||
expect(failures).toEqual([{ consecutiveFailures: 1, durationMs: 0 }]);
|
||||
expect(JSON.stringify(records)).not.toContain("credential-secret");
|
||||
});
|
||||
|
||||
it("emits one recovery and cancels terminal failure when the next send succeeds", async () => {
|
||||
const recovered: Failure[] = [];
|
||||
const terminal: Failure[] = [];
|
||||
client.on("voiceSendRecovered", event => recovered.push(event));
|
||||
client.on("voiceSendFailed", event => terminal.push(event));
|
||||
const send = vi.spyOn(sdk, "sendVoice").mockImplementation(() => { throw { code: "ENOBUFS" }; });
|
||||
client.sendVoiceData(Buffer.from([1]));
|
||||
await vi.advanceTimersByTimeAsync(20);
|
||||
send.mockImplementation(() => {});
|
||||
expect(client.sendVoiceData(Buffer.from([2]))).toBe("accepted");
|
||||
client.sendVoiceData(Buffer.from([3]));
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(recovered).toEqual([{ code: "ENOBUFS", consecutiveFailures: 1, durationMs: 20 }]);
|
||||
expect(terminal).toEqual([]);
|
||||
expect((client as unknown as Harness).voiceFramesSent).toBe(2);
|
||||
});
|
||||
|
||||
it("bounds persistent failure reporting to one first event and one terminal event per burst", async () => {
|
||||
const first: Failure[] = [];
|
||||
const terminal: Failure[] = [];
|
||||
client.on("voiceSendFailure", event => first.push(event));
|
||||
client.on("voiceSendFailed", event => terminal.push(event));
|
||||
vi.spyOn(sdk, "sendVoice").mockImplementation(() => { throw { code: "ERR_SOCKET_DGRAM_NOT_RUNNING" }; });
|
||||
for (let i = 0; i < 100; i++) {
|
||||
client.sendVoiceData(Buffer.from([1]));
|
||||
await vi.advanceTimersByTimeAsync(20);
|
||||
}
|
||||
expect(first).toHaveLength(1);
|
||||
expect(terminal).toEqual([{ code: "ERR_SOCKET_DGRAM_NOT_RUNNING", consecutiveFailures: 100, durationMs: 2000 }]);
|
||||
for (let i = 0; i < 100; i++) expect(client.sendVoiceData(Buffer.from([1]))).toBe("failed");
|
||||
await vi.advanceTimersByTimeAsync(10000);
|
||||
expect(terminal).toHaveLength(1);
|
||||
expect(records.filter(record => ["warn", "error"].includes(record.level)).length).toBeLessThanOrEqual(2);
|
||||
expect((client as unknown as Harness).voiceFramesSent).toBe(0);
|
||||
});
|
||||
|
||||
it("recovers after the terminal event and allows a fresh failure burst", async () => {
|
||||
const first: Failure[] = [], recovered: Failure[] = [], terminal: Failure[] = [];
|
||||
client.on("voiceSendFailure", event => first.push(event));
|
||||
client.on("voiceSendRecovered", event => recovered.push(event));
|
||||
client.on("voiceSendFailed", event => terminal.push(event));
|
||||
const send = vi.spyOn(sdk, "sendVoice").mockImplementation(() => { throw { code: "EPIPE" }; });
|
||||
client.sendVoiceData(Buffer.from([1]));
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
send.mockImplementation(() => {});
|
||||
expect(client.sendVoiceData(Buffer.from([1]))).toBe("accepted");
|
||||
send.mockImplementation(() => { throw { code: "EPIPE" }; });
|
||||
client.sendVoiceData(Buffer.from([1]));
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
expect(first).toHaveLength(2);
|
||||
expect(recovered).toHaveLength(1);
|
||||
expect(terminal).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("cancels failure timers on explicit disconnect", async () => {
|
||||
const terminal: Failure[] = [];
|
||||
client.on("voiceSendFailed", event => terminal.push(event));
|
||||
const send = vi.spyOn(sdk, "sendVoice").mockImplementation(() => {});
|
||||
client.sendVoiceData(Buffer.from([1]));
|
||||
send.mockImplementation(() => { throw { code: "EPIPE" }; });
|
||||
client.sendVoiceData(Buffer.from([1]));
|
||||
client.disconnect();
|
||||
expect(client.sendVoiceData(Buffer.from([1]))).toBe("unavailable");
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(terminal).toEqual([]);
|
||||
expect((client as unknown as Harness).voiceFramesSent).toBe(0);
|
||||
});
|
||||
|
||||
it("cancels failure timers on SDK connection loss", async () => {
|
||||
const terminal: Failure[] = [];
|
||||
client.on("voiceSendFailed", event => terminal.push(event));
|
||||
const send = vi.spyOn(sdk, "sendVoice").mockImplementation(() => {});
|
||||
client.sendVoiceData(Buffer.from([1]));
|
||||
send.mockImplementation(() => { throw { code: "EPIPE" }; });
|
||||
client.sendVoiceData(Buffer.from([1]));
|
||||
sdk.emitDisconnected(new Error("synthetic connection loss"));
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(terminal).toEqual([]);
|
||||
expect((client as unknown as Harness).voiceFramesSent).toBe(0);
|
||||
send.mockClear();
|
||||
client.sendVoiceData(Buffer.from([1]));
|
||||
expect(send).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not revive a connection whose handshake was cancelled", async () => {
|
||||
let finishHandshake!: () => void;
|
||||
onCreateSdk = (fake) => {
|
||||
vi.spyOn(fake, "connect").mockImplementationOnce(() => new Promise<void>(resolve => {
|
||||
finishHandshake = () => {
|
||||
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, "disconnect");
|
||||
const send = vi.spyOn(connectingSdk, "sendVoice");
|
||||
client.disconnect();
|
||||
finishHandshake();
|
||||
await pending;
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(client.getClientId()).toBe(0);
|
||||
expect(connected).not.toHaveBeenCalled();
|
||||
expect(close).toHaveBeenCalled();
|
||||
client.sendVoiceData(Buffer.from([1]));
|
||||
expect(send).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("ignores old SDK warnings and disconnect callbacks after replacement", async () => {
|
||||
const terminal: Failure[] = [];
|
||||
client.on("voiceSendFailed", event => terminal.push(event));
|
||||
vi.spyOn(sdk, "sendVoice").mockImplementation(() => { throw { code: "EPIPE" }; });
|
||||
client.sendVoiceData(Buffer.from([1]));
|
||||
await client.connect();
|
||||
// Old disconnect dispatch is queued; old socket callbacks may follow it.
|
||||
const before = records.length;
|
||||
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([]);
|
||||
expect(terminal).toEqual([]);
|
||||
});
|
||||
|
||||
it("does not let an older named-channel lookup move the replacement connection", async () => {
|
||||
client.disconnect();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
client = createClient({ defaultChannel: "Music" });
|
||||
let nextClientId = 101;
|
||||
let finishOlderLookup!: (rows: Record<string, string>[]) => void;
|
||||
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", pid: "0", channel_order: "0" }]);
|
||||
await first;
|
||||
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);
|
||||
});
|
||||
|
||||
it("keeps the replacement endpoint when an older DNS resolution finishes last", async () => {
|
||||
let finishOlderResolution!: (rows: ResolvedAddr[]) => void;
|
||||
const row = (addr: string): ResolvedAddr => ({ addr, source: "test", expiry: new Date(0) });
|
||||
vi.spyOn(Resolver.prototype, "resolve").mockImplementationOnce(() => new Promise(resolve => { finishOlderResolution = resolve; }))
|
||||
.mockResolvedValue([row("192.0.2.2:9987")]);
|
||||
let sequence = 0;
|
||||
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");
|
||||
await client.connect();
|
||||
expect(client.getResolvedVoiceEndpoint()).toEqual({ host: "192.0.2.2", port: 9987 });
|
||||
finishOlderResolution([row("192.0.2.1:9987")]);
|
||||
await first;
|
||||
expect(client.getClientId()).toBe(102);
|
||||
expect(client.getResolvedVoiceEndpoint()).toEqual({ host: "192.0.2.2", port: 9987 });
|
||||
});
|
||||
|
||||
it.each(["10", "Music"])("does not report an old %s channel move after connection replacement", async channel => {
|
||||
let finishMove!: () => void;
|
||||
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(moveSpy).toHaveBeenCalledTimes(1);
|
||||
await client.connect();
|
||||
finishMove();
|
||||
await joining;
|
||||
expect(records.filter(record => record.args[1] === "Joined channel")).toEqual([]);
|
||||
});
|
||||
|
||||
it("does not report a stale channel lookup failure against the new connection", async () => {
|
||||
let failLookup!: (error: Error) => void;
|
||||
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"));
|
||||
await joining;
|
||||
expect(records.filter(record => record.level === "error")).toEqual([]);
|
||||
expect(JSON.stringify(records)).not.toContain("credential-secret");
|
||||
});
|
||||
|
||||
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.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);
|
||||
expect(warnings[0].args[0]).toMatchObject({ code: "ECONNREFUSED", count: 1 });
|
||||
expect(warnings[1].args[0]).toMatchObject({ code: "ECONNREFUSED", count: 100 });
|
||||
expect(JSON.stringify(records)).not.toContain("credential-secret");
|
||||
expect(terminal).toEqual([]);
|
||||
});
|
||||
|
||||
it("discards unsafe async UDP codes and cancels their summary on disconnect", async () => {
|
||||
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);
|
||||
expect(JSON.stringify(records)).not.toContain("credential-secret");
|
||||
});
|
||||
});
|
||||
+300
-118
@@ -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 {
|
||||
@@ -80,32 +110,71 @@ export interface TS3VoiceActivity {
|
||||
clientUid?: string;
|
||||
}
|
||||
|
||||
/** Send acceptance only: an accepted UDP call does not confirm delivery. */
|
||||
export interface TS3VoiceSendFailure {
|
||||
code?: string;
|
||||
consecutiveFailures: number;
|
||||
durationMs: number;
|
||||
}
|
||||
|
||||
/** Sticky failure status lets playback stay paused when the terminal event
|
||||
* already fired during another track or an idle URL lookup. */
|
||||
export type TS3VoiceSendResult = "accepted" | "retrying" | "failed" | "unavailable";
|
||||
|
||||
const VOICE_SEND_FAILURE_TIMEOUT_MS = 2_000;
|
||||
const SAFE_SOCKET_ERROR_CODES = new Set([
|
||||
"ERR_SOCKET_DGRAM_NOT_RUNNING", "ERR_SOCKET_DGRAM_NOT_CONNECTED",
|
||||
"EPIPE", "ENOBUFS", "ECONNREFUSED", "ECONNRESET", "EHOSTUNREACH",
|
||||
"ENETUNREACH", "ENETDOWN", "EACCES", "EPERM", "EINVAL", "EMSGSIZE",
|
||||
"EAGAIN", "ENOTCONN", "EBADF",
|
||||
]);
|
||||
|
||||
function safeSocketErrorCode(error: unknown): string | undefined {
|
||||
try {
|
||||
if (!error || typeof error !== "object") return undefined;
|
||||
const code = (error as { code?: unknown }).code;
|
||||
return typeof code === "string" && SAFE_SOCKET_ERROR_CODES.has(code) ? code : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// Command notifications and UDP voice packets can be reordered in flight.
|
||||
// Retain a leaving client's UID briefly so its final packet is still
|
||||
// attributable; a new clientEnter for the same id cancels and overwrites it.
|
||||
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<
|
||||
@@ -117,18 +186,21 @@ export class TS3Client extends EventEmitter {
|
||||
private detectedProtocol: ServerProtocol = "unknown";
|
||||
private httpQuery: TS6HttpQuery | null = null;
|
||||
private udpErrorTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private readonly voiceEndpointResolver = new TrackingVoiceEndpointResolver();
|
||||
private connectionGeneration = 0;
|
||||
private voiceFailureTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private voiceFailure: { code?: string; consecutiveFailures: number; startedAt: number } | null = null;
|
||||
private voiceEndpointResolver = new TrackingVoiceEndpointResolver();
|
||||
|
||||
constructor(private options: TS3ClientOptions, logger: Logger) {
|
||||
super();
|
||||
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(). */
|
||||
@@ -142,18 +214,25 @@ export class TS3Client extends EventEmitter {
|
||||
}
|
||||
|
||||
async connect(): Promise<void> {
|
||||
this.voiceEndpointResolver.reset();
|
||||
const generation = ++this.connectionGeneration;
|
||||
this.resetVoiceSendState();
|
||||
this.disconnecting = false;
|
||||
const voiceEndpointResolver = new TrackingVoiceEndpointResolver();
|
||||
this.voiceEndpointResolver = voiceEndpointResolver;
|
||||
this.clearVisibleClientUids();
|
||||
this.httpQuery = null;
|
||||
// Clean up any existing connection before creating a new one
|
||||
if (this.client) {
|
||||
const previousClient = this.client;
|
||||
this.client = null;
|
||||
this.clientId = 0;
|
||||
if (previousClient) {
|
||||
this.logger.info("Cleaning up previous connection before reconnecting");
|
||||
try {
|
||||
await this.client.disconnect();
|
||||
await previousClient.disconnect();
|
||||
} catch {
|
||||
// Ignore errors during cleanup
|
||||
}
|
||||
this.client = null;
|
||||
this.clientId = 0;
|
||||
if (generation !== this.connectionGeneration) return;
|
||||
}
|
||||
|
||||
const addr = `${this.options.host}:${this.options.port}`;
|
||||
@@ -173,6 +252,7 @@ export class TS3Client extends EventEmitter {
|
||||
3000,
|
||||
{ ts3QueryPort: 10011, ts6HttpPort: 10080 },
|
||||
);
|
||||
if (generation !== this.connectionGeneration) return;
|
||||
this.detectedProtocol = detection.protocol;
|
||||
if (this.detectedProtocol === "unknown") {
|
||||
this.logger.warn(
|
||||
@@ -198,117 +278,136 @@ export class TS3Client extends EventEmitter {
|
||||
});
|
||||
}
|
||||
|
||||
// Guard against calling connect() while already connected.
|
||||
// Save detectedProtocol first because disconnect() resets it.
|
||||
if (this.client) {
|
||||
this.logger.warn("connect() called while already connected, disconnecting first");
|
||||
const savedProtocol = this.detectedProtocol;
|
||||
const savedHttpQuery = this.httpQuery;
|
||||
this.disconnect();
|
||||
this.detectedProtocol = savedProtocol;
|
||||
this.httpQuery = savedHttpQuery;
|
||||
// Give the old client a moment to tear down
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
}
|
||||
|
||||
this.logger.info(
|
||||
{ addr, protocol: this.detectedProtocol },
|
||||
"Connecting to TeamSpeak server (full client protocol)",
|
||||
);
|
||||
|
||||
// Throttle repeated "udp send error" warnings (fires every 20ms during playback if UDP breaks)
|
||||
let sdkClient: TS3FullClient | null = null;
|
||||
const isCurrent = () => sdkClient !== null && this.client === sdkClient &&
|
||||
this.connectionGeneration === generation && !this.disconnecting;
|
||||
let udpErrorCount = 0;
|
||||
let udpErrorCode: string | undefined;
|
||||
const throttledWarn = (msg: string, ...args: unknown[]) => {
|
||||
if (!isCurrent()) return;
|
||||
if (typeof msg === "string" && msg.includes("udp send error")) {
|
||||
udpErrorCount++;
|
||||
udpErrorCode = args.map(safeSocketErrorCode).find(code => code !== undefined) ?? udpErrorCode;
|
||||
if (udpErrorCount === 1) {
|
||||
this.logger.warn(msg);
|
||||
this.logger.warn({ ...(udpErrorCode ? { code: udpErrorCode } : {}), count: 1 }, "udp send error");
|
||||
// After 2 seconds, log a summary and reset.
|
||||
// Clear any previous timer to avoid leaking it.
|
||||
if (this.udpErrorTimer) clearTimeout(this.udpErrorTimer);
|
||||
this.udpErrorTimer = setTimeout(() => {
|
||||
if (!isCurrent()) return;
|
||||
if (udpErrorCount > 1) {
|
||||
this.logger.warn(`udp send error (repeated ${udpErrorCount} times, connection may be lost)`);
|
||||
this.logger.warn({ ...(udpErrorCode ? { code: udpErrorCode } : {}), count: udpErrorCount }, "Repeated udp send error; connection may be lost");
|
||||
}
|
||||
udpErrorCount = 0;
|
||||
udpErrorCode = undefined;
|
||||
this.udpErrorTimer = null;
|
||||
}, 2000);
|
||||
this.udpErrorTimer.unref?.();
|
||||
}
|
||||
return;
|
||||
}
|
||||
this.logger.warn(msg);
|
||||
};
|
||||
|
||||
this.client = 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: this.voiceEndpointResolver,
|
||||
resolver: voiceEndpointResolver,
|
||||
logger: {
|
||||
debug: (msg) => this.logger.debug(msg),
|
||||
info: (msg) => 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) => 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;
|
||||
|
||||
this.client.on("textMessage", (msg: TextMessage) => {
|
||||
sdkClient.on("textMessage", (msg: TextMessageEvent) => {
|
||||
if (!isCurrent()) return;
|
||||
if (msg.invokerID === this.clientId) return;
|
||||
this.emit("textMessage", toTS3TextMessage(msg));
|
||||
});
|
||||
|
||||
this.client.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);
|
||||
});
|
||||
|
||||
this.client.on("disconnected", (err) => {
|
||||
this.logger.warn({ err: err?.message }, "Connection closed");
|
||||
sdkClient.on("disconnected", (ev: DisconnectedEvent) => {
|
||||
if (!isCurrent()) return;
|
||||
const code = safeSocketErrorCode(ev.error);
|
||||
this.logger.warn(code ? { code } : {}, "Connection closed");
|
||||
++this.connectionGeneration;
|
||||
this.resetVoiceSendState();
|
||||
this.client = null;
|
||||
this.clientId = 0;
|
||||
this.clearVisibleClientUids();
|
||||
this.emit("disconnected");
|
||||
});
|
||||
|
||||
this.client.on("clientEnter", (info: ClientInfo) => {
|
||||
this.rememberVisibleClientUid(info.id, info.uid);
|
||||
sdkClient.on("clientEnter", (info: ClientEnterEvent) => {
|
||||
if (!isCurrent()) return;
|
||||
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);
|
||||
});
|
||||
|
||||
this.client.on("clientLeave", (ev: ClientLeftViewEvent) => {
|
||||
this.releaseVisibleClientUid(ev.id);
|
||||
this.logger.debug({ id: ev.id }, "Client left");
|
||||
this.emit("clientLeave", ev);
|
||||
sdkClient.on("clientLeave", (ev: ClientLeaveEvent) => {
|
||||
if (!isCurrent()) return;
|
||||
const id = Number(ev.clientID);
|
||||
this.releaseVisibleClientUid(id);
|
||||
this.logger.debug({ id }, "Client left");
|
||||
this.emit("clientLeave", { ...ev, id });
|
||||
});
|
||||
|
||||
this.client.on("clientMoved", (ev: ClientMovedEvent) => {
|
||||
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 this.client.connect();
|
||||
// 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 this.client.waitConnected();
|
||||
this.clientId = this.client.clientID();
|
||||
await sdkClient.connect();
|
||||
if (!isCurrent()) {
|
||||
// Handshake may finish after disconnect() or a newer connect() superseded it.
|
||||
await sdkClient.disconnect().catch(() => {});
|
||||
return;
|
||||
}
|
||||
this.clientId = Number(sdkClient.clientID);
|
||||
if (sdkClient.uid) {
|
||||
this.clientUid = sdkClient.uid;
|
||||
}
|
||||
this.voiceFramesSent = 0;
|
||||
this.logger.info(
|
||||
{ clientId: this.clientId, protocol: this.detectedProtocol },
|
||||
@@ -325,25 +424,37 @@ export class TS3Client extends EventEmitter {
|
||||
);
|
||||
}
|
||||
|
||||
this.emit("connected");
|
||||
if (isCurrent()) this.emit("connected");
|
||||
}
|
||||
|
||||
async joinChannel(channelName: string, password?: string): Promise<void> {
|
||||
if (!this.client) return;
|
||||
const client = this.client;
|
||||
if (!client || this.disconnecting) return;
|
||||
const clientId = this.clientId;
|
||||
const generation = this.connectionGeneration;
|
||||
const isCurrent = () => this.client === client && this.clientId === clientId &&
|
||||
this.connectionGeneration === generation && !this.disconnecting;
|
||||
|
||||
const isNumeric = /^\d+$/.test(channelName);
|
||||
if (isNumeric) {
|
||||
try {
|
||||
await clientMove(this.client, this.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) {
|
||||
this.logger.error({ err, channelName }, "Failed to join channel");
|
||||
if (isCurrent()) this.logger.error({ err, channelName }, "Failed to join channel");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const channels = await listChannels(this.client);
|
||||
const channels = await listChannels(client);
|
||||
if (!isCurrent()) return;
|
||||
const channel = channels.find((ch) => ch.name === channelName);
|
||||
|
||||
if (!channel) {
|
||||
@@ -351,31 +462,56 @@ export class TS3Client extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
|
||||
await clientMove(this.client, this.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() },
|
||||
"Joined channel"
|
||||
);
|
||||
} catch (err) {
|
||||
this.logger.error({ err, channelName }, "Failed to join channel");
|
||||
if (isCurrent()) this.logger.error({ err, channelName }, "Failed to join channel");
|
||||
}
|
||||
}
|
||||
|
||||
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 [];
|
||||
@@ -392,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 {
|
||||
@@ -406,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> {
|
||||
@@ -436,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). */
|
||||
@@ -449,28 +586,77 @@ 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;
|
||||
|
||||
sendVoiceData(opusFrame: Buffer): void {
|
||||
if (!this.client || this.disconnecting) return;
|
||||
sendVoiceData(opusFrame: Buffer): TS3VoiceSendResult {
|
||||
const client = this.client;
|
||||
if (!client || this.disconnecting) return "unavailable";
|
||||
try {
|
||||
this.client.sendVoice(opusFrame, 5);
|
||||
this.voiceFramesSent++;
|
||||
if (this.voiceFramesSent === 1) {
|
||||
this.logger.info({ opusBytes: opusFrame.length, clientId: this.clientId }, "First voice packet sent to TeamSpeak");
|
||||
}
|
||||
client.sendVoice(opusFrame, Codec.OpusMusic);
|
||||
} catch (err) {
|
||||
if (this.voiceFramesSent === 0) {
|
||||
this.logger.error({ err }, "Failed to send first voice packet");
|
||||
if (this.voiceFailure) {
|
||||
this.voiceFailure.consecutiveFailures++;
|
||||
this.voiceFailure.code = safeSocketErrorCode(err) ?? this.voiceFailure.code;
|
||||
return this.voiceFailureTimer ? "retrying" : "failed";
|
||||
}
|
||||
const code = safeSocketErrorCode(err);
|
||||
const failure = this.voiceFailure = {
|
||||
...(code ? { code } : {}), consecutiveFailures: 1, startedAt: Date.now(),
|
||||
};
|
||||
const generation = this.connectionGeneration;
|
||||
this.voiceFailureTimer = setTimeout(() => {
|
||||
if (this.client !== client || this.connectionGeneration !== generation ||
|
||||
this.disconnecting || this.voiceFailure !== failure) return;
|
||||
this.voiceFailureTimer = null;
|
||||
const event = this.voiceFailureDetails(failure);
|
||||
this.logger.error(event, "Voice sends have failed continuously; pausing playback is required");
|
||||
this.emit("voiceSendFailed", event);
|
||||
}, VOICE_SEND_FAILURE_TIMEOUT_MS);
|
||||
this.voiceFailureTimer.unref?.();
|
||||
const event = this.voiceFailureDetails(failure);
|
||||
this.logger.warn(event, "Voice send failed");
|
||||
this.emit("voiceSendFailure", event);
|
||||
return "retrying";
|
||||
}
|
||||
this.voiceFramesSent++;
|
||||
if (this.voiceFramesSent === 1) {
|
||||
this.logger.info({ opusBytes: opusFrame.length, clientId: this.clientId }, "First voice packet accepted by TeamSpeak client");
|
||||
}
|
||||
if (this.voiceFailure) {
|
||||
const event = this.voiceFailureDetails(this.voiceFailure);
|
||||
this.clearVoiceFailure();
|
||||
this.logger.info(event, "Voice send recovered");
|
||||
this.emit("voiceSendRecovered", event);
|
||||
}
|
||||
return "accepted";
|
||||
}
|
||||
|
||||
private voiceFailureDetails(failure: NonNullable<TS3Client["voiceFailure"]>): TS3VoiceSendFailure {
|
||||
return {
|
||||
...(failure.code ? { code: failure.code } : {}),
|
||||
consecutiveFailures: failure.consecutiveFailures,
|
||||
durationMs: Math.max(0, Date.now() - failure.startedAt),
|
||||
};
|
||||
}
|
||||
|
||||
private clearVoiceFailure(): void {
|
||||
if (this.voiceFailureTimer) clearTimeout(this.voiceFailureTimer);
|
||||
this.voiceFailureTimer = null;
|
||||
this.voiceFailure = null;
|
||||
}
|
||||
|
||||
private resetVoiceSendState(): void {
|
||||
this.clearVoiceFailure();
|
||||
this.voiceFramesSent = 0;
|
||||
if (this.udpErrorTimer) clearTimeout(this.udpErrorTimer);
|
||||
this.udpErrorTimer = null;
|
||||
}
|
||||
|
||||
getIdentityExport(): string {
|
||||
return this.identity.toString();
|
||||
return this.identity.export();
|
||||
}
|
||||
|
||||
getClientId(): number {
|
||||
@@ -524,24 +710,20 @@ export class TS3Client extends EventEmitter {
|
||||
}
|
||||
|
||||
disconnect(): void {
|
||||
if (this.client && !this.disconnecting) {
|
||||
const generation = ++this.connectionGeneration;
|
||||
this.resetVoiceSendState();
|
||||
const client = this.client;
|
||||
this.client = null;
|
||||
if (client && !this.disconnecting) {
|
||||
this.disconnecting = true;
|
||||
const client = this.client;
|
||||
client.disconnect().catch(() => {}).finally(() => {
|
||||
if (this.client === client) {
|
||||
this.client = null;
|
||||
}
|
||||
this.disconnecting = false;
|
||||
if (generation === this.connectionGeneration) this.disconnecting = false;
|
||||
});
|
||||
}
|
||||
this.clientId = 0;
|
||||
this.clearVisibleClientUids();
|
||||
this.httpQuery = null;
|
||||
this.detectedProtocol = "unknown";
|
||||
if (this.udpErrorTimer) {
|
||||
clearTimeout(this.udpErrorTimer);
|
||||
this.udpErrorTimer = null;
|
||||
}
|
||||
this.logger.info("Disconnected from TeamSpeak server");
|
||||
}
|
||||
}
|
||||
@@ -167,7 +167,12 @@ export class TS6HttpQuery {
|
||||
|
||||
/** List clients on a virtual server */
|
||||
async clientList(sid = 1): Promise<HttpQueryResult> {
|
||||
return this.request("GET", `/1/clientlist?sid=${sid}`);
|
||||
const path = `/1/clientlist?sid=${sid}`;
|
||||
const result = await this.request("GET", path);
|
||||
if (result.status < 200 || result.status >= 300) {
|
||||
throw new HttpQueryError(path, result.status, result.body);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** List channels on a virtual server */
|
||||
@@ -209,6 +214,51 @@ export class TS6HttpQuery {
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit a specific connected client.
|
||||
*
|
||||
* clientUpdate() modifies the HTTP Query client itself.
|
||||
* clientEdit() explicitly targets the supplied clid.
|
||||
*/
|
||||
async clientEdit(
|
||||
clid: number,
|
||||
properties: Record<string, string | number>,
|
||||
sid = 1,
|
||||
): Promise<HttpQueryResult> {
|
||||
const path = `/1/clientedit?sid=${sid}`;
|
||||
const result = await this.request("POST", path, {
|
||||
clid,
|
||||
...properties,
|
||||
});
|
||||
|
||||
if (result.status < 200 || result.status >= 300) {
|
||||
throw new HttpQueryError(path, result.status, result.body);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit a specific channel.
|
||||
*/
|
||||
async channelEdit(
|
||||
cid: number,
|
||||
properties: Record<string, string | number>,
|
||||
sid = 1,
|
||||
): Promise<HttpQueryResult> {
|
||||
const path = `/1/channeledit?sid=${sid}`;
|
||||
const result = await this.request("POST", path, {
|
||||
cid,
|
||||
...properties,
|
||||
});
|
||||
|
||||
if (result.status < 200 || result.status >= 300) {
|
||||
throw new HttpQueryError(path, result.status, result.body);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Move a client to a channel */
|
||||
async clientMove(
|
||||
clid: 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();
|
||||
@@ -0,0 +1,155 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from "vitest";
|
||||
import express from "express";
|
||||
import cookieParser from "cookie-parser";
|
||||
import request from "supertest";
|
||||
import { createDatabase, type BotDatabase } from "../../data/database.js";
|
||||
import { createUserStore } from "../../data/users.js";
|
||||
import { createSessionStore, type SessionStore } from "../../data/sessions.js";
|
||||
import { createAuditStore, type AuditStore } from "../../data/audit.js";
|
||||
import { createApiKeyStore, MAX_API_KEYS_PER_USER, type ApiKeyStore } from "../../data/api-keys.js";
|
||||
import { createPermissionStore } from "../../data/permissions.js";
|
||||
import { createRequireAuth } from "../middleware/requireAuth.js";
|
||||
import { createApiKeysRouter } from "./api-keys.js";
|
||||
import { SESSION_COOKIE_NAME } from "../auth/validateSession.js";
|
||||
|
||||
describe("api-keys router", () => {
|
||||
let botDb: BotDatabase;
|
||||
let app: express.Express;
|
||||
let sessions: SessionStore;
|
||||
let apiKeys: ApiKeyStore;
|
||||
let audit: AuditStore;
|
||||
let adminId: string;
|
||||
let memberId: string;
|
||||
let adminToken: string;
|
||||
let memberToken: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
botDb = createDatabase(":memory:");
|
||||
const users = createUserStore(botDb.db);
|
||||
sessions = createSessionStore(botDb.db);
|
||||
audit = createAuditStore(botDb.db);
|
||||
const permissions = createPermissionStore(botDb.db);
|
||||
apiKeys = createApiKeyStore(botDb.db);
|
||||
const admin = await users.createUser("alice", "pw-alice", "admin");
|
||||
const member = await users.createUser("bob", "pw-bob", "member");
|
||||
adminId = admin.id;
|
||||
memberId = member.id;
|
||||
adminToken = sessions.createSession(adminId).token;
|
||||
memberToken = sessions.createSession(memberId).token;
|
||||
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use(cookieParser());
|
||||
app.use(
|
||||
createRequireAuth(sessions, permissions, () => ({
|
||||
enabled: false,
|
||||
bots: "all",
|
||||
permissions: {} as any,
|
||||
}), apiKeys)
|
||||
);
|
||||
app.use("/api/keys", createApiKeysRouter(apiKeys, audit, { info: () => {}, warn: () => {}, error: () => {}, child: () => ({}) } as any));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
botDb.close();
|
||||
});
|
||||
|
||||
const authed = (token: string) => {
|
||||
const cookie = `${SESSION_COOKIE_NAME}=${token}`;
|
||||
return {
|
||||
get: (url: string) => request(app).get(url).set("Cookie", cookie),
|
||||
post: (url: string) => request(app).post(url).set("Cookie", cookie),
|
||||
delete: (url: string) => request(app).delete(url).set("Cookie", cookie),
|
||||
};
|
||||
};
|
||||
const asAdmin = () => authed(adminToken);
|
||||
const asMember = () => authed(memberToken);
|
||||
|
||||
it("lists only the caller's own keys", async () => {
|
||||
apiKeys.create(adminId, "mine");
|
||||
apiKeys.create(memberId, "theirs");
|
||||
const res = await asAdmin().get("/api/keys");
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.keys).toHaveLength(1);
|
||||
expect(res.body.keys[0].name).toBe("mine");
|
||||
expect(res.body.keys[0].rawKey).toBeUndefined();
|
||||
});
|
||||
|
||||
it("creates a key and returns the plaintext exactly once", async () => {
|
||||
const res = await asAdmin().post("/api/keys").send({ name: "ci" });
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body.rawKey).toMatch(/^tsmb_/);
|
||||
expect(apiKeys.validateAndTouch(res.body.rawKey)?.userId).toBe(adminId);
|
||||
// The list view never exposes the plaintext again.
|
||||
const list = await asAdmin().get("/api/keys");
|
||||
expect(JSON.stringify(list.body)).not.toContain(res.body.rawKey);
|
||||
});
|
||||
|
||||
it("rejects creation without a valid name", async () => {
|
||||
expect((await asAdmin().post("/api/keys").send({})).status).toBe(400);
|
||||
expect((await asAdmin().post("/api/keys").send({ name: "" })).status).toBe(400);
|
||||
expect((await asAdmin().post("/api/keys").send({ name: "x".repeat(65) })).status).toBe(400);
|
||||
});
|
||||
|
||||
it("rejects creation beyond the per-user cap with 409", async () => {
|
||||
for (let i = 0; i < MAX_API_KEYS_PER_USER; i++) {
|
||||
apiKeys.create(memberId, `k${i}`);
|
||||
}
|
||||
const res = await asMember().post("/api/keys").send({ name: "overflow" });
|
||||
expect(res.status).toBe(409);
|
||||
});
|
||||
|
||||
it("deletes own key and it stops validating", async () => {
|
||||
const { key } = apiKeys.create(memberId, "ci")!;
|
||||
const res = await asMember().delete(`/api/keys/${key.id}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(apiKeys.listForUser(memberId)).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("a member cannot delete another user's key", async () => {
|
||||
const { key } = apiKeys.create(adminId, "admin-key")!;
|
||||
const res = await asMember().delete(`/api/keys/${key.id}`);
|
||||
expect(res.status).toBe(404);
|
||||
expect(apiKeys.listForUser(adminId)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("an admin revoking another user's key audits that key's owner", async () => {
|
||||
const { key } = apiKeys.create(memberId, "member-key")!;
|
||||
const res = await asAdmin().delete(`/api/keys/${key.id}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(apiKeys.listForUser(memberId)).toHaveLength(0);
|
||||
expect(audit.list(10, 0)).toEqual([
|
||||
expect.objectContaining({
|
||||
actorId: adminId,
|
||||
actorUsername: "alice",
|
||||
targetUserId: memberId,
|
||||
targetUsername: "bob",
|
||||
action: "api_key.deleted",
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("admin can list all keys with ?all=1, members cannot", async () => {
|
||||
apiKeys.create(adminId, "a");
|
||||
apiKeys.create(memberId, "b");
|
||||
const adminAll = await asAdmin().get("/api/keys?all=1");
|
||||
expect(adminAll.body.keys).toHaveLength(2);
|
||||
expect(adminAll.body.keys.map((k: any) => k.username).sort()).toEqual(["alice", "bob"]);
|
||||
const memberAll = await asMember().get("/api/keys?all=1");
|
||||
expect(memberAll.body.keys).toHaveLength(1);
|
||||
expect(memberAll.body.keys[0].name).toBe("b");
|
||||
});
|
||||
|
||||
it("a request authenticated by an API key cannot manage keys", async () => {
|
||||
const { rawKey } = apiKeys.create(adminId, "self-mgmt")!;
|
||||
const res = await request(app)
|
||||
.post("/api/keys")
|
||||
.set("Authorization", `Bearer ${rawKey}`)
|
||||
.send({ name: "proliferate" });
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
|
||||
it("requires authentication", async () => {
|
||||
expect((await request(app).get("/api/keys")).status).toBe(401);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
import { Router } from "express";
|
||||
import type { Request, Response, NextFunction } from "express";
|
||||
import type { ApiKeyStore } from "../../data/api-keys.js";
|
||||
import { MAX_API_KEYS_PER_USER } from "../../data/api-keys.js";
|
||||
import type { AuditStore } from "../../data/audit.js";
|
||||
import type { Logger } from "../../logger.js";
|
||||
|
||||
/**
|
||||
* API-key management (list / create / revoke), mounted at /api/keys.
|
||||
* Only interactive sessions may call these endpoints. Administrator keys
|
||||
* retain user-management authority through /api/users.
|
||||
*/
|
||||
export function createApiKeysRouter(apiKeys: ApiKeyStore, audit: AuditStore, logger: Logger): Router {
|
||||
const router = Router();
|
||||
|
||||
const rejectApiKeyAuth = (req: Request, res: Response, next: NextFunction): void => {
|
||||
if (req.authMethod === "api-key") {
|
||||
res.status(403).json({ error: "API keys cannot manage API keys — log in to the WebUI" });
|
||||
return;
|
||||
}
|
||||
next();
|
||||
};
|
||||
router.use(rejectApiKeyAuth);
|
||||
|
||||
// GET /api/keys — the caller's keys; admins may pass ?all=1 for every user's.
|
||||
router.get("/", (req, res) => {
|
||||
const user = req.user!;
|
||||
if (req.query.all === "1" && user.role === "admin") {
|
||||
res.json({ keys: apiKeys.listAll() });
|
||||
return;
|
||||
}
|
||||
res.json({ keys: apiKeys.listForUser(user.id) });
|
||||
});
|
||||
|
||||
// POST /api/keys — create a key; the plaintext is returned exactly once.
|
||||
router.post("/", (req, res) => {
|
||||
const user = req.user!;
|
||||
const name = typeof req.body?.name === "string" ? req.body.name.trim() : "";
|
||||
if (!name || name.length > 64) {
|
||||
res.status(400).json({ error: "name is required (1-64 characters)" });
|
||||
return;
|
||||
}
|
||||
const created = apiKeys.create(user.id, name);
|
||||
if (!created) {
|
||||
res.status(409).json({ error: `每个用户最多创建 ${MAX_API_KEYS_PER_USER} 个 API Key` });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
audit.record({
|
||||
actorId: user.id,
|
||||
actorUsername: user.username,
|
||||
targetUserId: user.id,
|
||||
targetUsername: user.username,
|
||||
action: "api_key.created",
|
||||
});
|
||||
} catch (auditErr) {
|
||||
logger.warn({ err: auditErr, action: "api_key.created" }, "audit insert failed");
|
||||
}
|
||||
logger.info({ userId: user.id, keyId: created.key.id }, "API key created");
|
||||
res.status(201).json(created);
|
||||
});
|
||||
|
||||
// DELETE /api/keys/:id — revoke; members only their own, admins any.
|
||||
router.delete("/:id", (req, res) => {
|
||||
const user = req.user!;
|
||||
const key = apiKeys.findById(req.params.id);
|
||||
if (!key || !apiKeys.delete(key.id, user.role === "admin" ? undefined : user.id)) {
|
||||
res.status(404).json({ error: "API key not found" });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
audit.record({
|
||||
actorId: user.id,
|
||||
actorUsername: user.username,
|
||||
targetUserId: key.userId,
|
||||
targetUsername: key.username,
|
||||
action: "api_key.deleted",
|
||||
});
|
||||
} catch (auditErr) {
|
||||
logger.warn({ err: auditErr, action: "api_key.deleted" }, "audit insert failed");
|
||||
}
|
||||
logger.info({ userId: user.id, keyId: req.params.id }, "API key deleted");
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
@@ -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", () => {
|
||||
@@ -438,3 +451,182 @@ describe("music router POST /local/upload — content types and size cap (#149)"
|
||||
expect(uploadAudio).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("music router GET /bilibili/parts", () => {
|
||||
it("returns 400 when bvid is missing", async () => {
|
||||
const router = createMusicRouter(
|
||||
fakeProvider("netease"),
|
||||
fakeProvider("qq"),
|
||||
fakeProvider("bilibili"),
|
||||
pino({ level: "silent" })
|
||||
);
|
||||
const app = express();
|
||||
app.use("/api/music", router);
|
||||
|
||||
const res = await request(app).get("/api/music/bilibili/parts");
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error).toBe("bvid is required");
|
||||
});
|
||||
|
||||
it("returns parts from bilibili provider when available", async () => {
|
||||
const mockBilibili = {
|
||||
platform: "bilibili" as const,
|
||||
search: vi.fn(),
|
||||
getVideoParts: vi.fn().mockResolvedValue({
|
||||
bvid: "BV1test",
|
||||
title: "多P视频测试",
|
||||
parts: [
|
||||
{ part: 1, cid: 101, title: "P1", duration: 100 },
|
||||
{ part: 2, cid: 102, title: "P2", duration: 200 },
|
||||
],
|
||||
}),
|
||||
};
|
||||
const router = createMusicRouter(
|
||||
fakeProvider("netease"),
|
||||
fakeProvider("qq"),
|
||||
mockBilibili as unknown as MusicProvider,
|
||||
pino({ level: "silent" })
|
||||
);
|
||||
const app = express();
|
||||
app.use("/api/music", router);
|
||||
|
||||
const res = await request(app).get("/api/music/bilibili/parts?bvid=BV1test");
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.bvid).toBe("BV1test");
|
||||
expect(res.body.parts).toHaveLength(2);
|
||||
expect(mockBilibili.getVideoParts).toHaveBeenCalledWith("BV1test");
|
||||
});
|
||||
|
||||
it("returns 404 when getVideoParts returns null", async () => {
|
||||
const mockBilibili = {
|
||||
platform: "bilibili" as const,
|
||||
search: vi.fn(),
|
||||
getVideoParts: vi.fn().mockResolvedValue(null),
|
||||
};
|
||||
const router = createMusicRouter(
|
||||
fakeProvider("netease"),
|
||||
fakeProvider("qq"),
|
||||
mockBilibili as unknown as MusicProvider,
|
||||
pino({ level: "silent" })
|
||||
);
|
||||
const app = express();
|
||||
app.use("/api/music", router);
|
||||
|
||||
const res = await request(app).get("/api/music/bilibili/parts?bvid=BV1notfound");
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe("music router GET /artist/:id", () => {
|
||||
function artistProvider(overrides: Record<string, unknown> = {}): MusicProvider {
|
||||
return {
|
||||
platform: "netease",
|
||||
search: vi.fn().mockResolvedValue(empty),
|
||||
getArtistDetail: vi.fn().mockResolvedValue({
|
||||
id: "6452",
|
||||
name: "Adele",
|
||||
avatarUrl: "http://p/1.jpg",
|
||||
platform: "netease",
|
||||
description: "English singer",
|
||||
}),
|
||||
getArtistSongs: vi.fn().mockResolvedValue([
|
||||
{ id: "1", name: "Hello", artist: "Adele", album: "25", duration: 295, coverUrl: "c", platform: "netease" },
|
||||
]),
|
||||
getArtistAlbums: vi.fn().mockResolvedValue([
|
||||
{ id: "a1", name: "25", artist: "Adele", coverUrl: "c", songCount: 11, platform: "netease" },
|
||||
]),
|
||||
...overrides,
|
||||
} as unknown as MusicProvider;
|
||||
}
|
||||
|
||||
function mount(netease: MusicProvider, qq: MusicProvider = fakeProvider("qq")) {
|
||||
const app = express();
|
||||
app.use("/api/music", createMusicRouter(netease, qq, fakeProvider("bilibili"), pino({ level: "silent" })));
|
||||
return app;
|
||||
}
|
||||
|
||||
it("returns artist detail, hot songs and albums for the requested platform", async () => {
|
||||
const netease = artistProvider();
|
||||
const res = await request(mount(netease)).get("/api/music/artist/6452?platform=netease");
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.artist).toMatchObject({ id: "6452", name: "Adele", description: "English singer" });
|
||||
expect(res.body.songs).toHaveLength(1);
|
||||
expect(res.body.albums).toHaveLength(1);
|
||||
expect(netease.getArtistDetail).toHaveBeenCalledWith("6452");
|
||||
expect(netease.getArtistSongs).toHaveBeenCalledWith("6452");
|
||||
expect(netease.getArtistAlbums).toHaveBeenCalledWith("6452");
|
||||
});
|
||||
|
||||
it("routes to the QQ provider when platform=qq", async () => {
|
||||
const qq = artistProvider({ platform: "qq" });
|
||||
const res = await request(mount(fakeProvider("netease"), qq)).get("/api/music/artist/abc?platform=qq");
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(qq.getArtistDetail).toHaveBeenCalledWith("abc");
|
||||
});
|
||||
|
||||
it("404s when the provider has no such artist", async () => {
|
||||
const netease = artistProvider({ getArtistDetail: vi.fn().mockResolvedValue(null) });
|
||||
const res = await request(mount(netease)).get("/api/music/artist/999");
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body.error).toBe("Artist not found");
|
||||
});
|
||||
|
||||
it("501s when the provider does not support artists at all", async () => {
|
||||
const res = await request(mount(fakeProvider("netease"))).get("/api/music/artist/1");
|
||||
expect(res.status).toBe(501);
|
||||
expect(res.body.error).toBe("Not supported by this provider");
|
||||
});
|
||||
|
||||
it("degrades each leg independently — a failing songs/albums call still returns the hero", async () => {
|
||||
const netease = artistProvider({
|
||||
getArtistSongs: vi.fn().mockRejectedValue(new Error("boom")),
|
||||
getArtistAlbums: vi.fn().mockRejectedValue(new Error("boom")),
|
||||
});
|
||||
const res = await request(mount(netease)).get("/api/music/artist/6452");
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.artist.name).toBe("Adele");
|
||||
expect(res.body.songs).toEqual([]);
|
||||
expect(res.body.albums).toEqual([]);
|
||||
});
|
||||
|
||||
it("tolerates a provider that only implements getArtistDetail", async () => {
|
||||
const netease = artistProvider({ getArtistSongs: undefined, getArtistAlbums: undefined });
|
||||
const res = await request(mount(netease)).get("/api/music/artist/6452");
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.songs).toEqual([]);
|
||||
expect(res.body.albums).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("music router GET /search/all artist aggregation", () => {
|
||||
function searchProvider(platform: MusicProvider["platform"], artists: unknown[]): MusicProvider {
|
||||
return {
|
||||
platform,
|
||||
search: vi.fn().mockResolvedValue({ ...empty, artists }),
|
||||
} as unknown as MusicProvider;
|
||||
}
|
||||
|
||||
it("merges artists from netease and qq and ignores sources without artists", async () => {
|
||||
const app = express();
|
||||
app.use(
|
||||
"/api/music",
|
||||
createMusicRouter(
|
||||
searchProvider("netease", [{ id: "1", name: "N", avatarUrl: "", platform: "netease" }]),
|
||||
searchProvider("qq", [{ id: "2", name: "Q", avatarUrl: "", platform: "qq" }]),
|
||||
fakeProvider("bilibili"),
|
||||
pino({ level: "silent" })
|
||||
)
|
||||
);
|
||||
|
||||
const res = await request(app).get("/api/music/search/all?q=adele");
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.artists).toEqual([
|
||||
{ id: "1", name: "N", avatarUrl: "", platform: "netease" },
|
||||
{ id: "2", name: "Q", avatarUrl: "", platform: "qq" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
+133
-37
@@ -1,11 +1,14 @@
|
||||
import express, { Router, type Response } from "express";
|
||||
import type { MusicProvider, Song, Album } from "../../music/provider.js";
|
||||
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 });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -198,14 +217,25 @@ export function createMusicRouter(
|
||||
// searched. Jellyfin (an opt-in source) leads the merged results when
|
||||
// enabled — a self-hosted library match is almost always the wanted one.
|
||||
const enabled = (p: string) => !config || isProviderEnabled(config, p);
|
||||
const none = { songs: [], albums: [], playlists: [] };
|
||||
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 = [
|
||||
@@ -226,11 +256,18 @@ export function createMusicRouter(
|
||||
...(neteaseResult.status === "fulfilled" ? neteaseResult.value.playlists : []),
|
||||
...(qqResult.status === "fulfilled" ? qqResult.value.playlists : []),
|
||||
];
|
||||
// Artists come only from the sources that model them (netease/qq); other
|
||||
// providers simply contribute nothing.
|
||||
const artists = [
|
||||
...(neteaseResult.status === "fulfilled" ? neteaseResult.value.artists ?? [] : []),
|
||||
...(qqResult.status === "fulfilled" ? qqResult.value.artists ?? [] : []),
|
||||
];
|
||||
|
||||
res.json({ songs, albums, playlists });
|
||||
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 });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -240,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) {
|
||||
@@ -249,57 +286,87 @@ 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, req);
|
||||
if (!provider) return;
|
||||
if (!provider.getArtistDetail) {
|
||||
res.status(501).json({ error: "Not supported by this provider" });
|
||||
return;
|
||||
}
|
||||
// Each piece degrades independently: a source that cannot list albums (or
|
||||
// a transient upstream failure) must not take the hero or the songs down
|
||||
// with it, so every call falls back to an empty value.
|
||||
const [artist, songs, albums] = await Promise.all([
|
||||
provider.getArtistDetail(req.params.id).catch(() => null),
|
||||
provider.getArtistSongs
|
||||
? provider.getArtistSongs(req.params.id).catch(() => [] as Song[])
|
||||
: Promise.resolve([] as Song[]),
|
||||
provider.getArtistAlbums
|
||||
? provider.getArtistAlbums(req.params.id).catch(() => [] as Album[])
|
||||
: Promise.resolve([] as Album[]),
|
||||
]);
|
||||
if (!artist) {
|
||||
res.status(404).json({ error: "Artist not found" });
|
||||
return;
|
||||
}
|
||||
res.json({ artist, songs, albums });
|
||||
} catch (err) {
|
||||
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" });
|
||||
@@ -308,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" });
|
||||
@@ -324,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" });
|
||||
@@ -340,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" });
|
||||
@@ -360,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 });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -382,6 +453,31 @@ export function createMusicRouter(
|
||||
}
|
||||
});
|
||||
|
||||
// B站分P列表查询
|
||||
router.get("/bilibili/parts", async (req, res) => {
|
||||
try {
|
||||
const bvid = (req.query.bvid as string)?.trim();
|
||||
if (!bvid) {
|
||||
res.status(400).json({ error: "bvid is required" });
|
||||
return;
|
||||
}
|
||||
const provider = bilibiliProvider as any;
|
||||
if (typeof provider.getVideoParts === "function") {
|
||||
const result = await provider.getVideoParts(bvid);
|
||||
if (!result) {
|
||||
res.status(404).json({ error: "Video not found" });
|
||||
return;
|
||||
}
|
||||
res.json(result);
|
||||
} else {
|
||||
res.status(501).json({ error: "Not supported" });
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Get bilibili parts failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
}
|
||||
});
|
||||
|
||||
// Enabled sources + default platform, for the web UI (source tabs, default
|
||||
// search/playback source). Without a config (unit-test routers) everything
|
||||
// reports enabled with the legacy netease default.
|
||||
|
||||
@@ -374,13 +374,15 @@ describe("guest enforcement on player routes", () => {
|
||||
expect((await request(mountGuest({ transport: true })).post(`/api/player/${ALLOWED_BOT}/add-song`).send({ song: SONG })).status).toBe(403);
|
||||
});
|
||||
|
||||
it("playCollection flag gates /play-playlist, /play-album (issue #103)", async () => {
|
||||
it("playCollection flag gates /play-playlist, /play-album, /play-artist (issue #103)", async () => {
|
||||
const allow = mountGuest({ playCollection: true });
|
||||
const deny = mountGuest({ playCollection: false });
|
||||
expect((await request(allow).post(`/api/player/${ALLOWED_BOT}/play-playlist`).send({ playlistId: "1" })).status).not.toBe(403);
|
||||
expect((await request(allow).post(`/api/player/${ALLOWED_BOT}/play-album`).send({ albumId: "1" })).status).not.toBe(403);
|
||||
expect((await request(allow).post(`/api/player/${ALLOWED_BOT}/play-artist`).send({ artistId: "1" })).status).not.toBe(403);
|
||||
expect((await request(deny).post(`/api/player/${ALLOWED_BOT}/play-playlist`).send({ playlistId: "1" })).status).toBe(403);
|
||||
expect((await request(deny).post(`/api/player/${ALLOWED_BOT}/play-album`).send({ albumId: "1" })).status).toBe(403);
|
||||
expect((await request(deny).post(`/api/player/${ALLOWED_BOT}/play-artist`).send({ artistId: "1" })).status).toBe(403);
|
||||
// playCollection does NOT leak into the destructive single-song / queue ops.
|
||||
expect((await request(allow).post(`/api/player/${ALLOWED_BOT}/play`).send({ query: "x" })).status).toBe(403);
|
||||
expect((await request(allow).post(`/api/player/${ALLOWED_BOT}/play-song`).send({ song: SONG })).status).toBe(403);
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
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 { createPersonalMusicRouter } from "./personal-music.js";
|
||||
import { createPlayerRouter } from "./player.js";
|
||||
|
||||
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 (?,?,?,?,?,?)")
|
||||
.run("u1", "alice", "x", 0, 0, "member");
|
||||
const personalView = {
|
||||
getAuthStatus: vi.fn(async () => ({ loggedIn: true, nickname: "Alice163" })),
|
||||
};
|
||||
const provider: any = {
|
||||
platform: "netease",
|
||||
getQrCode: vi.fn(async () => ({ qrUrl: "u", qrImg: "data:img", key: "k1" })),
|
||||
pollQrLogin: vi.fn(async () => ({ status: "waiting" })),
|
||||
withCookie: vi.fn(() => personalView),
|
||||
setCookie: vi.fn(),
|
||||
};
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => {
|
||||
(req as any).user = { id: "u1", username: "alice", role: "member" };
|
||||
next();
|
||||
});
|
||||
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, source: "none", canUnlink: false, supportsQrLogin: true,
|
||||
preferShared: false, featureEnabled: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("creates a QR code", async () => {
|
||||
const { app } = mount();
|
||||
const res = await request(app).post("/api/me/music/netease/qrcode");
|
||||
expect(res.body).toEqual({ qrUrl: "u", qrImg: "data:img", key: "k1" });
|
||||
});
|
||||
|
||||
it("stores the cookie for this user on confirm, never on the shared provider, and never returns it", async () => {
|
||||
const { app, db, provider } = mount();
|
||||
provider.pollQrLogin.mockResolvedValue({ status: "confirmed", cookie: "MUSIC_U=alice" });
|
||||
const res = await request(app).get("/api/me/music/netease/qrcode/status").query({ key: "k1" });
|
||||
expect(res.body).toEqual({ status: "confirmed" });
|
||||
expect(JSON.stringify(res.body)).not.toContain("MUSIC_U");
|
||||
expect(db.getUserMusicCookie("u1", "netease")).toBe("MUSIC_U=alice");
|
||||
expect(provider.setCookie).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("requires a key to poll", async () => {
|
||||
const { app } = mount();
|
||||
expect((await request(app).get("/api/me/music/netease/qrcode/status")).status).toBe(400);
|
||||
});
|
||||
|
||||
it("reports the linked account's nickname via a view on the user's cookie", async () => {
|
||||
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,
|
||||
source: "personal",
|
||||
canUnlink: true,
|
||||
supportsQrLogin: true,
|
||||
preferShared: false,
|
||||
featureEnabled: false,
|
||||
loggedIn: true,
|
||||
nickname: "Alice163",
|
||||
});
|
||||
expect(provider.withCookie).toHaveBeenCalledWith("MUSIC_U=alice");
|
||||
});
|
||||
|
||||
it("unlinks", async () => {
|
||||
const { app, db } = mount();
|
||||
db.setUserMusicCookie("u1", "netease", "MUSIC_U=alice");
|
||||
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)", () => {
|
||||
async function startFm(opts: { linked: boolean; role?: string; platform?: string }) {
|
||||
const db = createDatabase(":memory:");
|
||||
db.db
|
||||
.prepare("INSERT INTO users (id, username, passwordHash, createdAt, updatedAt, role) VALUES (?,?,?,?,?,?)")
|
||||
.run("u1", "alice", "x", 0, 0, "member");
|
||||
if (opts.linked) db.setUserMusicCookie("u1", "netease", "MUSIC_U=alice");
|
||||
const personal = { platform: "netease", personal: true };
|
||||
const shared: any = { platform: "netease", pollQrLogin: vi.fn(), withCookie: vi.fn(() => personal) };
|
||||
const qq: any = { platform: "qq" };
|
||||
const bot = {
|
||||
id: "b1",
|
||||
getProviderFor: (p: string) => (p === "qq" ? qq : shared),
|
||||
startFm: vi.fn(async (_provider: unknown) => "Personal FM started"),
|
||||
};
|
||||
const botManager: any = { getBot: () => bot };
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => {
|
||||
(req as any).user = {
|
||||
id: "u1", username: "alice", role: opts.role ?? "member",
|
||||
capabilities: new Set(["player.control"]), bots: "all", guest: { playMode: true },
|
||||
};
|
||||
next();
|
||||
});
|
||||
app.use("/api/player", createPlayerRouter(botManager, pino({ level: "silent" }), db));
|
||||
const res = await request(app).post("/api/player/b1/fm").send({ platform: opts.platform ?? "netease" });
|
||||
return { res, bot, shared, personal, qq };
|
||||
}
|
||||
|
||||
it("starts FM on the user's own account when linked", async () => {
|
||||
const { res, bot, shared, personal } = await startFm({ linked: true });
|
||||
expect(res.status).toBe(200);
|
||||
expect(shared.withCookie).toHaveBeenCalledWith("MUSIC_U=alice");
|
||||
expect(bot.startFm.mock.calls[0][0]).toBe(personal);
|
||||
});
|
||||
|
||||
it("falls back to the shared account when the user has not linked one", async () => {
|
||||
const { bot, shared } = await startFm({ linked: false });
|
||||
expect(bot.startFm.mock.calls[0][0]).toBe(shared);
|
||||
});
|
||||
|
||||
it("leaves other platforms alone", async () => {
|
||||
const { bot, qq } = await startFm({ linked: true, platform: "qq" });
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,252 @@
|
||||
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
|
||||
* the bot's shared login, and hand out a view bound to that account (#164).
|
||||
*/
|
||||
export interface PersonalLoginProvider {
|
||||
getQrCode(): Promise<QrCodeResult>;
|
||||
pollQrLogin(key: string): Promise<{ status: "waiting" | "scanned" | "confirmed" | "expired"; cookie?: string }>;
|
||||
withCookie(cookie: string): MusicProvider;
|
||||
}
|
||||
|
||||
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";
|
||||
}
|
||||
|
||||
/** 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;
|
||||
|
||||
/**
|
||||
* 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,
|
||||
providers: Partial<Record<string, MusicProvider>>,
|
||||
logger: Logger,
|
||||
config?: MusicScopeDeps["config"],
|
||||
): Router {
|
||||
const router = Router();
|
||||
|
||||
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();
|
||||
});
|
||||
|
||||
/** 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(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("/: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, platform }, "Personal music QR generation failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
}
|
||||
});
|
||||
|
||||
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" });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const { status, cookie } = await provider.pollQrLogin(key);
|
||||
if (status === "confirmed" && cookie) {
|
||||
database.setUserMusicCookie(req.user!.id, platform, cookie);
|
||||
logger.info({ userId: req.user!.id, platform }, "Personal music account linked");
|
||||
}
|
||||
res.json({ status });
|
||||
} catch (err) {
|
||||
logger.error({ err, platform }, "Personal music QR status check failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
}
|
||||
});
|
||||
|
||||
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,308 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { collectArtistSongs } from "./player.js";
|
||||
import type { ArtistSongPage, Song } from "../../music/provider.js";
|
||||
import express from "express";
|
||||
import request from "supertest";
|
||||
import { createPlayerRouter } from "./player.js";
|
||||
import { BotInstance } from "../../bot/instance.js";
|
||||
import { PlayQueue } from "../../audio/queue.js";
|
||||
import type { BotDatabase } from "../../data/database.js";
|
||||
|
||||
function song(id: string): Song {
|
||||
return {
|
||||
id,
|
||||
name: `song-${id}`,
|
||||
artist: "Adele",
|
||||
album: "25",
|
||||
duration: 200,
|
||||
coverUrl: "c",
|
||||
platform: "netease",
|
||||
};
|
||||
}
|
||||
|
||||
function page(ids: string[], total: number, hasMore: boolean): ArtistSongPage {
|
||||
return { songs: ids.map(song), total, hasMore };
|
||||
}
|
||||
|
||||
describe("collectArtistSongs (play-artist all:true)", () => {
|
||||
it("walks every page until hasMore is false and de-duplicates ids", async () => {
|
||||
const pages: Record<number, ArtistSongPage> = {
|
||||
0: page(["1", "2"], 4, true),
|
||||
100: page(["2", "3"], 4, true),
|
||||
200: page(["4"], 4, false),
|
||||
};
|
||||
const fetchPage = vi.fn(async (_id: string, offset = 0, _limit = 100) => pages[offset] ?? page([], 4, false));
|
||||
|
||||
const songs = await collectArtistSongs(fetchPage as any, "artist-1");
|
||||
|
||||
expect(songs.map((s) => s.id)).toEqual(["1", "2", "3", "4"]);
|
||||
expect(fetchPage.mock.calls.map((c) => c[1])).toEqual([0, 100, 200]);
|
||||
expect(fetchPage.mock.calls[0][2]).toBe(100);
|
||||
});
|
||||
|
||||
it("stops at the 500-track safety cap", async () => {
|
||||
let n = 0;
|
||||
const fetchPage = vi.fn(async () => ({
|
||||
songs: Array.from({ length: 100 }, () => song(String(n++))),
|
||||
total: 100000,
|
||||
hasMore: true,
|
||||
}));
|
||||
|
||||
const songs = await collectArtistSongs(fetchPage as any, "a");
|
||||
|
||||
expect(songs).toHaveLength(500);
|
||||
expect(fetchPage).toHaveBeenCalledTimes(5);
|
||||
});
|
||||
|
||||
it("enforces the song cap even when an upstream page exceeds the requested limit", async () => {
|
||||
const fetchPage = vi.fn(async () => page(Array.from({ length: 600 }, (_, i) => String(i)), 600, false));
|
||||
expect(await collectArtistSongs(fetchPage, "a")).toHaveLength(500);
|
||||
});
|
||||
|
||||
it("stops on an empty page even when hasMore claims otherwise", async () => {
|
||||
const fetchPage = vi.fn(async () => page([], 9, true));
|
||||
|
||||
expect(await collectArtistSongs(fetchPage as any, "a")).toEqual([]);
|
||||
expect(fetchPage).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("returns the first page unchanged when it is already complete", async () => {
|
||||
const fetchPage = vi.fn(async () => page(["1"], 1, false));
|
||||
|
||||
const songs = await collectArtistSongs(fetchPage as any, "a");
|
||||
|
||||
expect(songs.map((s) => s.id)).toEqual(["1"]);
|
||||
expect(fetchPage).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("collection playback serialization", () => {
|
||||
it.each(["artist", "album", "playlist"])("serializes %s playback and single-song playback", async kind => {
|
||||
const queue = new PlayQueue();
|
||||
let audible: string | null = null;
|
||||
let releaseArtist!: () => void;
|
||||
let notifyArtistStarted!: () => void;
|
||||
let notifySingleArrived!: () => void;
|
||||
const artistStarted = new Promise<void>((resolve) => { notifyArtistStarted = resolve; });
|
||||
const artistHold = new Promise<void>((resolve) => { releaseArtist = resolve; });
|
||||
const singleArrived = new Promise<void>((resolve) => { notifySingleArrived = resolve; });
|
||||
const bot: any = {
|
||||
playGate: Promise.resolve(),
|
||||
getProviderFor: () => ({
|
||||
platform: "netease",
|
||||
getAlbumSongs: async () => [song("A")],
|
||||
getPlaylistSongs: async () => [song("A")],
|
||||
getArtistSongs: async () => [song("A")],
|
||||
getArtistAllSongs: async () => page(["A"], 1, false),
|
||||
}),
|
||||
emit: vi.fn(),
|
||||
getPlayer: () => ({ stop: () => { audible = null; }, resetFailures: () => {} }),
|
||||
getQueueManager: () => queue,
|
||||
resolveAndPlay: async (track: Song) => {
|
||||
notifyArtistStarted();
|
||||
await artistHold;
|
||||
audible = track.id;
|
||||
return true;
|
||||
},
|
||||
playSingleSong: async (track: Song) => {
|
||||
queue.clear();
|
||||
queue.add(track);
|
||||
queue.play();
|
||||
audible = track.id;
|
||||
return true;
|
||||
},
|
||||
};
|
||||
bot.runExclusive = (fn: () => Promise<unknown>) => BotInstance.prototype.runExclusive.call(bot, fn);
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => { (req as any).user = { role: "admin" }; next(); });
|
||||
app.use("/api/player/b/play-song", (_req, _res, next) => { notifySingleArrived(); next(); });
|
||||
app.use("/api/player", createPlayerRouter({ getBot: () => bot } as any, { error: vi.fn() } as any));
|
||||
const collectionRequest = request(app).post(`/api/player/b/play-${kind}`)
|
||||
.send({ [`${kind}Id`]: "collection", platform: "netease" }).then((res) => res);
|
||||
await artistStarted;
|
||||
const singleRequest = request(app).post("/api/player/b/play-song").send({ song: song("B") }).then((res) => res);
|
||||
// Let the overlapping HTTP request enter the real route while A's URL is pending.
|
||||
await singleArrived;
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
const whileArtistPending = queue.current()?.id;
|
||||
releaseArtist();
|
||||
const [collectionResponse, singleResponse] = await Promise.all([collectionRequest, singleRequest]);
|
||||
expect(collectionResponse.status).toBe(200);
|
||||
expect(singleResponse.status).toBe(200);
|
||||
expect(whileArtistPending).toBe("A");
|
||||
expect(queue.current()?.id).toBe("B");
|
||||
expect(audible).toBe("B");
|
||||
});
|
||||
});
|
||||
|
||||
describe("collection preflight", () => {
|
||||
it.each(["playlist", "album", "artist"])("checks QQ %s availability using the room's playback account", async kind => {
|
||||
const queue = new PlayQueue();
|
||||
const personalTracks = [{ ...song("personal-library-track"), platform: "qq" }];
|
||||
const readLibrary = vi.fn(async () => personalTracks);
|
||||
const personal = {
|
||||
platform: "qq",
|
||||
getPlaylistSongs: readLibrary,
|
||||
getAlbumSongs: readLibrary,
|
||||
getArtistSongs: readLibrary,
|
||||
getPlayableSongIds: vi.fn(async () => new Set<string>()),
|
||||
};
|
||||
const shared = {
|
||||
platform: "qq",
|
||||
withCookie: vi.fn(() => personal),
|
||||
getPlayableSongIds: vi.fn(async () => new Set(["personal-library-track"])),
|
||||
};
|
||||
const bot = {
|
||||
getProviderFor: () => shared,
|
||||
getQueueManager: () => queue,
|
||||
getPlayer: () => ({ stop: vi.fn(), resetFailures: vi.fn() }),
|
||||
runExclusive: (work: () => Promise<unknown>) => work(),
|
||||
resolveAndPlay: vi.fn(async () => true),
|
||||
emit: vi.fn(),
|
||||
};
|
||||
const db = {
|
||||
getUserMusicPreference: () => null,
|
||||
getUserMusicCookie: () => null,
|
||||
getGrantedMusicAccount: () => ({ cookie: "private-test-cookie", label: "Member's account", accountId: "account" }),
|
||||
} as unknown as BotDatabase;
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => {
|
||||
(req as { user?: unknown }).user = { id: "member", role: "member", bots: new Set(["b"]), capabilities: new Set(["player.control"]) };
|
||||
next();
|
||||
});
|
||||
app.use("/api/player", createPlayerRouter({ getBot: () => bot } as any, { error: vi.fn() } as any,
|
||||
db, undefined, undefined, undefined, { perUserMusicAccounts: true }));
|
||||
|
||||
const response = await request(app).post(`/api/player/b/play-${kind}`)
|
||||
.send({ [`${kind}Id`]: "id", platform: "qq" }).expect(200);
|
||||
|
||||
expect(response.body).toMatchObject({ ok: true });
|
||||
expect(response.text).not.toContain("private-test-cookie");
|
||||
expect(readLibrary).toHaveBeenCalledOnce();
|
||||
expect(personal.getPlayableSongIds).not.toHaveBeenCalled();
|
||||
expect(shared.getPlayableSongIds).toHaveBeenCalledWith(["personal-library-track"]);
|
||||
expect(queue.current()?.id).toBe("personal-library-track");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["playlist", "empty", 200],
|
||||
["playlist", "unavailable", 200],
|
||||
["album", "empty", 200],
|
||||
["album", "error", 500],
|
||||
])("preserves current playback if the %s is %s", async (kind, result, status) => {
|
||||
const queue = new PlayQueue();
|
||||
queue.add(song("playing"));
|
||||
queue.play();
|
||||
const player = { stop: vi.fn(), resetFailures: vi.fn() };
|
||||
const loadSongs = async () => {
|
||||
if (result === "error") throw new Error("Upstream failed");
|
||||
return result === "empty" ? [] : [song("next")];
|
||||
};
|
||||
const bot = {
|
||||
getProviderFor: () => ({
|
||||
platform: "qq",
|
||||
getPlaylistSongs: loadSongs,
|
||||
getAlbumSongs: loadSongs,
|
||||
getPlayableSongIds: async () => new Set<string>(),
|
||||
}),
|
||||
getQueueManager: () => queue,
|
||||
getPlayer: () => player,
|
||||
};
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => { (req as any).user = { role: "admin" }; next(); });
|
||||
app.use("/api/player", createPlayerRouter({ getBot: () => bot } as any, { error: vi.fn() } as any));
|
||||
|
||||
const response = await request(app).post(`/api/player/b/play-${kind}`).send({ [`${kind}Id`]: "id", platform: "qq" });
|
||||
|
||||
expect(response.status).toBe(status);
|
||||
if (status === 200) expect(response.body).toMatchObject({ ok: false });
|
||||
expect(player.stop).not.toHaveBeenCalled();
|
||||
expect(player.resetFailures).not.toHaveBeenCalled();
|
||||
expect(queue.current()?.id).toBe("playing");
|
||||
});
|
||||
});
|
||||
|
||||
describe("play a queue position", () => {
|
||||
function fixture() {
|
||||
const queue = new PlayQueue();
|
||||
queue.add(song("playing"));
|
||||
queue.add(song("unavailable"));
|
||||
queue.play();
|
||||
const player = { stop: vi.fn(), resetFailures: vi.fn(), getPlaybackSessionId: () => 1 };
|
||||
const bot = {
|
||||
getQueueManager: () => queue,
|
||||
getPlayer: () => player,
|
||||
runExclusive: (work: () => Promise<unknown>) => work(),
|
||||
resolveAndPlay: vi.fn(async (_song: Song, onFailure?: (failure: { message: string }) => void) => {
|
||||
onFailure?.({ message: "Source returned no stream" });
|
||||
return false;
|
||||
}),
|
||||
emit: vi.fn(),
|
||||
};
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => { (req as any).user = { role: "admin" }; next(); });
|
||||
app.use("/api/player", createPlayerRouter({ getBot: () => bot } as any, { error: vi.fn() } as any));
|
||||
return { app, bot, player, queue };
|
||||
}
|
||||
|
||||
it("rejects fractional positions without stopping the playing track", async () => {
|
||||
const { app, player, queue } = fixture();
|
||||
expect((await request(app).post("/api/player/b/play-at").send({ index: 0.5 })).status).toBe(400);
|
||||
expect(player.stop).not.toHaveBeenCalled();
|
||||
expect(queue.current()?.id).toBe("playing");
|
||||
});
|
||||
|
||||
it("returns the URL failure and publishes the selected stopped track", async () => {
|
||||
const { app, bot, queue } = fixture();
|
||||
const response = await request(app).post("/api/player/b/play-at").send({ index: 1 });
|
||||
expect(response.body).toEqual({ ok: false, message: expect.stringContaining("Source returned no stream") });
|
||||
expect(bot.emit).toHaveBeenCalledWith("stateChange");
|
||||
expect(queue.current()?.id).toBe("unavailable");
|
||||
});
|
||||
});
|
||||
|
||||
it("reports a failed restart while the existing track is still playing", async () => {
|
||||
const bot = {
|
||||
runExclusive: (work: () => Promise<unknown>) => work(),
|
||||
async playSingleSong(_song: Song, _requester: string, failure: (error: { message: string }, continues: boolean) => void) {
|
||||
failure({ message: "No URL" }, true);
|
||||
return false;
|
||||
},
|
||||
};
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => { (req as any).user = { role: "admin" }; next(); });
|
||||
app.use("/api/player", createPlayerRouter({ getBot: () => bot } as any, { error: vi.fn() } as any));
|
||||
|
||||
const response = await request(app).post("/api/player/b/play-song").send({ song: song("playing") });
|
||||
expect(response.body).toEqual({ ok: false, message: expect.stringContaining("当前曲目继续播放") });
|
||||
});
|
||||
|
||||
it("tries the newly appended track when idle and reports a failed URL lookup", async () => {
|
||||
const queue = new PlayQueue();
|
||||
queue.add(song("already-queued"));
|
||||
const bot = {
|
||||
getQueueManager: () => queue,
|
||||
getPlayer: () => ({ getState: () => "idle", resetFailures: vi.fn() }),
|
||||
runExclusive: (work: () => Promise<unknown>) => work(),
|
||||
resolveAndPlay: vi.fn(async (_track: Song, onFailure?: (failure: { message: string }) => void) => {
|
||||
onFailure?.({ message: "No URL" });
|
||||
return false;
|
||||
}),
|
||||
emit: vi.fn(),
|
||||
};
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => { (req as any).user = { role: "admin" }; next(); });
|
||||
app.use("/api/player", createPlayerRouter({ getBot: () => bot } as any, { error: vi.fn() } as any));
|
||||
|
||||
const response = await request(app).post("/api/player/b/add-song").send({ song: song("newly-added") });
|
||||
expect(bot.resolveAndPlay.mock.calls.map(([track]) => track.id)).toEqual(["newly-added"]);
|
||||
expect(queue.list().map(track => track.id)).toEqual(["already-queued", "newly-added"]);
|
||||
expect(response.body).toEqual({ ok: false, message: expect.stringContaining("No URL") });
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
+294
-166
@@ -1,11 +1,62 @@
|
||||
import { Router } from "express";
|
||||
import { Router, type Request } from "express";
|
||||
import type { BotInstance } from "../../bot/instance.js";
|
||||
import { blocksProviderForAdvance } from "../../bot/url-retry.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 } 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 { 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(
|
||||
fetchPage: (artistId: string, offset?: number, limit?: number) => Promise<ArtistSongPage>,
|
||||
artistId: string
|
||||
): Promise<Song[]> {
|
||||
const songs: Song[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (let offset = 0; offset < MAX_ARTIST_QUEUE; offset += ARTIST_QUEUE_PAGE) {
|
||||
const page = await fetchPage(artistId, offset, ARTIST_QUEUE_PAGE);
|
||||
for (const song of page.songs) {
|
||||
if (!seen.has(song.id)) {
|
||||
seen.add(song.id);
|
||||
songs.push(song);
|
||||
if (songs.length === MAX_ARTIST_QUEUE) return songs;
|
||||
}
|
||||
}
|
||||
if (!page.hasMore || page.songs.length === 0) break;
|
||||
}
|
||||
return songs;
|
||||
}
|
||||
|
||||
async function filterCollectionForRoom(
|
||||
bot: BotInstance,
|
||||
platform: Song["platform"],
|
||||
songs: Song[],
|
||||
): Promise<Song[]> {
|
||||
if (platform !== "qq") return songs;
|
||||
// Metadata can come from the caller's account. Room playback uses the
|
||||
// bot's shared account, so its entitlements must drive the batch check too.
|
||||
const playbackProvider = bot.getProviderFor("qq") as MusicProvider & {
|
||||
getPlayableSongIds?: (ids: string[]) => Promise<Set<string> | null>;
|
||||
};
|
||||
const available = await playbackProvider.getPlayableSongIds?.(songs.map(song => song.id));
|
||||
return available ? songs.filter(song => available.has(song.id)) : songs;
|
||||
}
|
||||
|
||||
export function createPlayerRouter(
|
||||
botManager: BotManager,
|
||||
@@ -14,9 +65,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.
|
||||
@@ -34,6 +115,50 @@ 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, songs: Song[], platform: Song["platform"], requestedBy: string | undefined, totalCount: number,
|
||||
) {
|
||||
return bot.runExclusive(async () => {
|
||||
bot.getPlayer().stop();
|
||||
bot.getPlayer().resetFailures();
|
||||
const queue = bot.getQueueManager();
|
||||
queue.clear();
|
||||
for (const song of songs) {
|
||||
queue.add({ ...song, platform, requestedBy });
|
||||
}
|
||||
bot.cleanupQueuedLocalSongs?.("queue_replaced");
|
||||
|
||||
const mode = queue.getMode();
|
||||
const first: QueuedSong | null = mode === "random" || mode === "rloop"
|
||||
? queue.playAt(Math.floor(Math.random() * queue.size()))
|
||||
: queue.play();
|
||||
// Publish the new idle queue even if the first URL lookup ultimately fails.
|
||||
bot.emit("stateChange");
|
||||
|
||||
let failure: PlayFailure | undefined;
|
||||
const capture = (reason: PlayFailure) => { failure = reason; };
|
||||
let started = first ? await bot.resolveAndPlay(first, capture) : false;
|
||||
if (first && !started && failure && !blocksProviderForAdvance(failure.code) && queue.current() === first) {
|
||||
// Many collections contain several consecutive unavailable tracks.
|
||||
started = await bot.playNext(20, capture);
|
||||
}
|
||||
|
||||
const playing = queue.current();
|
||||
const loaded = songs.length < totalCount
|
||||
? `已加载 ${songs.length}/${totalCount} 首(其余无法播放)`
|
||||
: `已加载 ${songs.length} 首`;
|
||||
const reason = failure?.message;
|
||||
return started && playing
|
||||
? { ok: true, message: `${loaded},正在播放:${playing.name}` }
|
||||
: { ok: false, message: `${loaded},但无法开始播放${reason ? `:${reason}` : "。"}` };
|
||||
});
|
||||
}
|
||||
|
||||
/** Map API platform string to the corresponding command flag. */
|
||||
const platformFlag = (platform: unknown): string => {
|
||||
if (platform === "bilibili") return "-b";
|
||||
@@ -111,7 +236,14 @@ export function createPlayerRouter(
|
||||
|
||||
router.post("/:botId/pause", authorize({ capability: "player.control", guestFlag: "transport" }), simpleCommand("!pause"));
|
||||
router.post("/:botId/resume", authorize({ capability: "player.control", guestFlag: "transport" }), simpleCommand("!resume"));
|
||||
router.post("/:botId/next", authorize({ capability: "player.control", guestFlag: "skip" }), simpleCommand("!next"));
|
||||
router.post("/:botId/next", authorize({ capability: "player.control", guestFlag: "skip" }), async (req, res) => {
|
||||
try {
|
||||
const bot: BotInstance = (req as any).bot;
|
||||
res.json(await bot.skipToNext());
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: musicRequestError(err).message });
|
||||
}
|
||||
});
|
||||
router.post("/:botId/prev", authorize({ capability: "player.control" }), simpleCommand("!prev"));
|
||||
router.post("/:botId/stop", authorize({ capability: "player.control" }), simpleCommand("!stop"));
|
||||
router.post("/:botId/clear", authorize({ capability: "player.queue", guestFlag: "removeClear" }), simpleCommand("!clear"));
|
||||
@@ -124,21 +256,17 @@ 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 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") &&
|
||||
!message.includes("not available") &&
|
||||
!message.includes("not connected"),
|
||||
ok: message.startsWith("Personal FM started") || message.startsWith("QQ Radar FM started"),
|
||||
message,
|
||||
});
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
res.status(500).json({ error: musicRequestError(err).message });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -233,10 +361,10 @@ export function createPlayerRouter(
|
||||
// Jump to a specific index in the queue (without clearing it)
|
||||
router.post("/:botId/play-at", authorize({ capability: "player.control" }), async (req, res) => {
|
||||
try {
|
||||
const bot = (req as any).bot;
|
||||
const bot: BotInstance = (req as any).bot;
|
||||
const { index } = req.body;
|
||||
if (typeof index !== "number" || index < 0) {
|
||||
res.status(400).json({ error: "index is required" });
|
||||
if (!Number.isSafeInteger(index) || index < 0) {
|
||||
res.status(400).json({ error: "index must be a non-negative integer" });
|
||||
return;
|
||||
}
|
||||
// Serialize the index-validation + stop/reset/playAt/resolveAndPlay so a
|
||||
@@ -247,20 +375,23 @@ export function createPlayerRouter(
|
||||
// Validate the index BEFORE stopping current playback — otherwise an
|
||||
// invalid index silently kills the user's current song and leaves the
|
||||
// queue idle.
|
||||
if (index >= queue.size()) {
|
||||
return { status: 400 as const, body: { error: "Invalid queue index" } };
|
||||
}
|
||||
bot.getPlayer().stop();
|
||||
bot.getPlayer().resetFailures();
|
||||
const song = queue.playAt(index);
|
||||
if (!song) {
|
||||
return { status: 400 as const, body: { error: "Invalid queue index" } };
|
||||
}
|
||||
const ok = await bot.resolveAndPlay(song);
|
||||
const player = bot.getPlayer();
|
||||
player.stop(true);
|
||||
player.resetFailures();
|
||||
const session = player.getPlaybackSessionId();
|
||||
bot.emit("stateChange");
|
||||
let reason: string | undefined;
|
||||
const ok = await bot.resolveAndPlay(song, failure => { reason = failure.message; });
|
||||
if (!ok) {
|
||||
return { body: { message: `Cannot play: ${song.name}` } };
|
||||
// Abandon this transition's silence loop, leaving newer playback alone.
|
||||
if (queue.current() === song && player.getPlaybackSessionId() === session) player.stop();
|
||||
return { body: { ok: false, message: whyUnplayable(song, reason) } };
|
||||
}
|
||||
return { body: { message: `Now playing: ${song.name} - ${song.artist}` } };
|
||||
return { body: { ok: true, message: `Now playing: ${song.name} - ${song.artist}` } };
|
||||
});
|
||||
if (result.status) {
|
||||
res.status(result.status).json(result.body);
|
||||
@@ -299,87 +430,26 @@ 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"
|
||||
);
|
||||
|
||||
// Stop current playback
|
||||
bot.getPlayer().stop();
|
||||
bot.getPlayer().resetFailures();
|
||||
const provider = scopedProvider(req, bot, platform);
|
||||
|
||||
const songs = await provider.getPlaylistSongs(playlistId);
|
||||
if (songs.length === 0) {
|
||||
res.json({ message: "Playlist is empty" });
|
||||
res.json({ ok: false, message: "Playlist is empty" });
|
||||
return;
|
||||
}
|
||||
|
||||
// QQ-specific optimization: many users' QQ playlists contain a
|
||||
// large fraction of songs that return result=104003 (region/copyright
|
||||
// restricted). Batch-resolve URLs once and only queue the playable
|
||||
// ones, otherwise the playback retry loop wastes time guessing.
|
||||
let queueable: { id: string }[] = songs;
|
||||
const totalCount = songs.length;
|
||||
const qqLike = provider as { getPlayableSongIds?: (ids: string[]) => Promise<Set<string> | null> };
|
||||
if (typeof qqLike.getPlayableSongIds === "function") {
|
||||
const playable = await qqLike.getPlayableSongIds(songs.map((s: { id: string }) => s.id));
|
||||
if (playable !== null) {
|
||||
// Authoritative answer from upstream — even an empty set means
|
||||
// "we know none are playable", short-circuit immediately rather
|
||||
// than wasting 20+ retries.
|
||||
queueable = songs.filter((s: { id: string }) => playable.has(s.id));
|
||||
}
|
||||
// If null, the batch endpoint itself errored — fall through to
|
||||
// the sequential retry path, which still has a chance.
|
||||
}
|
||||
const queueable = await filterCollectionForRoom(bot, provider.platform, songs);
|
||||
if (queueable.length === 0) {
|
||||
res.json({ ok: false, message: `歌单 ${totalCount} 首歌曲均无版权可播放(区域/版权限制)` });
|
||||
res.json({ ok: false, message: `歌单 ${totalCount} 首歌曲均无法播放` });
|
||||
return;
|
||||
}
|
||||
|
||||
const queue = bot.getQueueManager();
|
||||
queue.clear();
|
||||
for (const song of queueable) {
|
||||
queue.add({ ...song, platform: provider.platform, requestedBy: requesterName(req) });
|
||||
}
|
||||
// Sweep AFTER the queue is rebuilt: the previous queue's local uploads are
|
||||
// released and deleted, but an empty/failed playlist (early return above)
|
||||
// leaves the previous queue — and its files — intact.
|
||||
bot.cleanupQueuedLocalSongs?.("queue_replaced");
|
||||
|
||||
// Use queue.play() for sequential, or pick random index for random modes
|
||||
const mode = queue.getMode();
|
||||
let first;
|
||||
if (mode === "random" || mode === "rloop") {
|
||||
const idx = Math.floor(Math.random() * queue.size());
|
||||
first = queue.playAt(idx);
|
||||
} else {
|
||||
first = queue.play();
|
||||
}
|
||||
|
||||
// If the first picked song can't resolve (e.g., QQ song with no
|
||||
// streaming entitlement → result 104003), fall back to playNext's
|
||||
// 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 playing = queue.current();
|
||||
const loadedMsg = 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(await startCollection(bot, queueable, provider.platform, requesterName(req), totalCount));
|
||||
} 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 });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -392,72 +462,74 @@ export function createPlayerRouter(
|
||||
rejectDisabledLocalAudio(res);
|
||||
return;
|
||||
}
|
||||
const provider = bot.getProviderFor(
|
||||
platform === "bilibili" || platform === "qq" || platform === "youtube" || platform === "local" || platform === "kugou" || platform === "jellyfin"
|
||||
? platform
|
||||
: "netease"
|
||||
);
|
||||
|
||||
// Stop current playback
|
||||
bot.getPlayer().stop();
|
||||
bot.getPlayer().resetFailures();
|
||||
const provider = scopedProvider(req, bot, platform);
|
||||
|
||||
const songs = await provider.getAlbumSongs(albumId);
|
||||
if (songs.length === 0) {
|
||||
res.json({ message: "Album is empty" });
|
||||
res.json({ ok: false, message: "Album is empty" });
|
||||
return;
|
||||
}
|
||||
|
||||
// QQ-specific optimization: batch-resolve playable IDs to avoid
|
||||
// wasting retries on region/copyright-restricted tracks.
|
||||
let queueable: { id: string }[] = songs;
|
||||
const totalCount = songs.length;
|
||||
const qqLike = provider as { getPlayableSongIds?: (ids: string[]) => Promise<Set<string> | null> };
|
||||
if (typeof qqLike.getPlayableSongIds === "function") {
|
||||
const playable = await qqLike.getPlayableSongIds(songs.map((s: { id: string }) => s.id));
|
||||
if (playable !== null) {
|
||||
queueable = songs.filter((s: { id: string }) => playable.has(s.id));
|
||||
}
|
||||
}
|
||||
const queueable = await filterCollectionForRoom(bot, provider.platform, songs);
|
||||
if (queueable.length === 0) {
|
||||
res.json({ ok: false, message: `专辑 ${totalCount} 首歌曲均无版权可播放(区域/版权限制)` });
|
||||
res.json({ ok: false, message: `专辑 ${totalCount} 首歌曲均无法播放` });
|
||||
return;
|
||||
}
|
||||
|
||||
const queue = bot.getQueueManager();
|
||||
queue.clear();
|
||||
for (const song of queueable) {
|
||||
queue.add({ ...song, platform: provider.platform, requestedBy: requesterName(req) });
|
||||
}
|
||||
// Sweep AFTER the queue is rebuilt (see play-playlist).
|
||||
bot.cleanupQueuedLocalSongs?.("queue_replaced");
|
||||
|
||||
const mode = queue.getMode();
|
||||
let first;
|
||||
if (mode === "random" || mode === "rloop") {
|
||||
const idx = Math.floor(Math.random() * queue.size());
|
||||
first = queue.playAt(idx);
|
||||
} else {
|
||||
first = queue.play();
|
||||
}
|
||||
|
||||
let started = first ? await bot.resolveAndPlay(first) : false;
|
||||
if (first && !started) {
|
||||
started = await bot.playNext(20);
|
||||
}
|
||||
|
||||
const playing = queue.current();
|
||||
const loadedMsg = 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(await startCollection(bot, queueable, provider.platform, requesterName(req), totalCount));
|
||||
} 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 });
|
||||
}
|
||||
});
|
||||
|
||||
// Play an artist's songs. An artist page queues the singer's FULL catalogue —
|
||||
// never just the hot 50 — so this pages through getArtistAllSongs when the
|
||||
// source can page a catalogue, and falls back to getArtistSongs (hot songs)
|
||||
// when it cannot.
|
||||
router.post("/:botId/play-artist", authorize({ capability: "player.control", guestFlag: "playCollection" }), async (req, res) => {
|
||||
try {
|
||||
const bot = (req as any).bot;
|
||||
const { artistId, platform } = req.body;
|
||||
if (!artistId) {
|
||||
res.status(400).json({ error: "artistId is required" });
|
||||
return;
|
||||
}
|
||||
if (isLocalAudioDisabled(bot, platform)) {
|
||||
rejectDisabledLocalAudio(res);
|
||||
return;
|
||||
}
|
||||
const provider = scopedProvider(req, bot, platform);
|
||||
if (typeof provider.getArtistSongs !== "function") {
|
||||
res.status(501).json({ error: "Not supported by this provider" });
|
||||
return;
|
||||
}
|
||||
// Whole catalogue when the source can page it (bounded by the collector's
|
||||
// safety cap); otherwise the hot songs are the best it can offer.
|
||||
const fetchPage = provider.getArtistAllSongs?.bind(provider);
|
||||
|
||||
const songs = fetchPage
|
||||
? await collectArtistSongs(fetchPage, artistId)
|
||||
: await provider.getArtistSongs(artistId, 50);
|
||||
if (songs.length === 0) {
|
||||
res.json({ ok: false, message: "该歌手暂无可用歌曲" });
|
||||
return;
|
||||
}
|
||||
|
||||
const totalCount = songs.length;
|
||||
const queueable = await filterCollectionForRoom(bot, provider.platform, songs);
|
||||
if (queueable.length === 0) {
|
||||
res.json({ ok: false, message: `歌手 ${totalCount} 首歌曲均无法播放` });
|
||||
return;
|
||||
}
|
||||
|
||||
res.json(await startCollection(bot, queueable, provider.platform, requesterName(req), totalCount));
|
||||
} catch (err) {
|
||||
const error = musicRequestError(err);
|
||||
logger.error({ err: error }, "play-artist failed");
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -468,7 +540,7 @@ export function createPlayerRouter(
|
||||
// requests can't interleave the queue mutation + playback (#119).
|
||||
router.post("/:botId/play-song", authorize({ capability: "player.control" }), async (req, res) => {
|
||||
try {
|
||||
const bot = (req as any).bot;
|
||||
const bot: BotInstance = (req as any).bot;
|
||||
const { song } = req.body;
|
||||
if (!song || !song.id || !song.platform) {
|
||||
res.status(400).json({ error: "song object with id and platform is required" });
|
||||
@@ -482,10 +554,15 @@ 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 errorMessage = whyUnplayable(song);
|
||||
const ok = await bot.playSingleSong({ ...song }, requesterName(req), (failure, currentTrackContinues) => {
|
||||
errorMessage = currentTrackContinues
|
||||
? `未能重新播放「${song.name || song.id}」,当前曲目继续播放:${failure.message}`
|
||||
: whyUnplayable(song, failure.message);
|
||||
});
|
||||
return ok
|
||||
? { ok: true, message: `正在播放:${song.name || 'Unknown'} - ${song.artist || 'Unknown'}` }
|
||||
: { ok: false, message: `无法播放「${song.name || song.id}」(区域/版权限制)` };
|
||||
: { ok: false, message: errorMessage };
|
||||
});
|
||||
res.json(body);
|
||||
} catch (err) {
|
||||
@@ -525,9 +602,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'}` };
|
||||
}
|
||||
@@ -564,9 +642,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"}` };
|
||||
});
|
||||
@@ -578,7 +657,7 @@ export function createPlayerRouter(
|
||||
|
||||
router.post("/:botId/add-song", authorize({ capability: "player.queue", guestFlag: "addToQueue" }), async (req, res) => {
|
||||
try {
|
||||
const bot = (req as any).bot;
|
||||
const bot: BotInstance = (req as any).bot;
|
||||
const { song } = req.body;
|
||||
if (!song || !song.id || !song.platform) {
|
||||
res.status(400).json({ error: "song object with id and platform is required" });
|
||||
@@ -597,13 +676,18 @@ export function createPlayerRouter(
|
||||
|
||||
// If nothing was playing, start this newly-added song immediately.
|
||||
if (wasIdle) {
|
||||
queue.playAt(queue.size() - 1);
|
||||
const added = queue.playAt(queue.size() - 1)!;
|
||||
bot.getPlayer().resetFailures();
|
||||
await bot.resolveAndPlay(queue.current()!);
|
||||
return { message: `Now playing: ${song.name || 'Unknown'} - ${song.artist || 'Unknown'}` };
|
||||
let reason: string | undefined;
|
||||
const ok = await bot.resolveAndPlay(added, failure => { reason = failure.message; });
|
||||
if (!ok) {
|
||||
bot.emit("stateChange");
|
||||
return { ok: false, message: `已加入队列,但${whyUnplayable(added, reason)}` };
|
||||
}
|
||||
return { ok: true, message: `Now playing: ${song.name || 'Unknown'} - ${song.artist || 'Unknown'}` };
|
||||
}
|
||||
|
||||
return { message: `Added to queue: ${song.name || 'Unknown'} - ${song.artist || 'Unknown'} (position ${queue.size()})` };
|
||||
return { ok: true, message: `Added to queue: ${song.name || 'Unknown'} - ${song.artist || 'Unknown'} (position ${queue.size()})` };
|
||||
});
|
||||
res.json(body);
|
||||
} catch (err) {
|
||||
@@ -620,11 +704,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) {
|
||||
@@ -643,7 +723,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 });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -676,6 +756,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,
|
||||
@@ -689,5 +772,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);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import pino from "pino";
|
||||
import { createDatabase, type BotDatabase } from "../../data/database.js";
|
||||
import { createUserStore, type UserStore } from "../../data/users.js";
|
||||
import { createSessionStore, type SessionStore } from "../../data/sessions.js";
|
||||
import { createApiKeyStore, type ApiKeyStore } from "../../data/api-keys.js";
|
||||
import { createAuditStore } from "../../data/audit.js";
|
||||
import { createPermissionStore } from "../../data/permissions.js";
|
||||
import { getDefaultConfig, type GuestModeConfig } from "../../data/config.js";
|
||||
@@ -13,7 +14,7 @@ import type { GuestPermissions, BotAccess } from "../../data/permissions.js";
|
||||
import { createSessionRouter } from "./session.js";
|
||||
import { SESSION_COOKIE_NAME } from "../auth/validateSession.js";
|
||||
|
||||
function makeApp(botDb: BotDatabase, users: UserStore, sessions: SessionStore) {
|
||||
function makeApp(botDb: BotDatabase, users: UserStore, sessions: SessionStore, apiKeys?: ApiKeyStore) {
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use(cookieParser());
|
||||
@@ -27,7 +28,8 @@ function makeApp(botDb: BotDatabase, users: UserStore, sessions: SessionStore) {
|
||||
audit,
|
||||
pino({ level: "silent" }),
|
||||
permissions,
|
||||
() => getDefaultConfig().guestMode
|
||||
() => getDefaultConfig().guestMode,
|
||||
apiKeys
|
||||
)
|
||||
);
|
||||
return app;
|
||||
@@ -125,6 +127,29 @@ describe("session router", () => {
|
||||
expect(anon.status).toBe(401);
|
||||
});
|
||||
|
||||
it("stores accent preferences per account and returns them to other sessions", async () => {
|
||||
const alice = await users.createUser("alice", "pw-alice", "member");
|
||||
const bob = await users.createUser("bob", "pw-bob", "member");
|
||||
const cookieA = `${SESSION_COOKIE_NAME}=${sessions.createSession(alice.id).token}`;
|
||||
const cookieB = `${SESSION_COOKIE_NAME}=${sessions.createSession(alice.id).token}`;
|
||||
const updated = await request(app).put('/api/session/preferences').set('Cookie', cookieA)
|
||||
.send({ accentColor: '#8B5CF6', userId: bob.id });
|
||||
expect(updated.status).toBe(200);
|
||||
expect(updated.body.accentColor).toBe('#8b5cf6');
|
||||
expect((await request(app).get('/api/session/me').set('Cookie', cookieB)).body.accentColor).toBe('#8b5cf6');
|
||||
expect(users.getAccentColor(bob.id)).toBe('#335eea');
|
||||
});
|
||||
|
||||
it("rejects anonymous and invalid preference updates without altering the account", async () => {
|
||||
const alice = await users.createUser("alice", "pw-alice", "member");
|
||||
const cookie = `${SESSION_COOKIE_NAME}=${sessions.createSession(alice.id).token}`;
|
||||
expect((await request(app).put('/api/session/preferences').send({ accentColor: '#8b5cf6' })).status).toBe(401);
|
||||
for (const accentColor of ['red', '#fff', '#zzzzzz', null, 123]) {
|
||||
expect((await request(app).put('/api/session/preferences').set('Cookie', cookie).send({ accentColor })).status).toBe(400);
|
||||
}
|
||||
expect(users.getAccentColor(alice.id)).toBe('#335eea');
|
||||
});
|
||||
|
||||
it("POST /logout deletes the session and clears the cookie", async () => {
|
||||
await users.createUser("alice", "pw-alice", "admin");
|
||||
const loginRes = await request(app)
|
||||
@@ -176,6 +201,68 @@ describe("session router", () => {
|
||||
}, 20000);
|
||||
});
|
||||
|
||||
describe("session router — API key revocation", () => {
|
||||
let botDb: BotDatabase;
|
||||
let users: UserStore;
|
||||
let sessions: SessionStore;
|
||||
let apiKeys: ApiKeyStore;
|
||||
let app: express.Express;
|
||||
let userId: string;
|
||||
let currentCookie: string;
|
||||
let rawKey: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
botDb = createDatabase(":memory:");
|
||||
users = createUserStore(botDb.db);
|
||||
sessions = createSessionStore(botDb.db);
|
||||
apiKeys = createApiKeyStore(botDb.db);
|
||||
const member = await users.createUser("alice", "old-password", "member");
|
||||
userId = member.id;
|
||||
currentCookie = `${SESSION_COOKIE_NAME}=${sessions.createSession(userId).token}`;
|
||||
rawKey = apiKeys.create(userId, "integration")!.rawKey;
|
||||
app = makeApp(botDb, users, sessions, apiKeys);
|
||||
});
|
||||
|
||||
afterEach(() => botDb.close());
|
||||
|
||||
it("successful password change revokes all owned keys and preserves only the active browser session", async () => {
|
||||
const secondKey = apiKeys.create(userId, "another-integration")!.rawKey;
|
||||
const otherSession = `${SESSION_COOKIE_NAME}=${sessions.createSession(userId).token}`;
|
||||
const otherUser = await users.createUser("bob", "other-password", "member");
|
||||
const otherUserKey = apiKeys.create(otherUser.id, "other-user-integration")!.rawKey;
|
||||
|
||||
const changed = await request(app).post("/api/session/change-password")
|
||||
.set("Cookie", currentCookie)
|
||||
.send({ oldPassword: "old-password", newPassword: "new-password" });
|
||||
expect(changed.status).toBe(204);
|
||||
expect(apiKeys.validateAndTouch(rawKey)).toBeNull();
|
||||
expect(apiKeys.validateAndTouch(secondKey)).toBeNull();
|
||||
expect(apiKeys.listForUser(userId)).toEqual([]);
|
||||
expect(apiKeys.validateAndTouch(otherUserKey)?.userId).toBe(otherUser.id);
|
||||
expect((await request(app).get("/api/session/me").set("Cookie", currentCookie)).status).toBe(200);
|
||||
expect((await request(app).get("/api/session/me").set("Cookie", otherSession)).status).toBe(401);
|
||||
}, 20_000);
|
||||
|
||||
it.each([
|
||||
{ oldPassword: "wrong-password", newPassword: "new-password", status: 401 },
|
||||
{ oldPassword: "old-password", newPassword: "short", status: 400 },
|
||||
])("failed password change ($status) leaves API keys valid", async ({ oldPassword, newPassword, status }) => {
|
||||
const changed = await request(app).post("/api/session/change-password")
|
||||
.set("Cookie", currentCookie)
|
||||
.send({ oldPassword, newPassword });
|
||||
expect(changed.status).toBe(status);
|
||||
expect(apiKeys.validateAndTouch(rawKey)?.userId).toBe(userId);
|
||||
expect((await request(app).get("/api/session/me").set("Cookie", currentCookie)).status).toBe(200);
|
||||
});
|
||||
|
||||
it("unauthenticated password change leaves API keys valid", async () => {
|
||||
const changed = await request(app).post("/api/session/change-password")
|
||||
.send({ oldPassword: "old-password", newPassword: "new-password" });
|
||||
expect(changed.status).toBe(401);
|
||||
expect(apiKeys.validateAndTouch(rawKey)?.userId).toBe(userId);
|
||||
});
|
||||
});
|
||||
|
||||
describe("session router — guest mode", () => {
|
||||
let botDb: BotDatabase;
|
||||
|
||||
@@ -236,6 +323,8 @@ describe("session router — guest mode", () => {
|
||||
expect(me.body.guest.addToQueue).toBe(true);
|
||||
expect(me.body.guest.playNext).toBe(true);
|
||||
expect(me.body.capabilities).toEqual([]);
|
||||
expect(me.body.accentColor).toBeNull();
|
||||
expect((await request(app).put('/api/session/preferences').set('Cookie', cookie).send({ accentColor: '#8b5cf6' })).status).toBe(403);
|
||||
});
|
||||
|
||||
it("GET /needs-setup exposes guestAllowed", async () => {
|
||||
|
||||
+22
-1
@@ -3,6 +3,7 @@ import type { Request, Response, NextFunction } from "express";
|
||||
import type { Logger } from "../../logger.js";
|
||||
import type { UserStore } from "../../data/users.js";
|
||||
import type { SessionStore } from "../../data/sessions.js";
|
||||
import type { ApiKeyStore } from "../../data/api-keys.js";
|
||||
import type { AuditStore } from "../../data/audit.js";
|
||||
import { resolvePermissionContext, type PermissionStore } from "../../data/permissions.js";
|
||||
import { SESSION_TTL_MS, GUEST_SESSION_TTL_MS } from "../../data/sessions.js";
|
||||
@@ -54,7 +55,8 @@ export function createSessionRouter(
|
||||
audit: AuditStore,
|
||||
logger: Logger,
|
||||
permissions: PermissionStore,
|
||||
getGuestConfig: () => GuestModeConfig
|
||||
getGuestConfig: () => GuestModeConfig,
|
||||
apiKeys?: ApiKeyStore
|
||||
): Router {
|
||||
const router = Router();
|
||||
|
||||
@@ -180,9 +182,27 @@ export function createSessionRouter(
|
||||
capabilities: [...ctx.capabilities],
|
||||
bots: ctx.bots === "all" ? "all" : [...ctx.bots],
|
||||
guest: ctx.guest ?? null,
|
||||
accentColor: user.role === "guest" ? null : users.getAccentColor(user.id),
|
||||
});
|
||||
});
|
||||
|
||||
router.put("/preferences", requireAuthInline, (req, res) => {
|
||||
if (req.user!.role === "guest") {
|
||||
res.status(403).json({ error: "guests store appearance preferences locally" });
|
||||
return;
|
||||
}
|
||||
const color = req.body?.accentColor;
|
||||
if (typeof color !== "string" || !/^#[0-9a-fA-F]{6}$/.test(color)) {
|
||||
res.status(400).json({ error: "invalid accent color" });
|
||||
return;
|
||||
}
|
||||
if (!users.setAccentColor(req.user!.id, color.toLowerCase())) {
|
||||
res.status(404).json({ error: "user not found" });
|
||||
return;
|
||||
}
|
||||
res.json({ accentColor: color.toLowerCase() });
|
||||
});
|
||||
|
||||
router.post("/change-password", requireAuthInline, async (req, res) => {
|
||||
const { oldPassword, newPassword } = req.body ?? {};
|
||||
if (typeof oldPassword !== "string") {
|
||||
@@ -202,6 +222,7 @@ export function createSessionRouter(
|
||||
await users.changePassword(u.id, newPassword);
|
||||
const currentToken = parseTokenFromCookie(req.headers.cookie);
|
||||
sessions.deleteAllForUser(u.id, currentToken ?? undefined);
|
||||
apiKeys?.deleteAllForUser(u.id);
|
||||
try {
|
||||
audit.record({
|
||||
actorId: u.id, actorUsername: u.username,
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { Logger } from "../../logger.js";
|
||||
import type { UserStore } from "../../data/users.js";
|
||||
import { UsernameTakenError, GUEST_USER_ID } from "../../data/users.js";
|
||||
import type { SessionStore } from "../../data/sessions.js";
|
||||
import type { ApiKeyStore } from "../../data/api-keys.js";
|
||||
import type { AuditStore } from "../../data/audit.js";
|
||||
import { isCapability, BASIC_TIER_CAPABILITIES, type PermissionStore } from "../../data/permissions.js";
|
||||
import { extractSessionToken } from "../auth/validateSession.js";
|
||||
@@ -20,7 +21,8 @@ export function createUsersRouter(
|
||||
sessions: SessionStore,
|
||||
audit: AuditStore,
|
||||
logger: Logger,
|
||||
permissions: PermissionStore
|
||||
permissions: PermissionStore,
|
||||
apiKeys?: ApiKeyStore
|
||||
): Router {
|
||||
const router = Router();
|
||||
|
||||
@@ -85,6 +87,7 @@ export function createUsersRouter(
|
||||
}
|
||||
// FK CASCADE removes sessions; explicit call is belt-and-suspenders
|
||||
sessions.deleteAllForUser(targetId);
|
||||
apiKeys?.deleteAllForUser(targetId);
|
||||
try {
|
||||
audit.record({
|
||||
actorId: req.user!.id, actorUsername: req.user!.username,
|
||||
@@ -117,6 +120,9 @@ export function createUsersRouter(
|
||||
? (extractSessionToken(req.headers.cookie) ?? undefined)
|
||||
: undefined;
|
||||
sessions.deleteAllForUser(targetId, exceptToken);
|
||||
// A password reset must also kill the target's API keys — they are
|
||||
// long-lived credentials that otherwise survive credential rotation.
|
||||
apiKeys?.deleteAllForUser(targetId);
|
||||
try {
|
||||
audit.record({
|
||||
actorId: req.user!.id, actorUsername: req.user!.username,
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { Request } from "express";
|
||||
import { SESSION_COOKIE_NAME } from "./validateSession.js";
|
||||
|
||||
/**
|
||||
* Extract a raw API key from the `X-API-Key` header or an
|
||||
* `Authorization: Bearer <key>` header. Returns null when neither is present.
|
||||
*/
|
||||
export function extractApiKey(req: Request): string | null {
|
||||
const header = req.headers["x-api-key"];
|
||||
if (typeof header === "string" && header.trim()) {
|
||||
return header.trim();
|
||||
}
|
||||
const auth = req.headers.authorization;
|
||||
if (typeof auth === "string") {
|
||||
const match = /^bearer\s+(.+)$/i.exec(auth);
|
||||
if (match) {
|
||||
const key = match[1].trim();
|
||||
if (key) return key;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function hasApiKeyCredential(req: Request): boolean {
|
||||
return extractApiKey(req) !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* API-key clients (no session cookie) skip the origin check entirely. Requests
|
||||
* that ALSO carry the session cookie must NOT rely on this — an attacker page
|
||||
* can set arbitrary headers while the victim's cookie rides along ambiently,
|
||||
* so the cookie keeps the request under the origin check.
|
||||
*/
|
||||
export function isApiKeyOnlyRequest(req: Request): boolean {
|
||||
return hasApiKeyCredential(req) && !req.headers.cookie?.includes(`${SESSION_COOKIE_NAME}=`);
|
||||
}
|
||||
@@ -70,4 +70,28 @@ describe("csrfOriginCheck middleware", () => {
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body).toEqual({ error: "bad origin" });
|
||||
});
|
||||
|
||||
// API-key clients authenticate via a header the browser never attaches
|
||||
// automatically, so CSRF cannot abuse them — the origin check is skipped.
|
||||
it("allows POST with an X-API-Key header and no session cookie", async () => {
|
||||
const res = await request(app).post("/").set("X-API-Key", "tsmb_abc");
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
it("allows POST with an Authorization: Bearer key and no session cookie", async () => {
|
||||
const res = await request(app).post("/").set("Authorization", "Bearer tsmb_abc");
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
it("does NOT skip the origin check when a session cookie rides along with an API key", async () => {
|
||||
// An attacker page can set arbitrary headers while the victim's cookie is
|
||||
// attached ambiently — the cookie keeps the request under the gate.
|
||||
const res = await request(app)
|
||||
.post("/")
|
||||
.set("Host", "example.com")
|
||||
.set("Origin", "https://evil.com")
|
||||
.set("Cookie", "tsmb_session=whatever")
|
||||
.set("X-API-Key", "tsmb_abc");
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { Request, Response, NextFunction } from "express";
|
||||
import { isApiKeyOnlyRequest } from "../auth/api-key-header.js";
|
||||
|
||||
const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
|
||||
|
||||
@@ -10,7 +11,7 @@ const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
|
||||
* this header check covers the remaining attack surface.
|
||||
*/
|
||||
export function csrfOriginCheck(req: Request, res: Response, next: NextFunction): void {
|
||||
if (SAFE_METHODS.has(req.method)) {
|
||||
if (SAFE_METHODS.has(req.method) || isApiKeyOnlyRequest(req)) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import request from "supertest";
|
||||
import { createDatabase, type BotDatabase } from "../../data/database.js";
|
||||
import { createUserStore } from "../../data/users.js";
|
||||
import { createSessionStore } from "../../data/sessions.js";
|
||||
import { createApiKeyStore } from "../../data/api-keys.js";
|
||||
import { createPermissionStore } from "../../data/permissions.js";
|
||||
import { createRequireAuth } from "./requireAuth.js";
|
||||
import { SESSION_COOKIE_NAME } from "../auth/validateSession.js";
|
||||
@@ -114,3 +115,112 @@ describe("requireAuth middleware", () => {
|
||||
expect(req.user.bots instanceof Set && req.user.bots.has("bot1")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("requireAuth middleware with API keys", () => {
|
||||
let botDb: BotDatabase;
|
||||
let app: express.Express;
|
||||
let adminKey: string;
|
||||
let memberKey: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
botDb = createDatabase(":memory:");
|
||||
const users = createUserStore(botDb.db);
|
||||
const sessions = createSessionStore(botDb.db);
|
||||
const permissions = createPermissionStore(botDb.db);
|
||||
const apiKeys = createApiKeyStore(botDb.db);
|
||||
const admin = await users.createUser("alice", "pw-alice", "admin");
|
||||
const member = await users.createUser("bob", "pw-bob", "member");
|
||||
permissions.setPermissions(member.id, { capabilities: ["player.control"], bots: ["bot1"] });
|
||||
adminKey = apiKeys.create(admin.id, "ci")!.rawKey;
|
||||
memberKey = apiKeys.create(member.id, "deploy")!.rawKey;
|
||||
|
||||
app = express();
|
||||
app.use(cookieParser());
|
||||
app.use(
|
||||
createRequireAuth(sessions, permissions, () => ({
|
||||
enabled: false,
|
||||
bots: "all",
|
||||
permissions: {} as any,
|
||||
}), apiKeys)
|
||||
);
|
||||
app.get("/protected", (req, res) => {
|
||||
const u: any = (req as any).user;
|
||||
res.json({
|
||||
ok: true,
|
||||
authMethod: (req as any).authMethod,
|
||||
user: u
|
||||
? {
|
||||
username: u.username,
|
||||
role: u.role,
|
||||
capabilities: u.capabilities ? [...u.capabilities] : [],
|
||||
bots: u.bots === "all" ? "all" : [...(u.bots ?? [])],
|
||||
}
|
||||
: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
botDb.close();
|
||||
});
|
||||
|
||||
it("authenticates a valid X-API-Key header and attaches the owner user", async () => {
|
||||
const res = await request(app).get("/protected").set("X-API-Key", adminKey);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.ok).toBe(true);
|
||||
expect(res.body.user.username).toBe("alice");
|
||||
expect(res.body.user.role).toBe("admin");
|
||||
expect(res.body.authMethod).toBe("api-key");
|
||||
});
|
||||
|
||||
it("authenticates an Authorization: Bearer key", async () => {
|
||||
const res = await request(app).get("/protected").set("Authorization", `Bearer ${adminKey}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.user.username).toBe("alice");
|
||||
});
|
||||
|
||||
it("rejects an unknown key with 401", async () => {
|
||||
const res = await request(app).get("/protected").set("X-API-Key", "tsmb_bogus");
|
||||
expect(res.status).toBe(401);
|
||||
expect(res.body).toEqual({ error: "invalid api key" });
|
||||
});
|
||||
|
||||
it("ignores the session cookie when a key header is present", async () => {
|
||||
// Garbage cookie + valid key → key wins.
|
||||
const res = await request(app)
|
||||
.get("/protected")
|
||||
.set("Cookie", `${SESSION_COOKIE_NAME}=garbage`)
|
||||
.set("X-API-Key", memberKey);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.user.username).toBe("bob");
|
||||
});
|
||||
|
||||
it("a member key inherits the member's capabilities and bot scope", async () => {
|
||||
const res = await request(app).get("/protected").set("X-API-Key", memberKey);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.user.role).toBe("member");
|
||||
expect(res.body.user.capabilities).toContain("player.control");
|
||||
expect(res.body.user.bots).toContain("bot1");
|
||||
expect(res.body.user.capabilities).not.toContain("bot.manage");
|
||||
});
|
||||
|
||||
it("returns 401 when a key header is present but no store is wired", async () => {
|
||||
const sessions: any = { validateAndTouch: () => null };
|
||||
const permissions: any = { getCapabilities: () => [], getBotAccess: () => [] };
|
||||
const mw = createRequireAuth(sessions, permissions, () => ({ enabled: false, bots: "all", permissions: {} as any }));
|
||||
const req: any = { headers: { "x-api-key": "tsmb_x" } };
|
||||
const res: any = { status(c: number) { this.statusCode = c; return this; }, json() { return this; } };
|
||||
const next = vi.fn();
|
||||
mw(req, res, next);
|
||||
expect(res.statusCode).toBe(401);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("a key whose owner was deleted stops working", async () => {
|
||||
const users = createUserStore(botDb.db);
|
||||
const member = users.findByUsername("bob")!;
|
||||
users.deleteUser(member.id);
|
||||
const res = await request(app).get("/protected").set("X-API-Key", memberKey);
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Request, Response, NextFunction, RequestHandler } from "express";
|
||||
import type { SessionStore } from "../../data/sessions.js";
|
||||
import { SESSION_TTL_MS } from "../../data/sessions.js";
|
||||
import type { ApiKeyStore } from "../../data/api-keys.js";
|
||||
import { resolvePermissionContext, type PermissionStore, type GuestPermissions } from "../../data/permissions.js";
|
||||
import type { GuestModeConfig } from "../../data/config.js";
|
||||
import {
|
||||
@@ -8,6 +9,7 @@ import {
|
||||
extractSessionToken,
|
||||
SESSION_COOKIE_NAME,
|
||||
} from "../auth/validateSession.js";
|
||||
import { extractApiKey } from "../auth/api-key-header.js";
|
||||
|
||||
declare module "express-serve-static-core" {
|
||||
interface Request {
|
||||
@@ -19,15 +21,42 @@ declare module "express-serve-static-core" {
|
||||
bots?: "all" | Set<string>;
|
||||
guest?: GuestPermissions;
|
||||
};
|
||||
/** How this request authenticated: browser session cookie or API key. */
|
||||
authMethod?: "session" | "api-key";
|
||||
}
|
||||
}
|
||||
|
||||
export function createRequireAuth(
|
||||
sessions: SessionStore,
|
||||
permissions: PermissionStore,
|
||||
getGuestConfig: () => GuestModeConfig
|
||||
getGuestConfig: () => GuestModeConfig,
|
||||
apiKeys?: ApiKeyStore
|
||||
): RequestHandler {
|
||||
return function requireAuth(req: Request, res: Response, next: NextFunction) {
|
||||
// ─── API-key path ──────────────────────────────────────────────────────
|
||||
// A key in a header authenticates on its own; cookies are ignored on this
|
||||
// path so the two credential types can never be mixed.
|
||||
const rawKey = extractApiKey(req);
|
||||
if (rawKey !== null) {
|
||||
const validation = apiKeys?.validateAndTouch(rawKey) ?? null;
|
||||
if (!validation) {
|
||||
res.status(401).json({ error: "invalid api key" });
|
||||
return;
|
||||
}
|
||||
const ctx = resolvePermissionContext(validation.role, validation.userId, permissions);
|
||||
req.user = {
|
||||
id: validation.userId,
|
||||
username: validation.username,
|
||||
role: validation.role,
|
||||
capabilities: ctx.capabilities,
|
||||
bots: ctx.bots,
|
||||
};
|
||||
req.authMethod = "api-key";
|
||||
next();
|
||||
return;
|
||||
}
|
||||
|
||||
// ─── Session-cookie path (browser) ─────────────────────────────────────
|
||||
const result = validateSessionFromHeaders(req.headers.cookie, sessions);
|
||||
if (!result) {
|
||||
res.clearCookie(SESSION_COOKIE_NAME, { path: "/" });
|
||||
@@ -56,6 +85,7 @@ export function createRequireAuth(
|
||||
bots: ctx.bots,
|
||||
guest: ctx.guest,
|
||||
};
|
||||
req.authMethod = "session";
|
||||
const token = extractSessionToken(req.headers.cookie);
|
||||
if (token) {
|
||||
res.cookie(SESSION_COOKIE_NAME, token, {
|
||||
|
||||
+53
-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";
|
||||
@@ -19,8 +20,11 @@ import { createUsersRouter } from "./api/users.js";
|
||||
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";
|
||||
import type { SpotifyOAuth } from "../music/spotify/spotify-oauth.js";
|
||||
import type { SpotifyProvider } from "../music/spotify/provider.js";
|
||||
import type { JellyfinProvider } from "../music/jellyfin.js";
|
||||
@@ -32,6 +36,7 @@ import {
|
||||
import { setupWebSocket } from "./websocket.js";
|
||||
import { createUserStore } from "../data/users.js";
|
||||
import { createSessionStore } from "../data/sessions.js";
|
||||
import { createApiKeyStore } from "../data/api-keys.js";
|
||||
import { createPermissionStore } from "../data/permissions.js";
|
||||
import { createRequireAuth } from "./middleware/requireAuth.js";
|
||||
import { requireAdmin } from "./middleware/requireAdmin.js";
|
||||
@@ -101,6 +106,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
const sessions = createSessionStore(options.database.db);
|
||||
const audit = createAuditStore(options.database.db);
|
||||
const permissions = createPermissionStore(options.database.db);
|
||||
const apiKeys = createApiKeyStore(options.database.db);
|
||||
|
||||
// ─── Public routes (no auth, no CSRF) ───────────────────────────────────
|
||||
// Disallow every crawler (issue #128). Declared before the static SPA
|
||||
@@ -111,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) => {
|
||||
@@ -127,10 +133,10 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
app.use("/api/session/login", loginLimit);
|
||||
app.use("/api/session/setup", setupLimit);
|
||||
|
||||
app.use("/api/session", createSessionRouter(users, sessions, audit, logger, permissions, () => options.config.guestMode));
|
||||
app.use("/api/session", createSessionRouter(users, sessions, audit, logger, permissions, () => options.config.guestMode, apiKeys));
|
||||
|
||||
// ─── Gates for everything else under /api ───────────────────────────────
|
||||
const requireAuth = createRequireAuth(sessions, permissions, () => options.config.guestMode);
|
||||
const requireAuth = createRequireAuth(sessions, permissions, () => options.config.guestMode, apiKeys);
|
||||
app.use("/api", csrfOriginCheck);
|
||||
app.use("/api", requireAuth);
|
||||
|
||||
@@ -166,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(
|
||||
@@ -203,6 +210,42 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
);
|
||||
}
|
||||
app.use("/api/favorites", requireNotGuest, createFavoritesRouter(options.database, logger));
|
||||
// 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,
|
||||
{
|
||||
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.
|
||||
app.use(
|
||||
@@ -217,9 +260,13 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
);
|
||||
|
||||
// admin-only routes
|
||||
app.use("/api/users", requireAdmin, createUsersRouter(users, sessions, audit, logger, permissions));
|
||||
app.use("/api/users", requireAdmin, createUsersRouter(users, sessions, audit, logger, permissions, apiKeys));
|
||||
app.use("/api/audit", requireAdmin, createAuditRouter(audit));
|
||||
|
||||
// API-key management — interactive sessions only (guests excluded; the
|
||||
// router itself rejects key-authenticated requests).
|
||||
app.use("/api/keys", requireNotGuest, createApiKeysRouter(apiKeys, audit, logger));
|
||||
|
||||
// ─── Static SPA (public) ────────────────────────────────────────────────
|
||||
if (options.staticDir) {
|
||||
app.use(express.static(options.staticDir));
|
||||
|
||||
+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,9 @@
|
||||
import { configDefaults, defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
// TypeScript compiles test files into dist. Test the source once, even
|
||||
// when an older build is present, rather than collecting stale copies.
|
||||
exclude: [...configDefaults.exclude, "dist/**", "web/dist/**"],
|
||||
},
|
||||
});
|
||||
+2
-2
@@ -35,8 +35,8 @@
|
||||
full square. Android reads the manifest instead. -->
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
|
||||
<link rel="manifest" href="/site.webmanifest">
|
||||
<!-- Matches --bg-primary of the dark theme, which is what the app starts in
|
||||
(stores/player.ts defaults to 'dark' and never follows the OS scheme). -->
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<!-- Updated at startup and whenever the resolved appearance changes. -->
|
||||
<meta name="theme-color" content="#222222">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link href="https://fonts.googleapis.com/css2?family=Barlow:wght@400;500;600;700;800&display=swap" rel="stylesheet">
|
||||
|
||||
+12
-3
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<div class="app" :data-theme="theme">
|
||||
<div class="app" :data-theme="theme" :style="accentStyle">
|
||||
<Navbar />
|
||||
<main class="main-content">
|
||||
<RouterView />
|
||||
@@ -7,6 +7,7 @@
|
||||
<Player />
|
||||
<Toast />
|
||||
<Queue class="mobile-queue" :open="mobileQueueOpen" @close="mobileQueueOpen = false" />
|
||||
<BilibiliPartModal />
|
||||
|
||||
<!-- Mobile mini player -->
|
||||
<div v-if="currentSong" class="m-player" @click="onPlayerRowClick">
|
||||
@@ -81,7 +82,7 @@
|
||||
<Icon icon="mdi:music-box-multiple" class="tab-icon" />
|
||||
<span class="tab-label">音乐库</span>
|
||||
</RouterLink>
|
||||
<RouterLink v-if="!session.isGuest.value" to="/settings" class="m-tab" :class="{ active: route.path.startsWith('/settings') }">
|
||||
<RouterLink to="/settings" class="m-tab" :class="{ active: route.path.startsWith('/settings') }">
|
||||
<Icon icon="mdi:cog" class="tab-icon" />
|
||||
<span class="tab-label">设置</span>
|
||||
</RouterLink>
|
||||
@@ -97,11 +98,13 @@ import { usePlayerStore } from './stores/player.js';
|
||||
import { useDecoupledSlider } from './composables/useDecoupledSlider.js';
|
||||
import { useWebSocket } from './composables/useWebSocket.js';
|
||||
import { useSession } from './composables/useSession.js';
|
||||
import { accentTokens } from './styles/accent.js';
|
||||
import Navbar from './components/Navbar.vue';
|
||||
import Player from './components/Player.vue';
|
||||
import CoverArt from './components/CoverArt.vue';
|
||||
import Toast from './components/Toast.vue';
|
||||
import Queue from './components/Queue.vue';
|
||||
import BilibiliPartModal from './components/BilibiliPartModal.vue';
|
||||
|
||||
const playerStore = usePlayerStore();
|
||||
const session = useSession();
|
||||
@@ -111,6 +114,10 @@ const canTransport = computed(() => can('player.control') || guestCan('transport
|
||||
const canSkip = computed(() => can('player.control') || guestCan('skip'));
|
||||
const canModeCtl = computed(() => can('player.control') || guestCan('playMode'));
|
||||
const theme = computed(() => playerStore.theme);
|
||||
const accentStyle = computed(() => accentTokens(playerStore.accentColor));
|
||||
watch(() => `${session.currentUser.value?.id ?? ''}:${session.currentUser.value?.accentColor ?? ''}`, () => {
|
||||
playerStore.loadAccentColor(session.currentUser.value?.accentColor);
|
||||
}, { immediate: true });
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const { connect } = useWebSocket();
|
||||
@@ -329,8 +336,9 @@ function cycleMobileMode() {
|
||||
playerStore.setMode(nextMode);
|
||||
}
|
||||
|
||||
let stopThemeSync: (() => void) | undefined;
|
||||
onMounted(async () => {
|
||||
playerStore.loadTheme();
|
||||
stopThemeSync = playerStore.loadTheme();
|
||||
connect();
|
||||
// Hydrate favorites once per session so deep-links / hard refreshes onto
|
||||
// Search or Playlist render hearts correctly without first visiting Home.
|
||||
@@ -353,6 +361,7 @@ onMounted(async () => {
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
stopThemeSync?.();
|
||||
if (syncTimer) clearInterval(syncTimer);
|
||||
if (mobileRaf !== null) cancelAnimationFrame(mobileRaf);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
<template>
|
||||
<div class="rgb-picker">
|
||||
<button ref="trigger" type="button" class="picker-trigger" :aria-expanded="open" aria-controls="accent-rgb-panel" @click="toggle"><span class="trigger-swatch" :style="{ background: modelValue }" />自定义颜色<Icon :icon="open ? 'mdi:chevron-up' : 'mdi:chevron-down'" /></button>
|
||||
<Teleport to="body">
|
||||
<div v-if="open" class="picker-dismiss" @pointerdown="close" />
|
||||
<section v-if="open" id="accent-rgb-panel" ref="panel" class="picker-panel" :data-theme="theme" :style="[position, accentTokens(modelValue)]" role="dialog" aria-label="自定义颜色" @keydown.esc.stop.prevent="close">
|
||||
<header>自定义颜色<button type="button" aria-label="关闭调色板" @click="close"><Icon icon="mdi:close" /></button></header>
|
||||
<div ref="palette" class="color-palette" :style="{ backgroundColor: `hsl(${hue}, 100%, 50%)` }" tabindex="0" role="slider" aria-label="饱和度与明度" aria-valuemin="0" aria-valuemax="100" :aria-valuenow="Math.round(saturation * 100)" :aria-valuetext="`饱和度 ${Math.round(saturation * 100)}%,明度 ${Math.round(value * 100)}%`" @pointerdown="startPalette" @pointermove="movePalette" @pointerup="endPalette" @pointercancel="endPalette" @keydown="paletteKey"><span class="palette-cursor" :style="{ left: `${saturation * 100}%`, top: `${(1 - value) * 100}%`, background: modelValue }" /></div>
|
||||
<div class="hue-row"><span class="preview-swatch" :style="{ background: modelValue }" /><input class="hue-strip" type="range" min="0" max="360" :value="hue" aria-label="色相" @input="changeHue" /></div>
|
||||
<div class="rgb-values"><label v-for="(channel, index) in channels" :key="channel.key"><span>{{ channel.key }}</span><input type="number" min="0" max="255" step="1" :value="rgb[index]" :aria-label="`${channel.name}通道色值`" @change="updateChannel(index, $event)" @blur="updateChannel(index, $event)" @keydown.enter.prevent="updateChannel(index, $event)" /></label></div>
|
||||
<p>在色板上选取颜色,或输入 RGB 色值</p>
|
||||
</section>
|
||||
</Teleport>
|
||||
</div>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { Icon } from '@iconify/vue';
|
||||
import { accentTokens } from '../styles/accent';
|
||||
const props = defineProps<{ modelValue: string }>();
|
||||
const emit = defineEmits<{ 'update:modelValue': [color: string] }>();
|
||||
const open = ref(false);
|
||||
const theme = ref('dark');
|
||||
const trigger = ref<HTMLButtonElement>();
|
||||
const panel = ref<HTMLElement>();
|
||||
const palette = ref<HTMLElement>();
|
||||
const position = ref({ left: '0px', top: '0px' });
|
||||
const hue = ref(0), saturation = ref(0), value = ref(0);
|
||||
let dragging: number | null = null;
|
||||
const channels = [{ key: 'R', name: '红色' }, { key: 'G', name: '绿色' }, { key: 'B', name: '蓝色' }];
|
||||
const rgb = computed(() => [1, 3, 5].map(offset => parseInt(props.modelValue.slice(offset, offset + 2), 16)));
|
||||
watch(rgb, ([red, green, blue]) => {
|
||||
const [r, g, b] = [red / 255, green / 255, blue / 255];
|
||||
const max = Math.max(r, g, b), min = Math.min(r, g, b), delta = max - min;
|
||||
value.value = max; saturation.value = max ? delta / max : 0;
|
||||
if (delta) hue.value = ((max === r ? (g - b) / delta : max === g ? (b - r) / delta + 2 : (r - g) / delta + 4) * 60 + 360) % 360;
|
||||
}, { immediate: true });
|
||||
function emitRgb(next: number[]) { emit('update:modelValue', '#' + next.map(channel => Math.round(channel).toString(16).padStart(2, '0')).join('')); }
|
||||
function emitHsv() {
|
||||
const h = hue.value / 60, c = value.value * saturation.value, x = c * (1 - Math.abs(h % 2 - 1)), m = value.value - c;
|
||||
const components = [[c,x,0],[x,c,0],[0,c,x],[0,x,c],[x,0,c],[c,0,x]][Math.floor(h) % 6];
|
||||
emitRgb(components.map(component => (component + m) * 255));
|
||||
}
|
||||
function locate() {
|
||||
if (!trigger.value || !panel.value) return;
|
||||
const rect = trigger.value.getBoundingClientRect(), width = panel.value.offsetWidth, height = panel.value.offsetHeight;
|
||||
position.value = { left: `${Math.max(12, Math.min(rect.left, window.innerWidth - width - 12))}px`, top: `${rect.bottom + 8 + height <= window.innerHeight - 12 ? rect.bottom + 8 : Math.max(12, rect.top - height - 8)}px` };
|
||||
}
|
||||
async function toggle() {
|
||||
if (open.value) return close();
|
||||
theme.value = trigger.value?.closest('[data-theme]')?.getAttribute('data-theme') || 'dark';
|
||||
open.value = true; await nextTick(); locate(); palette.value?.focus({ preventScroll: true });
|
||||
window.addEventListener('resize', locate); window.addEventListener('scroll', locate, true); document.addEventListener('keydown', escape);
|
||||
}
|
||||
function removeListeners() { window.removeEventListener('resize', locate); window.removeEventListener('scroll', locate, true); document.removeEventListener('keydown', escape); }
|
||||
function close() { open.value = false; dragging = null; removeListeners(); trigger.value?.focus({ preventScroll: true }); }
|
||||
function escape(event: KeyboardEvent) { if (event.key === 'Escape') close(); }
|
||||
onBeforeUnmount(removeListeners);
|
||||
function selectPalette(event: PointerEvent) {
|
||||
const rect = palette.value!.getBoundingClientRect();
|
||||
saturation.value = Math.max(0, Math.min(1, (event.clientX - rect.left) / rect.width));
|
||||
value.value = 1 - Math.max(0, Math.min(1, (event.clientY - rect.top) / rect.height)); emitHsv();
|
||||
}
|
||||
function startPalette(event: PointerEvent) { if (event.button !== 0) return; dragging = event.pointerId; palette.value?.setPointerCapture(event.pointerId); palette.value?.focus({ preventScroll: true }); selectPalette(event); }
|
||||
function movePalette(event: PointerEvent) { if (dragging === event.pointerId) selectPalette(event); }
|
||||
function endPalette(event: PointerEvent) { if (dragging !== event.pointerId) return; if (palette.value?.hasPointerCapture(event.pointerId)) palette.value.releasePointerCapture(event.pointerId); dragging = null; }
|
||||
function paletteKey(event: KeyboardEvent) {
|
||||
if (!['ArrowLeft','ArrowRight','ArrowUp','ArrowDown'].includes(event.key)) return;
|
||||
event.preventDefault(); const step = event.shiftKey ? .1 : .01;
|
||||
saturation.value = Math.max(0, Math.min(1, saturation.value + (event.key === 'ArrowRight' ? step : event.key === 'ArrowLeft' ? -step : 0)));
|
||||
value.value = Math.max(0, Math.min(1, value.value + (event.key === 'ArrowUp' ? step : event.key === 'ArrowDown' ? -step : 0))); emitHsv();
|
||||
}
|
||||
function changeHue(event: Event) { hue.value = Number((event.target as HTMLInputElement).value); emitHsv(); }
|
||||
function updateChannel(index: number, event: Event) {
|
||||
const input = event.target as HTMLInputElement;
|
||||
if (!input.value.trim() || !Number.isFinite(Number(input.value))) { input.value = String(rgb.value[index]); return; }
|
||||
const next = [...rgb.value]; next[index] = Math.max(0, Math.min(255, Math.round(Number(input.value)))); input.value = String(next[index]); emitRgb(next);
|
||||
}
|
||||
</script>
|
||||
<style scoped lang="scss">
|
||||
.rgb-picker { width: 100%; }
|
||||
.picker-trigger { display: inline-flex; align-items: center; gap: 10px; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: var(--radius-md); background: var(--hover-bg); color: var(--text-primary); font-size: 13px; cursor: pointer; }
|
||||
.picker-trigger:hover { border-color: var(--color-primary); }
|
||||
.picker-trigger > svg { color: var(--text-secondary); font-size: 18px; }
|
||||
.trigger-swatch { width: 24px; height: 24px; border: 1px solid var(--border-color); border-radius: 6px; }
|
||||
.picker-dismiss { position: fixed; inset: 0; z-index: 149; }
|
||||
.picker-panel { position: fixed; z-index: 150; width: min(320px, calc(100vw - 24px)); box-sizing: border-box; max-height: calc(100dvh - 24px); overflow-y: auto; padding: 18px; border: 1px solid var(--border-color); border-radius: 16px; background: var(--bg-secondary); color: var(--text-primary); box-shadow: 0 16px 48px rgba(0,0,0,.24), 0 2px 8px rgba(0,0,0,.12); }
|
||||
.picker-panel header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 14px; font-size: 14px; font-weight: 600; }
|
||||
.picker-panel header button { display: grid; place-items: center; width: 26px; height: 26px; border: 0; border-radius: 6px; background: transparent; color: var(--text-secondary); font-size: 18px; cursor: pointer; }
|
||||
.picker-panel header button:hover { background: var(--hover-bg); }
|
||||
.color-palette { position: relative; height: 180px; border-radius: 9px; background-image: linear-gradient(to top, #000, transparent), linear-gradient(to right, #fff, transparent); cursor: crosshair; touch-action: none; }
|
||||
.palette-cursor { position: absolute; width: 16px; height: 16px; box-sizing: border-box; border: 2px solid #fff; border-radius: 50%; transform: translate(-50%,-50%); box-shadow: 0 0 0 1px rgba(0,0,0,.45), 0 1px 4px rgba(0,0,0,.3); pointer-events: none; }
|
||||
.hue-row { display: flex; align-items: center; gap: 12px; margin: 18px 0; }
|
||||
.preview-swatch { flex-shrink: 0; width: 28px; height: 28px; border-radius: 8px; border: 1px solid var(--border-color); }
|
||||
.hue-strip { appearance: none; min-width: 0; width: 100%; height: 12px; border-radius: 999px; background: linear-gradient(to right,#f00,#ff0,#0f0,#0ff,#00f,#f0f,#f00); cursor: pointer; }
|
||||
.hue-strip::-webkit-slider-thumb { appearance: none; width: 16px; height: 20px; border: 2px solid white; border-radius: 6px; background: transparent; box-shadow: 0 0 0 1px rgba(0,0,0,.35); }
|
||||
.hue-strip::-moz-range-thumb { width: 12px; height: 16px; border: 2px solid white; border-radius: 6px; background: transparent; box-shadow: 0 0 0 1px rgba(0,0,0,.35); }
|
||||
.rgb-values { display: grid; grid-template-columns: repeat(3,minmax(0,1fr)); gap: 10px; }
|
||||
.rgb-values label { display: flex; flex-direction: column; gap: 6px; text-align: center; font-size: 11px; color: var(--text-secondary); }
|
||||
.rgb-values input { width: 100%; box-sizing: border-box; padding: 8px; text-align: center; border: 1px solid var(--border-color); border-radius: 7px; background: var(--bg-primary); color: var(--text-primary); font: 13px var(--font-mono); appearance: textfield; }
|
||||
.rgb-values input::-webkit-inner-spin-button, .rgb-values input::-webkit-outer-spin-button { appearance: none; margin: 0; }
|
||||
.picker-panel :focus-visible, .picker-trigger:focus-visible { outline: 2px solid var(--color-primary); outline-offset: 3px; }
|
||||
.picker-panel p { margin: 14px 0 0; color: var(--text-tertiary); font-size: 11px; text-align: center; }
|
||||
</style>
|
||||
@@ -87,7 +87,7 @@ function clear() {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
transition: all var(--transition-fast);
|
||||
&:hover { background: var(--color-primary); color: white; }
|
||||
&:hover { background: var(--color-primary); color: var(--color-on-primary); }
|
||||
}
|
||||
|
||||
.btn-danger {
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
<template>
|
||||
<div v-if="modal.open" class="edit-modal-overlay" @click.self="store.closeBilibiliPartModal">
|
||||
<div class="edit-modal">
|
||||
<h3 class="modal-title">选择分P</h3>
|
||||
|
||||
<div class="form-group">
|
||||
<label>视频名称</label>
|
||||
<div class="video-info-box">
|
||||
<CoverArt :url="modal.coverUrl" :size="44" :radius="8" />
|
||||
<div class="video-meta">
|
||||
<div class="video-title" :title="modal.title">{{ modal.title }}</div>
|
||||
<div class="video-hint">共 {{ modal.parts.length }} 个分P · {{ actionHint }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label>分P列表</label>
|
||||
<div class="parts-list">
|
||||
<div
|
||||
v-for="part in modal.parts"
|
||||
:key="part.part"
|
||||
class="part-item"
|
||||
:class="{ active: selectedPart?.part === part.part }"
|
||||
@click="selectedPart = part"
|
||||
@dblclick="confirmSelect(part)"
|
||||
>
|
||||
<span class="part-badge">P{{ part.part }}</span>
|
||||
<span class="part-name" :title="part.title">{{ part.title }}</span>
|
||||
<span class="part-duration">{{ formatDuration(part.duration) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-actions">
|
||||
<button class="btn-secondary" @click="store.closeBilibiliPartModal">取消</button>
|
||||
<button
|
||||
class="btn-primary"
|
||||
:disabled="!selectedPart"
|
||||
@click="selectedPart && confirmSelect(selectedPart)"
|
||||
>
|
||||
{{ confirmBtnText }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, watch } from 'vue';
|
||||
import { usePlayerStore, type BiliPart } from '../stores/player.js';
|
||||
import CoverArt from './CoverArt.vue';
|
||||
|
||||
const store = usePlayerStore();
|
||||
const modal = computed(() => store.biliPartModal);
|
||||
|
||||
const selectedPart = ref<BiliPart | null>(null);
|
||||
|
||||
// 弹窗打开时默认选中第 1 P
|
||||
watch(
|
||||
() => modal.value.open,
|
||||
(open) => {
|
||||
if (open && modal.value.parts.length > 0) {
|
||||
selectedPart.value = modal.value.parts[0];
|
||||
} else {
|
||||
selectedPart.value = null;
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
const actionHint = computed(() => {
|
||||
if (modal.value.action === 'playNext') return '添加到下一首播放';
|
||||
if (modal.value.action === 'add') return '添加到播放队列';
|
||||
return '立即播放';
|
||||
});
|
||||
|
||||
const confirmBtnText = computed(() => {
|
||||
if (modal.value.action === 'playNext') return '下一首播放';
|
||||
if (modal.value.action === 'add') return '添加到队列';
|
||||
return '播放';
|
||||
});
|
||||
|
||||
function confirmSelect(part: BiliPart) {
|
||||
store.selectBilibiliPart(part);
|
||||
}
|
||||
|
||||
function formatDuration(seconds: number): string {
|
||||
if (!seconds || seconds <= 0) return '--:--';
|
||||
const m = Math.floor(seconds / 60);
|
||||
const s = seconds % 60;
|
||||
return `${m}:${s.toString().padStart(2, '0')}`;
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.edit-modal-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
z-index: 200;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.edit-modal {
|
||||
background: var(--bg-secondary);
|
||||
border-radius: var(--radius-lg);
|
||||
padding: 28px;
|
||||
width: 480px;
|
||||
max-width: 90vw;
|
||||
max-height: 80vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.modal-title {
|
||||
font-size: 20px;
|
||||
font-weight: 700;
|
||||
margin-bottom: 20px;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.form-group {
|
||||
margin-bottom: 16px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
|
||||
label {
|
||||
display: block;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
margin-bottom: 6px;
|
||||
opacity: 0.7;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
}
|
||||
|
||||
.video-info-box {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 10px 14px;
|
||||
background: var(--hover-bg);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--radius-sm);
|
||||
|
||||
.video-meta {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.video-title {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.video-hint {
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
}
|
||||
|
||||
.parts-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
max-height: 280px;
|
||||
overflow-y: auto;
|
||||
padding-right: 4px;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
}
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background: var(--border-color);
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
}
|
||||
|
||||
.part-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 10px 14px;
|
||||
background: var(--hover-bg);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--radius-sm);
|
||||
cursor: pointer;
|
||||
transition: all var(--transition-fast);
|
||||
|
||||
&:hover {
|
||||
border-color: var(--color-primary);
|
||||
background: var(--color-primary-10, rgba(0, 161, 214, 0.08));
|
||||
}
|
||||
|
||||
&.active {
|
||||
border-color: var(--color-primary);
|
||||
background: var(--color-primary-15, rgba(0, 161, 214, 0.15));
|
||||
|
||||
.part-badge {
|
||||
background: var(--color-primary);
|
||||
color: var(--color-on-primary);
|
||||
}
|
||||
|
||||
.part-name {
|
||||
color: var(--color-primary);
|
||||
font-weight: 600;
|
||||
}
|
||||
}
|
||||
|
||||
.part-badge {
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
padding: 2px 6px;
|
||||
border-radius: var(--radius-xs);
|
||||
background: var(--color-primary-10, rgba(0, 161, 214, 0.1));
|
||||
color: var(--color-primary);
|
||||
flex-shrink: 0;
|
||||
transition: all var(--transition-fast);
|
||||
}
|
||||
|
||||
.part-name {
|
||||
flex: 1;
|
||||
font-size: 13px;
|
||||
color: var(--text-primary);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.part-duration {
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
font-variant-numeric: tabular-nums;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.modal-actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
justify-content: flex-end;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
padding: 10px 20px;
|
||||
background: var(--color-primary);
|
||||
color: var(--color-on-primary);
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
transition: transform var(--transition-fast);
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
transform: scale(1.02);
|
||||
}
|
||||
&:active:not(:disabled) {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
&:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
padding: 10px 20px;
|
||||
background: var(--hover-bg);
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
transition: opacity var(--transition-fast);
|
||||
|
||||
&:hover {
|
||||
opacity: 0.8;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
Loaded 100 of 127 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user