Merge main into playback retry

This commit is contained in:
TIANYAO ZHANG committed 2026-11-18 17:02:46 +08:00
commit dc2659628e
6 files changed
+374 -37

No files matched your search

+37 -11
View File
@@ -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` 中,更新不会丢失。
@@ -929,7 +955,7 @@ A:B站搜索需要 buvid3 匿名 Cookie(程序启动时自动获取)。如
A:YouTube 是可选音源,需要手动安装 `yt-dlp`。详见 [可选:YouTube 音源](#可选youtube-音源) 章节。快速验证:在项目根目录执行 `bin/yt-dlp --version`(或系统 `yt-dlp --version`),能打印版本号即可。若 yt-dlp 已安装但仍搜索失败,通常是网络/地域问题或 yt-dlp 版本过旧(执行 `yt-dlp -U` 升级)。
**Q:如何更新到新版本?**
A:`git pull` 拉取最新代码,然后 `npm install && npm run build && npm start` 重新构建启动。Docker 用户执行 `docker-compose up -d --build`。
A:`git pull` 拉取最新代码,然后 `npm install && npm run build && npm start` 重新构建启动。使用预构建镜像的 Docker 用户执行 `docker compose pull && docker compose up -d`,离线导入或本地构建用户按各自的部署步骤升级。
**Q:忘记管理员密码怎么办?**
A:直接操作 SQLite 数据库。最简单的办法是清空 `users` 表然后重新进入 first-run 流程:`sqlite3 data/tsmusicbot.db "DELETE FROM users; DELETE FROM sessions;"`,重启后浏览器会自动跳转 `/first-run` 让你重新创建管理员。详细方法见 [从 WebUI 无鉴权版本升级](#从-webui-无鉴权版本升级重要)。
+3 -1
View File
@@ -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`) |
+24
View File
@@ -179,6 +179,10 @@ 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;
@@ -559,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)
@@ -831,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,
+47
View File
@@ -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);
});
});
+53
View File
@@ -15,6 +15,11 @@ import { resolveProviderForRequest } from "./provider-scope.js";
* 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(
@@ -827,6 +832,9 @@ export function createPlayerRouter(
const limit = parseInt(req.query.limit as string) || 50;
const records = database.getPlayHistory(req.params.botId, limit);
const history = records.map((r) => ({
// rowId is the history row primary key — needed to delete a single record.
// `id` stays the platform song id so existing players keep working.
rowId: r.id,
id: r.songId,
name: r.songName,
artist: r.artist,
@@ -840,5 +848,50 @@ export function createPlayerRouter(
res.json({ history });
});
// Delete one history record: /:botId/history/:rowId
router.delete(
"/:botId/history/:rowId",
authorize({ capability: "player.queue", guestFlag: "removeClear" }),
(req, res) => {
if (!database) {
res.status(404).json({ error: "history unavailable" });
return;
}
const rowId = Number(req.params.rowId);
if (!/^\d+$/.test(req.params.rowId) || !isHistoryRowId(rowId)) {
res.status(400).json({ error: "invalid rowId" });
return;
}
const deleted = database.deletePlayHistory(req.params.botId, [rowId]);
res.json({ deleted });
}
);
// Batch delete / clear all: body { ids: number[] } or { all: true }
router.delete(
"/:botId/history",
authorize({ capability: "player.queue", guestFlag: "removeClear" }),
(req, res) => {
if (!database) {
res.status(404).json({ error: "history unavailable" });
return;
}
const body = (req.body ?? {}) as { ids?: unknown; all?: unknown };
if (body.all === true && body.ids === undefined) {
const deleted = database.clearPlayHistory(req.params.botId);
res.json({ deleted });
return;
}
const { ids } = body;
if (body.all !== undefined || !Array.isArray(ids) || ids.length === 0 ||
ids.length > MAX_HISTORY_DELETE_BATCH || !ids.every(isHistoryRowId)) {
res.status(400).json({ error: "Provide 1 to 500 history IDs or all:true" });
return;
}
const deleted = database.deletePlayHistory(req.params.botId, ids);
res.json({ deleted });
}
);
return router;
}
+210 -25
View File
@@ -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;