feat: 增加配置导入导出功能

This commit is contained in:
2026-11-24 17:22:08 +08:00
parent 9a23cd1d32
commit eb9b6d534f
6 changed files with 257 additions and 24 deletions
+16 -2
View File
@@ -184,7 +184,9 @@ npm start
| GET | `/api/state` | 全部行情 + 配置 + 提醒 | | GET | `/api/state` | 全部行情 + 配置 + 提醒 |
| GET | `/api/health` | 存活检查 | | GET | `/api/health` | 存活检查 |
| PUT | `/api/config` | 局部更新配置(对象深合并) | | PUT | `/api/config` | 局部更新配置(对象深合并) |
| GET/POST | `/api/config/export` `/api/config/import` | 备份 / 恢复配置 | | GET | `/api/config/export?secrets=1` | 导出配置 JSON(不带 `secrets=1` 时邮箱密码 / WebHook 加签自动脱敏) |
| POST | `/api/config/import` | 导入配置(覆盖式,导入前自动备份到 `config/backups/`,返回备份文件名) |
| GET | `/api/config/backups` | 查看最近的配置备份(最多保留 20 份) |
| POST | `/api/instruments` | 新增品种(`presetKey` 或自定义字段) | | POST | `/api/instruments` | 新增品种(`presetKey` 或自定义字段) |
| PUT/DELETE | `/api/instruments/:id` | 修改 / 删除品种 | | PUT/DELETE | `/api/instruments/:id` | 修改 / 删除品种 |
| POST | `/api/instruments/:id/manual` | 手动推价 `{ "price": 781.2, "prevClose": 780 }` | | POST | `/api/instruments/:id/manual` | 手动推价 `{ "price": 781.2, "prevClose": 780 }` |
@@ -228,7 +230,19 @@ curl -X POST http://127.0.0.1:8787/api/instruments/ins_czbjcj/manual \
``` ```
改端口/监听地址需要重启进程,其它配置网页保存后即时生效。 改端口/监听地址需要重启进程,其它配置网页保存后即时生效。
`config.json` 里含邮箱授权码,请勿外传;页面导出配置同样含真实密码。
**配置导入导出**(「通知设置 → 配置备份」卡片):
- 导出:生成 `gold-price-watcher-config-20261124-165146.json`,包含品种、规则、渠道、端口等全部配置;
默认把邮箱密码 / WebHook 加签**脱敏为空**,方便分享;勾选「导出时包含密钥」才会写入真实密钥(此时文件请勿外传)。
- 导入:选 JSON 文件后先弹「确认导入配置」,摘要里列出文件大小、导出时间、品种数、规则数(按类型分解)、通知渠道、监听地址;
点「确认导入」才会真正覆盖。
- 覆盖前程序自动把当前配置备份到 `config/backups/config-<时间戳>.json`(最多保留 20 份),
页面上会显示最近备份清单,导入效果不对可以直接拿备份文件再导入回去。
- 导入后品种会按新配置重新编排轮询;端口/监听地址改动仍需重启进程才生效。
- 不是本工具导出的 JSON(缺少 `instruments` / `rules`)会被拒绝,不会覆盖配置。
`config.json` 里含邮箱授权码,请勿外传;导出时默认已脱敏,只有勾选「包含密钥」才会写出真实密码。
--- ---
+88 -8
View File
@@ -1368,25 +1368,50 @@ function bindEvents() {
} }
}); });
// 导入导出 // 配置导入导出
document.getElementById('btnExportConfig').addEventListener('click', () => { document.getElementById('btnExportConfig').addEventListener('click', () => {
window.location.href = '/api/config/export'; // 勾了「包含密钥」才把真实密码/加签密钥写进文件,默认脱敏,方便分享
const withSecrets = document.getElementById('exportWithSecrets').checked;
window.location.href = `/api/config/export${withSecrets ? '?secrets=1' : ''}`;
toast(withSecrets ? '正在导出(含密钥,请妥善保管)' : '正在导出(密钥已脱敏)', 'ok');
}); });
document.getElementById('btnImportConfig').addEventListener('click', () => document.getElementById('importFile').click()); document.getElementById('btnImportConfig').addEventListener('click', () => document.getElementById('importFile').click());
document.getElementById('importFile').addEventListener('change', async (e) => { document.getElementById('importFile').addEventListener('change', async (e) => {
const file = e.target.files?.[0]; const file = e.target.files?.[0];
e.target.value = '';
if (!file) return; if (!file) return;
try { try {
const text = await file.text(); const text = await file.text();
const json = JSON.parse(text); const json = JSON.parse(text);
const res = await api('/api/config/import', { method: 'POST', body: json }); const data = json?.config && typeof json.config === 'object' ? json.config : json;
applyState(res, true); if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('文件内容不是配置对象');
fillSettings(); if (!Array.isArray(data.instruments) && !Array.isArray(data.rules)) {
toast('配置已导入', 'ok'); throw new Error('这不像是本工具导出的配置文件(缺少 instruments / rules)');
}
// 先把摘要摆出来,让用户确认后再真正覆盖
ui.pendingImport = data;
ui.pendingImportFile = file.name;
document.getElementById('importSummary').innerHTML = buildImportSummary(data, file);
setResult('importResult', '');
openModal('modalImport');
} catch (err) { } catch (err) {
toast(`导入失败:${err.message}`, 'err'); toast(`导入失败:${err.message}`, 'err');
} finally { }
e.target.value = ''; });
document.getElementById('btnConfirmImport').addEventListener('click', async () => {
if (!ui.pendingImport) return;
try {
const res = await api('/api/config/import', { method: 'POST', body: ui.pendingImport });
applyState(res, true);
fillSettings();
closeModal('modalImport');
ui.pendingImport = null;
toast(`配置已导入${res.backup ? `,原配置已备份为 ${res.backup}` : ''}`, 'ok');
refreshBackupList();
} catch (err) {
setResult('importResult', err.message, false);
} }
}); });
@@ -1410,10 +1435,65 @@ function bindEvents() {
const TABS = ['market', 'rules', 'channels', 'alerts']; const TABS = ['market', 'rules', 'channels', 'alerts'];
/**
* 生成导入前的配置摘要(覆盖前先看清楚要导入什么)
* @param {object} data 待导入的配置对象
* @param {File} file 用户选择的文件
* @returns {string} 摘要 HTML
*/
function buildImportSummary(data, file) {
const instruments = Array.isArray(data.instruments) ? data.instruments : [];
const rules = Array.isArray(data.rules) ? data.rules : [];
const typeNames = { threshold: '价格阈值', change: '涨跌幅', spread: '价差', schedule: '定时' };
const ruleCounts = {};
rules.forEach((r) => {
const key = typeNames[r.type] || String(r.type || '未知');
ruleCounts[key] = (ruleCounts[key] || 0) + 1;
});
const ruleText = rules.length
? `${rules.length} 条(${Object.entries(ruleCounts).map(([k, v]) => `${k} ${v}`).join('、')})`
: '0 条';
const instText = instruments.length
? `${instruments.length} 个:${instruments.slice(0, 4).map((i) => i.name || i.id).join('、')}${instruments.length > 4 ? ' 等' : ''}`
: '0 个';
const channelText = [
data.desktop?.enabled ? '桌面通知' : null,
data.email?.enabled ? '邮件' : null,
data.webhook?.enabled ? `WebHook(${data.webhook?.format === 'dingtalk' ? '钉钉' : '内置 JSON'})` : null,
].filter(Boolean).join(' + ') || '仅使用规则自带渠道';
const sizeText = file?.size ? `${(file.size / 1024).toFixed(1)} KB` : '未知大小';
return [
`<div>文件:<b>${esc(file?.name || '未命名')}</b>(${esc(sizeText)})</div>`,
data.exportedAt ? `<div>导出时间:<b>${esc(data.exportedAt)}</b></div>` : '',
`<div>监控品种:<b>${esc(instText)}</b></div>`,
`<div>提醒规则:<b>${esc(ruleText)}</b></div>`,
`<div>通知渠道:<b>${esc(channelText)}</b></div>`,
`<div>监听地址:<b>${esc(`${data.app?.host || '127.0.0.1'}:${data.app?.port || 8787}`)}</b>(端口改动需重启程序才生效)</div>`,
data.email?.pass ? '<div>注意:文件里带有邮箱密码,导入后会按文件中的值覆盖当前密码。</div>' : '',
].filter(Boolean).join('');
}
/** 读取并展示最近的配置备份 */
async function refreshBackupList() {
const el = document.getElementById('backupListHint');
if (!el) return;
try {
const res = await api('/api/config/backups');
const list = res.backups || [];
el.textContent = list.length
? `最近备份(最多保留 20 份):${list.map((b) => `${b.name}(${b.at})`).join(';')}`
: '还没有备份:每次导入配置前会自动生成一份。';
} catch (err) {
el.textContent = `读取备份列表失败:${err.message}`;
}
}
/** 启动 */ /** 启动 */
async function boot() { async function boot() {
bindEvents(); bindEvents();
await refreshState(true); await refreshState(true);
refreshBackupList();
const hashTab = (location.hash || '').replace('#', ''); const hashTab = (location.hash || '').replace('#', '');
if (TABS.includes(hashTab)) activateTab(hashTab); if (TABS.includes(hashTab)) activateTab(hashTab);
window.addEventListener('hashchange', () => { window.addEventListener('hashchange', () => {
+35 -6
View File
@@ -4,7 +4,7 @@
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<title>金价提醒 · Gold Price Watcher</title> <title>金价提醒 · Gold Price Watcher</title>
<link rel="stylesheet" href="/styles.css?v=20261124q" /> <link rel="stylesheet" href="/styles.css?v=20261124s" />
</head> </head>
<body> <body>
<header class="topbar"> <header class="topbar">
@@ -194,11 +194,21 @@
<label class="check"><input type="checkbox" id="appOpenBrowser" /> 启动时自动打开浏览器</label> <label class="check"><input type="checkbox" id="appOpenBrowser" /> 启动时自动打开浏览器</label>
</div> </div>
<p class="hint" id="configPathHint"></p> <p class="hint" id="configPathHint"></p>
<div class="row"> </div>
<button class="btn ghost" id="btnExportConfig">导出配置</button>
<button class="btn ghost" id="btnImportConfig">导入配置</button> <!-- 配置备份:导出为 JSON 文件、导入前自动备份当前配置 -->
<input type="file" id="importFile" accept="application/json" hidden /> <div class="card setting-card">
<div class="card-head"><h3>配置备份</h3></div>
<p class="hint">导出成 JSON 文件,可用于换机迁移、分享给同事,或改坏配置后回滚;导入会<b>覆盖</b>当前全部配置(品种、规则、渠道、端口等),导入前程序会自动把现有配置备份到 <code>config/backups/</code>。</p>
<div class="row wrap">
<label class="check"><input type="checkbox" id="exportWithSecrets" /> 导出时包含密钥(邮箱密码 / WebHook 加签)</label>
</div> </div>
<div class="row wrap">
<button class="btn primary" id="btnExportConfig">导出配置</button>
<button class="btn ghost" id="btnImportConfig">导入配置</button>
<input type="file" id="importFile" accept="application/json,.json" hidden />
</div>
<p class="hint" id="backupListHint"></p>
</div> </div>
<div class="row sticky-save"> <div class="row sticky-save">
@@ -369,8 +379,27 @@
</div> </div>
</div> </div>
<!-- ============ 弹窗:确认导入配置 ============ -->
<div class="modal" id="modalImport" hidden>
<div class="modal-box">
<div class="modal-head">
<h3>确认导入配置</h3>
<button class="icon-btn" data-close="modalImport">✕</button>
</div>
<div class="modal-body">
<p class="hint">导入会<b>覆盖</b>当前全部配置(品种、规则、通知渠道、端口等);导入前程序会自动把现有配置备份到 <code>config/backups/</code>,不满意可以用备份回滚。</p>
<div class="import-summary" id="importSummary"></div>
</div>
<div class="modal-foot">
<span class="test-result" id="importResult"></span>
<button class="btn ghost" data-close="modalImport">取消</button>
<button class="btn primary" id="btnConfirmImport">确认导入</button>
</div>
</div>
</div>
<div class="toast-wrap" id="toastWrap"></div> <div class="toast-wrap" id="toastWrap"></div>
<script src="/app.js?v=20261124q"></script> <script src="/app.js?v=20261124s"></script>
</body> </body>
</html> </html>
+13
View File
@@ -349,6 +349,19 @@ main { padding: 22px 28px 60px; max-width: 1320px; margin: 0 auto; }
.tag.spread { color: #6a4b9a; border-color: #e0d4f0; background: #f7f3fc; } .tag.spread { color: #6a4b9a; border-color: #e0d4f0; background: #f7f3fc; }
/* 定时提醒:用偏绿的色,和三种价格条件规则区分开 */ /* 定时提醒:用偏绿的色,和三种价格条件规则区分开 */
.tag.schedule { color: #1f7a5c; border-color: #cfe8dd; background: #f1faf6; } .tag.schedule { color: #1f7a5c; border-color: #cfe8dd; background: #f1faf6; }
/* 导入配置前的摘要区块 */
.import-summary {
margin-top: 10px;
padding: 12px 14px;
border: 1px solid var(--line);
border-radius: 10px;
background: var(--panel-2, #fbfaf6);
font-size: 12.5px;
line-height: 1.9;
color: var(--text-dim);
}
.import-summary b { color: var(--text); }
.rule-cond { margin-top: 4px; font-size: 12.5px; color: var(--text-dim); } .rule-cond { margin-top: 4px; font-size: 12.5px; color: var(--text-dim); }
.rule-sub { margin-top: 3px; font-size: 11.5px; color: var(--text-faint); } .rule-sub { margin-top: 3px; font-size: 11.5px; color: var(--text-faint); }
.rule-actions { display: flex; align-items: center; gap: 8px; } .rule-actions { display: flex; align-items: center; gap: 8px; }
+83 -4
View File
@@ -9,13 +9,17 @@
*/ */
const path = require('node:path'); const path = require('node:path');
const fs = require('node:fs');
const { const {
deepMerge, readJson, writeJson, uid, toNum, maskSecret, log, isPlainObject, deepMerge, readJson, writeJson, uid, toNum, maskSecret, log, isPlainObject, ensureDir, nowText,
} = require('./util'); } = require('./util');
const { PRESETS, buildInstrument } = require('./presets'); const { PRESETS, buildInstrument } = require('./presets');
const ROOT = path.resolve(__dirname, '..'); const ROOT = path.resolve(__dirname, '..');
const CONFIG_FILE = path.join(ROOT, 'config', 'config.json'); const CONFIG_FILE = path.join(ROOT, 'config', 'config.json');
/** 导入前的自动备份目录,最多保留 20 份 */
const BACKUP_DIR = path.join(ROOT, 'config', 'backups');
const MAX_BACKUPS = 20;
const SCHEMA_VERSION = 1; const SCHEMA_VERSION = 1;
/** 允许的通知渠道 */ /** 允许的通知渠道 */
@@ -383,14 +387,87 @@ function forClient() {
}; };
} }
/** 导出完整配置(含真实密码,用于备份,仅本地接口使用) */ /**
function exportFile() { * 导出配置
return get(); * @param {boolean} includeSecrets 是否带上真实密钥(邮箱密码 / WebHook 加签)
* @returns {object} 可直接下载为 JSON 的配置对象
*/
function exportFile(includeSecrets = false) {
const cfg = JSON.parse(JSON.stringify(get()));
if (!includeSecrets) {
// 默认脱敏:方便把配置文件发给别人或贴到聊天里
if (cfg.email) cfg.email.pass = '';
if (cfg.webhook) cfg.webhook.secret = '';
}
return {
...cfg,
exportedAt: nowText(),
exportTool: 'gold-price-watcher',
exportVersion: SCHEMA_VERSION,
};
}
/**
* 生成文件名用的时间戳(本地时间,精确到秒)
* @param {Date} date 时间
* @returns {string} 例如 20261124-165012
*/
function fileStamp(date = new Date()) {
const pad = (n) => String(n).padStart(2, '0');
return `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}`
+ `-${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`;
}
/**
* 把当前配置备份到 config/backups/,返回备份文件名
* 导入前先调用,出问题可以直接拿这个文件回滚
* @returns {string|null} 备份文件名
*/
function backupCurrent() {
try {
ensureDir(BACKUP_DIR);
const name = `config-${fileStamp()}.json`;
writeJson(path.join(BACKUP_DIR, name), get());
// 只保留最近 MAX_BACKUPS 份,避免越攒越多
const files = fs.readdirSync(BACKUP_DIR).filter((f) => f.endsWith('.json')).sort();
while (files.length > MAX_BACKUPS) {
const oldest = files.shift();
try { fs.unlinkSync(path.join(BACKUP_DIR, oldest)); } catch { /* 删不掉就下次再说 */ }
}
return name;
} catch (err) {
log.warn(`备份当前配置失败:${err.message}`);
return null;
}
}
/**
* 列出最近的配置备份
* @param {number} limit 返回条数
* @returns {{name: string, size: number, at: string}[]}
*/
function listBackups(limit = 5) {
if (!fs.existsSync(BACKUP_DIR)) return [];
return fs.readdirSync(BACKUP_DIR)
.filter((f) => f.endsWith('.json'))
.sort()
.slice(-limit)
.reverse()
.map((name) => {
const filePath = path.join(BACKUP_DIR, name);
const stat = fs.statSync(filePath);
return {
name,
size: stat.size,
at: nowText(new Date(stat.mtimeMs)),
};
});
} }
module.exports = { module.exports = {
ROOT, ROOT,
CONFIG_FILE, CONFIG_FILE,
BACKUP_DIR,
defaultConfig, defaultConfig,
normalizeConfig, normalizeConfig,
load, load,
@@ -399,4 +476,6 @@ module.exports = {
patch, patch,
forClient, forClient,
exportFile, exportFile,
backupCurrent,
listBackups,
}; };
+22 -4
View File
@@ -62,17 +62,35 @@ function createApp({ monitor }) {
res.json({ ok: true, ...fullState() }); res.json({ ok: true, ...fullState() });
})); }));
// ---------------- 配置备份:导出 / 导入 ----------------
app.get('/api/config/export', wrap(async (req, res) => { app.get('/api/config/export', wrap(async (req, res) => {
res.setHeader('Content-Disposition', `attachment; filename="gold-price-watcher-config-${Date.now()}.json"`); const includeSecrets = String(req.query.secrets || '') === '1';
res.json(store.exportFile()); // 文件名用本地时间:gold-price-watcher-config-20261124-165146.json
const d = new Date();
const pad = (n) => String(n).padStart(2, '0');
const stamp = `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
res.setHeader('Content-Disposition', `attachment; filename="gold-price-watcher-config-${stamp}.json"`);
res.json(store.exportFile(includeSecrets));
})); }));
app.post('/api/config/import', wrap(async (req, res) => { app.post('/api/config/import', wrap(async (req, res) => {
const data = req.body?.config || req.body; const data = req.body?.config || req.body;
if (!data || typeof data !== 'object') throw new Error('导入内容不是合法 JSON 对象'); if (!data || typeof data !== 'object' || Array.isArray(data)) {
throw new Error('导入内容不是合法的配置对象');
}
if (!Array.isArray(data.instruments) && !Array.isArray(data.rules)) {
throw new Error('这不像是本工具导出的配置文件(缺少 instruments / rules)');
}
// 覆盖前先备份,导入失败或效果不对可以拿备份回滚
const backup = store.backupCurrent();
store.replace(data); store.replace(data);
monitor.reschedule(); monitor.reschedule();
res.json({ ok: true, ...fullState() }); res.json({ ok: true, backup, ...fullState() });
}));
// 列出最近的备份,页面上给出回滚提示
app.get('/api/config/backups', wrap(async (req, res) => {
res.json({ ok: true, dir: store.BACKUP_DIR, backups: store.listBackups(5) });
})); }));
// ---------------- 监控品种 ---------------- // ---------------- 监控品种 ----------------