diff --git a/docs/API.md b/docs/API.md index 3cb9394..ab52993 100644 --- a/docs/API.md +++ b/docs/API.md @@ -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`) | diff --git a/src/data/database.ts b/src/data/database.ts index fc0f6c4..9285685 100644 --- a/src/data/database.ts +++ b/src/data/database.ts @@ -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, diff --git a/src/web/api/play-history.test.ts b/src/web/api/play-history.test.ts new file mode 100644 index 0000000..644a0c5 --- /dev/null +++ b/src/web/api/play-history.test.ts @@ -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[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); + }); +}); diff --git a/src/web/api/player.ts b/src/web/api/player.ts index 487293f..ef6f948 100644 --- a/src/web/api/player.ts +++ b/src/web/api/player.ts @@ -12,6 +12,11 @@ import { supportsPersonalLogin } from "./personal-music.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( @@ -805,6 +810,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 +826,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; } diff --git a/web/src/views/History.vue b/web/src/views/History.vue index a52c0d2..97dcf6d 100644 --- a/web/src/views/History.vue +++ b/web/src/views/History.vue @@ -6,56 +6,169 @@

播放历史

+
加载中...
暂无播放记录
-
- -
+ @@ -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;