feat: 初始版本

This commit is contained in:
2026-11-24 16:37:13 +08:00
parent 1ec3657d18
commit 9a23cd1d32
23 changed files with 6727 additions and 0 deletions
+318
View File
@@ -0,0 +1,318 @@
/**
* HTTP 服务:提供配置网页 + 一组本地 JSON 接口。
* 默认只监听 127.0.0.1(本机访问),如需局域网访问请在配置里改 host 并设置 token。
*/
const path = require('node:path');
const express = require('express');
const store = require('./config-store');
const { Monitor } = require('./monitor');
const notify = require('./notify');
const sources = require('./sources');
const { buildInstrument } = require('./presets');
const { uid, toNum, log, nowText } = require('./util');
/**
* 创建 Express 应用
* @param {{monitor: Monitor, store: typeof store}} deps
* @returns {import('express').Express}
*/
function createApp({ monitor }) {
const app = express();
app.use(express.json({ limit: '1mb' }));
app.use(express.static(path.join(store.ROOT, 'public'), { extensions: ['html'] }));
// ---- 访问令牌校验(仅当配置了 token)----
app.use('/api', (req, res, next) => {
const token = store.get().app.token;
if (!token) return next();
const provided = req.get('x-token') || req.query.token || '';
if (provided === token) return next();
res.status(401).json({ ok: false, error: '访问令牌无效,请在请求头带上 x-token' });
});
/** 统一包装异步路由的错误 */
const wrap = (fn) => (req, res) => Promise.resolve(fn(req, res)).catch((err) => {
log.error(`${req.method} ${req.path} 处理失败:`, err.message);
if (!res.headersSent) res.status(500).json({ ok: false, error: err.message });
});
/** 返回完整状态(行情 + 配置 + 提醒) */
const fullState = () => ({ ok: true, ...monitor.getState(), config: store.forClient() });
// ---------------- 状态 ----------------
app.get('/api/state', wrap(async (req, res) => {
res.json(fullState());
}));
app.get('/api/health', wrap(async (req, res) => {
res.json({ ok: true, node: process.version, time: nowText(), running: monitor.running });
}));
// ---------------- 配置 ----------------
app.get('/api/config', wrap(async (req, res) => {
res.json({ ok: true, config: store.forClient() });
}));
app.put('/api/config', wrap(async (req, res) => {
const patchData = req.body || {};
// 端口/监听地址变动需要重启,其它配置即时生效
store.patch(patchData);
monitor.reschedule();
res.json({ ok: true, ...fullState() });
}));
app.get('/api/config/export', wrap(async (req, res) => {
res.setHeader('Content-Disposition', `attachment; filename="gold-price-watcher-config-${Date.now()}.json"`);
res.json(store.exportFile());
}));
app.post('/api/config/import', wrap(async (req, res) => {
const data = req.body?.config || req.body;
if (!data || typeof data !== 'object') throw new Error('导入内容不是合法 JSON 对象');
store.replace(data);
monitor.reschedule();
res.json({ ok: true, ...fullState() });
}));
// ---------------- 监控品种 ----------------
app.post('/api/instruments', wrap(async (req, res) => {
const body = req.body || {};
const presetKey = String(body.presetKey || '').trim();
let base = null;
if (presetKey) {
base = buildInstrument(presetKey, {
name: body.name,
unit: body.unit,
digits: body.digits,
intervalSec: body.intervalSec,
sourceOptions: body.sourceOptions,
});
if (!base) throw new Error(`未知预设品种:${presetKey}`);
} else {
if (!body.name) throw new Error('请填写品种名称');
if (!body.source) throw new Error('请选择数据源');
base = {
name: String(body.name),
source: String(body.source),
sourceOptions: body.sourceOptions || {},
unit: body.unit || '元/克',
digits: toNum(body.digits) ?? 2,
intervalSec: toNum(body.intervalSec) ?? store.get().monitor.defaultIntervalSec,
presetKey: '',
note: body.note || '',
};
}
const cfg = store.get();
const instrument = {
id: uid('ins'),
enabled: body.enabled !== false,
...base,
};
store.patch({ instruments: [...cfg.instruments, instrument] });
monitor.reschedule();
// 新增后立刻抓一次,页面马上有数据
monitor.tick(instrument.id, { force: true }).catch(() => {});
res.json({ ok: true, ...fullState() });
}));
app.put('/api/instruments/:id', wrap(async (req, res) => {
const id = req.params.id;
const cfg = store.get();
const target = cfg.instruments.find((i) => i.id === id);
if (!target) throw new Error('品种不存在');
const body = req.body || {};
const next = cfg.instruments.map((item) => (item.id === id ? {
...item,
...('name' in body ? { name: String(body.name || item.name) } : {}),
...('unit' in body ? { unit: String(body.unit || item.unit) } : {}),
...('digits' in body ? { digits: toNum(body.digits) ?? item.digits } : {}),
...('intervalSec' in body ? { intervalSec: toNum(body.intervalSec) ?? item.intervalSec } : {}),
...('enabled' in body ? { enabled: !!body.enabled } : {}),
...('source' in body ? { source: String(body.source || item.source) } : {}),
...('sourceOptions' in body ? { sourceOptions: body.sourceOptions || {} } : {}),
} : item));
store.patch({ instruments: next });
monitor.reschedule();
if (body.enabled !== false) monitor.tick(id, { force: true }).catch(() => {});
res.json({ ok: true, ...fullState() });
}));
app.delete('/api/instruments/:id', wrap(async (req, res) => {
const cfg = store.get();
const id = req.params.id;
const nextInstruments = cfg.instruments.filter((i) => i.id !== id);
// 顺带删掉引用了这个品种的规则
const nextRules = cfg.rules.filter((r) => r.instrumentId !== id && r.compareInstrumentId !== id);
store.patch({ instruments: nextInstruments, rules: nextRules });
monitor.reschedule();
res.json({ ok: true, ...fullState() });
}));
// 手动录价(manual 数据源,或临时覆盖任意品种)
app.post('/api/instruments/:id/manual', wrap(async (req, res) => {
const price = toNum(req.body?.price);
if (!price || price <= 0) throw new Error('价格必须为正数');
const prevClose = toNum(req.body?.prevClose);
await monitor.setManualPrice(req.params.id, price, prevClose && prevClose > 0 ? prevClose : null);
res.json({ ok: true, ...fullState() });
}));
// 单独测试某品种的抓取结果
app.post('/api/instruments/:id/test', wrap(async (req, res) => {
const inst = store.get().instruments.find((i) => i.id === req.params.id);
if (!inst) throw new Error('品种不存在');
try {
const quote = await sources.fetchQuote(inst, { getManualPrice: (id) => monitor.getManualPrice(id) });
res.json({ ok: true, quote, detail: `抓取成功:${quote.price} ${inst.unit}` });
} catch (err) {
res.json({ ok: false, error: err.message });
}
}));
// 保存前先试抓一次(新增品种时用,不写配置)
app.post('/api/test/source', wrap(async (req, res) => {
const body = req.body || {};
const inst = {
id: 'preview',
name: body.name || '预览品种',
source: body.source,
sourceOptions: body.sourceOptions || {},
unit: body.unit || '元/克',
};
try {
const quote = await sources.fetchQuote(inst, { getManualPrice: () => null });
res.json({
ok: true,
detail: `抓取成功:${quote.price} ${inst.unit}${quote.changePercent !== null ? `(${quote.changePercent > 0 ? '+' : ''}${quote.changePercent}%)` : ''}`,
});
} catch (err) {
res.json({ ok: false, error: err.message });
}
}));
// ---------------- 提醒规则 ----------------
app.post('/api/rules', wrap(async (req, res) => {
const body = req.body || {};
const cfg = store.get();
if (!cfg.instruments.some((i) => i.id === body.instrumentId)) throw new Error('请选择有效的监控品种');
if (body.type === 'spread' && !cfg.instruments.some((i) => i.id === body.compareInstrumentId)) {
throw new Error('价差提醒需要选择对比品种');
}
const rule = {
id: uid('rule'),
name: body.name || '未命名规则',
enabled: body.enabled !== false,
type: body.type || 'threshold',
instrumentId: body.instrumentId,
compareInstrumentId: body.compareInstrumentId || '',
mode: body.mode === 'percent' ? 'percent' : 'abs',
direction: body.direction || 'above',
value: toNum(body.value) ?? 0,
cooldownSec: toNum(body.cooldownSec) ?? 1800,
repeatIntervalSec: toNum(body.repeatIntervalSec) ?? 0,
// 涨跌幅的统计区间(秒):0=日内,>0=近 N 秒滚动窗口
windowSec: toNum(body.windowSec) ?? 0,
// 涨跌幅的阈值口径:percent=按百分比,amount=按具体价格变动值
changeBasis: body.changeBasis === 'amount' ? 'amount' : 'percent',
// 定时提醒:到点时刻、重复方式、每周生效的星期
scheduleTimes: Array.isArray(body.scheduleTimes) ? body.scheduleTimes : [],
scheduleRepeat: ['daily', 'weekday', 'weekly'].includes(body.scheduleRepeat) ? body.scheduleRepeat : 'daily',
scheduleWeekdays: Array.isArray(body.scheduleWeekdays) ? body.scheduleWeekdays : [],
// 生效时段("HH:mm-HH:mm",空=全天)
activeRange: String(body.activeRange || '').trim(),
channels: body.channels || ['desktop'],
note: body.note || '',
};
store.patch({ rules: [...cfg.rules, rule] });
res.json({ ok: true, ...fullState() });
}));
app.put('/api/rules/:id', wrap(async (req, res) => {
const cfg = store.get();
const id = req.params.id;
if (!cfg.rules.some((r) => r.id === id)) throw new Error('规则不存在');
const body = req.body || {};
const next = cfg.rules.map((r) => (r.id === id ? { ...r, ...body, id } : r));
store.patch({ rules: next });
res.json({ ok: true, ...fullState() });
}));
app.delete('/api/rules/:id', wrap(async (req, res) => {
const cfg = store.get();
store.patch({ rules: cfg.rules.filter((r) => r.id !== req.params.id) });
res.json({ ok: true, ...fullState() });
}));
// ---------------- 运行控制 ----------------
app.post('/api/monitor', wrap(async (req, res) => {
const running = req.body?.running !== false;
store.patch({ monitor: { running } });
if (running) monitor.start();
else monitor.stop();
res.json({ ok: true, ...fullState() });
}));
app.post('/api/refresh', wrap(async (req, res) => {
await monitor.refreshAll();
res.json({ ok: true, ...fullState() });
}));
// ---------------- 渠道自检 ----------------
app.post('/api/test/desktop', wrap(async (req, res) => {
const result = notify.testDesktop();
res.json({ ok: result.ok, detail: result.detail, error: result.ok ? '' : result.detail });
}));
app.post('/api/test/email', wrap(async (req, res) => {
const cfg = store.get();
const override = req.body?.to;
const emailConfig = {
...cfg.email,
enabled: true,
to: override ? String(override).split(/[,;,;\s]+/).filter(Boolean) : cfg.email.to,
};
const result = await notify.testEmail(emailConfig);
res.json({ ok: result.ok, detail: result.detail, error: result.ok ? '' : result.detail });
}));
app.post('/api/test/webhook', wrap(async (req, res) => {
const cfg = store.get();
const body = req.body || {};
// 允许临时覆盖地址/格式/密钥,方便「先测再存」(保存后仍以配置为准)
const webhookConfig = {
...cfg.webhook,
enabled: true,
...('url' in body ? { url: String(body.url || '') } : {}),
...('format' in body ? { format: String(body.format || '') } : {}),
...('secret' in body ? { secret: String(body.secret || '') } : {}),
};
const result = await notify.testWebhook(webhookConfig);
res.json({ ok: result.ok, detail: result.detail, error: result.ok ? '' : result.detail });
}));
// ---------------- 提醒记录 ----------------
app.get('/api/alerts', wrap(async (req, res) => {
res.json({ ok: true, alerts: monitor.alerts });
}));
app.delete('/api/alerts', wrap(async (req, res) => {
monitor.clearAlerts();
res.json({ ok: true });
}));
// 前端路由兜底
app.get('*', (req, res) => {
if (req.path.startsWith('/api')) {
res.status(404).json({ ok: false, error: '接口不存在' });
return;
}
res.sendFile(path.join(store.ROOT, 'public', 'index.html'));
});
return app;
}
module.exports = { createApp };