Files
37duAutomation/desktop/electron-shell/electron/last-fields.js
T

73 lines
2.5 KiB
JavaScript

// 上次执行参数(per 账号 + per 插件):供场景执行台「恢复上次参数」使用,免去每次逐项重填。
// 存储:%LOCALAPPDATA%\37duAutomation\last_run_fields.json(纯新增文件,不改既有契约)
// 安全:password 类型字段一律不落盘(插件 fields 可含密码),只保存非敏感项。
"use strict";
const fs = require("fs");
const path = require("path");
const config = require("./config");
const { makeLogger } = require("./logger");
const logger = makeLogger("last-fields");
const STORE_PATH = path.join(config.APP_DATA, "last_run_fields.json");
const MAX_FIELDS = 40; // 单插件最多记 40 项,防异常插件撑爆文件
function loadAll() {
if (!fs.existsSync(STORE_PATH)) return {};
try {
const d = JSON.parse(fs.readFileSync(STORE_PATH, "utf-8"));
return d && typeof d === "object" && !Array.isArray(d) ? d : {};
} catch (e) {
logger.warning(`上次参数读取失败:${e.message}`);
return {};
}
}
function saveAll(data) {
try {
fs.mkdirSync(config.APP_DATA, { recursive: true });
const tmp = STORE_PATH + ".tmp";
fs.writeFileSync(tmp, JSON.stringify(data, null, 2), "utf-8");
fs.renameSync(tmp, STORE_PATH); // 原子替换
} catch (e) {
logger.warning(`上次参数写入失败:${e.message}`);
}
}
// 保存一次执行的参数快照;schema = 插件的 fields 元数据(用于剔除 password 等敏感项)
function remember(account, pluginId, fields, schema) {
if (!account || !pluginId || !fields || typeof fields !== "object") return;
const secret = new Set(
(Array.isArray(schema) ? schema : [])
.filter((f) => f && f.type === "password")
.map((f) => f.key)
);
const keep = {};
for (const [k, v] of Object.entries(fields)) {
if (secret.has(k)) continue;
if (Object.keys(keep).length >= MAX_FIELDS) break;
keep[k] = v;
}
const all = loadAll();
if (!all[account] || typeof all[account] !== "object") all[account] = {};
all[account][pluginId] = {
fields: keep,
at: new Date().toLocaleString("zh-CN", { hour12: false }),
};
saveAll(all);
}
// 读取上次参数;无记录返回 { fields: {}, at: "" }
function recall(account, pluginId) {
const all = loadAll();
const rec = (all[account] || {})[pluginId] || null;
if (!rec || typeof rec !== "object") return { fields: {}, at: "" };
return {
fields: rec.fields && typeof rec.fields === "object" ? rec.fields : {},
at: rec.at || "",
};
}
module.exports = { STORE_PATH, MAX_FIELDS, remember, recall };