feat(history): delete single / batch / clear all play history

This commit is contained in:
jiayuLian committed 2026-11-08 03:11:36 +08:00
1 parent 17008ae52e
commit a613d6cac0
4 files changed
+250 -15

No files matched your search

+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[] }` 批量删除或 `{ all: true }` 清空,能力 `player.queue`) |
| GET | `/profile` | ProfileConfig |
| PUT | `/profile` | ProfileConfig(能力 `bot.manage`) |
+24
View File
@@ -130,6 +130,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;
@@ -416,6 +420,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)
@@ -566,6 +574,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,
+50
View File
@@ -805,6 +805,9 @@ export function createPlayerRouter(
const limit = parseInt(req.query.limit as string) || 50;
const records = database.getPlayHistory(req.params.botId, limit);
const history = records.map((r) => ({
// rowId is the history row primary key — needed to delete a single record.
// `id` stays the platform song id so existing players keep working.
rowId: r.id,
id: r.songId,
name: r.songName,
artist: r.artist,
@@ -818,5 +821,52 @@ 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.parseInt(req.params.rowId, 10);
if (!Number.isInteger(rowId) || rowId <= 0) {
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) {
const deleted = database.clearPlayHistory(req.params.botId);
res.json({ deleted });
return;
}
const ids = Array.isArray(body.ids)
? body.ids.filter((v): v is number => Number.isInteger(v) && (v as number) > 0)
: [];
if (ids.length === 0) {
res.status(400).json({ error: "ids[] or all:true required" });
return;
}
// Cap the batch so a hostile payload cannot lock the DB for long.
const deleted = database.deletePlayHistory(req.params.botId, ids.slice(0, 500));
res.json({ deleted });
}
);
return router;
}
+173 -14
View File
@@ -12,23 +12,56 @@
暂无播放记录
</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 class="toolbar">
<label class="select-all">
<input type="checkbox" :checked="allSelected" @change="toggleAll" />
全选
</label>
<span class="spacer" />
<button class="tool-btn" :disabled="selected.size === 0" @click="deleteSelected">
<Icon icon="mdi:delete-outline" />
删除选中{{ selected.size ? `(${selected.size})` : '' }}
</button>
<button class="tool-btn danger" :disabled="history.length === 0" @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
type="checkbox"
class="row-check"
:checked="selected.has(song.rowId)"
@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 class="row-del" title="删除这条记录" @click.stop="deleteOne(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 } from 'vue';
import { Icon } from '@iconify/vue';
import axios from 'axios';
import { usePlayerStore } from '../stores/player.js';
@@ -38,8 +71,65 @@ const store = usePlayerStore();
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 selected = ref(new Set<number>());
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 deleteOne(rowId: number) {
if (!store.activeBotId) return;
try {
await axios.delete(`/api/player/${store.activeBotId}/history/${rowId}`);
history.value = history.value.filter((s) => s.rowId !== rowId);
if (selected.value.has(rowId)) toggle(rowId);
} catch {
// Keep the row when the request fails; the list stays consistent with the server.
}
}
async function deleteSelected() {
if (!store.activeBotId || selected.value.size === 0) return;
const ids = Array.from(selected.value);
try {
await axios.delete(`/api/player/${store.activeBotId}/history`, { data: { ids } });
const drop = new Set(ids);
history.value = history.value.filter((s) => !drop.has(s.rowId));
selected.value = new Set<number>();
} catch {
// Leave the selection in place so the user can retry.
}
}
async function clearAll() {
if (!store.activeBotId) return;
if (!window.confirm('确定清空全部播放历史吗?此操作不可恢复。')) return;
try {
await axios.delete(`/api/player/${store.activeBotId}/history`, { data: { all: true } });
history.value = [];
selected.value = new Set<number>();
} catch {
// No optimistic clear on failure.
}
}
onMounted(async () => {
if (!store.activeBotId) {
@@ -77,12 +167,81 @@ onMounted(async () => {
margin-bottom: 24px;
}
.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;
opacity: 0;
color: var(--text-tertiary);
border-radius: var(--radius-sm);
transition: all var(--transition-fast);
&:hover { color: #f2555a; opacity: 1; }
}
&:hover .row-del { opacity: 1; }
}
.loading {
text-align: center;
padding: 60px;