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
+277
View File
@@ -0,0 +1,277 @@
# 金价提醒 · Gold Price Watcher
一个跑在本机的 Node.js 金价监控小工具:网页里配置要盯哪些黄金品种、多久刷一次、什么条件提醒,
命中后弹 Windows 桌面通知 / 发邮件。
- 配置网页:`http://127.0.0.1:8787`
- 数据只保存在本机:`config/config.json`、`data/alerts.jsonl`
- 无云服务、无账号,进程退出即停止监控
---
## 1. 快速开始
环境要求:Windows 10/11 + Node.js 18 及以上(本项目在 Node 22 上验证)。
```bat
cd /d E:\Temp\gold-price-watcher
npm install
npm start
```
启动后会自动打开浏览器;如果没打开,手动访问 <http://127.0.0.1:8787>。
其它入口:
- `启动.bat`:双击即用(缺依赖时自动 `npm install`)
- `静默启动.vbs`:不显示黑框,适合配开机自启
- `npm run dev`:改代码时自动重启
---
## 2. 功能与页面结构
页面一共四个标签:
1. **行情看板**:每个品种一张卡片,显示最新价、涨跌幅、最高/最低、迷你走势、抓取状态与刷新频率;
可以单个启用/停用、改频率、删除;手动类品种可直接在卡片里填价格。
2. **提醒规则**:价格阈值、涨跌幅(统计区间可选「日内」或「近 N 分钟」、阈值可按百分比或具体变动值)、
两品种价差三类规则,还可限定生效时段,可单独设置渠道与冷却时间;规则列表按名称自动排序
(中文按拼音、数字按大小,「涨跌 2%」排在「涨跌 10%」前面)。
3. **通知设置**:桌面通知开关与测试、SMTP 邮箱配置与测试、WebHook 推送(内置 JSON / 钉钉机器人)、默认渠道、静默时段、端口/令牌。
4. **提醒记录**:最近 200 条触发记录(渠道是否送达一目了然),历史同时写入 `data/alerts.jsonl`。
---
## 3. 可选的黄金品种
内置目录(「添加品种」弹窗里选):
| 分类 | 品种 | 数据来源 |
| --- | --- | --- |
| 上金所 | 黄金T+D、mAu(T+D)、黄金9999、黄金9995、黄金100g | 新浪财经行情 |
| 期货 | 沪金主连(AU0) | 新浪财经行情 |
| 国际 | 伦敦金(XAU)、纽约黄金(GC) | 新浪财经行情 |
| 银行积存金 | **浙商银行积存金**、工行、民生、广发、兴业、中信 | 公开积存金行情页(约每分钟更新) |
| 自定义 | 自定义 HTTP JSON 接口 / 自定义新浪代码 / 手动录入 | 自行指定 |
说明:
- 「浙商黄金」对应浙商银行「财富金积存」报价,取自公开行情页(`rijinjia.com/jicunjin`),
不是银行官方接口,页面改版可能失效;失效时卡片会标红并给出原因。
- 银行渠道若拿不到报价,可改用「手动录入价格」品种:在卡片里输入当前价格,
同样能触发阈值与价差提醒(也支持 `POST /api/instruments/:id/manual` 让脚本推送)。
- 自定义 HTTP 接口:填 URL + 价格字段路径(如 `data.price`),可选昨收字段路径。
默认已经建好 3 个品种:黄金T+D、黄金9999、浙商银行积存金。
---
## 4. 提醒规则怎么写
四种类型:
- **价格阈值**:`价格 ≥ 阈值`(上破)或 `价格 ≤ 阈值`(下破)。
- **涨跌幅**:涨幅 / 跌幅 / 涨跌幅绝对值 ≥ 阈值,**阈值可以按百分比,也可以直接写具体变动值**:
- 阈值口径「涨跌幅百分比(%)」:填 0.5 就是「涨/跌 0.5%」;
- 阈值口径「具体变动值(元/克)」:填 3 就是「涨/跌 3 元/克」(单位跟随品种,伦敦金为美元/盎司);
- **可以指定统计区间**:
- 「日内」:相对昨收计算(依赖数据源是否给出昨收);
- 「近 5 / 10 / 15 / 30 分钟、1 / 2 / 4 小时」或「自定义 N 分钟」:用本机缓存的行情点回算滚动区间,
例如「近 10 分钟涨幅 ≥ 0.5%」或者「近 10 分钟涨 ≥ 3 元/克」,适合盯短线急涨急跌。窗口越长,需要的行情点越多;
本机按品种保留最近 72 小时、最多 2400 个点,并定期写入 `data/history.json`,重启后接着算。
- **价差提醒**:两个同单位品种的价差 —— 绝对价差(元/克)或相对价差(%),
方向可选「绝对差」「前者高于后者」「后者高于前者」。典型用法:浙商积存金与黄金T+D 的价差走阔。
- **定时提醒**:到点按当时的行情发一条通知,不看价格条件。适合「每天 09:00 报一下开盘价」「工作日 15:30 收盘播报」。
- 提醒时刻:`09:00, 15:30`(24 小时制,逗号分隔,最多 12 个,会自动去重排序);
- 重复方式:「每天」「工作日(周一至周五)」「每周指定几天」(勾选周一~周日,至少选一天);
- 同一时刻每天只响一次(去重状态存在 `data/rule-state.json`,重启后不会重复);
- 程序当时没运行的时刻不会补发;到点时刻有 2 分钟容错窗口,抓取抖动不会漏掉整分钟。
每条规则还可以限定**生效时段**(如 `09:00-11:30`、`21:00-23:00`,支持跨零点写 `22:00-02:00`,留空表示全天)。
时段外不评估、不发提醒;进入时段后若条件成立,会正常提醒一次。
触发行为:
- **边沿触发**:只有从「不满足」变成「满足」时才提醒,来回震荡不会重复轰炸。
- **冷却时间**:同一个规则+品种在冷却时间内不会再提醒(默认 1800 秒)。
- **持续满足重复提醒**:把「重复间隔」设为大于 0(如 600 秒),条件一直满足时按间隔重复提醒。
- **启动时已满足**:默认不打扰;设置页勾选「启动时已满足条件也提醒一次」可改为提醒。
(规则状态会存到 `data/rule-state.json`,重启不会误报)
- **窗口数据未攒够**:「近 N 分钟」规则在启动初期历史点不够时会先跳过(日志里提示一次),
等攒够窗口长度后自动开始评估,不会因此丢掉随后的真实突破。
---
## 5. 通知渠道
### 桌面通知
直接调用 Windows 原生 Toast(通过系统自带 PowerShell 5.1 的 WinRT 接口),不额外装 exe。
在「通知设置」里点「发送测试通知」验证;如果没弹出,请检查
`设置 → 系统 → 通知` 是否允许通知、是否开启了「专注助手 / 勿扰」。
### 邮箱提醒
在「通知设置 → 邮箱提醒」填 SMTP:
| 邮箱 | 服务器 | 端口 | 加密 |
| --- | --- | --- | --- |
| QQ 邮箱 | smtp.qq.com | 465 | SSL |
| 163 邮箱 | smtp.163.com | 465 | SSL |
| 企业邮箱 | 按服务商文档 | 465 或 587 | SSL / STARTTLS |
密码栏要填**授权码**(在邮箱网页端「设置 → 账户 → POP3/SMTP 服务」里生成),不是登录密码。
填完勾选「启用」→ 保存设置 → 点「发送测试邮件」,收到即成功。
然后在规则里勾上「邮件」渠道(或在默认渠道里勾选邮件)。
静默时段(默认 23:00–07:00,可关)命中时只跳过桌面通知,邮件照发。
### WebHook 推送
在「通知设置 → WebHook 推送」里填地址、选格式,勾「启用」保存,再点「发送测试推送」验证。
**格式一:内置 JSON(自建服务 / 自动化脚本用)**
向你的地址 POST 一个固定结构的 JSON,`Content-Type: application/json`:
```json
{
"event": "gold_price_alert",
"title": "黄金T+D 上破 800.00 元/克",
"message": "最新价 801.20 元/克,已上破阈值 800.00 元/克;日内 +0.62%。",
"markdown": "### 黄金T+D 上破 800.00 元/克\n\n- 最新价:**801.20 元/克**\n…",
"at": "2026-11-24 13:17:43",
"rule": { "id": "rule_xxx", "name": "黄金T+D 上破 800" },
"lines": ["黄金T+D 最新价:**801.20 元/克**", "触发条件:价格上破 800.00 元/克"],
"source": "gold-price-watcher"
}
```
成功判定:HTTP 2xx;失败会在「提醒记录」里标为 `✕` 并带原因(连接被拒绝、超时、HTTP 4xx/5xx 等)。
**格式二:钉钉机器人(markdown)**
1. 钉钉群 → 群设置 → 智能群助手 → 添加机器人 → 自定义 → 复制 Webhook 地址
(形如 `https://oapi.dingtalk.com/robot/send?access_token=xxx`);
2. 安全设置若选「加签」,把 `SEC` 开头的密钥填进「钉钉加签密钥」,工具会自动拼接 `timestamp` 与 `sign`;
3. 安全设置若选「自定义关键词」,把那个词填进「钉钉自定义关键词」,工具会自动把它拼到消息标题开头;
两者可只开一个(都开的话请两处都填);
4. 想看群成员就填「钉钉 @ 手机号」,需要全体提醒再勾「@所有人」;
5. 选格式「钉钉机器人(markdown)」→ 保存 → 发送测试推送。
钉钉是 HTTP 200 也可能带 `errcode` 报错,工具会解析并给出中文提示,
例如 `310000` 会进一步区分「签名不匹配」还是「关键词不匹配」、`130101` 每分钟超过 20 条被限流、`300001` token 无效。
每条规则都能单独勾选 WebHook;规则没指定渠道时用「全局默认渠道」。静默时段只影响桌面通知,WebHook 照推。
---
## 6. 开机自启(可选)
1. `Win + R` 输入 `shell:startup` 打开启动文件夹;
2. 把 `静默启动.vbs` 的快捷方式放进去即可。
或用任务计划程序:新建任务 → 触发器「登录时」→ 操作「启动程序」
程序填 `node.exe`(`where node` 可查路径),参数填 `src\index.js`,起始于填项目目录。
---
## 7. HTTP 接口(脚本/自动化用)
| 方法 | 路径 | 说明 |
| --- | --- | --- |
| GET | `/api/state` | 全部行情 + 配置 + 提醒 |
| GET | `/api/health` | 存活检查 |
| PUT | `/api/config` | 局部更新配置(对象深合并) |
| GET/POST | `/api/config/export` `/api/config/import` | 备份 / 恢复配置 |
| POST | `/api/instruments` | 新增品种(`presetKey` 或自定义字段) |
| PUT/DELETE | `/api/instruments/:id` | 修改 / 删除品种 |
| POST | `/api/instruments/:id/manual` | 手动推价 `{ "price": 781.2, "prevClose": 780 }` |
| POST | `/api/instruments/:id/test` | 试抓该品种 |
| POST | `/api/test/source` | 试抓未保存的数据源配置 |
| POST | `/api/rules`、PUT/DELETE `/api/rules/:id` | 规则增改删 |
| POST | `/api/monitor` | `{ "running": false }` 暂停 / `true` 恢复 |
| POST | `/api/refresh` | 立刻刷新全部品种 |
| POST | `/api/test/desktop`、`/api/test/email`、`/api/test/webhook` | 渠道自检(webhook 可临时传 `{url, format, secret}` 先测再存) |
| GET/DELETE | `/api/alerts` | 查询 / 清空页面提醒记录 |
示例(curl):
```bash
curl -X POST http://127.0.0.1:8787/api/instruments/ins_czbjcj/manual \
-H "Content-Type: application/json" \
-d "{\"price\": 782.5}"
```
如果在设置里配了访问令牌,所有 `/api` 请求需带 `x-token` 头(或 `?token=`)。
---
## 8. 配置文件说明
`config/config.json` 主要字段:
```jsonc
{
"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": "", "to": [] },
"webhook": { "enabled": false, "url": "", "format": "generic", "secret": "", "keyword": "", "atMobiles": [], "mentionAll": false },
"instruments": [], // 监控品种:source + sourceOptions + intervalSec
"rules": [], // 规则:type/instrumentId/direction/value/changeBasis/windowSec/activeRange/cooldownSec/channels
"manualPrices": {} // 手动录入的价格
}
```
改端口/监听地址需要重启进程,其它配置网页保存后即时生效。
`config.json` 里含邮箱授权码,请勿外传;页面导出配置同样含真实密码。
---
## 9. 常见问题
- **端口被占用**:改 `config.json` 的 `app.port` 后重启。
- **行情显示「抓取失败」**:非交易时段部分上金所品种会返回 0 价;勾选错误货品种也会失败;
银行积存金页面改版同样会失败。卡片上会显示具体原因。
- **桌面通知没弹**:先点「发送测试通知」;仍无反应请检查系统通知开关 / 勿扰模式。
- **邮件收不到**:先确认测试邮件是否成功;QQ/163 必须用授权码,并确认 SMTP 服务已开启;
失败原因会在「提醒记录」和 `data/alerts.jsonl` 里记录。
- **数据准不准**:都来自第三方公开接口,仅供自用参考,不作为交易依据。
- **「近 N 分钟涨跌幅」一直不触发**:先确认品种已连续刷新够窗口长度(默认最多保留 72 小时行情点);
刚启动时会在日志提示「历史行情还没攒够」,攒够后自动评估。
- **WebHook 推送失败**:先在通知设置里点「发送测试推送」看具体原因;`连接被拒绝` 多为地址或端口不通,
`钉钉签名校验失败` 说明密钥填错或机器人没开加签却填了密钥,`每分钟超过 20 条` 是钉钉机器人限流,等一分钟即可。
---
## 10. 目录结构
```
gold-price-watcher/
├─ src/
│ ├─ index.js 入口(起监控 + 起 Web)
│ ├─ server.js 路由与接口
│ ├─ monitor.js 轮询引擎、规则评估、提醒分发
│ ├─ config-store.js 配置读写与归一化
│ ├─ presets.js 内置品种目录
│ ├─ util.js 小工具
│ └─ sources/
│ ├─ sina.js 新浪行情(批量聚合 + GBK 解码)
│ ├─ rijinjia.js 银行积存金行情页
│ ├─ http-json.js 自定义 JSON 接口
│ └─ manual.js 手动价格
│ └─ notify/
│ ├─ desktop.js Windows Toast
│ ├─ email.js SMTP 邮件
│ ├─ webhook.js WebHook 推送(内置 JSON / 钉钉机器人)
│ └─ index.js 渠道调度
├─ public/ 配置网页(纯静态,无构建)
├─ config/config.json 配置文件
└─ data/ 提醒日志(alerts.jsonl)、规则状态(rule-state.json)、行情历史(history.json)
```
> 数据源均为公开非官方接口,可能因对方改版或限流失效;本项目仅本地自用,不构成投资建议。
+853
View File
@@ -0,0 +1,853 @@
{
"name": "gold-price-watcher",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "gold-price-watcher",
"version": "1.0.0",
"dependencies": {
"express": "^4.19.2",
"nodemailer": "^6.9.16"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/accepts": {
"version": "1.3.8",
"resolved": "https://registry.npmmirror.com/accepts/-/accepts-1.3.8.tgz",
"integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==",
"license": "MIT",
"dependencies": {
"mime-types": "~2.1.34",
"negotiator": "0.6.3"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/array-flatten": {
"version": "1.1.1",
"resolved": "https://registry.npmmirror.com/array-flatten/-/array-flatten-1.1.1.tgz",
"integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==",
"license": "MIT"
},
"node_modules/body-parser": {
"version": "1.20.9",
"resolved": "https://registry.npmmirror.com/body-parser/-/body-parser-1.20.9.tgz",
"integrity": "sha512-FISIQxV5u91Y9gvuFq3q/tA/qTqLJn3AhRcEvyozyhJTh5OBFFtv827AdHU7Rbyct4r+Ba1/99oFa1Y3yuFsdw==",
"license": "MIT",
"dependencies": {
"bytes": "~3.1.2",
"content-type": "~1.0.5",
"debug": "2.6.9",
"depd": "2.0.0",
"destroy": "~1.2.0",
"http-errors": "~2.0.1",
"iconv-lite": "~0.4.24",
"on-finished": "~2.4.1",
"qs": "~6.16.0",
"raw-body": "~2.5.3",
"type-is": "~1.6.18",
"unpipe": "~1.0.0"
},
"engines": {
"node": ">= 0.8",
"npm": "1.2.8000 || >= 1.4.16"
}
},
"node_modules/bytes": {
"version": "3.1.2",
"resolved": "https://registry.npmmirror.com/bytes/-/bytes-3.1.2.tgz",
"integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/call-bind-apply-helpers": {
"version": "1.0.2",
"resolved": "https://registry.npmmirror.com/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"function-bind": "^1.1.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/call-bound": {
"version": "1.0.4",
"resolved": "https://registry.npmmirror.com/call-bound/-/call-bound-1.0.4.tgz",
"integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.2",
"get-intrinsic": "^1.3.0"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/content-disposition": {
"version": "0.5.4",
"resolved": "https://registry.npmmirror.com/content-disposition/-/content-disposition-0.5.4.tgz",
"integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==",
"license": "MIT",
"dependencies": {
"safe-buffer": "5.2.1"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/content-type": {
"version": "1.0.5",
"resolved": "https://registry.npmmirror.com/content-type/-/content-type-1.0.5.tgz",
"integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/cookie": {
"version": "0.7.2",
"resolved": "https://registry.npmmirror.com/cookie/-/cookie-0.7.2.tgz",
"integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/cookie-signature": {
"version": "1.0.7",
"resolved": "https://registry.npmmirror.com/cookie-signature/-/cookie-signature-1.0.7.tgz",
"integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==",
"license": "MIT"
},
"node_modules/debug": {
"version": "2.6.9",
"resolved": "https://registry.npmmirror.com/debug/-/debug-2.6.9.tgz",
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
"license": "MIT",
"dependencies": {
"ms": "2.0.0"
}
},
"node_modules/depd": {
"version": "2.0.0",
"resolved": "https://registry.npmmirror.com/depd/-/depd-2.0.0.tgz",
"integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/destroy": {
"version": "1.2.0",
"resolved": "https://registry.npmmirror.com/destroy/-/destroy-1.2.0.tgz",
"integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==",
"license": "MIT",
"engines": {
"node": ">= 0.8",
"npm": "1.2.8000 || >= 1.4.16"
}
},
"node_modules/dunder-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmmirror.com/dunder-proto/-/dunder-proto-1.0.1.tgz",
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.1",
"es-errors": "^1.3.0",
"gopd": "^1.2.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/ee-first": {
"version": "1.1.1",
"resolved": "https://registry.npmmirror.com/ee-first/-/ee-first-1.1.1.tgz",
"integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
"license": "MIT"
},
"node_modules/encodeurl": {
"version": "2.0.3",
"resolved": "https://registry.npmmirror.com/encodeurl/-/encodeurl-2.0.3.tgz",
"integrity": "sha512-mIteYONiEfc4xWf2F1WXovh1c8npzS00vNeiUPdwFF+QlVJni+gNvpQltLMQhob8rew/bWWc/bGTuUr0EUGt0w==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/es-define-property": {
"version": "1.0.1",
"resolved": "https://registry.npmmirror.com/es-define-property/-/es-define-property-1.0.1.tgz",
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-errors": {
"version": "1.3.0",
"resolved": "https://registry.npmmirror.com/es-errors/-/es-errors-1.3.0.tgz",
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-object-atoms": {
"version": "1.1.2",
"resolved": "https://registry.npmmirror.com/es-object-atoms/-/es-object-atoms-1.1.2.tgz",
"integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/escape-html": {
"version": "1.0.3",
"resolved": "https://registry.npmmirror.com/escape-html/-/escape-html-1.0.3.tgz",
"integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
"license": "MIT"
},
"node_modules/etag": {
"version": "1.8.1",
"resolved": "https://registry.npmmirror.com/etag/-/etag-1.8.1.tgz",
"integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/express": {
"version": "4.22.3",
"resolved": "https://registry.npmmirror.com/express/-/express-4.22.3.tgz",
"integrity": "sha512-Bdcs4+3qlpVlx2NRn6fgX2Ue2/gGRaPeawebgclM0ERSCqDpA+owF1fdPwjJUTAJWMTuAaxjDf+hzb0/4eKvvw==",
"license": "MIT",
"dependencies": {
"accepts": "~1.3.8",
"array-flatten": "1.1.1",
"body-parser": "~1.20.5",
"content-disposition": "~0.5.4",
"content-type": "~1.0.4",
"cookie": "~0.7.1",
"cookie-signature": "~1.0.6",
"debug": "2.6.9",
"depd": "2.0.0",
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"etag": "~1.8.1",
"finalhandler": "~1.3.1",
"fresh": "~0.5.2",
"http-errors": "~2.0.0",
"merge-descriptors": "1.0.3",
"methods": "~1.1.2",
"on-finished": "~2.4.1",
"parseurl": "~1.3.3",
"path-to-regexp": "~0.1.13",
"proxy-addr": "~2.0.7",
"qs": "~6.16.0",
"range-parser": "~1.2.1",
"safe-buffer": "5.2.1",
"send": "~0.19.0",
"serve-static": "~1.16.2",
"setprototypeof": "1.2.0",
"statuses": "~2.0.1",
"type-is": "~1.6.18",
"utils-merge": "1.0.1",
"vary": "~1.1.2"
},
"engines": {
"node": ">= 0.10.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/finalhandler": {
"version": "1.3.2",
"resolved": "https://registry.npmmirror.com/finalhandler/-/finalhandler-1.3.2.tgz",
"integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==",
"license": "MIT",
"dependencies": {
"debug": "2.6.9",
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"on-finished": "~2.4.1",
"parseurl": "~1.3.3",
"statuses": "~2.0.2",
"unpipe": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/forwarded": {
"version": "0.2.0",
"resolved": "https://registry.npmmirror.com/forwarded/-/forwarded-0.2.0.tgz",
"integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/fresh": {
"version": "0.5.2",
"resolved": "https://registry.npmmirror.com/fresh/-/fresh-0.5.2.tgz",
"integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/function-bind": {
"version": "1.1.2",
"resolved": "https://registry.npmmirror.com/function-bind/-/function-bind-1.1.2.tgz",
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-intrinsic": {
"version": "1.3.0",
"resolved": "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.2",
"es-define-property": "^1.0.1",
"es-errors": "^1.3.0",
"es-object-atoms": "^1.1.1",
"function-bind": "^1.1.2",
"get-proto": "^1.0.1",
"gopd": "^1.2.0",
"has-symbols": "^1.1.0",
"hasown": "^2.0.2",
"math-intrinsics": "^1.1.0"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmmirror.com/get-proto/-/get-proto-1.0.1.tgz",
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
"license": "MIT",
"dependencies": {
"dunder-proto": "^1.0.1",
"es-object-atoms": "^1.0.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/gopd": {
"version": "1.2.0",
"resolved": "https://registry.npmmirror.com/gopd/-/gopd-1.2.0.tgz",
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/has-symbols": {
"version": "1.1.0",
"resolved": "https://registry.npmmirror.com/has-symbols/-/has-symbols-1.1.0.tgz",
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/hasown": {
"version": "2.0.4",
"resolved": "https://registry.npmmirror.com/hasown/-/hasown-2.0.4.tgz",
"integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",
"license": "MIT",
"dependencies": {
"function-bind": "^1.1.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/http-errors": {
"version": "2.0.1",
"resolved": "https://registry.npmmirror.com/http-errors/-/http-errors-2.0.1.tgz",
"integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",
"license": "MIT",
"dependencies": {
"depd": "~2.0.0",
"inherits": "~2.0.4",
"setprototypeof": "~1.2.0",
"statuses": "~2.0.2",
"toidentifier": "~1.0.1"
},
"engines": {
"node": ">= 0.8"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/iconv-lite": {
"version": "0.4.24",
"resolved": "https://registry.npmmirror.com/iconv-lite/-/iconv-lite-0.4.24.tgz",
"integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
"license": "MIT",
"dependencies": {
"safer-buffer": ">= 2.1.2 < 3"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmmirror.com/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"license": "ISC"
},
"node_modules/ipaddr.js": {
"version": "1.9.1",
"resolved": "https://registry.npmmirror.com/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
"integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
"license": "MIT",
"engines": {
"node": ">= 0.10"
}
},
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmmirror.com/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/media-typer": {
"version": "0.3.0",
"resolved": "https://registry.npmmirror.com/media-typer/-/media-typer-0.3.0.tgz",
"integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/merge-descriptors": {
"version": "1.0.3",
"resolved": "https://registry.npmmirror.com/merge-descriptors/-/merge-descriptors-1.0.3.tgz",
"integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/methods": {
"version": "1.1.2",
"resolved": "https://registry.npmmirror.com/methods/-/methods-1.1.2.tgz",
"integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mime": {
"version": "1.6.0",
"resolved": "https://registry.npmmirror.com/mime/-/mime-1.6.0.tgz",
"integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==",
"license": "MIT",
"bin": {
"mime": "cli.js"
},
"engines": {
"node": ">=4"
}
},
"node_modules/mime-db": {
"version": "1.52.0",
"resolved": "https://registry.npmmirror.com/mime-db/-/mime-db-1.52.0.tgz",
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mime-types": {
"version": "2.1.35",
"resolved": "https://registry.npmmirror.com/mime-types/-/mime-types-2.1.35.tgz",
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
"license": "MIT",
"dependencies": {
"mime-db": "1.52.0"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/ms": {
"version": "2.0.0",
"resolved": "https://registry.npmmirror.com/ms/-/ms-2.0.0.tgz",
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
"license": "MIT"
},
"node_modules/negotiator": {
"version": "0.6.3",
"resolved": "https://registry.npmmirror.com/negotiator/-/negotiator-0.6.3.tgz",
"integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/nodemailer": {
"version": "6.10.1",
"resolved": "https://registry.npmmirror.com/nodemailer/-/nodemailer-6.10.1.tgz",
"integrity": "sha512-Z+iLaBGVaSjbIzQ4pX6XV41HrooLsQ10ZWPUehGmuantvzWoDVBnmsdUcOIDM1t+yPor5pDhVlDESgOMEGxhHA==",
"license": "MIT-0",
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/object-inspect": {
"version": "1.14.0",
"resolved": "https://registry.npmmirror.com/object-inspect/-/object-inspect-1.14.0.tgz",
"integrity": "sha512-IVgHNlp/jwQX271+Xzoq9LZNTWXxZK+cEOrGBOBxXNbn7fapnZ+Ts6TVMgNOuAezwG2wdtnMX97tTPK6VEnuOQ==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/on-finished": {
"version": "2.4.2",
"resolved": "https://registry.npmmirror.com/on-finished/-/on-finished-2.4.2.tgz",
"integrity": "sha512-ATWUv387i+nLD49EiDoOft5scf32Vsdz3ktrQJG9bi7jRFmaXTssvyvj1EmeKVVgvesbqUtvQQvaS2TpTukAZQ==",
"license": "MIT",
"dependencies": {
"ee-first": "1.1.1"
},
"engines": {
"node": ">= 0.8"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/parseurl": {
"version": "1.3.3",
"resolved": "https://registry.npmmirror.com/parseurl/-/parseurl-1.3.3.tgz",
"integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/path-to-regexp": {
"version": "0.1.13",
"resolved": "https://registry.npmmirror.com/path-to-regexp/-/path-to-regexp-0.1.13.tgz",
"integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==",
"license": "MIT"
},
"node_modules/proxy-addr": {
"version": "2.0.8",
"resolved": "https://registry.npmmirror.com/proxy-addr/-/proxy-addr-2.0.8.tgz",
"integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==",
"license": "MIT",
"dependencies": {
"forwarded": "0.2.0",
"ipaddr.js": "1.9.1"
},
"engines": {
"node": ">= 0.10"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/qs": {
"version": "6.16.2",
"resolved": "https://registry.npmmirror.com/qs/-/qs-6.16.2.tgz",
"integrity": "sha512-VYdnB5S7/0IeXzBacUtwNAaM6d7Y/PgYnNC7bJCI6meqA/OgnsQbZMtVW8Dt2D1PHgbHGtYmhSoEIgvt7xZ2ZA==",
"license": "BSD-3-Clause",
"dependencies": {
"es-define-property": "^1.0.1",
"side-channel": "^1.1.1"
},
"engines": {
"node": ">=0.6"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/range-parser": {
"version": "1.2.1",
"resolved": "https://registry.npmmirror.com/range-parser/-/range-parser-1.2.1.tgz",
"integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/raw-body": {
"version": "2.5.3",
"resolved": "https://registry.npmmirror.com/raw-body/-/raw-body-2.5.3.tgz",
"integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==",
"license": "MIT",
"dependencies": {
"bytes": "~3.1.2",
"http-errors": "~2.0.1",
"iconv-lite": "~0.4.24",
"unpipe": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/safe-buffer": {
"version": "5.2.1",
"resolved": "https://registry.npmmirror.com/safe-buffer/-/safe-buffer-5.2.1.tgz",
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmmirror.com/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT"
},
"node_modules/send": {
"version": "0.19.2",
"resolved": "https://registry.npmmirror.com/send/-/send-0.19.2.tgz",
"integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==",
"license": "MIT",
"dependencies": {
"debug": "2.6.9",
"depd": "2.0.0",
"destroy": "1.2.0",
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"etag": "~1.8.1",
"fresh": "~0.5.2",
"http-errors": "~2.0.1",
"mime": "1.6.0",
"ms": "2.1.3",
"on-finished": "~2.4.1",
"range-parser": "~1.2.1",
"statuses": "~2.0.2"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/send/node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmmirror.com/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/serve-static": {
"version": "1.16.3",
"resolved": "https://registry.npmmirror.com/serve-static/-/serve-static-1.16.3.tgz",
"integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==",
"license": "MIT",
"dependencies": {
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"parseurl": "~1.3.3",
"send": "~0.19.1"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/setprototypeof": {
"version": "1.2.0",
"resolved": "https://registry.npmmirror.com/setprototypeof/-/setprototypeof-1.2.0.tgz",
"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
"license": "ISC"
},
"node_modules/side-channel": {
"version": "1.1.1",
"resolved": "https://registry.npmmirror.com/side-channel/-/side-channel-1.1.1.tgz",
"integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"object-inspect": "^1.13.4",
"side-channel-list": "^1.0.1",
"side-channel-map": "^1.0.1",
"side-channel-weakmap": "^1.0.2"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel-list": {
"version": "1.0.1",
"resolved": "https://registry.npmmirror.com/side-channel-list/-/side-channel-list-1.0.1.tgz",
"integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"object-inspect": "^1.13.4"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel-map": {
"version": "1.0.1",
"resolved": "https://registry.npmmirror.com/side-channel-map/-/side-channel-map-1.0.1.tgz",
"integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.2",
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.5",
"object-inspect": "^1.13.3"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel-weakmap": {
"version": "1.0.2",
"resolved": "https://registry.npmmirror.com/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
"integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.2",
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.5",
"object-inspect": "^1.13.3",
"side-channel-map": "^1.0.1"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/statuses": {
"version": "2.0.2",
"resolved": "https://registry.npmmirror.com/statuses/-/statuses-2.0.2.tgz",
"integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/toidentifier": {
"version": "1.0.1",
"resolved": "https://registry.npmmirror.com/toidentifier/-/toidentifier-1.0.1.tgz",
"integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
"license": "MIT",
"engines": {
"node": ">=0.6"
}
},
"node_modules/type-is": {
"version": "1.6.18",
"resolved": "https://registry.npmmirror.com/type-is/-/type-is-1.6.18.tgz",
"integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
"license": "MIT",
"dependencies": {
"media-typer": "0.3.0",
"mime-types": "~2.1.24"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/unpipe": {
"version": "1.0.0",
"resolved": "https://registry.npmmirror.com/unpipe/-/unpipe-1.0.0.tgz",
"integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/utils-merge": {
"version": "1.0.1",
"resolved": "https://registry.npmmirror.com/utils-merge/-/utils-merge-1.0.1.tgz",
"integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==",
"license": "MIT",
"engines": {
"node": ">= 0.4.0"
}
},
"node_modules/vary": {
"version": "1.1.2",
"resolved": "https://registry.npmmirror.com/vary/-/vary-1.1.2.tgz",
"integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
}
}
}
+18
View File
@@ -0,0 +1,18 @@
{
"name": "gold-price-watcher",
"version": "1.0.0",
"private": true,
"description": "本地金价监控与提醒工具:Web 配置页 + 邮箱/桌面通知 + 阈值与价差提醒",
"main": "src/index.js",
"scripts": {
"start": "node src/index.js",
"dev": "node --watch src/index.js"
},
"engines": {
"node": ">=18.0.0"
},
"dependencies": {
"express": "^4.19.2",
"nodemailer": "^6.9.16"
}
}
+1426
View File
File diff suppressed because it is too large Load Diff
+377
View File
@@ -0,0 +1,377 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>金价提醒 · Gold Price Watcher</title>
<link rel="stylesheet" href="/styles.css?v=20261124q" />
</head>
<body>
<header class="topbar">
<div class="brand">
<span class="logo">Au</span>
<div class="brand-text">
<h1>金价提醒</h1>
<p>Gold Price Watcher · 本地监控</p>
</div>
</div>
<div class="status-bar">
<span class="pill" id="runPill"><i class="dot"></i><span id="runText">加载中…</span></span>
<span class="pill muted" id="quietPill" hidden>静默时段</span>
<span class="clock" id="serverTime">--:--:--</span>
<button class="btn ghost" id="btnRefresh">立即刷新</button>
<button class="btn primary" id="btnToggleRun">暂停监控</button>
</div>
</header>
<nav class="tabs" id="tabs">
<button class="tab active" data-tab="market">行情看板</button>
<button class="tab" data-tab="rules">提醒规则</button>
<button class="tab" data-tab="channels">通知设置</button>
<button class="tab" data-tab="alerts">提醒记录<span class="badge" id="alertBadge" hidden>0</span></button>
</nav>
<main>
<!-- ============ 行情看板 ============ -->
<section class="panel active" id="panel-market">
<div class="section-head">
<div>
<h2>监控品种</h2>
<p class="hint">每个品种可以单独设置刷新频率,价格变动后会按规则触发提醒。</p>
</div>
<button class="btn primary" id="btnAddInstrument">+ 添加品种</button>
</div>
<div class="grid" id="instrumentGrid"></div>
<p class="empty" id="instrumentEmpty" hidden>还没有监控品种,点击右上角「添加品种」开始。</p>
</section>
<!-- ============ 提醒规则 ============ -->
<section class="panel" id="panel-rules">
<div class="section-head">
<div>
<h2>提醒规则</h2>
<p class="hint">支持价格阈值、涨跌幅(可指定统计区间,如「近 10 分钟涨 0.5%」)、两个品种之间的价差、定时提醒四类规则;价格类规则还能限定生效时段并按冷却时间防轰炸,定时提醒按时刻去重。</p>
</div>
<button class="btn primary" id="btnAddRule">+ 新建规则</button>
</div>
<div class="rule-list" id="ruleList"></div>
<p class="empty" id="ruleEmpty" hidden>还没有规则。先添加一个「价格上破 800 元/克」试试。</p>
</section>
<!-- ============ 通知设置 ============ -->
<section class="panel" id="panel-channels">
<div class="section-head">
<div>
<h2>通知设置</h2>
<p class="hint">桌面通知走 Windows 原生 Toast;邮件走 SMTP;WebHook 支持内置 JSON 与钉钉机器人两种格式。配置只保存在本机。</p>
</div>
</div>
<div class="cards-2">
<div class="card setting-card">
<div class="card-head">
<h3>Windows 桌面通知</h3>
<label class="switch">
<input type="checkbox" id="desktopEnabled" />
<span></span>
</label>
</div>
<p class="hint">在右下角弹出系统通知,需要 Windows 10/11,且系统的「通知」未关闭。</p>
<div class="row">
<button class="btn ghost" id="btnTestDesktop">发送测试通知</button>
<span class="test-result" id="desktopTestResult"></span>
</div>
</div>
<div class="card setting-card">
<div class="card-head">
<h3>全局默认渠道</h3>
</div>
<p class="hint">规则没有单独指定渠道时,用这里的默认设置。</p>
<div class="row wrap">
<label class="check"><input type="checkbox" id="channelDesktop" /> 桌面通知</label>
<label class="check"><input type="checkbox" id="channelEmail" /> 邮件</label>
<label class="check"><input type="checkbox" id="channelWebhook" /> WebHook</label>
</div>
<div class="row">
<label class="field inline">
<span>默认刷新频率(秒)</span>
<input type="number" id="defaultInterval" min="5" max="86400" step="1" />
</label>
</div>
<div class="row wrap">
<label class="check"><input type="checkbox" id="quietEnabled" /> 静默时段只发邮件,不弹桌面通知</label>
<input type="text" id="quietRange" class="narrow" placeholder="23:00-07:00" />
<label class="check"><input type="checkbox" id="alertOnFirstCheck" /> 启动时已满足条件也提醒一次</label>
</div>
</div>
</div>
<div class="card setting-card" id="emailCard">
<div class="card-head">
<h3>邮箱提醒(SMTP)</h3>
<label class="switch">
<input type="checkbox" id="emailEnabled" />
<span></span>
</label>
</div>
<p class="hint">
常见填写:QQ 邮箱 <code>smtp.qq.com</code> + 465 + 授权码;163 邮箱 <code>smtp.163.com</code> + 465 + 授权码;
企业邮箱按服务商文档填写。密码处请填「授权码」而不是登录密码。
</p>
<div class="form-grid">
<label class="field"><span>SMTP 服务器</span><input type="text" id="emailHost" placeholder="smtp.qq.com" /></label>
<label class="field"><span>端口</span><input type="number" id="emailPort" placeholder="465" /></label>
<label class="field"><span>加密方式</span>
<select id="emailSecure">
<option value="true">SSL(端口 465)</option>
<option value="false">STARTTLS(端口 587)</option>
</select>
</label>
<label class="field"><span>发件邮箱</span><input type="text" id="emailUser" placeholder="you@qq.com" /></label>
<label class="field"><span>授权码 / 密码</span><input type="password" id="emailPass" placeholder="留空则不修改" autocomplete="new-password" /></label>
<label class="field"><span>发件人显示名</span><input type="text" id="emailFrom" placeholder="金价提醒 &lt;you@qq.com&gt;" /></label>
<label class="field wide"><span>收件人(多个用逗号或分号分隔)</span><input type="text" id="emailTo" placeholder="a@qq.com, b@163.com" /></label>
<label class="field"><span>邮件标题前缀</span><input type="text" id="emailPrefix" placeholder="【金价提醒】" /></label>
<label class="field check-field"><span>邮件正文附带行情快照</span><input type="checkbox" id="emailSnapshot" /></label>
</div>
<div class="row">
<button class="btn ghost" id="btnTestEmail">发送测试邮件</button>
<span class="test-result" id="emailTestResult"></span>
</div>
</div>
<div class="card setting-card" id="webhookCard">
<div class="card-head">
<h3>WebHook 推送</h3>
<label class="switch">
<input type="checkbox" id="webhookEnabled" />
<span></span>
</label>
</div>
<p class="hint">
触发提醒时向该地址 POST 一条消息。两种格式:<b>内置 JSON</b> 是本工具固定的字段结构,方便自建服务或自动化脚本消费;
<b>钉钉机器人</b> 直接填群机器人的 Webhook 地址即可,支持「加签」安全设置。
</p>
<div class="form-grid">
<label class="field wide"><span>WebHook 地址</span>
<input type="text" id="webhookUrl" placeholder="https://oapi.dingtalk.com/robot/send?access_token=xxx" />
</label>
<label class="field"><span>报文格式</span>
<select id="webhookFormat">
<option value="generic">内置 JSON(自定义服务)</option>
<option value="dingtalk">钉钉机器人(markdown)</option>
</select>
</label>
<label class="field" id="webhookSecretField"><span>钉钉加签密钥(可选)</span>
<input type="password" id="webhookSecret" placeholder="SEC 开头;机器人未启用加签可留空" autocomplete="new-password" />
</label>
<label class="field" id="webhookKeywordField"><span>钉钉自定义关键词(可选)</span>
<input type="text" id="webhookKeyword" placeholder="例如:金价(填机器人安全设置里的那个词)" />
</label>
<label class="field wide" id="webhookAtMobilesField"><span>钉钉 @ 手机号(多个用逗号分隔,可留空)</span>
<input type="text" id="webhookAtMobiles" placeholder="13800000000, 13900000000" />
</label>
<label class="field check-field" id="webhookMentionAllField"><span>钉钉 @所有人</span>
<input type="checkbox" id="webhookMentionAll" />
</label>
</div>
<p class="hint" id="webhookFormatHint"></p>
<div class="row">
<button class="btn ghost" id="btnTestWebhook">发送测试推送</button>
<span class="test-result" id="webhookTestResult"></span>
</div>
</div>
<div class="card setting-card">
<div class="card-head"><h3>服务与安全</h3></div>
<div class="form-grid">
<label class="field"><span>监听端口(改后需重启)</span><input type="number" id="appPort" min="1" max="65535" /></label>
<label class="field"><span>监听地址</span><input type="text" id="appHost" placeholder="127.0.0.1" /></label>
<label class="field wide"><span>访问令牌(留空表示本机免登录;非本机访问强烈建议设置)</span><input type="text" id="appToken" placeholder="自定义一串字符" /></label>
</div>
<div class="row">
<label class="check"><input type="checkbox" id="appOpenBrowser" /> 启动时自动打开浏览器</label>
</div>
<p class="hint" id="configPathHint"></p>
<div class="row">
<button class="btn ghost" id="btnExportConfig">导出配置</button>
<button class="btn ghost" id="btnImportConfig">导入配置</button>
<input type="file" id="importFile" accept="application/json" hidden />
</div>
</div>
<div class="row sticky-save">
<button class="btn primary" id="btnSaveSettings">保存设置</button>
<span class="test-result" id="saveResult"></span>
</div>
</section>
<!-- ============ 提醒记录 ============ -->
<section class="panel" id="panel-alerts">
<div class="section-head">
<div>
<h2>提醒记录</h2>
<p class="hint">最近 200 条触发记录,同时写入 <code>data/alerts.jsonl</code> 便于追溯。</p>
</div>
<button class="btn ghost" id="btnClearAlerts">清空</button>
</div>
<div class="alert-list" id="alertList"></div>
<p class="empty" id="alertEmpty" hidden>暂时还没有触发过提醒。</p>
</section>
</main>
<!-- ============ 弹窗:添加/编辑品种 ============ -->
<div class="modal" id="modalInstrument" hidden>
<div class="modal-box">
<div class="modal-head">
<h3 id="instrumentModalTitle">添加品种</h3>
<button class="icon-btn" data-close="modalInstrument">✕</button>
</div>
<div class="modal-body">
<label class="field wide">
<span>选择内置品种</span>
<select id="presetSelect"></select>
</label>
<p class="hint" id="presetHint"></p>
<div class="form-grid" id="instrumentCustomFields">
<label class="field wide"><span>名称</span><input type="text" id="instName" placeholder="例如 浙商黄金" /></label>
<label class="field"><span>数据源</span><select id="instSource"></select></label>
<label class="field"><span>刷新频率(秒)</span><input type="number" id="instInterval" min="5" max="86400" step="5" /></label>
<label class="field"><span>价格单位</span><input type="text" id="instUnit" placeholder="元/克" /></label>
<label class="field"><span>小数位</span><input type="number" id="instDigits" min="0" max="4" /></label>
<label class="field wide" id="sinaCodeField"><span>新浪行情代码</span><input type="text" id="instSinaCode" placeholder="SGE_AUTD / hf_XAU / nf_AU0" /></label>
<label class="field wide" id="rijinjiaKeyField"><span>积存金品种 key</span><input type="text" id="instRijinjiaKey" placeholder="czb-jcj" /></label>
<label class="field wide" id="httpUrlField"><span>接口地址</span><input type="text" id="instHttpUrl" placeholder="https://api.example.com/gold" /></label>
<label class="field" id="httpPricePathField"><span>价格字段路径</span><input type="text" id="instHttpPricePath" placeholder="data.price" /></label>
<label class="field" id="httpPrevPathField"><span>昨收字段路径(可选)</span><input type="text" id="instHttpPrevPath" placeholder="data.prevClose" /></label>
</div>
<p class="hint">提示:添加前可以先在「行情」里用「测试抓取」验证数据源是否可用。</p>
</div>
<div class="modal-foot">
<span class="test-result" id="instrumentResult"></span>
<button class="btn ghost" data-close="modalInstrument">取消</button>
<button class="btn ghost" id="btnTestInstrument">测试抓取</button>
<button class="btn primary" id="btnSaveInstrument">保存</button>
</div>
</div>
</div>
<!-- ============ 弹窗:规则 ============ -->
<div class="modal" id="modalRule" hidden>
<div class="modal-box">
<div class="modal-head">
<h3 id="ruleModalTitle">新建规则</h3>
<button class="icon-btn" data-close="modalRule">✕</button>
</div>
<div class="modal-body">
<div class="form-grid">
<!-- 1) 先定类型和标的:类型 → 监控品种(价差再加对比品种) -->
<label class="field"><span>规则类型</span>
<select id="ruleType">
<option value="threshold">价格阈值</option>
<option value="change">涨跌幅</option>
<option value="spread">价差提醒</option>
<option value="schedule">定时提醒</option>
</select>
</label>
<label class="field"><span>监控品种</span><select id="ruleInstrument"></select></label>
<label class="field" id="ruleCompareField" hidden><span>对比品种</span><select id="ruleCompare"></select></label>
<!-- 2) 再定口径和方向:口径决定阈值的单位,放在方向/阈值之前 -->
<label class="field" id="ruleModeField" hidden><span>价差口径</span>
<select id="ruleMode">
<option value="abs">绝对价差(元/克)</option>
<option value="percent">相对价差(%)</option>
</select>
</label>
<!-- 涨跌幅专用:阈值口径(百分比 / 具体价格变动值) -->
<label class="field" id="ruleBasisField" hidden><span>阈值口径</span>
<select id="ruleBasis">
<option value="percent">涨跌幅百分比(%)</option>
<option value="amount">具体变动值(元/克)</option>
</select>
</label>
<label class="field" id="ruleDirectionField"><span>触发方向</span><select id="ruleDirection"></select></label>
<!-- 3) 触发条件:阈值 + 统计区间 -->
<label class="field" id="ruleValueField"><span id="ruleValueLabel">阈值</span>
<input type="number" id="ruleValue" step="0.001" placeholder="800" />
</label>
<!-- 涨跌幅专用:统计区间(日内相对昨收,或近 N 分钟的滚动窗口) -->
<label class="field" id="ruleWindowField" hidden><span>统计区间</span>
<select id="ruleWindow">
<option value="0">日内(相对昨收)</option>
<option value="300">近 5 分钟</option>
<option value="600">近 10 分钟</option>
<option value="900">近 15 分钟</option>
<option value="1800">近 30 分钟</option>
<option value="3600">近 1 小时</option>
<option value="7200">近 2 小时</option>
<option value="14400">近 4 小时</option>
<option value="-1">自定义(分钟)</option>
</select>
</label>
<label class="field" id="ruleWindowCustomField" hidden><span>自定义分钟数(最长 720)</span>
<input type="number" id="ruleWindowCustom" min="1" max="720" step="1" placeholder="20" />
</label>
<!-- 4) 生效与提醒频率 -->
<!-- 生效时段:留空表示全天,支持跨零点(如 22:00 ~ 02:00) -->
<label class="field wide" id="ruleActiveRangeField"><span>生效时段(可选,留空表示全天)</span>
<div class="time-range">
<input type="time" id="ruleActiveFrom" />
<span class="range-sep">~</span>
<input type="time" id="ruleActiveTo" />
</div>
</label>
<label class="field" id="ruleCooldownField"><span>冷却时间(秒)</span><input type="number" id="ruleCooldown" min="30" step="30" value="1800" /></label>
<label class="field" id="ruleRepeatField"><span>持续满足时每 N 秒重复提醒(0 不重复)</span><input type="number" id="ruleRepeat" min="0" step="60" value="0" /></label>
<!-- 定时提醒专用:到点时刻 + 重复方式 -->
<label class="field wide" id="ruleScheduleTimesField" hidden><span>提醒时刻(24 小时制,多个用逗号分隔,最多 12 个)</span>
<input type="text" id="ruleScheduleTimes" placeholder="09:00, 15:30, 21:00" />
</label>
<label class="field" id="ruleScheduleRepeatField" hidden><span>重复方式</span>
<select id="ruleScheduleRepeat">
<option value="daily">每天</option>
<option value="weekday">工作日(周一至周五)</option>
<option value="weekly">每周指定几天</option>
</select>
</label>
<div class="field wide" id="ruleScheduleWeekdaysField" hidden>
<span>每周的哪几天</span>
<div class="row wrap">
<label class="check"><input type="checkbox" class="js-weekday" value="1" /> 周一</label>
<label class="check"><input type="checkbox" class="js-weekday" value="2" /> 周二</label>
<label class="check"><input type="checkbox" class="js-weekday" value="3" /> 周三</label>
<label class="check"><input type="checkbox" class="js-weekday" value="4" /> 周四</label>
<label class="check"><input type="checkbox" class="js-weekday" value="5" /> 周五</label>
<label class="check"><input type="checkbox" class="js-weekday" value="6" /> 周六</label>
<label class="check"><input type="checkbox" class="js-weekday" value="7" /> 周日</label>
</div>
</div>
<!-- 5) 最后填名称:留空则按上面的条件自动生成 -->
<label class="field wide"><span>规则名称(可选,留空自动生成)</span><input type="text" id="ruleName" placeholder="留空则按触发条件自动命名" /></label>
</div>
<div class="row wrap">
<span class="label-text">通知渠道</span>
<label class="check"><input type="checkbox" id="ruleChannelDesktop" /> 桌面通知</label>
<label class="check"><input type="checkbox" id="ruleChannelEmail" /> 邮件</label>
<label class="check"><input type="checkbox" id="ruleChannelWebhook" /> WebHook</label>
<label class="check"><input type="checkbox" id="ruleEnabled" /> 启用该规则</label>
</div>
<p class="hint" id="ruleSummary"></p>
<p class="hint" id="ruleWindowHint">提示:统计区间选「日内」时,涨跌幅相对昨收计算;选「近 N 分钟」时,用本机缓存的行情点回算滚动区间,重启后会接着用已保存的历史。</p>
<p class="hint" id="ruleScheduleHint" hidden>提示:定时提醒会在指定时刻按当时的行情发一条通知,不受价格条件影响;同一时刻每天只响一次,程序当时没运行则不会补发。</p>
</div>
<div class="modal-foot">
<span class="test-result" id="ruleResult"></span>
<button class="btn ghost" data-close="modalRule">取消</button>
<button class="btn primary" id="btnSaveRule">保存规则</button>
</div>
</div>
</div>
<div class="toast-wrap" id="toastWrap"></div>
<script src="/app.js?v=20261124q"></script>
</body>
</html>
+528
View File
@@ -0,0 +1,528 @@
/* 金价提醒 · 界面样式(浅色版)
暖白纸感底色 + 香槟金点缀,靠细描边和轻阴影分层次,避免大面积重色块。 */
:root {
--bg: #f7f5f0;
--bg-soft: #fffdf9;
--panel: #ffffff;
--panel-2: #f4f1e9;
--line: #e6e1d5;
--line-strong: #d8d2c3;
--text: #1d2127;
--text-dim: #5f6773;
--text-faint: #6b7382;
--gold: #b8862f;
--gold-soft: #8a5f13;
--gold-wash: #faf4e6;
--up: #d23c2f;
--down: #0f8a55;
--warn: #c07a12;
--radius: 14px;
--shadow-sm: 0 1px 2px rgba(28, 24, 16, .04);
--shadow-md: 0 10px 28px rgba(28, 24, 16, .07);
}
* { box-sizing: border-box; }
/* 有些元素自带 display,需要强制让 [hidden] 生效 */
[hidden] { display: none !important; }
body {
margin: 0;
min-height: 100vh;
background:
radial-gradient(1100px 520px at 88% -12%, rgba(184, 134, 47, .10), transparent 62%),
radial-gradient(900px 480px at -8% 4%, rgba(120, 150, 190, .07), transparent 58%),
var(--bg);
color: var(--text);
font-family: "Segoe UI", "Microsoft YaHei", system-ui, -apple-system, sans-serif;
font-size: 14px;
line-height: 1.6;
-webkit-font-smoothing: antialiased;
}
code {
background: var(--gold-wash);
border: 1px solid #efe6d0;
border-radius: 5px;
padding: 1px 5px;
font-size: 12px;
color: #7a5715;
}
/* ---------------- 顶栏 ---------------- */
.topbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 18px 28px 14px;
border-bottom: 1px solid var(--line);
background: rgba(255, 255, 255, .78);
backdrop-filter: blur(8px);
}
.brand { display: flex; align-items: center; gap: 12px; }
.logo {
width: 42px; height: 42px;
display: grid; place-items: center;
border-radius: 12px;
background: linear-gradient(140deg, #f6dda2, #c79327 72%);
color: #3a2a06;
font-weight: 800;
font-size: 17px;
letter-spacing: .5px;
box-shadow: 0 3px 10px rgba(184, 134, 47, .28);
}
.brand-text h1 { margin: 0; font-size: 19px; letter-spacing: .5px; color: #171a1f; }
.brand-text p { margin: 0; font-size: 11px; color: var(--text-faint); letter-spacing: 1.5px; text-transform: uppercase; }
.status-bar { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.pill {
display: inline-flex; align-items: center; gap: 7px;
padding: 5px 12px;
border: 1px solid var(--line);
border-radius: 999px;
font-size: 12px;
color: var(--text-dim);
background: #fff;
box-shadow: var(--shadow-sm);
}
.pill .dot {
width: 7px; height: 7px; border-radius: 50%;
background: var(--text-faint);
}
.pill.running .dot { background: var(--down); box-shadow: 0 0 0 3px rgba(15, 138, 85, .12); }
.pill.running { color: #0c6b44; border-color: #cbe7da; background: #f2fbf7; }
.pill.paused .dot { background: var(--warn); box-shadow: 0 0 0 3px rgba(192, 122, 18, .12); }
.pill.muted { color: var(--gold-soft); border-color: #ecdfc2; background: var(--gold-wash); }
.clock { font-size: 12px; color: var(--text-faint); font-variant-numeric: tabular-nums; }
/* ---------------- 通用按钮 ---------------- */
.btn {
border: 1px solid var(--line-strong);
background: #fff;
color: var(--text);
padding: 8px 16px;
border-radius: 10px;
font-size: 13px;
cursor: pointer;
transition: .15s ease;
white-space: nowrap;
box-shadow: var(--shadow-sm);
}
.btn:hover { background: #fffdf7; border-color: #cbb98d; transform: translateY(-1px); }
.btn:active { transform: translateY(0); box-shadow: none; }
.btn.primary {
background: linear-gradient(140deg, #f3d38f, #cf9c31);
border-color: #c08b22;
color: #3a2a06;
font-weight: 600;
box-shadow: 0 4px 12px rgba(184, 134, 47, .22);
}
.btn.primary:hover { filter: brightness(1.04); }
.btn.ghost { background: #fff; }
.btn.danger { color: #b8332a; border-color: #eececb; background: #fff8f7; }
.btn.danger:hover { background: #fdf0ee; border-color: #e2b3ad; }
.btn.tiny { padding: 4px 10px; font-size: 12px; border-radius: 8px; }
.btn:disabled { opacity: .5; cursor: not-allowed; transform: none; }
.icon-btn {
border: none; background: transparent; color: var(--text-faint);
font-size: 16px; cursor: pointer; line-height: 1;
}
.icon-btn:hover { color: var(--text); }
/* ---------------- 标签页 ---------------- */
.tabs {
display: flex;
/* 允许换行:极窄窗口下标签自动折行,不用横向滚动 */
flex-wrap: wrap;
gap: 6px;
padding: 14px 28px 0;
border-bottom: 1px solid var(--line);
background: rgba(255, 255, 255, .6);
/* 注意:这里不要写 overflow-x: auto。
一旦设了 overflow-x,overflow-y 会被一并算成 auto,
再叠加 .tab.active::after 的 bottom:-1px(超出 1px),
顶部菜单就会冒出一条多余的滚动条。 */
}
.tab {
position: relative;
border: none;
background: transparent;
color: var(--text-dim);
padding: 10px 14px 14px;
font-size: 14px;
cursor: pointer;
white-space: nowrap;
}
.tab:hover { color: var(--text); }
.tab.active { color: var(--gold-soft); font-weight: 600; }
.tab.active::after {
content: "";
position: absolute; left: 12px; right: 12px; bottom: -1px;
height: 2px;
background: linear-gradient(90deg, transparent, var(--gold), transparent);
}
.badge {
display: inline-block;
margin-left: 6px;
min-width: 18px;
padding: 0 5px;
border-radius: 999px;
background: #fbecea;
color: #b3352a;
font-size: 11px;
text-align: center;
}
/* ---------------- 主体 ---------------- */
main { padding: 22px 28px 60px; max-width: 1320px; margin: 0 auto; }
.panel { display: none; }
.panel.active { display: block; animation: fade .2s ease; }
@keyframes fade { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } }
.section-head {
display: flex; align-items: flex-start; justify-content: space-between;
gap: 16px; margin-bottom: 16px;
}
.section-head h2 { margin: 0 0 4px; font-size: 17px; font-weight: 600; color: #14171c; }
.hint { margin: 0; color: var(--text-faint); font-size: 12.5px; }
.empty { color: var(--text-faint); text-align: center; padding: 40px 0; }
/* ---------------- 行情卡片 ---------------- */
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(290px, 1fr));
gap: 14px;
}
.card {
position: relative;
background: var(--panel);
border: 1px solid var(--line);
border-radius: var(--radius);
padding: 16px 18px;
overflow: hidden;
box-shadow: var(--shadow-sm);
transition: box-shadow .18s ease, transform .18s ease;
}
.card:hover { box-shadow: var(--shadow-md); transform: translateY(-1px); }
.card::before {
content: "";
position: absolute; inset: 0 auto 0 0;
width: 3px;
background: linear-gradient(180deg, rgba(184, 134, 47, .7), rgba(184, 134, 47, .12));
}
.card.disabled { opacity: .62; }
.card.disabled:hover { transform: none; box-shadow: var(--shadow-sm); }
.card-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 10px; }
.card-head h3 { margin: 0; font-size: 14.5px; font-weight: 600; color: #14171c; }
.card-title-row { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
.source-tag {
font-size: 10.5px; color: var(--text-faint);
border: 1px solid var(--line); border-radius: 6px;
padding: 1px 6px;
background: var(--bg-soft);
}
.price-row { display: flex; align-items: baseline; gap: 8px; margin: 12px 0 2px; }
.price {
font-size: 30px; font-weight: 700; letter-spacing: -.5px;
font-variant-numeric: tabular-nums;
color: #0f1216;
}
.price.stale { color: var(--text-faint); font-size: 24px; }
.unit { font-size: 12px; color: var(--text-faint); }
.change-row { display: flex; align-items: center; gap: 10px; font-size: 12.5px; }
.change.up { color: var(--up); }
.change.down { color: var(--down); }
.change.flat { color: var(--text-dim); }
.change-row .js-range { color: var(--text-faint); }
.spark { display: block; width: 100%; height: 34px; margin: 8px 0 6px; }
.meta {
display: flex; flex-wrap: wrap; gap: 4px 12px;
font-size: 11.5px; color: var(--text-faint);
font-variant-numeric: tabular-nums;
}
.meta .status { display: inline-flex; align-items: center; gap: 4px; }
.meta .status i { width: 6px; height: 6px; border-radius: 50%; display: inline-block; }
.status.ok { color: #0c6b44; }
.status.ok i { background: var(--down); }
.status.error { color: #b3352a; }
.status.error i { background: var(--up); }
.status.pending { color: #8a5f13; }
.status.pending i { background: var(--warn); }
.status.manual { color: var(--gold-soft); }
.status.manual i { background: var(--gold); }
.status.disabled i { background: var(--text-faint); }
.card-error {
margin-top: 8px;
font-size: 11.5px;
color: #a3271f;
background: #fdf2f0;
border: 1px solid #f0cfca;
border-radius: 8px;
padding: 6px 9px;
word-break: break-all;
}
.card-foot {
display: flex; align-items: center; justify-content: space-between;
gap: 8px; margin-top: 12px; padding-top: 11px;
border-top: 1px dashed var(--line);
}
.card-foot .btn-row { display: flex; gap: 6px; }
.switch { position: relative; display: inline-block; width: 40px; height: 22px; flex: 0 0 auto; }
.switch input { opacity: 0; width: 0; height: 0; }
.switch span {
position: absolute; inset: 0;
background: #dcd7ca;
border: 1px solid #cfc8b8;
border-radius: 999px;
cursor: pointer;
transition: .2s;
}
.switch span::before {
content: "";
position: absolute; width: 14px; height: 14px;
left: 3px; top: 3px;
background: #fff;
box-shadow: 0 1px 2px rgba(0, 0, 0, .18);
border-radius: 50%;
transition: .2s;
}
.switch input:checked + span {
background: linear-gradient(135deg, #e7c27a, #c79230);
border-color: #b8862f;
}
.switch input:checked + span::before { background: #fffdf6; transform: translateX(18px); }
.manual-row { display: flex; gap: 6px; margin-top: 10px; }
.manual-row input {
flex: 1; min-width: 0;
background: #fff;
border: 1px solid var(--line-strong);
border-radius: 9px;
padding: 7px 10px;
font-size: 13px;
color: var(--text);
font-family: inherit;
outline: none;
}
.manual-row input:focus { border-color: var(--gold); box-shadow: 0 0 0 3px rgba(184, 134, 47, .12); }
/* ---------------- 规则列表 ---------------- */
.rule-list { display: flex; flex-direction: column; gap: 10px; }
.rule-item {
display: flex; align-items: center; gap: 14px;
padding: 14px 18px;
background: var(--panel);
border: 1px solid var(--line);
border-radius: 12px;
box-shadow: var(--shadow-sm);
}
.rule-item.disabled { opacity: .6; }
.rule-main { flex: 1; min-width: 0; }
.rule-title { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
.rule-name { font-weight: 600; font-size: 14px; color: #14171c; }
.tag {
font-size: 10.5px; padding: 1px 7px; border-radius: 6px;
border: 1px solid var(--line); color: var(--text-dim);
background: var(--bg-soft);
}
.tag.threshold { color: var(--gold-soft); border-color: #e8d7b4; background: var(--gold-wash); }
.tag.change { color: #2a5b96; border-color: #cfe0f2; background: #f2f7fc; }
.tag.spread { color: #6a4b9a; border-color: #e0d4f0; background: #f7f3fc; }
/* 定时提醒:用偏绿的色,和三种价格条件规则区分开 */
.tag.schedule { color: #1f7a5c; border-color: #cfe8dd; background: #f1faf6; }
.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-actions { display: flex; align-items: center; gap: 8px; }
/* ---------------- 设置区 ---------------- */
.cards-2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 14px; margin-bottom: 14px; }
.setting-card { margin-bottom: 14px; }
.setting-card .card-head { margin-bottom: 6px; align-items: center; }
.setting-card h3 { margin: 0; font-size: 15px; color: #14171c; }
.form-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 12px 16px;
margin: 14px 0 4px;
}
.field { display: flex; flex-direction: column; gap: 6px; font-size: 12.5px; color: var(--text-dim); }
.field.wide { grid-column: 1 / -1; }
.field.inline { flex-direction: row; align-items: center; gap: 10px; }
.field.check-field { flex-direction: row; align-items: center; justify-content: space-between; }
.field input, .field select, .field textarea {
background: #fff;
border: 1px solid var(--line-strong);
border-radius: 9px;
padding: 8px 11px;
color: var(--text);
font-size: 13px;
font-family: inherit;
outline: none;
transition: border-color .15s, box-shadow .15s;
}
.field input:focus, .field select:focus {
border-color: var(--gold);
box-shadow: 0 0 0 3px rgba(184, 134, 47, .12);
}
.field input.narrow { width: 120px; }
.field input[type="checkbox"] {
width: 16px; height: 16px;
padding: 0; border: none; background: none;
accent-color: var(--gold);
}
input::placeholder { color: #a8a294; }
.row { display: flex; align-items: center; gap: 10px; margin-top: 12px; flex-wrap: wrap; }
/* 不在 .field 里的裸输入框(如静默时段区间)也套用同一套皮肤 */
.row > input[type="text"], .row > input[type="number"] {
background: #fff;
border: 1px solid var(--line-strong);
border-radius: 9px;
padding: 7px 11px;
color: var(--text);
font-size: 13px;
font-family: inherit;
outline: none;
width: 150px;
}
.row > input[type="text"]:focus, .row > input[type="number"]:focus {
border-color: var(--gold);
box-shadow: 0 0 0 3px rgba(184, 134, 47, .12);
}
.label-text { color: var(--text-dim); font-size: 12.5px; }
.check { display: inline-flex; align-items: center; gap: 6px; font-size: 12.5px; color: var(--text-dim); cursor: pointer; }
.check input { accent-color: var(--gold); }
.test-result { font-size: 12px; color: var(--text-faint); }
.test-result.ok { color: #0c6b44; }
.test-result.err { color: #b8332a; }
.sticky-save {
position: sticky; bottom: 0;
padding: 12px 0 6px;
background: linear-gradient(180deg, transparent, var(--bg) 45%);
}
/* ---------------- 提醒记录 ---------------- */
.alert-list { display: flex; flex-direction: column; gap: 10px; }
.alert-item {
padding: 13px 16px;
background: var(--panel);
border: 1px solid var(--line);
border-left: 3px solid var(--gold);
border-radius: 10px;
box-shadow: var(--shadow-sm);
}
.alert-title { font-weight: 600; font-size: 13.5px; color: #14171c; }
.alert-msg { color: var(--text-dim); font-size: 12.5px; margin-top: 3px; }
.alert-meta { display: flex; gap: 12px; flex-wrap: wrap; margin-top: 6px; font-size: 11.5px; color: var(--text-faint); }
.alert-meta .chan { color: var(--text-dim); }
.alert-meta .chan.ok { color: #0c6b44; }
.alert-meta .chan.err { color: #b8332a; }
/* ---------------- 弹窗 ---------------- */
.modal {
position: fixed; inset: 0; z-index: 50;
display: grid; place-items: center;
background: rgba(35, 30, 22, .38);
backdrop-filter: blur(4px);
padding: 20px;
}
.modal[hidden] { display: none; }
.modal-box {
width: min(720px, 100%);
max-height: 88vh;
overflow: auto;
background: var(--panel);
border: 1px solid var(--line);
border-radius: 16px;
box-shadow: 0 24px 60px rgba(28, 24, 16, .18);
}
.modal-head {
display: flex; align-items: center; justify-content: space-between;
padding: 16px 20px;
border-bottom: 1px solid var(--line);
position: sticky; top: 0;
background: var(--panel);
z-index: 1;
}
.modal-head h3 { margin: 0; font-size: 16px; color: #14171c; }
.modal-body { padding: 18px 20px 6px; }
.modal-foot {
display: flex; align-items: center; justify-content: flex-end; gap: 10px;
padding: 14px 20px 18px;
border-top: 1px solid var(--line);
position: sticky; bottom: 0;
background: var(--panel);
}
.modal-foot .test-result { margin-right: auto; }
/* ---------------- 轻提示 ---------------- */
.toast-wrap {
position: fixed; right: 22px; bottom: 22px;
display: flex; flex-direction: column; gap: 8px;
z-index: 99;
}
.toast {
padding: 10px 16px;
border-radius: 10px;
background: #fff;
border: 1px solid var(--line-strong);
color: var(--text);
font-size: 13px;
box-shadow: var(--shadow-md);
animation: slideIn .2s ease;
}
.toast.ok { border-color: #bfe0d0; background: #f5fcf8; color: #0c6b44; }
.toast.err { border-color: #eec9c4; background: #fdf3f1; color: #a3271f; }
@keyframes slideIn { from { opacity: 0; transform: translateX(12px); } to { opacity: 1; transform: none; } }
/* ---------------- 规则弹窗:生效时段 ---------------- */
.time-range {
display: flex;
align-items: center;
gap: 8px;
}
.time-range input[type="time"] {
flex: 1 1 0;
min-width: 0;
}
.range-sep {
color: var(--text-faint);
font-size: 13px;
flex: 0 0 auto;
}
/* ---------------- 窄屏适配 ---------------- */
@media (max-width: 720px) {
.topbar { flex-direction: column; align-items: flex-start; padding: 16px; }
main { padding: 18px 16px 60px; }
.tabs { padding: 10px 16px 0; }
.price { font-size: 26px; }
.rule-item { flex-wrap: wrap; }
.form-grid { grid-template-columns: 1fr; }
}
+402
View File
@@ -0,0 +1,402 @@
/**
* 配置存取层。
* 配置全部落在 config/config.json:
* - instruments 监控品种(数据源、刷新频率、单位等)
* - rules 提醒规则(阈值 / 涨跌幅 / 价差)
* - email 邮箱 SMTP 配置
* - desktop Windows 桌面通知开关
* - monitor 全局轮询与静默时段
*/
const path = require('node:path');
const {
deepMerge, readJson, writeJson, uid, toNum, maskSecret, log, isPlainObject,
} = require('./util');
const { PRESETS, buildInstrument } = require('./presets');
const ROOT = path.resolve(__dirname, '..');
const CONFIG_FILE = path.join(ROOT, 'config', 'config.json');
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) {
const type = ['threshold', 'change', 'spread', 'schedule'].includes(raw?.type) ? raw.type : 'threshold';
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
: (type === 'threshold' ? 'above' : 'abs');
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,
value: clampNumber(raw?.value, 0, -1e9, 1e9),
cooldownSec: Math.round(clampNumber(raw?.cooldownSec, 1800, 30, 86400 * 7)),
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(),
},
};
}
/** 导出完整配置(含真实密码,用于备份,仅本地接口使用) */
function exportFile() {
return get();
}
module.exports = {
ROOT,
CONFIG_FILE,
defaultConfig,
normalizeConfig,
load,
get,
replace,
patch,
forClient,
exportFile,
};
+77
View File
@@ -0,0 +1,77 @@
#!/usr/bin/env node
/**
* 程序入口:载入配置 -> 启动监控 -> 启动 Web 配置页。
* 用法:npm start(或 node src/index.js)
*/
const http = require('node:http');
const path = require('node:path');
const { spawn } = require('node:child_process');
const store = require('./config-store');
const { Monitor } = require('./monitor');
const { createApp } = require('./server');
const { log, ensureDir } = require('./util');
/**
* 打开系统默认浏览器
* @param {string} url 目标地址
*/
function openBrowser(url) {
if (process.platform !== 'win32') return;
try {
spawn('cmd.exe', ['/c', 'start', '', url], { detached: true, stdio: 'ignore', windowsHide: true }).unref();
} catch {
/* 忽略打开失败,用户可手动访问 */
}
}
/**
* 主流程
*/
function main() {
const config = store.load();
ensureDir(path.join(store.ROOT, 'data'));
const monitor = new Monitor({ store });
const app = createApp({ monitor });
const server = http.createServer(app);
server.on('error', (err) => {
if (err.code === 'EADDRINUSE') {
log.error(`端口 ${config.app.port} 已被占用。请修改 config/config.json 里的 app.port 后重启,`
+ '或先关闭占用该端口的程序。');
} else {
log.error('服务启动失败:', err.message);
}
process.exit(1);
});
server.listen(config.app.port, config.app.host, () => {
const displayHost = config.app.host === '0.0.0.0' ? '127.0.0.1' : config.app.host;
const url = `http://${displayHost}:${config.app.port}/`;
log.info(`配置页已就绪:${url}`);
log.info(`配置文件:${store.CONFIG_FILE}`);
log.info('按 Ctrl+C 可停止运行');
if (config.monitor.running) {
monitor.start();
} else {
log.info('监控当前处于暂停状态(配置里 monitor.running = false),可在网页点击「开始监控」');
}
if (config.app.openBrowser) openBrowser(url);
});
/** 优雅退出 */
const shutdown = (signal) => {
log.info(`收到 ${signal},正在退出…`);
monitor.stop();
server.close(() => process.exit(0));
// 兜底:3 秒内没关干净也退出
setTimeout(() => process.exit(0), 3000).unref();
};
process.on('SIGINT', () => shutdown('SIGINT'));
process.on('SIGTERM', () => shutdown('SIGTERM'));
}
main();
+881
View File
@@ -0,0 +1,881 @@
/**
* 监控引擎:
* 1. 为每个「监控品种」按各自的刷新频率(更新频率)定时抓取行情;
* 2. 每次拿到新价格后,评估阈值提醒、涨跌幅提醒、价差提醒;
* 3. 命中规则时通过桌面通知 / 邮件发出提醒,并做冷却去重、静默时段处理;
* 4. 保存最近提醒记录与规则的触发状态,重启后不会重复轰炸。
*/
const path = require('node:path');
const {
log, nowText, uid, fmtPrice, fmtPercent, inTimeRange, readJson, writeJson, appendJsonLine,
} = require('./util');
const sources = require('./sources');
const notify = require('./notify');
/** 最多保留的提醒条数(内存 + 前端展示) */
const MAX_ALERTS = 200;
/** 每个品种保留的行情点数量(迷你走势 + 滚动窗口涨跌幅都靠它) */
const MAX_HISTORY = 2400;
/** 行情点最多保留多久(毫秒),超过即裁剪 */
const HISTORY_KEEP_MS = 72 * 60 * 60 * 1000;
/** 行情历史落盘周期(毫秒) */
const HISTORY_FLUSH_MS = 10 * 60 * 1000;
class Monitor {
/**
* @param {{store: object}} deps 依赖注入,store 提供配置读写
*/
constructor({ store }) {
this.store = store;
/** @type {Map<string, NodeJS.Timeout>} 品种定时器 */
this.timers = new Map();
/** @type {Map<string, object>} 品种行情状态 */
this.quotes = new Map();
/** @type {Map<string, {met: boolean|null, lastTriggerAt: number}>} 规则触发状态 */
this.ruleStates = new Map();
/** @type {object[]} 最近提醒 */
this.alerts = [];
/** 正在抓取的品种,避免同一品种并发请求 */
this.inflight = new Set();
/** 已经提示过「单位不一致」的规则,避免日志刷屏 */
this.warnedRules = new Set();
this.running = false;
this.startedAt = null;
this.alertFile = path.join(store.ROOT, 'data', 'alerts.jsonl');
this.stateFile = path.join(store.ROOT, 'data', 'rule-state.json');
this.historyFile = path.join(store.ROOT, 'data', 'history.json');
this.saveTimer = null;
/** 行情历史定期落盘的定时器 */
this.historyTimer = null;
/** 定时提醒的巡检定时器(每 15 秒检查一次到点没到) */
this.scheduleTimer = null;
}
// ------------------------------------------------------------------
// 生命周期
// ------------------------------------------------------------------
/** 启动监控 */
start() {
if (this.running) return;
this.running = true;
this.startedAt = new Date().toISOString();
this.loadRuleStates();
this.loadAlerts();
this.loadHistory();
const cfg = this.store.get();
this.pruneMissing(cfg);
for (const inst of cfg.instruments) {
this.ensureQuoteState(inst);
if (inst.enabled && inst.intervalSec > 0) this.scheduleInstrument(inst.id);
}
// 定时把行情历史落盘,重启后「近 N 分钟涨跌幅」还能接着算
if (this.historyTimer) clearInterval(this.historyTimer);
this.historyTimer = setInterval(() => this.saveHistory(), HISTORY_FLUSH_MS);
// 定时提醒巡检:独立于行情抓取节奏,避免某些品种 60 秒一刷导致整分钟被错过
if (this.scheduleTimer) clearInterval(this.scheduleTimer);
this.scheduleTimer = setInterval(() => {
this.evaluateSchedules().catch((err) => log.error(`定时提醒巡检异常:${err.message}`));
}, 15000);
this.evaluateSchedules().catch(() => {});
log.info(`监控已启动,共 ${cfg.instruments.filter((i) => i.enabled && i.intervalSec > 0).length} 个品种在轮询`);
}
/** 停止监控(清空所有定时器) */
stop() {
for (const timer of this.timers.values()) clearTimeout(timer);
this.timers.clear();
if (this.historyTimer) {
clearInterval(this.historyTimer);
this.historyTimer = null;
}
if (this.scheduleTimer) {
clearInterval(this.scheduleTimer);
this.scheduleTimer = null;
}
this.saveHistory();
this.running = false;
log.info('监控已暂停');
}
/**
* 配置变化后重新编排定时器(增删品种、改频率、启用停用都走这里)
*/
reschedule() {
for (const timer of this.timers.values()) clearTimeout(timer);
this.timers.clear();
const cfg = this.store.get();
this.pruneMissing(cfg);
for (const inst of cfg.instruments) {
this.ensureQuoteState(inst);
if (this.running && inst.enabled && inst.intervalSec > 0) this.scheduleInstrument(inst.id);
}
}
/** 清掉配置里已删除的品种行情 */
pruneMissing(cfg) {
const ids = new Set(cfg.instruments.map((i) => i.id));
for (const key of [...this.quotes.keys()]) {
if (!ids.has(key)) this.quotes.delete(key);
}
}
/**
* 为单个品种编排循环定时器(用递归 setTimeout 避免请求堆叠)
* @param {string} id 品种 id
*/
scheduleInstrument(id) {
const old = this.timers.get(id);
if (old) clearTimeout(old);
const inst0 = this.store.get().instruments.find((i) => i.id === id);
if (!inst0 || inst0.intervalSec <= 0) return; // 手动类品种不自动轮询
const loop = async () => {
if (!this.running) return;
await this.tick(id);
if (!this.running) return;
const inst = this.store.get().instruments.find((i) => i.id === id);
if (!inst || !inst.enabled) return;
const baseMs = Math.max(5, inst.intervalSec || 30) * 1000;
// 加 0~15% 抖动,避免多个品种同一秒打接口
const jitter = Math.floor(baseMs * 0.15 * Math.random());
this.timers.set(id, setTimeout(() => { loop().catch(() => {}); }, baseMs + jitter));
};
// 首次抓取稍微错开,避免同时起跑
this.timers.set(id, setTimeout(() => { loop().catch(() => {}); }, 200 + Math.random() * 800));
}
// ------------------------------------------------------------------
// 抓取与状态维护
// ------------------------------------------------------------------
/**
* 抓取一个品种并更新状态
* @param {string} id 品种 id
* @param {{force?: boolean}} options force=true 时忽略「已暂停」状态(手动刷新用)
*/
async tick(id, options = {}) {
const force = !!options.force;
if (this.inflight.has(id)) return this.quotes.get(id);
const inst = this.store.get().instruments.find((i) => i.id === id);
if (!inst) return null;
if (!inst.enabled && !force) return this.quotes.get(id);
const state = this.ensureQuoteState(inst);
this.inflight.add(id);
try {
const quote = await sources.fetchQuote(inst, {
getManualPrice: (instId) => this.getManualPrice(instId),
});
const now = Date.now();
state.price = quote.price;
state.prevClose = quote.prevClose;
state.change = quote.change;
state.changePercent = quote.changePercent;
state.high = quote.high;
state.low = quote.low;
state.open = quote.open;
state.volume = quote.volume;
state.sourceTime = quote.sourceTime || '';
state.status = quote.extra?.manual ? 'manual' : 'ok';
state.error = null;
state.errorCount = 0;
state.updatedAt = nowText();
state.updatedAtMs = now;
this.pushHistory(state, now, quote.price);
// 评估与该品种相关的规则
await this.evaluateRules(inst);
return state;
} catch (err) {
state.errorCount += 1;
state.error = err.message;
state.status = 'error';
// 连续失败才提示日志,避免休市期刷屏
if (state.errorCount <= 3 || state.errorCount % 20 === 0) {
log.warn(`【${inst.name}】抓取失败(第 ${state.errorCount} 次):${err.message}`);
}
return state;
} finally {
this.inflight.delete(id);
}
}
/** 立即刷新所有启用的品种 */
async refreshAll() {
const cfg = this.store.get();
await Promise.all(cfg.instruments.filter((i) => i.enabled).map((i) => this.tick(i.id, { force: true })));
}
/**
* 确保品种有行情状态对象
* @param {object} inst 品种
* @returns {object}
*/
ensureQuoteState(inst) {
let state = this.quotes.get(inst.id);
if (!state) {
state = {
id: inst.id,
price: null,
prevClose: null,
change: null,
changePercent: null,
high: null,
low: null,
open: null,
volume: null,
sourceTime: '',
status: inst.enabled ? 'pending' : 'disabled',
error: null,
errorCount: 0,
updatedAt: '',
updatedAtMs: 0,
history: [],
};
this.quotes.set(inst.id, state);
}
if (!inst.enabled) state.status = 'disabled';
else if (state.status === 'disabled') state.status = 'pending';
return state;
}
/** 取手动录入的价格 */
getManualPrice(instId) {
const cfg = this.store.get();
return cfg.manualPrices?.[instId] || null;
}
/**
* 手动更新某个品种的价格(会立刻重新评估规则)
* @param {string} instId 品种 id
* @param {number} price 价格
* @param {number|null} prevClose 昨收(可选)
* @returns {Promise<object|null>} 更新后的行情状态
*/
async setManualPrice(instId, price, prevClose = null) {
const inst = this.store.get().instruments.find((i) => i.id === instId);
if (!inst) throw new Error('品种不存在');
this.store.patch({ manualPrices: { [instId]: { price, prevClose, at: nowText() } } });
const old = this.timers.get(instId);
if (old) clearTimeout(old);
if (this.running && inst.enabled && inst.intervalSec > 0) this.scheduleInstrument(instId);
return this.tick(instId, { force: true });
}
/**
* 记录一个行情点,并按「条数 + 时间」两个维度裁剪
* @param {object} state 行情状态
* @param {number} t 时间戳
* @param {number} price 价格
*/
pushHistory(state, t, price) {
state.history.push({ t, p: price });
if (state.history.length > MAX_HISTORY) state.history.splice(0, state.history.length - MAX_HISTORY);
// 砍掉超过 72 小时的老数据(正常一轮只移动很少几个点)
const cutoff = t - HISTORY_KEEP_MS;
let drop = 0;
while (drop < state.history.length && state.history[drop].t < cutoff) drop += 1;
if (drop > 0) state.history.splice(0, drop);
}
/**
* 计算「近 windowSec 秒」的涨跌幅
* @param {object} state 行情状态
* @param {number} windowSec 统计区间(秒)
* @returns {{pct: number, ref: number, refAt: number}|null} 数据不足时返回 null
*/
computeWindowChange(state, windowSec) {
const hist = state.history || [];
if (hist.length < 2 || !state.price) return null;
const target = Date.now() - windowSec * 1000;
// 历史还没覆盖到目标时刻,说明数据不够,先不评估
if (hist[0].t > target + 1500) return null;
let ref = null;
for (const point of hist) {
if (point.t <= target) ref = point;
else break;
}
if (!ref || !ref.p) return null;
return {
ref: ref.p,
refAt: ref.t,
pct: ((state.price - ref.p) / ref.p) * 100,
};
}
/**
* 统计区间的人类可读文案
* @param {number} windowSec 秒
* @returns {string}
*/
static windowLabel(windowSec) {
if (windowSec <= 0) return '日内';
if (windowSec < 60) return `近 ${windowSec} 秒`;
if (windowSec % 3600 === 0) return `近 ${windowSec / 3600} 小时`;
return `近 ${Math.round(windowSec / 60)} 分钟`;
}
// ------------------------------------------------------------------
// 规则评估
// ------------------------------------------------------------------
/**
* 评估某个品种相关的全部规则
* @param {object} inst 刚更新的品种
*/
async evaluateRules(inst) {
const cfg = this.store.get();
for (const rule of cfg.rules) {
if (!rule.enabled) continue;
// 生效时段之外直接跳过("22:00-02:00" 这类跨零点区间也支持)
if (rule.activeRange && !inTimeRange(rule.activeRange)) {
// 时段外不评估,但把状态压成「不满足」:这样进入时段后条件一旦成立,
// 仍会按边沿触发正常提醒,而不是被当成「首次评估」静默掉。
const key = rule.type === 'spread' ? `${rule.id}::spread` : `${rule.id}::${inst.id}`;
const st = this.ruleStates.get(key);
if (!st) {
this.ruleStates.set(key, { met: false, lastTriggerAt: 0 });
this.persistRuleStates();
} else if (st.met !== false) {
st.met = false;
this.persistRuleStates();
}
continue;
}
try {
if (rule.type === 'spread') {
if (rule.instrumentId === inst.id || rule.compareInstrumentId === inst.id) {
await this.evaluateSpread(rule, cfg);
}
} else if (rule.instrumentId === inst.id) {
await this.evaluateSingle(rule, inst, cfg);
}
} catch (err) {
log.error(`规则「${rule.name}」评估异常:${err.message}`);
}
}
}
/**
* 阈值 / 涨跌幅规则
* @param {object} rule 规则
* @param {object} inst 品种
* @param {object} cfg 配置
*/
async evaluateSingle(rule, inst, cfg) {
const state = this.quotes.get(inst.id);
if (!state || !state.price) return;
const price = state.price;
/** 数据源自带的日内涨跌幅(相对昨收),窗口模式会用它兜底 */
const pct0 = state.changePercent;
if (rule.type === 'threshold') {
const met = rule.direction === 'below' ? price <= rule.value : price >= rule.value;
const key = `${rule.id}::${inst.id}`;
if (!this.markAndCheck(rule, key, met, cfg)) return;
const word = rule.direction === 'below' ? '下破' : '上破';
const title = `${inst.name} ${word} ${fmtPrice(rule.value, inst.digits)} ${inst.unit}`;
const message = `最新价 ${fmtPrice(price, inst.digits)} ${inst.unit},已${word}阈值 ${fmtPrice(rule.value, inst.digits)} ${inst.unit};日内 ${fmtPercent(pct0)}。`;
await this.raise(rule, {
title,
message,
lines: [
`${inst.name} 最新价:<b>${fmtPrice(price, inst.digits)} ${inst.unit}</b>`,
`触发条件:价格${word} ${fmtPrice(rule.value, inst.digits)} ${inst.unit}`,
`日内涨跌幅:${fmtPercent(pct0)}(昨收 ${fmtPrice(state.prevClose, inst.digits)})`,
`触发时间:${nowText()}`,
],
snapshot: this.snapshot(),
}, cfg);
return;
}
if (rule.type === 'change') {
const windowSec = rule.windowSec || 0;
const label = Monitor.windowLabel(windowSec);
/** 阈值口径:percent = 涨跌幅百分比;amount = 具体价格变动值(元/克等) */
const basis = rule.changeBasis === 'amount' ? 'amount' : 'percent';
/** 当前区间内的变动幅度(percent 为百分数,amount 为价格差) */
let metric = null;
let refPrice = state.prevClose;
if (windowSec > 0) {
// 滚动窗口:拿「近 N 分钟」的起算价重新算涨跌幅
const win = this.computeWindowChange(state, windowSec);
if (!win) {
// 历史数据还没攒够:先把状态记成「不满足」,等数据齐了再由边沿触发正常判断,
// 否则第一次能算出窗口涨跌幅时会被当成「首次评估」而静默掉。
this.markAndCheck(rule, `${rule.id}::${inst.id}`, false, cfg);
// 只提示一次,避免日志刷屏
const warnKey = `${rule.id}::${inst.id}::window`;
if (!this.warnedRules.has(warnKey)) {
this.warnedRules.add(warnKey);
log.warn(`规则「${rule.name}」需要${label}的历史行情,数据还没攒够,稍后再评估`);
}
return;
}
metric = basis === 'amount' ? price - win.ref : win.pct;
refPrice = win.ref;
} else if (basis === 'amount') {
// 日内口径:优先用数据源给的涨跌额,没有就用「现价 - 昨收」兜底
if (typeof state.change === 'number') metric = state.change;
else if (typeof state.prevClose === 'number' && state.prevClose > 0) metric = price - state.prevClose;
} else {
metric = pct0;
}
if (metric === null || metric === undefined) {
// 数据不足(比如缺昨收):先压成不满足,等数据齐了再正常触发
this.markAndCheck(rule, `${rule.id}::${inst.id}`, false, cfg);
return;
}
const threshold = Math.abs(rule.value);
let met = false;
if (rule.direction === 'up') met = metric >= threshold;
else if (rule.direction === 'down') met = metric <= -threshold;
else met = Math.abs(metric) >= threshold;
const key = `${rule.id}::${inst.id}`;
if (!this.markAndCheck(rule, key, met, cfg)) return;
const word = metric >= 0 ? '涨幅' : '跌幅';
// 幅度的展示文案:百分比用 xx.xx%,具体值用「数字 + 单位」
const metricText = basis === 'amount'
? `${fmtPrice(Math.abs(metric), inst.digits)} ${inst.unit}`
: `${Math.abs(metric).toFixed(2)}%`;
const signedText = basis === 'amount'
? `${fmtPrice(metric, inst.digits)} ${inst.unit}`
: fmtPercent(metric);
const thresholdText = basis === 'amount'
? `${fmtPrice(threshold, inst.digits)} ${inst.unit}`
: `${threshold.toFixed(2)}%`;
const title = `${inst.name} ${label}${word}达 ${metricText}`;
const message = `最新价 ${fmtPrice(price, inst.digits)} ${inst.unit},${label}${word} ${signedText},已超过 ${thresholdText}的提醒线。`;
const refLine = windowSec > 0
? `${label}变动:${signedText}(${label}起算价 ${fmtPrice(refPrice, inst.digits)} ${inst.unit})`
: basis === 'amount'
? `日内变动:${signedText}(昨收 ${fmtPrice(state.prevClose, inst.digits)} ${inst.unit})`
: `${label}涨跌幅:${fmtPercent(pct0)}(昨收 ${fmtPrice(state.prevClose, inst.digits)})`;
await this.raise(rule, {
title,
message,
lines: [
`${inst.name} 最新价:<b>${fmtPrice(price, inst.digits)} ${inst.unit}</b>`,
refLine,
`触发条件:${word} ≥ ${thresholdText}(${label})`,
`触发时间:${nowText()}`,
],
snapshot: this.snapshot(),
}, cfg);
}
}
/**
* 价差规则:两个品种价差超过阈值
* @param {object} rule 规则
* @param {object} cfg 配置
*/
async evaluateSpread(rule, cfg) {
const leftInst = cfg.instruments.find((i) => i.id === rule.instrumentId);
const rightInst = cfg.instruments.find((i) => i.id === rule.compareInstrumentId);
if (!leftInst || !rightInst) return;
const left = this.quotes.get(rule.instrumentId);
const right = this.quotes.get(rule.compareInstrumentId);
if (!left?.price || !right?.price) return;
// 单位不一致时无法比较价差
if (leftInst.unit !== rightInst.unit) {
if (!this.warnedRules.has(rule.id)) {
this.warnedRules.add(rule.id);
log.warn(`规则「${rule.name}」两个品种单位不一致(${leftInst.unit} / ${rightInst.unit}),已跳过`);
}
return;
}
const diff = left.price - right.price;
const value = rule.mode === 'percent' ? (diff / right.price) * 100 : diff;
const absThreshold = Math.abs(rule.value);
let met = false;
if (rule.direction === 'above') met = value >= absThreshold;
else if (rule.direction === 'below') met = value <= -absThreshold;
else met = Math.abs(value) >= absThreshold;
const key = `${rule.id}::spread`;
if (!this.markAndCheck(rule, key, met, cfg)) return;
const unitText = rule.mode === 'percent' ? '%' : leftInst.unit;
const valText = value.toFixed(rule.mode === 'percent' ? 2 : leftInst.digits);
const title = `${leftInst.name} 与 ${rightInst.name} 价差 ${valText}${rule.mode === 'percent' ? '%' : ` ${unitText}`}`;
const message = `当前 ${leftInst.name} ${fmtPrice(left.price, leftInst.digits)} ${leftInst.unit},`
+ `${rightInst.name} ${fmtPrice(right.price, rightInst.digits)} ${rightInst.unit},`
+ `价差 ${valText}${rule.mode === 'percent' ? '%' : ` ${unitText}`}(阈值 ${absThreshold})。`;
await this.raise(rule, {
title,
message,
lines: [
`${leftInst.name}:<b>${fmtPrice(left.price, leftInst.digits)} ${leftInst.unit}</b>`,
`${rightInst.name}:<b>${fmtPrice(right.price, rightInst.digits)} ${rightInst.unit}</b>`,
`价差:${valText}${rule.mode === 'percent' ? '%' : ` ${unitText}`}(触发阈值 ${absThreshold}${rule.mode === 'percent' ? '%' : ` ${unitText}`})`,
`触发时间:${nowText()}`,
],
snapshot: this.snapshot(),
}, cfg);
}
// ------------------------------------------------------------------
// 定时提醒
// ------------------------------------------------------------------
/**
* 判断某天是否命中定时规则的重复方式
* @param {object} rule 规则
* @param {Date} date 当前时间
* @returns {boolean} 当天是否需要提醒
*/
matchScheduleDay(rule, date) {
const repeat = rule.scheduleRepeat || 'daily';
/** getDay() 里周日是 0,这里换成 ISO 口径:周一=1 … 周日=7 */
const iso = date.getDay() === 0 ? 7 : date.getDay();
if (repeat === 'weekday') return iso <= 5;
if (repeat === 'weekly') return (rule.scheduleWeekdays || []).includes(iso);
return true;
}
/**
* 巡检所有定时提醒规则:到点了就发一条提醒。
* 容错窗口 2 分钟(巡检 15 秒一次,加上抓取抖动也不会漏掉整分钟);
* 同一档时刻(同一天同一时刻)只响一次,去重状态写进 data/rule-state.json,重启也不会重复提醒。
*/
async evaluateSchedules() {
if (!this.running) return;
const cfg = this.store.get();
const now = new Date();
const nowMs = now.getTime();
const pad = (n) => String(n).padStart(2, '0');
const dateKey = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
for (const rule of cfg.rules) {
if (rule.type !== 'schedule' || !rule.enabled) continue;
if (!this.matchScheduleDay(rule, now)) continue;
for (const time of rule.scheduleTimes || []) {
const [hh, mm] = time.split(':').map(Number);
const slotMs = new Date(now.getFullYear(), now.getMonth(), now.getDate(), hh, mm, 0, 0).getTime();
const diff = nowMs - slotMs;
if (diff < 0 || diff > 120000) continue; // 还没到点,或者已经错过 2 分钟以上
const stateKey = `${rule.id}::schedule::${dateKey} ${time}`;
if (this.ruleStates.has(stateKey)) continue; // 这一档今天已经响过
this.ruleStates.set(stateKey, { met: true, lastTriggerAt: nowMs });
this.persistRuleStates();
await this.fireSchedule(rule, time, cfg);
}
}
this.pruneScheduleStates();
}
/**
* 发送一条定时提醒,正文带上该品种的最新行情,方便一眼看到当时的价格
* @param {object} rule 定时规则
* @param {string} time 命中的时刻,如 "09:00"
* @param {object} cfg 配置
*/
async fireSchedule(rule, time, cfg) {
const inst = cfg.instruments.find((i) => i.id === rule.instrumentId);
const state = inst ? this.quotes.get(inst.id) : null;
const hasPrice = !!(inst && state && state.price);
const repeatText = rule.scheduleRepeat === 'weekday' ? '工作日' : rule.scheduleRepeat === 'weekly' ? '每周' : '每天';
const title = `${inst?.name || '定时提醒'} ${time} 定时提醒`;
const message = hasPrice
? `${repeatText} ${time} 定时提醒:${inst.name} 最新价 ${fmtPrice(state.price, inst.digits)} ${inst.unit},日内 ${fmtPercent(state.changePercent)}。`
: `${repeatText} ${time} 定时提醒:${inst?.name || '未绑定品种'}${state?.status === 'error' ? `,当前抓取失败(${state.error || '未知原因'})` : ',暂无行情数据'}。`;
await this.raise(rule, {
title,
message,
lines: [
hasPrice
? `${inst.name} 最新价:<b>${fmtPrice(state.price, inst.digits)} ${inst.unit}</b>`
: `${inst?.name || '未绑定品种'}:暂无行情`,
hasPrice
? `日内涨跌:${fmtPercent(state.changePercent)}(昨收 ${fmtPrice(state.prevClose, inst.digits)} ${inst.unit})`
: `数据状态:${state?.status === 'error' ? (state.error || '抓取失败') : '暂无行情'}`,
`提醒时刻:${repeatText} ${(rule.scheduleTimes || []).join('、')}`,
`触发时间:${nowText()}`,
],
snapshot: this.snapshot(),
}, cfg);
}
/** 清掉 3 天前的定时提醒去重记录,避免 rule-state.json 越攒越大 */
pruneScheduleStates() {
const cutoff = Date.now() - 3 * 24 * 60 * 60 * 1000;
let changed = false;
for (const [key, value] of [...this.ruleStates.entries()]) {
if (!key.includes('::schedule::')) continue;
if (!value || Number(value.lastTriggerAt) < cutoff) {
this.ruleStates.delete(key);
changed = true;
}
}
if (changed) this.persistRuleStates();
}
/**
* 记录规则当前是否满足,并判断此刻是否应该发提醒。
* 采用「边沿触发」:只有从「不满足」变成「满足」才提醒(可选按 repeatIntervalSec 重复)。
* @param {object} rule 规则
* @param {string} key 状态键
* @param {boolean} met 当前是否满足
* @param {object} cfg 配置
* @returns {boolean} 是否触发
*/
markAndCheck(rule, key, met, cfg) {
const now = Date.now();
let state = this.ruleStates.get(key);
const isFirst = !state;
if (!state) state = { met: null, lastTriggerAt: 0 };
const cooldownMs = (rule.cooldownSec || 0) * 1000;
let trigger = false;
if (met) {
if (isFirst) {
// 首次评估:默认不打扰(可配置成也提醒),但把状态记下来
trigger = cfg.monitor?.alertOnFirstCheck === true;
} else if (state.met !== true) {
trigger = true;
} else if (rule.repeatIntervalSec > 0 && now - state.lastTriggerAt >= rule.repeatIntervalSec * 1000) {
trigger = true;
}
}
if (trigger && cooldownMs > 0 && now - state.lastTriggerAt < cooldownMs) trigger = false;
state.met = met;
if (trigger) state.lastTriggerAt = now;
this.ruleStates.set(key, state);
this.persistRuleStates();
return trigger;
}
/**
* 组装一条提醒并分发到各通知渠道
* @param {object} rule 规则
* @param {{title: string, message: string, lines: string[], snapshot: object[]}} content 内容
* @param {object} cfg 配置
*/
async raise(rule, content, cfg) {
const channels = Array.isArray(rule.channels) && rule.channels.length ? rule.channels : cfg.channels.onTrigger;
const quietCfg = cfg.monitor?.quietHours || {};
const quietActive = !!quietCfg.enabled
&& inTimeRange(quietCfg.range)
&& quietCfg.desktopOnly !== false;
const alert = {
id: uid('alert'),
at: nowText(),
atMs: Date.now(),
ruleId: rule.id,
ruleName: rule.name,
title: content.title,
message: content.message,
lines: content.lines,
channels,
quietActive,
};
log.info(`🔔 触发提醒:${content.title}`);
const delivered = await notify.dispatch(alert, channels, { config: cfg, quietActive });
alert.delivered = delivered;
this.alerts.unshift(alert);
if (this.alerts.length > MAX_ALERTS) this.alerts.length = MAX_ALERTS;
try {
appendJsonLine(this.alertFile, {
at: alert.at,
ruleId: alert.ruleId,
ruleName: alert.ruleName,
title: alert.title,
message: alert.message,
channels,
delivered,
});
} catch (err) {
log.warn(`提醒日志写入失败:${err.message}`);
}
return alert;
}
/** 当前所有品种的行情快照(供邮件正文使用) */
snapshot() {
const cfg = this.store.get();
return cfg.instruments
.filter((i) => i.enabled)
.map((i) => {
const q = this.quotes.get(i.id);
return {
name: i.name,
price: q?.price ?? null,
unit: i.unit,
digits: i.digits,
changePercent: q?.changePercent ?? null,
};
})
.filter((i) => i.price);
}
// ------------------------------------------------------------------
// 状态持久化
// ------------------------------------------------------------------
/** 读取历史提醒(保留最近 MAX_ALERTS 条用于页面展示) */
loadAlerts() {
if (this.alerts.length) return;
try {
const fs = require('node:fs');
if (!fs.existsSync(this.alertFile)) return;
const lines = fs.readFileSync(this.alertFile, 'utf8').trim().split('\n').slice(-MAX_ALERTS);
this.alerts = lines
.map((line) => {
try { return JSON.parse(line); } catch { return null; }
})
.filter(Boolean)
.map((item) => ({ ...item, lines: item.lines || [] }))
.reverse();
} catch (err) {
log.warn(`读取历史提醒失败:${err.message}`);
}
}
/**
* 清空提醒记录:内存数组和 data/alerts.jsonl 一起清掉,
* 否则重启后旧记录又会从文件里读回来
*/
clearAlerts() {
this.alerts.length = 0;
try {
const fs = require('node:fs');
fs.writeFileSync(this.alertFile, '');
} catch (err) {
log.warn(`清空提醒记录文件失败:${err.message}`);
}
}
/** 读取规则触发状态 */
loadRuleStates() {
const saved = readJson(this.stateFile, null);
if (!saved) return;
for (const [key, value] of Object.entries(saved)) {
if (value && typeof value === 'object') {
this.ruleStates.set(key, { met: value.met === true ? true : (value.met === false ? false : null), lastTriggerAt: Number(value.lastTriggerAt) || 0 });
}
}
}
/** 延迟落盘规则状态,避免频繁写文件 */
persistRuleStates() {
if (this.saveTimer) return;
this.saveTimer = setTimeout(() => {
this.saveTimer = null;
const plain = {};
for (const [key, value] of this.ruleStates) plain[key] = value;
try {
writeJson(this.stateFile, plain);
} catch (err) {
log.warn(`规则状态保存失败:${err.message}`);
}
}, 1000);
}
/**
* 读取落盘的行情历史,让「近 N 分钟涨跌幅」在重启后也能立刻算
* (只恢复价格点,不恢复涨跌额等展示字段)
*/
loadHistory() {
const saved = readJson(this.historyFile, null);
if (!saved || typeof saved !== 'object') return;
const cutoff = Date.now() - HISTORY_KEEP_MS;
for (const [instId, points] of Object.entries(saved)) {
if (!Array.isArray(points) || points.length === 0) continue;
const state = this.ensureQuoteState({ id: instId, enabled: true });
const clean = points
.filter((p) => p && Number.isFinite(Number(p.t)) && Number.isFinite(Number(p.p)))
.map((p) => ({ t: Number(p.t), p: Number(p.p) }))
.filter((p) => p.t >= cutoff);
if (clean.length) {
state.history = clean.slice(-MAX_HISTORY);
const last = state.history[state.history.length - 1];
// 用最后一个点兜底填充展示价格,避免刚启动时卡片空着
if (!state.price) {
state.price = last.p;
state.updatedAtMs = last.t;
state.updatedAt = nowText(new Date(last.t));
}
}
}
}
/** 把各品种的行情历史落盘(体积很小,10 分钟一次即可) */
saveHistory() {
const plain = {};
for (const [instId, state] of this.quotes) {
if (state.history && state.history.length) plain[instId] = state.history;
}
try {
writeJson(this.historyFile, plain);
} catch (err) {
log.warn(`行情历史保存失败:${err.message}`);
}
}
// ------------------------------------------------------------------
// 对前端输出
// ------------------------------------------------------------------
/** 汇总给网页的状态 */
getState() {
const cfg = this.store.get();
const quietCfg = cfg.monitor?.quietHours || {};
const quietActive = !!quietCfg.enabled && inTimeRange(quietCfg.range);
return {
running: this.running,
startedAt: this.startedAt,
serverTime: nowText(),
quietActive,
rules: cfg.rules,
instruments: cfg.instruments.map((inst) => {
const q = this.quotes.get(inst.id) || {};
return {
...inst,
price: q.price ?? null,
prevClose: q.prevClose ?? null,
change: q.change ?? null,
changePercent: q.changePercent ?? null,
high: q.high ?? null,
low: q.low ?? null,
open: q.open ?? null,
sourceTime: q.sourceTime || '',
status: inst.enabled ? (q.status || 'pending') : 'disabled',
error: q.error || null,
errorCount: q.errorCount || 0,
updatedAt: q.updatedAt || '',
history: (q.history || []).slice(-60),
manualPrice: cfg.manualPrices?.[inst.id] || null,
};
}),
alerts: this.alerts.slice(0, 50),
};
}
}
module.exports = { Monitor };
+129
View File
@@ -0,0 +1,129 @@
/**
* Windows 桌面通知(Toast)。
* 实现方式:调用系统自带的 Windows PowerShell 5.1,用 WinRT 的
* Windows.UI.Notifications 弹出一条原生 Toast,不依赖第三方 EXE。
*
* 说明:PowerShell 7(pwsh)默认没有 WinRT 投影,所以这里固定用 powershell.exe。
*/
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const crypto = require('node:crypto');
const { spawnSync } = require('node:child_process');
/** 已注册可用于 Toast 的 AppUserModelID(Windows PowerShell 自带,实测可弹出) */
const APP_ID = '{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe';
/**
* 转义 XML 文本
* @param {string} text
* @returns {string}
*/
function escapeXml(text) {
return String(text)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;');
}
/**
* 解码子进程输出(优先按 GBK,失败回退 UTF-8)
* @param {Buffer|string} buffer 原始输出
* @returns {string}
*/
function decodeConsole(buffer) {
if (!buffer) return '';
if (typeof buffer === 'string') return buffer;
try {
return new TextDecoder('gbk').decode(buffer);
} catch {
return buffer.toString('utf8');
}
}
/**
* 生成 Toast 的 XML 内容(首行标题,其余为正文)
* @param {string} title 标题
* @param {string} message 正文
* @returns {string}
*/
function buildToastXml(title, message) {
const body = String(message || '').split(/\r?\n/).slice(0, 4).map((line) => `<text>${escapeXml(line)}</text>`).join('');
return `<toast duration="long" scenario="reminder"><visual><binding template="ToastGeneric">`
+ `<text>${escapeXml(title)}</text>${body}</binding></visual>`
+ `<audio src="ms-winsoundevent:Notification.Reminder"/></toast>`;
}
/**
* 弹出一条桌面通知(同步等待,最多 15 秒)
* @param {{title: string, message: string}} payload 通知内容
* @returns {{ok: boolean, error?: string}}
*/
function send(payload) {
if (process.platform !== 'win32') {
return { ok: false, error: '当前系统不是 Windows,桌面通知不可用' };
}
const title = String(payload?.title || '金价提醒').slice(0, 60);
const message = String(payload?.message || '').slice(0, 400);
const xml = buildToastXml(title, message);
// 把 XML 直接内嵌进脚本,避免命令行传中文时的编码问题
const script = [
'$ErrorActionPreference = "Stop"',
'try {',
' [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null',
' [Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null',
' $xmlText = @\'',
xml,
'\'@',
' $doc = New-Object Windows.Data.Xml.Dom.XmlDocument',
' $doc.LoadXml($xmlText)',
' $toast = [Windows.UI.Notifications.ToastNotification]::new($doc)',
` [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('${APP_ID}').Show($toast)`,
' Write-Output "OK"',
'} catch {',
' Write-Output ("ERR:" + $_.Exception.Message)',
' exit 1',
'}',
].join('\r\n');
const tmpDir = os.tmpdir();
const file = path.join(tmpDir, `gold-toast-${crypto.randomBytes(4).toString('hex')}.ps1`);
try {
// 带 BOM 写入,保证 powershell.exe 正确按 UTF-8 读取中文
fs.writeFileSync(file, `\uFEFF${script}`, { encoding: 'utf8' });
const result = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', file], {
timeout: 15000,
windowsHide: true,
encoding: 'buffer',
});
if (result.error) return { ok: false, error: `调用 PowerShell 失败:${result.error.message}` };
// powershell.exe 的输出是控制台代码页(中文系统为 GBK),这里统一解码
const stdout = decodeConsole(result.stdout).trim();
if (result.status !== 0) {
return { ok: false, error: stdout.replace(/^ERR:/, '').trim() || `PowerShell 退出码 ${result.status}` };
}
return { ok: true };
} catch (err) {
return { ok: false, error: err.message };
} finally {
fs.promises.unlink(file).catch(() => {});
}
}
/**
* 桌面通知自检:弹一条测试消息
* @returns {{ok: boolean, detail: string}}
*/
function selfTest() {
const r = send({ title: '金价提醒 · 测试', message: '如果你看到这条通知,说明桌面提醒可用。' });
return { ok: r.ok, detail: r.ok ? '已发送一条测试通知(请查看右下角通知中心)' : (r.error || '未知错误') };
}
module.exports = { send, selfTest, APP_ID };
+145
View File
@@ -0,0 +1,145 @@
/**
* 邮箱提醒通道(SMTP,基于 nodemailer)。
* 常见配置:QQ 邮箱 smtp.qq.com:465、163 smtp.163.com:465、企业邮箱按服务商说明填。
* 注意:多数邮箱需要「授权码」而不是登录密码。
*/
const nodemailer = require('nodemailer');
const { fmtPrice, fmtPercent, nowText } = require('../util');
/**
* 校验邮箱配置是否完整
* @param {object} cfg email 配置
* @returns {string|null} 错误信息,null 表示可用
*/
function validate(cfg) {
if (!cfg) return '缺少邮箱配置';
if (!cfg.host) return '未填写 SMTP 服务器';
if (!cfg.user) return '未填写发件邮箱账号';
if (!cfg.pass) return '未填写邮箱密码/授权码';
if (!cfg.to || cfg.to.length === 0) return '未填写收件邮箱';
return null;
}
/**
* 创建 SMTP 传输对象(每次新建,配置改了立刻生效)
* @param {object} cfg email 配置
*/
function createTransport(cfg) {
return nodemailer.createTransport({
host: cfg.host,
port: cfg.port,
secure: !!cfg.secure,
auth: { user: cfg.user, pass: cfg.pass },
// 国内邮箱服务器证书链偶有问题,这里放行但不影响加密传输
tls: { rejectUnauthorized: false },
connectionTimeout: 15000,
greetingTimeout: 12000,
socketTimeout: 20000,
});
}
/**
* 把 SMTP 错误翻译成更容易理解的提示
* @param {Error} err
* @returns {string}
*/
function friendlyError(err) {
const msg = err?.message || String(err);
if (/Invalid login|535|EAUTH/i.test(msg)) return `邮箱认证失败,请检查账号与授权码(${msg})`;
if (/ETIMEDOUT|ECONNREFUSED|ENOTFOUND|EAI_AGAIN/i.test(msg)) return `连不上 SMTP 服务器,请检查地址/端口/网络(${msg})`;
if (/self signed|CERT/i.test(msg)) return `SMTP 证书校验失败(${msg})`;
return msg;
}
/**
* 发送邮件
* @param {object} cfg email 配置
* @param {{subject: string, text: string, html?: string}} content 邮件内容
* @returns {Promise<{ok: boolean, error?: string, messageId?: string}>}
*/
async function send(cfg, content) {
const invalid = validate(cfg);
if (invalid) return { ok: false, error: invalid };
try {
const transporter = createTransport(cfg);
const info = await transporter.sendMail({
from: cfg.from || cfg.user,
to: cfg.to.join(', '),
subject: content.subject,
text: content.text,
html: content.html,
});
return { ok: true, messageId: info.messageId };
} catch (err) {
return { ok: false, error: friendlyError(err) };
}
}
/**
* 连通性自检:登录 SMTP 服务器并发送一封测试邮件
* @param {object} cfg email 配置
* @returns {Promise<{ok: boolean, detail: string}>}
*/
async function selfTest(cfg) {
const invalid = validate(cfg);
if (invalid) return { ok: false, detail: invalid };
try {
const transporter = createTransport(cfg);
await transporter.verify();
const result = await send(cfg, {
subject: `${cfg.subjectPrefix || '【金价提醒】'}这是一封测试邮件`,
text: `金价提醒工具连接成功。\n发送时间:${nowText()}\n收到这封邮件说明 SMTP 配置正确,触发提醒时会自动发到这里。`,
html: renderHtml({
title: 'SMTP 配置测试成功',
lines: [
'收到这封邮件说明邮箱提醒已经可用。',
`发送时间:${nowText()}`,
'之后金价触发阈值或价差时,会自动把提醒发到这个邮箱。',
],
snapshot: [],
}),
});
if (!result.ok) return { ok: false, detail: result.error || '发送失败' };
return { ok: true, detail: `测试邮件已发送至 ${cfg.to.join(', ')}` };
} catch (err) {
return { ok: false, detail: friendlyError(err) };
}
}
/**
* 生成统一风格的 HTML 邮件正文
* @param {{title: string, subtitle?: string, lines: string[], snapshot: Array<object>, footNote?: string}} data
* @returns {string}
*/
function renderHtml(data) {
const rows = (data.snapshot || []).map((item) => `
<tr>
<td style="padding:8px 0;color:#333;">${item.name}</td>
<td style="padding:8px 0;color:#111;font-weight:600;text-align:right;">${fmtPrice(item.price, item.digits ?? 2)} <span style="color:#999;font-weight:400;">${item.unit || ''}</span></td>
<td style="padding:8px 0;text-align:right;color:${item.changePercent > 0 ? '#d4380d' : item.changePercent < 0 ? '#389e0d' : '#666'};">${fmtPercent(item.changePercent)}</td>
</tr>`).join('');
return `<!DOCTYPE html><html><body style="margin:0;padding:24px;background:#f5f6f8;font-family:'Microsoft YaHei',Arial,sans-serif;">
<div style="max-width:560px;margin:0 auto;background:#fff;border-radius:12px;overflow:hidden;border:1px solid #eee;">
<div style="padding:20px 24px;background:linear-gradient(135deg,#1f1a12,#3a2f1d);color:#f7e7b7;">
<div style="font-size:12px;letter-spacing:2px;opacity:.7;">GOLD PRICE WATCHER</div>
<div style="font-size:20px;font-weight:700;margin-top:6px;">${data.title}</div>
${data.subtitle ? `<div style="font-size:13px;opacity:.85;margin-top:6px;">${data.subtitle}</div>` : ''}
</div>
<div style="padding:20px 24px;color:#333;font-size:14px;line-height:1.7;">
${(data.lines || []).map((line) => `<p style="margin:0 0 10px;">${line}</p>`).join('')}
${rows ? `<div style="margin-top:16px;padding-top:12px;border-top:1px dashed #eee;">
<div style="font-size:12px;color:#999;margin-bottom:6px;">当前行情快照</div>
<table style="width:100%;border-collapse:collapse;font-size:13px;">${rows}</table>
</div>` : ''}
</div>
<div style="padding:14px 24px;background:#fafafa;color:#999;font-size:12px;">
${data.footNote || '此邮件由本地「金价提醒」工具自动发送。如需调整规则,请打开配置页修改。'}
</div>
</div>
</body></html>`;
}
module.exports = { send, selfTest, validate, renderHtml, friendlyError };
+86
View File
@@ -0,0 +1,86 @@
/**
* 通知调度层:把一条提醒分发到「桌面通知 / 邮件 / WebHook」等渠道,并汇总发送结果。
*/
const desktop = require('./desktop');
const email = require('./email');
const webhook = require('./webhook');
const { log } = require('../util');
/**
* 分发一条提醒
* @param {object} alert 提醒对象(含 title/message/lines/snapshot)
* @param {string[]} channels 目标渠道
* @param {{config: object, quietActive?: boolean}} options 运行参数
* @returns {Promise<Array<{channel: string, ok: boolean, error?: string, muted?: boolean}>>}
*/
async function dispatch(alert, channels, options) {
const config = options?.config || {};
const quietActive = !!options?.quietActive;
const targets = Array.isArray(channels) && channels.length ? channels : ['desktop'];
const results = await Promise.all(targets.map(async (channel) => {
if (channel === 'desktop') {
if (!config.desktop?.enabled) return { channel, ok: false, error: '桌面通知未开启' };
if (quietActive) return { channel, ok: false, muted: true, error: '处于静默时段,已跳过桌面通知' };
const r = desktop.send({
title: alert.title,
message: alert.message,
});
return { channel, ok: r.ok, error: r.error };
}
if (channel === 'email') {
if (!config.email?.enabled) return { channel, ok: false, error: '邮箱提醒未开启' };
const prefix = config.email.subjectPrefix || '【金价提醒】';
const r = await email.send(config.email, {
subject: `${prefix}${alert.title}`,
text: [alert.title, '', ...(alert.lines || []), '', '此邮件由本地「金价提醒」工具自动发送。'].join('\n'),
html: email.renderHtml({
title: alert.title,
subtitle: alert.ruleName,
lines: alert.lines || [],
snapshot: config.email.withSnapshot === false ? [] : (alert.snapshot || []),
}),
});
return { channel, ok: r.ok, error: r.error };
}
if (channel === 'webhook') {
if (!config.webhook?.enabled) return { channel, ok: false, error: 'WebHook 推送未开启' };
const r = await webhook.send(config.webhook, alert);
return { channel, ok: r.ok, error: r.error };
}
return { channel, ok: false, error: `未知通知渠道:${channel}` };
}));
for (const r of results) {
if (!r.ok && !r.muted) log.warn(`提醒渠道 ${r.channel} 发送失败:${r.error}`);
}
return results;
}
/**
* 桌面通知自检
* @returns {{ok: boolean, detail: string}}
*/
function testDesktop() {
return desktop.selfTest();
}
/**
* 邮件自检
* @param {object} emailConfig
* @returns {Promise<{ok: boolean, detail: string}>}
*/
async function testEmail(emailConfig) {
return email.selfTest(emailConfig);
}
/**
* WebHook 自检
* @param {object} webhookConfig
* @returns {Promise<{ok: boolean, detail: string}>}
*/
async function testWebhook(webhookConfig) {
return webhook.selfTest(webhookConfig);
}
module.exports = { dispatch, testDesktop, testEmail, testWebhook };
+234
View File
@@ -0,0 +1,234 @@
/**
* WebHook 推送通道。
* 支持两种报文格式:
* - generic :本工具自带的 JSON 结构(字段稳定,方便自建服务、运维平台或自动化脚本消费);
* - dingtalk :钉钉自定义机器人的 markdown 报文,填了「加签密钥」会自动拼接 timestamp + sign。
*
* 全部用 Node 内置 fetch 实现,不额外引入依赖。
*/
const crypto = require('node:crypto');
const { nowText } = require('../util');
/** 支持的报文格式 */
const FORMATS = ['generic', 'dingtalk'];
/** 单次请求超时(毫秒) */
const TIMEOUT_MS = 10000;
/** 兜底成合法格式 */
function normalizeFormat(value) {
return FORMATS.includes(value) ? value : 'generic';
}
/**
* 校验 WebHook 配置是否可用
* @param {object} cfg webhook 配置
* @returns {string|null} 错误信息,null 表示可用
*/
function validate(cfg) {
if (!cfg) return '缺少 WebHook 配置';
if (!cfg.url) return '未填写 WebHook 地址';
if (!/^https?:\/\//i.test(String(cfg.url).trim())) return 'WebHook 地址需要以 http:// 或 https:// 开头';
// 配置层会兜底成 generic,这里主要拦「测试时临时传了非法格式」
if (cfg.format && !FORMATS.includes(String(cfg.format))) return `不支持的报文格式:${cfg.format}`;
return null;
}
/**
* 生成钉钉「加签」后的地址
* 算法:sign = base64(hmacSHA256(secret, `${timestamp}\n${secret}`))
* @param {string} url 机器人地址
* @param {string} secret 加签密钥
* @returns {string} 带 timestamp / sign 参数的地址
*/
function signedUrl(url, secret) {
const timestamp = Date.now();
const stringToSign = `${timestamp}\n${secret}`;
const sign = crypto.createHmac('sha256', secret).update(stringToSign).digest('base64');
const u = new URL(url);
u.searchParams.set('timestamp', String(timestamp));
u.searchParams.set('sign', sign);
return u.toString();
}
/**
* 把提醒里的 HTML 粗体标签换成 markdown 的 ** **,保证钉钉里显示正常
* @param {string} text
* @returns {string}
*/
function toMarkdownText(text) {
return String(text).replace(/<\/?b>/g, '**');
}
/**
* 组装 markdown 正文(钉钉与内置格式共用)
* @param {object} alert 提醒对象
* @returns {string}
*/
function toMarkdown(alert) {
const title = `### ${alert.title}`;
const lines = (alert.lines || []).map((line) => `- ${toMarkdownText(line)}`);
const foot = '> 来自本地「金价提醒」· Gold Price Watcher';
return [title, '', ...lines, '', foot].join('\n');
}
/**
* 按格式组装请求体
* @param {object} alert 提醒对象
* @param {object} cfg webhook 配置
* @returns {object} 请求体
*/
function buildPayload(alert, cfg) {
const format = normalizeFormat(cfg.format);
const keyword = String(cfg.keyword || '').trim();
if (format === 'dingtalk') {
// 机器人若开了「自定义关键词」安全设置,消息里必须出现该词,这里直接拼到标题上
const title = keyword ? `${keyword}|${alert.title}` : alert.title;
const markdown = toMarkdown({ ...alert, title });
const atMobiles = Array.isArray(cfg.atMobiles) ? cfg.atMobiles.filter(Boolean) : [];
return {
msgtype: 'markdown',
markdown: { title, text: markdown },
at: {
atMobiles,
isAtAll: !!cfg.mentionAll,
},
};
}
// 内置格式:字段固定,第三方系统按需取用
return {
event: 'gold_price_alert',
title: alert.title,
message: alert.message || '',
markdown: toMarkdown(alert),
at: alert.at || nowText(),
rule: { id: alert.ruleId || '', name: alert.ruleName || '' },
lines: (alert.lines || []).map((line) => toMarkdownText(line)),
source: 'gold-price-watcher',
};
}
/**
* 把 fetch 抛出的错误翻译成更好理解的提示
* @param {Error} err
* @returns {string}
*/
function friendlyError(err) {
const name = err?.name || '';
const msg = err?.message || String(err);
// Node 的 fetch 只抛 "fetch failed",真正的网络错误码在 cause 里
const cause = err?.cause || {};
const code = String(cause.code || err?.code || '');
const causeMsg = cause.message ? `:${cause.message}` : '';
if (name === 'TimeoutError' || code === 'UND_ERR_CONNECT_TIMEOUT' || /aborted|timeout/i.test(msg)) {
return `请求超时(${TIMEOUT_MS / 1000} 秒),请检查地址是否可访问`;
}
if (code === 'ENOTFOUND' || code === 'EAI_AGAIN') return `域名解析失败,请检查 WebHook 地址${causeMsg}`;
if (code === 'ECONNREFUSED') return `连接被拒绝,请检查地址与端口${causeMsg}`;
if (code === 'EHOSTUNREACH' || code === 'ENETUNREACH') return `网络不可达,请检查本机网络或代理设置${causeMsg}`;
if (code === 'CERT_HAS_EXPIRED' || /certificate|CERT/i.test(msg) || /certificate/i.test(String(cause.message))) {
return `HTTPS 证书校验失败${causeMsg}`;
}
if (/fetch failed/i.test(msg) && causeMsg) return `请求失败${causeMsg}`;
return msg;
}
/**
* 钉钉返回码翻译
* @param {number} errcode
* @param {string} errmsg
* @returns {string}
*/
function dingTalkError(errcode, errmsg) {
const msg = String(errmsg || '');
// 钉钉把「加签不匹配」和「自定义关键词不匹配」都归到 310000,需要看 errmsg 才能区分
if (errcode === 310000) {
if (/关键词/.test(msg)) {
return `钉钉机器人开了「自定义关键词」,消息里必须包含它:把关键词填到「钉钉关键词」,工具会自动拼进标题(${msg})`;
}
if (/签名|sign/i.test(msg)) {
return `钉钉签名校验失败:请检查加签密钥,或机器人没开加签却填了密钥(${msg})`;
}
return `钉钉安全校验失败:${msg}`;
}
const map = {
300001: '钉钉机器人 token 无效,请检查 WebHook 地址是否完整',
130101: '钉钉发送太频繁(每分钟上限 20 条),稍后再试',
400013: '钉钉机器人已被停用或不在群内',
};
const hint = map[errcode];
return hint ? `${hint}(errcode=${errcode}${msg ? `,${msg}` : ''})` : `钉钉返回错误:${msg || '未知错误'}(errcode=${errcode})`;
}
/**
* 发送一条提醒到 WebHook
* @param {object} cfg webhook 配置
* @param {object} alert 提醒对象
* @returns {Promise<{ok: boolean, error?: string, detail?: string}>}
*/
async function send(cfg, alert) {
const invalid = validate(cfg);
if (invalid) return { ok: false, error: invalid };
const format = normalizeFormat(cfg.format);
const url = format === 'dingtalk' && cfg.secret ? signedUrl(String(cfg.url).trim(), cfg.secret) : String(cfg.url).trim();
const payload = buildPayload(alert, cfg);
try {
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json; charset=utf-8' },
body: JSON.stringify(payload),
signal: AbortSignal.timeout(TIMEOUT_MS),
});
const text = await res.text().catch(() => '');
if (!res.ok) {
return { ok: false, error: `HTTP ${res.status}${text ? `:${text.slice(0, 200)}` : ''}` };
}
// 钉钉就算 HTTP 200,也可能在 body 里返回 errcode 报错
if (format === 'dingtalk' && text) {
let data = null;
try {
data = JSON.parse(text);
} catch {
data = null;
}
if (data && typeof data.errcode === 'number' && data.errcode !== 0) {
return { ok: false, error: dingTalkError(data.errcode, data.errmsg) };
}
}
return { ok: true, detail: `推送成功(HTTP ${res.status})` };
} catch (err) {
return { ok: false, error: friendlyError(err) };
}
}
/**
* 连通性自检:推一条测试消息
* @param {object} cfg webhook 配置
* @returns {Promise<{ok: boolean, detail: string}>}
*/
async function selfTest(cfg) {
const invalid = validate(cfg);
if (invalid) return { ok: false, detail: invalid };
const format = normalizeFormat(cfg.format);
const result = await send(cfg, {
title: 'WebHook 推送测试',
message: '这是一条来自本地「金价提醒」工具的测试推送。',
lines: [
'收到这条消息说明 WebHook 配置可用。',
`报文格式:${format === 'dingtalk' ? '钉钉机器人(markdown)' : '内置 JSON'}`,
`发送时间:${nowText()}`,
'之后触发价格阈值、涨跌幅或价差规则时,会自动推到这里。',
],
at: nowText(),
});
if (!result.ok) return { ok: false, detail: result.error || '推送失败' };
return { ok: true, detail: '测试推送已发出,请查看接收端是否收到' };
}
module.exports = { send, selfTest, validate, buildPayload, toMarkdown, FORMATS, normalizeFormat, signedUrl };
+235
View File
@@ -0,0 +1,235 @@
/**
* 内置「黄金品种」预设目录。
* 每个预设描述:名称、数据源及其参数、计价单位、价格小数位、建议刷新频率。
* 用户在网页里从目录挑一个品种,即可生成一条监控项。
*/
const PRESETS = [
// ---------- 上海黄金交易所(数据源:新浪财经行情接口) ----------
{
key: 'autd',
name: '黄金T+D(上金所)',
shortName: '黄金T+D',
category: '上金所',
source: 'sina',
sourceOptions: { code: 'SGE_AUTD' },
unit: '元/克',
digits: 2,
intervalSec: 30,
note: '上海黄金交易所延期交收合约 Au(T+D),最常用的国内金价参考。',
},
{
key: 'mautd',
name: 'mAu(T+D)(上金所)',
shortName: 'mAu(T+D)',
category: '上金所',
source: 'sina',
sourceOptions: { code: 'SGE_MAUTD' },
unit: '元/克',
digits: 2,
intervalSec: 30,
},
{
key: 'au9999',
name: '黄金9999(上金所)',
shortName: '黄金9999',
category: '上金所',
source: 'sina',
sourceOptions: { code: 'SGE_AU9999' },
unit: '元/克',
digits: 2,
intervalSec: 30,
},
{
key: 'au9995',
name: '黄金9995(上金所)',
shortName: '黄金9995',
category: '上金所',
source: 'sina',
sourceOptions: { code: 'SGE_AU9995' },
unit: '元/克',
digits: 2,
intervalSec: 30,
},
{
key: 'au100g',
name: '黄金100g(上金所)',
shortName: '黄金100g',
category: '上金所',
source: 'sina',
sourceOptions: { code: 'SGE_AU100G' },
unit: '元/克',
digits: 2,
intervalSec: 30,
},
// ---------- 国内期货 ----------
{
key: 'au0',
name: '沪金主连(期货)',
shortName: '沪金主连',
category: '期货',
source: 'sina',
sourceOptions: { code: 'nf_AU0' },
unit: '元/克',
digits: 2,
intervalSec: 30,
},
// ---------- 国际金价 ----------
{
key: 'xau',
name: '伦敦金(现货)',
shortName: '伦敦金',
category: '国际',
source: 'sina',
sourceOptions: { code: 'hf_XAU' },
unit: '美元/盎司',
digits: 2,
intervalSec: 30,
},
{
key: 'gc',
name: '纽约黄金(COMEX)',
shortName: '纽约黄金',
category: '国际',
source: 'sina',
sourceOptions: { code: 'hf_GC' },
unit: '美元/盎司',
digits: 2,
intervalSec: 30,
},
// ---------- 银行积存金(数据源:日金价公开行情页,含浙商银行) ----------
{
key: 'czb-jcj',
name: '浙商银行积存金',
shortName: '浙商黄金',
category: '银行积存金',
source: 'rijinjia',
sourceOptions: { key: 'czb-jcj' },
unit: '元/克',
digits: 2,
intervalSec: 60,
note: '浙商银行「财富金积存」报价,数据取自公开行情页(约每分钟更新)。',
},
{
key: 'icbc-jcj',
name: '工商银行积存金',
shortName: '工行积存金',
category: '银行积存金',
source: 'rijinjia',
sourceOptions: { key: 'icbc-jcj' },
unit: '元/克',
digits: 2,
intervalSec: 60,
},
{
key: 'cmbc-jcj',
name: '民生银行积存金',
shortName: '民生积存金',
category: '银行积存金',
source: 'rijinjia',
sourceOptions: { key: 'cmbc-jcj' },
unit: '元/克',
digits: 2,
intervalSec: 60,
},
{
key: 'cgb-jcj',
name: '广发银行积存金',
shortName: '广发积存金',
category: '银行积存金',
source: 'rijinjia',
sourceOptions: { key: 'cgb-jcj' },
unit: '元/克',
digits: 2,
intervalSec: 60,
},
{
key: 'cib-jcj',
name: '兴业银行积存金',
shortName: '兴业积存金',
category: '银行积存金',
source: 'rijinjia',
sourceOptions: { key: 'cib-jcj' },
unit: '元/克',
digits: 2,
intervalSec: 60,
},
{
key: 'cncb-jcj',
name: '中信银行积存金',
shortName: '中信积存金',
category: '银行积存金',
source: 'rijinjia',
sourceOptions: { key: 'cncb-jcj' },
unit: '元/克',
digits: 2,
intervalSec: 60,
},
// ---------- 自定义数据源 ----------
{
key: 'custom-http',
name: '自定义 HTTP 接口',
shortName: '自定义接口',
category: '自定义',
source: 'http-json',
sourceOptions: { url: '', pricePath: 'data.price', prevClosePath: '', headers: {} },
unit: '元/克',
digits: 2,
intervalSec: 60,
note: '填写任意返回 JSON 的行情接口,用 pricePath 指定价格字段路径,例如 data.price。',
},
{
key: 'custom-sina',
name: '自定义新浪代码',
shortName: '新浪代码',
category: '自定义',
source: 'sina',
sourceOptions: { code: '' },
unit: '元/克',
digits: 2,
intervalSec: 30,
note: '填写新浪行情代码,如 SGE_AUTD、hf_XAU、nf_AU0 等。',
},
{
key: 'manual',
name: '手动录入价格',
shortName: '手动价格',
category: '自定义',
source: 'manual',
sourceOptions: {},
unit: '元/克',
digits: 2,
intervalSec: 0,
note: '没有公开接口时可用:在网页或 HTTP 接口里手动更新价格,同样能触发阈值/价差提醒。',
},
];
/** 以 key 建索引,便于查找 */
const PRESET_MAP = new Map(PRESETS.map((item) => [item.key, item]));
/** 按 key 取预设 */
function getPreset(key) {
return PRESET_MAP.get(key) || null;
}
/** 取出预设里的数据源相关字段,组装成一条监控项(不含 id/enabled) */
function buildInstrument(presetKey, overrides = {}) {
const preset = getPreset(presetKey);
if (!preset) return null;
return {
name: overrides.name || preset.name,
source: preset.source,
sourceOptions: { ...preset.sourceOptions, ...(overrides.sourceOptions || {}) },
unit: overrides.unit || preset.unit,
digits: overrides.digits ?? preset.digits,
intervalSec: overrides.intervalSec ?? preset.intervalSec,
presetKey: preset.key,
note: preset.note || '',
};
}
module.exports = { PRESETS, getPreset, buildInstrument };
+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 };
+76
View File
@@ -0,0 +1,76 @@
/**
* 自定义 HTTP JSON 数据源。
* 适合对接任何自有/第三方行情接口:只要返回 JSON,并用点号路径指出价格字段即可。
* 例:url = https://api.example.com/gold ,pricePath = data.price ,prevClosePath = data.prevClose
*/
const { toNum, round } = require('../util');
/**
* 按点号路径取嵌套字段,支持数组下标(如 data.list.0.price)
* @param {any} obj 目标对象
* @param {string} path 路径
* @returns {any}
*/
function getByPath(obj, path) {
if (!path) return undefined;
return String(path)
.split('.')
.filter((seg) => seg !== '')
.reduce((acc, seg) => (acc === null || acc === undefined ? undefined : acc[seg]), obj);
}
/**
* 数据源统一入口
* @param {object} instrument 监控项
* @returns {Promise<object>}
*/
async function fetchQuote(instrument) {
const opts = instrument?.sourceOptions || {};
const url = String(opts.url || '').trim();
if (!url) throw new Error('未配置接口地址');
if (!/^https?:\/\//i.test(url)) throw new Error('接口地址必须以 http:// 或 https:// 开头');
const res = await fetch(url, {
headers: {
'User-Agent': 'gold-price-watcher/1.0',
Accept: 'application/json',
...(opts.headers || {}),
},
signal: AbortSignal.timeout(12000),
});
if (!res.ok) throw new Error(`接口返回 HTTP ${res.status}`);
let data;
const text = await res.text();
try {
data = JSON.parse(text);
} catch {
throw new Error('接口返回的不是合法 JSON');
}
const price = toNum(getByPath(data, opts.pricePath || 'price'));
if (!price || price <= 0) throw new Error(`按路径 ${opts.pricePath || 'price'} 取不到有效价格`);
const prevCloseRaw = getByPath(data, opts.prevClosePath || '');
const prevClose = toNum(prevCloseRaw);
const pctRaw = toNum(getByPath(data, opts.percentPath || ''));
const changePercent = pctRaw !== null
? pctRaw
: (prevClose && prevClose > 0 ? ((price - prevClose) / prevClose) * 100 : null);
return {
price: round(price, 4),
prevClose: prevClose && prevClose > 0 ? round(prevClose, 4) : null,
change: prevClose && prevClose > 0 ? round(price - prevClose, 4) : null,
changePercent: changePercent === null ? null : round(changePercent, 3),
high: null,
low: null,
open: null,
volume: null,
sourceTime: '自定义接口',
extra: { url },
};
}
module.exports = { fetchQuote, getByPath };
+70
View File
@@ -0,0 +1,70 @@
/**
* 数据源注册表:把「监控项」路由到具体的抓取实现,
* 并在上层统一做超时、数值校验与错误包装。
*/
const sina = require('./sina');
const rijinjia = require('./rijinjia');
const httpJson = require('./http-json');
const manual = require('./manual');
/** 数据源实现与展示信息 */
const SOURCES = {
sina: {
label: '新浪财经行情',
impl: sina,
hint: '支持 SGE_AUTD / SGE_AU9999 / hf_XAU / nf_AU0 等代码',
},
rijinjia: {
label: '银行积存金行情页',
impl: rijinjia,
hint: '一次抓取全部银行积存金报价,约每分钟更新',
},
'http-json': {
label: '自定义 HTTP 接口',
impl: httpJson,
hint: '返回 JSON,用 pricePath 指定字段路径',
},
manual: {
label: '手动录入',
impl: manual,
hint: '在网页或接口里手动更新价格',
},
};
/** 给前端用的数据源清单 */
function listSources() {
return Object.entries(SOURCES).map(([key, item]) => ({ key, label: item.label, hint: item.hint }));
}
/**
* 抓取一条监控项的行情
* @param {object} instrument 监控项
* @param {object} ctx 运行时上下文(手动价格等)
* @returns {Promise<object>} 标准化行情
*/
async function fetchQuote(instrument, ctx) {
const source = SOURCES[instrument?.source];
if (!source) throw new Error(`未知数据源:${instrument?.source}`);
const quote = await source.impl.fetchQuote(instrument, ctx);
if (!quote || typeof quote.price !== 'number' || !Number.isFinite(quote.price) || quote.price <= 0) {
throw new Error('行情数据无效(价格为空或非数字)');
}
return quote;
}
/**
* 数据源自检
* @param {string} sourceKey
* @returns {Promise<{ok: boolean, detail: string}>}
*/
async function selfTest(sourceKey) {
const source = SOURCES[sourceKey];
if (!source) return { ok: false, detail: `未知数据源:${sourceKey}` };
if (typeof source.impl.selfTest !== 'function') {
return { ok: false, detail: '该数据源不支持自检' };
}
return source.impl.selfTest();
}
module.exports = { fetchQuote, selfTest, listSources, SOURCES };
+38
View File
@@ -0,0 +1,38 @@
/**
* 手动价格数据源。
* 适用场景:某个品种(例如某些银行积存金、线下金店报价)没有公开接口,
* 由用户自己在网页里录入价格,或让别的脚本调用 POST /api/instruments/:id/manual 推送。
*/
const { toNum, round } = require('../util');
/**
* 数据源统一入口
* @param {object} instrument 监控项
* @param {{getManualPrice: Function}} ctx 运行时上下文
* @returns {Promise<object>}
*/
async function fetchQuote(instrument, ctx) {
const record = ctx?.getManualPrice ? ctx.getManualPrice(instrument.id) : null;
if (!record) throw new Error('尚未录入手动价格,请在网页里填写或调用手动更新接口');
const price = toNum(record.price);
if (!price || price <= 0) throw new Error('手动价格无效');
const prevClose = toNum(record.prevClose);
return {
price: round(price, 4),
prevClose: prevClose && prevClose > 0 ? round(prevClose, 4) : null,
change: prevClose && prevClose > 0 ? round(price - prevClose, 4) : null,
changePercent: prevClose && prevClose > 0 ? round(((price - prevClose) / prevClose) * 100, 3) : null,
high: null,
low: null,
open: null,
volume: null,
sourceTime: record.at || '手动录入',
extra: { manual: true },
};
}
module.exports = { fetchQuote };
+133
View File
@@ -0,0 +1,133 @@
/**
* 银行积存金数据源(rijiinjia 公开行情页)。
*
* 银行积存金(含浙商银行「财富金积存」)没有公开的官方行情接口,
* 这里抓取公开行情页上已经渲染好的价格单元格,例如:
* <td data-pa="czb-jcj" ...>781.70 <span>元/克</span></td>
* <td data-pa-cv="czb-jcj" ...>-7.03</td>
* <td data-pa-cp="czb-jcj" ...>-0.89%</td>
*
* 特点:一次请求即可拿到所有银行的报价,因此做 10 秒级缓存 + in-flight 去重。
*/
const { toNum, round, log } = require('../util');
const PAGE_URL = 'https://www.rijinjia.com/jicunjin';
const HEADERS = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36',
Referer: 'https://www.rijinjia.com/',
'Accept-Language': 'zh-CN,zh;q=0.9',
};
const CACHE_TTL_MS = 10000;
/** 页面级缓存 */
let cache = { at: 0, map: null };
/** 正在进行中的抓取(避免并发重复请求) */
let inflight = null;
/**
* 抓取并解析整页的所有积存金报价
* @returns {Promise<Map<string, object>>} key -> 报价
*/
async function loadAll() {
const now = Date.now();
if (cache.map && now - cache.at < CACHE_TTL_MS) return cache.map;
if (inflight) return inflight;
inflight = (async () => {
const res = await fetch(PAGE_URL, { headers: HEADERS, signal: AbortSignal.timeout(15000) });
if (!res.ok) throw new Error(`积存金行情页返回 HTTP ${res.status}`);
const html = await res.text();
const map = new Map();
// 价格为页面里 data-pa="key" 后的第一个数字
const priceRe = /data-pa="([a-z0-9-]+)"[^>]*>\s*([\d.]+)/g;
let m;
while ((m = priceRe.exec(html)) !== null) {
const key = m[1];
const price = toNum(m[2]);
if (!price || price <= 0) continue;
map.set(key, { price: round(price, 3) });
}
if (map.size === 0) throw new Error('未解析到任何积存金价格,行情页结构可能已变化');
// 涨跌额
const cvRe = /data-pa-cv="([a-z0-9-]+)"[^>]*>\s*([-+]?[\d.]+)/g;
while ((m = cvRe.exec(html)) !== null) {
const item = map.get(m[1]);
if (item) item.change = toNum(m[2]);
}
// 涨跌幅(截断窗口内匹配百分号)
const cpRe = /data-pa-cp="([a-z0-9-]+)"[\s\S]{0,220}?([-+]?[\d.]+)\s*%/g;
while ((m = cpRe.exec(html)) !== null) {
const item = map.get(m[1]);
if (item) item.changePercent = toNum(m[2]);
}
cache = { at: Date.now(), map };
return map;
})()
.catch((err) => {
// 失败时保留旧缓存,避免整页抖动导致所有品种一起报错
if (cache.map) {
log.warn('积存金行情抓取失败,沿用上一次数据:', err.message);
return cache.map;
}
throw err;
})
.finally(() => {
inflight = null;
});
return inflight;
}
/**
* 数据源统一入口
* @param {object} instrument 监控项
* @returns {Promise<object>}
*/
async function fetchQuote(instrument) {
const key = instrument?.sourceOptions?.key;
if (!key) throw new Error('未配置积存金品种 key');
const map = await loadAll();
const item = map.get(key);
if (!item) throw new Error(`行情页里找不到品种 ${key},可能已下线`);
const prevClose = item.change !== null && item.change !== undefined
? item.price - item.change
: (item.changePercent ? item.price / (1 + item.changePercent / 100) : null);
return {
price: round(item.price, 4),
prevClose: prevClose ? round(prevClose, 4) : null,
change: item.change !== null && item.change !== undefined ? round(item.change, 4) : (prevClose ? round(item.price - prevClose, 4) : null),
changePercent: item.changePercent !== null && item.changePercent !== undefined
? round(item.changePercent, 3)
: (prevClose && prevClose > 0 ? round(((item.price - prevClose) / prevClose) * 100, 3) : null),
high: null,
low: null,
open: null,
volume: null,
sourceTime: '公开行情页',
extra: { key },
};
}
/**
* 连通性检查
* @returns {Promise<{ok: boolean, detail: string}>}
*/
async function selfTest() {
try {
const map = await loadAll();
const item = map.get('czb-jcj');
if (!item) return { ok: false, detail: '行情页可用,但未找到浙商银行积存金' };
return { ok: true, detail: `积存金行情页可用,浙商银行积存金 ${item.price} 元/克` };
} catch (err) {
return { ok: false, detail: `积存金行情页不可用:${err.message}` };
}
}
module.exports = { fetchQuote, selfTest, loadAll };
+239
View File
@@ -0,0 +1,239 @@
/**
* 新浪财经行情源(hq.sinajs.cn)。
* 支持三类代码前缀:
* - SGE_* 上海黄金交易所现货/延期(字段最全,带涨跌幅)
* - gds_* 上金所旧格式(保留兼容)
* - hf_* 国际现货/期货(伦敦金、纽约金)
* - nf_* 国内期货(沪金主连等)
*
* 说明:该接口需要带 Referer,返回内容是 GBK 编码的 JS 变量。
*/
const { toNum, round } = require('../util');
const ENDPOINT = 'https://hq.sinajs.cn/list=';
const HEADERS = {
Referer: 'https://finance.sina.com.cn',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36',
};
// ---- 批量聚合:同一个事件循环内多个品种的请求合并成一次 HTTP 调用 ----
/** @type {Map<string, {resolve: Function, reject: Function}[]>} */
const pendingCodes = new Map();
let flushTimer = null;
let flushing = false;
/**
* 请求单个代码的行情(内部会被自动合并成批量请求)
* @param {string} code 新浪行情代码,如 SGE_AUTD
* @returns {Promise<object>} 标准化行情对象
*/
function requestQuote(code) {
const normalized = String(code || '').trim();
if (!normalized) return Promise.reject(new Error('新浪代码为空'));
return new Promise((resolve, reject) => {
const waiting = pendingCodes.get(normalized) || [];
waiting.push({ resolve, reject });
pendingCodes.set(normalized, waiting);
if (flushTimer) return;
flushTimer = setTimeout(() => {
flushTimer = null;
flush().catch(() => {});
}, 30);
});
}
/** 立即把队列里的代码合并成一次请求 */
async function flush() {
if (flushing || pendingCodes.size === 0) return;
flushing = true;
const codes = [...pendingCodes.keys()];
const waiters = new Map(pendingCodes);
pendingCodes.clear();
try {
const text = await fetchRaw(codes);
const parsed = parseSinaText(text);
for (const code of codes) {
const group = waiters.get(code) || [];
const quote = parsed.get(code);
for (const w of group) {
if (quote) w.resolve(quote);
else w.reject(new Error(`新浪未返回 ${code} 的行情(代码可能不存在或长期停牌)`));
}
}
} catch (err) {
for (const group of waiters.values()) {
for (const w of group) w.reject(err);
}
} finally {
flushing = false;
// 修剪期间若又来了新请求,继续下一轮
if (pendingCodes.size > 0 && !flushTimer) {
flushTimer = setTimeout(() => {
flushTimer = null;
flush().catch(() => {});
}, 30);
}
}
}
/**
* 发起 HTTP 请求并解码(GBK -> UTF-8)
* @param {string[]} codes
* @returns {Promise<string>}
*/
async function fetchRaw(codes) {
const url = `${ENDPOINT}${codes.join(',')}`;
const res = await fetch(url, {
headers: HEADERS,
signal: AbortSignal.timeout(10000),
});
if (!res.ok) throw new Error(`新浪行情接口返回 HTTP ${res.status}`);
const buffer = Buffer.from(await res.arrayBuffer());
try {
return new TextDecoder('gbk').decode(buffer);
} catch {
// 个别 Node 构建不支持 GBK 时退化为 UTF-8(价格字段是 ASCII,不影响解析)
return buffer.toString('utf8');
}
}
/**
* 把新浪返回的整段文本解析成 Map<code, quote>
* @param {string} text
* @returns {Map<string, object>}
*/
function parseSinaText(text) {
const result = new Map();
const re = /var\s+hq_str_([A-Za-z0-9_]+)\s*=\s*"([^"]*)";?/g;
let m;
while ((m = re.exec(text)) !== null) {
const code = m[1];
const raw = m[2];
if (!raw) continue; // 空串表示无数据
try {
const quote = parseQuote(code, raw);
if (quote) result.set(code, quote);
} catch (err) {
// 单条解析失败不影响其它代码
result.set(code, { error: err.message });
}
}
// 过滤掉解析失败的条目
for (const [code, quote] of result) {
if (quote && quote.error) result.delete(code);
}
return result;
}
/**
* 解析单条行情字符串
* @param {string} code 代码
* @param {string} raw 引号内的内容
* @returns {object}
*/
function parseQuote(code, raw) {
const f = raw.split(',');
const num = (i) => toNum(f[i]);
let price = null;
let prevClose = null;
let changePercent = null;
let high = null;
let low = null;
let open = null;
let volume = null;
let sourceTime = '';
if (code.startsWith('SGE_')) {
// 字段:0 代码 1 名称 2 品种 3 最新价 ... 7 最高 8 最低 ... 14 成交量 16 时间 17 涨跌幅%
price = num(3);
high = num(7);
low = num(8);
volume = num(14);
sourceTime = (f[16] || '').trim();
const pct = toNum(String(f[17] || '').replace('%', ''));
if (pct !== null) changePercent = pct;
} else if (code.startsWith('gds_')) {
// 字段:0 最新 2 买价 3 卖价 4 最高 5 最低 6 时间 7 昨收 8 开盘 9 成交量
price = num(0);
high = num(4);
low = num(5);
prevClose = num(7);
open = num(8);
volume = num(9);
sourceTime = (f[6] || '').trim();
} else if (code.startsWith('hf_')) {
// 字段:0 最新 2 买 3 卖 4 最高 5 最低 6 时间 7 昨收 8 开盘
price = num(0);
high = num(4);
low = num(5);
prevClose = num(7);
open = num(8);
sourceTime = (f[6] || '').trim();
} else if (code.startsWith('nf_')) {
// 字段:0 名称 1 时间 2 开盘 3 最高 4 最低 6 买 7 卖 8 最新 10 昨结算 14 成交量
price = num(8);
open = num(2);
high = num(3);
low = num(4);
prevClose = num(10);
volume = num(14);
sourceTime = (f[1] || '').trim();
} else {
throw new Error(`不支持的代码前缀:${code}`);
}
if (!price || price <= 0) throw new Error('最新价为 0,可能是非交易时段或代码无效');
if (price > 1000000) throw new Error('价格异常,疑似代码错误');
// 涨跌幅:优先用接口自带,其次用昨收推算
if (changePercent === null && prevClose && prevClose > 0) {
changePercent = ((price - prevClose) / prevClose) * 100;
}
// 用涨跌幅反推昨收,保证两者一致
if ((!prevClose || prevClose <= 0) && changePercent !== null) {
prevClose = price / (1 + changePercent / 100);
}
return {
price: round(price, 4),
prevClose: prevClose ? round(prevClose, 4) : null,
change: prevClose ? round(price - prevClose, 4) : null,
changePercent: changePercent === null ? null : round(changePercent, 3),
high: high ? round(high, 4) : null,
low: low ? round(low, 4) : null,
open: open ? round(open, 4) : null,
volume,
sourceTime,
extra: { code },
};
}
/**
* 数据源统一入口
* @param {object} instrument 监控项
* @returns {Promise<object>}
*/
async function fetchQuote(instrument) {
const code = instrument?.sourceOptions?.code;
if (!code) throw new Error('未配置新浪行情代码');
const quote = await requestQuote(code);
return quote;
}
/**
* 连通性检查:拉一条固定的行情看是否可用
* @returns {Promise<{ok: boolean, detail: string}>}
*/
async function selfTest() {
try {
const quote = await requestQuote('SGE_AUTD');
return { ok: true, detail: `新浪行情可用,黄金T+D 最新价 ${quote.price}` };
} catch (err) {
return { ok: false, detail: `新浪行情不可用:${err.message}` };
}
}
module.exports = { fetchQuote, selfTest, parseQuote, requestQuote };
+161
View File
@@ -0,0 +1,161 @@
/**
* 通用小工具集合:对象合并、数值格式化、JSON 读写、日志等。
* 全部为纯函数或轻量副作用,便于被其它模块复用。
*/
const fs = require('node:fs');
const path = require('node:path');
const crypto = require('node:crypto');
/** 判断是否为「普通对象」(非数组、非 null) */
function isPlainObject(value) {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
/**
* 深合并:以 base 为底,把 patch 覆盖上去。
* 数组与标量直接替换(不递归),对象递归合并。
* @template T
* @param {T} base 基础对象
* @param {any} patch 待覆盖的内容
* @returns {T} 合并后的新对象
*/
function deepMerge(base, patch) {
if (!isPlainObject(patch)) return patch === undefined ? base : patch;
const out = isPlainObject(base) ? { ...base } : {};
for (const [key, value] of Object.entries(patch)) {
if (value === undefined) continue;
if (isPlainObject(value) && isPlainObject(out[key])) {
out[key] = deepMerge(out[key], value);
} else if (Array.isArray(value)) {
out[key] = value.slice();
} else {
out[key] = value;
}
}
return out;
}
/** 生成短随机 id,用于品种、规则等 */
function uid(prefix = 'id') {
return `${prefix}_${crypto.randomBytes(4).toString('hex')}`;
}
/** 安全转数字,非法则返回 null */
function toNum(value) {
if (value === null || value === undefined || value === '') return null;
const n = Number(value);
return Number.isFinite(n) ? n : null;
}
/** 按精度四舍五入(默认 2 位) */
function round(value, digits = 2) {
const n = toNum(value);
if (n === null) return null;
const factor = 10 ** digits;
return Math.round(n * factor) / factor;
}
/** 价格展示:保留 digits 位小数 */
function fmtPrice(value, digits = 2) {
const n = toNum(value);
if (n === null) return '--';
return n.toFixed(digits);
}
/** 涨跌幅展示:带正负号 */
function fmtPercent(value, digits = 2) {
const n = toNum(value);
if (n === null) return '--';
const sign = n > 0 ? '+' : '';
return `${sign}${n.toFixed(digits)}%`;
}
/** 当前时间 ISO 字符串(本地时区可读形式) */
function nowText(date = new Date()) {
const pad = (v) => String(v).padStart(2, '0');
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} `
+ `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
}
/** 简单 sleep */
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/** 保证目录存在 */
function ensureDir(dir) {
fs.mkdirSync(dir, { recursive: true });
}
/** 读取 JSON 文件,失败返回 fallback */
function readJson(file, fallback = null) {
try {
return JSON.parse(fs.readFileSync(file, 'utf8'));
} catch {
return fallback;
}
}
/** 原子写入 JSON(先写临时文件再重命名,避免半截文件) */
function writeJson(file, data) {
ensureDir(path.dirname(file));
const tmp = `${file}.tmp`;
fs.writeFileSync(tmp, JSON.stringify(data, null, 2), 'utf8');
fs.renameSync(tmp, file);
}
/** 追加一行 JSON(用于提醒日志) */
function appendJsonLine(file, data) {
ensureDir(path.dirname(file));
fs.appendFileSync(file, `${JSON.stringify(data)}\n`, 'utf8');
}
/** 带时间戳的控制台日志 */
const log = {
info: (...args) => console.log(`[${nowText()}]`, ...args),
warn: (...args) => console.warn(`[${nowText()}] ⚠`, ...args),
error: (...args) => console.error(`[${nowText()}] ✖`, ...args),
};
/** 把密码等敏感字段打码,避免直接回传给前端 */
function maskSecret(value) {
if (!value) return '';
const s = String(value);
if (s.length <= 4) return '****';
return `${s.slice(0, 2)}${'*'.repeat(Math.min(8, s.length - 4))}${s.slice(-2)}`;
}
/** 判断当前时间是否落在 "HH:mm-HH:mm" 区间(支持跨天,如 23:00-07:00) */
function inTimeRange(range, date = new Date()) {
if (!range || typeof range !== 'string' || !range.includes('-')) return false;
const [start, end] = range.split('-').map((s) => s.trim());
const toMin = (text) => {
const m = /^(\d{1,2}):(\d{2})$/.exec(text || '');
return m ? Number(m[1]) * 60 + Number(m[2]) : null;
};
const s = toMin(start);
const e = toMin(end);
if (s === null || e === null) return false;
const cur = date.getHours() * 60 + date.getMinutes();
return s <= e ? cur >= s && cur <= e : cur >= s || cur <= e;
}
module.exports = {
isPlainObject,
deepMerge,
uid,
toNum,
round,
fmtPrice,
fmtPercent,
nowText,
sleep,
ensureDir,
readJson,
writeJson,
appendJsonLine,
log,
maskSecret,
inTimeRange,
};
+19
View File
@@ -0,0 +1,19 @@
@echo off
chcp 65001 >nul
cd /d "%~dp0"
title 金价提醒
if not exist node_modules (
echo 首次运行,正在安装依赖...
call npm install --no-audit --no-fund
if errorlevel 1 (
echo 依赖安装失败,请检查网络后重试。
pause
exit /b 1
)
)
node src\index.js
echo.
echo 程序已退出。
pause
+5
View File
@@ -0,0 +1,5 @@
' 静默启动(不显示命令行窗口),适合配合开机自启使用
Set fso = CreateObject("Scripting.FileSystemObject")
Set shell = CreateObject("WScript.Shell")
shell.CurrentDirectory = fso.GetParentFolderName(WScript.ScriptFullName)
shell.Run "node src\index.js", 0, False