mirror of
https://github.com/ZHANGTIANYAO1/teamspeak-music-bot.git
synced 2026-12-01 02:12:50 +08:00
Compare commits
77
Commits
v1.15.1
...
fc4d472685
| 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 |
No files matched your search
@@ -103,12 +103,12 @@ npm start
|
||||
|
||||
### 方式三:Docker 一键部署
|
||||
|
||||
所有依赖已内置(Node.js、FFmpeg、Opus 编码器),无需安装任何额外软件。
|
||||
需要 Docker 和 Docker Compose v2。默认从 GitHub Container Registry(GHCR)拉取预构建镜像,镜像已包含 Node.js、FFmpeg 和 Opus 编码器。
|
||||
|
||||
```bash
|
||||
git clone https://github.com/ZHANGTIANYAO1/teamspeak-music-bot.git
|
||||
cd teamspeak-music-bot/scripts/docker
|
||||
docker-compose up -d
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
打开浏览器访问 **http://localhost:3000**
|
||||
@@ -116,15 +116,14 @@ docker-compose up -d
|
||||
<details>
|
||||
<summary>Docker 详细说明</summary>
|
||||
|
||||
- 首次构建需要几分钟(编译原生模块)
|
||||
- 默认使用 `host` 网络模式,机器人可直接连接局域网 TS3 服务器
|
||||
- 数据持久化在 Docker 命名卷 `tsmusicbot-data` 中(数据库、Cookie、日志)
|
||||
- 内置健康检查(`/api/health`),支持 Docker 自动重启
|
||||
|
||||
```bash
|
||||
docker logs -f tsmusicbot # 查看日志
|
||||
docker-compose down # 停止
|
||||
docker-compose up -d --build # 代码更新后重新构建
|
||||
docker compose down # 停止
|
||||
docker compose pull && docker compose up -d # 更新预构建镜像
|
||||
```
|
||||
|
||||
如果 TS3 服务器在其他机器上,编辑 `docker-compose.yml`:
|
||||
@@ -136,6 +135,36 @@ ports:
|
||||
|
||||
</details>
|
||||
|
||||
#### 无法访问 GHCR 时部署
|
||||
|
||||
**离线导入发布镜像。** 在能访问 GHCR 的机器上拉取项目官方发布镜像并导出。下面以 `1.15.4` 和 `linux/amd64` 为例,请选择所需发布版本以及部署服务器的架构(`linux/amd64` 或 `linux/arm64`)。Git 发布标签带 `v`,镜像标签不带 `v`。
|
||||
|
||||
```bash
|
||||
image=ghcr.io/zhangtianyao1/teamspeak-music-bot:1.15.4
|
||||
docker pull --platform linux/amd64 "$image"
|
||||
docker image save -o tsmusicbot-1.15.4.tar "$image"
|
||||
```
|
||||
|
||||
将归档和同版本的 `scripts/docker/docker-compose.yml` 复制到部署服务器。在 Compose 文件中把 `image:` 改为上面导入的完整镜像名和标签,然后在该文件所在目录运行:
|
||||
|
||||
```bash
|
||||
docker image load -i tsmusicbot-1.15.4.tar
|
||||
docker compose config --images
|
||||
docker compose up -d --pull never
|
||||
```
|
||||
|
||||
升级时导入新版本的镜像并更新 `image:` 的标签,再在同一部署目录运行启动命令,以继续使用现有的数据卷。
|
||||
|
||||
**从发布源码本地构建。** 若部署机可以访问构建依赖但无法访问 GHCR,可下载或克隆对应发布标签的源码。在 `scripts/docker/docker-compose.yml` 中把 `image:` 替换成下列配置,保持它位于 `services.tsmusicbot` 下:
|
||||
|
||||
```yaml
|
||||
build:
|
||||
context: ../..
|
||||
dockerfile: scripts/docker/Dockerfile
|
||||
```
|
||||
|
||||
进入源码的 `scripts/docker` 目录,运行 `docker compose up -d --build`。构建需要获取 `node:22-slim` 基础镜像,以及 Dockerfile 使用的 apt、npm 和原生依赖下载源。升级时切换到所需的新发布标签并重新构建。
|
||||
|
||||
### 方式四:Linux 安装脚本
|
||||
|
||||
Linux 下有两个脚本,按需二选一:
|
||||
@@ -302,11 +331,8 @@ npm start
|
||||
```bash
|
||||
cd scripts/docker
|
||||
|
||||
# 拉取最新代码
|
||||
git pull
|
||||
|
||||
# 重新构建并启动(数据自动保留)
|
||||
docker-compose up -d --build
|
||||
# 拉取预构建镜像并重新启动
|
||||
docker compose pull && docker compose up -d
|
||||
```
|
||||
|
||||
> 数据(数据库、Cookie、日志)保存在 Docker 命名卷 `tsmusicbot-data` 中,更新不会丢失。
|
||||
@@ -347,6 +373,20 @@ sudo systemctl start tsmusicbot
|
||||
4. (可选)在 **设置 → Jellyfin 音乐库** 连接自建 Jellyfin 服务器并打开「启用 Jellyfin 音源」(安装向导第 3 步保存连接时会自动启用;详见 [可选:Jellyfin 音源](#可选jellyfin-音源))
|
||||
5. 在 **设置 → 用户管理**(仅管理员可见)按需添加成员。成员默认可控制播放但无法管理其他用户;管理员还可为每个成员单独配置**能力**(播放控制 / 队列 / 机器人管理 / 平台登录 / 音质)和**可操作的机器人白名单**,未授权的机器人对该成员不可见、不可控
|
||||
|
||||
### QQ 音乐自动续期
|
||||
|
||||
QQ 音源启用时,`QQ_MUSIC_MANAGED_SESSION` 默认为 `1`。在 **设置 → 音乐账号 → QQ 音乐** 用手机 QQ 扫码授权一次后,机器人每 24 小时自动续期,遇到有效期更短的凭据会在到期前提前续期。凭据和上次成功续期时间保存在数据目录的 `cookies/qq-session.json`,重启后继续按原时间安排续期。
|
||||
|
||||
已有 `cookies/qq.json` 可继续播放,扫码授权后才会获得续期所需的凭据。手动导入 Cookie 会替换当前登录并取消该账号的自动续期。设置页会显示上次成功续期时间、下次续期时间、重试状态或重新扫码提示。具备平台登录权限的用户也可以调用 `POST /api/auth/qq/refresh` 手动尝试续期。
|
||||
|
||||
设置 `QQ_MUSIC_MANAGED_SESSION=0` 并重启可关闭自动续期。机器人继续使用当前的 QQ 播放 Cookie,并从 `cookies/qq.json` 兼容读取旧部署的 Cookie。
|
||||
|
||||
### 每用户音乐账号
|
||||
|
||||
管理员可在设置中开启「每个成员使用自己的音乐账号」,默认关闭。成员可扫码绑定自己的网易云,也可接受管理员分配的网易云、QQ 音乐、酷狗或 B 站账号。网页搜索、歌单和推荐默认优先使用自己的绑定,其次使用分配账号,最后使用机器人共享账号。成员也可在「我的音乐账号」中主动选择共享账号。房间播歌使用机器人共享账号。
|
||||
|
||||
从共享账号导入时,账号池保存当前 Cookie 的副本。共享账号续期或更换后,管理员可在账号池中更新该条目的 Cookie。
|
||||
|
||||
### WebUI 页面说明
|
||||
|
||||
| 页面 | 功能 |
|
||||
@@ -583,7 +623,7 @@ teamspeak-music-bot/
|
||||
| **后端框架** | Express 4, WebSocket (ws) |
|
||||
| **数据库** | better-sqlite3 (SQLite) |
|
||||
| **音频处理** | FFmpeg (ffmpeg-static 内置), @discordjs/opus |
|
||||
| **TS 协议** | @honeybbq/teamspeak-client(完整客户端协议)+ 自研 TS6 协议适配层 |
|
||||
| **TS 协议** | @honeybbq/teamspeak(TS3 / TS6 完整客户端协议,支持 OpenProtocol v1) |
|
||||
| **Jellyfin** | Jellyfin REST API(可选音源,直连,无额外 npm 依赖) |
|
||||
| **网易云 API** | NeteaseCloudMusicApi |
|
||||
| **QQ 音乐 API** | @sansenjian/qq-music-api(锁定 `~2.4.0`,需 Node ≥ 20.17) |
|
||||
@@ -865,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`。
|
||||
|
||||
@@ -887,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` 字段就是实际监听端口。
|
||||
@@ -915,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-无鉴权版本升级重要)。
|
||||
@@ -953,7 +997,42 @@ A:本项目内置 `/login` 限流(每 IP 每分钟 5 次),但生产部
|
||||
|
||||
> 完整历史请查看 [git log](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/commits/main) 或 [Releases](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/releases)。这里只列出重要变更和面向用户的破坏性改动。
|
||||
|
||||
### 最新版本 — v1.15.1:长视频播放阻塞与音乐 API 日志隐私修复
|
||||
### 最新版本 — 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 下载失败日志采用同样的处理。
|
||||
@@ -1235,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 许可) |
|
||||
|
||||
|
||||
+3
-1
@@ -225,7 +225,9 @@ interface BotStatus {
|
||||
| GET | `/queue` | `{ queue: QueuedSong[], status: BotStatus }` |
|
||||
| GET | `/elapsed` | `{ elapsed: 42.5 }` |
|
||||
| DELETE | `/queue/:index` | `{ message }`(移除指定下标,能力 `player.queue`) |
|
||||
| GET | `/history?limit=50` | `{ history: [{ id, name, artist, album, coverUrl, platform, playedAt, requestedBy }] }` |
|
||||
| GET | `/history?limit=50` | `{ history: [{ rowId, id, name, artist, album, coverUrl, platform, playedAt, requestedBy }] }` |
|
||||
| DELETE | `/history/:rowId` | `{ deleted }`(删除单条记录,能力 `player.queue`) |
|
||||
| DELETE | `/history` | `{ deleted }`(请求体 `{ ids: number[] }` 批量删除 1–500 条或 `{ all: true }` 清空,能力 `player.queue`) |
|
||||
| GET | `/profile` | ProfileConfig |
|
||||
| PUT | `/profile` | ProfileConfig(能力 `bot.manage`) |
|
||||
|
||||
|
||||
Generated
+26
-15
@@ -1,16 +1,16 @@
|
||||
{
|
||||
"name": "tsmusicbot",
|
||||
"version": "0.1.0",
|
||||
"version": "1.16.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",
|
||||
|
||||
+150
-2
@@ -40,6 +40,47 @@ 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);
|
||||
@@ -825,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;
|
||||
@@ -837,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;
|
||||
@@ -846,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 {
|
||||
|
||||
+120
-20
@@ -87,8 +87,20 @@ export function cleanupTempDir(dir: string): void {
|
||||
|
||||
export function buildFfmpegArgs(url: string, seekSeconds: number): string[] {
|
||||
const args: string[] = ["-nostats"];
|
||||
const isHttp = /^https?:\/\//i.test(url);
|
||||
const isBilibili = isHttp && (url.includes("bilivideo") || url.includes("bilibili"));
|
||||
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 (isBilibili) {
|
||||
args.push(
|
||||
@@ -194,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;
|
||||
@@ -244,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;
|
||||
@@ -258,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;
|
||||
}
|
||||
@@ -485,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;
|
||||
@@ -575,7 +595,26 @@ 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;
|
||||
@@ -618,6 +657,17 @@ 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 {
|
||||
@@ -662,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仍在运行但缓冲区不足一帧,且连续多次无法获取数据
|
||||
@@ -683,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
|
||||
@@ -732,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";
|
||||
@@ -748,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);
|
||||
|
||||
@@ -782,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);
|
||||
}
|
||||
@@ -797,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);
|
||||
@@ -828,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;
|
||||
|
||||
@@ -852,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; }
|
||||
|
||||
+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();
|
||||
});
|
||||
});
|
||||
+425
-8
@@ -1,15 +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";
|
||||
@@ -134,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 })),
|
||||
@@ -393,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;
|
||||
@@ -458,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,
|
||||
@@ -484,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();
|
||||
@@ -1268,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,
|
||||
@@ -1310,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;
|
||||
}
|
||||
|
||||
@@ -1344,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)", () => {
|
||||
@@ -1541,6 +1761,36 @@ describe("BotInstance live-queue persistence (#119)", () => {
|
||||
});
|
||||
|
||||
describe("BotInstance Bilibili multi-P resolution", () => {
|
||||
it("passes the page from a TeamSpeak video link to the Bilibili provider", async () => {
|
||||
const song = {
|
||||
id: "BV1yxHQeYEuE?p=2",
|
||||
name: "Video - P2",
|
||||
artist: "Uploader",
|
||||
album: "",
|
||||
duration: 180,
|
||||
coverUrl: "",
|
||||
platform: "bilibili" as const,
|
||||
};
|
||||
const provider = { platform: "bilibili", getSongDetail: vi.fn().mockResolvedValue(song) };
|
||||
const ctx = {
|
||||
config: { commandPrefix: "!" },
|
||||
assertProviderEnabled: vi.fn(),
|
||||
getProviderFor: vi.fn().mockReturnValue(provider),
|
||||
};
|
||||
const args = "[URL]https://www.bilibili.com/video/BV1yxHQeYEuE/?p=2[/URL]";
|
||||
|
||||
const result = await (BotInstance.prototype as any).resolvePlayQuery.call(ctx, {
|
||||
name: "play",
|
||||
args,
|
||||
rawArgs: [args],
|
||||
flags: new Set(),
|
||||
});
|
||||
|
||||
expect(ctx.getProviderFor).toHaveBeenCalledWith("bilibili");
|
||||
expect(provider.getSongDetail).toHaveBeenCalledWith("BV1yxHQeYEuE?p=2");
|
||||
expect(result.song).toEqual(song);
|
||||
});
|
||||
|
||||
it("resolves multi-P search result to P1 with accurate duration and name", async () => {
|
||||
const multiPSongDetail = {
|
||||
id: "BV1multiP?p=1",
|
||||
@@ -1646,6 +1896,12 @@ describe("cmdPlaylist with a playlist link (#160)", () => {
|
||||
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"); });
|
||||
@@ -1660,6 +1916,8 @@ describe("cmdPlaylist with a playlist link (#160)", () => {
|
||||
});
|
||||
|
||||
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>;
|
||||
@@ -1678,6 +1936,7 @@ describe("resumeInterruptedStream — long B站 streams dying mid-play (#161)",
|
||||
song,
|
||||
provider,
|
||||
connected: true,
|
||||
lifecycleGeneration: 0,
|
||||
effectiveDuration: song.duration,
|
||||
streamRecovery: null,
|
||||
queue: { current: vi.fn(() => song) },
|
||||
@@ -1698,7 +1957,7 @@ describe("resumeInterruptedStream — long B站 streams dying mid-play (#161)",
|
||||
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).toHaveBeenCalledWith("BV1abc");
|
||||
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");
|
||||
});
|
||||
@@ -1739,7 +1998,10 @@ describe("resumeInterruptedStream — long B站 streams dying mid-play (#161)",
|
||||
|
||||
it("falls through to advancing when no fresh URL can be fetched", async () => {
|
||||
const ctx = makeCtx({ url: null });
|
||||
expect(await resumeInterruptedStream.call(ctx)).toBe(false);
|
||||
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();
|
||||
});
|
||||
|
||||
@@ -1755,6 +2017,8 @@ describe("resumeInterruptedStream — long B站 streams dying mid-play (#161)",
|
||||
});
|
||||
|
||||
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: "",
|
||||
@@ -1769,11 +2033,16 @@ describe("BotInstance trackEnd — stale playback sessions", () => {
|
||||
player.getPlaybackSessionId = AudioPlayer.prototype.getPlaybackSessionId;
|
||||
player.pause = AudioPlayer.prototype.pause;
|
||||
player.resume = AudioPlayer.prototype.resume;
|
||||
// The real pause()/resume() drive the de-click transport ramp
|
||||
// (a0f0b49..6f165b5). A stub player must expose it too, or the prototype
|
||||
// methods throw "setTransportRamp is not a function".
|
||||
player.setTransportRamp = vi.fn();
|
||||
player.play = vi.fn(() => { player.sessionId++; player.state = "playing"; });
|
||||
const provider = { getSongUrl: vi.fn(async () => ({ url: "fresh" })) };
|
||||
const advances: string[] = [];
|
||||
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(),
|
||||
@@ -1893,7 +2162,7 @@ describe("BotInstance trackEnd — stale playback sessions", () => {
|
||||
expect(ctx.advances).toEqual([]);
|
||||
});
|
||||
|
||||
it("resume after a paused failed lookup retries recovery instead of remaining idle", async () => {
|
||||
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);
|
||||
@@ -1903,7 +2172,7 @@ describe("BotInstance trackEnd — stale playback sessions", () => {
|
||||
await flushEvents();
|
||||
ctx.provider.getSongUrl.mockResolvedValue({ url: "recovered" });
|
||||
ctx.resume();
|
||||
await flushEvents();
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(ctx.player.getState()).toBe("playing");
|
||||
expect(ctx.player.play).toHaveBeenCalledWith("recovered", 1000, 10_000);
|
||||
expect(ctx.advances).toEqual([]);
|
||||
@@ -1936,3 +2205,151 @@ describe("BotInstance trackEnd — stale playback sessions", () => {
|
||||
expect(ctx.advances).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("BotInstance — OpenProtocol & command routing", () => {
|
||||
it("routes private DM command replies to invokerId and channel replies to the channel", async () => {
|
||||
const ctx = makeGateCtx({ adminGroups: [] });
|
||||
ctx.executeCommand = vi.fn(async (parsed: { name: string; args: string }) =>
|
||||
`ok:${parsed.name}:${parsed.args}`,
|
||||
);
|
||||
|
||||
const dm: TS3TextMessage = {
|
||||
invokerName: "FlSpeakUser",
|
||||
invokerId: "12",
|
||||
invokerUid: "uid-fl",
|
||||
message: "!play 晴天",
|
||||
targetMode: 1,
|
||||
invokerGroups: [],
|
||||
};
|
||||
await handleTextMessage.call(ctx, dm);
|
||||
|
||||
expect(ctx.executeCommand).toHaveBeenCalledTimes(1);
|
||||
expect(ctx.tsClient.sendTextMessage).toHaveBeenCalledTimes(1);
|
||||
expect(ctx.tsClient.sendTextMessage).toHaveBeenCalledWith("ok:play:晴天", 1, 12);
|
||||
|
||||
ctx.tsClient.sendTextMessage.mockClear();
|
||||
await handleTextMessage.call(ctx, makeMsg("!now"));
|
||||
expect(ctx.tsClient.sendTextMessage).toHaveBeenCalledWith("ok:now:");
|
||||
});
|
||||
|
||||
it("drops a private command reply when the connection changed during execution", async () => {
|
||||
const ctx = makeGateCtx({});
|
||||
ctx.lifecycleGeneration = 1;
|
||||
const executed = deferred();
|
||||
const reply = deferred<string>();
|
||||
ctx.executeCommand = vi.fn(() => {
|
||||
executed.resolve();
|
||||
return reply.promise;
|
||||
});
|
||||
|
||||
const pending = handleTextMessage.call(ctx, { ...makeMsg("!now"), targetMode: 1 });
|
||||
await executed.promise;
|
||||
ctx.lifecycleGeneration++;
|
||||
reply.resolve("Prior connection's queue");
|
||||
await pending;
|
||||
|
||||
expect(ctx.tsClient.sendTextMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("drops a command from a previous connection after the group check", async () => {
|
||||
const ctx = makeGateCtx({ adminGroups: [6] });
|
||||
ctx.lifecycleGeneration = 1;
|
||||
const groups = deferred<string[]>();
|
||||
ctx.tsClient.getClientServerGroups.mockReturnValue(groups.promise);
|
||||
|
||||
const pending = handleTextMessage.call(ctx, { ...makeMsg("!stop"), targetMode: 1 });
|
||||
expect(ctx.tsClient.getClientServerGroups).toHaveBeenCalled();
|
||||
ctx.lifecycleGeneration++;
|
||||
groups.resolve(["6"]);
|
||||
await pending;
|
||||
|
||||
expect(ctx.executeCommand).not.toHaveBeenCalled();
|
||||
expect(ctx.tsClient.sendTextMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("routes permission denied and execution errors privately when triggered via DM", async () => {
|
||||
const ctx = makeGateCtx({ adminGroups: [6], lookupGroups: [] });
|
||||
const dmStop: TS3TextMessage = {
|
||||
invokerName: "Guest",
|
||||
invokerId: "22",
|
||||
invokerUid: "uid-guest",
|
||||
message: "!stop",
|
||||
targetMode: 1,
|
||||
invokerGroups: [],
|
||||
};
|
||||
await handleTextMessage.call(ctx, dmStop);
|
||||
expect(ctx.tsClient.sendTextMessage).toHaveBeenCalledWith(COMMAND_DENIED_MESSAGE, 1, 22);
|
||||
|
||||
ctx.tsClient.sendTextMessage.mockClear();
|
||||
const okCtx = makeGateCtx({ adminGroups: [] });
|
||||
okCtx.executeCommand = vi.fn(async () => {
|
||||
throw new Error("boom");
|
||||
});
|
||||
await handleTextMessage.call(okCtx, { ...dmStop, message: "!play x" });
|
||||
expect(okCtx.tsClient.sendTextMessage).toHaveBeenCalledWith("Error: boom", 1, 22);
|
||||
});
|
||||
|
||||
it("wires connected, clientMoved, pluginCommand, and disconnected to openProtocol", () => {
|
||||
const tsClient = new EventEmitter() as EventEmitter & {
|
||||
getClientId(): number;
|
||||
};
|
||||
tsClient.getClientId = () => 99;
|
||||
const openProtocol = {
|
||||
scheduleAnnounce: vi.fn(),
|
||||
handlePluginCommand: vi.fn(async () => {}),
|
||||
reset: vi.fn(),
|
||||
};
|
||||
const ctx = {
|
||||
tsClient,
|
||||
openProtocol,
|
||||
connected: true,
|
||||
lifecycleGeneration: 0,
|
||||
autoPaused: false,
|
||||
idleTimer: null,
|
||||
idlePollTimer: null,
|
||||
jellyfinPollTimer: null,
|
||||
snapshotTimer: null,
|
||||
currentSourceIsSpotify: false,
|
||||
disconnectEmitted: false,
|
||||
_cancelIdleTimer: vi.fn(),
|
||||
_startIdlePoller: vi.fn(),
|
||||
_startJellyfinReportPoller: vi.fn(),
|
||||
unregisterManagedVoiceClient: vi.fn(),
|
||||
voiceDucking: { reset: vi.fn(), removeSpeaker: vi.fn(), handleVoiceActivity: vi.fn() },
|
||||
spotifyController: { stop: vi.fn() },
|
||||
player: { stop: vi.fn() },
|
||||
jellyfinReporter: undefined,
|
||||
queue: { clear: vi.fn() },
|
||||
sweepLocalAudio: vi.fn(),
|
||||
emit: vi.fn(),
|
||||
refreshOccupancy: vi.fn(async () => {}),
|
||||
_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);
|
||||
});
|
||||
});
|
||||
+478
-226
File diff suppressed because it is too large.
Load diff
@@ -1,5 +1,4 @@
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import { Client, generateIdentity } from "@honeybbq/teamspeak-client";
|
||||
import { BotProfileManager } from "./profile.js";
|
||||
import { TS6HttpQuery } from "../ts-protocol/http-query.js";
|
||||
import type { TS3Client } from "../ts-protocol/client.js";
|
||||
@@ -419,20 +418,15 @@ describe("BotProfileManager checked TS6 profile lifecycle", () => {
|
||||
|
||||
it("checks self clientupdate permission responses and retries only after reconnect", async () => {
|
||||
const { pm, ts, request, logger } = makeHttpProfile({ nicknameEnabled: true, awayStatusEnabled: true });
|
||||
const client: any = new Client(generateIdentity(0), "127.0.0.1:9987", "Bot");
|
||||
const commands: string[] = [];
|
||||
client.handler.sendPacket = vi.fn((_type, data: Buffer) => {
|
||||
const command = data.toString();
|
||||
ts.execCommand.mockImplementation(async (command: string) => {
|
||||
commands.push(command);
|
||||
const returnCode = command.match(/return_code=(\d+)/)?.[1];
|
||||
client.handler.onPacket({ typeFlagged: 2, data: Buffer.from(`error id=2568 msg=insufficient\\sclient\\spermissions${returnCode ? ` return_code=${returnCode}` : ""}`) });
|
||||
throw new Error("insufficient client permissions (error id=2568)");
|
||||
});
|
||||
ts.sendCommandNoWait.mockImplementation((command: string) => client.sendCommandNoWait(command));
|
||||
ts.execCommand.mockImplementation((command: string) => client.execCommand(command));
|
||||
await pm.onSongChange(null);
|
||||
await pm.onSongChange(null);
|
||||
expect(commands).toHaveLength(1);
|
||||
expect(commands[0]).toMatch(/^clientupdate client_nickname=Bot client_away=1 client_away_message=等待播放 return_code=\d+$/);
|
||||
expect(commands[0]).toBe("clientupdate client_nickname=Bot client_away=1 client_away_message=等待播放");
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
expect(logger.info.mock.calls.some((call: any[]) => call[1] === "Client properties updated (nickname + away)")).toBe(false);
|
||||
pm.onConnect();
|
||||
|
||||
@@ -101,6 +101,34 @@ describe("parseSongRef (#90 exact-song selection)", () => {
|
||||
expect(parseSongRef("https://www.bilibili.com/video/BV1yxHQeYEuE")).toEqual({ id: "BV1yxHQeYEuE", platform: "bilibili" });
|
||||
expect(parseSongRef("https://b23.tv/BV1yxHQeYEuE")).toEqual({ id: "BV1yxHQeYEuE", platform: "bilibili" });
|
||||
});
|
||||
|
||||
it.each([
|
||||
"https://www.bilibili.com/video/BV1yxHQeYEuE?p=2",
|
||||
"https://b23.tv/BV1yxHQeYEuE?p=2",
|
||||
"https://www.bilibili.com/video/BV1yxHQeYEuE/?from=share&p=2&vd_source=test#reply",
|
||||
"https://www.bilibili.com/video/BV1yxHQeYEuE/?from=share?p=3&p=2",
|
||||
"https://www.bilibili.com/video/BV1yxHQeYEuE/?p=%32",
|
||||
"[URL]https://www.bilibili.com/video/BV1yxHQeYEuE/?p=2[/URL]",
|
||||
"[url]https://www.bilibili.com/video/BV1yxHQeYEuE/?p=2#reply[/url]",
|
||||
"[URL=https://www.bilibili.com/video/BV1yxHQeYEuE/?p=2]点击播放[/URL]",
|
||||
"参考 https://example.com/?p=9 视频 https://www.bilibili.com/video/BV1yxHQeYEuE/?p=2 请播放",
|
||||
])("preserves the Bilibili page query in %s", (input) => {
|
||||
expect(parseSongRef(input)).toEqual({ id: "BV1yxHQeYEuE?p=2", platform: "bilibili" });
|
||||
});
|
||||
|
||||
it.each([
|
||||
"?p=2extra",
|
||||
"?p=-2",
|
||||
"?page=2",
|
||||
"?sp=2",
|
||||
"?from=share?p=2",
|
||||
"?from=share%3Fp%3D2",
|
||||
"?from=share#reply&p=2",
|
||||
"#reply?p=2",
|
||||
])("ignores an invalid or unrelated Bilibili page query %s", (query) => {
|
||||
expect(parseSongRef(`https://www.bilibili.com/video/BV1yxHQeYEuE${query}`))
|
||||
.toEqual({ id: "BV1yxHQeYEuE", platform: "bilibili" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseSelectionIndex (#90 pick from last search)", () => {
|
||||
|
||||
+5
-1
@@ -69,7 +69,11 @@ export function parseSongRef(raw: string): SongRef | null {
|
||||
// a "BV..." token never collides with them).
|
||||
const bv = /BV[0-9A-Za-z]{8,12}/.exec(q);
|
||||
if (bv && (/^BV[0-9A-Za-z]{8,12}$/.test(q) || /bilibili\.com|b23\.tv/i.test(q))) {
|
||||
return { id: bv[0], platform: "bilibili" };
|
||||
// Extract the query attached to this BV id, including in [URL=...] tags.
|
||||
const suffix = q.slice(bv.index + bv[0].length);
|
||||
const query = /^\/?\?([^#\s[\]]*)/.exec(suffix)?.[1];
|
||||
const page = new URLSearchParams(query).get("p");
|
||||
return { id: page && /^\d+$/.test(page) ? `${bv[0]}?p=${page}` : bv[0], platform: "bilibili" };
|
||||
}
|
||||
|
||||
// NetEase song URL. Only treat `id=N` as a SONG id when the URL is not a
|
||||
|
||||
@@ -0,0 +1,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(); }
|
||||
});
|
||||
});
|
||||
@@ -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")
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import Database from "better-sqlite3";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { CAPABILITIES, BOTS_ALL } from "./permissions.js";
|
||||
import { GUEST_USER_ID, GUEST_USERNAME } from "./users.js";
|
||||
import type { QueuedSong } from "../audio/queue.js";
|
||||
@@ -126,10 +127,62 @@ export interface FavoritePlaylist {
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A music-platform login the ADMIN owns and may hand out to members
|
||||
* (`perUserMusicAccounts`, #164 follow-up).
|
||||
*
|
||||
* Two separate tables, on purpose:
|
||||
* - `music_accounts` = the pool. Only the admin writes it.
|
||||
* - `music_account_grants` = "member X may use account Y".
|
||||
*
|
||||
* Keeping grants out of `user_music_cookies` is what makes "self-linked beats
|
||||
* admin-granted" possible: a member scanning their own QR code must not
|
||||
* silently overwrite (or be overwritten by) an account the admin assigned, and
|
||||
* unlinking on the member side must never revoke what the admin granted.
|
||||
*
|
||||
* `cookie` is server-side only — the API layer masks it before answering.
|
||||
*/
|
||||
export interface MusicAccount {
|
||||
id: string;
|
||||
platform: string;
|
||||
/** Admin-facing name ("网易云-主号"). Members see this instead of a nickname. */
|
||||
label: string;
|
||||
cookie: string;
|
||||
/** Who provided the login; null = imported from the bot's shared login. */
|
||||
ownerId: string | null;
|
||||
/** 0 = any number of grantees, 1 = exclusive (one member at a time). */
|
||||
capacity: number;
|
||||
enabled: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
/** One row of `music_account_grants`, joined with display fields for the UI. */
|
||||
export interface MusicAccountGrant {
|
||||
userId: string;
|
||||
username: string;
|
||||
platform: string;
|
||||
accountId: string;
|
||||
accountLabel: string;
|
||||
grantedBy: string;
|
||||
grantedAt: string;
|
||||
}
|
||||
|
||||
/** An account resolved FOR a user: what provider-scope needs to build a view. */
|
||||
export interface GrantedMusicAccount {
|
||||
accountId: string;
|
||||
label: string;
|
||||
cookie: string;
|
||||
}
|
||||
|
||||
export interface BotDatabase {
|
||||
db: Database.Database;
|
||||
addPlayHistory(entry: PlayHistoryEntry): void;
|
||||
getPlayHistory(botId: string, limit: number): PlayHistoryRecord[];
|
||||
/** Deletes the given history rows (by primary key) for one bot. Returns affected rows. */
|
||||
deletePlayHistory(botId: string, ids: number[]): number;
|
||||
/** Deletes every history row of one bot. Returns affected rows. */
|
||||
clearPlayHistory(botId: string): number;
|
||||
saveBotInstance(instance: BotInstance): void;
|
||||
getBotInstances(): BotInstance[];
|
||||
deleteBotInstance(id: string): boolean;
|
||||
@@ -148,6 +201,54 @@ export interface BotDatabase {
|
||||
getUserMusicCookie(userId: string, platform: string): string | null;
|
||||
setUserMusicCookie(userId: string, platform: string, cookie: string): void;
|
||||
deleteUserMusicCookie(userId: string, platform: string): boolean;
|
||||
/** null when the member never chose; callers treat that as "prefer own". */
|
||||
getUserMusicPreference(userId: string, platform: string): { preferShared: boolean } | null;
|
||||
setUserMusicPreference(userId: string, platform: string, preferShared: boolean): void;
|
||||
// Admin-owned account pool + assignments (#164 follow-up).
|
||||
listMusicAccounts(platform?: string): MusicAccount[];
|
||||
getMusicAccount(id: string): MusicAccount | null;
|
||||
createMusicAccount(input: {
|
||||
platform: string;
|
||||
label: string;
|
||||
cookie: string;
|
||||
ownerId?: string | null;
|
||||
capacity?: number;
|
||||
enabled?: boolean;
|
||||
}): MusicAccount;
|
||||
/**
|
||||
* Partial update; false when the id does not exist or the capacity is too low.
|
||||
*
|
||||
* `platform` is intentionally NOT patchable: grants are keyed by
|
||||
* (userId, platform) while pointing at `accountId`, so moving an account to
|
||||
* another platform would silently orphan every existing assignment (the
|
||||
* grant would still say "netease" while the account says "qq"). Re-create the
|
||||
* account instead — that path preserves the invariant.
|
||||
*/
|
||||
updateMusicAccount(
|
||||
id: string,
|
||||
patch: Partial<Pick<MusicAccount, "label" | "cookie" | "capacity" | "enabled">>,
|
||||
): boolean;
|
||||
/** Removes the account AND every grant pointing at it (FK cascade). */
|
||||
deleteMusicAccount(id: string): boolean;
|
||||
countMusicAccountGrants(accountId: string): number;
|
||||
listMusicAccountGrants(accountId: string): MusicAccountGrant[];
|
||||
/** Every grant, grouped for the admin overview page. */
|
||||
listAllMusicAccountGrants(): MusicAccountGrant[];
|
||||
/**
|
||||
* Assign `accountId` to `userId`, enforcing enabled/capacity in ONE
|
||||
* transaction so two concurrent assignments cannot both pass the capacity
|
||||
* check and overshoot an exclusive account.
|
||||
*/
|
||||
assignMusicAccount(
|
||||
userId: string,
|
||||
accountId: string,
|
||||
grantedBy: string,
|
||||
):
|
||||
| { ok: true; replacedAccountId: string | null }
|
||||
| { ok: false; reason: "not_found" | "disabled" | "exclusive" | "full" };
|
||||
deleteMusicAccountGrant(userId: string, platform: string, accountId: string): boolean;
|
||||
/** The account an admin assigned to `userId`, or null. Disabled accounts are skipped. */
|
||||
getGrantedMusicAccount(userId: string, platform: string): GrantedMusicAccount | null;
|
||||
// Saved queues (Feature 1) — upsert by (ownerId, name), capped.
|
||||
saveQueue(ownerId: string, name: string, songs: StoredSong[]): SavedQueue;
|
||||
listSavedQueues(ownerId: string, includeShared: boolean): SavedQueueMeta[];
|
||||
@@ -210,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);
|
||||
@@ -355,6 +459,52 @@ function initTables(db: Database.Database): void {
|
||||
PRIMARY KEY (userId, platform),
|
||||
FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- Which login a member wants to use for a platform (#164 follow-up).
|
||||
-- preferShared = 1 means "ignore my own / assigned account and play
|
||||
-- through the bot's shared login", which is how someone whose own account
|
||||
-- has no membership still gets to play paid tracks. Default 0 keeps the
|
||||
-- privacy-first behaviour (own account wins).
|
||||
CREATE TABLE IF NOT EXISTS user_music_prefs (
|
||||
userId TEXT NOT NULL,
|
||||
platform TEXT NOT NULL,
|
||||
preferShared INTEGER NOT NULL DEFAULT 0,
|
||||
updatedAt TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
PRIMARY KEY (userId, platform),
|
||||
FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- Admin-owned music logins that can be handed out to members (#164
|
||||
-- follow-up). Separate from user_music_cookies so a member's own QR login
|
||||
-- and an admin's assignment never overwrite each other.
|
||||
CREATE TABLE IF NOT EXISTS music_accounts (
|
||||
id TEXT PRIMARY KEY,
|
||||
platform TEXT NOT NULL,
|
||||
label TEXT NOT NULL,
|
||||
cookie TEXT NOT NULL,
|
||||
ownerId TEXT,
|
||||
capacity INTEGER NOT NULL DEFAULT 0,
|
||||
enabled INTEGER NOT NULL DEFAULT 1,
|
||||
createdAt TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
updatedAt TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_music_accounts_platform ON music_accounts(platform);
|
||||
|
||||
-- "member X may use account Y". PK (userId, platform) = at most one
|
||||
-- assigned account per platform per member; assigning another replaces it.
|
||||
-- accountId cascade keeps a deleted account from leaving dangling grants.
|
||||
CREATE TABLE IF NOT EXISTS music_account_grants (
|
||||
userId TEXT NOT NULL,
|
||||
platform TEXT NOT NULL,
|
||||
accountId TEXT NOT NULL,
|
||||
grantedBy TEXT NOT NULL,
|
||||
grantedAt TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
PRIMARY KEY (userId, platform),
|
||||
FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (accountId) REFERENCES music_accounts(id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_music_account_grants_accountId
|
||||
ON music_account_grants(accountId);
|
||||
`);
|
||||
}
|
||||
|
||||
@@ -413,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)
|
||||
@@ -491,6 +645,128 @@ export function createDatabase(dbPath: string): BotDatabase {
|
||||
`DELETE FROM user_music_cookies WHERE userId = ? AND platform = ?`,
|
||||
);
|
||||
|
||||
const selectUserMusicPref = db.prepare(
|
||||
`SELECT preferShared FROM user_music_prefs WHERE userId = ? AND platform = ?`,
|
||||
);
|
||||
const upsertUserMusicPref = db.prepare(`
|
||||
INSERT INTO user_music_prefs (userId, platform, preferShared) VALUES (?, ?, ?)
|
||||
ON CONFLICT(userId, platform) DO UPDATE SET preferShared = excluded.preferShared, updatedAt = datetime('now')
|
||||
`);
|
||||
|
||||
// ---- Admin-owned account pool (#164 follow-up) -------------------------
|
||||
const MUSIC_ACCOUNT_GRANT_SELECT = `
|
||||
SELECT g.userId, COALESCE(u.username, g.userId) AS username, g.platform,
|
||||
g.accountId, a.label AS accountLabel, g.grantedBy, g.grantedAt
|
||||
FROM music_account_grants g
|
||||
JOIN music_accounts a ON a.id = g.accountId
|
||||
LEFT JOIN users u ON u.id = g.userId`;
|
||||
|
||||
const selectMusicAccount = db.prepare(`SELECT * FROM music_accounts WHERE id = ?`);
|
||||
const selectMusicAccountsAll = db.prepare(
|
||||
`SELECT * FROM music_accounts ORDER BY platform ASC, createdAt ASC`,
|
||||
);
|
||||
const selectMusicAccountsByPlatform = db.prepare(
|
||||
`SELECT * FROM music_accounts WHERE platform = ? ORDER BY createdAt ASC`,
|
||||
);
|
||||
const insertMusicAccount = db.prepare(`
|
||||
INSERT INTO music_accounts (id, platform, label, cookie, ownerId, capacity, enabled)
|
||||
VALUES (@id, @platform, @label, @cookie, @ownerId, @capacity, @enabled)
|
||||
`);
|
||||
const updateMusicAccountStmt = db.prepare(`
|
||||
UPDATE music_accounts
|
||||
SET platform = @platform, label = @label, cookie = @cookie,
|
||||
capacity = @capacity, enabled = @enabled, updatedAt = datetime('now')
|
||||
WHERE id = @id
|
||||
AND (@capacity = 0 OR @capacity >= (
|
||||
SELECT COUNT(*) FROM music_account_grants WHERE accountId = @id
|
||||
))
|
||||
`);
|
||||
const deleteMusicAccountStmt = db.prepare(`DELETE FROM music_accounts WHERE id = ?`);
|
||||
const countGrantsByAccount = db.prepare(
|
||||
`SELECT COUNT(*) AS c FROM music_account_grants WHERE accountId = ?`,
|
||||
);
|
||||
const selectGrantsByAccount = db.prepare(
|
||||
`${MUSIC_ACCOUNT_GRANT_SELECT} WHERE g.accountId = ? ORDER BY username ASC`,
|
||||
);
|
||||
const selectGrantsAll = db.prepare(
|
||||
`${MUSIC_ACCOUNT_GRANT_SELECT} ORDER BY g.platform ASC, username ASC`,
|
||||
);
|
||||
const upsertGrantStmt = db.prepare(`
|
||||
INSERT INTO music_account_grants (userId, platform, accountId, grantedBy)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(userId, platform) DO UPDATE SET
|
||||
accountId = excluded.accountId,
|
||||
grantedBy = excluded.grantedBy,
|
||||
grantedAt = datetime('now')
|
||||
`);
|
||||
const deleteGrantStmt = db.prepare(
|
||||
`DELETE FROM music_account_grants WHERE userId = ? AND platform = ? AND accountId = ?`,
|
||||
);
|
||||
// A disabled account is invisible to the resolver, so switching it off is an
|
||||
// instant, reversible rollback for everyone holding it (shared login returns).
|
||||
const selectGrantedAccount = db.prepare(`
|
||||
SELECT a.id AS accountId, a.label, a.cookie
|
||||
FROM music_account_grants g
|
||||
JOIN music_accounts a ON a.id = g.accountId
|
||||
WHERE g.userId = ? AND g.platform = ? AND a.enabled = 1
|
||||
`);
|
||||
|
||||
const rowToMusicAccount = (r: Record<string, unknown>): MusicAccount => ({
|
||||
id: String(r.id),
|
||||
platform: String(r.platform),
|
||||
label: String(r.label),
|
||||
cookie: String(r.cookie),
|
||||
ownerId: r.ownerId === null || r.ownerId === undefined ? null : String(r.ownerId),
|
||||
capacity: Number(r.capacity ?? 0),
|
||||
enabled: Number(r.enabled ?? 1) === 1,
|
||||
createdAt: String(r.createdAt ?? ""),
|
||||
updatedAt: String(r.updatedAt ?? ""),
|
||||
});
|
||||
|
||||
const selectGrantForUser = db.prepare(
|
||||
`SELECT accountId FROM music_account_grants WHERE userId = ? AND platform = ?`,
|
||||
);
|
||||
|
||||
/** Row → object lookup shared by the read/update paths (no `this` reliance). */
|
||||
const getAccountById = (id: string): MusicAccount | null => {
|
||||
const row = selectMusicAccount.get(id) as Record<string, unknown> | undefined;
|
||||
return row ? rowToMusicAccount(row) : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Capacity check + grant write in ONE transaction. Reading the holder count
|
||||
* outside the write would let two admins assigning simultaneously both pass
|
||||
* the check and overshoot an exclusive account.
|
||||
*/
|
||||
const assignMusicAccountTx = db.transaction(
|
||||
(
|
||||
userId: string,
|
||||
accountId: string,
|
||||
grantedBy: string,
|
||||
):
|
||||
| { ok: true; replacedAccountId: string | null }
|
||||
| { ok: false; reason: "not_found" | "disabled" | "exclusive" | "full" } => {
|
||||
const row = selectMusicAccount.get(accountId) as Record<string, unknown> | undefined;
|
||||
if (!row) return { ok: false, reason: "not_found" };
|
||||
const account = rowToMusicAccount(row);
|
||||
if (!account.enabled) return { ok: false, reason: "disabled" };
|
||||
|
||||
const existing = selectGrantForUser.get(userId, account.platform) as
|
||||
| { accountId: string }
|
||||
| undefined;
|
||||
// Re-assigning the SAME account is a no-op, not a capacity conflict.
|
||||
if (existing?.accountId === account.id) return { ok: true, replacedAccountId: null };
|
||||
const replacedAccountId = existing ? existing.accountId : null;
|
||||
|
||||
const { c } = countGrantsByAccount.get(account.id) as { c: number };
|
||||
if (account.capacity === 1 && c >= 1) return { ok: false, reason: "exclusive" };
|
||||
if (account.capacity > 1 && c >= account.capacity) return { ok: false, reason: "full" };
|
||||
|
||||
upsertGrantStmt.run(userId, account.platform, account.id, grantedBy);
|
||||
return { ok: true, replacedAccountId };
|
||||
},
|
||||
);
|
||||
|
||||
// A corrupt/hand-edited songs blob must never throw into a route or the
|
||||
// restore path — degrade to an empty list instead.
|
||||
const parseSongs = (raw: string): StoredSong[] => {
|
||||
@@ -563,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,
|
||||
@@ -685,6 +977,98 @@ export function createDatabase(dbPath: string): BotDatabase {
|
||||
return deleteUserMusicCookieStmt.run(userId, platform).changes > 0;
|
||||
},
|
||||
|
||||
getUserMusicPreference(userId, platform) {
|
||||
const row = selectUserMusicPref.get(userId, platform) as
|
||||
| { preferShared: number }
|
||||
| undefined;
|
||||
if (!row) return null;
|
||||
return { preferShared: Number(row.preferShared) === 1 };
|
||||
},
|
||||
|
||||
setUserMusicPreference(userId, platform, preferShared) {
|
||||
upsertUserMusicPref.run(userId, platform, preferShared ? 1 : 0);
|
||||
},
|
||||
|
||||
listMusicAccounts(platform) {
|
||||
const rows = platform
|
||||
? (selectMusicAccountsByPlatform.all(platform) as Record<string, unknown>[])
|
||||
: (selectMusicAccountsAll.all() as Record<string, unknown>[]);
|
||||
return rows.map(rowToMusicAccount);
|
||||
},
|
||||
|
||||
getMusicAccount(id) {
|
||||
return getAccountById(id);
|
||||
},
|
||||
|
||||
createMusicAccount(input) {
|
||||
const id = randomUUID();
|
||||
insertMusicAccount.run({
|
||||
id,
|
||||
platform: input.platform,
|
||||
label: input.label,
|
||||
cookie: input.cookie,
|
||||
ownerId: input.ownerId ?? null,
|
||||
// Clamped so a negative capacity can never slip through and make the
|
||||
// "exclusive" check behave like "unlimited".
|
||||
capacity: Math.max(0, Math.trunc(input.capacity ?? 0)),
|
||||
enabled: input.enabled === false ? 0 : 1,
|
||||
});
|
||||
// No `this` hop: the factory's returned object can be destructured without
|
||||
// losing the lookup.
|
||||
return getAccountById(id)!;
|
||||
},
|
||||
|
||||
updateMusicAccount(id, patch) {
|
||||
const current = getAccountById(id);
|
||||
if (!current) return false;
|
||||
return updateMusicAccountStmt.run({
|
||||
id,
|
||||
// Platform is immutable (see the interface doc): existing grants are
|
||||
// keyed by the OLD platform and would be orphaned by a move.
|
||||
platform: current.platform,
|
||||
label: patch.label ?? current.label,
|
||||
cookie: patch.cookie ?? current.cookie,
|
||||
capacity:
|
||||
patch.capacity === undefined
|
||||
? current.capacity
|
||||
: Math.max(0, Math.trunc(patch.capacity)),
|
||||
enabled: (patch.enabled ?? current.enabled) ? 1 : 0,
|
||||
}).changes > 0;
|
||||
},
|
||||
|
||||
deleteMusicAccount(id) {
|
||||
return deleteMusicAccountStmt.run(id).changes > 0;
|
||||
},
|
||||
|
||||
countMusicAccountGrants(accountId) {
|
||||
const row = countGrantsByAccount.get(accountId) as { c: number } | undefined;
|
||||
return row?.c ?? 0;
|
||||
},
|
||||
|
||||
listMusicAccountGrants(accountId) {
|
||||
return selectGrantsByAccount.all(accountId) as MusicAccountGrant[];
|
||||
},
|
||||
|
||||
listAllMusicAccountGrants() {
|
||||
return selectGrantsAll.all() as MusicAccountGrant[];
|
||||
},
|
||||
|
||||
assignMusicAccount(userId, accountId, grantedBy) {
|
||||
return assignMusicAccountTx(userId, accountId, grantedBy);
|
||||
},
|
||||
|
||||
deleteMusicAccountGrant(userId, platform, accountId) {
|
||||
return deleteGrantStmt.run(userId, platform, accountId).changes > 0;
|
||||
},
|
||||
|
||||
getGrantedMusicAccount(userId, platform) {
|
||||
const row = selectGrantedAccount.get(userId, platform) as
|
||||
| { accountId: string; label: string; cookie: string }
|
||||
| undefined;
|
||||
if (!row || !row.cookie.trim()) return null;
|
||||
return { accountId: row.accountId, label: row.label, cookie: row.cookie };
|
||||
},
|
||||
|
||||
saveQueue(ownerId, name, songs) {
|
||||
if (songs.length > MAX_QUEUE_SONGS) {
|
||||
throw new Error(`保存失败:歌曲数量超过上限 ${MAX_QUEUE_SONGS}`);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -34,7 +34,7 @@ describe("embedded API runtime", () => {
|
||||
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; });
|
||||
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;
|
||||
@@ -74,9 +74,18 @@ describe("embedded API runtime", () => {
|
||||
});
|
||||
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" });
|
||||
|
||||
@@ -34,6 +34,38 @@ export function isApiPortFree(port: number): Promise<boolean> {
|
||||
});
|
||||
}
|
||||
|
||||
/** 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) => {
|
||||
@@ -80,7 +112,10 @@ export async function startEmbeddedApi(provider: ApiProvider, port: number): Pro
|
||||
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))) return { server: null };
|
||||
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!);
|
||||
|
||||
@@ -67,7 +67,7 @@ describe("embedded API child lifecycle", () => {
|
||||
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(); });
|
||||
afterEach(async () => { manager.stop(); await flush(); vi.useRealTimers(); vi.restoreAllMocks(); });
|
||||
|
||||
it("isolates both APIs with ignored stdio, configured ports and IPC", async () => {
|
||||
await manager.start();
|
||||
@@ -87,10 +87,22 @@ describe("embedded API child lifecycle", () => {
|
||||
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"];
|
||||
|
||||
+22
-1
@@ -1,6 +1,6 @@
|
||||
import { fork, type ChildProcess } from "node:child_process";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { getSafeApiStartupError, isApiPortFree, safeApiErrorCode, type ApiProvider, type SafeApiStartupError } from "./api-server-runtime.js";
|
||||
import { getSafeApiStartupError, isApiPortFree, isQqMusicApi, safeApiErrorCode, type ApiProvider, type SafeApiStartupError } from "./api-server-runtime.js";
|
||||
|
||||
export interface ApiServerOptions {
|
||||
neteasePort: number;
|
||||
@@ -13,6 +13,7 @@ export interface ApiServerManager {
|
||||
stop(): void;
|
||||
getNeteaseBaseUrl(): string;
|
||||
getQQMusicBaseUrl(): string;
|
||||
assertQqMusicApiPort(): void;
|
||||
}
|
||||
|
||||
export function describeQqApiStartupError(err: unknown): string | null {
|
||||
@@ -52,6 +53,13 @@ export function createApiServerManager(options: ApiServerOptions, logger: Logger
|
||||
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");
|
||||
@@ -158,16 +166,24 @@ export function createApiServerManager(options: ApiServerOptions, logger: Logger
|
||||
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;
|
||||
}
|
||||
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`);
|
||||
}
|
||||
@@ -191,5 +207,10 @@ export function createApiServerManager(options: ApiServerOptions, logger: Logger
|
||||
},
|
||||
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;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -185,6 +185,11 @@ describe("pickStableAudioUrl (#161 long streams dying mid-play)", () => {
|
||||
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();
|
||||
});
|
||||
|
||||
+40
-16
@@ -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,
|
||||
@@ -51,26 +53,23 @@ 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, else the baseUrl as before.
|
||||
* 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[];
|
||||
}): string | undefined {
|
||||
}, avoidHosts?: ReadonlySet<string>): string | undefined {
|
||||
const primary = stream.baseUrl ?? stream.base_url;
|
||||
const candidates = [primary, ...(stream.backupUrl ?? stream.backup_url ?? [])].filter(
|
||||
(u): u is string => typeof u === "string" && u.length > 0,
|
||||
);
|
||||
const stable = candidates.find((u) => {
|
||||
try {
|
||||
return !BILI_PCDN_HOST.test(new URL(u).hostname);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
return stable ?? primary;
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -361,7 +360,11 @@ export class BiliBiliProvider implements MusicProvider {
|
||||
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> {
|
||||
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;
|
||||
@@ -384,7 +387,7 @@ export class BiliBiliProvider implements MusicProvider {
|
||||
(b.bandwidth ?? 0) > (a.bandwidth ?? 0) ? b : a
|
||||
);
|
||||
|
||||
const biliUrl = pickStableAudioUrl(best);
|
||||
const biliUrl = pickStableAudioUrl(best, options?.avoidHosts);
|
||||
return biliUrl ? { url: biliUrl } : null;
|
||||
} catch {
|
||||
return null;
|
||||
@@ -461,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> {
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import { once } from "node:events";
|
||||
import { createServer } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { normalizeCookie } from "./cookie-normalize.js";
|
||||
import { RiskControlError, SongUrlUnavailable } from "./provider.js";
|
||||
import {
|
||||
parseLyrics,
|
||||
mapNeteaseAlbums,
|
||||
@@ -8,6 +13,64 @@ import {
|
||||
NeteaseProvider,
|
||||
} from "./netease.js";
|
||||
|
||||
describe("NeteaseProvider playback user agent", () => {
|
||||
it("matches the playback UA to each account's platform without changing cookies or other requests", async () => {
|
||||
const requests: URL[] = [];
|
||||
const server = createServer((req, res) => {
|
||||
requests.push(new URL(req.url!, "http://localhost"));
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.end(JSON.stringify({ code: 200, data: [{ url: "https://example.com/song.mp3" }] }));
|
||||
});
|
||||
server.listen(0, "127.0.0.1");
|
||||
await once(server, "listening");
|
||||
try {
|
||||
const provider = new NeteaseProvider(
|
||||
`http://127.0.0.1:${(server.address() as AddressInfo).port}`,
|
||||
);
|
||||
const cases = [
|
||||
["", "NeteaseMusicDesktop"],
|
||||
["MUSIC_U=shared", "NeteaseMusicDesktop"],
|
||||
["MUSIC_U=shared; os=pc", "NeteaseMusicDesktop"],
|
||||
["MUSIC_U=shared; os=android", "Android"],
|
||||
["MUSIC_U=shared; os=android; os=iphone", "iPhone"],
|
||||
["MUSIC_U=shared; os=iphone", "iPhone"],
|
||||
["MUSIC_U=shared; os=linux", "Linux"],
|
||||
["MUSIC_U=shared; os=unknown", "NeteaseMusicDesktop"],
|
||||
["MUSIC_U=shared; os=%69phone", "iPhone"],
|
||||
["MUSIC_U=shared; os=%invalid", "NeteaseMusicDesktop"],
|
||||
];
|
||||
for (const [cookie, uaFamily] of cases) {
|
||||
provider.setCookie(cookie);
|
||||
expect(await provider.getSongUrl("1", "standard")).toMatchObject({ url: "https://example.com/song.mp3" });
|
||||
const params = requests.at(-1)!.searchParams;
|
||||
expect(params.get("ua")).toContain(uaFamily);
|
||||
expect(params.get("level")).toBe("standard");
|
||||
const normalized = normalizeCookie(cookie);
|
||||
expect(params.get("cookie")).toBe(normalized || null);
|
||||
expect(provider.getCookie()).toBe(normalized);
|
||||
}
|
||||
|
||||
provider.setCookie("MUSIC_U=shared; os=pc");
|
||||
const personal = provider.withCookie("MUSIC_U=personal; os=android");
|
||||
await personal.getSongUrl("2");
|
||||
expect(requests.at(-1)!.searchParams.get("ua")).toContain("Android");
|
||||
expect(requests.at(-1)!.searchParams.get("cookie")).toBe("MUSIC_U=personal; os=android");
|
||||
await provider.getSongUrl("3");
|
||||
expect(requests.at(-1)!.searchParams.get("ua")).toContain("NeteaseMusicDesktop");
|
||||
expect(provider.getCookie()).toBe("MUSIC_U=shared; os=pc");
|
||||
|
||||
requests.length = 0;
|
||||
await provider.search("hello");
|
||||
await provider.getQrCode();
|
||||
expect(requests).toHaveLength(6);
|
||||
expect(requests.every((url) => !url.searchParams.has("ua"))).toBe(true);
|
||||
} finally {
|
||||
server.closeAllConnections();
|
||||
await new Promise<void>((resolve, reject) => server.close((err) => err ? reject(err) : resolve()));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("NetEase adapter", () => {
|
||||
it("parses LRC format lyrics", () => {
|
||||
const lrc = `[00:00.00] 作词 : 周杰伦
|
||||
@@ -314,3 +377,184 @@ describe("NeteaseProvider.getArtistAllSongs (全部歌曲 paging)", () => {
|
||||
expect(page.hasMore).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("NetEase quality fallback ladder", () => {
|
||||
it("offers every lower level, best-first, for the default 320k setting", () => {
|
||||
const p = new NeteaseProvider("http://x");
|
||||
// Default quality is exhigh (320k) → 192k then 128k.
|
||||
expect(p.getFallbackQualities()).toEqual(["higher", "standard"]);
|
||||
});
|
||||
|
||||
// The real-world case that produced «点四五次才能播»: a track playable at
|
||||
// 192k while BOTH 320k and 128k return null. Dropping only to the cheapest
|
||||
// level would still fail, so 192k has to be in the list.
|
||||
it("includes intermediate levels, not just the cheapest", () => {
|
||||
const p = new NeteaseProvider("http://x");
|
||||
p.setQuality("lossless");
|
||||
expect(p.getFallbackQualities()).toEqual(["exhigh", "higher", "standard"]);
|
||||
});
|
||||
|
||||
it("has nothing to offer once already at the lowest level", () => {
|
||||
const p = new NeteaseProvider("http://x");
|
||||
p.setQuality("standard");
|
||||
expect(p.getFallbackQualities()).toEqual([]);
|
||||
});
|
||||
|
||||
it("never proposes a level above the configured one", () => {
|
||||
const p = new NeteaseProvider("http://x");
|
||||
p.setQuality("higher");
|
||||
expect(p.getFallbackQualities()).toEqual(["standard"]);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Risk control (-460)
|
||||
//
|
||||
// Live measurement on a cloud host, same song, same second:
|
||||
// GET /song/url/v1?id=1827600686&level=exhigh → 400 {"code":-460}
|
||||
// GET …&cookie=<account cookie> → 200, 320k url
|
||||
// axios reports both 400s and 200s alike as ERR_BAD_REQUEST when it fails, so
|
||||
// the body has to be inspected to know whether retrying is worthwhile.
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("NetEase risk control (-460)", () => {
|
||||
/** Swap the axios instance for a stub — no module mocking needed. */
|
||||
function providerWithApi(get: (url: string, cfg: unknown) => Promise<unknown>) {
|
||||
const p = new NeteaseProvider("http://127.0.0.1:3001");
|
||||
(p as unknown as { api: { get: typeof get } }).api = { get };
|
||||
return p;
|
||||
}
|
||||
|
||||
function httpError(status: number, data: unknown) {
|
||||
const err = new Error(`Request failed with status code ${status}`) as Error & {
|
||||
response: unknown;
|
||||
};
|
||||
err.response = { status, data };
|
||||
return err;
|
||||
}
|
||||
|
||||
it("turns 400 + code -460 into a RiskControlError", async () => {
|
||||
const p = providerWithApi(async () => {
|
||||
throw httpError(400, {
|
||||
code: -460,
|
||||
message: "检测到您的网络环境存在风险,请稍后再试",
|
||||
});
|
||||
});
|
||||
await expect(p.getSongUrl("1827600686")).rejects.toBeInstanceOf(RiskControlError);
|
||||
});
|
||||
|
||||
it("returns a fixed risk-control error without exposing the upstream message", async () => {
|
||||
const p = providerWithApi(async () => {
|
||||
throw httpError(400, { code: -460, message: "upstream sample detail" });
|
||||
});
|
||||
await expect(p.getSongUrl("1827600686")).rejects.toThrow("网易云请求被风控拦截 (-460)");
|
||||
});
|
||||
|
||||
it("does not disguise a genuine bad request", async () => {
|
||||
const p = providerWithApi(async () => {
|
||||
throw httpError(400, { code: 400, msg: "参数错误" });
|
||||
});
|
||||
await expect(p.getSongUrl("1")).rejects.not.toBeInstanceOf(RiskControlError);
|
||||
});
|
||||
|
||||
it("does not disguise an unrelated 400 without a body code", async () => {
|
||||
const p = providerWithApi(async () => {
|
||||
throw httpError(400, "<html>Bad Request</html>");
|
||||
});
|
||||
await expect(p.getSongUrl("1")).rejects.not.toBeInstanceOf(RiskControlError);
|
||||
});
|
||||
|
||||
// A 200 with no url is not "the track does not exist" — it is one of five
|
||||
// different things, and this used to collapse all of them into a bare null.
|
||||
it("names the cause for a 200 that carries no url", async () => {
|
||||
const p = providerWithApi(async () => ({ data: { data: [{ url: null, code: 404 }] } }));
|
||||
await expect(p.getSongUrl("1")).rejects.toMatchObject({
|
||||
failure: { code: "no_copyright" },
|
||||
});
|
||||
});
|
||||
|
||||
it("returns the url and the trial window on success", async () => {
|
||||
const p = providerWithApi(async () => ({
|
||||
data: { data: [{ url: "http://cdn.example/x.mp3", freeTrialInfo: { start: 0, end: 60 } }] },
|
||||
}));
|
||||
const r = await p.getSongUrl("1");
|
||||
expect(r?.url).toBe("http://cdn.example/x.mp3");
|
||||
expect(r?.trialDuration).toBe(60);
|
||||
});
|
||||
|
||||
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 });
|
||||
});
|
||||
});
|
||||
+150
-6
@@ -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,
|
||||
@@ -114,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 },
|
||||
@@ -124,6 +206,29 @@ export const NETEASE_QUALITY_LEVELS = [
|
||||
{ value: "jymaster", label: "超清母带", bitrate: 4000 },
|
||||
] as const;
|
||||
|
||||
function getPlaybackUserAgent(cookie: string): string {
|
||||
let decoded = cookie;
|
||||
try {
|
||||
decoded = decodeURIComponent(cookie);
|
||||
} catch {
|
||||
// A malformed cookie escape must not prevent a playback request.
|
||||
}
|
||||
// The sidecar's cookie parser keeps the last value of a repeated key.
|
||||
const platform = [...decoded.matchAll(/(?:^|;)\s*os\s*=\s*([^;=]*)(?=;|$)/g)].at(-1)?.[1].trim();
|
||||
// NCM API 4.32.0 defaults cookie profiles to PC but eapi's UA to iPhone.
|
||||
// Match its client profiles here, and scope the override to playback only.
|
||||
switch (platform) {
|
||||
case "android":
|
||||
return "NeteaseMusic/9.1.65.240927161425(9001065);Dalvik/2.1.0 (Linux; U; Android 14; 23013RK75C Build/UKQ1.230804.001)";
|
||||
case "iphone":
|
||||
return "NeteaseMusic 9.0.90/5038 (iPhone; iOS 16.2; zh_CN)";
|
||||
case "linux":
|
||||
return "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36";
|
||||
default:
|
||||
return "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Safari/537.36 Chrome/91.0.4472.164 NeteaseMusicDesktop/3.0.18.203152";
|
||||
}
|
||||
}
|
||||
|
||||
export class NeteaseProvider implements MusicProvider {
|
||||
readonly platform = "netease" as const;
|
||||
private api: AxiosInstance;
|
||||
@@ -195,17 +300,54 @@ export class NeteaseProvider implements MusicProvider {
|
||||
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 },
|
||||
@@ -390,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 {
|
||||
|
||||
+128
-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;
|
||||
@@ -113,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>;
|
||||
@@ -134,6 +242,25 @@ export interface MusicProvider {
|
||||
setCookie(cookie: string): void;
|
||||
getCookie(): string;
|
||||
getAuthStatus(): Promise<AuthStatus>;
|
||||
/**
|
||||
* Lower quality levels to try when the configured one has no URL, ordered
|
||||
* best→worst.
|
||||
*
|
||||
* NetEase does not publish a uniform ladder: a track can be playable at 192k
|
||||
* ("higher") while BOTH 320k ("exhigh") and 128k ("standard") return null —
|
||||
* so the list has to contain every level below the current one, not just the
|
||||
* cheapest. Sources whose quality is not a user-selectable knob (Bilibili,
|
||||
* local files, Jellyfin) omit this and the caller keeps its single attempt.
|
||||
*/
|
||||
getFallbackQualities?(): string[];
|
||||
/**
|
||||
* A view of this same provider logged in as another account, without
|
||||
* disturbing the shared instance. Implemented by the sources that support
|
||||
* per-account logins — NetEase since #164, QQ / Kugou / Bilibili following in
|
||||
* the #164 follow-up. The rest simply omit it and the web layer falls back to
|
||||
* the shared login (see web/api/provider-scope.ts).
|
||||
*/
|
||||
withCookie?(cookie: string): MusicProvider;
|
||||
getPersonalFm?(): Promise<Song[]>;
|
||||
getDailyRecommendSongs?(): Promise<Song[]>;
|
||||
getUserPlaylists?(): Promise<Playlist[]>;
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const { get, post } = vi.hoisted(() => ({ get: vi.fn(), post: vi.fn() }));
|
||||
vi.mock("axios", () => ({ default: { create: () => ({ get, post }), isAxiosError: () => false } }));
|
||||
|
||||
import { createQqLoginClient, parseQqCredential } from "./qq-login.js";
|
||||
|
||||
const credential = {
|
||||
musicid: 12345, musickey: "test-music-key", openid: "test-openid", access_token: "test-access",
|
||||
refresh_token: "test-token", refresh_key: "test-refresh", expired_at: 1234,
|
||||
musickeyCreateTime: 5678, keyExpiresIn: 3600,
|
||||
};
|
||||
|
||||
describe("QQ login transport", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
it("accepts the QQ QR image when Tencent omits its content type", async () => {
|
||||
get.mockResolvedValueOnce({
|
||||
data: Buffer.from("89504e470d0a1a0a", "hex"),
|
||||
headers: { "set-cookie": ["qrsig=test-sig; Path=/"] },
|
||||
});
|
||||
expect(await createQqLoginClient().getQr()).toMatchObject({
|
||||
img: "data:image/png;base64,iVBORw0KGgo=", sig: "test-sig",
|
||||
});
|
||||
});
|
||||
|
||||
it("exchanges a confirmed QR for the full JSON credential", async () => {
|
||||
get
|
||||
.mockResolvedValueOnce({
|
||||
data: "ptuiCB('0','0','https://ssl.ptlogin2.graph.qq.com/check_sig?uin=12345&ptsigx=sigx','0','','');",
|
||||
})
|
||||
.mockResolvedValueOnce({ headers: { "set-cookie": ["p_skey=test==; Path=/; Secure"] } });
|
||||
post
|
||||
.mockResolvedValueOnce({ headers: { location: "https://y.qq.com/portal/wx_redirect.html?code=example&state=state" } })
|
||||
.mockResolvedValueOnce({
|
||||
headers: {},
|
||||
data: { code: 0, req_0: { code: 0, data: { ...credential, loginType: 2 } } },
|
||||
});
|
||||
expect(await createQqLoginClient().pollQr("test-sig")).toEqual({ status: "confirmed", credential });
|
||||
expect(post).toHaveBeenNthCalledWith(
|
||||
1, "https://graph.qq.com/oauth2.0/authorize", expect.any(URLSearchParams),
|
||||
expect.objectContaining({ headers: { Cookie: "p_skey=test==" } }),
|
||||
);
|
||||
expect(post).toHaveBeenNthCalledWith(
|
||||
2, "https://u.y.qq.com/cgi-bin/musicu.fcg",
|
||||
expect.objectContaining({
|
||||
req_0: { module: "QQConnectLogin.LoginServer", method: "QQLogin", param: { code: "example" } },
|
||||
}),
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
it("sends the login type 2 refresh payload and validates the CGI status", async () => {
|
||||
post.mockResolvedValue({
|
||||
headers: {},
|
||||
data: { code: 0, req_0: { code: 104604, data: { ...credential, musickey: "do-not-use" } } },
|
||||
});
|
||||
expect(await createQqLoginClient().refresh(credential)).toEqual({ status: "rate_limited" });
|
||||
expect(post).toHaveBeenCalledWith(
|
||||
"https://u.y.qq.com/cgi-bin/musicu.fcg",
|
||||
expect.objectContaining({
|
||||
comm: expect.objectContaining({ tmeLoginType: "2" }),
|
||||
req_0: {
|
||||
module: "music.login.LoginServer", method: "Login",
|
||||
param: {
|
||||
loginMode: 2, musicid: 12345, musickey: "test-music-key", openid: "test-openid",
|
||||
access_token: "test-access", refresh_token: "test-token", refresh_key: "test-refresh", expired_in: 1234,
|
||||
},
|
||||
},
|
||||
}),
|
||||
expect.anything(),
|
||||
);
|
||||
post.mockResolvedValueOnce({ headers: {}, data: { code: 104401 } });
|
||||
expect(await createQqLoginClient().refresh(credential)).toEqual({ status: "reauth_required" });
|
||||
post.mockResolvedValueOnce({ headers: {}, data: { code: 0, req_0: { code: 0, data: { musicid: 12345 } } } });
|
||||
expect(await createQqLoginClient().refresh(credential)).toEqual({ status: "upstream_error" });
|
||||
});
|
||||
|
||||
it("accepts playback-only QQ credentials and rejects other types or invalid keys", () => {
|
||||
expect(parseQqCredential({ str_musicid: "12345", musickey: "music-key" })).toMatchObject({
|
||||
musicid: 12345, musickey: "music-key", refresh_key: "",
|
||||
});
|
||||
expect(parseQqCredential({ ...credential, loginType: 1 })).toBeUndefined();
|
||||
expect(parseQqCredential({ ...credential, musickey: "music-key\r\n" })).toBeUndefined();
|
||||
});
|
||||
|
||||
it("keeps unchanged OAuth fields when QQ returns a partial rotation for the same account", async () => {
|
||||
post.mockResolvedValueOnce({
|
||||
headers: {},
|
||||
data: { code: 0, req_0: { code: 0, data: {
|
||||
musicid: 12345, musickey: "rotated-key", refresh_token: "rotated-token",
|
||||
} } },
|
||||
});
|
||||
expect(await createQqLoginClient().refresh(credential)).toMatchObject({
|
||||
status: "refreshed",
|
||||
credential: {
|
||||
musicid: 12345, musickey: "rotated-key", refresh_token: "rotated-token",
|
||||
openid: credential.openid, access_token: credential.access_token,
|
||||
musickeyCreateTime: 0, keyExpiresIn: 0,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("fills missing expiration fields only for the same account and playback key", async () => {
|
||||
const sameKey = { musicid: credential.musicid, musickey: credential.musickey, refresh_token: "rotated-token" };
|
||||
post.mockResolvedValueOnce({
|
||||
headers: {},
|
||||
data: { code: 0, req_0: { code: 0, data: sameKey } },
|
||||
});
|
||||
expect(await createQqLoginClient().refresh(credential)).toMatchObject({
|
||||
status: "refreshed",
|
||||
credential: { refresh_token: "rotated-token", musickeyCreateTime: 5678, keyExpiresIn: 3600 },
|
||||
});
|
||||
expect(parseQqCredential({ ...sameKey, keyExpiresIn: 7200 }, credential)).toMatchObject({
|
||||
musickeyCreateTime: 5678, keyExpiresIn: 7200,
|
||||
});
|
||||
expect(parseQqCredential({ ...sameKey, musicid: 999 }, credential)).toMatchObject({
|
||||
musickeyCreateTime: 0, keyExpiresIn: 0,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,229 @@
|
||||
import axios from "axios";
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
export interface QqCredential {
|
||||
musicid: number;
|
||||
musickey: string;
|
||||
openid: string;
|
||||
access_token: string;
|
||||
refresh_token: string;
|
||||
refresh_key: string;
|
||||
expired_at: number;
|
||||
musickeyCreateTime: number;
|
||||
keyExpiresIn: number;
|
||||
}
|
||||
|
||||
export type QqPollResult =
|
||||
| { status: "waiting" | "scanned" | "expired" }
|
||||
| { status: "confirmed"; credential: QqCredential };
|
||||
|
||||
export type QqRefreshResult =
|
||||
| { status: "refreshed"; credential: QqCredential }
|
||||
| { status: "reauth_required" | "rate_limited" | "upstream_error" };
|
||||
|
||||
export interface QqLoginClient {
|
||||
getQr(): Promise<{ img: string; sig: string }>;
|
||||
pollQr(sig: string): Promise<QqPollResult>;
|
||||
refresh(credential: QqCredential): Promise<QqRefreshResult>;
|
||||
}
|
||||
|
||||
const QR_HOST = "https://ssl.ptlogin2.qq.com";
|
||||
const REFERER = "https://xui.ptlogin2.qq.com/";
|
||||
const QQ_JUMP = "https://graph.qq.com/oauth2.0/login_jump";
|
||||
const MUSIC_REDIRECT = "https://y.qq.com/portal/wx_redirect.html";
|
||||
const APP_ID = "100497308";
|
||||
const LOGIN_SCOPE = { daid: "383", pt_3rd_aid: APP_ID };
|
||||
const AUTH_REJECTED = new Set([1000, 104400, 104401, 20261, 20272, 20274, 20277, 20278, 20279, 20450]);
|
||||
|
||||
function record(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
? value as Record<string, unknown> : {};
|
||||
}
|
||||
|
||||
function token(value: unknown): string {
|
||||
return typeof value === "string" && /^[\x21-\x3a\x3c-\x7e]+$/.test(value) ? value : "";
|
||||
}
|
||||
|
||||
function positiveInt(value: unknown): number {
|
||||
const n = typeof value === "string" && /^\d+$/.test(value) ? Number(value) : value;
|
||||
return typeof n === "number" && Number.isSafeInteger(n) && n > 0 ? n : 0;
|
||||
}
|
||||
|
||||
export function parseQqCredential(value: unknown, previous?: QqCredential): QqCredential | undefined {
|
||||
const data = record(value);
|
||||
const type = data.loginType ?? data.login_type;
|
||||
if (type !== undefined && type !== 2 && type !== "2") return;
|
||||
const musicid = positiveInt(data.musicid) || positiveInt(data.str_musicid);
|
||||
const musickey = token(data.musickey);
|
||||
if (!musicid || !musickey) return;
|
||||
const sameAccount = previous?.musicid === musicid ? previous : undefined;
|
||||
const sameKey = sameAccount?.musickey === musickey ? sameAccount : undefined;
|
||||
return {
|
||||
musicid,
|
||||
musickey,
|
||||
openid: token(data.openid ?? sameAccount?.openid),
|
||||
access_token: token(data.access_token ?? sameAccount?.access_token),
|
||||
refresh_token: token(data.refresh_token ?? sameAccount?.refresh_token),
|
||||
refresh_key: token(data.refresh_key),
|
||||
expired_at: positiveInt(data.expired_at ?? sameAccount?.expired_at),
|
||||
musickeyCreateTime: positiveInt(data.musickeyCreateTime ?? sameKey?.musickeyCreateTime),
|
||||
keyExpiresIn: positiveInt(data.keyExpiresIn ?? sameKey?.keyExpiresIn),
|
||||
};
|
||||
}
|
||||
|
||||
export function hasQqRenewalMaterial(credential?: QqCredential): credential is QqCredential {
|
||||
// QQ's web QR flow may return OAuth tokens without a separate refresh key.
|
||||
return Boolean(credential?.refresh_key || (credential?.openid && credential.access_token && credential.refresh_token));
|
||||
}
|
||||
|
||||
export function qqPlaybackCookie({ musicid, musickey }: QqCredential): string {
|
||||
return `uin=${musicid}; qqmusic_uin=${musicid}; qm_keyst=${musickey}; qqmusic_key=${musickey}; login_type=2; tmeLoginType=2`;
|
||||
}
|
||||
|
||||
function hash33(value: string, seed: number): number {
|
||||
let hash = seed;
|
||||
for (let i = 0; i < value.length; i++) hash = (hash * 33 + value.charCodeAt(i)) | 0;
|
||||
return hash & 0x7fffffff;
|
||||
}
|
||||
|
||||
function setCookies(headers: string[] = []): Map<string, string> {
|
||||
const cookies = new Map<string, string>();
|
||||
for (const header of headers) {
|
||||
const pair = header.split(";", 1)[0];
|
||||
const equals = pair.indexOf("=");
|
||||
if (equals < 1) continue;
|
||||
const value = token(pair.slice(equals + 1));
|
||||
if (value) cookies.set(pair.slice(0, equals), value);
|
||||
}
|
||||
return cookies;
|
||||
}
|
||||
|
||||
function cookieHeader(cookies: Map<string, string>): string {
|
||||
return Array.from(cookies, ([key, value]) => `${key}=${value}`).join("; ");
|
||||
}
|
||||
|
||||
export function createQqLoginClient(): QqLoginClient {
|
||||
const http = axios.create({ timeout: 10_000, maxRedirects: 0 });
|
||||
|
||||
// QQMusicApi's web CGI profile. Keep authorization fields in the HTTPS body.
|
||||
async function musicu(module: string, method: string, param: object, credential?: QqCredential) {
|
||||
const gTk = String(hash33(credential?.musickey ?? "", 5381));
|
||||
const res = await http.post("https://u.y.qq.com/cgi-bin/musicu.fcg", {
|
||||
comm: {
|
||||
ct: "24", cv: "4747474", platform: "yqq.json", chid: "0",
|
||||
uin: String(credential?.musicid ?? 0), g_tk: gTk, g_tk_new_20200303: gTk,
|
||||
format: "json", inCharset: "utf-8", outCharset: "utf-8", notice: "0",
|
||||
need_new_code: "1", tmeLoginType: "2",
|
||||
},
|
||||
req_0: { module, method, param },
|
||||
}, { headers: { Referer: "https://y.qq.com/" } });
|
||||
const body = record(res.data);
|
||||
const item = record(body.req_0);
|
||||
return { code: body.code === 0 ? item.code : body.code, data: item.data, cookies: setCookies(res.headers["set-cookie"]) };
|
||||
}
|
||||
|
||||
async function authorize(redirect: string): Promise<QqCredential | undefined> {
|
||||
const url = new URL(redirect);
|
||||
const uin = url.searchParams.get("uin");
|
||||
const sigx = url.searchParams.get("ptsigx");
|
||||
if (!uin || !/^\d+$/.test(uin) || !sigx) return;
|
||||
const noFollow = (status: number) => status >= 200 && status < 400;
|
||||
const checked = await http.get("https://ssl.ptlogin2.graph.qq.com/check_sig", {
|
||||
params: {
|
||||
...LOGIN_SCOPE, uin, ptsigx: sigx, pttype: "1", service: "ptqrlogin",
|
||||
nodirect: "0", s_url: QQ_JUMP, ptlang: "2052", ptredirect: "100",
|
||||
aid: "716027609", j_later: "0", low_login_hour: "0", regmaster: "0",
|
||||
pt_login_type: "3", pt_aid: "0", pt_aaid: "16", pt_light: "0",
|
||||
},
|
||||
headers: { Referer: REFERER },
|
||||
validateStatus: noFollow,
|
||||
});
|
||||
const cookies = setCookies(checked.headers["set-cookie"]);
|
||||
const pSkey = cookies.get("p_skey");
|
||||
if (!pSkey) return;
|
||||
|
||||
const authorized = await http.post("https://graph.qq.com/oauth2.0/authorize", new URLSearchParams({
|
||||
response_type: "code", client_id: APP_ID, redirect_uri: `${MUSIC_REDIRECT}?login_type=1&surl=https://y.qq.com/`,
|
||||
scope: "get_user_info,get_app_friends", state: "state", switch: "",
|
||||
from_ptlogin: "1", src: "1", update_auth: "1", openapi: "1010_1030",
|
||||
g_tk: String(hash33(pSkey, 5381)), auth_time: String(Date.now()), ui: randomUUID(),
|
||||
}), { headers: { Cookie: cookieHeader(cookies) }, validateStatus: noFollow });
|
||||
if (typeof authorized.headers.location !== "string") return;
|
||||
const callback = new URL(authorized.headers.location);
|
||||
if (callback.origin + callback.pathname !== MUSIC_REDIRECT) return;
|
||||
const code = callback.searchParams.get("code");
|
||||
if (!code) return;
|
||||
|
||||
const result = await musicu("QQConnectLogin.LoginServer", "QQLogin", { code });
|
||||
if (result.code !== 0) return;
|
||||
return parseQqCredential(result.data) ?? parseQqCredential({
|
||||
musicid: result.cookies.get("qqmusic_uin") ?? uin,
|
||||
musickey: result.cookies.get("qqmusic_key") ?? result.cookies.get("qm_keyst"),
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
async getQr() {
|
||||
try {
|
||||
const res = await http.get(`${QR_HOST}/ptqrshow`, {
|
||||
params: { ...LOGIN_SCOPE, appid: "716027609", e: "2", l: "M", s: "3", d: "72", v: "4", t: Math.random() },
|
||||
headers: { Referer: REFERER },
|
||||
responseType: "arraybuffer",
|
||||
});
|
||||
const sig = setCookies(res.headers["set-cookie"]).get("qrsig");
|
||||
// Tencent can send the PNG without a Content-Type header.
|
||||
const bytes = Buffer.from(res.data);
|
||||
const isPng = bytes.subarray(0, 8).toString("hex") === "89504e470d0a1a0a";
|
||||
const isJpeg = bytes.subarray(0, 3).toString("hex") === "ffd8ff";
|
||||
if (sig && (isPng || isJpeg)) {
|
||||
return { img: `data:image/${isPng ? "png" : "jpeg"};base64,${bytes.toString("base64")}`, sig };
|
||||
}
|
||||
} catch { /* Do not expose the request or response. */ }
|
||||
throw new Error("QQ QR code unavailable");
|
||||
},
|
||||
async pollQr(sig) {
|
||||
let response: string;
|
||||
try {
|
||||
const res = await http.get<string>(`${QR_HOST}/ptqrlogin`, {
|
||||
params: {
|
||||
...LOGIN_SCOPE, u1: QQ_JUMP, ptqrtoken: hash33(sig, 0), ptredirect: "0",
|
||||
h: "1", t: "1", g: "1", from_ui: "1", ptlang: "2052",
|
||||
action: `0-0-${Date.now()}`, js_ver: "20102616", js_type: "1",
|
||||
pt_uistyle: "40", aid: "716027609", has_onekey: "1",
|
||||
},
|
||||
headers: { Referer: REFERER, Cookie: `qrsig=${sig}` },
|
||||
responseType: "text",
|
||||
});
|
||||
response = res.data;
|
||||
} catch { return { status: "waiting" }; }
|
||||
|
||||
const fields = /^\s*ptuiCB\((.*)\)/.exec(response)?.[1].match(/'((?:\\.|[^'])*)'/g);
|
||||
const code = fields?.[0]?.slice(1, -1);
|
||||
if (code === "66") return { status: "waiting" };
|
||||
if (code === "67") return { status: "scanned" };
|
||||
if (code === "0" && fields?.[2]) {
|
||||
try {
|
||||
const credential = await authorize(fields[2].slice(1, -1));
|
||||
if (credential) return { status: "confirmed", credential };
|
||||
} catch { /* A used QR cannot safely replay the authorization code. */ }
|
||||
}
|
||||
return { status: "expired" };
|
||||
},
|
||||
async refresh(credential) {
|
||||
const { openid, access_token, refresh_token, expired_at, musicid, musickey, refresh_key } = credential;
|
||||
try {
|
||||
const result = await musicu("music.login.LoginServer", "Login", {
|
||||
openid, access_token, refresh_token, expired_in: expired_at, musicid, musickey, refresh_key, loginMode: 2,
|
||||
}, credential);
|
||||
const code = Number(result.code);
|
||||
if (code === 104604 || code === 2001) return { status: "rate_limited" };
|
||||
if (AUTH_REJECTED.has(code)) return { status: "reauth_required" };
|
||||
const next = result.code === 0 ? parseQqCredential(result.data, credential) : undefined;
|
||||
if (next) return { status: "refreshed", credential: next };
|
||||
} catch (err) {
|
||||
if (axios.isAxiosError(err) && err.response?.status === 429) return { status: "rate_limited" };
|
||||
}
|
||||
return { status: "upstream_error" };
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import pino from "pino";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { createCookieStore } from "./auth.js";
|
||||
import { parseQqCredential, qqPlaybackCookie, type QqCredential, type QqLoginClient, type QqRefreshResult } from "./qq-login.js";
|
||||
import { createQqSessionStore, QQManagedSession } from "./qq-session.js";
|
||||
|
||||
const NOW = new Date("2026-11-09T00:00:00.000Z");
|
||||
const MINUTE = 60_000;
|
||||
const DAY = 24 * 60 * MINUTE;
|
||||
const first: QqCredential = {
|
||||
musicid: 123456, musickey: "first-key", refresh_key: "first-refresh",
|
||||
openid: "test-openid", access_token: "test-access", refresh_token: "test-refresh",
|
||||
expired_at: 123, musickeyCreateTime: NOW.valueOf() / 1000, keyExpiresIn: 3 * DAY / 1000,
|
||||
};
|
||||
const second = { ...first, musickey: "second-key", refresh_key: "second-refresh" };
|
||||
|
||||
describe("managed QQ session", () => {
|
||||
let dir: string;
|
||||
let file: string;
|
||||
let store: ReturnType<typeof createQqSessionStore>;
|
||||
let client: QqLoginClient;
|
||||
let session: QQManagedSession;
|
||||
const logger = pino({ level: "silent" });
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(NOW);
|
||||
dir = fs.mkdtempSync(path.join(os.tmpdir(), "tsbot-qq-"));
|
||||
file = path.join(dir, "qq-session.json");
|
||||
store = createQqSessionStore(file);
|
||||
client = {
|
||||
getQr: vi.fn().mockResolvedValue({ img: "test-image", sig: "private-qr-sig" }),
|
||||
pollQr: vi.fn().mockResolvedValue({ status: "confirmed", credential: first }),
|
||||
refresh: vi.fn().mockResolvedValue({ status: "refreshed", credential: second }),
|
||||
};
|
||||
session = new QQManagedSession(client, store, logger);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
session.stop();
|
||||
vi.useRealTimers();
|
||||
fs.rmSync(file, { force: true });
|
||||
fs.rmSync(path.join(dir, "qq.json"), { force: true });
|
||||
fs.rmdirSync(dir);
|
||||
});
|
||||
|
||||
async function scan() {
|
||||
const qr = await session.getQrCode();
|
||||
expect(qr.key).not.toContain("private-qr-sig");
|
||||
expect(await Promise.all([
|
||||
session.checkQrCodeStatus(qr.key),
|
||||
session.checkQrCodeStatus(qr.key),
|
||||
])).toEqual(["confirmed", "confirmed"]);
|
||||
expect(client.pollQr).toHaveBeenCalledTimes(1);
|
||||
}
|
||||
|
||||
it("persists the scan, refreshes after 24 hours and keeps the next due date across restarts", async () => {
|
||||
await scan();
|
||||
expect(store.load()?.credential).toEqual(first);
|
||||
if (process.platform !== "win32") expect(fs.statSync(file).mode & 0o777).toBe(0o600);
|
||||
expect(session.getStatus()).toEqual({
|
||||
renewalStatus: "scheduled",
|
||||
nextRefreshAt: new Date(NOW.valueOf() + DAY).toISOString(),
|
||||
lastRefreshAt: null,
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(DAY / 2);
|
||||
session.stop();
|
||||
session = new QQManagedSession(client, store, logger);
|
||||
await vi.advanceTimersByTimeAsync(DAY / 2 - 1);
|
||||
expect(client.refresh).not.toHaveBeenCalled();
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(client.refresh).toHaveBeenCalledWith(first);
|
||||
expect(store.load()?.credential).toEqual(second);
|
||||
expect(session.getCookie()).toContain("qm_keyst=second-key");
|
||||
expect(store.load()?.lastRefreshAt).toBe(NOW.valueOf() + DAY);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(DAY / 2);
|
||||
session.stop();
|
||||
session = new QQManagedSession(client, store, logger);
|
||||
expect(session.getStatus()).toEqual({
|
||||
renewalStatus: "scheduled",
|
||||
nextRefreshAt: new Date(NOW.valueOf() + 2 * DAY).toISOString(),
|
||||
lastRefreshAt: new Date(NOW.valueOf() + DAY).toISOString(),
|
||||
});
|
||||
});
|
||||
|
||||
it("renews before expiry when a QQ key lasts less than one day", async () => {
|
||||
const shortLived = { ...first, keyExpiresIn: 3600 };
|
||||
vi.mocked(client.pollQr).mockResolvedValueOnce({ status: "confirmed", credential: shortLived });
|
||||
await scan();
|
||||
await vi.advanceTimersByTimeAsync(54 * MINUTE - 1);
|
||||
expect(client.refresh).not.toHaveBeenCalled();
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(client.refresh).toHaveBeenCalledWith(shortLived);
|
||||
});
|
||||
|
||||
it("keeps scheduling before expiry after a same-key token rotation", async () => {
|
||||
const shortLived = { ...first, keyExpiresIn: 3600 };
|
||||
vi.mocked(client.pollQr).mockResolvedValueOnce({ status: "confirmed", credential: shortLived });
|
||||
await scan();
|
||||
vi.setSystemTime(NOW.valueOf() + 54 * MINUTE);
|
||||
const rotated = parseQqCredential({
|
||||
musicid: first.musicid, musickey: first.musickey, refresh_token: "rotated-token",
|
||||
}, shortLived)!;
|
||||
vi.mocked(client.refresh).mockResolvedValueOnce({ status: "refreshed", credential: rotated });
|
||||
|
||||
expect(await session.refresh()).toBe("refreshed");
|
||||
expect(store.load()?.credential?.refresh_token).toBe("rotated-token");
|
||||
expect(session.getStatus().nextRefreshAt).toBe(new Date(NOW.valueOf() + 55 * MINUTE).toISOString());
|
||||
});
|
||||
|
||||
it("schedules older saved sessions using QQ's issue time without inventing a last renewal", () => {
|
||||
const older = { ...first, musickeyCreateTime: (NOW.valueOf() - DAY / 2) / 1000 };
|
||||
store.save({ cookie: qqPlaybackCookie(older), credential: older });
|
||||
session.stop();
|
||||
session = new QQManagedSession(client, store, logger);
|
||||
expect(session.getStatus()).toEqual({
|
||||
renewalStatus: "scheduled",
|
||||
nextRefreshAt: new Date(NOW.valueOf() + DAY / 2).toISOString(),
|
||||
lastRefreshAt: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("shares an in-flight refresh and uses the rotated credential after restart", async () => {
|
||||
await scan();
|
||||
const a = session.refresh();
|
||||
expect(session.refresh()).toBe(a);
|
||||
expect(await a).toBe("refreshed");
|
||||
expect(client.refresh).toHaveBeenCalledTimes(1);
|
||||
session.stop();
|
||||
session = new QQManagedSession(client, store, logger);
|
||||
vi.mocked(client.refresh).mockResolvedValueOnce({
|
||||
status: "refreshed", credential: { ...second, musickey: "third-key" },
|
||||
});
|
||||
expect(await session.refresh()).toBe("refreshed");
|
||||
expect(client.refresh).toHaveBeenLastCalledWith(second);
|
||||
expect(session.getCookie()).toContain("qm_keyst=third-key");
|
||||
});
|
||||
|
||||
it("refreshes a web login with OAuth authorization even when QQ omits refresh_key", async () => {
|
||||
const webCredential = { ...first, refresh_key: "" };
|
||||
vi.mocked(client.pollQr).mockResolvedValueOnce({ status: "confirmed", credential: webCredential });
|
||||
await scan();
|
||||
expect(session.getStatus().renewalStatus).toBe("scheduled");
|
||||
expect(await session.refresh()).toBe("refreshed");
|
||||
expect(client.refresh).toHaveBeenCalledWith(webCredential);
|
||||
});
|
||||
|
||||
it("keeps the current cookie on rate limiting and retries after the backoff", async () => {
|
||||
await scan();
|
||||
vi.mocked(client.refresh).mockResolvedValueOnce({ status: "rate_limited" });
|
||||
expect(await session.refresh()).toBe("rate_limited");
|
||||
expect(session.getStatus()).toMatchObject({ renewalStatus: "retrying" });
|
||||
expect(await session.refresh()).toBe("cooldown");
|
||||
expect(store.load()?.credential).toEqual(first);
|
||||
await vi.advanceTimersByTimeAsync(15 * MINUTE);
|
||||
expect(client.refresh).toHaveBeenCalledTimes(2);
|
||||
expect(store.load()?.credential).toEqual(second);
|
||||
});
|
||||
|
||||
it("retries only the disk write when QQ has already rotated the credential", async () => {
|
||||
await scan();
|
||||
vi.spyOn(store, "save").mockImplementationOnce(() => { throw new Error("test write failed"); });
|
||||
expect(await session.refresh()).toBe("persist_failed");
|
||||
expect(session.getCookie()).toContain("qm_keyst=first-key");
|
||||
expect(session.getStatus().lastRefreshAt).toBeNull();
|
||||
await vi.advanceTimersByTimeAsync(5 * MINUTE);
|
||||
expect(client.refresh).toHaveBeenCalledTimes(1);
|
||||
expect(store.load()?.credential).toEqual(second);
|
||||
expect(session.getCookie()).toContain("qm_keyst=second-key");
|
||||
expect(session.getStatus().lastRefreshAt).toBe(new Date(NOW.valueOf() + 5 * MINUTE).toISOString());
|
||||
});
|
||||
|
||||
it("discards a late response when an operator imports another account", async () => {
|
||||
await scan();
|
||||
let resolve!: (response: QqRefreshResult) => void;
|
||||
vi.mocked(client.refresh).mockImplementationOnce(() => new Promise((done) => { resolve = done; }));
|
||||
const refresh = session.refresh();
|
||||
session.setCookie("uin=999; qm_keyst=manual");
|
||||
resolve({ status: "refreshed", credential: second });
|
||||
expect(await refresh).toBe("superseded");
|
||||
expect(store.load()).toMatchObject({ cookie: "uin=999; qm_keyst=manual" });
|
||||
expect(store.load()?.credential).toBeUndefined();
|
||||
expect(await session.refresh()).toBe("reauth_required");
|
||||
});
|
||||
|
||||
it("does not accept another account from the upstream refresh endpoint", async () => {
|
||||
await scan();
|
||||
vi.mocked(client.refresh).mockResolvedValueOnce({
|
||||
status: "refreshed", credential: { ...second, musicid: 999 },
|
||||
});
|
||||
expect(await session.refresh()).toBe("upstream_error");
|
||||
expect(store.load()?.credential).toEqual(first);
|
||||
});
|
||||
|
||||
it("persists a suspension when QQ explicitly rejects renewal", async () => {
|
||||
await scan();
|
||||
vi.mocked(client.refresh).mockResolvedValueOnce({ status: "reauth_required" });
|
||||
expect(await session.refresh()).toBe("reauth_required");
|
||||
session.stop();
|
||||
session = new QQManagedSession(client, store, logger);
|
||||
expect(session.getStatus()).toEqual({ renewalStatus: "reauth_required", nextRefreshAt: null, lastRefreshAt: null });
|
||||
expect(await session.refresh()).toBe("reauth_required");
|
||||
expect(client.refresh).toHaveBeenCalledTimes(1);
|
||||
expect(session.getCookie()).toContain("qm_keyst=first-key");
|
||||
});
|
||||
|
||||
it("preserves a legacy cookie and renews daily even when QQ omits the key expiration", async () => {
|
||||
createCookieStore(dir).save("qq", "uin=123; qm_keyst=legacy");
|
||||
session.stop();
|
||||
store = createQqSessionStore(file, path.join(dir, "qq.json"));
|
||||
session = new QQManagedSession(client, store, logger);
|
||||
expect(session.getCookie()).toContain("qm_keyst=legacy");
|
||||
expect(session.getStatus()).toEqual({ renewalStatus: "cookie_only", nextRefreshAt: null, lastRefreshAt: null });
|
||||
expect(fs.existsSync(file)).toBe(false);
|
||||
vi.mocked(client.pollQr).mockResolvedValueOnce({
|
||||
status: "confirmed", credential: { ...first, musickeyCreateTime: 0, keyExpiresIn: 0 },
|
||||
});
|
||||
await scan();
|
||||
expect(session.getStatus()).toMatchObject({
|
||||
renewalStatus: "scheduled",
|
||||
nextRefreshAt: new Date(NOW.valueOf() + DAY).toISOString(),
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(DAY);
|
||||
expect(client.refresh).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("shares the current login across managed and unmanaged restarts", async () => {
|
||||
const legacyFile = path.join(dir, "qq.json");
|
||||
store = createQqSessionStore(file, legacyFile);
|
||||
session.stop();
|
||||
session = new QQManagedSession(client, store, logger);
|
||||
await scan();
|
||||
session.stop();
|
||||
|
||||
const cookies = createCookieStore(dir, store);
|
||||
expect(cookies.load("qq")).toBe(qqPlaybackCookie(first));
|
||||
cookies.save("qq", "uin=999; qm_keyst=imported");
|
||||
session = new QQManagedSession(client, createQqSessionStore(file, legacyFile), logger);
|
||||
expect(session.getCookie()).toBe("uin=999; qm_keyst=imported");
|
||||
expect(await session.refresh()).toBe("reauth_required");
|
||||
expect(client.refresh).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("normalises manual cookies in memory and at the shared session store", () => {
|
||||
const raw = "Set-Cookie: uin=999; Path=/\r\nSet-Cookie: qm_keyst=manual; Secure";
|
||||
const expected = "uin=999; qm_keyst=manual";
|
||||
session.setCookie(raw);
|
||||
expect(session.getCookie()).toBe(expected);
|
||||
expect(store.load()?.cookie).toBe(expected);
|
||||
createCookieStore(dir, store).save("qq", raw);
|
||||
expect(store.load()?.cookie).toBe(expected);
|
||||
});
|
||||
|
||||
it("normalises cookies migrated from old installations", () => {
|
||||
const legacyFile = path.join(dir, "qq.json");
|
||||
const raw = "uin=999; Path=/;;qm_keyst=legacy; Secure";
|
||||
fs.writeFileSync(legacyFile, JSON.stringify({ cookie: raw }));
|
||||
store = createQqSessionStore(file, legacyFile);
|
||||
expect(store.load()).toEqual({ cookie: "uin=999; qm_keyst=legacy" });
|
||||
});
|
||||
|
||||
it("uses the newer login when both older session files already exist", () => {
|
||||
const legacyFile = path.join(dir, "qq.json");
|
||||
const legacyCookie = "uin=999; qm_keyst=legacy";
|
||||
fs.writeFileSync(file, JSON.stringify({ version: 1, cookie: qqPlaybackCookie(first), credential: first }));
|
||||
createCookieStore(dir).save("qq", legacyCookie);
|
||||
fs.utimesSync(file, 1, 1);
|
||||
fs.utimesSync(legacyFile, 2, 2);
|
||||
store = createQqSessionStore(file, legacyFile);
|
||||
expect(store.load()).toEqual({ cookie: legacyCookie });
|
||||
|
||||
fs.utimesSync(file, 3, 3);
|
||||
expect(store.load()?.credential).toEqual(first);
|
||||
|
||||
store.save({ cookie: "uin=42; qm_keyst=shared" });
|
||||
fs.utimesSync(file, 1, 1);
|
||||
expect(store.load()?.cookie).toBe("uin=42; qm_keyst=shared");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,294 @@
|
||||
import fs from "node:fs";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import path from "node:path";
|
||||
import type { Logger } from "../logger.js";
|
||||
import type { QrCodeResult } from "./provider.js";
|
||||
import { normalizeCookie } from "./cookie-normalize.js";
|
||||
import { hasQqRenewalMaterial, parseQqCredential, qqPlaybackCookie, type QqCredential, type QqLoginClient, type QqPollResult } from "./qq-login.js";
|
||||
|
||||
interface QqSessionRecord {
|
||||
cookie: string;
|
||||
credential?: QqCredential;
|
||||
reauthRequired?: boolean;
|
||||
authorizedAt?: number;
|
||||
lastRefreshAt?: number;
|
||||
}
|
||||
|
||||
type QrStatus = QqPollResult["status"];
|
||||
export type QqRenewalStatus = "cookie_only" | "scheduled" | "retrying" | "reauth_required";
|
||||
export type QqRenewalResult = "refreshed" | "reauth_required" | "upstream_error" | "rate_limited" | "persist_failed" | "cooldown" | "superseded";
|
||||
|
||||
const MINUTE = 60_000;
|
||||
const DAY = 24 * 60 * MINUTE;
|
||||
const QR_TTL = 3 * MINUTE;
|
||||
|
||||
function timestamp(value: unknown): number | undefined {
|
||||
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && value <= 8.64e15
|
||||
? value : undefined;
|
||||
}
|
||||
|
||||
function expiryTime(credential: QqCredential): number | undefined {
|
||||
if (!credential.musickeyCreateTime || !credential.keyExpiresIn) return;
|
||||
return timestamp((credential.musickeyCreateTime + credential.keyExpiresIn) * 1000);
|
||||
}
|
||||
|
||||
export function createQqSessionStore(file: string, legacyFile?: string) {
|
||||
function loadLegacy(newerThan = -Infinity): QqSessionRecord | undefined {
|
||||
if (!legacyFile) return;
|
||||
try {
|
||||
if (fs.statSync(legacyFile).mtimeMs <= newerThan) return;
|
||||
const { cookie } = JSON.parse(fs.readFileSync(legacyFile, "utf8"));
|
||||
const clean = typeof cookie === "string" ? normalizeCookie(cookie) : "";
|
||||
if (clean) return { cookie: clean };
|
||||
} catch { /* The legacy cookie is missing or unreadable. */ }
|
||||
}
|
||||
|
||||
return {
|
||||
load(): QqSessionRecord | undefined {
|
||||
let raw: string;
|
||||
try {
|
||||
raw = fs.readFileSync(file, "utf8");
|
||||
} catch (err) {
|
||||
if ((err as NodeJS.ErrnoException).code === "ENOENT") return loadLegacy();
|
||||
throw err;
|
||||
}
|
||||
const data = JSON.parse(raw);
|
||||
if (data?.version !== 1 || typeof data.cookie !== "string") throw new Error("Invalid QQ session record");
|
||||
// Before the stores were shared, a newer login could be in the legacy file.
|
||||
if (data.shared !== true && legacyFile) {
|
||||
const legacy = loadLegacy(fs.statSync(file).mtimeMs);
|
||||
if (legacy) return legacy;
|
||||
}
|
||||
const credential = parseQqCredential(data.credential);
|
||||
const cookie = normalizeCookie(data.cookie);
|
||||
if (data.credential && (!credential || qqPlaybackCookie(credential) !== cookie)) {
|
||||
throw new Error("Invalid QQ session credential");
|
||||
}
|
||||
return {
|
||||
cookie,
|
||||
credential,
|
||||
reauthRequired: data.reauthRequired === true,
|
||||
authorizedAt: timestamp(data.authorizedAt),
|
||||
lastRefreshAt: timestamp(data.lastRefreshAt),
|
||||
};
|
||||
},
|
||||
save(data: QqSessionRecord): void {
|
||||
const temp = path.join(path.dirname(file), `.qq-session-${randomUUID()}.tmp`);
|
||||
try {
|
||||
fs.writeFileSync(temp, JSON.stringify({ version: 1, shared: true, ...data, cookie: normalizeCookie(data.cookie) }), {
|
||||
encoding: "utf8", mode: 0o600, flag: "wx", flush: true,
|
||||
});
|
||||
fs.renameSync(temp, file);
|
||||
} finally {
|
||||
try { fs.unlinkSync(temp); } catch { /* Already renamed or unavailable. */ }
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
interface ActiveQr {
|
||||
key: string;
|
||||
sig: string;
|
||||
expiresAt: number;
|
||||
terminal?: "confirmed" | "expired";
|
||||
poll?: Promise<QrStatus>;
|
||||
}
|
||||
|
||||
export class QQManagedSession {
|
||||
private state: QqSessionRecord = { cookie: "" };
|
||||
private generation = 0;
|
||||
private qrGeneration = 0;
|
||||
private qr?: ActiveQr;
|
||||
private inFlight?: Promise<QqRenewalResult>;
|
||||
private pending?: { record: QqSessionRecord; result: "refreshed" | "reauth_required" };
|
||||
private timer?: ReturnType<typeof setTimeout>;
|
||||
private retryAt?: number;
|
||||
private nextAttempt?: number;
|
||||
private failures = 0;
|
||||
private stopped = false;
|
||||
|
||||
constructor(
|
||||
private readonly client: QqLoginClient,
|
||||
private readonly store: ReturnType<typeof createQqSessionStore>,
|
||||
private readonly logger: Logger,
|
||||
) {
|
||||
try {
|
||||
const saved = store.load();
|
||||
if (saved) this.state = saved;
|
||||
} catch {
|
||||
logger.warn("Could not read QQ managed session");
|
||||
}
|
||||
this.schedule();
|
||||
}
|
||||
|
||||
getCookie(): string {
|
||||
return this.state.cookie;
|
||||
}
|
||||
|
||||
getStatus(): { renewalStatus: QqRenewalStatus; nextRefreshAt: string | null; lastRefreshAt: string | null } {
|
||||
const renewalStatus = this.retryAt ? "retrying"
|
||||
: this.state.reauthRequired ? "reauth_required"
|
||||
: !hasQqRenewalMaterial(this.state.credential) ? "cookie_only"
|
||||
: "scheduled";
|
||||
const { lastRefreshAt } = this.state;
|
||||
return {
|
||||
renewalStatus,
|
||||
nextRefreshAt: this.nextAttempt === undefined ? null : new Date(this.nextAttempt).toISOString(),
|
||||
lastRefreshAt: lastRefreshAt === undefined ? null : new Date(lastRefreshAt).toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
setCookie(cookie: string): void {
|
||||
this.replace({ cookie: normalizeCookie(cookie) });
|
||||
this.qrGeneration++;
|
||||
this.qr = undefined;
|
||||
}
|
||||
|
||||
async getQrCode(): Promise<QrCodeResult> {
|
||||
const generation = ++this.qrGeneration;
|
||||
this.qr = undefined;
|
||||
const { img, sig } = await this.client.getQr();
|
||||
if (this.stopped || generation !== this.qrGeneration) throw new Error("QQ QR code superseded");
|
||||
const key = randomUUID();
|
||||
this.qr = { key, sig, expiresAt: Date.now() + QR_TTL };
|
||||
return { key, qrUrl: "", qrImg: img };
|
||||
}
|
||||
|
||||
async checkQrCodeStatus(key: string): Promise<QrStatus> {
|
||||
const qr = this.qr;
|
||||
if (!qr || qr.key !== key || this.stopped || qr.expiresAt <= Date.now()) return "expired";
|
||||
if (qr.terminal) return qr.terminal;
|
||||
qr.poll ??= this.poll(qr).finally(() => { qr.poll = undefined; });
|
||||
return qr.poll;
|
||||
}
|
||||
|
||||
private async poll(qr: ActiveQr): Promise<QrStatus> {
|
||||
const result = await this.client.pollQr(qr.sig);
|
||||
if (this.stopped || this.qr !== qr || qr.expiresAt <= Date.now()) return "expired";
|
||||
if (result.status === "confirmed") {
|
||||
try {
|
||||
this.replace({
|
||||
cookie: qqPlaybackCookie(result.credential),
|
||||
credential: result.credential,
|
||||
authorizedAt: Date.now(),
|
||||
});
|
||||
} catch {
|
||||
this.logger.warn("Could not save QQ login");
|
||||
return qr.terminal = "expired";
|
||||
}
|
||||
qr.terminal = "confirmed";
|
||||
}
|
||||
if (result.status === "expired") qr.terminal = "expired";
|
||||
return result.status;
|
||||
}
|
||||
|
||||
private replace(record: QqSessionRecord): void {
|
||||
this.store.save(record);
|
||||
this.state = record;
|
||||
this.generation++;
|
||||
this.inFlight = undefined;
|
||||
this.pending = undefined;
|
||||
this.retryAt = undefined;
|
||||
this.failures = 0;
|
||||
this.schedule();
|
||||
}
|
||||
|
||||
private schedule(earliest = 0): void {
|
||||
clearTimeout(this.timer);
|
||||
this.nextAttempt = undefined;
|
||||
if (this.stopped) return;
|
||||
const credential = this.state.credential;
|
||||
this.nextAttempt = this.retryAt;
|
||||
if (this.nextAttempt === undefined && !this.state.reauthRequired && hasQqRenewalMaterial(credential)) {
|
||||
const now = Date.now();
|
||||
// Older session records predate local timestamps. Use QQ's key creation
|
||||
// time to establish their first due date without inventing a renewal history.
|
||||
const keyCreatedAt = credential.musickeyCreateTime
|
||||
? timestamp(credential.musickeyCreateTime * 1000) : undefined;
|
||||
const anchor = this.state.lastRefreshAt ?? this.state.authorizedAt ?? keyCreatedAt;
|
||||
const dailyAt = anchor === undefined ? now : Math.min(anchor, now) + DAY;
|
||||
const expiresAt = expiryTime(credential);
|
||||
const leadTime = Math.min(30 * MINUTE, credential.keyExpiresIn * 100);
|
||||
const dueAt = expiresAt === undefined ? dailyAt : Math.min(dailyAt, expiresAt - leadTime);
|
||||
this.nextAttempt = Math.max(earliest, now, dueAt);
|
||||
}
|
||||
if (this.nextAttempt === undefined) return;
|
||||
this.timer = setTimeout(() => {
|
||||
if (this.nextAttempt !== undefined && Date.now() < this.nextAttempt) this.schedule(earliest);
|
||||
else void this.refresh();
|
||||
}, Math.min(2 ** 31 - 1, this.nextAttempt - Date.now()));
|
||||
this.timer.unref();
|
||||
}
|
||||
|
||||
refresh(): Promise<QqRenewalResult> {
|
||||
if (this.stopped) return Promise.resolve("superseded");
|
||||
if (this.inFlight) return this.inFlight;
|
||||
if (this.retryAt && Date.now() < this.retryAt) return Promise.resolve("cooldown");
|
||||
if (this.pending) return Promise.resolve(this.commitPending());
|
||||
const credential = this.state.credential;
|
||||
if (!hasQqRenewalMaterial(credential) || this.state.reauthRequired) return Promise.resolve("reauth_required");
|
||||
const generation = this.generation;
|
||||
this.inFlight = this.renew(credential, generation).finally(() => {
|
||||
if (generation === this.generation) this.inFlight = undefined;
|
||||
});
|
||||
return this.inFlight;
|
||||
}
|
||||
|
||||
private async renew(credential: QqCredential, generation: number): Promise<QqRenewalResult> {
|
||||
const result = await this.client.refresh(credential).catch(() => ({ status: "upstream_error" } as const));
|
||||
if (this.stopped || this.generation !== generation) return "superseded";
|
||||
if (result.status === "reauth_required") {
|
||||
this.pending = { record: { ...this.state, reauthRequired: true }, result: "reauth_required" };
|
||||
return this.commitPending();
|
||||
}
|
||||
if (result.status === "refreshed") {
|
||||
const next = result.credential;
|
||||
const renewed = next.musickey !== credential.musickey
|
||||
|| (expiryTime(next) ?? 0) > (expiryTime(credential) ?? 0)
|
||||
|| (next.refresh_key && next.refresh_key !== credential.refresh_key)
|
||||
|| (next.refresh_token && next.refresh_token !== credential.refresh_token);
|
||||
if (next.musicid === credential.musicid && renewed) {
|
||||
this.pending = {
|
||||
record: { cookie: qqPlaybackCookie(next), credential: next, reauthRequired: !hasQqRenewalMaterial(next) },
|
||||
result: "refreshed",
|
||||
};
|
||||
return this.commitPending();
|
||||
}
|
||||
}
|
||||
const outcome = result.status === "rate_limited" ? "rate_limited" : "upstream_error";
|
||||
this.defer(outcome);
|
||||
return outcome;
|
||||
}
|
||||
|
||||
private commitPending(): QqRenewalResult {
|
||||
const pending = this.pending!;
|
||||
const record = pending.result === "refreshed"
|
||||
? { ...pending.record, lastRefreshAt: Date.now() }
|
||||
: pending.record;
|
||||
try {
|
||||
this.store.save(record);
|
||||
} catch {
|
||||
this.defer("persist_failed");
|
||||
return "persist_failed";
|
||||
}
|
||||
this.state = record;
|
||||
this.pending = undefined;
|
||||
this.retryAt = undefined;
|
||||
this.failures = 0;
|
||||
this.schedule(Date.now() + MINUTE);
|
||||
this.logger.info({ outcome: pending.result }, "QQ session renewal");
|
||||
return pending.result;
|
||||
}
|
||||
|
||||
private defer(outcome: "rate_limited" | "upstream_error" | "persist_failed"): void {
|
||||
const initialMinutes = outcome === "rate_limited" ? 15 : 5;
|
||||
this.retryAt = Date.now() + Math.min(60, initialMinutes * 2 ** this.failures++) * MINUTE;
|
||||
this.schedule();
|
||||
this.logger.warn({ outcome }, "QQ session renewal deferred");
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.stopped = true;
|
||||
this.schedule();
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,94 @@ vi.mock("axios", () => ({
|
||||
|
||||
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", () => {
|
||||
const out = mapQqSongs([
|
||||
|
||||
+168
-48
@@ -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,
|
||||
@@ -15,6 +17,7 @@ import type {
|
||||
ArtistSongPage,
|
||||
} from "./provider.js";
|
||||
import { parseLyrics } from "./netease.js";
|
||||
import type { QQManagedSession } from "./qq-session.js";
|
||||
|
||||
// Primary search client: u.y.qq.com/cgi-bin/musicu.fcg (JSON sub-request
|
||||
// batch). Was broken ca. 2026-05 due to two upstream API changes:
|
||||
@@ -43,6 +46,53 @@ 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 {
|
||||
@@ -170,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 } : {};
|
||||
}
|
||||
@@ -352,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})`,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -384,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> {
|
||||
@@ -426,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 {
|
||||
@@ -477,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", {
|
||||
@@ -768,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
|
||||
@@ -787,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";
|
||||
|
||||
@@ -808,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";
|
||||
@@ -818,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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import pino from "pino";
|
||||
import { APP_VERSION } from "../version.js";
|
||||
import {
|
||||
ACK_GLOBAL_BURST,
|
||||
ANNOUNCE_DEBOUNCE_MS,
|
||||
ANNOUNCE_RETRY_DELAY_MS,
|
||||
APP_NAME,
|
||||
BOT_CAPABILITIES,
|
||||
COMMANDS_LIST_REQ_COOLDOWN_MS,
|
||||
COMMANDS_PLUGIN,
|
||||
IDENTITY_ANNOUNCE_COOLDOWN_MS,
|
||||
IDENTITY_PLUGIN,
|
||||
IDENTITY_QUERY_COOLDOWN_MS,
|
||||
MAX_CMD_ARGS_CHARS,
|
||||
MAX_CMD_DESC_CHARS,
|
||||
MAX_CMD_NAME_CHARS,
|
||||
MAX_COMMANDS,
|
||||
MAX_PAYLOAD_BYTES,
|
||||
OPEN_PROTOCOL_VERSION,
|
||||
OpenProtocolManager,
|
||||
buildCommandsListAckJson,
|
||||
buildIdentityPayloadJson,
|
||||
buildOpenProtocolCommands,
|
||||
type OpenProtocolRuntimeConfig,
|
||||
type OpenProtocolTransport,
|
||||
} from "./open-protocol.js";
|
||||
import type { TS3PluginCommand } from "./client.js";
|
||||
|
||||
function makeCmd(overrides: Partial<TS3PluginCommand> = {}): TS3PluginCommand {
|
||||
return {
|
||||
name: IDENTITY_PLUGIN,
|
||||
data: JSON.stringify({ v: 1, action: "announce" }),
|
||||
invokerId: 7,
|
||||
invokerName: "Alice",
|
||||
invokerUid: "uid-alice",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("OpenProtocol payload builders", () => {
|
||||
it("builds valid v1 identity payloads with package version under 1024 bytes", () => {
|
||||
const raw = buildIdentityPayloadJson("announce");
|
||||
expect(Buffer.byteLength(raw, "utf8")).toBeLessThan(MAX_PAYLOAD_BYTES);
|
||||
expect(JSON.parse(raw)).toEqual({
|
||||
v: OPEN_PROTOCOL_VERSION,
|
||||
action: "announce",
|
||||
client_type: "bot",
|
||||
app_name: APP_NAME,
|
||||
app_version: APP_VERSION,
|
||||
capabilities: [...BOT_CAPABILITIES],
|
||||
});
|
||||
|
||||
const ack = JSON.parse(buildIdentityPayloadJson("announce_ack"));
|
||||
expect(ack.action).toBe("announce_ack");
|
||||
expect(ack.command_prefix).toBeUndefined();
|
||||
});
|
||||
|
||||
it("advertises only playback mode values supported by the bot", () => {
|
||||
for (const locale of ["zh", "en"] as const) {
|
||||
expect(buildOpenProtocolCommands(locale).find(({ name }) => name === "mode")?.args)
|
||||
.toBe("<seq|loop|random|rloop>");
|
||||
}
|
||||
});
|
||||
|
||||
it("builds localized command lists adhering to field caps and <1024 byte UTF-8 limit", () => {
|
||||
for (const locale of ["zh", "en"] as const) {
|
||||
const cmds = buildOpenProtocolCommands(locale);
|
||||
expect(cmds.length).toBeGreaterThan(0);
|
||||
expect(cmds.length).toBeLessThanOrEqual(MAX_COMMANDS);
|
||||
|
||||
for (const cmd of cmds) {
|
||||
expect(Array.from(cmd.name).length).toBeLessThanOrEqual(MAX_CMD_NAME_CHARS);
|
||||
expect(Array.from(cmd.desc).length).toBeLessThanOrEqual(MAX_CMD_DESC_CHARS);
|
||||
if (cmd.args !== undefined) {
|
||||
expect(Array.from(cmd.args).length).toBeLessThanOrEqual(MAX_CMD_ARGS_CHARS);
|
||||
}
|
||||
}
|
||||
|
||||
const raw = buildCommandsListAckJson(locale, "!");
|
||||
if (raw === null) throw new Error("Expected a command list for a valid prefix");
|
||||
expect(Buffer.byteLength(raw, "utf8")).toBeLessThan(MAX_PAYLOAD_BYTES);
|
||||
const parsed = JSON.parse(raw) as {
|
||||
v: number;
|
||||
action: string;
|
||||
command_prefix: string;
|
||||
commands: unknown[];
|
||||
};
|
||||
expect(parsed.v).toBe(OPEN_PROTOCOL_VERSION);
|
||||
expect(parsed.action).toBe("list_ack");
|
||||
expect(parsed.command_prefix).toBe("!");
|
||||
expect(parsed.commands.length).toBe(cmds.length);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("OpenProtocolManager", () => {
|
||||
let nowMs: number;
|
||||
let clientId: number;
|
||||
let config: OpenProtocolRuntimeConfig;
|
||||
let sendPluginCommand: ReturnType<typeof vi.fn>;
|
||||
let manager: OpenProtocolManager;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
nowMs = 100_000;
|
||||
clientId = 42;
|
||||
config = { locale: "zh", commandPrefix: "!" };
|
||||
sendPluginCommand = vi.fn(async () => {});
|
||||
const transport: OpenProtocolTransport = {
|
||||
getClientId: () => clientId,
|
||||
sendPluginCommand: sendPluginCommand as OpenProtocolTransport["sendPluginCommand"],
|
||||
};
|
||||
manager = new OpenProtocolManager({
|
||||
transport,
|
||||
getConfig: () => config,
|
||||
logger: pino({ level: "silent" }),
|
||||
now: () => nowMs,
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
manager.reset();
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("ignores unrelated plugins, self-sent commands, malformed JSON, and non-v1 versions", async () => {
|
||||
await manager.handlePluginCommand(makeCmd({ name: "other:plugin" }));
|
||||
await manager.handlePluginCommand(makeCmd({ invokerId: 42 }));
|
||||
await manager.handlePluginCommand(makeCmd({ data: "{not-json" }));
|
||||
await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 2, action: "query" }) }));
|
||||
await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "announce_ack" }) }));
|
||||
await manager.handlePluginCommand(
|
||||
makeCmd({ name: COMMANDS_PLUGIN, data: JSON.stringify({ v: 1, action: "list_ack" }) }),
|
||||
);
|
||||
expect(sendPluginCommand).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("replies with unicast announce_ack to announce and query, with separate cooldowns", async () => {
|
||||
await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "announce" }) }));
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(1);
|
||||
expect(sendPluginCommand).toHaveBeenLastCalledWith(IDENTITY_PLUGIN, expect.any(String), 7);
|
||||
expect(JSON.parse(sendPluginCommand.mock.calls[0][1] as string).action).toBe("announce_ack");
|
||||
|
||||
// Repeated announce within 10s cooldown is suppressed
|
||||
nowMs += 3_000;
|
||||
await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "announce" }) }));
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(1);
|
||||
|
||||
// query uses an independent 5s cooldown bucket, so it succeeds immediately
|
||||
await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "query" }) }));
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(2);
|
||||
|
||||
// Repeated query within 5s is suppressed, then allowed after 5s
|
||||
nowMs += IDENTITY_QUERY_COOLDOWN_MS - 1;
|
||||
await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "query" }) }));
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(2);
|
||||
nowMs += 1;
|
||||
await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "query" }) }));
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(3);
|
||||
|
||||
// announce still respects its 10s cooldown until elapsed
|
||||
nowMs += 1_000; // total 9_000ms since first announce
|
||||
await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "announce" }) }));
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(3);
|
||||
nowMs += IDENTITY_ANNOUNCE_COOLDOWN_MS;
|
||||
await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "announce" }) }));
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(4);
|
||||
});
|
||||
|
||||
it("replies with localized unicast list_ack on commands list_req using dynamic config", async () => {
|
||||
config = { locale: "en", commandPrefix: "?" };
|
||||
await manager.handlePluginCommand(
|
||||
makeCmd({
|
||||
name: COMMANDS_PLUGIN,
|
||||
data: JSON.stringify({ v: 1, action: "list_req" }),
|
||||
invokerId: 11,
|
||||
invokerUid: "",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(1);
|
||||
expect(sendPluginCommand).toHaveBeenCalledWith(COMMANDS_PLUGIN, expect.any(String), 11);
|
||||
const payload = JSON.parse(sendPluginCommand.mock.calls[0][1] as string);
|
||||
expect(payload.v).toBe(1);
|
||||
expect(payload.action).toBe("list_ack");
|
||||
expect(payload.command_prefix).toBe("?");
|
||||
expect(payload.commands[0]).toEqual({ name: "play", args: "<query>", desc: "Play song" });
|
||||
|
||||
// Cooldown falls back to invokerId when invokerUid is empty
|
||||
nowMs += COMMANDS_LIST_REQ_COOLDOWN_MS - 10;
|
||||
await manager.handlePluginCommand(
|
||||
makeCmd({
|
||||
name: COMMANDS_PLUGIN,
|
||||
data: JSON.stringify({ v: 1, action: "list_req" }),
|
||||
invokerId: 11,
|
||||
invokerUid: "",
|
||||
}),
|
||||
);
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("does not advertise command discovery with a prefix too long to send unchanged", async () => {
|
||||
config.commandPrefix = "musicbot!!";
|
||||
manager.scheduleAnnounce();
|
||||
await manager.handlePluginCommand(makeCmd({
|
||||
name: COMMANDS_PLUGIN,
|
||||
data: JSON.stringify({ v: 1, action: "list_req" }),
|
||||
}));
|
||||
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(1);
|
||||
const identity = JSON.parse(sendPluginCommand.mock.calls[0][1] as string);
|
||||
expect(identity.capabilities).not.toContain("chat:slash_commands");
|
||||
});
|
||||
|
||||
it("ignores inbound payloads beyond the protocol byte limit", async () => {
|
||||
await manager.handlePluginCommand(makeCmd({
|
||||
data: JSON.stringify({ v: 1, action: "query", padding: "中".repeat(MAX_PAYLOAD_BYTES / 2) }),
|
||||
}));
|
||||
expect(sendPluginCommand).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("enforces global and peer cooldowns when sending replies fails", async () => {
|
||||
for (let i = 1; i <= ACK_GLOBAL_BURST; i++) {
|
||||
await manager.handlePluginCommand(
|
||||
makeCmd({
|
||||
name: COMMANDS_PLUGIN,
|
||||
data: JSON.stringify({ v: 1, action: "list_req" }),
|
||||
invokerId: i,
|
||||
invokerUid: `peer-${i}`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(ACK_GLOBAL_BURST);
|
||||
|
||||
// 5th distinct peer in same millisecond is throttled by global burst
|
||||
await manager.handlePluginCommand(
|
||||
makeCmd({
|
||||
name: COMMANDS_PLUGIN,
|
||||
data: JSON.stringify({ v: 1, action: "list_req" }),
|
||||
invokerId: 99,
|
||||
invokerUid: "peer-99",
|
||||
}),
|
||||
);
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(ACK_GLOBAL_BURST);
|
||||
|
||||
// After 500ms, 1 token refills (2/sec)
|
||||
nowMs += 500;
|
||||
sendPluginCommand.mockRejectedValueOnce(new Error("transient send failure"));
|
||||
await manager.handlePluginCommand(
|
||||
makeCmd({
|
||||
name: COMMANDS_PLUGIN,
|
||||
data: JSON.stringify({ v: 1, action: "list_req" }),
|
||||
invokerId: 99,
|
||||
invokerUid: "peer-99",
|
||||
}),
|
||||
);
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(ACK_GLOBAL_BURST + 1);
|
||||
|
||||
// A rejected reply still consumes the global allowance for other peers.
|
||||
const otherRequest = makeCmd({
|
||||
name: COMMANDS_PLUGIN,
|
||||
data: JSON.stringify({ v: 1, action: "list_req" }),
|
||||
invokerId: 98,
|
||||
invokerUid: "peer-98",
|
||||
});
|
||||
await manager.handlePluginCommand(otherRequest);
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(ACK_GLOBAL_BURST + 1);
|
||||
|
||||
// Once a global slot refills, the original peer is still cooling down.
|
||||
nowMs += 500;
|
||||
await manager.handlePluginCommand({ ...otherRequest, invokerId: 99, invokerUid: "peer-99" });
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(ACK_GLOBAL_BURST + 1);
|
||||
await manager.handlePluginCommand(otherRequest);
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(ACK_GLOBAL_BURST + 2);
|
||||
});
|
||||
|
||||
it("debounces self-announce over 2s window and emits at most one trailing announce", async () => {
|
||||
manager.scheduleAnnounce();
|
||||
await Promise.resolve();
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(1);
|
||||
expect(sendPluginCommand).toHaveBeenLastCalledWith(IDENTITY_PLUGIN, expect.any(String), "channel");
|
||||
|
||||
// Two calls inside 2s window coalesce into a single trailing broadcast
|
||||
nowMs += 400;
|
||||
manager.scheduleAnnounce();
|
||||
nowMs += 600;
|
||||
manager.scheduleAnnounce();
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(1);
|
||||
|
||||
nowMs += ANNOUNCE_DEBOUNCE_MS - 1_000;
|
||||
await vi.advanceTimersByTimeAsync(ANNOUNCE_DEBOUNCE_MS - 400);
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("retries failed announce once after 500ms and cancels pending timers on reset", async () => {
|
||||
sendPluginCommand.mockRejectedValueOnce(new Error("channel broadcast error"));
|
||||
manager.scheduleAnnounce();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(1);
|
||||
|
||||
nowMs += ANNOUNCE_RETRY_DELAY_MS;
|
||||
await vi.advanceTimersByTimeAsync(ANNOUNCE_RETRY_DELAY_MS);
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(2);
|
||||
|
||||
// Trigger another failure then reset before retry fires
|
||||
nowMs += ANNOUNCE_DEBOUNCE_MS;
|
||||
sendPluginCommand.mockRejectedValueOnce(new Error("error before disconnect"));
|
||||
manager.scheduleAnnounce();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(3);
|
||||
|
||||
manager.reset();
|
||||
await vi.advanceTimersByTimeAsync(ANNOUNCE_RETRY_DELAY_MS);
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,473 @@
|
||||
import { PlayMode } from "../audio/queue.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { APP_VERSION } from "../version.js";
|
||||
import type { PluginCommandTarget, TS3PluginCommand } from "./client.js";
|
||||
|
||||
export const OPEN_PROTOCOL_VERSION = 1;
|
||||
export const IDENTITY_PLUGIN = "tsclient:identity";
|
||||
export const COMMANDS_PLUGIN = "tsclient:commands";
|
||||
export const MAX_PAYLOAD_BYTES = 1024;
|
||||
|
||||
export const APP_NAME = "TSMusicBot";
|
||||
export const BOT_CAPABILITIES = ["chat:slash_commands"] as const;
|
||||
|
||||
export const ANNOUNCE_DEBOUNCE_MS = 2_000;
|
||||
export const ANNOUNCE_RETRY_DELAY_MS = 500;
|
||||
|
||||
export const IDENTITY_ANNOUNCE_COOLDOWN_MS = 10_000;
|
||||
export const IDENTITY_QUERY_COOLDOWN_MS = 5_000;
|
||||
export const COMMANDS_LIST_REQ_COOLDOWN_MS = 5_000;
|
||||
|
||||
export const ACK_GLOBAL_BURST = 4;
|
||||
export const ACK_GLOBAL_RATE_PER_SEC = 2;
|
||||
|
||||
export const MAX_COMMANDS = 16;
|
||||
export const MAX_CMD_PREFIX_CHARS = 8;
|
||||
export const MAX_CMD_NAME_CHARS = 24;
|
||||
export const MAX_CMD_ARGS_CHARS = 32;
|
||||
export const MAX_CMD_DESC_CHARS = 64;
|
||||
export const MAX_APP_META_CHARS = 32;
|
||||
const MAX_COOLDOWN_ENTRIES_BEFORE_PRUNE = 128;
|
||||
|
||||
export interface OpenProtocolCommandSpec {
|
||||
name: string;
|
||||
args?: string;
|
||||
desc: string;
|
||||
}
|
||||
|
||||
export interface OpenProtocolIdentityPayload {
|
||||
v: 1;
|
||||
action: "announce" | "announce_ack";
|
||||
client_type: "bot";
|
||||
app_name: string;
|
||||
app_version: string;
|
||||
capabilities: string[];
|
||||
}
|
||||
|
||||
export interface OpenProtocolCommandsListAckPayload {
|
||||
v: 1;
|
||||
action: "list_ack";
|
||||
command_prefix: string;
|
||||
commands: OpenProtocolCommandSpec[];
|
||||
}
|
||||
|
||||
export interface OpenProtocolRuntimeConfig {
|
||||
locale: "zh" | "en";
|
||||
commandPrefix: string;
|
||||
}
|
||||
|
||||
export interface OpenProtocolTransport {
|
||||
getClientId(): number;
|
||||
sendPluginCommand(
|
||||
name: string,
|
||||
data: string,
|
||||
target?: PluginCommandTarget | number,
|
||||
): Promise<void>;
|
||||
}
|
||||
|
||||
interface CommandCatalogEntry {
|
||||
name: string;
|
||||
args?: string;
|
||||
descZh: string;
|
||||
descEn: string;
|
||||
}
|
||||
|
||||
const CORE_COMMAND_CATALOG: readonly CommandCatalogEntry[] = [
|
||||
{ name: "play", args: "<歌曲>", descZh: "点歌并立即播放", descEn: "Play song" },
|
||||
{ name: "add", args: "<歌曲>", descZh: "添加到队列", descEn: "Add to queue" },
|
||||
{ name: "search", args: "<关键词>", descZh: "搜索歌曲", descEn: "Search songs" },
|
||||
{ name: "pause", descZh: "暂停播放", descEn: "Pause playback" },
|
||||
{ name: "resume", descZh: "恢复播放", descEn: "Resume playback" },
|
||||
{ name: "next", descZh: "下一首", descEn: "Next track" },
|
||||
{ name: "prev", descZh: "上一首", descEn: "Previous track" },
|
||||
{ name: "stop", descZh: "停止并清空队列", descEn: "Stop & clear" },
|
||||
{ name: "now", descZh: "当前播放", descEn: "Current track" },
|
||||
{ name: "queue", descZh: "查看队列", descEn: "Show queue" },
|
||||
{ name: "vol", args: "<0-100>", descZh: "调节音量", descEn: "Set volume" },
|
||||
{ name: "mode", args: `<${Object.values(PlayMode).join("|")}>`, descZh: "切换播放模式", descEn: "Set play mode" },
|
||||
{ name: "clear", descZh: "清空队列", descEn: "Clear queue" },
|
||||
{ name: "remove", args: "<序号>", descZh: "移除指定曲目", descEn: "Remove track" },
|
||||
{ name: "playlist", args: "<歌单>", descZh: "导入歌单", descEn: "Load playlist" },
|
||||
{ name: "help", descZh: "命令帮助", descEn: "Command help" },
|
||||
];
|
||||
|
||||
const CORE_COMMAND_ARGS_EN: Readonly<Record<string, string>> = {
|
||||
play: "<query>",
|
||||
add: "<query>",
|
||||
search: "<keyword>",
|
||||
vol: "<0-100>",
|
||||
remove: "<index>",
|
||||
playlist: "<id|url>",
|
||||
};
|
||||
|
||||
function truncateChars(value: string, maxChars: number): string {
|
||||
const sanitized = value.replace(/[\u0000-\u001F\u007F]/g, "");
|
||||
const chars = Array.from(sanitized);
|
||||
if (chars.length <= maxChars) return sanitized;
|
||||
return chars.slice(0, maxChars).join("");
|
||||
}
|
||||
|
||||
function isDiscoverablePrefix(prefix: string): boolean {
|
||||
return typeof prefix === "string"
|
||||
&& prefix.length > 0
|
||||
&& prefix.trim() === prefix
|
||||
&& truncateChars(prefix, MAX_CMD_PREFIX_CHARS) === prefix;
|
||||
}
|
||||
|
||||
export function buildIdentityPayloadJson(
|
||||
action: "announce" | "announce_ack",
|
||||
appVersion: string = APP_VERSION,
|
||||
commandPrefix = "!",
|
||||
): string {
|
||||
const payload: OpenProtocolIdentityPayload = {
|
||||
v: OPEN_PROTOCOL_VERSION,
|
||||
action,
|
||||
client_type: "bot",
|
||||
app_name: truncateChars(APP_NAME, MAX_APP_META_CHARS),
|
||||
app_version: truncateChars(appVersion, MAX_APP_META_CHARS),
|
||||
capabilities: isDiscoverablePrefix(commandPrefix) ? [...BOT_CAPABILITIES] : [],
|
||||
};
|
||||
|
||||
return JSON.stringify(payload);
|
||||
}
|
||||
|
||||
export function buildOpenProtocolCommands(locale: "zh" | "en"): OpenProtocolCommandSpec[] {
|
||||
return CORE_COMMAND_CATALOG.slice(0, MAX_COMMANDS).map((entry) => {
|
||||
const rawArgs = locale === "zh" ? entry.args : (CORE_COMMAND_ARGS_EN[entry.name] ?? entry.args);
|
||||
const rawDesc = locale === "zh" ? entry.descZh : entry.descEn;
|
||||
const spec: OpenProtocolCommandSpec = {
|
||||
name: truncateChars(entry.name, MAX_CMD_NAME_CHARS),
|
||||
desc: truncateChars(rawDesc, MAX_CMD_DESC_CHARS),
|
||||
};
|
||||
if (rawArgs) {
|
||||
spec.args = truncateChars(rawArgs, MAX_CMD_ARGS_CHARS);
|
||||
}
|
||||
return spec;
|
||||
});
|
||||
}
|
||||
|
||||
export function buildCommandsListAckJson(
|
||||
locale: "zh" | "en",
|
||||
commandPrefix: string,
|
||||
): string | null {
|
||||
if (!isDiscoverablePrefix(commandPrefix)) return null;
|
||||
|
||||
const commands = buildOpenProtocolCommands(locale);
|
||||
while (commands.length > 0) {
|
||||
const payload: OpenProtocolCommandsListAckPayload = {
|
||||
v: OPEN_PROTOCOL_VERSION,
|
||||
action: "list_ack",
|
||||
command_prefix: commandPrefix,
|
||||
commands,
|
||||
};
|
||||
const json = JSON.stringify(payload);
|
||||
if (Buffer.byteLength(json, "utf8") < MAX_PAYLOAD_BYTES) {
|
||||
return json;
|
||||
}
|
||||
commands.pop();
|
||||
}
|
||||
|
||||
return JSON.stringify({
|
||||
v: OPEN_PROTOCOL_VERSION,
|
||||
action: "list_ack",
|
||||
command_prefix: commandPrefix,
|
||||
commands: [],
|
||||
} satisfies OpenProtocolCommandsListAckPayload);
|
||||
}
|
||||
|
||||
class AckRateLimiter {
|
||||
private readonly lastSent = new Map<string, number>();
|
||||
private tokens = ACK_GLOBAL_BURST;
|
||||
private lastRefillMs: number | null = null;
|
||||
|
||||
private refill(nowMs: number): void {
|
||||
if (this.lastRefillMs === null) {
|
||||
this.lastRefillMs = nowMs;
|
||||
return;
|
||||
}
|
||||
const elapsedMs = Math.max(0, nowMs - this.lastRefillMs);
|
||||
this.tokens = Math.min(
|
||||
ACK_GLOBAL_BURST,
|
||||
this.tokens + (elapsedMs / 1000) * ACK_GLOBAL_RATE_PER_SEC,
|
||||
);
|
||||
this.lastRefillMs = nowMs;
|
||||
}
|
||||
|
||||
private prune(nowMs: number): void {
|
||||
if (this.lastSent.size <= MAX_COOLDOWN_ENTRIES_BEFORE_PRUNE) return;
|
||||
const maxAgeMs = Math.max(
|
||||
IDENTITY_ANNOUNCE_COOLDOWN_MS,
|
||||
IDENTITY_QUERY_COOLDOWN_MS,
|
||||
COMMANDS_LIST_REQ_COOLDOWN_MS,
|
||||
);
|
||||
for (const [key, ts] of this.lastSent) {
|
||||
if (nowMs - ts >= maxAgeMs) {
|
||||
this.lastSent.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tryAcquire(peerKey: string, actionKey: string, cooldownMs: number, nowMs: number): boolean {
|
||||
this.prune(nowMs);
|
||||
const key = `${peerKey}:${actionKey}`;
|
||||
const prev = this.lastSent.get(key);
|
||||
if (prev !== undefined && nowMs - prev < cooldownMs) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.refill(nowMs);
|
||||
if (this.tokens < 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.tokens -= 1;
|
||||
this.lastSent.set(key, nowMs);
|
||||
return true;
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.lastSent.clear();
|
||||
this.tokens = ACK_GLOBAL_BURST;
|
||||
this.lastRefillMs = null;
|
||||
}
|
||||
}
|
||||
|
||||
export interface OpenProtocolManagerOptions {
|
||||
transport: OpenProtocolTransport;
|
||||
getConfig: () => OpenProtocolRuntimeConfig;
|
||||
logger: Logger;
|
||||
now?: () => number;
|
||||
}
|
||||
|
||||
export class OpenProtocolManager {
|
||||
private readonly transport: OpenProtocolTransport;
|
||||
private readonly getConfig: () => OpenProtocolRuntimeConfig;
|
||||
private readonly logger: Logger;
|
||||
private readonly now: () => number;
|
||||
private readonly rateLimiter = new AckRateLimiter();
|
||||
|
||||
private generation = 0;
|
||||
private announceSeq = 0;
|
||||
private lastSuccessSeq = 0;
|
||||
private lastAnnounceAttemptMs: number | null = null;
|
||||
private trailingAnnounceTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private retryAnnounceTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
constructor(options: OpenProtocolManagerOptions) {
|
||||
this.transport = options.transport;
|
||||
this.getConfig = options.getConfig;
|
||||
this.logger = options.logger;
|
||||
this.now = options.now ?? (() => Date.now());
|
||||
}
|
||||
|
||||
/** Reset timers and rate-limit state on disconnect or teardown. */
|
||||
reset(): void {
|
||||
this.generation += 1;
|
||||
this.announceSeq = 0;
|
||||
this.lastSuccessSeq = 0;
|
||||
this.lastAnnounceAttemptMs = null;
|
||||
this.clearTimers();
|
||||
this.rateLimiter.clear();
|
||||
}
|
||||
|
||||
/** Schedule or send a debounced channel broadcast announcing this bot's identity. */
|
||||
scheduleAnnounce(): void {
|
||||
const clientId = this.transport.getClientId();
|
||||
if (clientId <= 0) return;
|
||||
|
||||
const nowMs = this.now();
|
||||
if (
|
||||
this.lastAnnounceAttemptMs !== null &&
|
||||
nowMs - this.lastAnnounceAttemptMs < ANNOUNCE_DEBOUNCE_MS
|
||||
) {
|
||||
if (!this.trailingAnnounceTimer) {
|
||||
const delayMs = Math.max(
|
||||
0,
|
||||
ANNOUNCE_DEBOUNCE_MS - (nowMs - this.lastAnnounceAttemptMs),
|
||||
);
|
||||
const gen = this.generation;
|
||||
this.trailingAnnounceTimer = setTimeout(() => {
|
||||
this.trailingAnnounceTimer = null;
|
||||
if (gen !== this.generation) return;
|
||||
this.dispatchAnnounce(gen);
|
||||
}, delayMs);
|
||||
this.trailingAnnounceTimer.unref?.();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
this.clearTimers();
|
||||
this.dispatchAnnounce(this.generation);
|
||||
}
|
||||
|
||||
/** Handle an incoming TeamSpeak plugin command. */
|
||||
async handlePluginCommand(cmd: TS3PluginCommand): Promise<void> {
|
||||
if (cmd.name !== IDENTITY_PLUGIN && cmd.name !== COMMANDS_PLUGIN) {
|
||||
return;
|
||||
}
|
||||
|
||||
const selfClientId = this.transport.getClientId();
|
||||
if (selfClientId <= 0 || cmd.invokerId === selfClientId || cmd.invokerId <= 0
|
||||
|| Buffer.byteLength(cmd.data, "utf8") >= MAX_PAYLOAD_BYTES) {
|
||||
return;
|
||||
}
|
||||
|
||||
let parsed: Record<string, unknown>;
|
||||
try {
|
||||
const value = JSON.parse(cmd.data) as unknown;
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
||||
return;
|
||||
}
|
||||
parsed = value as Record<string, unknown>;
|
||||
} catch {
|
||||
this.logger.debug(
|
||||
{ name: cmd.name, invokerId: cmd.invokerId },
|
||||
"Ignoring malformed OpenProtocol JSON payload",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (parsed.v !== OPEN_PROTOCOL_VERSION || typeof parsed.action !== "string") {
|
||||
return;
|
||||
}
|
||||
|
||||
const peerKey = cmd.invokerUid.trim() || String(cmd.invokerId);
|
||||
|
||||
if (cmd.name === IDENTITY_PLUGIN) {
|
||||
await this.handleIdentityAction(parsed.action, peerKey, cmd.invokerId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (cmd.name === COMMANDS_PLUGIN) {
|
||||
await this.handleCommandsAction(parsed.action, peerKey, cmd.invokerId);
|
||||
}
|
||||
}
|
||||
|
||||
private async handleIdentityAction(
|
||||
action: string,
|
||||
peerKey: string,
|
||||
invokerId: number,
|
||||
): Promise<void> {
|
||||
let cooldownMs: number;
|
||||
if (action === "announce") {
|
||||
cooldownMs = IDENTITY_ANNOUNCE_COOLDOWN_MS;
|
||||
} else if (action === "query") {
|
||||
cooldownMs = IDENTITY_QUERY_COOLDOWN_MS;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.rateLimiter.tryAcquire(
|
||||
peerKey, `${IDENTITY_PLUGIN}:${action}`, cooldownMs, this.now(),
|
||||
)) return;
|
||||
|
||||
const payload = buildIdentityPayloadJson("announce_ack", APP_VERSION, this.getConfig().commandPrefix);
|
||||
await this.sendAck(IDENTITY_PLUGIN, payload, invokerId);
|
||||
}
|
||||
|
||||
private async handleCommandsAction(
|
||||
action: string,
|
||||
peerKey: string,
|
||||
invokerId: number,
|
||||
): Promise<void> {
|
||||
if (action !== "list_req") return;
|
||||
|
||||
const { locale, commandPrefix } = this.getConfig();
|
||||
if (!isDiscoverablePrefix(commandPrefix) || !this.rateLimiter.tryAcquire(
|
||||
peerKey, `${COMMANDS_PLUGIN}:list_req`, COMMANDS_LIST_REQ_COOLDOWN_MS, this.now(),
|
||||
)) return;
|
||||
|
||||
const payload = buildCommandsListAckJson(locale, commandPrefix);
|
||||
if (payload !== null) await this.sendAck(COMMANDS_PLUGIN, payload, invokerId);
|
||||
}
|
||||
|
||||
private async sendAck(
|
||||
pluginName: string,
|
||||
payload: string,
|
||||
invokerId: number,
|
||||
): Promise<void> {
|
||||
if (Buffer.byteLength(payload, "utf8") >= MAX_PAYLOAD_BYTES) {
|
||||
this.logger.debug({ pluginName }, "OpenProtocol payload exceeded size limit");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await this.transport.sendPluginCommand(pluginName, payload, invokerId);
|
||||
} catch (err) {
|
||||
this.logger.debug(
|
||||
{ err, pluginName, invokerId },
|
||||
"Failed to send OpenProtocol response",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private dispatchAnnounce(expectedGen: number): void {
|
||||
if (expectedGen !== this.generation || this.transport.getClientId() <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.lastAnnounceAttemptMs = this.now();
|
||||
const seq = ++this.announceSeq;
|
||||
const payload = buildIdentityPayloadJson("announce", APP_VERSION, this.getConfig().commandPrefix);
|
||||
|
||||
if (Buffer.byteLength(payload, "utf8") >= MAX_PAYLOAD_BYTES) {
|
||||
this.logger.debug("OpenProtocol announce payload exceeded size limit");
|
||||
return;
|
||||
}
|
||||
|
||||
this.transport
|
||||
.sendPluginCommand(IDENTITY_PLUGIN, payload, "channel")
|
||||
.then(() => {
|
||||
if (expectedGen !== this.generation) return;
|
||||
this.lastSuccessSeq = Math.max(this.lastSuccessSeq, seq);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (expectedGen !== this.generation) return;
|
||||
this.logger.debug({ err }, "OpenProtocol announce broadcast failed");
|
||||
this.scheduleAnnounceRetry(expectedGen, seq);
|
||||
});
|
||||
}
|
||||
|
||||
private scheduleAnnounceRetry(expectedGen: number, failedSeq: number): void {
|
||||
if (this.retryAnnounceTimer) {
|
||||
clearTimeout(this.retryAnnounceTimer);
|
||||
this.retryAnnounceTimer = null;
|
||||
}
|
||||
|
||||
this.retryAnnounceTimer = setTimeout(() => {
|
||||
this.retryAnnounceTimer = null;
|
||||
if (
|
||||
expectedGen !== this.generation ||
|
||||
this.lastSuccessSeq >= failedSeq ||
|
||||
this.transport.getClientId() <= 0
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const retrySeq = ++this.announceSeq;
|
||||
const payload = buildIdentityPayloadJson("announce", APP_VERSION, this.getConfig().commandPrefix);
|
||||
this.lastAnnounceAttemptMs = this.now();
|
||||
this.transport
|
||||
.sendPluginCommand(IDENTITY_PLUGIN, payload, "channel")
|
||||
.then(() => {
|
||||
if (expectedGen !== this.generation) return;
|
||||
this.lastSuccessSeq = Math.max(this.lastSuccessSeq, retrySeq);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (expectedGen !== this.generation) return;
|
||||
this.logger.debug({ err }, "OpenProtocol announce retry failed");
|
||||
});
|
||||
}, ANNOUNCE_RETRY_DELAY_MS);
|
||||
this.retryAnnounceTimer.unref?.();
|
||||
}
|
||||
|
||||
private clearTimers(): void {
|
||||
if (this.trailingAnnounceTimer) {
|
||||
clearTimeout(this.trailingAnnounceTimer);
|
||||
this.trailingAnnounceTimer = null;
|
||||
}
|
||||
if (this.retryAnnounceTimer) {
|
||||
clearTimeout(this.retryAnnounceTimer);
|
||||
this.retryAnnounceTimer = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,21 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { toTS3TextMessage } from "./client.js";
|
||||
import type { TextMessage } from "@honeybbq/teamspeak-client";
|
||||
import {
|
||||
asClientID,
|
||||
asServerGroupID,
|
||||
asUID,
|
||||
type TextMessageEvent,
|
||||
} from "@honeybbq/teamspeak";
|
||||
|
||||
function makeMsg(over: Partial<TextMessage> = {}): TextMessage {
|
||||
function makeMsg(over: Partial<TextMessageEvent> = {}): TextMessageEvent {
|
||||
return {
|
||||
invokerName: "Alice",
|
||||
invokerUID: "uid-abc",
|
||||
invokerUID: asUID("uid-abc"),
|
||||
message: "!stop",
|
||||
invokerGroups: ["6", "8"],
|
||||
invokerGroups: [asServerGroupID(6n), asServerGroupID(8n)],
|
||||
targetMode: 2,
|
||||
targetID: 0n,
|
||||
invokerID: 5,
|
||||
targetID: asClientID(0),
|
||||
invokerID: asClientID(5),
|
||||
...over,
|
||||
};
|
||||
}
|
||||
@@ -26,18 +31,20 @@ describe("toTS3TextMessage", () => {
|
||||
});
|
||||
|
||||
it("preserves the sender's server groups", () => {
|
||||
expect(toTS3TextMessage(makeMsg({ invokerGroups: ["6"] })).invokerGroups).toEqual(["6"]);
|
||||
expect(
|
||||
toTS3TextMessage(makeMsg({ invokerGroups: [asServerGroupID(6n)] })).invokerGroups,
|
||||
).toEqual(["6"]);
|
||||
});
|
||||
|
||||
it("defaults missing invokerGroups to an empty array", () => {
|
||||
const partial = {
|
||||
invokerName: "Bob",
|
||||
invokerUID: "u",
|
||||
invokerUID: asUID("u"),
|
||||
message: "!stop",
|
||||
targetMode: 1,
|
||||
targetID: 0n,
|
||||
invokerID: 7,
|
||||
} as unknown as TextMessage;
|
||||
targetID: asClientID(0),
|
||||
invokerID: asClientID(7),
|
||||
} as unknown as TextMessageEvent;
|
||||
expect(toTS3TextMessage(partial).invokerGroups).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { AddrResolver, ResolvedAddr } from "@honeybbq/teamspeak-client";
|
||||
import type { AddrResolver, ResolvedAddr } from "@honeybbq/teamspeak/client";
|
||||
import { TrackingVoiceEndpointResolver } from "./voice-endpoint.js";
|
||||
|
||||
function result(addr: string): ResolvedAddr {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { lookup } from "node:dns/promises";
|
||||
import { isIP } from "node:net";
|
||||
import { Resolver } from "@honeybbq/teamspeak-client/discovery";
|
||||
import { Resolver } from "@honeybbq/teamspeak/client";
|
||||
import type {
|
||||
AddrResolver,
|
||||
ResolvedAddr,
|
||||
} from "@honeybbq/teamspeak-client";
|
||||
} from "@honeybbq/teamspeak/client";
|
||||
|
||||
export interface ResolvedVoiceEndpoint {
|
||||
host: string;
|
||||
@@ -66,9 +66,12 @@ export class TrackingVoiceEndpointResolver implements AddrResolver {
|
||||
private readonly resolveHost: ResolveIpv4 = resolveIpv4,
|
||||
) {}
|
||||
|
||||
async resolve(input: string, signal?: AbortSignal): Promise<ResolvedAddr[]> {
|
||||
async resolve(
|
||||
input: string,
|
||||
options?: { readonly signal?: AbortSignal },
|
||||
): Promise<readonly ResolvedAddr[]> {
|
||||
this.endpoint = null;
|
||||
const candidates = await this.delegate.resolve(input, signal);
|
||||
const candidates = await this.delegate.resolve(input, options);
|
||||
const selected = candidates[0];
|
||||
if (!selected) return candidates;
|
||||
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
function loadAppVersion(): string {
|
||||
try {
|
||||
const manifest = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")) as { version?: unknown };
|
||||
if (typeof manifest.version === "string" && manifest.version.trim()) {
|
||||
return manifest.version.trim();
|
||||
}
|
||||
} catch {
|
||||
// A custom bundle may omit the package manifest.
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
export const APP_VERSION = loadAppVersion();
|
||||
@@ -3,6 +3,7 @@ import express from "express";
|
||||
import request from "supertest";
|
||||
import pino from "pino";
|
||||
import type { MusicProvider } from "../../music/provider.js";
|
||||
import type { QQMusicProvider } from "../../music/qq.js";
|
||||
import { getDefaultConfig, type JellyfinConfig } from "../../data/config.js";
|
||||
import { createAuthRouter } from "./auth.js";
|
||||
|
||||
@@ -72,3 +73,79 @@ describe("auth router POST /jellyfin/test", () => {
|
||||
expect(testConnection).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("managed QQ authentication routes", () => {
|
||||
function mount(managed: boolean, user: unknown = { role: "admin" }) {
|
||||
const renewal = {
|
||||
renewalStatus: "scheduled" as const,
|
||||
nextRefreshAt: "2026-11-10T00:00:00.000Z",
|
||||
lastRefreshAt: "2026-11-09T00:00:00.000Z",
|
||||
};
|
||||
const refresh = vi.fn().mockResolvedValue("refreshed");
|
||||
const qq = {
|
||||
platform: "qq",
|
||||
managedSession: managed ? { refresh, getStatus: () => renewal } : undefined,
|
||||
checkQrCodeStatus: vi.fn().mockResolvedValue("confirmed"),
|
||||
setCookie: vi.fn(),
|
||||
getCookie: () => "private-test-cookie",
|
||||
getAuthStatus: vi.fn().mockResolvedValue({ loggedIn: true }),
|
||||
} as unknown as QQMusicProvider;
|
||||
const legacyStore = { load: vi.fn(), save: vi.fn() };
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => { (req as { user?: unknown }).user = user; next(); });
|
||||
app.use("/api/auth", createAuthRouter(
|
||||
fakeProvider("netease"), qq, fakeProvider("bilibili"), pino({ level: "silent" }), legacyStore,
|
||||
));
|
||||
return { app, qq, refresh, legacyStore };
|
||||
}
|
||||
|
||||
it("returns status only and delegates persistence to the managed session", async () => {
|
||||
const { app, qq, refresh, legacyStore } = mount(true);
|
||||
await request(app).get("/api/auth/qrcode/status").query({ platform: "qq", key: "opaque" }).expect(200);
|
||||
await request(app).post("/api/auth/cookie").send({ platform: "qq", cookie: "uin=1" }).expect(200);
|
||||
expect(qq.setCookie).toHaveBeenCalledWith("uin=1");
|
||||
expect(legacyStore.save).not.toHaveBeenCalled();
|
||||
const status = await request(app).get("/api/auth/status").query({ platform: "qq" }).expect(200);
|
||||
expect(status.body.lastRefreshAt).toBe("2026-11-09T00:00:00.000Z");
|
||||
const res = await request(app).post("/api/auth/qq/refresh").expect(200);
|
||||
expect(res.body).toEqual({
|
||||
outcome: "refreshed", renewalStatus: "scheduled", nextRefreshAt: "2026-11-10T00:00:00.000Z",
|
||||
lastRefreshAt: "2026-11-09T00:00:00.000Z",
|
||||
});
|
||||
expect(refresh).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("guards managed QQ polling and refresh with platform.auth", async () => {
|
||||
const { app, qq, refresh } = mount(true, { role: "member", capabilities: new Set() });
|
||||
await request(app).get("/api/auth/qrcode/status").query({ platform: "qq", key: "opaque" }).expect(403);
|
||||
await request(app).post("/api/auth/qq/refresh").expect(403);
|
||||
expect(qq.checkQrCodeStatus).not.toHaveBeenCalled();
|
||||
expect(refresh).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps the current QQ login when an import contains only response attributes", async () => {
|
||||
const { app, qq } = mount(true);
|
||||
await request(app).post("/api/auth/cookie")
|
||||
.send({ platform: "qq", cookie: "Path=/; HttpOnly" })
|
||||
.expect(400);
|
||||
expect(qq.setCookie).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("continues persisting the legacy cookie when the feature is disabled", async () => {
|
||||
const { app, legacyStore } = mount(false);
|
||||
await request(app).get("/api/auth/qrcode/status").query({ platform: "qq", key: "legacy" }).expect(200);
|
||||
expect(legacyStore.save).toHaveBeenCalledWith("qq", "private-test-cookie");
|
||||
await request(app).post("/api/auth/qq/refresh").expect(404);
|
||||
});
|
||||
|
||||
it("keeps the current QQ cookie when an unmanaged import cannot be saved", async () => {
|
||||
const { app, qq, legacyStore } = mount(false);
|
||||
legacyStore.save.mockImplementationOnce(() => { throw new Error("test write failed"); });
|
||||
await request(app).post("/api/auth/cookie").send({ platform: "qq", cookie: "uin=999" }).expect(503);
|
||||
expect(qq.setCookie).not.toHaveBeenCalled();
|
||||
await request(app).post("/api/auth/cookie").send({ platform: "qq", cookie: "uin=999" }).expect(200);
|
||||
expect(legacyStore.save).toHaveBeenLastCalledWith("qq", "uin=999");
|
||||
expect(qq.setCookie).toHaveBeenCalledWith("uin=999");
|
||||
});
|
||||
});
|
||||
+95
-12
@@ -1,24 +1,34 @@
|
||||
import { Router } from "express";
|
||||
import type { ParamsDictionary } from "express-serve-static-core";
|
||||
import type { MusicProvider } from "../../music/provider.js";
|
||||
import type { QQMusicProvider } from "../../music/qq.js";
|
||||
import { normalizeCookie } from "../../music/cookie-normalize.js";
|
||||
import { musicRequestError } from "../../music/request-error.js";
|
||||
import { YouTubeProvider } from "../../music/youtube.js";
|
||||
import type { CookieStore } from "../../music/auth.js";
|
||||
import type { Logger } from "../../logger.js";
|
||||
import type { BotConfig, JellyfinConfig } from "../../data/config.js";
|
||||
import type { BotDatabase } from "../../data/database.js";
|
||||
import { requirePermission } from "../middleware/requirePermission.js";
|
||||
import { requireNotGuest } from "../middleware/requireNotGuest.js";
|
||||
import { resolveMusicCookie } from "./provider-scope.js";
|
||||
|
||||
export function createAuthRouter(
|
||||
neteaseProvider: MusicProvider,
|
||||
qqProvider: MusicProvider,
|
||||
qqProvider: MusicProvider & Partial<Pick<QQMusicProvider, "managedSession">>,
|
||||
bilibiliProvider: MusicProvider,
|
||||
logger: Logger,
|
||||
cookieStore?: CookieStore,
|
||||
kugouProvider?: MusicProvider,
|
||||
spotifyProvider?: MusicProvider,
|
||||
jellyfinProvider?: MusicProvider,
|
||||
config?: BotConfig
|
||||
config?: BotConfig,
|
||||
// Per-user music accounts (#164 follow-up). Omitted by unit-test routers →
|
||||
// every caller keeps seeing the bot's shared login status.
|
||||
database?: BotDatabase,
|
||||
): Router {
|
||||
const router = Router();
|
||||
const qqSession = qqProvider.managedSession;
|
||||
// YouTube is auth-less; we only use this instance so /auth/status can
|
||||
// report whether yt-dlp is actually installed (loggedIn=false otherwise).
|
||||
const youtubeProvider: MusicProvider = new YouTubeProvider();
|
||||
@@ -36,12 +46,56 @@ export function createAuthRouter(
|
||||
try {
|
||||
const platform = req.query.platform as string;
|
||||
const provider = getProvider(platform);
|
||||
// Per-user accounts (#164 follow-up). Two different questions, two
|
||||
// different answers:
|
||||
//
|
||||
// /api/auth/status → "is the BOT's shared login alive?" This is the
|
||||
// admin console (Settings → 音乐平台), so an
|
||||
// admin always gets the shared status even if
|
||||
// they linked or were assigned a personal one.
|
||||
// /api/me/music/status → "which account does THIS user actually play
|
||||
// through?" (personal-music.ts) — that one does
|
||||
// report the personal/granted view.
|
||||
//
|
||||
// For a non-admin the shared nickname/avatar must never be returned: that
|
||||
// is exactly the leak this feature exists to close, so they get
|
||||
// loggedIn:false instead until they have an account of their own.
|
||||
const user = (req as { user?: { id?: string; role?: string } }).user;
|
||||
// A platform without per-account login support (spotify / jellyfin /
|
||||
// youtube) keeps reporting the shared status for everyone: the toggle only
|
||||
// governs sources that can actually build a per-user view.
|
||||
const perUser =
|
||||
config?.perUserMusicAccounts === true &&
|
||||
user?.role !== "admin" &&
|
||||
typeof provider.withCookie === "function";
|
||||
|
||||
if (perUser) {
|
||||
const own = resolveMusicCookie(req, provider.platform, { database, config });
|
||||
if (own && typeof provider.withCookie === "function") {
|
||||
const view = provider.withCookie(own.cookie);
|
||||
const status = await view.getAuthStatus();
|
||||
res.json({
|
||||
platform: provider.platform,
|
||||
personal: true,
|
||||
source: own.source,
|
||||
// Admin-facing name for an assigned account; absent for self-linked.
|
||||
label: own.label,
|
||||
...status,
|
||||
});
|
||||
return;
|
||||
}
|
||||
res.json({ platform: provider.platform, loggedIn: false, personal: true, source: "none" });
|
||||
return;
|
||||
}
|
||||
|
||||
const status = await provider.getAuthStatus();
|
||||
logger.debug({ platform, status }, "Auth status check");
|
||||
res.json({ platform: provider.platform, ...status });
|
||||
logger.debug({ platform, loggedIn: status.loggedIn }, "Auth status check");
|
||||
const renewal = platform === "qq" ? qqSession?.getStatus() : undefined;
|
||||
res.json({ platform: provider.platform, source: "shared", ...status, ...renewal });
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Auth status check failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
const error = musicRequestError(err);
|
||||
logger.error({ err: error }, "Auth status check failed");
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -50,7 +104,7 @@ export function createAuthRouter(
|
||||
const { platform } = req.body;
|
||||
const provider = getProvider(platform);
|
||||
const qr = await provider.getQrCode();
|
||||
logger.info({ platform, key: qr.key }, "QR code generated");
|
||||
logger.info({ platform }, "QR code generated");
|
||||
res.json(qr);
|
||||
} catch (err) {
|
||||
logger.error({ err }, "QR code generation failed");
|
||||
@@ -58,7 +112,11 @@ export function createAuthRouter(
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/qrcode/status", requireNotGuest, async (req, res) => {
|
||||
const requirePlatformAuth = requirePermission<ParamsDictionary>("platform.auth");
|
||||
router.get("/qrcode/status", requireNotGuest, (req, res, next) => {
|
||||
if (qqSession && req.query.platform === "qq") requirePlatformAuth(req, res, next);
|
||||
else next();
|
||||
}, async (req, res) => {
|
||||
try {
|
||||
const { key, platform } = req.query;
|
||||
if (!key) {
|
||||
@@ -67,10 +125,10 @@ export function createAuthRouter(
|
||||
}
|
||||
const provider = getProvider(platform as string);
|
||||
const status = await provider.checkQrCodeStatus(key as string);
|
||||
logger.info({ platform, status, key }, "QR status check");
|
||||
logger.info({ platform, status }, "QR status check");
|
||||
|
||||
// When confirmed, persist cookie
|
||||
if (status === "confirmed") {
|
||||
if (status === "confirmed" && !(platform === "qq" && qqSession)) {
|
||||
const cookie = provider.getCookie();
|
||||
const plat = (platform as string) === "bilibili" ? "bilibili" as const
|
||||
: (platform as string) === "kugou" ? "kugou" as const
|
||||
@@ -88,6 +146,19 @@ export function createAuthRouter(
|
||||
}
|
||||
});
|
||||
|
||||
router.post("/qq/refresh", requirePlatformAuth, async (_req, res) => {
|
||||
if (!qqSession) {
|
||||
res.status(404).json({ outcome: "disabled" });
|
||||
return;
|
||||
}
|
||||
const outcome = await qqSession.refresh();
|
||||
const status = outcome === "refreshed" ? 200
|
||||
: outcome === "cooldown" || outcome === "rate_limited" ? 429
|
||||
: outcome === "reauth_required" || outcome === "superseded" ? 409
|
||||
: outcome === "persist_failed" ? 503 : 502;
|
||||
res.status(status).json({ outcome, ...qqSession.getStatus() });
|
||||
});
|
||||
|
||||
// Jellyfin has no QR/cookie flow — the connection is admin-configured. This
|
||||
// round-trips /System/Info so Settings can verify form values BEFORE saving.
|
||||
// Empty/missing credential fields fall back to the stored config, so a
|
||||
@@ -169,7 +240,8 @@ export function createAuthRouter(
|
||||
});
|
||||
|
||||
router.post("/cookie", requirePermission("platform.auth"), (req, res) => {
|
||||
const { platform, cookie } = req.body;
|
||||
const { platform, cookie: raw } = req.body;
|
||||
const cookie = typeof raw === "string" ? normalizeCookie(raw) : "";
|
||||
if (!cookie) {
|
||||
res.status(400).json({ error: "cookie is required" });
|
||||
return;
|
||||
@@ -191,10 +263,21 @@ export function createAuthRouter(
|
||||
return;
|
||||
}
|
||||
const provider = getProvider(platform);
|
||||
if (platform === "qq") {
|
||||
try {
|
||||
if (!qqSession) cookieStore?.save("qq", cookie);
|
||||
provider.setCookie(cookie);
|
||||
res.json({ success: true });
|
||||
} catch {
|
||||
logger.warn("Could not save imported QQ cookie");
|
||||
res.status(503).json({ error: "Could not save QQ cookie" });
|
||||
}
|
||||
return;
|
||||
}
|
||||
provider.setCookie(cookie);
|
||||
const plat = platform === "bilibili" ? "bilibili" as const
|
||||
: platform === "kugou" ? "kugou" as const
|
||||
: platform === "qq" ? "qq" as const : "netease" as const;
|
||||
: "netease" as const;
|
||||
if (cookieStore) {
|
||||
cookieStore.save(plat, cookie);
|
||||
}
|
||||
|
||||
+10
-2
@@ -677,12 +677,12 @@ describe("bot router /settings jellyfin block + enabledProviders", () => {
|
||||
rmSync(tmpDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function mountBot(): express.Express {
|
||||
function mountBot(user: unknown = { role: "admin" }): express.Express {
|
||||
const fakeManager = { getAllBots: () => [] } as unknown as BotManager;
|
||||
const avatarStore = createAvatarStore(tmpDir);
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => { (req as { user?: unknown }).user = { role: "admin" }; next(); });
|
||||
app.use((req, _res, next) => { (req as { user?: unknown }).user = user; next(); });
|
||||
app.use(
|
||||
"/api/bot",
|
||||
createBotRouter(
|
||||
@@ -694,6 +694,14 @@ describe("bot router /settings jellyfin block + enabledProviders", () => {
|
||||
return app;
|
||||
}
|
||||
|
||||
it("reserves the music-account policy toggle for administrators", async () => {
|
||||
const member = mountBot({ role: "member", capabilities: new Set(["bot.manage"]) });
|
||||
await request(member).post("/api/bot/settings").send({ perUserMusicAccounts: true }).expect(403);
|
||||
expect(config.perUserMusicAccounts).toBe(false);
|
||||
await request(mountBot()).post("/api/bot/settings").send({ perUserMusicAccounts: true }).expect(200);
|
||||
expect(config.perUserMusicAccounts).toBe(true);
|
||||
});
|
||||
|
||||
it("GET /settings exposes a masked jellyfin block (no password/apiKey echo)", async () => {
|
||||
config.jellyfin.serverUrl = "https://jf.example.com";
|
||||
config.jellyfin.password = "secret";
|
||||
|
||||
@@ -74,7 +74,10 @@ export function createBotRouter(
|
||||
voiceDucking: config.voiceDucking,
|
||||
localAudioEnabled: config.localAudioEnabled,
|
||||
savedQueuesEnabled: config.savedQueuesEnabled,
|
||||
perUserMusicAccounts: config.perUserMusicAccounts === true,
|
||||
playKeepsQueue: config.playKeepsQueue,
|
||||
// Silent re-resolve budget for a track whose URL came back empty.
|
||||
playUrlRetries: config.playUrlRetries ?? 0,
|
||||
adminGroups: config.adminGroups ?? [],
|
||||
guestMode: config.guestMode,
|
||||
spotify: maskedSpotify(),
|
||||
@@ -94,6 +97,8 @@ export function createBotRouter(
|
||||
voiceDucking,
|
||||
guestMode,
|
||||
adminGroups,
|
||||
playUrlRetries,
|
||||
perUserMusicAccounts,
|
||||
} = req.body;
|
||||
|
||||
const hasIdle = idleTimeoutMinutes !== undefined;
|
||||
@@ -104,10 +109,31 @@ export function createBotRouter(
|
||||
|
||||
const hasAutoPause = typeof autoPauseOnEmpty === "boolean";
|
||||
const hasLocalAudioEnabled = typeof localAudioEnabled === "boolean";
|
||||
// Retry budget is an integer 0..5; out-of-range is a client bug, not
|
||||
// something to silently clamp, so it 400s like the other numeric fields.
|
||||
const hasPlayUrlRetries = playUrlRetries !== undefined;
|
||||
if (
|
||||
hasPlayUrlRetries &&
|
||||
(typeof playUrlRetries !== "number" ||
|
||||
!Number.isInteger(playUrlRetries) ||
|
||||
playUrlRetries < 0 ||
|
||||
playUrlRetries > 5)
|
||||
) {
|
||||
res.status(400).json({ error: "playUrlRetries must be an integer 0-5" });
|
||||
return;
|
||||
}
|
||||
|
||||
const hasPerUserMusicAccounts = typeof perUserMusicAccounts === "boolean";
|
||||
if (hasPerUserMusicAccounts && req.user?.role !== "admin") {
|
||||
res.status(403).json({ error: "forbidden" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (hasIdle) config.idleTimeoutMinutes = idleTimeoutMinutes;
|
||||
if (hasAutoPause) config.autoPauseOnEmpty = autoPauseOnEmpty;
|
||||
if (hasLocalAudioEnabled) config.localAudioEnabled = localAudioEnabled;
|
||||
if (hasPlayUrlRetries) config.playUrlRetries = playUrlRetries;
|
||||
if (hasPerUserMusicAccounts) config.perUserMusicAccounts = perUserMusicAccounts;
|
||||
|
||||
// Voice ducking is a partial settings block. Merge only known, strictly
|
||||
// valid fields so malformed JSON cannot replace the object or inject NaN /
|
||||
@@ -282,7 +308,10 @@ export function createBotRouter(
|
||||
voiceDucking: config.voiceDucking,
|
||||
localAudioEnabled: config.localAudioEnabled,
|
||||
savedQueuesEnabled: config.savedQueuesEnabled,
|
||||
perUserMusicAccounts: config.perUserMusicAccounts === true,
|
||||
playKeepsQueue: config.playKeepsQueue,
|
||||
// Silent re-resolve budget for a track whose URL came back empty.
|
||||
playUrlRetries: config.playUrlRetries ?? 0,
|
||||
adminGroups: config.adminGroups ?? [],
|
||||
guestMode: config.guestMode,
|
||||
spotify: maskedSpotify(),
|
||||
|
||||
@@ -0,0 +1,273 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import express from "express";
|
||||
import request from "supertest";
|
||||
import pino from "pino";
|
||||
import { createDatabase } from "../../data/database.js";
|
||||
import { createUserStore } from "../../data/users.js";
|
||||
import { createMusicAccountsRouter } from "./music-accounts.js";
|
||||
|
||||
function mount(opts: { cookieStore?: { save: any; load: any }; providers?: Record<string, any> } = {}) {
|
||||
const db = createDatabase(":memory:");
|
||||
const insert = db.db.prepare(
|
||||
"INSERT INTO users (id, username, passwordHash, createdAt, updatedAt, role) VALUES (?,?,?,?,?,?)",
|
||||
);
|
||||
insert.run("u1", "alice", "x", 0, 0, "member");
|
||||
insert.run("u2", "bob", "x", 0, 0, "member");
|
||||
insert.run("u3", "carol", "x", 0, 0, "member");
|
||||
insert.run("u4", "root2", "x", 0, 0, "admin");
|
||||
|
||||
const users = createUserStore(db.db);
|
||||
const providers = opts.providers ?? {
|
||||
netease: {
|
||||
platform: "netease",
|
||||
withCookie: vi.fn(() => ({ getAuthStatus: async () => ({ loggedIn: true, nickname: "主号" }) })),
|
||||
},
|
||||
};
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => {
|
||||
(req as any).user = { id: "admin", username: "admin", role: "admin" };
|
||||
next();
|
||||
});
|
||||
app.use(
|
||||
"/api/music-accounts",
|
||||
createMusicAccountsRouter(db, users, providers as any, pino({ level: "silent" }), opts.cookieStore as any),
|
||||
);
|
||||
return { app, db, providers };
|
||||
}
|
||||
|
||||
const SECRET = "MUSIC_U=abcdefghijklmnopqrstuvwxyz0123456789";
|
||||
|
||||
async function seed(app: express.Express, over: Record<string, unknown> = {}) {
|
||||
const res = await request(app)
|
||||
.post("/api/music-accounts")
|
||||
.send({ platform: "netease", label: "主号", cookie: SECRET, ...over });
|
||||
return res;
|
||||
}
|
||||
|
||||
describe("admin music account pool", () => {
|
||||
it("creates an account and never echoes the cookie", async () => {
|
||||
const { app } = mount();
|
||||
const res = await seed(app);
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body.label).toBe("主号");
|
||||
expect(res.body.capacity).toBe(0);
|
||||
expect(res.body.enabled).toBe(true);
|
||||
expect(JSON.stringify(res.body)).not.toContain(SECRET);
|
||||
expect(res.body.cookiePreview).toContain("…");
|
||||
});
|
||||
|
||||
it("rejects an unknown platform and a missing cookie", async () => {
|
||||
const { app } = mount();
|
||||
expect((await seed(app, { platform: "deezer" })).status).toBe(400);
|
||||
expect((await seed(app, { cookie: "" })).status).toBe(400);
|
||||
expect((await seed(app, { label: "" })).status).toBe(400);
|
||||
});
|
||||
|
||||
it("lists accounts with their holders and the assignable users", async () => {
|
||||
const { app } = mount();
|
||||
const created = await seed(app);
|
||||
await request(app).post(`/api/music-accounts/${created.body.id}/assign`).send({ userId: "u1" });
|
||||
|
||||
const res = await request(app).get("/api/music-accounts");
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.accounts).toHaveLength(1);
|
||||
expect(res.body.accounts[0].granteeCount).toBe(1);
|
||||
expect(res.body.accounts[0].grantees[0]).toMatchObject({ userId: "u1", username: "alice" });
|
||||
// Guests are excluded from the dropdown by UserStore.listUsers().
|
||||
expect(res.body.users.map((u: any) => u.username)).toEqual(["alice", "bob", "carol", "root2"]);
|
||||
expect(JSON.stringify(res.body)).not.toContain(SECRET);
|
||||
});
|
||||
|
||||
it("toggles enabled and capacity", async () => {
|
||||
const { app } = mount();
|
||||
const created = await seed(app);
|
||||
const res = await request(app)
|
||||
.patch(`/api/music-accounts/${created.body.id}`)
|
||||
.send({ enabled: false, capacity: 1, label: "备用" });
|
||||
expect(res.body).toEqual(expect.objectContaining({ enabled: false, capacity: 1, label: "备用" }));
|
||||
});
|
||||
|
||||
it("enforces exclusive capacity (capacity = 1)", async () => {
|
||||
const { app } = mount();
|
||||
const created = await seed(app, { capacity: 1 });
|
||||
const id = created.body.id;
|
||||
|
||||
expect((await request(app).post(`/api/music-accounts/${id}/assign`).send({ userId: "u1" })).status).toBe(200);
|
||||
const second = await request(app).post(`/api/music-accounts/${id}/assign`).send({ userId: "u2" });
|
||||
expect(second.status).toBe(409);
|
||||
expect(second.body.error).toBe("account_exclusive");
|
||||
expect(second.body.holders).toEqual([{ userId: "u1", username: "alice" }]);
|
||||
|
||||
// Re-assigning the SAME user is idempotent, not a conflict.
|
||||
expect((await request(app).post(`/api/music-accounts/${id}/assign`).send({ userId: "u1" })).status).toBe(200);
|
||||
});
|
||||
|
||||
it("enforces a numeric capacity", async () => {
|
||||
const { app } = mount();
|
||||
const created = await seed(app, { capacity: 2 });
|
||||
const id = created.body.id;
|
||||
expect((await request(app).post(`/api/music-accounts/${id}/assign`).send({ userId: "u1" })).status).toBe(200);
|
||||
expect((await request(app).post(`/api/music-accounts/${id}/assign`).send({ userId: "u2" })).status).toBe(200);
|
||||
const third = await request(app).post(`/api/music-accounts/${id}/assign`).send({ userId: "u3" });
|
||||
expect(third.status).toBe(409);
|
||||
expect(third.body.error).toBe("account_full");
|
||||
});
|
||||
|
||||
it("allows unlimited grantees when capacity is 0", async () => {
|
||||
const { app } = mount();
|
||||
const created = await seed(app);
|
||||
for (const userId of ["u1", "u2", "u3", "u4"]) {
|
||||
expect(
|
||||
(await request(app).post(`/api/music-accounts/${created.body.id}/assign`).send({ userId })).status,
|
||||
).toBe(200);
|
||||
}
|
||||
// An admin can be a grantee too — "assigning an admin out" is allowed.
|
||||
const list = await request(app).get("/api/music-accounts");
|
||||
expect(list.body.accounts[0].grantees.map((g: any) => g.username).sort()).toEqual([
|
||||
"alice", "bob", "carol", "root2",
|
||||
]);
|
||||
});
|
||||
|
||||
it("refuses an assignment to a missing user", async () => {
|
||||
const { app } = mount();
|
||||
const created = await seed(app);
|
||||
expect(
|
||||
(await request(app).post(`/api/music-accounts/${created.body.id}/assign`).send({ userId: "nope" })).status,
|
||||
).toBe(404);
|
||||
});
|
||||
|
||||
it("refuses an assignment from a disabled account", async () => {
|
||||
const { app } = mount();
|
||||
const created = await seed(app, { enabled: false });
|
||||
const res = await request(app)
|
||||
.post(`/api/music-accounts/${created.body.id}/assign`)
|
||||
.send({ userId: "u1" });
|
||||
expect(res.status).toBe(409);
|
||||
expect(res.body.error).toBe("account_disabled");
|
||||
});
|
||||
|
||||
it("replaces the previous assignment for the same platform", async () => {
|
||||
const { app, db } = mount();
|
||||
const first = await seed(app, { label: "一号" });
|
||||
const second = await seed(app, { label: "二号" });
|
||||
await request(app).post(`/api/music-accounts/${first.body.id}/assign`).send({ userId: "u1" });
|
||||
const res = await request(app)
|
||||
.post(`/api/music-accounts/${second.body.id}/assign`)
|
||||
.send({ userId: "u1" });
|
||||
expect(res.body.replacedAccountId).toBe(first.body.id);
|
||||
|
||||
// PK (userId, platform) keeps it to one assigned login per platform.
|
||||
const grants = db.listAllMusicAccountGrants().filter((g) => g.userId === "u1");
|
||||
expect(grants).toHaveLength(1);
|
||||
expect(grants[0].accountId).toBe(second.body.id);
|
||||
});
|
||||
|
||||
it("revokes a single assignment", async () => {
|
||||
const { app, db } = mount();
|
||||
const created = await seed(app);
|
||||
await request(app).post(`/api/music-accounts/${created.body.id}/assign`).send({ userId: "u1" });
|
||||
const res = await request(app).delete(`/api/music-accounts/${created.body.id}/assign/u1`);
|
||||
expect(res.body).toEqual({ ok: true, removed: true });
|
||||
expect(db.getGrantedMusicAccount("u1", "netease")).toBeNull();
|
||||
});
|
||||
|
||||
it("preserves a replacement assignment when an old assignment is revoked", async () => {
|
||||
const { app, db } = mount();
|
||||
const first = await seed(app, { label: "一号" });
|
||||
const second = await seed(app, { label: "二号" });
|
||||
for (const account of [first, second]) {
|
||||
await request(app).post(`/api/music-accounts/${account.body.id}/assign`).send({ userId: "u1" }).expect(200);
|
||||
}
|
||||
const res = await request(app).delete(`/api/music-accounts/${first.body.id}/assign/u1`).expect(200);
|
||||
expect(res.body.removed).toBe(false);
|
||||
expect(db.getGrantedMusicAccount("u1", "netease")?.accountId).toBe(second.body.id);
|
||||
});
|
||||
|
||||
it("does not lower the capacity below the current number of assignees", async () => {
|
||||
const { app, db } = mount();
|
||||
const id = (await seed(app)).body.id;
|
||||
for (const userId of ["u1", "u2"]) {
|
||||
await request(app).post(`/api/music-accounts/${id}/assign`).send({ userId }).expect(200);
|
||||
}
|
||||
await request(app).patch(`/api/music-accounts/${id}`).send({ capacity: 1 }).expect(409);
|
||||
expect(db.getMusicAccount(id)?.capacity).toBe(0);
|
||||
});
|
||||
|
||||
// Deleting the account must not leave grants pointing at a dead row.
|
||||
it("cascades grantees when the account is deleted", async () => {
|
||||
const { app, db } = mount();
|
||||
const created = await seed(app);
|
||||
await request(app).post(`/api/music-accounts/${created.body.id}/assign`).send({ userId: "u1" });
|
||||
expect((await request(app).delete(`/api/music-accounts/${created.body.id}`)).status).toBe(200);
|
||||
expect(db.listMusicAccounts()).toHaveLength(0);
|
||||
expect(db.getGrantedMusicAccount("u1", "netease")).toBeNull();
|
||||
});
|
||||
|
||||
it("probes the login and reports unsupported platforms", async () => {
|
||||
const { app } = mount();
|
||||
const created = await seed(app);
|
||||
const ok = await request(app).post(`/api/music-accounts/${created.body.id}/probe`);
|
||||
expect(ok.body).toEqual({ ok: true, loggedIn: true, nickname: "主号" });
|
||||
|
||||
// kugou without a withCookie implementation → 501, not a crash.
|
||||
const kugou = await seed(app, { platform: "kugou", label: "酷狗" });
|
||||
expect(kugou.status).toBe(201);
|
||||
expect((await request(app).post(`/api/music-accounts/${kugou.body.id}/probe`)).status).toBe(501);
|
||||
});
|
||||
|
||||
it("imports the shared login into the pool", async () => {
|
||||
const cookieStore = {
|
||||
save: vi.fn(),
|
||||
load: vi.fn(() => "MUSIC_U=shared"),
|
||||
};
|
||||
const { app } = mount({ cookieStore });
|
||||
const res = await request(app)
|
||||
.post("/api/music-accounts/import-shared")
|
||||
.send({ platform: "netease", label: "从共享导入" });
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body.label).toBe("从共享导入");
|
||||
expect(cookieStore.load).toHaveBeenCalledWith("netease");
|
||||
});
|
||||
|
||||
it("409s import-shared when the bot has no shared login", async () => {
|
||||
const cookieStore = { save: vi.fn(), load: vi.fn(() => "") };
|
||||
const { app } = mount({ cookieStore });
|
||||
const res = await request(app)
|
||||
.post("/api/music-accounts/import-shared")
|
||||
.send({ platform: "netease" });
|
||||
expect(res.status).toBe(409);
|
||||
expect(res.body.error).toBe("no_shared_login");
|
||||
});
|
||||
|
||||
it("imports the running QQ cookie instead of the stale file copy", async () => {
|
||||
const cookieStore = { save: vi.fn(), load: vi.fn(() => "uin=999; qm_keyst=stale") };
|
||||
const qq = {
|
||||
platform: "qq",
|
||||
withCookie: vi.fn(),
|
||||
// 托管会话轮换后,内存里已经是新 cookie,qq.json 还是旧的
|
||||
getCookie: () => "uin=1; qm_keyst=rotated",
|
||||
};
|
||||
const { app, db } = mount({ cookieStore, providers: { qq } });
|
||||
const res = await request(app)
|
||||
.post("/api/music-accounts/import-shared")
|
||||
.send({ platform: "qq", label: "QQ 主号" });
|
||||
expect(res.status).toBe(201);
|
||||
expect(db.listMusicAccounts()[0]?.cookie).toBe("uin=1; qm_keyst=rotated");
|
||||
expect(cookieStore.load).not.toHaveBeenCalled();
|
||||
// cookie 不出服务器:响应里不能出现完整值
|
||||
expect(JSON.stringify(res.body)).not.toContain("rotated");
|
||||
});
|
||||
|
||||
it("409s a QQ import when the running provider has no login", async () => {
|
||||
const cookieStore = { save: vi.fn(), load: vi.fn(() => "uin=999; qm_keyst=stale") };
|
||||
const qq = { platform: "qq", withCookie: vi.fn(), getCookie: () => "" };
|
||||
const { app, db } = mount({ cookieStore, providers: { qq } });
|
||||
const res = await request(app)
|
||||
.post("/api/music-accounts/import-shared")
|
||||
.send({ platform: "qq" });
|
||||
expect(res.status).toBe(409);
|
||||
expect(res.body.error).toBe("no_shared_login");
|
||||
expect(db.listMusicAccounts()).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,360 @@
|
||||
import { Router } from "express";
|
||||
import type { BotDatabase, MusicAccount } from "../../data/database.js";
|
||||
import type { MusicProvider } from "../../music/provider.js";
|
||||
import type { CookieStore } from "../../music/auth.js";
|
||||
import type { UserStore } from "../../data/users.js";
|
||||
import type { Logger } from "../../logger.js";
|
||||
import { PERSONAL_MUSIC_PLATFORMS } from "./personal-music.js";
|
||||
|
||||
/**
|
||||
* Admin console for the music-account pool (#164 follow-up).
|
||||
*
|
||||
* Why a pool instead of "everyone links their own account":
|
||||
* - Most members do not own a paid NetEase/QQ/Kugou login, and the bot's
|
||||
* shared account is usually the ADMIN's. Handing the shared login to some
|
||||
* members while giving others their own is exactly the "mixed" case this
|
||||
* feature has to support.
|
||||
* - So the admin keeps a pool of logins (`music_accounts`) and assigns one to
|
||||
* a member (`music_account_grants`). Assignment is per platform, and a
|
||||
* member can hold at most one assigned account per platform.
|
||||
*
|
||||
* The controls that stop assignments from turning into a mess:
|
||||
* 1. OWN BEATS ASSIGNED. A member who linked their own account ignores the
|
||||
* assignment entirely (see provider-scope.ts). Assigning never overrides
|
||||
* a member's own login.
|
||||
* 2. CAPACITY. `capacity = 1` means exclusive: the API refuses to hand the
|
||||
* same login to a second member (409). `capacity = 0` means unlimited
|
||||
* (fine for a throwaway account, NOT for one whose recommendations you
|
||||
* care about — every grantee writes to that account's history).
|
||||
* 3. ENABLED FLAG. Disabling an account is an instant, reversible rollback:
|
||||
* every grantee falls back to their own login / the shared login without
|
||||
* the grants being deleted.
|
||||
* 4. DELETE CASCADES. Removing an account deletes its grants in the same
|
||||
* transaction (FK ON DELETE CASCADE), so no member is left pointing at a
|
||||
* row that no longer exists.
|
||||
* 5. COOKIES NEVER LEAVE THE SERVER. Every response carries a masked
|
||||
* preview only; the full value is only ever written, never read back.
|
||||
*
|
||||
* The whole router is admin-only (requireAdmin at the mount point): a member
|
||||
* with `bot.manage` still must not see what other people are assigned.
|
||||
*/
|
||||
export function createMusicAccountsRouter(
|
||||
database: BotDatabase,
|
||||
users: UserStore,
|
||||
providers: Partial<Record<string, MusicProvider>>,
|
||||
logger: Logger,
|
||||
cookieStore?: CookieStore,
|
||||
): Router {
|
||||
const router = Router();
|
||||
|
||||
const knownPlatforms = new Set<string>(PERSONAL_MUSIC_PLATFORMS);
|
||||
|
||||
/**
|
||||
* Cookies are bearer credentials: showing one in full once is enough to take
|
||||
* the account over. The console only ever needs to tell two logins apart.
|
||||
*/
|
||||
const maskCookie = (cookie: string): string => {
|
||||
if (!cookie) return "";
|
||||
if (cookie.length <= 16) return "••••••";
|
||||
return `${cookie.slice(0, 6)}…${cookie.slice(-4)} (${cookie.length} 字符)`;
|
||||
};
|
||||
|
||||
const toWire = (a: MusicAccount) => {
|
||||
const holders = database.listMusicAccountGrants(a.id);
|
||||
return {
|
||||
id: a.id,
|
||||
platform: a.platform,
|
||||
label: a.label,
|
||||
cookiePreview: maskCookie(a.cookie),
|
||||
ownerId: a.ownerId,
|
||||
capacity: a.capacity,
|
||||
enabled: a.enabled,
|
||||
createdAt: a.createdAt,
|
||||
updatedAt: a.updatedAt,
|
||||
// The UI needs the count to grey out "assign" on an exclusive account.
|
||||
granteeCount: holders.length,
|
||||
grantees: holders.map((g) => ({
|
||||
userId: g.userId,
|
||||
username: g.username,
|
||||
grantedAt: g.grantedAt,
|
||||
})),
|
||||
// A platform without withCookie stores the cookie but cannot build a
|
||||
// per-account view yet — surfaced so the admin is not left guessing.
|
||||
playbackSupported: typeof providers[a.platform]?.withCookie === "function",
|
||||
};
|
||||
};
|
||||
|
||||
const isPlatform = (v: unknown): v is (typeof PERSONAL_MUSIC_PLATFORMS)[number] =>
|
||||
typeof v === "string" && knownPlatforms.has(v);
|
||||
|
||||
const nonEmpty = (v: unknown, max: number): v is string =>
|
||||
typeof v === "string" && v.trim().length > 0 && v.length <= max;
|
||||
|
||||
const validCapacity = (value: unknown): value is number | undefined =>
|
||||
value === undefined || (typeof value === "number" && Number.isSafeInteger(value) && value >= 0);
|
||||
|
||||
/** Every real (non-guest) user, for the assign dropdown. */
|
||||
const assignableUsers = () =>
|
||||
users.listUsers().map((u) => ({ id: u.id, username: u.username, role: u.role }));
|
||||
|
||||
router.get("/", (_req, res) => {
|
||||
const accounts = database.listMusicAccounts().map(toWire);
|
||||
res.json({
|
||||
accounts,
|
||||
users: assignableUsers(),
|
||||
platforms: [...PERSONAL_MUSIC_PLATFORMS].map((p) => ({
|
||||
platform: p,
|
||||
// Only platforms that implement withCookie can actually play back a
|
||||
// per-user login; the rest accept a paste but fall back to shared.
|
||||
playbackSupported: typeof providers[p]?.withCookie === "function",
|
||||
})),
|
||||
});
|
||||
});
|
||||
|
||||
router.post("/", (req, res) => {
|
||||
const { platform, label, cookie, capacity, ownerId, enabled } = req.body ?? {};
|
||||
if (!isPlatform(platform)) {
|
||||
res.status(400).json({ error: "unsupported platform" });
|
||||
return;
|
||||
}
|
||||
if (!nonEmpty(label, 64)) {
|
||||
res.status(400).json({ error: "label is required (max 64 chars)" });
|
||||
return;
|
||||
}
|
||||
if (!nonEmpty(cookie, 8192)) {
|
||||
res.status(400).json({ error: "cookie is required" });
|
||||
return;
|
||||
}
|
||||
if (!validCapacity(capacity)) {
|
||||
res.status(400).json({ error: "capacity must be a non-negative integer" });
|
||||
return;
|
||||
}
|
||||
if (ownerId !== undefined && ownerId !== null && typeof ownerId !== "string") {
|
||||
res.status(400).json({ error: "ownerId must be a string or null" });
|
||||
return;
|
||||
}
|
||||
if (enabled !== undefined && typeof enabled !== "boolean") {
|
||||
res.status(400).json({ error: "enabled must be a boolean" });
|
||||
return;
|
||||
}
|
||||
const created = database.createMusicAccount({
|
||||
platform,
|
||||
label: label.trim(),
|
||||
cookie: cookie.trim(),
|
||||
ownerId: ownerId ?? null,
|
||||
capacity,
|
||||
// Creating a disabled account is allowed: it lets the admin stage a
|
||||
// cookie before handing it out.
|
||||
enabled: enabled !== false,
|
||||
});
|
||||
logger.info({ accountId: created.id, platform, label: created.label }, "Music account added");
|
||||
res.status(201).json(toWire(created));
|
||||
});
|
||||
|
||||
router.patch("/:id", (req, res) => {
|
||||
const account = database.getMusicAccount(req.params.id);
|
||||
if (!account) {
|
||||
res.status(404).json({ error: "not found" });
|
||||
return;
|
||||
}
|
||||
const { label, cookie, capacity, enabled } = req.body ?? {};
|
||||
if (label !== undefined && !nonEmpty(label, 64)) {
|
||||
res.status(400).json({ error: "invalid label" });
|
||||
return;
|
||||
}
|
||||
if (cookie !== undefined && !nonEmpty(cookie, 8192)) {
|
||||
res.status(400).json({ error: "invalid cookie" });
|
||||
return;
|
||||
}
|
||||
if (!validCapacity(capacity)) {
|
||||
res.status(400).json({ error: "capacity must be a non-negative integer" });
|
||||
return;
|
||||
}
|
||||
if (enabled !== undefined && typeof enabled !== "boolean") {
|
||||
res.status(400).json({ error: "enabled must be a boolean" });
|
||||
return;
|
||||
}
|
||||
// Replacing the cookie invalidates any device-bound session (Kugou binds
|
||||
// the token to guid/mid) — the existing grants keep pointing at the row,
|
||||
// so the admin only has to paste a fresh cookie to fix everyone at once.
|
||||
const updated = database.updateMusicAccount(account.id, {
|
||||
label: label === undefined ? undefined : label.trim(),
|
||||
cookie: cookie === undefined ? undefined : cookie.trim(),
|
||||
capacity,
|
||||
enabled,
|
||||
});
|
||||
if (!updated) {
|
||||
res.status(409).json({ error: "capacity_below_existing_grants" });
|
||||
return;
|
||||
}
|
||||
logger.info(
|
||||
{ accountId: account.id, enabled: enabled ?? account.enabled },
|
||||
"Music account updated",
|
||||
);
|
||||
res.json(toWire(database.getMusicAccount(account.id)!));
|
||||
});
|
||||
|
||||
router.delete("/:id", (req, res) => {
|
||||
const account = database.getMusicAccount(req.params.id);
|
||||
if (!account) {
|
||||
res.status(404).json({ error: "not found" });
|
||||
return;
|
||||
}
|
||||
// FK ON DELETE CASCADE removes the grants with it, so no member is left
|
||||
// pointing at a deleted row. `changes` on the parent is what we report.
|
||||
const deleted = database.deleteMusicAccount(account.id);
|
||||
logger.info(
|
||||
{ accountId: account.id, platform: account.platform, deleted },
|
||||
"Music account removed",
|
||||
);
|
||||
res.json({ ok: deleted, revokedGrants: true });
|
||||
});
|
||||
|
||||
/**
|
||||
* Assign an account to a user (member OR another admin — an admin can be a
|
||||
* grantee too, they are just not forced onto the shared login).
|
||||
*/
|
||||
router.post("/:id/assign", (req, res) => {
|
||||
const account = database.getMusicAccount(req.params.id);
|
||||
if (!account) {
|
||||
res.status(404).json({ error: "not_found" });
|
||||
return;
|
||||
}
|
||||
const { userId } = req.body ?? {};
|
||||
if (typeof userId !== "string" || !userId) {
|
||||
res.status(400).json({ error: "userId is required" });
|
||||
return;
|
||||
}
|
||||
const target = users.findById(userId);
|
||||
if (!target || target.role === "guest") {
|
||||
res.status(404).json({ error: "user not found" });
|
||||
return;
|
||||
}
|
||||
|
||||
// Enabled + capacity are enforced inside a single transaction in the data
|
||||
// layer, so two concurrent assignments cannot both slip past the check.
|
||||
const result = database.assignMusicAccount(userId, account.id, req.user!.id);
|
||||
if (!result.ok) {
|
||||
if (result.reason === "not_found") {
|
||||
res.status(404).json({ error: "not_found" });
|
||||
return;
|
||||
}
|
||||
if (result.reason === "disabled") {
|
||||
res.status(409).json({ error: "account_disabled" });
|
||||
return;
|
||||
}
|
||||
const holders = database.listMusicAccountGrants(account.id).map((h) => ({
|
||||
userId: h.userId,
|
||||
username: h.username,
|
||||
}));
|
||||
if (result.reason === "exclusive") {
|
||||
res.status(409).json({ error: "account_exclusive", holders });
|
||||
return;
|
||||
}
|
||||
res.status(409).json({ error: "account_full", capacity: account.capacity, holders });
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info(
|
||||
{ accountId: account.id, userId, replacedAccountId: result.replacedAccountId },
|
||||
"Music account assigned",
|
||||
);
|
||||
res.json({
|
||||
ok: true,
|
||||
userId,
|
||||
username: target.username,
|
||||
accountId: account.id,
|
||||
platform: account.platform,
|
||||
replacedAccountId: result.replacedAccountId,
|
||||
});
|
||||
});
|
||||
|
||||
router.delete("/:id/assign/:userId", (req, res) => {
|
||||
const account = database.getMusicAccount(req.params.id);
|
||||
if (!account) {
|
||||
res.status(404).json({ error: "not found" });
|
||||
return;
|
||||
}
|
||||
const removed = database.deleteMusicAccountGrant(req.params.userId, account.platform, account.id);
|
||||
logger.info(
|
||||
{ accountId: account.id, userId: req.params.userId, removed },
|
||||
"Music account assignment revoked",
|
||||
);
|
||||
res.json({ ok: true, removed });
|
||||
});
|
||||
|
||||
/** Live check: is this cookie still logged in? */
|
||||
router.post("/:id/probe", async (req, res) => {
|
||||
const account = database.getMusicAccount(req.params.id);
|
||||
if (!account) {
|
||||
res.status(404).json({ error: "not found" });
|
||||
return;
|
||||
}
|
||||
const provider = providers[account.platform];
|
||||
if (!provider || typeof provider.withCookie !== "function") {
|
||||
res.status(501).json({ error: "playback not supported for this platform" });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const status = await provider.withCookie(account.cookie).getAuthStatus();
|
||||
res.json({ ok: true, ...status });
|
||||
} catch {
|
||||
logger.warn({ accountId: account.id }, "Music account probe failed");
|
||||
res.status(502).json({ error: "music_account_probe_failed", loggedIn: false });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Seed the pool with the login the bot already uses, so an admin who scanned
|
||||
* the shared account can hand it to selected members without re-scanning.
|
||||
*/
|
||||
router.post("/import-shared", (req, res) => {
|
||||
const { platform, label, capacity } = req.body ?? {};
|
||||
// QQ 的共享登录以"运行中的 provider"为准:登录写的是它内存里的 cookie,
|
||||
// qq.json 只是落盘副本。托管会话轮换凭据之后文件就旧了(#188),
|
||||
// 从这里导入会把一个过期 cookie 塞进账号池。
|
||||
const sharedQq = platform === "qq" ? providers.qq : undefined;
|
||||
if (!sharedQq && !cookieStore) {
|
||||
res.status(501).json({ error: "cookie store unavailable" });
|
||||
return;
|
||||
}
|
||||
if (!isPlatform(platform)) {
|
||||
res.status(400).json({ error: "unsupported platform" });
|
||||
return;
|
||||
}
|
||||
if (!validCapacity(capacity)) {
|
||||
res.status(400).json({ error: "capacity must be a non-negative integer" });
|
||||
return;
|
||||
}
|
||||
// 没有 qq provider(例如单测只挂了 netease)时仍然回落到 cookie store,
|
||||
// 所以这个改动对已有平台零影响。
|
||||
let cookie: string | undefined;
|
||||
if (sharedQq) {
|
||||
try {
|
||||
cookie = sharedQq.getCookie();
|
||||
} catch {
|
||||
// Provider 还没建立登录态时抛错等价于「没有可导入的登录」
|
||||
cookie = "";
|
||||
}
|
||||
} else {
|
||||
cookie = cookieStore?.load(platform);
|
||||
}
|
||||
if (!cookie || !cookie.trim()) {
|
||||
res.status(409).json({ error: "no_shared_login", platform });
|
||||
return;
|
||||
}
|
||||
const created = database.createMusicAccount({
|
||||
platform,
|
||||
label: nonEmpty(label, 64) ? label.trim() : `${platform} 共享账号`,
|
||||
cookie: cookie.trim(),
|
||||
// ownerId stays null: this login was provided by the bot, not a person.
|
||||
ownerId: null,
|
||||
capacity,
|
||||
enabled: true,
|
||||
});
|
||||
logger.info({ accountId: created.id, platform }, "Shared login imported into pool");
|
||||
res.status(201).json(toWire(created));
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import express from "express";
|
||||
import cookieParser from "cookie-parser";
|
||||
import request from "supertest";
|
||||
import pino from "pino";
|
||||
import { AxiosError } from "axios";
|
||||
import { mkdtempSync, rmSync, readFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
@@ -58,6 +59,18 @@ describe("music router GET /search offset pagination", () => {
|
||||
expect(res.status).toBe(200);
|
||||
expect(netease.search).toHaveBeenCalledWith("hello", 20, 0);
|
||||
});
|
||||
|
||||
it("keeps provider request credentials out of search errors", async () => {
|
||||
const logger = pino({ level: "silent" });
|
||||
const logError = vi.spyOn(logger, "error");
|
||||
const privateCookie = "MUSIC_U=test-private-session";
|
||||
vi.mocked(netease.search).mockRejectedValueOnce(new AxiosError(`Provider request failed: ${privateCookie}`));
|
||||
const route = express();
|
||||
route.use("/api/music", createMusicRouter(netease, fakeProvider("qq"), fakeProvider("bilibili"), logger));
|
||||
const res = await request(route).get("/api/music/search?q=test").expect(500);
|
||||
expect(res.text).not.toContain(privateCookie);
|
||||
expect(JSON.stringify(logError.mock.calls)).not.toContain(privateCookie);
|
||||
});
|
||||
});
|
||||
|
||||
describe("music router provider gating (enabledProviders) + jellyfin endpoints", () => {
|
||||
|
||||
+71
-36
@@ -1,11 +1,14 @@
|
||||
import express, { Router, type Response } from "express";
|
||||
import express, { Router, type Request, type Response } from "express";
|
||||
import type { MusicProvider, Song, Album, SearchResult } from "../../music/provider.js";
|
||||
import { musicRequestError } from "../../music/request-error.js";
|
||||
import { YouTubeProvider } from "../../music/youtube.js";
|
||||
import type { Logger } from "../../logger.js";
|
||||
import { isProviderEnabled, defaultPlatform, saveConfig, type BotConfig } from "../../data/config.js";
|
||||
import type { BotDatabase } from "../../data/database.js";
|
||||
import { requirePermission } from "../middleware/requirePermission.js";
|
||||
import { requireNotGuest } from "../middleware/requireNotGuest.js";
|
||||
import { authorize } from "../middleware/authorize.js";
|
||||
import { resolveProviderForRequest } from "./provider-scope.js";
|
||||
|
||||
/**
|
||||
* Body cap for a local upload. express.raw buffers the whole body in memory,
|
||||
@@ -70,6 +73,10 @@ export function createMusicRouter(
|
||||
// When set (alongside config), a quality change is persisted to config.json so
|
||||
// it survives a restart (#125). Omitted by unit-test routers → no persistence.
|
||||
configPath?: string,
|
||||
// Per-user music accounts (#164 follow-up): when config.perUserMusicAccounts
|
||||
// is on, a request carrying a linked account reads through that account
|
||||
// instead of the bot's shared login. Omitted by unit-test routers → shared.
|
||||
database?: BotDatabase,
|
||||
): Router {
|
||||
const router = Router();
|
||||
const youtubeProvider: MusicProvider = new YouTubeProvider();
|
||||
@@ -95,14 +102,25 @@ export function createMusicRouter(
|
||||
* return immediately. Without a config (unit-test routers), everything
|
||||
* stays enabled.
|
||||
*/
|
||||
function resolveProvider(platform: unknown, res: Response): MusicProvider | null {
|
||||
function resolveProvider(
|
||||
platform: unknown,
|
||||
res: Response,
|
||||
req?: Request,
|
||||
): MusicProvider | null {
|
||||
const requested = typeof platform === "string" && platform ? platform : undefined;
|
||||
const target = requested ?? (config ? defaultPlatform(config) : "netease");
|
||||
if (config && !isProviderEnabled(config, target)) {
|
||||
res.status(400).json({ error: `音源未启用:${target} (provider disabled)` });
|
||||
return null;
|
||||
}
|
||||
return getProvider(target);
|
||||
// Per-user accounts: with the feature on, a user who linked their own
|
||||
// account reads search/playlists/lyrics/artists through THAT
|
||||
// login instead of the bot's shared one, so members stop seeing the
|
||||
// admin's library. Everyone else keeps the shared provider unchanged.
|
||||
return resolveProviderForRequest(req, target, getProvider(target), {
|
||||
database,
|
||||
config,
|
||||
});
|
||||
}
|
||||
|
||||
router.post(
|
||||
@@ -164,7 +182,7 @@ export function createMusicRouter(
|
||||
res.json({ songs: [], playlists: [], albums: [] });
|
||||
return;
|
||||
}
|
||||
const provider = resolveProvider(platform, res);
|
||||
const provider = resolveProvider(platform, res, req);
|
||||
if (!provider) return;
|
||||
// Server-side pagination: offset lets the web load past the first page.
|
||||
// Clamp to >= 0 so a bad/negative value falls back to the first page.
|
||||
@@ -176,8 +194,9 @@ export function createMusicRouter(
|
||||
);
|
||||
res.json(result);
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Search failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
const error = musicRequestError(err);
|
||||
logger.error({ err: error }, "Search failed");
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -199,13 +218,24 @@ export function createMusicRouter(
|
||||
// enabled — a self-hosted library match is almost always the wanted one.
|
||||
const enabled = (p: string) => !config || isProviderEnabled(config, p);
|
||||
const none: SearchResult = { songs: [], albums: [], playlists: [] };
|
||||
// Unified search hits every source at once, so each one has to be scoped
|
||||
// individually — otherwise a member with their own linked account would
|
||||
// still get the admin's results merged in from the other platforms.
|
||||
// Local audio and Jellyfin have no per-account login, so they stay shared.
|
||||
const scope = { database, config };
|
||||
const nProvider = resolveProviderForRequest(req, "netease", neteaseProvider, scope);
|
||||
const qProvider = resolveProviderForRequest(req, "qq", qqProvider, scope);
|
||||
const bProvider = resolveProviderForRequest(req, "bilibili", bilibiliProvider, scope);
|
||||
const kProvider = kugouProvider
|
||||
? resolveProviderForRequest(req, "kugou", kugouProvider, scope)
|
||||
: kugouProvider;
|
||||
const [jellyfinResult, neteaseResult, qqResult, bilibiliResult, localResult, kugouResult] = await Promise.allSettled([
|
||||
jellyfinProvider && enabled("jellyfin") ? jellyfinProvider.search(q as string, parsedLimit) : Promise.resolve(none),
|
||||
enabled("netease") ? neteaseProvider.search(q as string, parsedLimit) : Promise.resolve(none),
|
||||
enabled("qq") ? qqProvider.search(q as string, parsedLimit) : Promise.resolve(none),
|
||||
enabled("bilibili") ? bilibiliProvider.search(q as string, parsedLimit) : Promise.resolve(none),
|
||||
enabled("netease") ? nProvider.search(q as string, parsedLimit) : Promise.resolve(none),
|
||||
enabled("qq") ? qProvider.search(q as string, parsedLimit) : Promise.resolve(none),
|
||||
enabled("bilibili") ? bProvider.search(q as string, parsedLimit) : Promise.resolve(none),
|
||||
localProvider && isLocalAudioEnabled() ? localProvider.search(q as string, parsedLimit) : Promise.resolve(none),
|
||||
kugouProvider && enabled("kugou") ? kugouProvider.search(q as string, parsedLimit) : Promise.resolve(none),
|
||||
kProvider && enabled("kugou") ? kProvider.search(q as string, parsedLimit) : Promise.resolve(none),
|
||||
]);
|
||||
|
||||
const songs = [
|
||||
@@ -235,8 +265,9 @@ export function createMusicRouter(
|
||||
|
||||
res.json({ songs, albums, playlists, artists });
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Unified search failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
const error = musicRequestError(err);
|
||||
logger.error({ err: error }, "Unified search failed");
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -246,7 +277,7 @@ export function createMusicRouter(
|
||||
res.status(403).json({ error: "本地音频播放已关闭" });
|
||||
return;
|
||||
}
|
||||
const provider = resolveProvider(req.query.platform, res);
|
||||
const provider = resolveProvider(req.query.platform, res, req);
|
||||
if (!provider) return;
|
||||
const song = await provider.getSongDetail(req.params.id);
|
||||
if (!song) {
|
||||
@@ -255,57 +286,57 @@ export function createMusicRouter(
|
||||
}
|
||||
res.json(song);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
res.status(500).json({ error: musicRequestError(err).message });
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/playlist/:id", async (req, res) => {
|
||||
try {
|
||||
const provider = resolveProvider(req.query.platform, res);
|
||||
const provider = resolveProvider(req.query.platform, res, req);
|
||||
if (!provider) return;
|
||||
const songs = await provider.getPlaylistSongs(req.params.id);
|
||||
res.json({ songs });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
res.status(500).json({ error: musicRequestError(err).message });
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/recommend/playlists", async (req, res) => {
|
||||
try {
|
||||
const provider = resolveProvider(req.query.platform, res);
|
||||
const provider = resolveProvider(req.query.platform, res, req);
|
||||
if (!provider) return;
|
||||
const playlists = await provider.getRecommendPlaylists();
|
||||
res.json({ playlists });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
res.status(500).json({ error: musicRequestError(err).message });
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/album/:id", async (req, res) => {
|
||||
try {
|
||||
const provider = resolveProvider(req.query.platform, res);
|
||||
const provider = resolveProvider(req.query.platform, res, req);
|
||||
if (!provider) return;
|
||||
const songs = await provider.getAlbumSongs(req.params.id);
|
||||
res.json({ songs });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
res.status(500).json({ error: musicRequestError(err).message });
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/lyrics/:id", async (req, res) => {
|
||||
try {
|
||||
const provider = resolveProvider(req.query.platform, res);
|
||||
const provider = resolveProvider(req.query.platform, res, req);
|
||||
if (!provider) return;
|
||||
const lyrics = await provider.getLyrics(req.params.id);
|
||||
res.json({ lyrics });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
res.status(500).json({ error: musicRequestError(err).message });
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/artist/:id", async (req, res) => {
|
||||
try {
|
||||
const provider = resolveProvider(req.query.platform, res);
|
||||
const provider = resolveProvider(req.query.platform, res, req);
|
||||
if (!provider) return;
|
||||
if (!provider.getArtistDetail) {
|
||||
res.status(501).json({ error: "Not supported by this provider" });
|
||||
@@ -329,13 +360,13 @@ export function createMusicRouter(
|
||||
}
|
||||
res.json({ artist, songs, albums });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
res.status(500).json({ error: musicRequestError(err).message });
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/recommend/songs", requireNotGuest, async (req, res) => {
|
||||
try {
|
||||
const provider = resolveProvider(req.query.platform, res);
|
||||
const provider = resolveProvider(req.query.platform, res, req);
|
||||
if (!provider) return;
|
||||
if (!provider.getDailyRecommendSongs) {
|
||||
res.status(501).json({ error: "Not supported by this provider" });
|
||||
@@ -344,14 +375,15 @@ export function createMusicRouter(
|
||||
const songs = await provider.getDailyRecommendSongs();
|
||||
res.json({ songs });
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Get daily recommend songs failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
const error = musicRequestError(err);
|
||||
logger.error({ err: error }, "Get daily recommend songs failed");
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/personal/fm", requireNotGuest, async (req, res) => {
|
||||
try {
|
||||
const provider = resolveProvider(req.query.platform, res);
|
||||
const provider = resolveProvider(req.query.platform, res, req);
|
||||
if (!provider) return;
|
||||
if (!provider.getPersonalFm) {
|
||||
res.status(501).json({ error: "Not supported by this provider" });
|
||||
@@ -360,14 +392,15 @@ export function createMusicRouter(
|
||||
const songs = await provider.getPersonalFm();
|
||||
res.json({ songs });
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Get personal FM failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
const error = musicRequestError(err);
|
||||
logger.error({ err: error }, "Get personal FM failed");
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/user/playlists", requireNotGuest, async (req, res) => {
|
||||
try {
|
||||
const provider = resolveProvider(req.query.platform, res);
|
||||
const provider = resolveProvider(req.query.platform, res, req);
|
||||
if (!provider) return;
|
||||
if (!provider.getUserPlaylists) {
|
||||
res.status(501).json({ error: "Not supported by this provider" });
|
||||
@@ -376,14 +409,15 @@ export function createMusicRouter(
|
||||
const playlists = await provider.getUserPlaylists();
|
||||
res.json({ playlists });
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Get user playlists failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
const error = musicRequestError(err);
|
||||
logger.error({ err: error }, "Get user playlists failed");
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/playlist/:id/detail", async (req, res) => {
|
||||
try {
|
||||
const provider = resolveProvider(req.query.platform, res);
|
||||
const provider = resolveProvider(req.query.platform, res, req);
|
||||
if (!provider) return;
|
||||
if (!provider.getPlaylistDetail) {
|
||||
res.status(501).json({ error: "Not supported by this provider" });
|
||||
@@ -396,8 +430,9 @@ export function createMusicRouter(
|
||||
}
|
||||
res.json({ playlist: detail });
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Get playlist detail failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
const error = musicRequestError(err);
|
||||
logger.error({ err: error }, "Get playlist detail failed");
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -6,7 +6,10 @@ import { createDatabase } from "../../data/database.js";
|
||||
import { createPersonalMusicRouter } from "./personal-music.js";
|
||||
import { createPlayerRouter } from "./player.js";
|
||||
|
||||
function mount() {
|
||||
function mount(opts: {
|
||||
config?: { perUserMusicAccounts?: boolean };
|
||||
extraProviders?: Record<string, unknown>;
|
||||
} = {}) {
|
||||
const db = createDatabase(":memory:");
|
||||
db.db
|
||||
.prepare("INSERT INTO users (id, username, passwordHash, createdAt, updatedAt, role) VALUES (?,?,?,?,?,?)")
|
||||
@@ -27,16 +30,38 @@ function mount() {
|
||||
(req as any).user = { id: "u1", username: "alice", role: "member" };
|
||||
next();
|
||||
});
|
||||
app.use("/api/me/music", createPersonalMusicRouter(db, provider, pino({ level: "silent" })));
|
||||
app.use(
|
||||
"/api/me/music",
|
||||
createPersonalMusicRouter(
|
||||
db,
|
||||
{ netease: provider, ...(opts.extraProviders as object) },
|
||||
pino({ level: "silent" }),
|
||||
opts.config,
|
||||
),
|
||||
);
|
||||
return { app, db, provider, personalView };
|
||||
}
|
||||
|
||||
/** Seed an admin-owned account and assign it to u1. */
|
||||
function assignAccount(db: ReturnType<typeof createDatabase>, label = "网易云-主号") {
|
||||
const account = db.createMusicAccount({
|
||||
platform: "netease",
|
||||
label,
|
||||
cookie: "MUSIC_U=granted",
|
||||
});
|
||||
db.assignMusicAccount("u1", account.id, "admin");
|
||||
return account;
|
||||
}
|
||||
|
||||
describe("personal music account router (#164)", () => {
|
||||
it("reports not linked until the user logs in", async () => {
|
||||
const { app } = mount();
|
||||
const res = await request(app).get("/api/me/music/netease/status");
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ linked: false, loggedIn: false });
|
||||
expect(res.body).toEqual({
|
||||
linked: false, loggedIn: false, source: "none", canUnlink: false, supportsQrLogin: true,
|
||||
preferShared: false, featureEnabled: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("creates a QR code", async () => {
|
||||
@@ -64,7 +89,16 @@ describe("personal music account router (#164)", () => {
|
||||
const { app, db, provider } = mount();
|
||||
db.setUserMusicCookie("u1", "netease", "MUSIC_U=alice");
|
||||
const res = await request(app).get("/api/me/music/netease/status");
|
||||
expect(res.body).toEqual({ linked: true, loggedIn: true, nickname: "Alice163" });
|
||||
expect(res.body).toEqual({
|
||||
linked: true,
|
||||
source: "personal",
|
||||
canUnlink: true,
|
||||
supportsQrLogin: true,
|
||||
preferShared: false,
|
||||
featureEnabled: false,
|
||||
loggedIn: true,
|
||||
nickname: "Alice163",
|
||||
});
|
||||
expect(provider.withCookie).toHaveBeenCalledWith("MUSIC_U=alice");
|
||||
});
|
||||
|
||||
@@ -74,6 +108,62 @@ describe("personal music account router (#164)", () => {
|
||||
expect((await request(app).delete("/api/me/music/netease")).status).toBe(200);
|
||||
expect(db.getUserMusicCookie("u1", "netease")).toBeNull();
|
||||
});
|
||||
|
||||
// 404 for a platform this build does not expose — keeps the param route from
|
||||
// silently answering "not linked" for a typo'd URL.
|
||||
it("404s an unknown platform", async () => {
|
||||
const { app } = mount();
|
||||
expect((await request(app).get("/api/me/music/deezer/status")).status).toBe(404);
|
||||
});
|
||||
|
||||
// qq/kugou/bilibili ship withCookie but not pollQrLogin yet: linking is 501,
|
||||
// while an admin-assigned account still works (see below).
|
||||
it("501s QR login on a platform without per-user polling", async () => {
|
||||
const { app } = mount({ extraProviders: { qq: { platform: "qq", withCookie: vi.fn() } } });
|
||||
expect((await request(app).post("/api/me/music/qq/qrcode")).status).toBe(501);
|
||||
});
|
||||
|
||||
describe("admin-assigned account", () => {
|
||||
it("reports source=granted with the admin's label and forbids unlinking", async () => {
|
||||
const { app, db, provider } = mount({ config: { perUserMusicAccounts: true } });
|
||||
assignAccount(db);
|
||||
const res = await request(app).get("/api/me/music/netease/status");
|
||||
expect(res.body).toEqual({
|
||||
linked: true,
|
||||
source: "granted",
|
||||
label: "网易云-主号",
|
||||
canUnlink: false,
|
||||
supportsQrLogin: true,
|
||||
preferShared: false,
|
||||
featureEnabled: true,
|
||||
loggedIn: true,
|
||||
nickname: "Alice163",
|
||||
});
|
||||
expect(provider.withCookie).toHaveBeenCalledWith("MUSIC_U=granted");
|
||||
});
|
||||
|
||||
it("is invisible while the admin toggle is off", async () => {
|
||||
const { app, db } = mount({ config: { perUserMusicAccounts: false } });
|
||||
assignAccount(db);
|
||||
const res = await request(app).get("/api/me/music/netease/status");
|
||||
expect(res.body).toEqual({
|
||||
linked: false, loggedIn: false, source: "none", canUnlink: false, supportsQrLogin: true,
|
||||
preferShared: false, featureEnabled: false,
|
||||
});
|
||||
});
|
||||
|
||||
// Unlinking on the member side must never revoke what the admin granted:
|
||||
// the two live in separate tables on purpose.
|
||||
it("survives a member unlink and is reported as the fallback", async () => {
|
||||
const { app, db } = mount({ config: { perUserMusicAccounts: true } });
|
||||
assignAccount(db);
|
||||
db.setUserMusicCookie("u1", "netease", "MUSIC_U=alice");
|
||||
const res = await request(app).delete("/api/me/music/netease");
|
||||
expect(res.body).toEqual({ ok: true, removed: true, fallback: "granted" });
|
||||
expect(db.getUserMusicCookie("u1", "netease")).toBeNull();
|
||||
expect(db.getGrantedMusicAccount("u1", "netease")?.cookie).toBe("MUSIC_U=granted");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("web FM uses the caller's linked NetEase account (#164)", () => {
|
||||
@@ -123,3 +213,73 @@ describe("web FM uses the caller's linked NetEase account (#164)", () => {
|
||||
expect(bot.startFm.mock.calls[0][0]).toBe(qq);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// "Play through the shared account" preference (#164 follow-up)
|
||||
//
|
||||
// The case this exists for: the member's own NetEase login has no VIP, the
|
||||
// admin's does. The preference is per-platform and per-user, and it must not
|
||||
// touch either stored login.
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("personal music — shared-account preference", () => {
|
||||
const ON = { config: { perUserMusicAccounts: true } };
|
||||
|
||||
it("defaults to the member's own account", async () => {
|
||||
const { app } = mount(ON);
|
||||
const res = await request(app).get("/api/me/music/netease/preference");
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ platform: "netease", preferShared: false });
|
||||
});
|
||||
|
||||
it("stores the choice and reports it back", async () => {
|
||||
const { app } = mount(ON);
|
||||
const put = await request(app).put("/api/me/music/netease/preference").send({ preferShared: true });
|
||||
expect(put.status).toBe(200);
|
||||
expect(put.body).toEqual({ platform: "netease", preferShared: true });
|
||||
|
||||
const get = await request(app).get("/api/me/music/netease/preference");
|
||||
expect(get.body.preferShared).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps the choice per platform", async () => {
|
||||
const { app } = mount({
|
||||
...ON,
|
||||
extraProviders: { qq: { platform: "qq", withCookie: () => ({ getAuthStatus: async () => ({ loggedIn: true }) }) } },
|
||||
});
|
||||
await request(app).put("/api/me/music/netease/preference").send({ preferShared: true });
|
||||
const qq = await request(app).get("/api/me/music/qq/preference");
|
||||
expect(qq.body.preferShared).toBe(false);
|
||||
});
|
||||
|
||||
it("does not touch the stored login", async () => {
|
||||
const { app, db } = mount(ON);
|
||||
db.setUserMusicCookie("u1", "netease", "MUSIC_U=mine");
|
||||
await request(app).put("/api/me/music/netease/preference").send({ preferShared: true });
|
||||
|
||||
expect(db.getUserMusicCookie("u1", "netease")).toBe("MUSIC_U=mine");
|
||||
expect(db.getUserMusicPreference("u1", "netease")).toEqual({ preferShared: true });
|
||||
});
|
||||
|
||||
it("surfaces the choice on the status payload the UI already reads", async () => {
|
||||
const { app, db } = mount(ON);
|
||||
db.setUserMusicCookie("u1", "netease", "MUSIC_U=mine");
|
||||
await request(app).put("/api/me/music/netease/preference").send({ preferShared: true });
|
||||
|
||||
const res = await request(app).get("/api/me/music/netease/status");
|
||||
expect(res.body.preferShared).toBe(true);
|
||||
expect(res.body.featureEnabled).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a non-boolean", async () => {
|
||||
const { app } = mount(ON);
|
||||
const res = await request(app).put("/api/me/music/netease/preference").send({ preferShared: "yes" });
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it("refuses when the admin has the feature off", async () => {
|
||||
const { app } = mount({ config: { perUserMusicAccounts: false } });
|
||||
const res = await request(app).put("/api/me/music/netease/preference").send({ preferShared: true });
|
||||
expect(res.status).toBe(409);
|
||||
expect(res.body.error).toBe("per_user_accounts_disabled");
|
||||
});
|
||||
});
|
||||
+184
-27
@@ -2,6 +2,7 @@ import { Router } from "express";
|
||||
import type { BotDatabase } from "../../data/database.js";
|
||||
import type { MusicProvider, QrCodeResult } from "../../music/provider.js";
|
||||
import type { Logger } from "../../logger.js";
|
||||
import { perUserMusicEnabled, type MusicScopeDeps } from "./provider-scope.js";
|
||||
|
||||
/**
|
||||
* A provider that can log a web user into their OWN account without touching
|
||||
@@ -17,56 +18,165 @@ export function supportsPersonalLogin(
|
||||
provider: MusicProvider | undefined,
|
||||
): provider is MusicProvider & PersonalLoginProvider {
|
||||
const p = provider as Partial<PersonalLoginProvider> | undefined;
|
||||
return typeof p?.pollQrLogin === "function" && typeof p.withCookie === "function";
|
||||
return typeof p?.pollQrLogin === "function" && typeof p?.withCookie === "function";
|
||||
}
|
||||
|
||||
/** Platforms a member can link an account for. Kept in sync with the providers map. */
|
||||
export const PERSONAL_MUSIC_PLATFORMS = ["netease", "qq", "kugou", "bilibili"] as const;
|
||||
|
||||
/**
|
||||
* The caller's own NetEase account, used for their personal FM instead of the
|
||||
* bot's shared login (#164). Every route acts on req.user only; the cookie is
|
||||
* stored server-side and never sent back to the browser.
|
||||
* A web user's own music account (#164), generalised to every platform that
|
||||
* implements `withCookie` (#164 follow-up).
|
||||
*
|
||||
* Three states are reported, and the member UI needs all three:
|
||||
* - `personal`: the caller scanned their own QR code. They may unlink it.
|
||||
* - `granted` : an ADMIN assigned one of the pool accounts to them. It cannot
|
||||
* be unlinked from here — only the admin can take it back —
|
||||
* which is why `canUnlink` is part of the payload instead of
|
||||
* the UI guessing from `linked`.
|
||||
* - `none` : nothing linked; playback falls back to the bot's shared login.
|
||||
*
|
||||
* The cookie is stored server-side and never sent back to the browser; the
|
||||
* `label` of an assigned account is what the member sees instead of a nickname.
|
||||
*/
|
||||
export function createPersonalMusicRouter(
|
||||
database: BotDatabase,
|
||||
neteaseProvider: MusicProvider,
|
||||
providers: Partial<Record<string, MusicProvider>>,
|
||||
logger: Logger,
|
||||
config?: MusicScopeDeps["config"],
|
||||
): Router {
|
||||
const router = Router();
|
||||
const platform = "netease";
|
||||
|
||||
router.use((_req, res, next) => {
|
||||
if (!supportsPersonalLogin(neteaseProvider)) {
|
||||
res.status(501).json({ error: "Personal login not supported" });
|
||||
const providerFor = (platform: string): MusicProvider | undefined => providers[platform];
|
||||
|
||||
/** 404 for platforms this build does not expose at all. */
|
||||
router.param("platform", (req, res, next, platform: string) => {
|
||||
if (!providerFor(platform)) {
|
||||
res.status(404).json({ error: `Unknown platform: ${platform}` });
|
||||
return;
|
||||
}
|
||||
next();
|
||||
});
|
||||
const provider = neteaseProvider as MusicProvider & PersonalLoginProvider;
|
||||
|
||||
router.get("/netease/status", async (req, res) => {
|
||||
const cookie = database.getUserMusicCookie(req.user!.id, platform);
|
||||
if (!cookie) {
|
||||
res.json({ linked: false, loggedIn: false });
|
||||
/** Read the account state for one platform: own first, then admin-assigned. */
|
||||
const describeAccount = (
|
||||
userId: string,
|
||||
platform: string,
|
||||
): { source: "personal" | "granted" | "none"; cookie: string | null; label?: string; canUnlink: boolean } => {
|
||||
const own = database.getUserMusicCookie(userId, platform);
|
||||
if (own && own.trim()) {
|
||||
return { source: "personal", cookie: own, canUnlink: true };
|
||||
}
|
||||
// An assignment only exists because the admin turned the feature on, so it
|
||||
// stops applying the moment the toggle goes off (same rule as playback).
|
||||
if (perUserMusicEnabled({ database, config })) {
|
||||
const granted = database.getGrantedMusicAccount(userId, platform);
|
||||
if (granted) {
|
||||
return { source: "granted", cookie: granted.cookie, label: granted.label, canUnlink: false };
|
||||
}
|
||||
}
|
||||
return { source: "none", cookie: null, canUnlink: false };
|
||||
};
|
||||
|
||||
router.get("/:platform/status", async (req, res) => {
|
||||
const platform = req.params.platform;
|
||||
const provider = providerFor(platform)!;
|
||||
const account = describeAccount(req.user!.id, platform);
|
||||
// Lets the member UI hide "扫码绑定" on platforms that only accept an
|
||||
// admin-assigned account (qq / kugou / bilibili today).
|
||||
const supportsQrLogin = supportsPersonalLogin(provider);
|
||||
// The member's explicit "play through the shared login" choice, so the UI
|
||||
// can render the radio without a second round-trip.
|
||||
const preferShared =
|
||||
database.getUserMusicPreference(req.user!.id, platform)?.preferShared === true;
|
||||
// The choice only exists while the admin has per-user accounts on; with it
|
||||
// off everyone is already on the shared login and the radio is meaningless.
|
||||
const featureEnabled = perUserMusicEnabled({ database, config });
|
||||
|
||||
if (!account.cookie) {
|
||||
res.json({
|
||||
linked: false,
|
||||
loggedIn: false,
|
||||
source: "none",
|
||||
canUnlink: false,
|
||||
supportsQrLogin,
|
||||
preferShared,
|
||||
featureEnabled,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (typeof provider.withCookie !== "function") {
|
||||
// Account stored but this platform cannot build a per-account view yet.
|
||||
res.json({
|
||||
linked: true,
|
||||
loggedIn: false,
|
||||
source: account.source,
|
||||
label: account.label,
|
||||
canUnlink: account.canUnlink,
|
||||
supportsQrLogin,
|
||||
preferShared,
|
||||
featureEnabled,
|
||||
unsupported: true,
|
||||
});
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const status = await provider.withCookie(cookie).getAuthStatus();
|
||||
res.json({ linked: true, ...status });
|
||||
} catch (err) {
|
||||
logger.warn({ err }, "Personal NetEase status check failed");
|
||||
res.json({ linked: true, loggedIn: false });
|
||||
const status = await provider.withCookie(account.cookie).getAuthStatus();
|
||||
res.json({
|
||||
linked: true,
|
||||
source: account.source,
|
||||
label: account.label,
|
||||
canUnlink: account.canUnlink,
|
||||
supportsQrLogin,
|
||||
preferShared,
|
||||
featureEnabled,
|
||||
...status,
|
||||
});
|
||||
} catch {
|
||||
logger.warn({ platform, source: account.source }, "Personal music status check failed");
|
||||
res.json({
|
||||
linked: true,
|
||||
loggedIn: false,
|
||||
source: account.source,
|
||||
label: account.label,
|
||||
canUnlink: account.canUnlink,
|
||||
supportsQrLogin,
|
||||
preferShared,
|
||||
featureEnabled,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.post("/netease/qrcode", async (_req, res) => {
|
||||
router.post("/:platform/qrcode", async (req, res) => {
|
||||
const platform = req.params.platform;
|
||||
const provider = providerFor(platform)!;
|
||||
if (!supportsPersonalLogin(provider)) {
|
||||
// Only NetEase ships "poll and hand back the cookie" today. The other
|
||||
// platforms can still receive an admin-assigned account.
|
||||
res.status(501).json({
|
||||
error: "Personal QR login is not implemented for this platform yet",
|
||||
platform,
|
||||
});
|
||||
return;
|
||||
}
|
||||
try {
|
||||
res.json(await provider.getQrCode());
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Personal NetEase QR generation failed");
|
||||
logger.error({ err, platform }, "Personal music QR generation failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/netease/qrcode/status", async (req, res) => {
|
||||
router.get("/:platform/qrcode/status", async (req, res) => {
|
||||
const platform = req.params.platform;
|
||||
const provider = providerFor(platform)!;
|
||||
if (!supportsPersonalLogin(provider)) {
|
||||
res.status(501).json({
|
||||
error: "Personal QR login is not implemented for this platform yet",
|
||||
platform,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const key = req.query.key;
|
||||
if (typeof key !== "string" || !key) {
|
||||
res.status(400).json({ error: "key is required" });
|
||||
@@ -80,15 +190,62 @@ export function createPersonalMusicRouter(
|
||||
}
|
||||
res.json({ status });
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Personal NetEase QR status check failed");
|
||||
logger.error({ err, platform }, "Personal music QR status check failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
}
|
||||
});
|
||||
|
||||
router.delete("/netease", (req, res) => {
|
||||
database.deleteUserMusicCookie(req.user!.id, platform);
|
||||
logger.info({ userId: req.user!.id, platform }, "Personal music account unlinked");
|
||||
res.json({ ok: true });
|
||||
router.delete("/:platform", (req, res) => {
|
||||
const platform = req.params.platform;
|
||||
const userId = req.user!.id;
|
||||
// Only the member's OWN login is removed. An admin-assigned account lives
|
||||
// in a different table and must stay put — otherwise a member could revoke
|
||||
// (or accidentally destroy) what the admin handed them.
|
||||
const removed = database.deleteUserMusicCookie(userId, platform);
|
||||
if (removed) {
|
||||
logger.info({ userId, platform }, "Personal music account unlinked");
|
||||
}
|
||||
const remaining = describeAccount(userId, platform);
|
||||
res.json({
|
||||
ok: true,
|
||||
removed,
|
||||
// What playback falls back to now — the member UI shows the right hint.
|
||||
fallback: remaining.source === "granted" ? "granted" : "shared",
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Which login this member plays through.
|
||||
*
|
||||
* `preferShared: true` = ignore my own (and any assigned) account and use the
|
||||
* bot's shared login — the admin's, usually the one with a membership. It is
|
||||
* the answer to "my NetEase account has no VIP, the admin's does, and I want
|
||||
* the paid track". Nothing is deleted: flipping it back restores the personal
|
||||
* account exactly as it was.
|
||||
*/
|
||||
router.put("/:platform/preference", (req, res) => {
|
||||
const platform = req.params.platform;
|
||||
const { preferShared } = req.body ?? {};
|
||||
if (typeof preferShared !== "boolean") {
|
||||
res.status(400).json({ error: "preferShared must be a boolean" });
|
||||
return;
|
||||
}
|
||||
// With the feature off there is nothing to choose between — everything
|
||||
// already runs on the shared login. Refuse instead of storing a value that
|
||||
// would silently do nothing.
|
||||
if (!perUserMusicEnabled({ database, config })) {
|
||||
res.status(409).json({ error: "per_user_accounts_disabled" });
|
||||
return;
|
||||
}
|
||||
database.setUserMusicPreference(req.user!.id, platform, preferShared);
|
||||
logger.info({ userId: req.user!.id, platform, preferShared }, "Music account preference set");
|
||||
res.json({ platform, preferShared });
|
||||
});
|
||||
|
||||
router.get("/:platform/preference", (req, res) => {
|
||||
const platform = req.params.platform;
|
||||
const pref = database.getUserMusicPreference(req.user!.id, platform);
|
||||
res.json({ platform, preferShared: pref?.preferShared === true });
|
||||
});
|
||||
|
||||
return router;
|
||||
|
||||
@@ -6,6 +6,7 @@ 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 {
|
||||
@@ -75,8 +76,8 @@ describe("collectArtistSongs (play-artist all:true)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("play-artist playback serialization", () => {
|
||||
it("keeps the queue and audible song consistent when single-song playback overlaps artist playback", async () => {
|
||||
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;
|
||||
@@ -87,7 +88,14 @@ describe("play-artist playback serialization", () => {
|
||||
const singleArrived = new Promise<void>((resolve) => { notifySingleArrived = resolve; });
|
||||
const bot: any = {
|
||||
playGate: Promise.resolve(),
|
||||
getProviderFor: () => ({ platform: "netease", getArtistSongs: async () => [song("A")], getArtistAllSongs: async () => page(["A"], 1, false) }),
|
||||
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) => {
|
||||
@@ -110,7 +118,8 @@ describe("play-artist playback serialization", () => {
|
||||
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 artistRequest = request(app).post("/api/player/b/play-artist").send({ artistId: "artist", platform: "netease" }).then((res) => res);
|
||||
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.
|
||||
@@ -119,11 +128,181 @@ describe("play-artist playback serialization", () => {
|
||||
await Promise.resolve();
|
||||
const whileArtistPending = queue.current()?.id;
|
||||
releaseArtist();
|
||||
const [artistResponse, singleResponse] = await Promise.all([artistRequest, singleRequest]);
|
||||
expect(artistResponse.status).toBe(200);
|
||||
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);
|
||||
});
|
||||
});
|
||||
+227
-227
@@ -1,17 +1,26 @@
|
||||
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, Song, ArtistSongPage } from "../../music/provider.js";
|
||||
import type { MusicProvider, Song, ArtistSongPage, PlayFailure } from "../../music/provider.js";
|
||||
import { musicRequestError } from "../../music/request-error.js";
|
||||
import type { Logger } from "../../logger.js";
|
||||
import { parseCommand } from "../../bot/commands.js";
|
||||
import { requireBotAccess } from "../middleware/requirePermission.js";
|
||||
import { authorize } from "../middleware/authorize.js";
|
||||
import { supportsPersonalLogin } from "./personal-music.js";
|
||||
import { resolveProviderForRequest } from "./provider-scope.js";
|
||||
|
||||
/** Hard cap on how many tracks one "播放全部" request may queue — a safety net
|
||||
* against a pathological catalogue (and against an upstream paging bug). */
|
||||
const MAX_ARTIST_QUEUE = 500;
|
||||
const ARTIST_QUEUE_PAGE = 100;
|
||||
const MAX_HISTORY_DELETE_BATCH = 500;
|
||||
|
||||
function isHistoryRowId(value: unknown): value is number {
|
||||
return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
|
||||
}
|
||||
|
||||
/** Walks every page of an artist's catalogue (best-first, de-duplicated). */
|
||||
export async function collectArtistSongs(
|
||||
@@ -34,6 +43,21 @@ export async function collectArtistSongs(
|
||||
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,
|
||||
logger: Logger,
|
||||
@@ -41,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.
|
||||
@@ -61,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";
|
||||
@@ -138,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"));
|
||||
@@ -151,29 +256,17 @@ export function createPlayerRouter(
|
||||
rejectDisabledLocalAudio(res);
|
||||
return;
|
||||
}
|
||||
let provider = bot.getProviderFor(
|
||||
platform === "bilibili" || platform === "qq" || platform === "youtube" || platform === "local" || platform === "kugou" || platform === "jellyfin"
|
||||
? platform
|
||||
: "netease"
|
||||
);
|
||||
// A signed-in user who linked their own NetEase account gets FM from
|
||||
// THEIR taste, not the bot's shared login (#164). Songs still resolve
|
||||
// through the shared provider when played.
|
||||
const user = (req as any).user;
|
||||
if (provider.platform === "netease" && user && user.role !== "guest" && database) {
|
||||
const cookie = database.getUserMusicCookie(user.id, "netease");
|
||||
if (cookie && supportsPersonalLogin(provider)) provider = provider.withCookie(cookie);
|
||||
}
|
||||
const message = await bot.startFm(provider, requesterName(req));
|
||||
// Resolve FM recommendations with the caller's account. The bot resolves
|
||||
// each queued track's playback URL using the shared account.
|
||||
const scope = { user: req.user };
|
||||
const resolveFmProvider = () => fmProvider(scope, bot, platform);
|
||||
const message = await bot.startFm(resolveFmProvider(), requesterName(req), resolveFmProvider);
|
||||
res.json({
|
||||
ok:
|
||||
!message.startsWith("No FM songs") &&
|
||||
!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 });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -268,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
|
||||
@@ -282,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);
|
||||
@@ -334,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 });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -427,72 +462,26 @@ 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 });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -512,11 +501,7 @@ export function createPlayerRouter(
|
||||
rejectDisabledLocalAudio(res);
|
||||
return;
|
||||
}
|
||||
const provider = bot.getProviderFor(
|
||||
platform === "bilibili" || platform === "qq" || platform === "youtube" || platform === "local" || platform === "kugou" || platform === "jellyfin"
|
||||
? platform
|
||||
: "netease"
|
||||
);
|
||||
const provider = scopedProvider(req, bot, platform);
|
||||
if (typeof provider.getArtistSongs !== "function") {
|
||||
res.status(501).json({ error: "Not supported by this provider" });
|
||||
return;
|
||||
@@ -533,59 +518,18 @@ export function createPlayerRouter(
|
||||
return;
|
||||
}
|
||||
|
||||
// Same QQ batch-resolve optimization as play-album: drop tracks that are
|
||||
// region/copyright blocked instead of burning retries on them.
|
||||
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;
|
||||
}
|
||||
|
||||
// Catalogue and copyright lookups leave current playback running. Only
|
||||
// the queue replacement and playback itself occupy the shared play gate.
|
||||
const body = await bot.runExclusive(async () => {
|
||||
bot.getPlayer().stop();
|
||||
bot.getPlayer().resetFailures();
|
||||
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} 首`;
|
||||
return started && playing
|
||||
? { ok: true, message: `${loadedMsg},正在播放:${playing.name}` }
|
||||
: { ok: false, message: `${loadedMsg},但无法开始播放。` };
|
||||
});
|
||||
res.json(body);
|
||||
res.json(await startCollection(bot, queueable, provider.platform, requesterName(req), totalCount));
|
||||
} catch (err) {
|
||||
logger.error({ err }, "play-artist failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
const error = musicRequestError(err);
|
||||
logger.error({ err: error }, "play-artist failed");
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -596,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" });
|
||||
@@ -610,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) {
|
||||
@@ -653,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'}` };
|
||||
}
|
||||
@@ -692,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"}` };
|
||||
});
|
||||
@@ -706,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" });
|
||||
@@ -725,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) {
|
||||
@@ -748,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) {
|
||||
@@ -771,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 });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -804,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,
|
||||
@@ -817,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);
|
||||
}
|
||||
@@ -127,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)
|
||||
@@ -300,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 () => {
|
||||
|
||||
@@ -182,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") {
|
||||
|
||||
+38
-6
@@ -8,6 +8,7 @@ import type { MusicProvider } from "../music/provider.js";
|
||||
import type { BotDatabase } from "../data/database.js";
|
||||
import type { BotConfig, GuestModeConfig } from "../data/config.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { APP_VERSION } from "../version.js";
|
||||
import type { CookieStore } from "../music/auth.js";
|
||||
import type { AvatarStore } from "../data/avatars.js";
|
||||
import { createBotRouter } from "./api/bot.js";
|
||||
@@ -20,6 +21,7 @@ import { createAuditStore } from "../data/audit.js";
|
||||
import { createAuditRouter } from "./api/audit.js";
|
||||
import { createFavoritesRouter } from "./api/favorites.js";
|
||||
import { createPersonalMusicRouter } from "./api/personal-music.js";
|
||||
import { createMusicAccountsRouter } from "./api/music-accounts.js";
|
||||
import { createSavedQueuesRouter } from "./api/saved-queues.js";
|
||||
import { createSpotifyRouter } from "./api/spotify.js";
|
||||
import { createApiKeysRouter } from "./api/api-keys.js";
|
||||
@@ -115,7 +117,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
});
|
||||
|
||||
app.get("/api/health", (_req, res) => {
|
||||
res.json({ status: "ok", version: "0.1.0" });
|
||||
res.json({ status: "ok", version: APP_VERSION });
|
||||
});
|
||||
|
||||
app.get("/api/config/public-url", (_req, res) => {
|
||||
@@ -170,15 +172,16 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
);
|
||||
app.use(
|
||||
"/api/music",
|
||||
createMusicRouter(options.neteaseProvider, options.qqProvider, options.bilibiliProvider, logger, options.localProvider, options.config, options.kugouProvider, options.spotifyProvider, options.jellyfinProvider, options.configPath)
|
||||
createMusicRouter(options.neteaseProvider, options.qqProvider, options.bilibiliProvider, logger, options.localProvider, options.config, options.kugouProvider, options.spotifyProvider, options.jellyfinProvider, options.configPath, options.database)
|
||||
);
|
||||
app.use("/api/player", createPlayerRouter(
|
||||
options.botManager, logger, options.database,
|
||||
options.neteaseProvider, options.qqProvider, options.bilibiliProvider,
|
||||
options.config,
|
||||
));
|
||||
app.use(
|
||||
"/api/auth",
|
||||
createAuthRouter(options.neteaseProvider, options.qqProvider, options.bilibiliProvider, logger, options.cookieStore, options.kugouProvider, options.spotifyProvider, options.jellyfinProvider, options.config)
|
||||
createAuthRouter(options.neteaseProvider, options.qqProvider, options.bilibiliProvider, logger, options.cookieStore, options.kugouProvider, options.spotifyProvider, options.jellyfinProvider, options.config, options.database)
|
||||
);
|
||||
if (options.spotifyOAuth) {
|
||||
app.use(
|
||||
@@ -207,12 +210,41 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
);
|
||||
}
|
||||
app.use("/api/favorites", requireNotGuest, createFavoritesRouter(options.database, logger));
|
||||
// The caller's own NetEase login for their personal FM (#164). Guests share
|
||||
// one anonymous identity, so they cannot link an account.
|
||||
// The caller's own music login, per platform (#164 + #164 follow-up). Guests
|
||||
// share one anonymous identity, so they cannot link an account.
|
||||
app.use(
|
||||
"/api/me/music",
|
||||
requireNotGuest,
|
||||
createPersonalMusicRouter(options.database, options.neteaseProvider, logger),
|
||||
createPersonalMusicRouter(
|
||||
options.database,
|
||||
{
|
||||
netease: options.neteaseProvider,
|
||||
qq: options.qqProvider,
|
||||
kugou: options.kugouProvider,
|
||||
bilibili: options.bilibiliProvider,
|
||||
},
|
||||
logger,
|
||||
options.config,
|
||||
),
|
||||
);
|
||||
// Admin-only pool of music logins + per-member assignments (#164 follow-up).
|
||||
// Mounted on requireAdmin, NOT bot.manage: members must never see which
|
||||
// account was handed to whom.
|
||||
app.use(
|
||||
"/api/music-accounts",
|
||||
requireAdmin,
|
||||
createMusicAccountsRouter(
|
||||
options.database,
|
||||
users,
|
||||
{
|
||||
netease: options.neteaseProvider,
|
||||
qq: options.qqProvider,
|
||||
kugou: options.kugouProvider,
|
||||
bilibili: options.bilibiliProvider,
|
||||
},
|
||||
logger,
|
||||
options.cookieStore,
|
||||
),
|
||||
);
|
||||
// Saved queues (Feature 1, #119). Members + admins only (requireNotGuest);
|
||||
// the router itself 403s every route unless savedQueuesEnabled is on.
|
||||
|
||||
+7
-8
@@ -10,12 +10,12 @@ import { QQMusicProvider } from "./src/music/qq.js";
|
||||
import { BotManager } from "./src/bot/manager.js";
|
||||
import { createWebServer } from "./src/web/server.js";
|
||||
import {
|
||||
Client as TS3FullClient,
|
||||
generateIdentity,
|
||||
listClients,
|
||||
sendTextMessage,
|
||||
consoleLogger,
|
||||
} from "@honeybbq/teamspeak-client";
|
||||
} from "@honeybbq/teamspeak";
|
||||
import {
|
||||
Client as TS3FullClient,
|
||||
generateIdentitySync,
|
||||
} from "@honeybbq/teamspeak/client";
|
||||
|
||||
const logger = createLogger();
|
||||
let passed = 0;
|
||||
@@ -83,7 +83,7 @@ async function main() {
|
||||
// ═══ Test 2: Verify bot is visible using a second client ═══
|
||||
log("\n═══ Test 2: Verify Bot Visibility ═══");
|
||||
|
||||
const verifyIdentity = generateIdentity(8);
|
||||
const verifyIdentity = generateIdentitySync(8);
|
||||
const verifyClient = new TS3FullClient(
|
||||
verifyIdentity,
|
||||
"127.0.0.1:9987",
|
||||
@@ -92,8 +92,7 @@ async function main() {
|
||||
);
|
||||
|
||||
await verifyClient.connect();
|
||||
await verifyClient.waitConnected();
|
||||
log(` Verification client connected (id=${verifyClient.clientID()})`);
|
||||
log(` Verification client connected (id=${verifyClient.clientID})`);
|
||||
|
||||
try {
|
||||
const clients = await listClients(verifyClient);
|
||||
|
||||
+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">
|
||||
|
||||
+10
-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 />
|
||||
@@ -82,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>
|
||||
@@ -98,6 +98,7 @@ 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';
|
||||
@@ -113,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();
|
||||
@@ -331,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.
|
||||
@@ -355,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 {
|
||||
|
||||
@@ -207,7 +207,7 @@ function formatDuration(seconds: number): string {
|
||||
|
||||
.part-badge {
|
||||
background: var(--color-primary);
|
||||
color: white;
|
||||
color: var(--color-on-primary);
|
||||
}
|
||||
|
||||
.part-name {
|
||||
@@ -254,7 +254,7 @@ function formatDuration(seconds: number): string {
|
||||
.btn-primary {
|
||||
padding: 10px 20px;
|
||||
background: var(--color-primary);
|
||||
color: white;
|
||||
color: var(--color-on-primary);
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
|
||||
@@ -0,0 +1,553 @@
|
||||
<template>
|
||||
<!-- Admin console for the music-account pool (#164 follow-up).
|
||||
One row per login the admin owns; each row can be handed to members (or
|
||||
to another admin). See src/web/api/music-accounts.ts for the rules. -->
|
||||
<div class="pool">
|
||||
<p class="hint">
|
||||
这里存放管理员拥有的音乐账号,可以逐个分配给成员。成员自己扫码绑定的账号优先级更高,
|
||||
管理员分配的账号只在他们没绑定自己的账号时生效。播放地址、搜索、歌单都会按被分配的账号获取。
|
||||
</p>
|
||||
|
||||
<!-- Create -->
|
||||
<div class="create-row">
|
||||
<select v-model="draft.platform" class="field">
|
||||
<option v-for="p in platforms" :key="p.platform" :value="p.platform">
|
||||
{{ PLATFORM_LABEL[p.platform] ?? p.platform }}
|
||||
{{ p.playbackSupported ? '' : '(暂不支持按账号播放)' }}
|
||||
</option>
|
||||
</select>
|
||||
<input v-model="draft.label" class="field" placeholder="名称,如 网易云-主号" maxlength="64" />
|
||||
<input
|
||||
v-model.number="draft.capacity"
|
||||
class="field field-narrow"
|
||||
type="number"
|
||||
min="0"
|
||||
title="0 = 可分配给多人;1 = 独占,只能给一个人"
|
||||
placeholder="人数上限"
|
||||
/>
|
||||
<button class="btn primary" :disabled="creating" @click="create">
|
||||
<Icon icon="mdi:plus" /> 添加账号
|
||||
</button>
|
||||
<button class="btn" :disabled="creating" @click="importShared">
|
||||
<Icon icon="mdi:download" /> 从共享账号导入
|
||||
</button>
|
||||
</div>
|
||||
<textarea
|
||||
v-model="draft.cookie"
|
||||
class="field cookie-input"
|
||||
rows="2"
|
||||
placeholder="粘贴该账号的 Cookie(仅保存在服务器,列表里只显示掩码)"
|
||||
></textarea>
|
||||
<p v-if="error" class="error">{{ error }}</p>
|
||||
|
||||
<!-- List -->
|
||||
<div v-if="accounts.length === 0" class="empty">还没有添加任何账号</div>
|
||||
|
||||
<div v-for="a in accounts" :key="a.id" class="account" :class="{ disabled: !a.enabled }">
|
||||
<div class="account-head">
|
||||
<div class="account-title">
|
||||
<span class="badge">{{ PLATFORM_LABEL[a.platform] ?? a.platform }}</span>
|
||||
<span class="label">{{ a.label }}</span>
|
||||
<span v-if="a.capacity === 1" class="tag exclusive">独占</span>
|
||||
<span v-else-if="a.capacity > 1" class="tag">最多 {{ a.capacity }} 人</span>
|
||||
<span v-else class="tag">不限人数</span>
|
||||
<span v-if="!a.playbackSupported" class="tag warn">该平台暂不支持按账号播放</span>
|
||||
</div>
|
||||
<div class="account-actions">
|
||||
<button class="btn tiny" @click="probe(a)">
|
||||
<Icon icon="mdi:shield-check" /> 检测
|
||||
</button>
|
||||
<label class="switch" :title="a.enabled ? '已启用' : '已停用'">
|
||||
<input type="checkbox" :checked="a.enabled" @change="toggleEnabled(a)" />
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
<button class="btn tiny danger" @click="remove(a)">
|
||||
<Icon icon="mdi:trash-can-outline" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="account-meta">
|
||||
<span class="mono">{{ a.cookiePreview }}</span>
|
||||
<span v-if="probeResult[a.id]" class="probe" :class="{ ok: probeResult[a.id]!.loggedIn }">
|
||||
{{ probeResult[a.id]!.loggedIn ? `登录有效${probeResult[a.id]!.nickname ? ':' + probeResult[a.id]!.nickname : ''}` : '登录已失效' }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="grantees">
|
||||
<span class="grantees-label">已分配:</span>
|
||||
<span v-if="a.grantees.length === 0" class="muted">无</span>
|
||||
<span v-for="g in a.grantees" :key="g.userId" class="chip">
|
||||
{{ g.username }}
|
||||
<button class="chip-x" title="收回" @click="revoke(a, g.userId)">×</button>
|
||||
</span>
|
||||
<select
|
||||
class="field field-narrow assign-select"
|
||||
:value="''"
|
||||
:disabled="assignable(a).length === 0"
|
||||
@change="onAssign(a, $event)"
|
||||
>
|
||||
<option value="">{{ assignable(a).length === 0 ? '已满额' : '+ 分配给…' }}</option>
|
||||
<option v-for="u in assignable(a)" :key="u.id" :value="u.id">
|
||||
{{ u.username }}{{ u.role === 'admin' ? '(管理员)' : '' }}
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="cookie-edit">
|
||||
<input
|
||||
v-model="cookieDraft[a.id]"
|
||||
class="field"
|
||||
type="password"
|
||||
placeholder="更新 Cookie(登录失效时用)"
|
||||
/>
|
||||
<button class="btn tiny" :disabled="!cookieDraft[a.id]" @click="updateCookie(a)">
|
||||
保存
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from 'vue';
|
||||
import { Icon } from '@iconify/vue';
|
||||
import axios from 'axios';
|
||||
|
||||
interface Grantee { userId: string; username: string; grantedAt: string }
|
||||
interface PoolAccount {
|
||||
id: string;
|
||||
platform: string;
|
||||
label: string;
|
||||
cookiePreview: string;
|
||||
capacity: number;
|
||||
enabled: boolean;
|
||||
playbackSupported: boolean;
|
||||
granteeCount: number;
|
||||
grantees: Grantee[];
|
||||
}
|
||||
interface AssignableUser { id: string; username: string; role: string }
|
||||
|
||||
const PLATFORM_LABEL: Record<string, string> = {
|
||||
netease: '网易云',
|
||||
qq: 'QQ音乐',
|
||||
kugou: '酷狗',
|
||||
bilibili: 'B站',
|
||||
};
|
||||
|
||||
const accounts = ref<PoolAccount[]>([]);
|
||||
const users = ref<AssignableUser[]>([]);
|
||||
const platforms = ref<Array<{ platform: string; playbackSupported: boolean }>>([]);
|
||||
const creating = ref(false);
|
||||
const error = ref('');
|
||||
// Default to exclusive: sharing one login between members mixes their
|
||||
// playback history and recommendations, which is almost never intended.
|
||||
const draft = reactive({ platform: 'netease', label: '', cookie: '', capacity: 1 });
|
||||
const cookieDraft = reactive<Record<string, string>>({});
|
||||
const probeResult = ref<Record<string, { loggedIn: boolean; nickname?: string } | undefined>>({});
|
||||
|
||||
const assignable = (a: PoolAccount) => {
|
||||
const held = new Set(a.grantees.map((g) => g.userId));
|
||||
// An exclusive account that already has a holder offers nobody: the API would
|
||||
// answer 409 anyway, so don't dangle options that cannot work.
|
||||
if (a.capacity === 1 && a.granteeCount >= 1) return [];
|
||||
if (a.capacity > 1 && a.granteeCount >= a.capacity) return [];
|
||||
return users.value.filter((u) => !held.has(u.id));
|
||||
};
|
||||
|
||||
const errText = (err: any, fallback: string) => {
|
||||
const e = err?.response?.data?.error;
|
||||
if (e === 'account_exclusive') return '该账号是独占的,请先收回其他成员';
|
||||
if (e === 'account_full') return '该账号已分配满额';
|
||||
if (e === 'account_disabled') return '该账号已停用';
|
||||
if (e === 'no_shared_login') return '机器人还没有登录该平台的共享账号';
|
||||
return e ?? fallback;
|
||||
};
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const res = await axios.get('/api/music-accounts');
|
||||
accounts.value = res.data.accounts ?? [];
|
||||
users.value = res.data.users ?? [];
|
||||
platforms.value = res.data.platforms ?? [];
|
||||
if (!platforms.value.some((p) => p.platform === draft.platform)) {
|
||||
draft.platform = platforms.value[0]?.platform ?? 'netease';
|
||||
}
|
||||
} catch (err) {
|
||||
error.value = errText(err, '加载失败');
|
||||
}
|
||||
}
|
||||
|
||||
async function create() {
|
||||
error.value = '';
|
||||
if (!draft.label.trim() || !draft.cookie.trim()) {
|
||||
error.value = '名称和 Cookie 都要填';
|
||||
return;
|
||||
}
|
||||
creating.value = true;
|
||||
try {
|
||||
await axios.post('/api/music-accounts', {
|
||||
platform: draft.platform,
|
||||
label: draft.label.trim(),
|
||||
cookie: draft.cookie.trim(),
|
||||
capacity: Number(draft.capacity) || 0,
|
||||
});
|
||||
draft.label = '';
|
||||
draft.cookie = '';
|
||||
draft.capacity = 1;
|
||||
await load();
|
||||
} catch (err) {
|
||||
error.value = errText(err, '添加失败');
|
||||
} finally {
|
||||
creating.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function importShared() {
|
||||
error.value = '';
|
||||
creating.value = true;
|
||||
try {
|
||||
await axios.post('/api/music-accounts/import-shared', {
|
||||
platform: draft.platform,
|
||||
label: `${PLATFORM_LABEL[draft.platform] ?? draft.platform} 共享账号`,
|
||||
capacity: Number(draft.capacity) || 0,
|
||||
});
|
||||
await load();
|
||||
} catch (err) {
|
||||
error.value = errText(err, '导入失败');
|
||||
} finally {
|
||||
creating.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleEnabled(a: PoolAccount) {
|
||||
error.value = '';
|
||||
try {
|
||||
await axios.patch(`/api/music-accounts/${a.id}`, { enabled: !a.enabled });
|
||||
await load();
|
||||
} catch (err) {
|
||||
error.value = errText(err, '操作失败');
|
||||
}
|
||||
}
|
||||
|
||||
async function updateCookie(a: PoolAccount) {
|
||||
error.value = '';
|
||||
try {
|
||||
await axios.patch(`/api/music-accounts/${a.id}`, { cookie: cookieDraft[a.id] });
|
||||
cookieDraft[a.id] = '';
|
||||
await load();
|
||||
} catch (err) {
|
||||
error.value = errText(err, '保存失败');
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(a: PoolAccount) {
|
||||
if (!confirm(`删除「${a.label}」?已分配给成员的记录会一起收回。`)) return;
|
||||
error.value = '';
|
||||
try {
|
||||
await axios.delete(`/api/music-accounts/${a.id}`);
|
||||
await load();
|
||||
} catch (err) {
|
||||
error.value = errText(err, '删除失败');
|
||||
}
|
||||
}
|
||||
|
||||
async function onAssign(a: PoolAccount, ev: Event) {
|
||||
const select = ev.target as HTMLSelectElement;
|
||||
const userId = select.value;
|
||||
select.value = '';
|
||||
if (!userId) return;
|
||||
error.value = '';
|
||||
try {
|
||||
await axios.post(`/api/music-accounts/${a.id}/assign`, { userId });
|
||||
await load();
|
||||
} catch (err) {
|
||||
error.value = errText(err, '分配失败');
|
||||
}
|
||||
}
|
||||
|
||||
async function revoke(a: PoolAccount, userId: string) {
|
||||
error.value = '';
|
||||
try {
|
||||
await axios.delete(`/api/music-accounts/${a.id}/assign/${userId}`);
|
||||
await load();
|
||||
} catch (err) {
|
||||
error.value = errText(err, '收回失败');
|
||||
}
|
||||
}
|
||||
|
||||
async function probe(a: PoolAccount) {
|
||||
error.value = '';
|
||||
try {
|
||||
const res = await axios.post(`/api/music-accounts/${a.id}/probe`);
|
||||
probeResult.value[a.id] = { loggedIn: Boolean(res.data.loggedIn), nickname: res.data.nickname };
|
||||
} catch (err) {
|
||||
probeResult.value[a.id] = { loggedIn: false };
|
||||
error.value = errText(err, '检测失败');
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load);
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.pool {
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.hint {
|
||||
font-size: 12px;
|
||||
color: var(--text-tertiary);
|
||||
line-height: 1.6;
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
|
||||
.create-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.field {
|
||||
padding: 7px 10px;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--radius-sm);
|
||||
color: inherit;
|
||||
font-size: 13px;
|
||||
min-width: 0;
|
||||
&:focus {
|
||||
outline: none;
|
||||
border-color: var(--color-primary);
|
||||
}
|
||||
}
|
||||
|
||||
.field-narrow {
|
||||
width: 96px;
|
||||
}
|
||||
|
||||
.cookie-input {
|
||||
width: 100%;
|
||||
resize: vertical;
|
||||
font-family: var(--font-mono, monospace);
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
padding: 7px 14px;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 13px;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
transition: all var(--transition-fast);
|
||||
&:hover:not(:disabled) {
|
||||
border-color: var(--color-primary);
|
||||
color: var(--color-primary);
|
||||
}
|
||||
&:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: default;
|
||||
}
|
||||
&.primary {
|
||||
border-color: var(--color-primary);
|
||||
color: var(--color-primary);
|
||||
}
|
||||
&.tiny {
|
||||
padding: 4px 8px;
|
||||
font-size: 12px;
|
||||
}
|
||||
&.danger:hover {
|
||||
border-color: #e26a6a;
|
||||
color: #e26a6a;
|
||||
}
|
||||
}
|
||||
|
||||
.empty {
|
||||
padding: 16px;
|
||||
font-size: 13px;
|
||||
color: var(--text-tertiary);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.account {
|
||||
padding: 12px 14px;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--radius-md);
|
||||
margin-bottom: 10px;
|
||||
background: var(--hover-bg);
|
||||
&.disabled {
|
||||
opacity: 0.6;
|
||||
}
|
||||
}
|
||||
|
||||
.account-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.account-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.badge {
|
||||
font-size: 11px;
|
||||
padding: 2px 7px;
|
||||
border-radius: 10px;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border-color);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.label {
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.tag {
|
||||
font-size: 11px;
|
||||
color: var(--text-tertiary);
|
||||
&.exclusive {
|
||||
color: var(--color-primary);
|
||||
}
|
||||
&.warn {
|
||||
color: #d19a3a;
|
||||
}
|
||||
}
|
||||
|
||||
.account-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.account-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin-top: 6px;
|
||||
font-size: 12px;
|
||||
color: var(--text-tertiary);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.mono {
|
||||
font-family: var(--font-mono, monospace);
|
||||
}
|
||||
|
||||
.probe {
|
||||
color: #e26a6a;
|
||||
&.ok {
|
||||
color: var(--color-online);
|
||||
}
|
||||
}
|
||||
|
||||
.grantees {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.grantees-label {
|
||||
font-size: 12px;
|
||||
color: var(--text-tertiary);
|
||||
}
|
||||
|
||||
.muted {
|
||||
font-size: 12px;
|
||||
color: var(--text-tertiary);
|
||||
}
|
||||
|
||||
.chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 3px;
|
||||
padding: 2px 8px;
|
||||
font-size: 12px;
|
||||
border-radius: 10px;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.chip-x {
|
||||
border: none;
|
||||
background: none;
|
||||
color: var(--text-tertiary);
|
||||
cursor: pointer;
|
||||
font-size: 13px;
|
||||
line-height: 1;
|
||||
padding: 0 0 0 2px;
|
||||
&:hover {
|
||||
color: #e26a6a;
|
||||
}
|
||||
}
|
||||
|
||||
.assign-select {
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.cookie-edit {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-top: 10px;
|
||||
.field {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.switch {
|
||||
position: relative;
|
||||
display: inline-block;
|
||||
width: 34px;
|
||||
height: 18px;
|
||||
input {
|
||||
opacity: 0;
|
||||
width: 0;
|
||||
height: 0;
|
||||
}
|
||||
.slider {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: var(--border-color);
|
||||
border-radius: 9px;
|
||||
cursor: pointer;
|
||||
transition: background var(--transition-fast);
|
||||
}
|
||||
.slider::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
left: 2px;
|
||||
top: 2px;
|
||||
background: #fff;
|
||||
border-radius: 50%;
|
||||
transition: transform var(--transition-fast);
|
||||
}
|
||||
input:checked + .slider {
|
||||
background: var(--color-primary);
|
||||
}
|
||||
input:checked + .slider::before {
|
||||
transform: translateX(16px);
|
||||
}
|
||||
}
|
||||
|
||||
.error {
|
||||
margin: 6px 0;
|
||||
font-size: 12px;
|
||||
color: #e26a6a;
|
||||
}
|
||||
</style>
|
||||
@@ -104,7 +104,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<RouterLink v-if="!session.isGuest.value" to="/settings" class="settings-btn">
|
||||
<RouterLink to="/settings" class="settings-btn" aria-label="设置" title="设置">
|
||||
<Icon icon="mdi:cog" />
|
||||
</RouterLink>
|
||||
|
||||
@@ -655,7 +655,7 @@ onUnmounted(() => {
|
||||
|
||||
&.primary {
|
||||
background: var(--color-primary);
|
||||
color: #fff;
|
||||
color: var(--color-on-primary);
|
||||
border-color: var(--color-primary);
|
||||
}
|
||||
|
||||
@@ -665,9 +665,16 @@ onUnmounted(() => {
|
||||
}
|
||||
|
||||
.settings-btn {
|
||||
font-size: 22px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
flex-shrink: 0;
|
||||
font-size: 20px;
|
||||
line-height: 1;
|
||||
opacity: 0.6;
|
||||
transition: opacity var(--transition-fast);
|
||||
svg { display: block; width: 20px; height: 20px; }
|
||||
&:hover { opacity: 1; }
|
||||
|
||||
@media (max-width: 768px) {
|
||||
@@ -750,7 +757,7 @@ onUnmounted(() => {
|
||||
&.primary {
|
||||
background: var(--color-primary);
|
||||
border-color: var(--color-primary);
|
||||
color: #fff;
|
||||
color: var(--color-on-primary);
|
||||
|
||||
&:hover {
|
||||
filter: brightness(1.08);
|
||||
|
||||
@@ -0,0 +1,552 @@
|
||||
<template>
|
||||
<!-- The signed-in user's own music accounts (#164 + #164 follow-up).
|
||||
Two ways an account can apply to this user:
|
||||
- 自己扫码绑定 (source = personal) → they may unlink it
|
||||
- 管理员分配 (source = granted) → only the admin can revoke it
|
||||
Everything is read from /api/me/music/<platform>/status; the cookie never
|
||||
reaches the browser. -->
|
||||
<div class="account-card">
|
||||
<div class="account-header">
|
||||
<Icon icon="mdi:account-music" class="account-icon" />
|
||||
<div class="account-info">
|
||||
<div class="account-name">我的音乐账号</div>
|
||||
<div class="account-status" :class="{ logged: status.loggedIn, granted: status.source === 'granted' }">
|
||||
<template v-if="status.source === 'granted'">
|
||||
由管理员分配:{{ status.label || '已分配的账号' }}
|
||||
<template v-if="status.loggedIn && status.nickname">({{ status.nickname }})</template>
|
||||
<template v-else-if="!status.loggedIn">,但登录已失效,请联系管理员</template>
|
||||
</template>
|
||||
<template v-else-if="status.loggedIn">已绑定:{{ status.nickname }}</template>
|
||||
<template v-else-if="status.linked">已绑定,但登录已失效,请重新扫码</template>
|
||||
<template v-else>未绑定 — 使用机器人的共享账号</template>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Platform switch: only the sources this instance has enabled. -->
|
||||
<div v-if="platforms.length > 1" class="platform-tabs">
|
||||
<button
|
||||
v-for="p in platforms"
|
||||
:key="p"
|
||||
class="platform-tab"
|
||||
:class="{ active: p === current }"
|
||||
@click="selectPlatform(p)"
|
||||
>
|
||||
{{ PLATFORM_LABEL[p] ?? p }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p class="hint">
|
||||
<template v-if="status.source === 'granted'">
|
||||
网页搜索、歌单和每日推荐默认使用管理员分配的账号。自己的绑定优先。
|
||||
</template>
|
||||
<template v-else-if="status.supportsQrLogin">
|
||||
管理员开启每用户独立账号后,可使用你绑定的{{ PLATFORM_LABEL[current] ?? current }}账号查看网页搜索、歌单和推荐。登录凭据保存在服务器。
|
||||
</template>
|
||||
<template v-else>
|
||||
该平台暂不支持在网页端自助绑定,需要账号请联系管理员分配。
|
||||
</template>
|
||||
</p>
|
||||
|
||||
<!-- 网页用哪个账号。只有真的持有个人/分配账号、且管理员开了这个功能时
|
||||
才有得选;否则本来就走共享账号。 -->
|
||||
<div
|
||||
v-if="status.featureEnabled && status.linked"
|
||||
class="account-choice"
|
||||
role="radiogroup"
|
||||
aria-label="网页端使用哪个账号"
|
||||
>
|
||||
<div class="account-choice-title">网页端使用哪个账号</div>
|
||||
|
||||
<div
|
||||
class="account-choice-option"
|
||||
:class="{ active: !status.preferShared }"
|
||||
role="radio"
|
||||
:aria-checked="!status.preferShared"
|
||||
tabindex="0"
|
||||
@click="setPreference(false)"
|
||||
@keydown.enter.prevent="setPreference(false)"
|
||||
@keydown.space.prevent="setPreference(false)"
|
||||
>
|
||||
<span class="account-choice-dot" :class="{ on: !status.preferShared }" />
|
||||
<span class="account-choice-text">
|
||||
<strong>我的账号</strong>
|
||||
<em>
|
||||
{{ status.source === 'granted' ? '管理员分配的账号' : '我扫码绑定的账号' }}
|
||||
</em>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="account-choice-option"
|
||||
:class="{ active: status.preferShared }"
|
||||
role="radio"
|
||||
:aria-checked="status.preferShared"
|
||||
tabindex="0"
|
||||
@click="setPreference(true)"
|
||||
@keydown.enter.prevent="setPreference(true)"
|
||||
@keydown.space.prevent="setPreference(true)"
|
||||
>
|
||||
<span class="account-choice-dot" :class="{ on: status.preferShared }" />
|
||||
<span class="account-choice-text">
|
||||
<strong>共享账号(管理员的)</strong>
|
||||
<em>查看共享账号的歌单和推荐</em>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="account-choice-note">
|
||||
这个选择影响网页端的搜索、歌单和推荐。房间播歌使用机器人共享账号。
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="login-methods">
|
||||
<button
|
||||
v-if="status.supportsQrLogin"
|
||||
class="login-btn"
|
||||
:disabled="qr.loading"
|
||||
@click="startQrLogin"
|
||||
>
|
||||
<Icon icon="mdi:qrcode" />
|
||||
{{ status.linked ? '重新扫码绑定' : '扫码绑定' }}
|
||||
</button>
|
||||
<!-- Only the user's OWN login can be removed here; an admin-granted one
|
||||
is managed from Settings → 音乐账号分配. -->
|
||||
<button v-if="status.canUnlink" class="login-btn" @click="unlink">
|
||||
<Icon icon="mdi:link-off" />
|
||||
解除绑定
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="qr.loading" class="qr-loading">
|
||||
<Icon icon="mdi:loading" class="spin" />
|
||||
生成二维码中...
|
||||
</div>
|
||||
<div v-else-if="qr.dataUrl" class="qr-wrap">
|
||||
<img :src="qr.dataUrl" class="qr-image" alt="QR Code" />
|
||||
<div class="qr-status" :class="qr.status">
|
||||
<template v-if="qr.status === 'waiting'">
|
||||
<Icon icon="mdi:cellphone" /> 请使用{{ PLATFORM_LABEL[current] ?? '' }}APP扫码
|
||||
</template>
|
||||
<template v-else-if="qr.status === 'scanned'">
|
||||
<Icon icon="mdi:check" /> 已扫码,请在手机上确认
|
||||
</template>
|
||||
<template v-else-if="qr.status === 'confirmed'">
|
||||
<Icon icon="mdi:check-circle" /> 绑定成功!
|
||||
</template>
|
||||
<template v-else-if="qr.status === 'expired'">
|
||||
<Icon icon="mdi:refresh" /> 二维码已过期
|
||||
<button class="btn-link" @click="startQrLogin">重新生成</button>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="error" class="error">{{ error }}</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted, onUnmounted, reactive, ref, watch } from 'vue';
|
||||
import { Icon } from '@iconify/vue';
|
||||
import axios from 'axios';
|
||||
import QRCode from 'qrcode';
|
||||
|
||||
const props = withDefaults(defineProps<{ platforms?: string[] }>(), {
|
||||
platforms: () => ['netease'],
|
||||
});
|
||||
|
||||
const PLATFORM_LABEL: Record<string, string> = {
|
||||
netease: '网易云',
|
||||
qq: 'QQ音乐',
|
||||
kugou: '酷狗',
|
||||
bilibili: 'B站',
|
||||
};
|
||||
|
||||
const current = ref(props.platforms[0] ?? 'netease');
|
||||
const status = reactive({
|
||||
linked: false,
|
||||
loggedIn: false,
|
||||
nickname: '',
|
||||
label: '',
|
||||
source: 'none' as 'none' | 'personal' | 'granted',
|
||||
canUnlink: false,
|
||||
supportsQrLogin: false,
|
||||
preferShared: false,
|
||||
featureEnabled: false,
|
||||
});
|
||||
const qr = reactive({
|
||||
loading: false,
|
||||
dataUrl: '',
|
||||
key: '',
|
||||
status: 'waiting' as 'waiting' | 'scanned' | 'confirmed' | 'expired',
|
||||
});
|
||||
const error = ref('');
|
||||
let pollTimer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
const base = () => `/api/me/music/${current.value}`;
|
||||
|
||||
function stopPolling() {
|
||||
if (pollTimer) clearInterval(pollTimer);
|
||||
pollTimer = null;
|
||||
}
|
||||
|
||||
async function refreshStatus() {
|
||||
try {
|
||||
const res = await axios.get(`${base()}/status`);
|
||||
status.linked = Boolean(res.data?.linked);
|
||||
status.loggedIn = Boolean(res.data?.loggedIn);
|
||||
status.nickname = res.data?.nickname ?? '';
|
||||
status.label = res.data?.label ?? '';
|
||||
status.source = res.data?.source ?? 'none';
|
||||
status.canUnlink = Boolean(res.data?.canUnlink);
|
||||
status.supportsQrLogin = Boolean(res.data?.supportsQrLogin);
|
||||
status.preferShared = Boolean(res.data?.preferShared);
|
||||
status.featureEnabled = Boolean(res.data?.featureEnabled);
|
||||
} catch {
|
||||
// Leave the last known state
|
||||
}
|
||||
}
|
||||
|
||||
function resetQr() {
|
||||
stopPolling();
|
||||
qr.dataUrl = '';
|
||||
qr.key = '';
|
||||
qr.status = 'waiting';
|
||||
}
|
||||
|
||||
function selectPlatform(p: string) {
|
||||
if (p === current.value) return;
|
||||
current.value = p;
|
||||
error.value = '';
|
||||
resetQr();
|
||||
void refreshStatus();
|
||||
}
|
||||
|
||||
async function startQrLogin() {
|
||||
stopPolling();
|
||||
error.value = '';
|
||||
qr.loading = true;
|
||||
qr.dataUrl = '';
|
||||
qr.status = 'waiting';
|
||||
try {
|
||||
const res = await axios.post(`${base()}/qrcode`);
|
||||
const { qrUrl, qrImg, key } = res.data;
|
||||
qr.key = key;
|
||||
// Dark-on-light only: many in-app scanners can't read an inverted code.
|
||||
qr.dataUrl = qrImg || (await QRCode.toDataURL(qrUrl, {
|
||||
width: 200,
|
||||
margin: 2,
|
||||
color: { dark: '#000000', light: '#ffffff' },
|
||||
}));
|
||||
pollTimer = setInterval(pollQrStatus, 2000);
|
||||
} catch (err: any) {
|
||||
const code = err?.response?.status;
|
||||
error.value = code === 501
|
||||
? '该平台暂不支持自助绑定,请联系管理员分配账号'
|
||||
: (err?.response?.data?.error ?? '二维码生成失败');
|
||||
} finally {
|
||||
qr.loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function pollQrStatus() {
|
||||
if (!qr.key) return;
|
||||
try {
|
||||
const res = await axios.get(`${base()}/qrcode/status`, { params: { key: qr.key } });
|
||||
qr.status = res.data.status;
|
||||
if (qr.status === 'confirmed') {
|
||||
stopPolling();
|
||||
await refreshStatus();
|
||||
} else if (qr.status === 'expired') {
|
||||
stopPolling();
|
||||
}
|
||||
} catch {
|
||||
// Ignore poll errors
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Switch which login playback uses.
|
||||
*
|
||||
* `true` = the bot's shared account (usually the admin's, usually the one with
|
||||
* a membership), `false` = my own / the assigned one. Nothing is unlinked, so
|
||||
* switching back restores the personal account exactly as it was.
|
||||
*/
|
||||
async function setPreference(preferShared: boolean) {
|
||||
if (preferShared === status.preferShared) return;
|
||||
error.value = '';
|
||||
const previous = status.preferShared;
|
||||
status.preferShared = preferShared; // optimistic — the radio must feel instant
|
||||
try {
|
||||
await axios.put(`${base()}/preference`, { preferShared });
|
||||
} catch (err: any) {
|
||||
status.preferShared = previous;
|
||||
const code = err?.response?.status;
|
||||
error.value =
|
||||
code === 409
|
||||
? '管理员未开启「每用户独立账号」,暂时无法切换'
|
||||
: (err?.response?.data?.error ?? '切换失败');
|
||||
}
|
||||
}
|
||||
|
||||
async function unlink() {
|
||||
error.value = '';
|
||||
try {
|
||||
await axios.delete(base());
|
||||
resetQr();
|
||||
await refreshStatus();
|
||||
} catch (err: any) {
|
||||
error.value = err?.response?.data?.error ?? '解除绑定失败';
|
||||
}
|
||||
}
|
||||
|
||||
// Settings can render before the provider list is known; follow it if it changes.
|
||||
watch(
|
||||
() => props.platforms,
|
||||
(list) => {
|
||||
if (list.length > 0 && !list.includes(current.value)) {
|
||||
current.value = list[0];
|
||||
void refreshStatus();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
onMounted(refreshStatus);
|
||||
onUnmounted(stopPolling);
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.account-card {
|
||||
margin-top: 16px;
|
||||
padding: 20px;
|
||||
background: var(--hover-bg);
|
||||
border-radius: var(--radius-md);
|
||||
}
|
||||
|
||||
.account-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.account-icon {
|
||||
font-size: 28px;
|
||||
color: var(--color-primary);
|
||||
}
|
||||
|
||||
.account-name {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.account-status {
|
||||
font-size: 12px;
|
||||
color: var(--text-tertiary);
|
||||
&.logged { color: var(--color-online); }
|
||||
&.granted { color: var(--text-secondary); }
|
||||
}
|
||||
|
||||
.platform-tabs {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.platform-tab {
|
||||
padding: 5px 12px;
|
||||
font-size: 12px;
|
||||
border-radius: 14px;
|
||||
border: 1px solid var(--border-color);
|
||||
background: var(--bg-card);
|
||||
color: var(--text-secondary);
|
||||
cursor: pointer;
|
||||
transition: all var(--transition-fast);
|
||||
&.active {
|
||||
border-color: var(--color-primary);
|
||||
color: var(--color-primary);
|
||||
}
|
||||
}
|
||||
|
||||
.hint {
|
||||
font-size: 12px;
|
||||
color: var(--text-tertiary);
|
||||
margin: 0 0 12px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.account-choice {
|
||||
margin: 12px 0 16px;
|
||||
padding: 12px;
|
||||
border: 1px solid var(--border-color, rgba(128, 128, 128, 0.2));
|
||||
border-radius: var(--radius-sm, 8px);
|
||||
}
|
||||
|
||||
.account-choice-title {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
margin-bottom: 8px;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.account-choice-option {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
padding: 8px 10px;
|
||||
border-radius: var(--radius-sm, 8px);
|
||||
cursor: pointer;
|
||||
transition: background-color 0.15s ease;
|
||||
|
||||
& + & {
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
background: var(--hover-bg-strong, rgba(128, 128, 128, 0.08));
|
||||
}
|
||||
|
||||
&.active {
|
||||
background: var(--hover-bg-strong, rgba(128, 128, 128, 0.1));
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--color-primary);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
.account-choice-dot {
|
||||
flex: 0 0 auto;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
margin-top: 2px;
|
||||
border-radius: 50%;
|
||||
border: 2px solid var(--text-secondary, #888);
|
||||
position: relative;
|
||||
|
||||
&.on {
|
||||
border-color: var(--color-primary);
|
||||
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 2px;
|
||||
border-radius: 50%;
|
||||
background: var(--color-primary);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.account-choice-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
font-size: 13px;
|
||||
line-height: 1.45;
|
||||
|
||||
strong {
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
em {
|
||||
font-style: normal;
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
/* Scope disclaimer: the radio above governs the web player only. Members were
|
||||
reading "共享账号" as "房间里也用这个" — which is true, but for the opposite
|
||||
reason, so it needs saying. */
|
||||
.account-choice-note {
|
||||
margin-top: 8px;
|
||||
padding-top: 8px;
|
||||
border-top: 1px dashed var(--border-color, rgba(128, 128, 128, 0.2));
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
color: var(--text-secondary);
|
||||
|
||||
code {
|
||||
font-size: 11px;
|
||||
padding: 1px 4px;
|
||||
border-radius: 3px;
|
||||
background: var(--hover-bg-strong, rgba(128, 128, 128, 0.12));
|
||||
}
|
||||
}
|
||||
|
||||
.login-methods {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.login-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 8px 16px;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
transition: all var(--transition-fast);
|
||||
&:hover:not(:disabled) { border-color: var(--color-primary); color: var(--color-primary); }
|
||||
&:disabled { opacity: 0.6; cursor: default; }
|
||||
}
|
||||
|
||||
.qr-loading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.qr-wrap {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.qr-image {
|
||||
width: 200px;
|
||||
height: 200px;
|
||||
border-radius: var(--radius-md);
|
||||
border: 2px solid var(--border-color);
|
||||
}
|
||||
|
||||
.qr-status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
&.confirmed { color: var(--color-online); }
|
||||
}
|
||||
|
||||
.btn-link {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--color-primary);
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.error {
|
||||
margin-top: 8px;
|
||||
font-size: 12px;
|
||||
color: #e26a6a;
|
||||
}
|
||||
|
||||
.spin {
|
||||
animation: spin 1s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
</style>
|
||||
@@ -1,261 +0,0 @@
|
||||
<template>
|
||||
<!-- The signed-in user's own NetEase account, used for THEIR 私人FM instead
|
||||
of the bot's shared login (#164). -->
|
||||
<div class="account-card">
|
||||
<div class="account-header">
|
||||
<Icon icon="mdi:radio" class="account-icon" />
|
||||
<div class="account-info">
|
||||
<div class="account-name">我的网易云账号(私人FM)</div>
|
||||
<div class="account-status" :class="{ logged: status.loggedIn }">
|
||||
<template v-if="status.loggedIn">已绑定: {{ status.nickname }}</template>
|
||||
<template v-else-if="status.linked">已绑定,但登录已失效,请重新扫码</template>
|
||||
<template v-else>未绑定 — 私人FM使用机器人的共享账号</template>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="hint">
|
||||
绑定后,你在网页端开启的网易云私人FM会按你自己的口味推荐;其他人不受影响。
|
||||
仅保存在服务器上,不会显示给任何人。
|
||||
</p>
|
||||
|
||||
<div class="login-methods">
|
||||
<button class="login-btn" :disabled="qr.loading" @click="startQrLogin">
|
||||
<Icon icon="mdi:qrcode" />
|
||||
{{ status.linked ? '重新扫码绑定' : '扫码绑定' }}
|
||||
</button>
|
||||
<button v-if="status.linked" class="login-btn" @click="unlink">
|
||||
<Icon icon="mdi:link-off" />
|
||||
解除绑定
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="qr.loading" class="qr-loading">
|
||||
<Icon icon="mdi:loading" class="spin" />
|
||||
生成二维码中...
|
||||
</div>
|
||||
<div v-else-if="qr.dataUrl" class="qr-wrap">
|
||||
<img :src="qr.dataUrl" class="qr-image" alt="QR Code" />
|
||||
<div class="qr-status" :class="qr.status">
|
||||
<template v-if="qr.status === 'waiting'">
|
||||
<Icon icon="mdi:cellphone" /> 请使用网易云音乐APP扫码
|
||||
</template>
|
||||
<template v-else-if="qr.status === 'scanned'">
|
||||
<Icon icon="mdi:check" /> 已扫码,请在手机上确认
|
||||
</template>
|
||||
<template v-else-if="qr.status === 'confirmed'">
|
||||
<Icon icon="mdi:check-circle" /> 绑定成功!
|
||||
</template>
|
||||
<template v-else-if="qr.status === 'expired'">
|
||||
<Icon icon="mdi:refresh" /> 二维码已过期
|
||||
<button class="btn-link" @click="startQrLogin">重新生成</button>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="error" class="error">{{ error }}</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted, onUnmounted, reactive, ref } from 'vue';
|
||||
import { Icon } from '@iconify/vue';
|
||||
import axios from 'axios';
|
||||
import QRCode from 'qrcode';
|
||||
|
||||
const BASE = '/api/me/music/netease';
|
||||
|
||||
const status = reactive({ linked: false, loggedIn: false, nickname: '' });
|
||||
const qr = reactive({
|
||||
loading: false,
|
||||
dataUrl: '',
|
||||
key: '',
|
||||
status: 'waiting' as 'waiting' | 'scanned' | 'confirmed' | 'expired',
|
||||
});
|
||||
const error = ref('');
|
||||
let pollTimer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
function stopPolling() {
|
||||
if (pollTimer) clearInterval(pollTimer);
|
||||
pollTimer = null;
|
||||
}
|
||||
|
||||
async function refreshStatus() {
|
||||
try {
|
||||
const res = await axios.get(`${BASE}/status`);
|
||||
status.linked = Boolean(res.data?.linked);
|
||||
status.loggedIn = Boolean(res.data?.loggedIn);
|
||||
status.nickname = res.data?.nickname ?? '';
|
||||
} catch {
|
||||
// Leave the last known state
|
||||
}
|
||||
}
|
||||
|
||||
async function startQrLogin() {
|
||||
stopPolling();
|
||||
error.value = '';
|
||||
qr.loading = true;
|
||||
qr.dataUrl = '';
|
||||
qr.status = 'waiting';
|
||||
try {
|
||||
const res = await axios.post(`${BASE}/qrcode`);
|
||||
const { qrUrl, qrImg, key } = res.data;
|
||||
qr.key = key;
|
||||
// Dark-on-light only: many in-app scanners can't read an inverted code.
|
||||
qr.dataUrl = qrImg || (await QRCode.toDataURL(qrUrl, {
|
||||
width: 200,
|
||||
margin: 2,
|
||||
color: { dark: '#000000', light: '#ffffff' },
|
||||
}));
|
||||
pollTimer = setInterval(pollQrStatus, 2000);
|
||||
} catch (err: any) {
|
||||
error.value = err?.response?.data?.error ?? '二维码生成失败';
|
||||
} finally {
|
||||
qr.loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function pollQrStatus() {
|
||||
if (!qr.key) return;
|
||||
try {
|
||||
const res = await axios.get(`${BASE}/qrcode/status`, { params: { key: qr.key } });
|
||||
qr.status = res.data.status;
|
||||
if (qr.status === 'confirmed') {
|
||||
stopPolling();
|
||||
await refreshStatus();
|
||||
} else if (qr.status === 'expired') {
|
||||
stopPolling();
|
||||
}
|
||||
} catch {
|
||||
// Ignore poll errors
|
||||
}
|
||||
}
|
||||
|
||||
async function unlink() {
|
||||
error.value = '';
|
||||
try {
|
||||
await axios.delete(BASE);
|
||||
stopPolling();
|
||||
qr.dataUrl = '';
|
||||
await refreshStatus();
|
||||
} catch (err: any) {
|
||||
error.value = err?.response?.data?.error ?? '解除绑定失败';
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(refreshStatus);
|
||||
onUnmounted(stopPolling);
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.account-card {
|
||||
margin-top: 16px;
|
||||
padding: 20px;
|
||||
background: var(--hover-bg);
|
||||
border-radius: var(--radius-md);
|
||||
}
|
||||
|
||||
.account-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.account-icon {
|
||||
font-size: 28px;
|
||||
color: var(--color-primary);
|
||||
}
|
||||
|
||||
.account-name {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.account-status {
|
||||
font-size: 12px;
|
||||
color: var(--text-tertiary);
|
||||
&.logged { color: var(--color-online); }
|
||||
}
|
||||
|
||||
.hint {
|
||||
font-size: 12px;
|
||||
color: var(--text-tertiary);
|
||||
margin: 0 0 12px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.login-methods {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.login-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 8px 16px;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
transition: all var(--transition-fast);
|
||||
&:hover:not(:disabled) { border-color: var(--color-primary); color: var(--color-primary); }
|
||||
&:disabled { opacity: 0.6; cursor: default; }
|
||||
}
|
||||
|
||||
.qr-loading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.qr-wrap {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.qr-image {
|
||||
width: 200px;
|
||||
height: 200px;
|
||||
border-radius: var(--radius-md);
|
||||
border: 2px solid var(--border-color);
|
||||
}
|
||||
|
||||
.qr-status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
&.confirmed { color: var(--color-online); }
|
||||
}
|
||||
|
||||
.btn-link {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--color-primary);
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.error {
|
||||
margin-top: 8px;
|
||||
font-size: 12px;
|
||||
color: #e26a6a;
|
||||
}
|
||||
|
||||
.spin {
|
||||
animation: spin 1s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
</style>
|
||||
@@ -426,7 +426,7 @@ function cycleMode() {
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 18px;
|
||||
color: white;
|
||||
color: var(--color-on-primary);
|
||||
transition: transform var(--transition-fast);
|
||||
&:hover { transform: scale(1.08); }
|
||||
&:active { transform: scale(0.95); }
|
||||
|
||||
@@ -7,6 +7,7 @@ interface User {
|
||||
capabilities?: string[];
|
||||
bots?: "all" | string[];
|
||||
guest?: Record<string, boolean> | null;
|
||||
accentColor?: string | null;
|
||||
}
|
||||
|
||||
const currentUser = ref<User | null>(null);
|
||||
@@ -112,6 +113,20 @@ async function logout(): Promise<void> {
|
||||
currentUser.value = null;
|
||||
}
|
||||
|
||||
async function saveAccentColor(accentColor: string): Promise<void> {
|
||||
const userId = currentUser.value?.id;
|
||||
const res = await fetch('/api/session/preferences', {
|
||||
method: 'PUT', credentials: 'same-origin',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ accentColor }),
|
||||
});
|
||||
if (!res.ok) throw new Error('主题色保存失败,请稍后重试。');
|
||||
const saved = await res.json();
|
||||
if (currentUser.value?.id === userId && currentUser.value) {
|
||||
currentUser.value = { ...currentUser.value, accentColor: saved.accentColor };
|
||||
}
|
||||
}
|
||||
|
||||
function can(cap: string): boolean {
|
||||
const u = currentUser.value;
|
||||
return !!u && (u.role === "admin" || (u.capabilities ?? []).includes(cap));
|
||||
@@ -143,6 +158,7 @@ export function useSession() {
|
||||
logout,
|
||||
setup,
|
||||
continueAsGuest,
|
||||
saveAccentColor,
|
||||
can,
|
||||
guestCan,
|
||||
canControlBot,
|
||||
|
||||
@@ -5,7 +5,9 @@ import router from './router/index.js';
|
||||
import { installApiClient } from './api/http.js';
|
||||
import './styles/global.scss';
|
||||
import './styles/mobile.scss';
|
||||
import { applyDocumentTheme, readThemePreference, resolveTheme } from './styles/theme.js';
|
||||
|
||||
applyDocumentTheme(resolveTheme(readThemePreference()));
|
||||
installApiClient();
|
||||
|
||||
const app = createApp(App);
|
||||
|
||||
@@ -60,8 +60,8 @@ router.beforeEach(async (to) => {
|
||||
return { name: 'login', query: { next: to.fullPath } };
|
||||
}
|
||||
|
||||
// Guests may never reach settings/setup, even by typing the URL.
|
||||
const GUEST_BLOCKED = new Set(['settings', 'setup']);
|
||||
// Guests can customize appearance; server configuration remains inaccessible.
|
||||
const GUEST_BLOCKED = new Set(['setup']);
|
||||
if (session.isGuest.value && GUEST_BLOCKED.has(to.name as string)) {
|
||||
return { name: 'home' };
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { describe, it, expect, vi, afterEach } from "vitest";
|
||||
import { interpolateElapsed, type TimingState } from "./player.js";
|
||||
import { describe, it, expect, vi, afterEach, beforeEach } from "vitest";
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
import axios from "axios";
|
||||
import { interpolateElapsed, usePlayerStore, type Song, type TimingState } from "./player.js";
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
@@ -42,3 +44,81 @@ describe("interpolateElapsed", () => {
|
||||
expect(interpolateElapsed(t, false, 180)).toBe(180);
|
||||
});
|
||||
});
|
||||
|
||||
const track: Song = { id: "song", name: "song", artist: "", album: "", coverUrl: "", duration: 180, platform: "netease" };
|
||||
|
||||
describe("playback request timing", () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal("window", { matchMedia: () => ({ matches: false }) });
|
||||
vi.useFakeTimers();
|
||||
setActivePinia(createPinia());
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.clearAllTimers();
|
||||
vi.useRealTimers();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it.each(["playSong", "playPlaylist", "playAlbum", "playArtist", "next", "playAtIndex", "startFm"] as const)(
|
||||
"keeps the current clock when %s fails",
|
||||
async (action) => {
|
||||
const store = usePlayerStore();
|
||||
store.activeBotId = "a";
|
||||
const current = timing({ serverElapsed: 63, serverSyncTime: 10_000, wasPlaying: true });
|
||||
store.timings.a = current;
|
||||
vi.spyOn(axios, "post").mockResolvedValue({ data: { ok: false, message: "播放失败" } });
|
||||
|
||||
if (action === "playSong") await store.playSong(track);
|
||||
else if (action === "startFm") await store.startFm();
|
||||
else if (action === "next") await store.next();
|
||||
else if (action === "playAtIndex") await store.playAtIndex(1);
|
||||
else await store[action]("collection");
|
||||
|
||||
expect(store.timings.a).toEqual(current);
|
||||
expect(store.notification?.type).toBe("error");
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps an in-flight elapsed response attached to its original bot", async () => {
|
||||
const store = usePlayerStore();
|
||||
const status = {
|
||||
name: "bot", connected: true, playing: true, paused: false, currentSong: track,
|
||||
queueSize: 1, volume: 50, playMode: "sequential",
|
||||
};
|
||||
store.bots = [{ ...status, id: "a" }, { ...status, id: "b" }];
|
||||
store.activeBotId = "a";
|
||||
store.timings.b = timing({ serverElapsed: 10 });
|
||||
let sendElapsed!: (response: { data: { elapsed: number } }) => void;
|
||||
const response = new Promise<{ data: { elapsed: number } }>(resolve => { sendElapsed = resolve; });
|
||||
vi.spyOn(axios, "get").mockReturnValue(response);
|
||||
|
||||
const syncing = store.syncElapsed();
|
||||
store.activeBotId = "b";
|
||||
sendElapsed({ data: { elapsed: 58 } });
|
||||
await syncing;
|
||||
|
||||
expect(store.timings.a?.serverElapsed).toBe(58);
|
||||
expect(store.timings.b?.serverElapsed).toBe(10);
|
||||
});
|
||||
|
||||
it("freezes steady elapsed samples and interpolates again when audio advances", async () => {
|
||||
const store = usePlayerStore();
|
||||
store.activeBotId = "a";
|
||||
store.bots = [{
|
||||
id: "a", name: "bot", connected: true, playing: true, paused: false, currentSong: track,
|
||||
queueSize: 1, volume: 50, playMode: "sequential",
|
||||
}];
|
||||
const poll = vi.spyOn(axios, "get").mockResolvedValue({ data: { elapsed: 60 } });
|
||||
vi.setSystemTime(10000);
|
||||
await store.syncElapsed();
|
||||
vi.setSystemTime(13000);
|
||||
await store.syncElapsed();
|
||||
vi.setSystemTime(14000);
|
||||
expect(store.liveElapsed()).toBe(60);
|
||||
|
||||
poll.mockResolvedValue({ data: { elapsed: 61 } });
|
||||
await store.syncElapsed();
|
||||
vi.setSystemTime(15000);
|
||||
expect(store.liveElapsed()).toBe(62);
|
||||
});
|
||||
});
|
||||
+90
-51
@@ -2,6 +2,8 @@ import { defineStore } from 'pinia';
|
||||
import axios from 'axios';
|
||||
import { resolveScopedBot } from './scope.js';
|
||||
import { useSession } from '../composables/useSession.js';
|
||||
import { DEFAULT_ACCENT, normalizeAccent, readGuestAccent, saveGuestAccent } from '../styles/accent.js';
|
||||
import { applyDocumentTheme, observeSystemTheme, readThemePreference, resolveTheme, type ThemePreference } from '../styles/theme.js';
|
||||
|
||||
export interface Song {
|
||||
id: string;
|
||||
@@ -80,6 +82,7 @@ export interface TimingState {
|
||||
serverElapsed: number;
|
||||
serverSyncTime: number;
|
||||
wasPlaying: boolean;
|
||||
lastPolledElapsed?: number;
|
||||
}
|
||||
|
||||
const HOME_CACHE_TTL = 5 * 60 * 1000;
|
||||
@@ -126,7 +129,9 @@ export const usePlayerStore = defineStore('player', {
|
||||
queues: {} as Record<string, Song[]>,
|
||||
/** Per-bot timing state keyed by botId */
|
||||
timings: {} as Record<string, TimingState>,
|
||||
theme: 'dark' as 'dark' | 'light',
|
||||
themePreference: readThemePreference(),
|
||||
theme: resolveTheme(readThemePreference()),
|
||||
accentColor: DEFAULT_ACCENT,
|
||||
|
||||
// Which sources the server has enabled (GET /api/music/providers) and the
|
||||
// configured default. Empty until fetched — sections stay hidden briefly.
|
||||
@@ -308,6 +313,7 @@ export const usePlayerStore = defineStore('player', {
|
||||
serverElapsed: status.elapsed,
|
||||
serverSyncTime: Date.now(),
|
||||
wasPlaying: status.playing && !status.paused,
|
||||
lastPolledElapsed: undefined,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -317,6 +323,7 @@ export const usePlayerStore = defineStore('player', {
|
||||
serverElapsed: status.elapsed ?? 0,
|
||||
serverSyncTime: Date.now(),
|
||||
wasPlaying: status.playing && !status.paused,
|
||||
lastPolledElapsed: undefined,
|
||||
});
|
||||
}
|
||||
},
|
||||
@@ -336,14 +343,39 @@ export const usePlayerStore = defineStore('player', {
|
||||
this.queues[botId] = queue;
|
||||
},
|
||||
|
||||
toggleTheme() {
|
||||
this.theme = this.theme === 'dark' ? 'light' : 'dark';
|
||||
localStorage.setItem('theme', this.theme);
|
||||
setThemePreference(preference: ThemePreference) {
|
||||
this.themePreference = preference;
|
||||
try { localStorage.setItem('theme', preference); } catch { /* Keep the selection for this session if storage is unavailable. */ }
|
||||
this.theme = resolveTheme(preference);
|
||||
applyDocumentTheme(this.theme);
|
||||
},
|
||||
|
||||
loadTheme() {
|
||||
const saved = localStorage.getItem('theme') as 'dark' | 'light' | null;
|
||||
if (saved) this.theme = saved;
|
||||
this.themePreference = readThemePreference();
|
||||
this.theme = resolveTheme(this.themePreference);
|
||||
applyDocumentTheme(this.theme);
|
||||
return observeSystemTheme((dark) => {
|
||||
if (this.themePreference !== 'system') return;
|
||||
this.theme = resolveTheme('system', dark);
|
||||
applyDocumentTheme(this.theme);
|
||||
});
|
||||
},
|
||||
|
||||
setAccentColor(value: string) {
|
||||
const color = normalizeAccent(value);
|
||||
if (!color) return;
|
||||
this.accentColor = color;
|
||||
},
|
||||
|
||||
saveGuestAccentColor() {
|
||||
saveGuestAccent(this.accentColor);
|
||||
},
|
||||
|
||||
loadAccentColor(value?: string | null) {
|
||||
const session = useSession();
|
||||
this.accentColor = !session.currentUser.value || session.isGuest.value
|
||||
? readGuestAccent()
|
||||
: normalizeAccent(value ?? '') ?? DEFAULT_ACCENT;
|
||||
},
|
||||
|
||||
async startBotInstance(id: string) {
|
||||
@@ -367,20 +399,28 @@ export const usePlayerStore = defineStore('player', {
|
||||
serverElapsed: bot.elapsed,
|
||||
serverSyncTime: Date.now(),
|
||||
wasPlaying: bot.playing && !bot.paused,
|
||||
lastPolledElapsed: undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/** Poll server for real elapsed time for active bot */
|
||||
async syncElapsed() {
|
||||
if (!this.activeBotId || !this.isPlaying) return;
|
||||
/** Poll the same bot for authoritative elapsed time. */
|
||||
async syncElapsed(botId?: string) {
|
||||
botId ??= this.activeBotId ?? undefined;
|
||||
if (!botId || !this.bots.some(bot => bot.id === botId && bot.playing && !bot.paused)) return;
|
||||
const timing = this.timings[botId];
|
||||
try {
|
||||
const res = await axios.get(`/api/player/${this.activeBotId}/elapsed`);
|
||||
this._setTiming(this.activeBotId, {
|
||||
serverElapsed: res.data.elapsed,
|
||||
const res = await axios.get(`/api/player/${botId}/elapsed`);
|
||||
// A newer WebSocket update or poll supersedes this result.
|
||||
if (this.timings[botId] !== timing) return;
|
||||
const elapsed = res.data.elapsed;
|
||||
if (!Number.isFinite(elapsed)) return;
|
||||
this._setTiming(botId, {
|
||||
serverElapsed: elapsed,
|
||||
serverSyncTime: Date.now(),
|
||||
wasPlaying: true,
|
||||
wasPlaying: timing?.lastPolledElapsed !== elapsed,
|
||||
lastPolledElapsed: elapsed,
|
||||
});
|
||||
} catch {
|
||||
// ignore
|
||||
@@ -388,13 +428,7 @@ export const usePlayerStore = defineStore('player', {
|
||||
},
|
||||
|
||||
async fetchQueue() {
|
||||
if (!this.activeBotId) return;
|
||||
try {
|
||||
const res = await axios.get(`/api/player/${this.activeBotId}/queue`);
|
||||
this.queues[this.activeBotId] = res.data.queue ?? [];
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
if (this.activeBotId) await this.fetchQueueForBot(this.activeBotId);
|
||||
},
|
||||
|
||||
async fetchQueueForBot(botId: string) {
|
||||
@@ -417,10 +451,11 @@ export const usePlayerStore = defineStore('player', {
|
||||
},
|
||||
|
||||
async playAtIndex(index: number) {
|
||||
if (!this.activeBotId) return;
|
||||
await axios.post(`/api/player/${this.activeBotId}/play-at`, { index });
|
||||
this._setTiming(this.activeBotId, { serverElapsed: 0 });
|
||||
this._syncAfterAction();
|
||||
const botId = this.activeBotId;
|
||||
if (!botId) return;
|
||||
const res = await axios.post(`/api/player/${botId}/play-at`, { index });
|
||||
if (res.data?.ok === false && res.data?.message) this.notify(res.data.message, 'error');
|
||||
if (res.data?.ok === true) void this.syncElapsed(botId);
|
||||
},
|
||||
|
||||
async play(query: string, platform = 'netease') {
|
||||
@@ -504,7 +539,8 @@ export const usePlayerStore = defineStore('player', {
|
||||
},
|
||||
|
||||
async playSong(song: Song, skipPartCheck = false) {
|
||||
if (!this.activeBotId) return;
|
||||
const botId = this.activeBotId;
|
||||
if (!botId) return;
|
||||
if (!skipPartCheck && song.platform === 'bilibili' && !song.id.includes('?p=')) {
|
||||
const handled = await this.checkBilibiliMultiPart(song, 'play');
|
||||
if (handled) return;
|
||||
@@ -512,12 +548,11 @@ export const usePlayerStore = defineStore('player', {
|
||||
// Guests use the non-destructive "play now" (insert-next + skip) so they
|
||||
// can't wipe everyone else's queue; members/admins keep the normal behavior.
|
||||
const endpoint = useSession().isGuest.value ? 'play-now-song' : 'play-song';
|
||||
const res = await axios.post(`/api/player/${this.activeBotId}/${endpoint}`, { song });
|
||||
const res = await axios.post(`/api/player/${botId}/${endpoint}`, { song });
|
||||
if (res.data?.ok === false && res.data?.message) {
|
||||
this.notify(res.data.message, 'error');
|
||||
}
|
||||
this._setTiming(this.activeBotId, { serverElapsed: 0 });
|
||||
this._syncAfterAction();
|
||||
if (res.data?.ok === true) void this.syncElapsed(botId);
|
||||
},
|
||||
|
||||
async playNextSong(song: Song, skipPartCheck = false) {
|
||||
@@ -550,18 +585,19 @@ export const usePlayerStore = defineStore('player', {
|
||||
const handled = await this.checkBilibiliMultiPart(song, 'add');
|
||||
if (handled) return;
|
||||
}
|
||||
await axios.post(`/api/player/${this.activeBotId}/add-song`, { song });
|
||||
const res = await axios.post(`/api/player/${this.activeBotId}/add-song`, { song });
|
||||
if (res.data?.ok === false && res.data?.message) this.notify(res.data.message, 'error');
|
||||
},
|
||||
|
||||
async playPlaylist(playlistId: string, platform = 'netease') {
|
||||
if (!this.activeBotId) return;
|
||||
const botId = this.activeBotId;
|
||||
if (!botId) return;
|
||||
try {
|
||||
const res = await axios.post(`/api/player/${this.activeBotId}/play-playlist`, { playlistId, platform });
|
||||
const res = await axios.post(`/api/player/${botId}/play-playlist`, { playlistId, platform });
|
||||
if (res.data?.message) {
|
||||
this.notify(res.data.message, res.data.ok === false ? 'error' : 'info');
|
||||
}
|
||||
this._setTiming(this.activeBotId, { serverElapsed: 0 });
|
||||
this._syncAfterAction();
|
||||
if (res.data?.ok === true) void this.syncElapsed(botId);
|
||||
} catch (e: any) {
|
||||
// A 403 here means a guest lacks the "play entire collection" permission
|
||||
// (issue #103) — surface it instead of failing silently.
|
||||
@@ -570,14 +606,14 @@ export const usePlayerStore = defineStore('player', {
|
||||
},
|
||||
|
||||
async playAlbum(albumId: string, platform = 'netease') {
|
||||
if (!this.activeBotId) return;
|
||||
const botId = this.activeBotId;
|
||||
if (!botId) return;
|
||||
try {
|
||||
const res = await axios.post(`/api/player/${this.activeBotId}/play-album`, { albumId, platform });
|
||||
const res = await axios.post(`/api/player/${botId}/play-album`, { albumId, platform });
|
||||
if (res.data?.message) {
|
||||
this.notify(res.data.message, res.data.ok === false ? 'error' : 'info');
|
||||
}
|
||||
this._setTiming(this.activeBotId, { serverElapsed: 0 });
|
||||
this._syncAfterAction();
|
||||
if (res.data?.ok === true) void this.syncElapsed(botId);
|
||||
} catch (e: any) {
|
||||
this.notify(e?.response?.status === 403 ? '没有权限播放整个专辑' : '播放专辑失败', 'error');
|
||||
}
|
||||
@@ -589,18 +625,18 @@ export const usePlayerStore = defineStore('player', {
|
||||
* trips, so the caller gets a "loading" notice first.
|
||||
*/
|
||||
async playArtist(artistId: string, platform = 'netease') {
|
||||
if (!this.activeBotId) return;
|
||||
const botId = this.activeBotId;
|
||||
if (!botId) return;
|
||||
this.notify('正在载入该歌手的全部歌曲…', 'info');
|
||||
try {
|
||||
const res = await axios.post(
|
||||
`/api/player/${this.activeBotId}/play-artist`,
|
||||
`/api/player/${botId}/play-artist`,
|
||||
{ artistId, platform },
|
||||
);
|
||||
if (res.data?.message) {
|
||||
this.notify(res.data.message, res.data.ok === false ? 'error' : 'info');
|
||||
}
|
||||
this._setTiming(this.activeBotId, { serverElapsed: 0 });
|
||||
this._syncAfterAction();
|
||||
if (res.data?.ok === true) void this.syncElapsed(botId);
|
||||
} catch (e: any) {
|
||||
const status = e?.response?.status;
|
||||
this.notify(
|
||||
@@ -636,10 +672,11 @@ export const usePlayerStore = defineStore('player', {
|
||||
},
|
||||
|
||||
async next() {
|
||||
if (!this.activeBotId) return;
|
||||
await axios.post(`/api/player/${this.activeBotId}/next`);
|
||||
this._setTiming(this.activeBotId, { serverElapsed: 0 });
|
||||
this._syncAfterAction();
|
||||
const botId = this.activeBotId;
|
||||
if (!botId) return;
|
||||
const res = await axios.post(`/api/player/${botId}/next`);
|
||||
if (res.data?.ok === false && res.data?.message) this.notify(res.data.message, 'error');
|
||||
if (res.data?.ok === true) void this.syncElapsed(botId);
|
||||
},
|
||||
|
||||
async prev() {
|
||||
@@ -681,14 +718,16 @@ export const usePlayerStore = defineStore('player', {
|
||||
},
|
||||
|
||||
async startFm(platform: Source = 'netease') {
|
||||
if (!this.activeBotId) return;
|
||||
const res = await axios.post(`/api/player/${this.activeBotId}/fm`, { platform });
|
||||
if (res.data?.message) {
|
||||
const botId = this.activeBotId;
|
||||
if (!botId) return;
|
||||
const res = await axios.post(`/api/player/${botId}/fm`, { platform });
|
||||
if (this.activeBotId === botId && res.data?.message) {
|
||||
this.notify(res.data.message, res.data.ok === false ? 'error' : 'info');
|
||||
}
|
||||
this._setTiming(this.activeBotId, { serverElapsed: 0 });
|
||||
this._syncAfterAction();
|
||||
this.fetchQueue();
|
||||
if (res.data?.ok === true) {
|
||||
void this.syncElapsed(botId);
|
||||
void this.fetchQueueForBot(botId);
|
||||
}
|
||||
},
|
||||
|
||||
async fetchFavorites() {
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, it, vi, afterEach } from 'vitest';
|
||||
import { accentTokens, DEFAULT_ACCENT, normalizeAccent, readGuestAccent, saveGuestAccent } from './accent.js';
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
describe('accent preferences', () => {
|
||||
it('normalizes hex values and rejects invalid saved input', () => {
|
||||
expect(normalizeAccent(' #AbC ')).toBe('#aabbcc');
|
||||
expect(normalizeAccent('#8B5CF6')).toBe('#8b5cf6');
|
||||
expect(normalizeAccent('url(example)')).toBeNull();
|
||||
expect(accentTokens('invalid')['--color-primary']).toBe(DEFAULT_ACCENT);
|
||||
});
|
||||
|
||||
it('keeps button text readable for light and dark custom colors', () => {
|
||||
expect(accentTokens('#ffffff')['--color-on-primary']).toBe('#000000');
|
||||
expect(accentTokens('#000000')['--color-on-primary']).toBe('#ffffff');
|
||||
expect(accentTokens('#8b5cf6')['--color-primary-12']).toBe('rgba(139, 92, 246, 0.12)');
|
||||
});
|
||||
|
||||
it('restores guest colors from a cookie and scopes persistence to the site', () => {
|
||||
const doc = { cookie: 'other=value; tsmb_accent=#8b5cf6' };
|
||||
vi.stubGlobal('document', doc);
|
||||
vi.stubGlobal('location', { protocol: 'https:' });
|
||||
expect(readGuestAccent()).toBe('#8b5cf6');
|
||||
saveGuestAccent('#0891b2');
|
||||
expect(doc.cookie).toBe('tsmb_accent=#0891b2; Path=/; Max-Age=31536000; SameSite=Lax; Secure');
|
||||
doc.cookie = 'tsmb_accent=invalid';
|
||||
expect(readGuestAccent()).toBe(DEFAULT_ACCENT);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
export const DEFAULT_ACCENT = '#335eea';
|
||||
export const ACCENT_COOKIE = 'tsmb_accent';
|
||||
|
||||
export function readGuestAccent(): string {
|
||||
const value = document.cookie.split(';').map((part) => part.trim()).find((part) => part.startsWith(`${ACCENT_COOKIE}=`));
|
||||
return normalizeAccent(value?.slice(ACCENT_COOKIE.length + 1) ?? '') ?? DEFAULT_ACCENT;
|
||||
}
|
||||
|
||||
export function saveGuestAccent(color: string): void {
|
||||
const secure = location.protocol === 'https:' ? '; Secure' : '';
|
||||
document.cookie = `${ACCENT_COOKIE}=${color}; Path=/; Max-Age=31536000; SameSite=Lax${secure}`;
|
||||
}
|
||||
|
||||
export const ACCENT_PRESETS = [
|
||||
{ name: '经典蓝', color: DEFAULT_ACCENT },
|
||||
{ name: '紫罗兰', color: '#8b5cf6' },
|
||||
{ name: '玫瑰粉', color: '#e8447a' },
|
||||
{ name: '珊瑚橙', color: '#ea580c' },
|
||||
{ name: '翡翠绿', color: '#16a34a' },
|
||||
{ name: '湖水青', color: '#0891b2' },
|
||||
] as const;
|
||||
|
||||
export function normalizeAccent(value: string): string | null {
|
||||
const hex = value.trim().toLowerCase();
|
||||
if (/^#[0-9a-f]{6}$/.test(hex)) return hex;
|
||||
if (/^#[0-9a-f]{3}$/.test(hex)) return '#' + [...hex.slice(1)].map((c) => c + c).join('');
|
||||
return null;
|
||||
}
|
||||
|
||||
export function accentTokens(value: string): Record<string, string> {
|
||||
const color = normalizeAccent(value) ?? DEFAULT_ACCENT;
|
||||
const rgb = [1, 3, 5].map((offset) => parseInt(color.slice(offset, offset + 2), 16));
|
||||
const linear = rgb.map((channel) => {
|
||||
const srgb = channel / 255;
|
||||
return srgb <= 0.04045 ? srgb / 12.92 : ((srgb + 0.055) / 1.055) ** 2.4;
|
||||
});
|
||||
const luminance = linear[0] * 0.2126 + linear[1] * 0.7152 + linear[2] * 0.0722;
|
||||
const onAccent = luminance > 0.179 ? '#000000' : '#ffffff';
|
||||
const tint = (amount: number) => '#' + rgb.map((channel) =>
|
||||
Math.round(channel + (255 - channel) * amount).toString(16).padStart(2, '0'),
|
||||
).join('');
|
||||
return {
|
||||
'--color-primary': color,
|
||||
'--color-on-primary': onAccent,
|
||||
'--color-primary-bg': tint(0.9),
|
||||
'--color-primary-10': `rgba(${rgb.join(', ')}, 0.10)`,
|
||||
'--color-primary-12': `rgba(${rgb.join(', ')}, 0.12)`,
|
||||
'--color-primary-15': `rgba(${rgb.join(', ')}, 0.15)`,
|
||||
'--gradient-fm': `linear-gradient(135deg, ${color}, ${color === DEFAULT_ACCENT ? '#6366f1' : tint(0.2)})`,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { observeSystemTheme, readThemePreference, resolveTheme } from './theme.js';
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
describe('theme preferences', () => {
|
||||
it('defaults to system and preserves existing explicit choices', () => {
|
||||
for (const [saved, expected] of [[null, 'system'], ['invalid', 'system'], ['system', 'system'], ['dark', 'dark'], ['light', 'light']]) {
|
||||
vi.stubGlobal('localStorage', { getItem: () => saved });
|
||||
expect(readThemePreference()).toBe(expected);
|
||||
}
|
||||
vi.stubGlobal('localStorage', { getItem: () => { throw new Error('blocked'); } });
|
||||
expect(readThemePreference()).toBe('system');
|
||||
});
|
||||
it('follows the browser preference while keeping manual overrides', () => {
|
||||
expect(resolveTheme('system', true)).toBe('dark');
|
||||
expect(resolveTheme('system', false)).toBe('light');
|
||||
expect(resolveTheme('light', true)).toBe('light');
|
||||
expect(resolveTheme('dark', false)).toBe('dark');
|
||||
});
|
||||
it('receives live system changes and removes its listener on cleanup', () => {
|
||||
const media = new EventTarget();
|
||||
const matchMedia = vi.fn(() => media);
|
||||
vi.stubGlobal('window', { matchMedia });
|
||||
const onChange = vi.fn();
|
||||
const stop = observeSystemTheme(onChange);
|
||||
expect(matchMedia).toHaveBeenCalledWith('(prefers-color-scheme: dark)');
|
||||
media.dispatchEvent(Object.assign(new Event('change'), { matches: true }));
|
||||
media.dispatchEvent(Object.assign(new Event('change'), { matches: false }));
|
||||
expect(onChange.mock.calls).toEqual([[true], [false]]);
|
||||
stop();
|
||||
media.dispatchEvent(Object.assign(new Event('change'), { matches: true }));
|
||||
expect(onChange).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
export type Theme = 'dark' | 'light';
|
||||
export type ThemePreference = Theme | 'system';
|
||||
|
||||
export function readThemePreference(): ThemePreference {
|
||||
try {
|
||||
const saved = localStorage.getItem('theme');
|
||||
return saved === 'dark' || saved === 'light' ? saved : 'system';
|
||||
} catch {
|
||||
return 'system';
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveTheme(preference: ThemePreference, systemDark = window.matchMedia('(prefers-color-scheme: dark)').matches): Theme {
|
||||
return preference === 'system' ? (systemDark ? 'dark' : 'light') : preference;
|
||||
}
|
||||
|
||||
export function applyDocumentTheme(theme: Theme) {
|
||||
document.documentElement.dataset.theme = theme;
|
||||
document.documentElement.style.colorScheme = theme;
|
||||
document.querySelector('meta[name="theme-color"]')?.setAttribute('content', theme === 'dark' ? '#222222' : '#ffffff');
|
||||
}
|
||||
|
||||
export function observeSystemTheme(onChange: (dark: boolean) => void) {
|
||||
const media = window.matchMedia('(prefers-color-scheme: dark)');
|
||||
const listener = (event: MediaQueryListEvent) => onChange(event.matches);
|
||||
media.addEventListener('change', listener);
|
||||
return () => media.removeEventListener('change', listener);
|
||||
}
|
||||
@@ -59,6 +59,7 @@
|
||||
|
||||
// Accent
|
||||
--color-primary: #335eea;
|
||||
--color-on-primary: #ffffff;
|
||||
--color-primary-bg: #eaeffd;
|
||||
--color-primary-15: rgba(51, 94, 234, 0.15);
|
||||
--color-primary-10: rgba(51, 94, 234, 0.10);
|
||||
|
||||
@@ -322,7 +322,7 @@ watch(() => `${route.params.id}|${route.query.platform ?? ''}`, loadArtist);
|
||||
|
||||
.play-all-btn {
|
||||
background: var(--color-primary);
|
||||
color: white;
|
||||
color: var(--color-on-primary);
|
||||
&:not(:disabled):hover { transform: scale(1.04); }
|
||||
&:not(:disabled):active { transform: scale(0.96); }
|
||||
}
|
||||
|
||||
@@ -68,7 +68,7 @@ async function submit() {
|
||||
}
|
||||
.auth-card button {
|
||||
height: 38px; border-radius: var(--radius-sm); border: 0;
|
||||
background: var(--color-primary); color: #fff; font-weight: 500; cursor: pointer;
|
||||
background: var(--color-primary); color: var(--color-on-primary); font-weight: 500; cursor: pointer;
|
||||
}
|
||||
.auth-card button:disabled { opacity: 0.6; cursor: progress; }
|
||||
.auth-error { color: #e26a6a; font-size: 13px; margin: 0; }
|
||||
|
||||
+210
-25
@@ -6,56 +6,169 @@
|
||||
</button>
|
||||
<h1 class="page-title">播放历史</h1>
|
||||
|
||||
<p v-if="error" class="history-error" role="alert">{{ error }}</p>
|
||||
<div v-if="loading" class="loading">加载中...</div>
|
||||
|
||||
<div v-else-if="history.length === 0" class="empty">
|
||||
暂无播放记录
|
||||
</div>
|
||||
|
||||
<div v-else class="history-list">
|
||||
<SongCard
|
||||
v-for="(song, i) in history"
|
||||
:key="`${song.id}-${i}`"
|
||||
:song="song"
|
||||
:index="i + 1"
|
||||
:active="store.currentSong?.id === song.id"
|
||||
@play="store.playSong(song)"
|
||||
@playNext="store.playNextSong(song)"
|
||||
@add="store.addSong(song)"
|
||||
/>
|
||||
</div>
|
||||
<template v-else>
|
||||
<div v-if="canDelete" class="toolbar">
|
||||
<label class="select-all">
|
||||
<input type="checkbox" :checked="allSelected" :disabled="deleting" @change="toggleAll" />
|
||||
全选
|
||||
</label>
|
||||
<span class="spacer" />
|
||||
<button class="tool-btn" :disabled="deleting || selected.size === 0" @click="deleteSelected">
|
||||
<Icon icon="mdi:delete-outline" />
|
||||
删除选中{{ selected.size ? `(${selected.size})` : '' }}
|
||||
</button>
|
||||
<button class="tool-btn danger" :disabled="deleting" @click="clearAll">
|
||||
<Icon icon="mdi:delete-sweep-outline" />
|
||||
清空全部
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="history-list">
|
||||
<div
|
||||
v-for="(song, i) in history"
|
||||
:key="song.rowId"
|
||||
class="history-row"
|
||||
:class="{ selected: selected.has(song.rowId) }"
|
||||
>
|
||||
<input
|
||||
v-if="canDelete"
|
||||
type="checkbox"
|
||||
class="row-check"
|
||||
:aria-label="`选择 ${song.name}`"
|
||||
:checked="selected.has(song.rowId)"
|
||||
:disabled="deleting"
|
||||
@change="toggle(song.rowId)"
|
||||
/>
|
||||
<SongCard
|
||||
class="row-card"
|
||||
:song="song"
|
||||
:index="i + 1"
|
||||
:active="store.currentSong?.id === song.id"
|
||||
@play="store.playSong(song)"
|
||||
@playNext="store.playNextSong(song)"
|
||||
@add="store.addSong(song)"
|
||||
/>
|
||||
<button
|
||||
v-if="canDelete"
|
||||
class="row-del"
|
||||
title="删除这条记录"
|
||||
:aria-label="`删除 ${song.name} 的播放记录`"
|
||||
:disabled="deleting"
|
||||
@click.stop="deleteHistory([song.rowId])"
|
||||
>
|
||||
<Icon icon="mdi:close" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue';
|
||||
import { ref, computed, onMounted, watch } from 'vue';
|
||||
import { Icon } from '@iconify/vue';
|
||||
import axios from 'axios';
|
||||
import { usePlayerStore } from '../stores/player.js';
|
||||
import { useSession } from '../composables/useSession.js';
|
||||
import SongCard from '../components/SongCard.vue';
|
||||
|
||||
const store = usePlayerStore();
|
||||
const { can, guestCan } = useSession();
|
||||
|
||||
import { Song } from '../stores/player.js';
|
||||
|
||||
const history = ref<Song[]>([]);
|
||||
/** History rows carry their DB primary key (`rowId`) so a single record can be removed. */
|
||||
type HistorySong = Song & { rowId: number };
|
||||
|
||||
const history = ref<HistorySong[]>([]);
|
||||
const loading = ref(true);
|
||||
const deleting = ref(false);
|
||||
const error = ref('');
|
||||
const selected = ref(new Set<number>());
|
||||
const canDelete = computed(() => can('player.queue') || guestCan('removeClear'));
|
||||
let historyVersion = 0;
|
||||
|
||||
const allSelected = computed(
|
||||
() => history.value.length > 0 && selected.value.size === history.value.length
|
||||
);
|
||||
|
||||
function toggle(rowId: number) {
|
||||
const next = new Set(selected.value);
|
||||
if (next.has(rowId)) next.delete(rowId);
|
||||
else next.add(rowId);
|
||||
selected.value = next;
|
||||
}
|
||||
|
||||
function toggleAll() {
|
||||
selected.value = allSelected.value
|
||||
? new Set<number>()
|
||||
: new Set(history.value.map((s) => s.rowId));
|
||||
}
|
||||
|
||||
async function deleteHistory(ids: number[] | null) {
|
||||
const botId = store.activeBotId;
|
||||
if (!botId || !canDelete.value || deleting.value) return;
|
||||
const version = historyVersion;
|
||||
const url = `/api/player/${encodeURIComponent(botId)}/history`;
|
||||
deleting.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
if (ids?.length === 1) {
|
||||
await axios.delete(`${url}/${ids[0]}`);
|
||||
} else {
|
||||
await axios.delete(url, { data: ids ? { ids } : { all: true } });
|
||||
}
|
||||
if (version !== historyVersion) return;
|
||||
const removed = new Set(ids);
|
||||
history.value = ids ? history.value.filter((song) => !removed.has(song.rowId)) : [];
|
||||
selected.value = ids ? new Set([...selected.value].filter((id) => !removed.has(id))) : new Set();
|
||||
} catch {
|
||||
if (version === historyVersion) error.value = '删除播放记录失败,请重试。';
|
||||
} finally {
|
||||
if (version === historyVersion) deleting.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function deleteSelected() {
|
||||
if (selected.value.size) void deleteHistory([...selected.value]);
|
||||
}
|
||||
|
||||
function clearAll() {
|
||||
if (window.confirm('确定清空全部播放历史吗?此操作不可恢复。')) void deleteHistory(null);
|
||||
}
|
||||
|
||||
watch(() => store.activeBotId, async (botId, _previous, onCleanup) => {
|
||||
historyVersion++;
|
||||
history.value = [];
|
||||
selected.value = new Set();
|
||||
deleting.value = false;
|
||||
error.value = '';
|
||||
loading.value = !!botId;
|
||||
if (!botId) return;
|
||||
|
||||
const controller = new AbortController();
|
||||
onCleanup(() => controller.abort());
|
||||
try {
|
||||
const { data } = await axios.get(`/api/player/${encodeURIComponent(botId)}/history`, { signal: controller.signal });
|
||||
if (!controller.signal.aborted) history.value = data.history;
|
||||
} catch {
|
||||
if (!controller.signal.aborted) error.value = '加载播放历史失败。';
|
||||
} finally {
|
||||
if (!controller.signal.aborted) loading.value = false;
|
||||
}
|
||||
}, { immediate: true, flush: 'sync' });
|
||||
|
||||
onMounted(async () => {
|
||||
if (!store.activeBotId) {
|
||||
await store.fetchBots();
|
||||
}
|
||||
|
||||
if (store.activeBotId) {
|
||||
try {
|
||||
const res = await axios.get(`/api/player/${store.activeBotId}/history`);
|
||||
history.value = res.data.history;
|
||||
} catch {
|
||||
// Ignore if API not ready
|
||||
}
|
||||
}
|
||||
|
||||
loading.value = false;
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -77,12 +190,84 @@ onMounted(async () => {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.history-error {
|
||||
color: var(--text-secondary);
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin-bottom: 12px;
|
||||
|
||||
.spacer { flex: 1; }
|
||||
|
||||
.select-all {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
}
|
||||
|
||||
.tool-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 6px 12px;
|
||||
font-size: 13px;
|
||||
border-radius: var(--radius-md);
|
||||
background: var(--bg-elevated);
|
||||
color: var(--text-secondary);
|
||||
transition: all var(--transition-fast);
|
||||
|
||||
&:hover:not(:disabled) { color: var(--text-primary); }
|
||||
&:disabled { opacity: 0.4; cursor: not-allowed; }
|
||||
|
||||
&.danger:hover:not(:disabled) { color: #f2555a; }
|
||||
}
|
||||
|
||||
.history-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.history-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
border-radius: var(--radius-md);
|
||||
transition: background var(--transition-fast);
|
||||
|
||||
&.selected { background: rgba(51, 94, 234, 0.08); }
|
||||
|
||||
.row-check {
|
||||
flex: none;
|
||||
margin-left: 4px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.row-card { flex: 1; min-width: 0; }
|
||||
|
||||
.row-del {
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 4px;
|
||||
color: var(--text-tertiary);
|
||||
border-radius: var(--radius-sm);
|
||||
transition: all var(--transition-fast);
|
||||
|
||||
&:hover, &:focus-visible { color: #f2555a; }
|
||||
&:disabled { opacity: 0.4; cursor: not-allowed; }
|
||||
}
|
||||
}
|
||||
|
||||
.loading {
|
||||
text-align: center;
|
||||
padding: 60px;
|
||||
|
||||
@@ -455,7 +455,7 @@ onMounted(() => {
|
||||
width: 56px;
|
||||
height: 56px;
|
||||
border-radius: var(--radius-md);
|
||||
background: linear-gradient(135deg, var(--color-primary), #6366f1);
|
||||
background: var(--gradient-fm);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
|
||||
@@ -96,7 +96,7 @@ async function enterAsGuest() {
|
||||
}
|
||||
.auth-card button {
|
||||
height: 38px; border-radius: var(--radius-sm); border: 0;
|
||||
background: var(--color-primary); color: #fff; font-weight: 500; cursor: pointer;
|
||||
background: var(--color-primary); color: var(--color-on-primary); font-weight: 500; cursor: pointer;
|
||||
}
|
||||
.auth-card button:disabled { opacity: 0.6; cursor: progress; }
|
||||
.auth-error { color: #e26a6a; font-size: 13px; margin: 0; }
|
||||
|
||||
@@ -227,7 +227,7 @@ async function toggleFavorite() {
|
||||
gap: 6px;
|
||||
padding: 10px 28px;
|
||||
background: var(--color-primary);
|
||||
color: white;
|
||||
color: var(--color-on-primary);
|
||||
border-radius: var(--radius-lg);
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
|
||||
Loaded 100 of 104 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user