2026-11-24 16:37:13 +08:00
|
|
|
|
/**
|
|
|
|
|
|
* 配置存取层。
|
|
|
|
|
|
* 配置全部落在 config/config.json:
|
|
|
|
|
|
* - instruments 监控品种(数据源、刷新频率、单位等)
|
2026-11-24 18:01:49 +08:00
|
|
|
|
* - rules 提醒规则(阈值 / 涨跌幅 / 阶梯 / 价差 / 定时 / 请求失败告警)
|
2026-11-24 16:37:13 +08:00
|
|
|
|
* - email 邮箱 SMTP 配置
|
|
|
|
|
|
* - desktop Windows 桌面通知开关
|
|
|
|
|
|
* - monitor 全局轮询与静默时段
|
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
|
|
const path = require('node:path');
|
2026-11-24 17:22:08 +08:00
|
|
|
|
const fs = require('node:fs');
|
2026-11-24 16:37:13 +08:00
|
|
|
|
const {
|
2026-11-24 17:22:08 +08:00
|
|
|
|
deepMerge, readJson, writeJson, uid, toNum, maskSecret, log, isPlainObject, ensureDir, nowText,
|
2026-11-24 16:37:13 +08:00
|
|
|
|
} = require('./util');
|
|
|
|
|
|
const { PRESETS, buildInstrument } = require('./presets');
|
|
|
|
|
|
|
|
|
|
|
|
const ROOT = path.resolve(__dirname, '..');
|
|
|
|
|
|
const CONFIG_FILE = path.join(ROOT, 'config', 'config.json');
|
2026-11-24 17:22:08 +08:00
|
|
|
|
/** 导入前的自动备份目录,最多保留 20 份 */
|
|
|
|
|
|
const BACKUP_DIR = path.join(ROOT, 'config', 'backups');
|
|
|
|
|
|
const MAX_BACKUPS = 20;
|
2026-11-24 16:37:13 +08:00
|
|
|
|
const SCHEMA_VERSION = 1;
|
|
|
|
|
|
|
|
|
|
|
|
/** 允许的通知渠道 */
|
|
|
|
|
|
const CHANNEL_KEYS = ['desktop', 'email', 'webhook'];
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 默认配置工厂(每次返回全新对象,避免共享引用)
|
|
|
|
|
|
* @returns {object}
|
|
|
|
|
|
*/
|
|
|
|
|
|
function defaultConfig() {
|
|
|
|
|
|
const instruments = ['autd', 'au9999', 'czb-jcj'].map((key, index) => {
|
|
|
|
|
|
const base = buildInstrument(key);
|
|
|
|
|
|
return {
|
|
|
|
|
|
id: `ins_${key.replace(/[^a-z0-9]/gi, '')}`,
|
|
|
|
|
|
enabled: index < 3,
|
|
|
|
|
|
...base,
|
|
|
|
|
|
};
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
|
version: SCHEMA_VERSION,
|
|
|
|
|
|
app: {
|
|
|
|
|
|
port: 8787,
|
|
|
|
|
|
host: '127.0.0.1',
|
|
|
|
|
|
token: '',
|
|
|
|
|
|
openBrowser: true,
|
|
|
|
|
|
},
|
|
|
|
|
|
monitor: {
|
|
|
|
|
|
running: true,
|
|
|
|
|
|
/** 新增品种时的默认刷新频率(秒) */
|
|
|
|
|
|
defaultIntervalSec: 30,
|
|
|
|
|
|
/** 启动时若规则条件已满足,是否也提醒一次 */
|
|
|
|
|
|
alertOnFirstCheck: false,
|
|
|
|
|
|
/** 静默时段:命中时不发桌面通知(邮件照发) */
|
|
|
|
|
|
quietHours: { enabled: false, range: '23:00-07:00', desktopOnly: true },
|
|
|
|
|
|
},
|
|
|
|
|
|
channels: {
|
|
|
|
|
|
/** 规则没有单独指定渠道时,用这里的默认渠道 */
|
|
|
|
|
|
onTrigger: ['desktop'],
|
|
|
|
|
|
},
|
|
|
|
|
|
desktop: {
|
|
|
|
|
|
enabled: true,
|
|
|
|
|
|
},
|
|
|
|
|
|
email: {
|
|
|
|
|
|
enabled: false,
|
|
|
|
|
|
host: '',
|
|
|
|
|
|
port: 465,
|
|
|
|
|
|
secure: true,
|
|
|
|
|
|
user: '',
|
|
|
|
|
|
pass: '',
|
|
|
|
|
|
from: '',
|
|
|
|
|
|
to: [],
|
|
|
|
|
|
subjectPrefix: '【金价提醒】',
|
|
|
|
|
|
/** 邮件正文附带行情快照 */
|
|
|
|
|
|
withSnapshot: true,
|
|
|
|
|
|
},
|
|
|
|
|
|
webhook: {
|
|
|
|
|
|
enabled: false,
|
|
|
|
|
|
/** 推送地址:钉钉机器人的 https://oapi.dingtalk.com/robot/send?access_token=... */
|
|
|
|
|
|
url: '',
|
|
|
|
|
|
/** 报文格式:generic=内置 JSON,dingtalk=钉钉机器人 markdown */
|
|
|
|
|
|
format: 'generic',
|
|
|
|
|
|
/** 钉钉「加签」密钥(H5 安全设置里那一串 SEC 开头的内容) */
|
|
|
|
|
|
secret: '',
|
|
|
|
|
|
/** 钉钉「自定义关键词」安全设置要求的词,会自动拼进消息标题 */
|
|
|
|
|
|
keyword: '',
|
|
|
|
|
|
/** 钉钉 @ 手机号 */
|
|
|
|
|
|
atMobiles: [],
|
|
|
|
|
|
/** 钉钉是否 @所有人 */
|
|
|
|
|
|
mentionAll: false,
|
|
|
|
|
|
},
|
|
|
|
|
|
instruments,
|
|
|
|
|
|
rules: [
|
|
|
|
|
|
{
|
|
|
|
|
|
id: 'rule_autd_above',
|
|
|
|
|
|
name: '黄金T+D 上破 800 元/克(示例规则)',
|
|
|
|
|
|
enabled: true,
|
|
|
|
|
|
type: 'threshold',
|
|
|
|
|
|
instrumentId: instruments[0].id,
|
|
|
|
|
|
direction: 'above',
|
|
|
|
|
|
value: 800,
|
|
|
|
|
|
cooldownSec: 1800,
|
|
|
|
|
|
repeatIntervalSec: 0,
|
|
|
|
|
|
channels: ['desktop'],
|
|
|
|
|
|
note: '价格由下往上突破阈值时提醒一次',
|
|
|
|
|
|
},
|
|
|
|
|
|
{
|
|
|
|
|
|
id: 'rule_spread_czb_autd',
|
|
|
|
|
|
name: '浙商积存金与黄金T+D 价差≥3元(示例规则)',
|
|
|
|
|
|
enabled: true,
|
|
|
|
|
|
type: 'spread',
|
|
|
|
|
|
instrumentId: instruments[2].id,
|
|
|
|
|
|
compareInstrumentId: instruments[0].id,
|
|
|
|
|
|
mode: 'abs',
|
|
|
|
|
|
direction: 'abs',
|
|
|
|
|
|
value: 3,
|
|
|
|
|
|
cooldownSec: 1800,
|
|
|
|
|
|
repeatIntervalSec: 0,
|
|
|
|
|
|
channels: ['desktop'],
|
|
|
|
|
|
note: '两个品种价差(绝对值)超过阈值时提醒',
|
|
|
|
|
|
},
|
|
|
|
|
|
],
|
|
|
|
|
|
manualPrices: {},
|
|
|
|
|
|
};
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/** 数值兜底 */
|
|
|
|
|
|
function clampNumber(value, fallback, min, max) {
|
|
|
|
|
|
const n = toNum(value);
|
|
|
|
|
|
if (n === null) return fallback;
|
|
|
|
|
|
return Math.min(max, Math.max(min, n));
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/** 归一化单个监控项 */
|
|
|
|
|
|
function normalizeInstrument(raw, index) {
|
|
|
|
|
|
const name = String(raw?.name || `品种${index + 1}`).slice(0, 60);
|
|
|
|
|
|
const source = ['sina', 'rijinjia', 'http-json', 'manual'].includes(raw?.source) ? raw.source : 'sina';
|
|
|
|
|
|
return {
|
|
|
|
|
|
id: raw?.id ? String(raw.id) : uid('ins'),
|
|
|
|
|
|
name,
|
|
|
|
|
|
source,
|
|
|
|
|
|
sourceOptions: isPlainObject(raw?.sourceOptions) ? raw.sourceOptions : {},
|
|
|
|
|
|
unit: String(raw?.unit || '元/克').slice(0, 12),
|
|
|
|
|
|
digits: Math.round(clampNumber(raw?.digits, 2, 0, 4)),
|
|
|
|
|
|
// 手动录入类品种允许 intervalSec = 0(不自动轮询,由用户推价)
|
|
|
|
|
|
intervalSec: Math.round(clampNumber(raw?.intervalSec, 30, source === 'manual' ? 0 : 5, 86400)),
|
|
|
|
|
|
enabled: raw?.enabled !== false,
|
|
|
|
|
|
presetKey: raw?.presetKey ? String(raw.presetKey) : '',
|
|
|
|
|
|
note: String(raw?.note || '').slice(0, 200),
|
|
|
|
|
|
};
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/** 归一化单条规则 */
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 归一化「定时提醒」的时刻列表
|
|
|
|
|
|
* 兼容数组与逗号/空格分隔的字符串,只保留合法的 HH:mm,去重后按时间排序
|
|
|
|
|
|
* @param {Array<string>|string} raw 原始值
|
|
|
|
|
|
* @returns {string[]} 形如 ["09:00","15:30"]
|
|
|
|
|
|
*/
|
|
|
|
|
|
function normalizeScheduleTimes(raw) {
|
|
|
|
|
|
const list = Array.isArray(raw)
|
|
|
|
|
|
? raw
|
|
|
|
|
|
: String(raw || '').split(/[,,\s]+/);
|
|
|
|
|
|
const seen = new Set();
|
|
|
|
|
|
const valid = [];
|
|
|
|
|
|
for (const item of list) {
|
|
|
|
|
|
const text = String(item || '').trim();
|
|
|
|
|
|
if (!/^\d{1,2}:\d{2}$/.test(text)) continue;
|
|
|
|
|
|
const [h, m] = text.split(':').map(Number);
|
|
|
|
|
|
if (h > 23 || m > 59) continue;
|
|
|
|
|
|
const hhmm = `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`;
|
|
|
|
|
|
if (seen.has(hhmm)) continue;
|
|
|
|
|
|
seen.add(hhmm);
|
|
|
|
|
|
valid.push(hhmm);
|
|
|
|
|
|
}
|
|
|
|
|
|
// 按时间先后排序,最多 12 个时刻,避免刷屏
|
|
|
|
|
|
valid.sort((a, b) => a.localeCompare(b));
|
|
|
|
|
|
return valid.slice(0, 12);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
function normalizeRule(raw, index) {
|
2026-11-24 18:01:49 +08:00
|
|
|
|
const type = ['threshold', 'change', 'spread', 'schedule', 'ladder', 'failure'].includes(raw?.type) ? raw.type : 'threshold';
|
2026-11-24 16:37:13 +08:00
|
|
|
|
const channels = Array.isArray(raw?.channels)
|
|
|
|
|
|
? raw.channels.filter((c) => CHANNEL_KEYS.includes(c))
|
|
|
|
|
|
: ['desktop'];
|
|
|
|
|
|
const direction = ['above', 'below', 'abs', 'up', 'down', 'both'].includes(raw?.direction)
|
|
|
|
|
|
? raw.direction
|
2026-11-24 18:01:49 +08:00
|
|
|
|
: (type === 'threshold' ? 'above' : type === 'ladder' ? 'up' : 'abs');
|
|
|
|
|
|
|
|
|
|
|
|
// 请求失败告警的 value 是「连续失败次数」,必须是 1 以上的整数,默认 3 次
|
|
|
|
|
|
const value = type === 'failure'
|
|
|
|
|
|
? Math.round(clampNumber(raw?.value, 3, 1, 500))
|
|
|
|
|
|
: clampNumber(raw?.value, 0, -1e9, 1e9);
|
2026-11-24 16:37:13 +08:00
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
|
id: raw?.id ? String(raw.id) : uid('rule'),
|
|
|
|
|
|
name: String(raw?.name || `规则${index + 1}`).slice(0, 80),
|
|
|
|
|
|
enabled: raw?.enabled !== false,
|
|
|
|
|
|
type,
|
|
|
|
|
|
instrumentId: String(raw?.instrumentId || ''),
|
|
|
|
|
|
compareInstrumentId: raw?.compareInstrumentId ? String(raw.compareInstrumentId) : '',
|
|
|
|
|
|
mode: raw?.mode === 'percent' ? 'percent' : 'abs',
|
|
|
|
|
|
direction,
|
2026-11-24 18:01:49 +08:00
|
|
|
|
value,
|
|
|
|
|
|
// 请求失败告警不看「次数」以外的条件,冷却固定为 0(重复频率交给 repeatIntervalSec)
|
|
|
|
|
|
cooldownSec: type === 'failure' ? 0 : Math.round(clampNumber(raw?.cooldownSec, 1800, 30, 86400 * 7)),
|
2026-11-24 16:37:13 +08:00
|
|
|
|
repeatIntervalSec: Math.round(clampNumber(raw?.repeatIntervalSec, 0, 0, 86400)),
|
|
|
|
|
|
// 涨跌幅的统计区间(秒):0 = 日内(相对昨收),>0 = 近 N 秒的滚动窗口
|
|
|
|
|
|
windowSec: Math.round(clampNumber(raw?.windowSec, 0, 0, 43200)),
|
|
|
|
|
|
// 涨跌幅的阈值口径:percent = 按百分比;amount = 按具体价格变动值(元/克等)
|
|
|
|
|
|
// 只有显式传 amount 才算具体值,老规则(缺字段)一律按百分比,行为不变
|
|
|
|
|
|
changeBasis: raw?.changeBasis === 'amount' ? 'amount' : 'percent',
|
|
|
|
|
|
// 定时提醒:每天要响的时刻("HH:mm"),到点按当前行情发一条提醒
|
|
|
|
|
|
scheduleTimes: normalizeScheduleTimes(raw?.scheduleTimes),
|
|
|
|
|
|
// 定时提醒的重复方式:daily=每天;weekday=工作日(周一至周五);weekly=每周指定几天
|
|
|
|
|
|
scheduleRepeat: ['daily', 'weekday', 'weekly'].includes(raw?.scheduleRepeat) ? raw.scheduleRepeat : 'daily',
|
|
|
|
|
|
// weekly 生效的星期,1=周一 … 7=周日
|
|
|
|
|
|
scheduleWeekdays: Array.isArray(raw?.scheduleWeekdays)
|
|
|
|
|
|
? [...new Set(raw.scheduleWeekdays
|
|
|
|
|
|
.map((n) => Math.round(Number(n)))
|
|
|
|
|
|
.filter((n) => n >= 1 && n <= 7))].sort((a, b) => a - b)
|
|
|
|
|
|
: [],
|
|
|
|
|
|
// 生效时段:"HH:mm-HH:mm",空字符串表示全天生效(支持跨零点,如 22:00-02:00)
|
|
|
|
|
|
activeRange: /^\d{1,2}:\d{2}-\d{1,2}:\d{2}$/.test(String(raw?.activeRange || '').trim())
|
|
|
|
|
|
? String(raw.activeRange).trim()
|
|
|
|
|
|
: '',
|
|
|
|
|
|
channels: channels.length ? channels : ['desktop'],
|
|
|
|
|
|
note: String(raw?.note || '').slice(0, 200),
|
|
|
|
|
|
};
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 归一化整份配置:补齐缺省值、修正越界数值、去掉无效引用
|
|
|
|
|
|
* @param {object} cfg 原始配置
|
|
|
|
|
|
* @returns {object} 归一化后的配置
|
|
|
|
|
|
*/
|
|
|
|
|
|
function normalizeConfig(cfg) {
|
|
|
|
|
|
const defaults = defaultConfig();
|
|
|
|
|
|
const merged = deepMerge(defaults, cfg || {});
|
|
|
|
|
|
|
|
|
|
|
|
// 应用基本参数
|
|
|
|
|
|
merged.app.port = Math.round(clampNumber(merged.app.port, 8787, 1, 65535));
|
|
|
|
|
|
merged.app.host = String(merged.app.host || '127.0.0.1');
|
|
|
|
|
|
merged.app.token = String(merged.app.token || '').trim();
|
|
|
|
|
|
merged.app.openBrowser = merged.app.openBrowser !== false;
|
|
|
|
|
|
|
|
|
|
|
|
// 轮询
|
|
|
|
|
|
merged.monitor.defaultIntervalSec = Math.round(clampNumber(merged.monitor.defaultIntervalSec, 30, 5, 86400));
|
|
|
|
|
|
merged.monitor.running = merged.monitor.running !== false;
|
|
|
|
|
|
merged.monitor.quietHours = deepMerge(defaults.monitor.quietHours, merged.monitor.quietHours || {});
|
|
|
|
|
|
merged.monitor.quietHours.range = String(merged.monitor.quietHours.range || '23:00-07:00');
|
|
|
|
|
|
|
|
|
|
|
|
// 通知渠道
|
|
|
|
|
|
merged.channels.onTrigger = (Array.isArray(merged.channels.onTrigger) ? merged.channels.onTrigger : [])
|
|
|
|
|
|
.filter((c) => CHANNEL_KEYS.includes(c));
|
|
|
|
|
|
if (merged.channels.onTrigger.length === 0) merged.channels.onTrigger = ['desktop'];
|
|
|
|
|
|
|
|
|
|
|
|
merged.desktop.enabled = merged.desktop.enabled !== false;
|
|
|
|
|
|
|
|
|
|
|
|
// 邮箱
|
|
|
|
|
|
merged.email.enabled = !!merged.email.enabled;
|
|
|
|
|
|
merged.email.host = String(merged.email.host || '').trim();
|
|
|
|
|
|
merged.email.port = Math.round(clampNumber(merged.email.port, 465, 1, 65535));
|
|
|
|
|
|
merged.email.secure = merged.email.secure !== false;
|
|
|
|
|
|
merged.email.user = String(merged.email.user || '').trim();
|
|
|
|
|
|
merged.email.pass = String(merged.email.pass || '');
|
|
|
|
|
|
merged.email.from = String(merged.email.from || merged.email.user || '').trim();
|
|
|
|
|
|
merged.email.to = (Array.isArray(merged.email.to) ? merged.email.to : String(merged.email.to || '').split(/[,;,;\s]+/))
|
|
|
|
|
|
.map((s) => String(s).trim())
|
|
|
|
|
|
.filter(Boolean);
|
|
|
|
|
|
merged.email.subjectPrefix = String(merged.email.subjectPrefix || '【金价提醒】');
|
|
|
|
|
|
merged.email.withSnapshot = merged.email.withSnapshot !== false;
|
|
|
|
|
|
|
|
|
|
|
|
// WebHook 推送
|
|
|
|
|
|
merged.webhook = isPlainObject(merged.webhook) ? merged.webhook : {};
|
|
|
|
|
|
merged.webhook.enabled = merged.webhook.enabled === true;
|
|
|
|
|
|
merged.webhook.url = String(merged.webhook.url || '').trim();
|
|
|
|
|
|
merged.webhook.format = ['generic', 'dingtalk'].includes(merged.webhook.format) ? merged.webhook.format : 'generic';
|
|
|
|
|
|
merged.webhook.secret = String(merged.webhook.secret || '').trim();
|
|
|
|
|
|
merged.webhook.keyword = String(merged.webhook.keyword || '').trim().slice(0, 30);
|
|
|
|
|
|
merged.webhook.atMobiles = (Array.isArray(merged.webhook.atMobiles)
|
|
|
|
|
|
? merged.webhook.atMobiles
|
|
|
|
|
|
: String(merged.webhook.atMobiles || '').split(/[,;,;\s]+/))
|
|
|
|
|
|
.map((s) => String(s).trim())
|
|
|
|
|
|
.filter(Boolean)
|
|
|
|
|
|
.slice(0, 20);
|
|
|
|
|
|
merged.webhook.mentionAll = merged.webhook.mentionAll === true;
|
|
|
|
|
|
|
|
|
|
|
|
// 监控项
|
|
|
|
|
|
merged.instruments = (Array.isArray(merged.instruments) ? merged.instruments : [])
|
|
|
|
|
|
.map(normalizeInstrument);
|
|
|
|
|
|
// 去掉重复 id
|
|
|
|
|
|
const seen = new Set();
|
|
|
|
|
|
merged.instruments = merged.instruments.filter((item) => {
|
|
|
|
|
|
if (seen.has(item.id)) return false;
|
|
|
|
|
|
seen.add(item.id);
|
|
|
|
|
|
return true;
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
// 规则:丢掉引用了不存在品种的规则
|
|
|
|
|
|
const instrumentIds = new Set(merged.instruments.map((i) => i.id));
|
|
|
|
|
|
merged.rules = (Array.isArray(merged.rules) ? merged.rules : [])
|
|
|
|
|
|
.map(normalizeRule)
|
|
|
|
|
|
.filter((rule) => {
|
|
|
|
|
|
if (!instrumentIds.has(rule.instrumentId)) return false;
|
|
|
|
|
|
if (rule.type === 'spread' && !instrumentIds.has(rule.compareInstrumentId)) return false;
|
|
|
|
|
|
return true;
|
|
|
|
|
|
});
|
|
|
|
|
|
const seenRules = new Set();
|
|
|
|
|
|
merged.rules = merged.rules.filter((rule) => {
|
|
|
|
|
|
if (seenRules.has(rule.id)) return false;
|
|
|
|
|
|
seenRules.add(rule.id);
|
|
|
|
|
|
return true;
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
// 手动价格
|
|
|
|
|
|
merged.manualPrices = isPlainObject(merged.manualPrices) ? merged.manualPrices : {};
|
|
|
|
|
|
|
|
|
|
|
|
merged.version = SCHEMA_VERSION;
|
|
|
|
|
|
return merged;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/** 当前内存中的配置 */
|
|
|
|
|
|
let current = null;
|
|
|
|
|
|
|
|
|
|
|
|
/** 从磁盘载入(首次运行会生成默认配置) */
|
|
|
|
|
|
function load() {
|
|
|
|
|
|
const fileConfig = readJson(CONFIG_FILE, null);
|
|
|
|
|
|
if (!fileConfig) {
|
|
|
|
|
|
log.info(`未找到配置文件,正在生成默认配置:${CONFIG_FILE}`);
|
|
|
|
|
|
}
|
|
|
|
|
|
current = normalizeConfig(fileConfig || {});
|
|
|
|
|
|
writeJson(CONFIG_FILE, current);
|
|
|
|
|
|
return current;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/** 取当前配置(未载入则先载入) */
|
|
|
|
|
|
function get() {
|
|
|
|
|
|
if (!current) load();
|
|
|
|
|
|
return current;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 整体替换并保存
|
|
|
|
|
|
* @param {object} next 新配置
|
|
|
|
|
|
*/
|
|
|
|
|
|
function replace(next) {
|
|
|
|
|
|
current = normalizeConfig(next);
|
|
|
|
|
|
writeJson(CONFIG_FILE, current);
|
|
|
|
|
|
return current;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 局部更新并保存
|
|
|
|
|
|
* @param {object} patch 局部配置
|
|
|
|
|
|
*/
|
|
|
|
|
|
function patch(patchData) {
|
|
|
|
|
|
// 防呆:前端回传的打码密码不应覆盖真实密码
|
|
|
|
|
|
if (patchData?.email && typeof patchData.email.pass === 'string' && /^\*+/.test(patchData.email.pass.trim())) {
|
|
|
|
|
|
delete patchData.email.pass;
|
|
|
|
|
|
}
|
|
|
|
|
|
// 同理:WebHook 加签密钥也是打码回传的
|
|
|
|
|
|
if (patchData?.webhook && typeof patchData.webhook.secret === 'string' && /^\*+/.test(patchData.webhook.secret.trim())) {
|
|
|
|
|
|
delete patchData.webhook.secret;
|
|
|
|
|
|
}
|
|
|
|
|
|
current = normalizeConfig(deepMerge(get(), patchData || {}));
|
|
|
|
|
|
writeJson(CONFIG_FILE, current);
|
|
|
|
|
|
return current;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/** 供网页使用的配置副本(敏感字段打码) */
|
|
|
|
|
|
function forClient() {
|
|
|
|
|
|
const cfg = get();
|
|
|
|
|
|
return {
|
|
|
|
|
|
...cfg,
|
|
|
|
|
|
email: {
|
|
|
|
|
|
...cfg.email,
|
|
|
|
|
|
pass: maskSecret(cfg.email.pass),
|
|
|
|
|
|
passConfigured: !!cfg.email.pass,
|
|
|
|
|
|
},
|
|
|
|
|
|
webhook: {
|
|
|
|
|
|
...cfg.webhook,
|
|
|
|
|
|
secret: maskSecret(cfg.webhook.secret),
|
|
|
|
|
|
secretConfigured: !!cfg.webhook.secret,
|
|
|
|
|
|
},
|
|
|
|
|
|
meta: {
|
|
|
|
|
|
configFile: CONFIG_FILE,
|
|
|
|
|
|
presets: PRESETS,
|
|
|
|
|
|
dataSources: require('./sources').listSources(),
|
|
|
|
|
|
},
|
|
|
|
|
|
};
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-11-24 17:22:08 +08:00
|
|
|
|
/**
|
|
|
|
|
|
* 导出配置
|
|
|
|
|
|
* @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)),
|
|
|
|
|
|
};
|
|
|
|
|
|
});
|
2026-11-24 16:37:13 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
|
|
ROOT,
|
|
|
|
|
|
CONFIG_FILE,
|
2026-11-24 17:22:08 +08:00
|
|
|
|
BACKUP_DIR,
|
2026-11-24 16:37:13 +08:00
|
|
|
|
defaultConfig,
|
|
|
|
|
|
normalizeConfig,
|
|
|
|
|
|
load,
|
|
|
|
|
|
get,
|
|
|
|
|
|
replace,
|
|
|
|
|
|
patch,
|
|
|
|
|
|
forClient,
|
|
|
|
|
|
exportFile,
|
2026-11-24 17:22:08 +08:00
|
|
|
|
backupCurrent,
|
|
|
|
|
|
listBackups,
|
2026-11-24 16:37:13 +08:00
|
|
|
|
};
|