74 lines
2.9 KiB
JavaScript
74 lines
2.9 KiB
JavaScript
// 场景配置方案(多配置)· SQLite 实现:同一场景可保存多套命名参数组合,运行台/定时任务按需选用。
|
||
// 表:plugin_configs(shell.db),按账号 + 插件隔离,同名覆盖。
|
||
// 安全:password 类型字段一律不落盘(与 last-fields.js 一致,仅保存非敏感项)。
|
||
"use strict";
|
||
|
||
const { db } = require("./db");
|
||
|
||
const MAX_CONFIGS_PER_PLUGIN = 10; // 单插件最多 10 套方案,防异常堆满
|
||
|
||
// 过滤敏感字段:schema = 插件的 fields 元数据,password 类型不入库
|
||
function sanitize(fields, schema) {
|
||
const secret = new Set(
|
||
(Array.isArray(schema) ? schema : [])
|
||
.filter((f) => f && f.type === "password")
|
||
.map((f) => f.key)
|
||
);
|
||
const out = {};
|
||
for (const [k, v] of Object.entries(fields || {})) {
|
||
if (secret.has(k)) continue;
|
||
out[k] = v;
|
||
}
|
||
return out;
|
||
}
|
||
|
||
function rowToCfg(row) {
|
||
if (!row) return null;
|
||
let fields = {};
|
||
try { fields = JSON.parse(row.fields || "{}"); } catch (_) { fields = {}; }
|
||
return { id: String(row.id), name: row.name, fields, at: row.at || "" };
|
||
}
|
||
|
||
function listConfigs(account, pluginId) {
|
||
const rows = db.prepare(
|
||
"SELECT id, name, fields, at FROM plugin_configs WHERE account = ? AND plugin_id = ? ORDER BY id"
|
||
).all(account, pluginId);
|
||
return rows.map(rowToCfg);
|
||
}
|
||
|
||
// 保存/覆盖:同名方案更新字段,否则新增;返回新/更新后的配置
|
||
function saveConfig(account, pluginId, name, fields, schema) {
|
||
const trimmed = String(name || "").trim().slice(0, 20);
|
||
if (!trimmed) return null;
|
||
const keep = sanitize(fields, schema);
|
||
const at = new Date().toLocaleString("zh-CN", { hour12: false });
|
||
const exists = db.prepare(
|
||
"SELECT id FROM plugin_configs WHERE account = ? AND plugin_id = ? AND name = ?"
|
||
).get(account, pluginId, trimmed);
|
||
if (exists) {
|
||
db.prepare(
|
||
"UPDATE plugin_configs SET fields = ?, at = ? WHERE id = ?"
|
||
).run(JSON.stringify(keep), at, exists.id);
|
||
return rowToCfg(db.prepare("SELECT id, name, fields, at FROM plugin_configs WHERE id = ?").get(exists.id));
|
||
}
|
||
const count = db.prepare(
|
||
"SELECT COUNT(*) AS n FROM plugin_configs WHERE account = ? AND plugin_id = ?"
|
||
).get(account, pluginId);
|
||
if (count.n >= MAX_CONFIGS_PER_PLUGIN) {
|
||
throw Object.assign(new Error(`每个场景最多保存 ${MAX_CONFIGS_PER_PLUGIN} 套配置`), { status: 400 });
|
||
}
|
||
const r = db.prepare(
|
||
"INSERT INTO plugin_configs (account, plugin_id, name, fields, at) VALUES (?, ?, ?, ?, ?)"
|
||
).run(account, pluginId, trimmed, JSON.stringify(keep), at);
|
||
return rowToCfg(db.prepare("SELECT id, name, fields, at FROM plugin_configs WHERE id = ?").get(r.lastInsertRowid));
|
||
}
|
||
|
||
function deleteConfig(account, pluginId, cfgId) {
|
||
const r = db.prepare(
|
||
"DELETE FROM plugin_configs WHERE account = ? AND plugin_id = ? AND id = ?"
|
||
).run(account, pluginId, cfgId);
|
||
return r.changes > 0;
|
||
}
|
||
|
||
module.exports = { MAX_CONFIGS_PER_PLUGIN, listConfigs, saveConfig, deleteConfig };
|