dsh-workbench-danmaku 0.0.0-stage → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ityq777
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,27 @@
1
- # Temporary Holding Version
1
+ # dsh-workbench-danmaku
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 个人工作台弹幕插件:把自建弹幕轮播在整个 DSH 界面,并可叠加到整个桌面
4
+
5
+ ## 安装
6
+
7
+ ```sh
8
+ dsh plugin --profile web add dsh-workbench-danmaku
9
+ ```
10
+
11
+ 安装或升级后按 DSH 提示重启/刷新。
12
+
13
+ 桌面透明层依赖 Electron 外壳;弹幕库只存本机,不上传也不参与云同步。
14
+
15
+ ## 兼容性
16
+
17
+ - DSH:`>=0.2.0-rc.1 <0.3.0`
18
+ - Node:`>=22.5`
19
+
20
+ ## 仓库
21
+
22
+ - 源码入口:https://github.com/ityyq777/dsh-workbench
23
+ - 问题反馈:https://github.com/ityyq777/dsh-workbench/issues
24
+
25
+ ## 许可
26
+
27
+ MIT
@@ -0,0 +1,7 @@
1
+ - insert:
2
+ - id: workbench
3
+ name: 'dsh-workbench-host'
4
+ config:
5
+ enabled: true
6
+ - id: workbench-danmaku
7
+ name: 'dsh-workbench-danmaku'
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+
3
+ import { configState, loadConfig, resetConfig, writeConfig } from "../config.js";
4
+
5
+ export function registerConfigActions(api, deps) {
6
+ const db = api.db;
7
+
8
+ api.action("danmaku.configGet", {
9
+ description: "读取弹幕插件配置:分组、全部配置项(含中文说明)、当前值、用户覆盖与告警",
10
+ input: { type: "object", properties: {}, additionalProperties: false },
11
+ execute: () => configState(db),
12
+ render: (r) => `弹幕配置 ${Object.keys(r.values).length} 项,覆盖 ${Object.keys(r.overrides).length} 项`,
13
+ });
14
+
15
+ api.action("danmaku.configSet", {
16
+ description: "写入弹幕配置;值会做类型与范围校验,写入后立即影响调度节奏与显示层",
17
+ input: {
18
+ type: "object",
19
+ properties: {
20
+ values: { type: "object", description: '要写入的配置项,如 {"intervalMs": 1200, "surface": "both"}' },
21
+ },
22
+ required: ["values"],
23
+ additionalProperties: false,
24
+ },
25
+ execute: (args) => {
26
+ const out = writeConfig(db, args.values);
27
+ if (out.changed.length) deps.changed("config", out.changed.join(","));
28
+ return { changed: out.changed, values: out.state.values, overrides: out.state.overrides };
29
+ },
30
+ render: (r) => (r.changed.length ? `已更新配置:${r.changed.join("、")}` : "配置没有变化"),
31
+ });
32
+
33
+ api.action("danmaku.configReset", {
34
+ description: "把弹幕配置恢复默认;不传 ids 时恢复全部配置项",
35
+ input: {
36
+ type: "object",
37
+ properties: {
38
+ ids: { type: "array", items: { type: "string" }, description: "要恢复默认的配置项 id 列表" },
39
+ },
40
+ additionalProperties: false,
41
+ },
42
+ execute: (args) => {
43
+ const state = resetConfig(db, args.ids);
44
+ deps.changed("config-reset", "");
45
+ return { values: state.values, overrides: state.overrides };
46
+ },
47
+ render: () => "弹幕配置已恢复默认",
48
+ });
49
+
50
+ api.action("danmaku.theme", {
51
+ description: "由界面层上报当前 DSH 主题色,桌面透明窗据此换色;不写库",
52
+ input: {
53
+ type: "object",
54
+ properties: {
55
+ colors: {
56
+ type: "object",
57
+ description: "形如 {fg,bg,border,accent,ok,warn,danger,dark} 的 CSS 颜色",
58
+ additionalProperties: true,
59
+ },
60
+ },
61
+ required: ["colors"],
62
+ additionalProperties: false,
63
+ },
64
+ execute: (args) => {
65
+ const colors = args.colors && typeof args.colors === "object" ? args.colors : {};
66
+ deps.desktop.theme(colors);
67
+ return { synced: deps.desktop.status().themeSynced };
68
+ },
69
+ render: (r) => (r.synced ? "桌面主题已同步" : "桌面层尚未启动,主题已缓存"),
70
+ });
71
+
72
+ api.action("danmaku.desktop", {
73
+ description: "桌面弹幕层控制:status 查询状态,restart 重启,stop 本次停止,resume 恢复",
74
+ input: {
75
+ type: "object",
76
+ properties: {
77
+ op: {
78
+ type: "string",
79
+ enum: ["status", "restart", "stop", "resume"],
80
+ description: "操作;默认 status",
81
+ },
82
+ },
83
+ additionalProperties: false,
84
+ },
85
+ execute: (args) => {
86
+ const op = args.op || "status";
87
+ if (op === "restart") deps.desktop.restart();
88
+ else if (op === "stop") deps.desktop.suppress();
89
+ else if (op === "resume") deps.desktop.resume();
90
+ return deps.desktop.status();
91
+ },
92
+ render: (r) => `桌面弹幕:${r.phase}`,
93
+ });
94
+
95
+ api.action("danmaku.status", {
96
+ description: "弹幕运行状态:调度器节奏、下一个播放时间、启用条数与当前显示端",
97
+ input: { type: "object", properties: {}, additionalProperties: false },
98
+ execute: () => {
99
+ const values = loadConfig(db).values;
100
+ return Object.assign({ config: values }, deps.player.status(), { desktop: deps.desktop.status() });
101
+ },
102
+ render: (r) => `弹幕运行中 ${r.enabled} 条,间隔 ${r.intervalMs}ms`,
103
+ });
104
+ }
@@ -0,0 +1,174 @@
1
+ "use strict";
2
+ // 数据页的两个只读 action:表清单与分页查询,表名/列名全走白名单。
3
+
4
+ import { DOMAIN } from "../config.js";
5
+
6
+ const TABLES = [{ name: "danmaku", zh: "弹幕", en: "Danmaku" }];
7
+
8
+ const COLUMN_LABELS = {
9
+ id: { zh: "ID", en: "ID" },
10
+ body: { zh: "内容", en: "Body" },
11
+ tone: { zh: "颜色", en: "Tone" },
12
+ enabled: { zh: "启用", en: "Enabled" },
13
+ card: { zh: "卡片背景", en: "Card" },
14
+ font_size: { zh: "字号", en: "Font size" },
15
+ speed: { zh: "速度", en: "Speed" },
16
+ opacity: { zh: "不透明度", en: "Opacity" },
17
+ font_weight: { zh: "字重", en: "Weight" },
18
+ font_family: { zh: "字体", en: "Typeface" },
19
+ band: { zh: "泳道区域", en: "Lane area" },
20
+ prefix: { zh: "前缀", en: "Prefix" },
21
+ chance: { zh: "权重", en: "Chance" },
22
+ sort_order: { zh: "顺序", en: "Sort order" },
23
+ created_at: { zh: "创建时间", en: "Created at" },
24
+ updated_at: { zh: "更新时间", en: "Updated at" },
25
+ deleted_at: { zh: "删除时间", en: "Deleted at" },
26
+ rev: { zh: "版本号", en: "Rev" },
27
+ };
28
+
29
+ const SYSTEM_COLUMNS = new Set(["rev", "created_at", "updated_at", "deleted_at"]);
30
+ const PAGE_SIZES = [10, 25, 50, 100, 200];
31
+ const MAX_TEXT = 100;
32
+
33
+ function labelOf(name) {
34
+ const hit = COLUMN_LABELS[name];
35
+ return hit ? { zh: hit.zh, en: hit.en } : { zh: name, en: name };
36
+ }
37
+
38
+ function kindOf(name, declared) {
39
+ const type = String(declared || "").toUpperCase();
40
+ if (name === "id" || name.endsWith("_id")) return "id";
41
+ if (name.endsWith("_at") && type === "INTEGER") return "timestamp";
42
+ if (name === "card" || name === "enabled") return "bool";
43
+ if (type === "INTEGER" || type === "REAL") return "number";
44
+ return "text";
45
+ }
46
+
47
+ function pickPageSize(raw) {
48
+ const n = Math.floor(Number(raw));
49
+ if (!Number.isFinite(n) || n <= 0) return 50;
50
+ let best = PAGE_SIZES[0];
51
+ for (const size of PAGE_SIZES) if (Math.abs(size - n) < Math.abs(best - n)) best = size;
52
+ return best;
53
+ }
54
+
55
+ function likeEscape(text) {
56
+ return String(text).slice(0, MAX_TEXT).replace(/[\\%_]/g, (match) => "\\" + match);
57
+ }
58
+
59
+ function toPlain(row) {
60
+ const out = {};
61
+ for (const key of Object.keys(row)) out[key] = typeof row[key] === "bigint" ? Number(row[key]) : row[key];
62
+ return out;
63
+ }
64
+
65
+ export function registerDataActions(api) {
66
+ const db = api.db;
67
+
68
+ function columnList(table) {
69
+ try {
70
+ return db.prepare("PRAGMA table_info(" + table + ")").all().map((column) => ({
71
+ name: column.name,
72
+ type: String(column.type || ""),
73
+ kind: kindOf(column.name, column.type),
74
+ label: labelOf(column.name),
75
+ system: SYSTEM_COLUMNS.has(column.name),
76
+ pk: Boolean(column.pk),
77
+ }));
78
+ } catch (error) {
79
+ return [];
80
+ }
81
+ }
82
+
83
+ function tableMeta() {
84
+ return TABLES.map((def) => {
85
+ const columns = columnList(def.name);
86
+ let count = 0;
87
+ let deletedCount = 0;
88
+ try {
89
+ const row = db
90
+ .prepare("SELECT COUNT(*) AS total, SUM(CASE WHEN deleted_at IS NULL THEN 1 ELSE 0 END) AS live FROM " + def.name)
91
+ .get();
92
+ count = Number(row && row.live) || 0;
93
+ deletedCount = Math.max(0, (Number(row && row.total) || 0) - count);
94
+ } catch (error) {
95
+ count = 0;
96
+ }
97
+ return { name: def.name, label: { zh: def.zh, en: def.en }, columns, count, deletedCount };
98
+ });
99
+ }
100
+
101
+ api.action("danmaku.dataTables", {
102
+ description: "只读:弹幕插件负责的表清单、列元信息与行数",
103
+ input: { type: "object", properties: {}, additionalProperties: false },
104
+ execute: () => ({ domain: DOMAIN, tables: tableMeta() }),
105
+ render: (r) => `弹幕数据表 ${r.tables.map((t) => t.name + "(" + t.count + ")").join("、")}`,
106
+ });
107
+
108
+ api.action("danmaku.dataQuery", {
109
+ description: "只读:分页查询弹幕表;表名、排序列、筛选列都走白名单",
110
+ input: {
111
+ type: "object",
112
+ properties: {
113
+ table: { type: "string", description: "表名,目前只有 danmaku" },
114
+ page: { type: "number", description: "页码,从 1 开始,默认 1" },
115
+ pageSize: { type: "number", description: "每页数量,取 10/25/50/100/200 中最近的值,默认 50" },
116
+ sort: { type: "string", description: "排序列名(必须是真实列)" },
117
+ order: { type: "string", enum: ["asc", "desc"], description: "排序方向,默认 desc" },
118
+ search: { type: "string", description: "按弹幕内容模糊搜索" },
119
+ filters: { type: "object", description: "逐列包含筛选:{列名: 值}" },
120
+ includeDeleted: { type: "boolean", description: "包含已软删的行" },
121
+ },
122
+ required: ["table"],
123
+ additionalProperties: false,
124
+ },
125
+ execute: (args) => {
126
+ const def = TABLES.find((row) => row.name === String(args.table || ""));
127
+ if (!def) throw new Error("未知数据表:" + String(args.table || ""));
128
+ const columns = columnList(def.name);
129
+ const names = columns.map((column) => column.name);
130
+ const pageSize = pickPageSize(args.pageSize === undefined ? 50 : args.pageSize);
131
+ const page = Math.max(1, Number(args.page) || 1);
132
+ const order = args.order === "asc" ? "asc" : "desc";
133
+ const sort = args.sort && names.indexOf(String(args.sort)) >= 0 ? String(args.sort) : "created_at";
134
+ const where = [];
135
+ const params = [];
136
+ if (args.includeDeleted !== true) where.push("deleted_at IS NULL");
137
+ const search = String(args.search || "").trim().slice(0, MAX_TEXT);
138
+ if (search) {
139
+ where.push("instr(lower(body), lower(?)) > 0");
140
+ params.push(search);
141
+ }
142
+ const filters = args.filters && typeof args.filters === "object" && !Array.isArray(args.filters) ? args.filters : {};
143
+ for (const key of Object.keys(filters)) {
144
+ if (names.indexOf(key) < 0) throw new Error("未知筛选列:" + key);
145
+ const value = filters[key];
146
+ if (value === undefined || value === null) continue;
147
+ const text = String(value).trim().slice(0, MAX_TEXT);
148
+ if (!text) continue;
149
+ where.push("CAST(" + key + " AS TEXT) LIKE ? ESCAPE '\\'");
150
+ params.push("%" + likeEscape(text) + "%");
151
+ }
152
+ const whereSql = where.length ? where.join(" AND ") : "1=1";
153
+ const total = Number(db.prepare("SELECT COUNT(*) AS n FROM " + def.name + " WHERE " + whereSql).get(...params).n);
154
+ const rows = db
155
+ .prepare(
156
+ "SELECT * FROM " + def.name + " WHERE " + whereSql + " ORDER BY " + sort + " " + order + ", id " + order + " LIMIT ? OFFSET ?",
157
+ )
158
+ .all(...params, pageSize, (page - 1) * pageSize)
159
+ .map(toPlain);
160
+ return {
161
+ table: def.name,
162
+ columns,
163
+ rows,
164
+ total,
165
+ page,
166
+ pageSize,
167
+ pages: Math.max(1, Math.ceil(total / pageSize)),
168
+ sort,
169
+ order,
170
+ };
171
+ },
172
+ render: (r) => `表 ${r.table} 共 ${r.total} 行,第 ${r.page}/${r.pages} 页返回 ${r.rows.length} 行`,
173
+ });
174
+ }
@@ -0,0 +1,315 @@
1
+ "use strict";
2
+
3
+ import { findLive, liveRows, mapRow, newId, now, tx } from "../db/db.js";
4
+
5
+ export const TONES = ["normal", "accent", "success", "warn", "danger"];
6
+ export const BANDS = ["", "full", "upper", "lower"];
7
+ export const FAMILIES = ["", "rounded", "serif", "mono"];
8
+ export const WEIGHTS = [400, 500, 600, 700];
9
+ export const MAX_BODY = 100;
10
+ const STEP = 10;
11
+
12
+ function fail(message) {
13
+ throw new Error(message);
14
+ }
15
+
16
+ function normalizeBody(raw) {
17
+ if (typeof raw !== "string") fail("body 需要字符串");
18
+ const text = raw.replace(/\s+/g, " ").trim();
19
+ if (!text) fail("body 不能为空");
20
+ if (Array.from(text).length > MAX_BODY) fail(`body 不能超过 ${MAX_BODY} 个字符`);
21
+ return text;
22
+ }
23
+
24
+ function readRange(raw, field, min, max, fallback, integer) {
25
+ if (raw === undefined) return fallback;
26
+ if (raw === null || raw === "") return null;
27
+ const n = Number(raw);
28
+ if (!Number.isFinite(n)) fail(`${field} 需要数字`);
29
+ if (integer ? !Number.isInteger(n) : false) fail(`${field} 需要整数`);
30
+ if (n < min || n > max) fail(`${field} 需在 ${min}–${max} 之间`);
31
+ return n;
32
+ }
33
+
34
+ function readChoice(raw, field, allowed, fallback) {
35
+ if (raw === undefined) return fallback;
36
+ const text = raw === null ? "" : String(raw);
37
+ if (allowed.indexOf(text) < 0) fail(`${field} 只接受:${allowed.filter(Boolean).join(" / ") || "空"}`);
38
+ return text;
39
+ }
40
+
41
+ function readPrefix(raw, fallback) {
42
+ if (raw === undefined) return fallback;
43
+ if (raw === null) return "";
44
+ if (typeof raw !== "string") fail("prefix 需要字符串");
45
+ const text = raw.replace(/[\r\n\t]/g, " ").trim();
46
+ if (Array.from(text).length > 8) fail("prefix 不能超过 8 个字符");
47
+ return text;
48
+ }
49
+
50
+ function readStyle(args, item) {
51
+ const base = item || {};
52
+ return {
53
+ fontSize: readRange(args.fontSize, "fontSize", 10, 48, base.fontSize === undefined ? null : base.fontSize, true),
54
+ speed: readRange(args.speed, "speed", 30, 800, base.speed === undefined ? null : base.speed, true),
55
+ opacity: readRange(args.opacity, "opacity", 0.15, 1, base.opacity === undefined ? null : base.opacity, false),
56
+ fontWeight: readRange(args.fontWeight, "fontWeight", 300, 800, base.fontWeight === undefined ? null : base.fontWeight, true),
57
+ fontFamily: readChoice(args.fontFamily, "fontFamily", FAMILIES, base.fontFamily === undefined ? "" : base.fontFamily),
58
+ band: readChoice(args.band, "band", BANDS, base.band === undefined ? "" : base.band),
59
+ prefix: readPrefix(args.prefix, base.prefix === undefined ? "" : base.prefix),
60
+ chance: readRange(args.chance, "chance", 1, 5, base.chance === undefined ? 1 : base.chance, true) || 1,
61
+ };
62
+ }
63
+
64
+ function readCard(raw, fallback) {
65
+ if (raw === undefined || raw === null) return typeof fallback === "boolean" ? fallback : true;
66
+ if (typeof raw !== "boolean") fail("card 需要布尔值");
67
+ return raw;
68
+ }
69
+
70
+ function readTone(raw, fallback) {
71
+ if (raw === undefined || raw === null) return fallback || "normal";
72
+ if (typeof raw !== "string" || TONES.indexOf(raw) < 0) fail("tone 只接受:" + TONES.join(" / "));
73
+ return raw;
74
+ }
75
+
76
+ export function listItems(db) {
77
+ const rows = liveRows(db).map(mapRow);
78
+ const paused = rows.filter((item) => !item.enabled).length;
79
+ return { items: rows, total: rows.length, paused, enabled: rows.length - paused };
80
+ }
81
+
82
+ function nextOrder(db) {
83
+ const row = db.prepare("SELECT MAX(sort_order) AS m FROM danmaku WHERE deleted_at IS NULL").get();
84
+ const max = Number(row && row.m);
85
+ return (Number.isFinite(max) ? max : 0) + STEP;
86
+ }
87
+
88
+ function assertUnique(db, body, exceptId) {
89
+ const row = db.prepare("SELECT id FROM danmaku WHERE lower(body) = lower(?) AND deleted_at IS NULL").get(body);
90
+ if (row && row.id !== exceptId) fail("这条弹幕已在库里,无需重复添加");
91
+ }
92
+
93
+ export function createItem(db, args) {
94
+ const body = normalizeBody(args.body);
95
+ const tone = readTone(args.tone, "normal");
96
+ const card = readCard(args.card, true);
97
+ const style = readStyle(args, null);
98
+ assertUnique(db, body, "");
99
+ const ts = now();
100
+ const id = newId("dm");
101
+ const order = nextOrder(db);
102
+ db.prepare(
103
+ `INSERT INTO danmaku(id, body, tone, enabled, card, font_size, speed, opacity, font_weight, font_family, band, prefix, chance, sort_order, created_at, updated_at, rev)
104
+ VALUES(?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)`,
105
+ ).run(
106
+ id,
107
+ body,
108
+ tone,
109
+ card ? 1 : 0,
110
+ style.fontSize,
111
+ style.speed,
112
+ style.opacity,
113
+ style.fontWeight,
114
+ style.fontFamily,
115
+ style.band,
116
+ style.prefix,
117
+ style.chance,
118
+ order,
119
+ ts,
120
+ ts,
121
+ );
122
+ return { item: findLive(db, id) };
123
+ }
124
+
125
+ export function updateItem(db, args) {
126
+ const id = String(args.id || "");
127
+ if (!id) fail("id 必填");
128
+ const item = findLive(db, id);
129
+ if (!item) fail("弹幕不存在或已删除");
130
+ const fields = [];
131
+ const params = [];
132
+ if (args.body !== undefined) {
133
+ const body = normalizeBody(args.body);
134
+ assertUnique(db, body, id);
135
+ fields.push("body = ?");
136
+ params.push(body);
137
+ }
138
+ if (args.tone !== undefined) {
139
+ fields.push("tone = ?");
140
+ params.push(readTone(args.tone, item.tone));
141
+ }
142
+ if (args.enabled !== undefined) {
143
+ if (typeof args.enabled !== "boolean") fail("enabled 需要布尔值");
144
+ fields.push("enabled = ?");
145
+ params.push(args.enabled ? 1 : 0);
146
+ }
147
+ if (args.card !== undefined) {
148
+ fields.push("card = ?");
149
+ params.push(readCard(args.card, item.card) ? 1 : 0);
150
+ }
151
+ const styleFields = [
152
+ ["font_size", "fontSize"],
153
+ ["speed", "speed"],
154
+ ["opacity", "opacity"],
155
+ ["font_weight", "fontWeight"],
156
+ ["font_family", "fontFamily"],
157
+ ["band", "band"],
158
+ ["prefix", "prefix"],
159
+ ["chance", "chance"],
160
+ ];
161
+ const style = readStyle(args, item);
162
+ for (const [column, key] of styleFields) {
163
+ if (args[key] === undefined) continue;
164
+ fields.push(column + " = ?");
165
+ params.push(style[key] === "" ? null : style[key]);
166
+ }
167
+ if (!fields.length) return { item };
168
+ fields.push("updated_at = ?", "rev = rev + 1");
169
+ params.push(now());
170
+ params.push(id);
171
+ db.prepare("UPDATE danmaku SET " + fields.join(", ") + " WHERE id = ? AND deleted_at IS NULL").run(...params);
172
+ return { item: findLive(db, id) };
173
+ }
174
+
175
+ export function removeItem(db, args) {
176
+ const id = String(args.id || "");
177
+ if (!id) fail("id 必填");
178
+ const item = findLive(db, id);
179
+ if (!item) fail("弹幕不存在或已删除");
180
+ const ts = now();
181
+ db.prepare("UPDATE danmaku SET deleted_at = ?, updated_at = ?, rev = rev + 1 WHERE id = ?").run(ts, ts, id);
182
+ return { id };
183
+ }
184
+
185
+ export function reorderItems(db, args) {
186
+ const ids = Array.isArray(args.ids) ? args.ids.map((id) => String(id)) : [];
187
+ if (!ids.length) fail("ids 必填且不能为空");
188
+ const known = new Map(liveRows(db).map((row) => [row.id, row]));
189
+ const ts = now();
190
+ tx(db, () => {
191
+ ids.forEach((id, index) => {
192
+ if (!known.has(id)) return;
193
+ db.prepare("UPDATE danmaku SET sort_order = ?, updated_at = ?, rev = rev + 1 WHERE id = ?").run(index * STEP, ts, id);
194
+ });
195
+ });
196
+ return listItems(db);
197
+ }
198
+
199
+ export function registerManageActions(api, deps) {
200
+ const db = api.db;
201
+
202
+ api.action("danmaku.list", {
203
+ description: "弹幕库列表:按 sort_order 返回未删除的弹幕,以及启用/停用计数",
204
+ input: { type: "object", properties: {}, additionalProperties: false },
205
+ execute: () => listItems(db),
206
+ render: (r) => `弹幕库 ${r.total} 条(启用 ${r.enabled})`,
207
+ });
208
+
209
+ api.action("danmaku.create", {
210
+ description: "新增一条弹幕;同一内容(忽略大小写)在库中唯一,重复会报错",
211
+ input: {
212
+ type: "object",
213
+ properties: {
214
+ body: { type: "string", description: "弹幕内容,空白折叠,最长 100 字" },
215
+ tone: { type: "string", enum: TONES, description: "颜色主题,默认 normal" },
216
+ card: { type: "boolean", description: "是否带卡片背景,默认 true;false 时只显示文字" },
217
+ fontSize: { type: "integer", minimum: 10, maximum: 48, description: "字号像素;省略或 null = 跟随全局" },
218
+ speed: { type: "integer", minimum: 30, maximum: 800, description: "滚动速度 px/s;省略或 null = 跟随全局" },
219
+ opacity: { type: "number", minimum: 0.15, maximum: 1, description: "不透明度;省略或 null = 跟随全局" },
220
+ fontWeight: { type: "integer", enum: WEIGHTS, description: "字重 400/500/600/700;省略 = 跟随全局" },
221
+ fontFamily: { type: "string", enum: FAMILIES, description: "字体:空 = 系统,rounded = 圆体,serif = 衬线,mono = 等宽" },
222
+ band: { type: "string", enum: BANDS, description: "泳道区域:空 = 跟随全局,full/upper/lower" },
223
+ prefix: { type: "string", description: "可选前缀(如 emoji),最多 8 字" },
224
+ chance: { type: "integer", minimum: 1, maximum: 5, description: "轮播权重 1–5,越大越常出现" },
225
+ },
226
+ required: ["body"],
227
+ additionalProperties: false,
228
+ },
229
+ execute: (args) => {
230
+ const out = createItem(db, args);
231
+ deps.changed("create", out.item.id);
232
+ return out;
233
+ },
234
+ render: (r) => `已添加弹幕:${r.item.body}`,
235
+ });
236
+
237
+ api.action("danmaku.update", {
238
+ description: "修改一条弹幕的内容、外观(颜色/背景/字号/字重/字体/透明度)、动效(速度/泳道)、轮播(前缀/权重)或启停;只传要改的字段",
239
+ input: {
240
+ type: "object",
241
+ properties: {
242
+ id: { type: "string", description: "弹幕 id" },
243
+ body: { type: "string", description: "新内容,最长 100 字" },
244
+ tone: { type: "string", enum: TONES, description: "颜色主题" },
245
+ card: { type: "boolean", description: "是否带卡片背景" },
246
+ enabled: { type: "boolean", description: "是否参与轮播" },
247
+ fontSize: { type: "integer", minimum: 10, maximum: 48, description: "字号像素;null = 跟随全局" },
248
+ speed: { type: "integer", minimum: 30, maximum: 800, description: "滚动速度 px/s;null = 跟随全局" },
249
+ opacity: { type: "number", minimum: 0.15, maximum: 1, description: "不透明度;null = 跟随全局" },
250
+ fontWeight: { type: "integer", enum: WEIGHTS, description: "字重;省略 = 不变" },
251
+ fontFamily: { type: "string", enum: FAMILIES, description: "字体,空 = 系统" },
252
+ band: { type: "string", enum: BANDS, description: "泳道区域,空 = 跟随全局" },
253
+ prefix: { type: "string", description: "前缀,最多 8 字" },
254
+ chance: { type: "integer", minimum: 1, maximum: 5, description: "轮播权重" },
255
+ },
256
+ required: ["id"],
257
+ additionalProperties: false,
258
+ },
259
+ execute: (args) => {
260
+ const out = updateItem(db, args);
261
+ deps.changed("update", out.item.id);
262
+ return out;
263
+ },
264
+ render: (r) => `已保存弹幕:${r.item.body}`,
265
+ });
266
+
267
+ api.action("danmaku.remove", {
268
+ description: "软删除一条弹幕;删除后不再参与轮播,相同内容之后可以重新添加",
269
+ input: {
270
+ type: "object",
271
+ properties: { id: { type: "string", description: "弹幕 id" } },
272
+ required: ["id"],
273
+ additionalProperties: false,
274
+ },
275
+ execute: (args) => {
276
+ const out = removeItem(db, args);
277
+ deps.changed("remove", out.id);
278
+ return out;
279
+ },
280
+ render: (r) => `已删除弹幕 ${r.id}`,
281
+ });
282
+
283
+ api.action("danmaku.reorder", {
284
+ description: "按传入的 id 顺序重排弹幕库(决定「按列表顺序」轮播的次序)",
285
+ input: {
286
+ type: "object",
287
+ properties: {
288
+ ids: { type: "array", items: { type: "string" }, description: "完整的目标顺序;未知 id 会被忽略" },
289
+ },
290
+ required: ["ids"],
291
+ additionalProperties: false,
292
+ },
293
+ execute: (args) => {
294
+ const out = reorderItems(db, args);
295
+ deps.changed("reorder", "");
296
+ return out;
297
+ },
298
+ render: (r) => `弹幕顺序已更新,共 ${r.total} 条`,
299
+ });
300
+
301
+ api.action("danmaku.preview", {
302
+ description: "立刻让一条弹幕(默认随机一条启用中的)在界面层和桌面层各预览一次,不改库",
303
+ input: {
304
+ type: "object",
305
+ properties: { id: { type: "string", description: "要预览的弹幕 id;省略则随机一条" } },
306
+ additionalProperties: false,
307
+ },
308
+ execute: (args) => {
309
+ const out = deps.player.preview(args.id ? String(args.id) : "");
310
+ if (!out) fail("没有启用中的弹幕可预览");
311
+ return out;
312
+ },
313
+ render: (r) => `已预览:${r.body}`,
314
+ });
315
+ }