From 9a23cd1d32db875e64f05117b0e13871ef46129d Mon Sep 17 00:00:00 2001 From: ouyangzixuan Date: Tue, 24 Nov 2026 16:37:13 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=88=9D=E5=A7=8B=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 277 ++++++++ package-lock.json | 853 +++++++++++++++++++++++ package.json | 18 + public/app.js | 1426 ++++++++++++++++++++++++++++++++++++++ public/index.html | 377 ++++++++++ public/styles.css | 528 ++++++++++++++ src/config-store.js | 402 +++++++++++ src/index.js | 77 ++ src/monitor.js | 881 +++++++++++++++++++++++ src/notify/desktop.js | 129 ++++ src/notify/email.js | 145 ++++ src/notify/index.js | 86 +++ src/notify/webhook.js | 234 +++++++ src/presets.js | 235 +++++++ src/server.js | 318 +++++++++ src/sources/http-json.js | 76 ++ src/sources/index.js | 70 ++ src/sources/manual.js | 38 + src/sources/rijinjia.js | 133 ++++ src/sources/sina.js | 239 +++++++ src/util.js | 161 +++++ 启动.bat | 19 + 静默启动.vbs | 5 + 23 files changed, 6727 insertions(+) create mode 100644 README.md create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 public/app.js create mode 100644 public/index.html create mode 100644 public/styles.css create mode 100644 src/config-store.js create mode 100644 src/index.js create mode 100644 src/monitor.js create mode 100644 src/notify/desktop.js create mode 100644 src/notify/email.js create mode 100644 src/notify/index.js create mode 100644 src/notify/webhook.js create mode 100644 src/presets.js create mode 100644 src/server.js create mode 100644 src/sources/http-json.js create mode 100644 src/sources/index.js create mode 100644 src/sources/manual.js create mode 100644 src/sources/rijinjia.js create mode 100644 src/sources/sina.js create mode 100644 src/util.js create mode 100644 启动.bat create mode 100644 静默启动.vbs diff --git a/README.md b/README.md new file mode 100644 index 0000000..3e5ecff --- /dev/null +++ b/README.md @@ -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 +``` + +启动后会自动打开浏览器;如果没打开,手动访问 。 + +其它入口: + +- `启动.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) +``` + +> 数据源均为公开非官方接口,可能因对方改版或限流失效;本项目仅本地自用,不构成投资建议。 diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..78425c4 --- /dev/null +++ b/package-lock.json @@ -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" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..bfcd52a --- /dev/null +++ b/package.json @@ -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" + } +} diff --git a/public/app.js b/public/app.js new file mode 100644 index 0000000..8d62837 --- /dev/null +++ b/public/app.js @@ -0,0 +1,1426 @@ +/** + * 前端交互脚本(无框架、无构建步骤)。 + * 负责:轮询 /api/state、渲染行情/规则/记录、打开弹窗、保存配置、渠道自检。 + */ + +/** 前端全局状态 */ +const ui = { + /** @type {object|null} 最近一次 /api/state 返回 */ + data: null, + /** 当前标签页 */ + tab: 'market', + /** 上次查看提醒记录的时间,用于未读角标 */ + seenAtMs: Date.now(), + /** 是否已有未读提醒 */ + unread: 0, + /** 编辑中的品种 id(null 表示新增) */ + editingInstrumentId: null, + /** 编辑中的规则 id(null 表示新增) */ + editingRuleId: null, + /** 行情卡片的 DOM 引用缓存:id -> {root, refs...} */ + cards: new Map(), + /** 上一次渲染时的品种签名,签名变化才重建卡片 */ + marketSignature: '', + /** 轮询定时器 */ + timer: null, +}; + +const TOKEN_KEY = 'goldWatcherToken'; + +/* ================================================================== + * 基础工具 + * ================================================================== */ + +/** 读写访问令牌 */ +function getToken() { + return localStorage.getItem(TOKEN_KEY) || ''; +} + +/** 数字格式化 */ +function fmt(value, digits = 2) { + if (value === null || value === undefined || Number.isNaN(Number(value))) return '--'; + return Number(value).toFixed(digits); +} + +/** 百分比格式化,带正负号 */ +function fmtPct(value) { + if (value === null || value === undefined || Number.isNaN(Number(value))) return '--'; + const n = Number(value); + return `${n > 0 ? '+' : ''}${n.toFixed(2)}%`; +} + +/** HTML 转义 */ +function esc(text) { + return String(text === null || text === undefined ? '' : text) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + +/** 涨跌方向 class */ +function trendClass(value) { + if (value === null || value === undefined) return 'flat'; + if (Number(value) > 0) return 'up'; + if (Number(value) < 0) return 'down'; + return 'flat'; +} + +/** + * 统一的后端请求封装(自动带令牌、统一错误处理) + * @param {string} path 接口路径 + * @param {{method?: string, body?: any}} options 请求选项 + * @returns {Promise} + */ +async function api(path, options = {}) { + const method = options.method || 'GET'; + const headers = { 'Content-Type': 'application/json' }; + const token = getToken(); + if (token) headers['x-token'] = token; + + const res = await fetch(path, { + method, + headers, + body: options.body === undefined ? undefined : JSON.stringify(options.body), + }); + + if (res.status === 401) { + const input = window.prompt('该页面配置了访问令牌,请输入(会记住在本机):'); + if (input) { + localStorage.setItem(TOKEN_KEY, input.trim()); + return api(path, options); + } + throw new Error('未授权访问'); + } + + let payload = null; + try { + payload = await res.json(); + } catch { + throw new Error(`接口返回异常(HTTP ${res.status})`); + } + // 失败时优先用后端给的 error,其次 detail(渠道自检接口只有 detail),最后才退化成 HTTP 状态 + if (!res.ok || payload.ok === false) { + throw new Error(payload.error || payload.detail || `请求失败(HTTP ${res.status})`); + } + return payload; +} + +/** 右下角轻提示 */ +function toast(message, type = '') { + const wrap = document.getElementById('toastWrap'); + const el = document.createElement('div'); + el.className = `toast ${type}`; + el.textContent = message; + wrap.appendChild(el); + setTimeout(() => { + el.style.opacity = '0'; + el.style.transition = 'opacity .2s'; + setTimeout(() => el.remove(), 250); + }, 2600); +} + +/** 设置测试结果文案 */ +function setResult(id, text, ok) { + const el = document.getElementById(id); + if (!el) return; + el.textContent = text || ''; + el.className = `test-result ${ok === true ? 'ok' : ok === false ? 'err' : ''}`; +} + +/* ================================================================== + * 渲染:顶栏 / 行情 / 规则 / 记录 + * ================================================================== */ + +/** 渲染顶栏状态 */ +function renderHeader() { + const data = ui.data; + if (!data) return; + const pill = document.getElementById('runPill'); + const text = document.getElementById('runText'); + const running = !!data.running; + pill.className = `pill ${running ? 'running' : 'paused'}`; + text.textContent = running ? '监控运行中' : '已暂停'; + document.getElementById('btnToggleRun').textContent = running ? '暂停监控' : '开始监控'; + document.getElementById('serverTime').textContent = data.serverTime || ''; + document.getElementById('quietPill').hidden = !data.quietActive; + + // 未读提醒角标 + const badge = document.getElementById('alertBadge'); + if (ui.unread > 0 && ui.tab !== 'alerts') { + badge.hidden = false; + badge.textContent = ui.unread > 99 ? '99+' : String(ui.unread); + } else { + badge.hidden = true; + } +} + +/** 数据源展示名 */ +function sourceLabel(sourceKey) { + const sources = ui.data?.config?.meta?.dataSources || []; + return (sources.find((s) => s.key === sourceKey) || {}).label || sourceKey; +} + +/** 生成迷你走势 SVG */ +function sparkline(history, digits) { + if (!Array.isArray(history) || history.length < 2) { + return ''; + } + const points = history.map((p) => Number(p.p)).filter((n) => Number.isFinite(n)); + if (points.length < 2) return ''; + const min = Math.min(...points); + const max = Math.max(...points); + const span = max - min || 1; + const stepX = 300 / (points.length - 1); + const coords = points.map((p, i) => { + const y = 30 - ((p - min) / span) * 26; + return `${(i * stepX).toFixed(1)},${y.toFixed(1)}`; + }).join(' '); + const rising = points[points.length - 1] >= points[0]; + const color = rising ? 'var(--up)' : 'var(--down)'; + return ` + + `; +} + +/** 构建一张行情卡片 */ +function buildCard(inst) { + const root = document.createElement('div'); + root.className = 'card'; + root.dataset.id = inst.id; + root.innerHTML = ` +
+
+

+ +
+ +
+
+ -- + +
+
+ -- + +
+
+
+ + + +
+
+
+
+ +
+ + +
+
+ `; + + const refs = { + root, + name: root.querySelector('.js-name'), + source: root.querySelector('.js-source'), + toggle: root.querySelector('.js-toggle'), + price: root.querySelector('.js-price'), + unit: root.querySelector('.js-unit'), + change: root.querySelector('.js-change'), + range: root.querySelector('.js-range'), + spark: root.querySelector('.js-spark'), + status: root.querySelector('.js-status'), + statusText: root.querySelector('.js-status-text'), + updated: root.querySelector('.js-updated'), + interval: root.querySelector('.js-interval'), + error: root.querySelector('.js-error'), + manual: root.querySelector('.js-manual'), + manualHint: root.querySelector('.js-manual-hint'), + }; + + // 事件绑定 + refs.toggle.addEventListener('change', async () => { + try { + const res = await api(`/api/instruments/${inst.id}`, { method: 'PUT', body: { enabled: refs.toggle.checked } }); + applyState(res, true); + toast(refs.toggle.checked ? '已启用' : '已停用', 'ok'); + } catch (err) { + toast(err.message, 'err'); + refs.toggle.checked = !refs.toggle.checked; + } + }); + + root.querySelector('.js-edit').addEventListener('click', () => openInstrumentModal(inst.id)); + + root.querySelector('.js-del').addEventListener('click', async () => { + if (!window.confirm(`确定删除「${inst.name}」?相关规则也会一起删除。`)) return; + try { + const res = await api(`/api/instruments/${inst.id}`, { method: 'DELETE' }); + applyState(res, true); + toast('已删除', 'ok'); + } catch (err) { + toast(err.message, 'err'); + } + }); + + ui.cards.set(inst.id, refs); + return { root, refs }; +} + +/** 更新卡片内容(不重建 DOM) */ +function updateCard(refs, inst) { + const digits = inst.digits ?? 2; + refs.root.classList.toggle('disabled', !inst.enabled); + refs.name.textContent = inst.name; + refs.source.textContent = sourceLabel(inst.source); + refs.toggle.checked = !!inst.enabled; + refs.unit.textContent = inst.unit || ''; + + const hasPrice = inst.price !== null && inst.price !== undefined; + refs.price.textContent = hasPrice ? fmt(inst.price, digits) : '--'; + refs.price.classList.toggle('stale', !hasPrice); + + const dir = trendClass(inst.changePercent); + refs.change.className = `change js-change ${dir}`; + refs.change.textContent = hasPrice + ? `${fmtPct(inst.changePercent)}${inst.change !== null && inst.change !== undefined ? ` ${inst.change > 0 ? '+' : ''}${fmt(inst.change, digits)}` : ''}` + : ''; + refs.range.textContent = hasPrice && inst.high && inst.low + ? `高 ${fmt(inst.high, digits)} / 低 ${fmt(inst.low, digits)}` + : ''; + + refs.spark.innerHTML = sparkline(inst.history, digits); + + const statusMap = { + ok: '正常', error: '抓取失败', pending: '等待首次数据', manual: '手动价格', disabled: '已停用', + }; + refs.status.className = `status js-status ${inst.status}`; + refs.statusText.textContent = statusMap[inst.status] || inst.status; + refs.updated.textContent = inst.updatedAt ? `更新 ${inst.updatedAt}` : ''; + refs.interval.textContent = inst.intervalSec > 0 ? `每 ${inst.intervalSec} 秒` : '不自动刷新'; + + if (inst.error) { + refs.error.innerHTML = `
${esc(inst.error)}
`; + } else { + refs.error.innerHTML = ''; + } + + // 手动录价:manual 数据源常驻输入框;其它品种只在出错时给一个快捷补价入口 + const needManual = inst.source === 'manual' || inst.status === 'error'; + if (needManual) { + if (!refs.manual.querySelector('input')) { + refs.manual.innerHTML = ` +
+ + +
`; + const input = refs.manual.querySelector('input'); + const btn = refs.manual.querySelector('button'); + const submit = async () => { + const value = Number(input.value); + if (!value || value <= 0) { + toast('请输入有效价格', 'err'); + return; + } + btn.disabled = true; + try { + const res = await api(`/api/instruments/${inst.id}/manual`, { method: 'POST', body: { price: value } }); + applyState(res, true); + toast('已更新价格并重新评估规则', 'ok'); + } catch (err) { + toast(err.message, 'err'); + } finally { + btn.disabled = false; + } + }; + btn.addEventListener('click', submit); + input.addEventListener('keydown', (e) => { if (e.key === 'Enter') submit(); }); + } + refs.manualHint.textContent = inst.manualPrice?.at ? `手动价更新于 ${inst.manualPrice.at}` : ''; + } else { + refs.manual.innerHTML = ''; + refs.manualHint.textContent = ''; + } +} + +/** 渲染行情看板 */ +function renderMarket() { + const data = ui.data; + if (!data) return; + const grid = document.getElementById('instrumentGrid'); + const empty = document.getElementById('instrumentEmpty'); + const list = data.instruments || []; + empty.hidden = list.length > 0; + + // 结构变化(增删、顺序、名称、频率、单位)时才重建卡片 + const signature = list.map((i) => `${i.id}:${i.name}:${i.unit}:${i.intervalSec}:${i.source}`).join('|'); + const needRebuild = signature !== ui.marketSignature; + if (needRebuild) { + ui.marketSignature = signature; + ui.cards.clear(); + grid.innerHTML = ''; + for (const inst of list) { + const { root, refs } = buildCard(inst); + grid.appendChild(root); + updateCard(refs, inst); + } + } else { + for (const inst of list) { + const refs = ui.cards.get(inst.id); + if (refs) updateCard(refs, inst); + } + } +} + +/** + * 通知渠道 key 的中文名 + * @param {string} key 渠道标识(desktop / email / webhook) + * @returns {string} + */ +function channelName(key) { + return { desktop: '桌面', email: '邮件', webhook: 'WebHook' }[key] || key; +} + +/** 星期文案:定时提醒里用,1=周一 … 7=周日 */ +const WEEKDAY_NAMES = { 1: '周一', 2: '周二', 3: '周三', 4: '周四', 5: '周五', 6: '周六', 7: '周日' }; + +/** + * 统计区间秒数转文案(0 表示日内相对昨收) + * @param {number} windowSec 秒 + * @returns {string} 例如「日内」「近 10 分钟」「近 2 小时」 + */function windowText(windowSec) { + const sec = Number(windowSec) || 0; + if (sec <= 0) return '日内'; + if (sec < 60) return `近 ${sec} 秒`; + if (sec % 3600 === 0) return `近 ${sec / 3600} 小时`; + return `近 ${Math.round(sec / 60)} 分钟`; +} + +/** + * 取品种的价格单位(找不到时回落到「元/克」) + * @param {string} instrumentId 品种 id + * @returns {string} 单位文案,例如「元/克」「美元/盎司」 + */ +function unitOf(instrumentId) { + const inst = (ui.data?.instruments || []).find((i) => i.id === instrumentId); + return inst?.unit || '元/克'; +} + +/** 规则条件的可读描述 */ +function ruleConditionText(rule) { + const data = ui.data; + const instruments = data?.instruments || []; + const left = instruments.find((i) => i.id === rule.instrumentId); + const right = instruments.find((i) => i.id === rule.compareInstrumentId); + if (!left) return '品种已删除'; + + // 生效时段统一追加在条件末尾 + const rangeSuffix = rule.activeRange ? `(仅 ${rule.activeRange} 生效)` : ''; + + if (rule.type === 'threshold') { + const op = rule.direction === 'below' ? '≤' : '≥'; + return `${left.name} 价格 ${op} ${fmt(rule.value, left.digits)} ${left.unit}${rangeSuffix}`; + } + if (rule.type === 'change') { + const dirText = rule.direction === 'up' ? '涨幅' : rule.direction === 'down' ? '跌幅' : '涨跌幅'; + // 统计区间:日内相对昨收,或近 N 分钟的滚动窗口 + const scope = windowText(rule.windowSec); + // 阈值口径:百分比,或具体价格变动值(元/克等) + const isAmount = rule.changeBasis === 'amount'; + const valueText = isAmount + ? `${fmt(Math.abs(rule.value), left.digits)} ${left.unit}` + : `${Math.abs(rule.value).toFixed(2)}%`; + const absText = rule.direction === 'both' ? '绝对值' : ''; + return `${left.name} ${scope}${dirText} ${absText} ≥ ${valueText}${rangeSuffix}`.replace(' ', ' '); + } + if (rule.type === 'schedule') { + // 定时提醒:重复方式 + 时刻,必要时带上每周哪几天 + const repeatText = rule.scheduleRepeat === 'weekday' ? '工作日' : rule.scheduleRepeat === 'weekly' ? '每周' : '每天'; + const weekText = rule.scheduleRepeat === 'weekly' + ? `(${(rule.scheduleWeekdays || []).map((n) => WEEKDAY_NAMES[n]).filter(Boolean).join('、') || '未选星期'})` + : ''; + const times = (rule.scheduleTimes || []).join('、') || '未设置时刻'; + return `${left.name} ${repeatText}${weekText} ${times} 定时提醒${rangeSuffix}`; + } + if (!right) return '对比品种已删除'; + const unitText = rule.mode === 'percent' ? '%' : left.unit; + const dirText = rule.direction === 'above' ? `${left.name} 高于 ${right.name}` : rule.direction === 'below' ? `${right.name} 高于 ${left.name}` : '两者价差'; + return `${dirText} ≥ ${Math.abs(rule.value)}${unitText}${rangeSuffix}`; +} + +/** + * 规则名称比较函数:中文按拼音、数字按大小排序 + * (例如「涨跌 2%」会排在「涨跌 10%」前面,而不是按字符顺序排到后面) + * @param {object} a 规则 A + * @param {object} b 规则 B + * @returns {number} 比较结果 + */ +function compareRuleName(a, b) { + return String(a.name || '').localeCompare(String(b.name || ''), 'zh-Hans-CN', { numeric: true, sensitivity: 'base' }); +} + +/** 渲染规则列表(按名称自动排序) */ +function renderRules() { + const data = ui.data; + if (!data) return; + const list = [...(data.rules || [])].sort(compareRuleName); + const box = document.getElementById('ruleList'); + document.getElementById('ruleEmpty').hidden = list.length > 0; + + box.innerHTML = list.map((rule) => { + const channels = (rule.channels || []).map(channelName).join(' + '); + const typeText = rule.type === 'threshold' ? '价格阈值' : rule.type === 'change' ? '涨跌幅' : rule.type === 'schedule' ? '定时' : '价差'; + // 定时提醒按时刻去重,没有冷却/重复的概念,列表里不展示这两项 + const extraText = rule.type === 'schedule' + ? '' + : ` · 冷却 ${rule.cooldownSec}s${rule.repeatIntervalSec > 0 ? ` · 每 ${rule.repeatIntervalSec}s 重复` : ''}`; + return ` +
+ +
+
+ ${esc(rule.name)} + ${typeText} +
+
${esc(ruleConditionText(rule))}
+
渠道:${esc(channels || '默认渠道')}${extraText}
+
+
+ + +
+
`; + }).join(''); + + // 事件绑定 + box.querySelectorAll('.rule-item').forEach((item) => { + const id = item.dataset.id; + const rule = list.find((r) => r.id === id); + if (!rule) return; + + item.querySelector('.js-rule-toggle').addEventListener('change', async (e) => { + try { + const res = await api(`/api/rules/${id}`, { method: 'PUT', body: { enabled: e.target.checked } }); + applyState(res, false); + } catch (err) { + toast(err.message, 'err'); + } + }); + + item.querySelector('.js-rule-edit').addEventListener('click', () => openRuleModal(id)); + item.querySelector('.js-rule-del').addEventListener('click', async () => { + if (!window.confirm(`确定删除规则「${rule.name}」?`)) return; + try { + const res = await api(`/api/rules/${id}`, { method: 'DELETE' }); + applyState(res, false); + toast('已删除规则', 'ok'); + } catch (err) { + toast(err.message, 'err'); + } + }); + }); +} + +/** 渲染提醒记录 */ +function renderAlerts() { + const data = ui.data; + if (!data) return; + const alerts = data.alerts || []; + const box = document.getElementById('alertList'); + document.getElementById('alertEmpty').hidden = alerts.length > 0; + + box.innerHTML = alerts.map((alert) => { + const chan = (alert.delivered || []).map((d) => { + const name = channelName(d.channel); + const state = d.ok ? '✓' : d.muted ? '—' : '✕'; + const cls = d.ok ? 'ok' : d.muted ? '' : 'err'; + return `${name} ${state}`; + }).join(' · '); + return ` +
+
${esc(alert.title)}
+
${esc(alert.message)}
+
+ ${esc(alert.at)} + 规则:${esc(alert.ruleName || '')} + ${chan} +
+
`; + }).join(''); +} + +/** 渲染当前标签页 */ +function renderActiveTab() { + if (ui.tab === 'market') renderMarket(); + if (ui.tab === 'rules') renderRules(); + if (ui.tab === 'alerts') renderAlerts(); +} + +/** + * 应用一次后端返回的完整状态 + * @param {object} payload /api/* 返回的数据 + * @param {boolean} forceRebuild 是否强制重建行情卡片 + */ +function applyState(payload, forceRebuild = false) { + if (!payload) return; + ui.data = payload; + + // 计算未读提醒 + const alerts = payload.alerts || []; + ui.unread = alerts.filter((a) => (a.atMs || 0) > ui.seenAtMs).length; + + if (forceRebuild) ui.marketSignature = ''; + + renderHeader(); + renderActiveTab(); +} + +/** 拉取最新状态 */ +async function refreshState(forceRebuild = false) { + try { + const payload = await api('/api/state'); + applyState(payload, forceRebuild); + return payload; + } catch (err) { + toast(`状态刷新失败:${err.message}`, 'err'); + return null; + } +} + +/** 开始轮询(5 秒一次) */ +function startPolling() { + if (ui.timer) clearInterval(ui.timer); + ui.timer = setInterval(() => { + if (document.hidden) return; + refreshState(false); + }, 5000); +} + +/* ================================================================== + * 设置区:读取与保存 + * ================================================================== */ + +/** 把配置填进设置表单 */ +function fillSettings() { + const cfg = ui.data?.config; + if (!cfg) return; + document.getElementById('desktopEnabled').checked = !!cfg.desktop.enabled; + document.getElementById('channelDesktop').checked = (cfg.channels.onTrigger || []).includes('desktop'); + document.getElementById('channelEmail').checked = (cfg.channels.onTrigger || []).includes('email'); + document.getElementById('channelWebhook').checked = (cfg.channels.onTrigger || []).includes('webhook'); + document.getElementById('defaultInterval').value = cfg.monitor.defaultIntervalSec; + document.getElementById('quietEnabled').checked = !!cfg.monitor.quietHours.enabled; + document.getElementById('quietRange').value = cfg.monitor.quietHours.range || '23:00-07:00'; + document.getElementById('alertOnFirstCheck').checked = cfg.monitor.alertOnFirstCheck === true; + + document.getElementById('emailEnabled').checked = !!cfg.email.enabled; + document.getElementById('emailHost').value = cfg.email.host || ''; + document.getElementById('emailPort').value = cfg.email.port || 465; + document.getElementById('emailSecure').value = cfg.email.secure ? 'true' : 'false'; + document.getElementById('emailUser').value = cfg.email.user || ''; + document.getElementById('emailPass').value = ''; + document.getElementById('emailPass').placeholder = cfg.email.passConfigured ? '已设置(留空则不修改)' : '留空则不修改'; + document.getElementById('emailFrom').value = cfg.email.from || ''; + document.getElementById('emailTo').value = (cfg.email.to || []).join(', '); + document.getElementById('emailPrefix').value = cfg.email.subjectPrefix || '【金价提醒】'; + document.getElementById('emailSnapshot').checked = cfg.email.withSnapshot !== false; + + // WebHook + const webhook = cfg.webhook || {}; + document.getElementById('webhookEnabled').checked = !!webhook.enabled; + document.getElementById('webhookUrl').value = webhook.url || ''; + document.getElementById('webhookFormat').value = webhook.format || 'generic'; + document.getElementById('webhookSecret').value = ''; + document.getElementById('webhookSecret').placeholder = webhook.secretConfigured + ? '已设置(留空则不修改)' + : 'SEC 开头;机器人未启用加签可留空'; + document.getElementById('webhookKeyword').value = webhook.keyword || ''; + document.getElementById('webhookAtMobiles').value = (webhook.atMobiles || []).join(', '); + document.getElementById('webhookMentionAll').checked = webhook.mentionAll === true; + syncWebhookFields(); + + document.getElementById('appPort').value = cfg.app.port; + document.getElementById('appHost').value = cfg.app.host; + document.getElementById('appToken').value = cfg.app.token || ''; + document.getElementById('appOpenBrowser').checked = cfg.app.openBrowser !== false; + + document.getElementById('configPathHint').textContent = `配置文件:${cfg.meta?.configFile || ''}`; + setResult('emailTestResult', ''); + setResult('desktopTestResult', ''); + setResult('webhookTestResult', ''); + setResult('saveResult', ''); +} + +/** 按报文格式切换 WebHook 的钉钉专属字段,并给出格式说明 */ +function syncWebhookFields() { + const isDingTalk = document.getElementById('webhookFormat').value === 'dingtalk'; + document.getElementById('webhookSecretField').hidden = !isDingTalk; + document.getElementById('webhookKeywordField').hidden = !isDingTalk; + document.getElementById('webhookAtMobilesField').hidden = !isDingTalk; + document.getElementById('webhookMentionAllField').hidden = !isDingTalk; + document.getElementById('webhookUrl').placeholder = isDingTalk + ? 'https://oapi.dingtalk.com/robot/send?access_token=xxx' + : 'https://your-server.com/hooks/gold-alert'; + document.getElementById('webhookFormatHint').textContent = isDingTalk + ? '钉钉:群设置 → 机器人 → 自定义 → Webhook 地址。安全设置若用「加签」填密钥,若用「自定义关键词」把那个词填到上面(工具会自动拼进消息标题),二者可只开一个。' + : '内置 JSON:POST { event, title, message, markdown, at, rule, lines, source },第三方系统按字段取用即可。'; +} + +/** 收集设置表单,保存到后端 */ +async function saveSettings() { + const emailPass = document.getElementById('emailPass').value.trim(); + const payload = { + desktop: { enabled: document.getElementById('desktopEnabled').checked }, + channels: { + onTrigger: [ + document.getElementById('channelDesktop').checked ? 'desktop' : null, + document.getElementById('channelEmail').checked ? 'email' : null, + document.getElementById('channelWebhook').checked ? 'webhook' : null, + ].filter(Boolean), + }, + monitor: { + defaultIntervalSec: Number(document.getElementById('defaultInterval').value) || 30, + alertOnFirstCheck: document.getElementById('alertOnFirstCheck').checked, + quietHours: { + enabled: document.getElementById('quietEnabled').checked, + range: document.getElementById('quietRange').value.trim() || '23:00-07:00', + desktopOnly: true, + }, + }, + email: { + enabled: document.getElementById('emailEnabled').checked, + host: document.getElementById('emailHost').value.trim(), + port: Number(document.getElementById('emailPort').value) || 465, + secure: document.getElementById('emailSecure').value === 'true', + user: document.getElementById('emailUser').value.trim(), + from: document.getElementById('emailFrom').value.trim(), + to: document.getElementById('emailTo').value.split(/[,;,;\s]+/).filter(Boolean), + subjectPrefix: document.getElementById('emailPrefix').value.trim() || '【金价提醒】', + withSnapshot: document.getElementById('emailSnapshot').checked, + }, + webhook: { + enabled: document.getElementById('webhookEnabled').checked, + url: document.getElementById('webhookUrl').value.trim(), + format: document.getElementById('webhookFormat').value === 'dingtalk' ? 'dingtalk' : 'generic', + keyword: document.getElementById('webhookKeyword').value.trim(), + atMobiles: document.getElementById('webhookAtMobiles').value.split(/[,;,;\s]+/).filter(Boolean), + mentionAll: document.getElementById('webhookMentionAll').checked, + }, + app: { + port: Number(document.getElementById('appPort').value) || 8787, + host: document.getElementById('appHost').value.trim() || '127.0.0.1', + token: document.getElementById('appToken').value.trim(), + openBrowser: document.getElementById('appOpenBrowser').checked, + }, + }; + // 只有用户真正输入了密码才提交,避免把打码值写回 + if (emailPass) payload.email.pass = emailPass; + // 加签密钥同理:留空表示沿用已保存的密钥 + const webhookSecret = document.getElementById('webhookSecret').value.trim(); + if (webhookSecret) payload.webhook.secret = webhookSecret; + + const res = await api('/api/config', { method: 'PUT', body: payload }); + applyState(res, false); + fillSettings(); + setResult('saveResult', '已保存', true); + toast('设置已保存', 'ok'); + return res; +} + +/* ================================================================== + * 弹窗:品种 + * ================================================================== */ + +/** 打开品种弹窗(id 为空表示新增) */ +function openInstrumentModal(id) { + const data = ui.data; + ui.editingInstrumentId = id || null; + const inst = id ? (data.instruments || []).find((i) => i.id === id) : null; + + document.getElementById('instrumentModalTitle').textContent = inst ? `编辑品种 · ${inst.name}` : '添加品种'; + setResult('instrumentResult', ''); + + // 预设下拉 + const presetRow = document.getElementById('presetSelect').closest('label'); + const presets = data?.config?.meta?.presets || []; + if (!inst) { + presetRow.hidden = false; + const groups = new Map(); + for (const p of presets) { + if (!groups.has(p.category)) groups.set(p.category, []); + groups.get(p.category).push(p); + } + const select = document.getElementById('presetSelect'); + select.innerHTML = [...groups.entries()].map(([category, items]) => ` + + ${items.map((p) => ``).join('')} + `).join(''); + select.value = presets[0]?.key || ''; + } else { + presetRow.hidden = true; + } + + // 数据源下拉(编辑模式可见) + const sourceSelect = document.getElementById('instSource'); + sourceSelect.innerHTML = (data?.config?.meta?.dataSources || []) + .map((s) => ``).join(''); + sourceSelect.closest('label').hidden = !inst; + + // 填入字段 + document.getElementById('instName').value = inst?.name || ''; + document.getElementById('instInterval').value = inst?.intervalSec ?? data?.config?.monitor.defaultIntervalSec ?? 30; + document.getElementById('instUnit').value = inst?.unit || '元/克'; + document.getElementById('instDigits').value = inst?.digits ?? 2; + sourceSelect.value = inst?.source || presets[0]?.source || 'sina'; + document.getElementById('instSinaCode').value = inst?.sourceOptions?.code || ''; + document.getElementById('instRijinjiaKey').value = inst?.sourceOptions?.key || ''; + document.getElementById('instHttpUrl').value = inst?.sourceOptions?.url || ''; + document.getElementById('instHttpPricePath').value = inst?.sourceOptions?.pricePath || 'data.price'; + document.getElementById('instHttpPrevPath').value = inst?.sourceOptions?.prevClosePath || ''; + + syncInstrumentFields(); + // 新增模式最后再按预设回填,避免被上面的空值覆盖 + if (!inst) applyPreset(document.getElementById('presetSelect').value); + openModal('modalInstrument'); +} + +/** 根据数据源显示/隐藏对应参数输入 */ +function syncInstrumentFields() { + const source = document.getElementById('instSource').value; + document.getElementById('sinaCodeField').hidden = source !== 'sina'; + document.getElementById('rijinjiaKeyField').hidden = source !== 'rijinjia'; + document.getElementById('httpUrlField').hidden = source !== 'http-json'; + document.getElementById('httpPricePathField').hidden = source !== 'http-json'; + document.getElementById('httpPrevPathField').hidden = source !== 'http-json'; + document.getElementById('instSource').closest('label').hidden = !ui.editingInstrumentId; +} + +/** 从预设回填字段 */ +function applyPreset(presetKey) { + const preset = (ui.data?.config?.meta?.presets || []).find((p) => p.key === presetKey); + if (!preset) return; + document.getElementById('instName').value = preset.name; + document.getElementById('instInterval').value = preset.intervalSec || 30; + document.getElementById('instUnit').value = preset.unit || '元/克'; + document.getElementById('instDigits').value = preset.digits ?? 2; + document.getElementById('instSource').value = preset.source; + document.getElementById('instSinaCode').value = preset.sourceOptions?.code || ''; + document.getElementById('instRijinjiaKey').value = preset.sourceOptions?.key || ''; + document.getElementById('instHttpUrl').value = preset.sourceOptions?.url || ''; + document.getElementById('instHttpPricePath').value = preset.sourceOptions?.pricePath || 'data.price'; + document.getElementById('instHttpPrevPath').value = preset.sourceOptions?.prevClosePath || ''; + document.getElementById('presetHint').textContent = preset.note || ''; + syncInstrumentFields(); +} + +/** 收集品种弹窗的字段 */ +function collectInstrument(extra = {}) { + const source = document.getElementById('instSource').value; + const sourceOptions = {}; + if (source === 'sina') sourceOptions.code = document.getElementById('instSinaCode').value.trim(); + if (source === 'rijinjia') sourceOptions.key = document.getElementById('instRijinjiaKey').value.trim(); + if (source === 'http-json') { + sourceOptions.url = document.getElementById('instHttpUrl').value.trim(); + sourceOptions.pricePath = document.getElementById('instHttpPricePath').value.trim() || 'price'; + const prevPath = document.getElementById('instHttpPrevPath').value.trim(); + if (prevPath) sourceOptions.prevClosePath = prevPath; + } + return { + name: document.getElementById('instName').value.trim(), + source, + sourceOptions, + unit: document.getElementById('instUnit').value.trim() || '元/克', + digits: Number(document.getElementById('instDigits').value) || 2, + intervalSec: Number(document.getElementById('instInterval').value) || 30, + ...extra, + }; +} + +/** 保存品种 */ +async function saveInstrument() { + const body = collectInstrument(); + if (!body.name) { + setResult('instrumentResult', '请填写名称', false); + return; + } + try { + let res; + if (ui.editingInstrumentId) { + res = await api(`/api/instruments/${ui.editingInstrumentId}`, { method: 'PUT', body }); + } else { + body.presetKey = document.getElementById('presetSelect').value; + res = await api('/api/instruments', { method: 'POST', body }); + } + applyState(res, true); + closeModal('modalInstrument'); + toast(ui.editingInstrumentId ? '品种已更新' : '品种已添加', 'ok'); + } catch (err) { + setResult('instrumentResult', err.message, false); + } +} + +/* ================================================================== + * 弹窗:规则 + * ================================================================== */ + +/** 按规则类型刷新方向选项与字段显隐 */ +function syncRuleFields() { + const type = document.getElementById('ruleType').value; + const isSchedule = type === 'schedule'; + const dirSelect = document.getElementById('ruleDirection'); + // 涨跌幅的阈值口径:percent 按百分比,amount 按具体价格变动值 + const isAmount = document.getElementById('ruleBasis').value === 'amount'; + const unit = unitOf(document.getElementById('ruleInstrument').value); + const changeUnitText = isAmount ? unit : '%'; + const options = type === 'threshold' + ? [['above', '上破(价格 ≥ 阈值)'], ['below', '下破(价格 ≤ 阈值)']] + : type === 'change' + ? [['up', `涨幅 ≥ 阈值(${changeUnitText})`], ['down', `跌幅 ≥ 阈值(${changeUnitText})`], ['both', `涨跌幅绝对值 ≥ 阈值(${changeUnitText})`]] + : [['abs', '绝对价差 ≥ 阈值'], ['above', '前者高于后者 ≥ 阈值'], ['below', '后者高于前者 ≥ 阈值']]; + + const current = dirSelect.value; + dirSelect.innerHTML = options.map(([v, t]) => ``).join(''); + dirSelect.value = options.some(([v]) => v === current) ? current : options[0][0]; + + document.getElementById('ruleCompareField').hidden = type !== 'spread'; + document.getElementById('ruleModeField').hidden = type !== 'spread'; + document.getElementById('ruleBasisField').hidden = type !== 'change'; + document.getElementById('ruleWindowField').hidden = type !== 'change'; + // 定时提醒不看价格条件:方向和阈值、统计区间、生效时段、冷却/重复都收起 + document.getElementById('ruleDirectionField').hidden = isSchedule; + document.getElementById('ruleValueField').hidden = isSchedule; + document.getElementById('ruleActiveRangeField').hidden = isSchedule; + document.getElementById('ruleCooldownField').hidden = isSchedule; + document.getElementById('ruleRepeatField').hidden = isSchedule; + // 定时提醒自己的字段:时刻、重复方式、每周星期 + document.getElementById('ruleScheduleTimesField').hidden = !isSchedule; + document.getElementById('ruleScheduleRepeatField').hidden = !isSchedule; + syncScheduleWeekdays(); + syncWindowCustom(); + document.getElementById('ruleValueLabel').textContent = type === 'threshold' + ? '阈值(价格)' + : type === 'change' ? (isAmount ? `阈值(${unit})` : '阈值(百分比 %)') : '阈值(价差)'; + // 阈值输入框的示例值按当前口径切换,避免涨跌幅里还显示价格的 800 + document.getElementById('ruleValue').placeholder = type === 'threshold' + ? '800' + : type === 'change' ? (isAmount ? '3' : '0.5') + : (document.getElementById('ruleMode').value === 'percent' ? '1' : '100'); + // 统计区间 / 定时提醒的说明各管各的 + document.getElementById('ruleWindowHint').hidden = type !== 'change'; + document.getElementById('ruleScheduleHint').hidden = !isSchedule; + updateRuleSummary(); +} + +/** 定时提醒选「每周指定几天」时显示星期勾选框 */ +function syncScheduleWeekdays() { + const isSchedule = document.getElementById('ruleType').value === 'schedule'; + const isWeekly = isSchedule && document.getElementById('ruleScheduleRepeat').value === 'weekly'; + document.getElementById('ruleScheduleWeekdaysField').hidden = !isWeekly; +} + +/** + * 读取定时提醒的时刻列表 + * 支持逗号/空格分隔,自动补零、去重、按时间排序 + * @returns {string[]} 形如 ["09:00","15:30"] + */ +function readScheduleTimes() { + const raw = document.getElementById('ruleScheduleTimes').value || ''; + const seen = new Set(); + const list = []; + for (const item of raw.split(/[,,\s]+/)) { + const text = 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); + list.push(hhmm); + } + return list.sort(); +} + +/** + * 读取定时提醒选中的星期 + * @returns {number[]} 1=周一 … 7=周日 + */ +function readScheduleWeekdays() { + return [...document.querySelectorAll('.js-weekday:checked')].map((el) => Number(el.value)).sort((a, b) => a - b); +} + +/** 统计区间选「自定义」时显示分钟输入框 */ +function syncWindowCustom() { + const isChange = document.getElementById('ruleType').value === 'change'; + const isCustom = isChange && document.getElementById('ruleWindow').value === '-1'; + document.getElementById('ruleWindowCustomField').hidden = !isCustom; +} + +/** + * 读取弹窗里的统计区间(秒) + * @returns {number} 0 表示日内(相对昨收),>0 表示近 N 秒滚动窗口 + */ +function readWindowSec() { + if (document.getElementById('ruleType').value !== 'change') return 0; + const selectValue = document.getElementById('ruleWindow').value; + if (selectValue === '-1') { + const minutes = Number(document.getElementById('ruleWindowCustom').value); + return Number.isFinite(minutes) && minutes > 0 ? Math.round(minutes * 60) : 0; + } + return Number(selectValue) || 0; +} + +/** + * 读取生效时段 + * @returns {string} "HH:mm-HH:mm",两端任一为空则返回空字符串(表示全天) + */ +function readActiveRange() { + const from = document.getElementById('ruleActiveFrom').value; + const to = document.getElementById('ruleActiveTo').value; + return from && to ? `${from}-${to}` : ''; +} + +/** 生成规则预览文案 */ +function updateRuleSummary() { + const type = document.getElementById('ruleType').value; + const draft = { + type, + instrumentId: document.getElementById('ruleInstrument').value, + compareInstrumentId: document.getElementById('ruleCompare').value, + mode: document.getElementById('ruleMode').value, + changeBasis: document.getElementById('ruleBasis').value, + direction: document.getElementById('ruleDirection').value, + value: Number(document.getElementById('ruleValue').value) || 0, + cooldownSec: Number(document.getElementById('ruleCooldown').value) || 0, + windowSec: readWindowSec(), + activeRange: readActiveRange(), + scheduleTimes: readScheduleTimes(), + scheduleRepeat: document.getElementById('ruleScheduleRepeat').value, + scheduleWeekdays: readScheduleWeekdays(), + }; + // 定时提醒没有阈值,直接按时刻生成预览 + if (type === 'schedule') { + document.getElementById('ruleSummary').textContent = draft.scheduleTimes.length + ? `预览:${ruleConditionText(draft)}` + : '预览:填写提醒时刻后显示条件预览'; + return; + } + const value = Number(document.getElementById('ruleValue').value); + if (!Number.isFinite(value) || value === 0) { + document.getElementById('ruleSummary').textContent = '预览:填写阈值后显示条件预览'; + return; + } + document.getElementById('ruleSummary').textContent = `预览:${ruleConditionText(draft)}`; +} + +/** 打开规则弹窗 */ +function openRuleModal(id) { + const data = ui.data; + ui.editingRuleId = id || null; + const rule = id ? (data.rules || []).find((r) => r.id === id) : null; + document.getElementById('ruleModalTitle').textContent = rule ? '编辑规则' : '新建规则'; + setResult('ruleResult', ''); + + const instruments = data.instruments || []; + const instOptions = instruments.map((i) => ``).join(''); + document.getElementById('ruleInstrument').innerHTML = instOptions || ''; + document.getElementById('ruleCompare').innerHTML = instOptions || ''; + + document.getElementById('ruleName').value = rule?.name || ''; + document.getElementById('ruleType').value = rule?.type || 'threshold'; + document.getElementById('ruleInstrument').value = rule?.instrumentId || instruments[0]?.id || ''; + document.getElementById('ruleCompare').value = rule?.compareInstrumentId || instruments[1]?.id || instruments[0]?.id || ''; + document.getElementById('ruleMode').value = rule?.mode || 'abs'; + document.getElementById('ruleBasis').value = rule?.changeBasis === 'amount' ? 'amount' : 'percent'; + document.getElementById('ruleValue').value = rule?.value ?? ''; + document.getElementById('ruleCooldown').value = rule?.cooldownSec ?? 1800; + document.getElementById('ruleRepeat').value = rule?.repeatIntervalSec ?? 0; + + // 定时提醒:时刻用逗号展示,重复方式与每周星期回填 + document.getElementById('ruleScheduleTimes').value = (rule?.scheduleTimes || []).join(', '); + document.getElementById('ruleScheduleRepeat').value = ['daily', 'weekday', 'weekly'].includes(rule?.scheduleRepeat) + ? rule.scheduleRepeat : 'daily'; + const weekdays = rule?.scheduleWeekdays || []; + document.querySelectorAll('.js-weekday').forEach((el) => { + el.checked = weekdays.includes(Number(el.value)); + }); + + // 统计区间:命中预设选项就直接选中,否则退到「自定义(分钟)」 + const windowSec = Number(rule?.windowSec) || 0; + const windowSelect = document.getElementById('ruleWindow'); + if (windowSec > 0 && [...windowSelect.options].some((opt) => opt.value === String(windowSec))) { + windowSelect.value = String(windowSec); + document.getElementById('ruleWindowCustom').value = ''; + } else if (windowSec > 0) { + windowSelect.value = '-1'; + document.getElementById('ruleWindowCustom').value = Math.round(windowSec / 60); + } else { + windowSelect.value = '0'; + document.getElementById('ruleWindowCustom').value = ''; + } + + // 生效时段:"HH:mm-HH:mm",时间控件要求两位小时 + const activeRange = String(rule?.activeRange || ''); + const rangeMatch = /^(\d{1,2}):(\d{2})-(\d{1,2}):(\d{2})$/.exec(activeRange); + document.getElementById('ruleActiveFrom').value = rangeMatch + ? `${String(rangeMatch[1]).padStart(2, '0')}:${rangeMatch[2]}` : ''; + document.getElementById('ruleActiveTo').value = rangeMatch + ? `${String(rangeMatch[3]).padStart(2, '0')}:${rangeMatch[4]}` : ''; + // 新建规则时:桌面默认勾选;邮箱/WebHook 已在设置里启用则一并勾选 + const defaultChannels = rule + ? (rule.channels || ['desktop']) + : ['desktop'] + .concat(ui.data?.config?.email?.enabled ? ['email'] : []) + .concat(ui.data?.config?.webhook?.enabled ? ['webhook'] : []); + document.getElementById('ruleChannelDesktop').checked = defaultChannels.includes('desktop'); + document.getElementById('ruleChannelEmail').checked = defaultChannels.includes('email'); + document.getElementById('ruleChannelWebhook').checked = defaultChannels.includes('webhook'); + document.getElementById('ruleEnabled').checked = rule ? !!rule.enabled : true; + + syncRuleFields(); + if (rule?.direction) document.getElementById('ruleDirection').value = rule.direction; + updateRuleSummary(); + openModal('modalRule'); +} + +/** 保存规则 */ +async function saveRule() { + const instruments = ui.data?.instruments || []; + const instrumentId = document.getElementById('ruleInstrument').value; + const compareInstrumentId = document.getElementById('ruleCompare').value; + if (!instrumentId) { + setResult('ruleResult', '请先添加监控品种', false); + return; + } + + const type = document.getElementById('ruleType').value; + const direction = document.getElementById('ruleDirection').value; + const value = Number(document.getElementById('ruleValue').value); + // 定时提醒不看阈值,单独校验时刻 + const scheduleTimes = readScheduleTimes(); + if (type === 'schedule') { + if (!scheduleTimes.length) { + setResult('ruleResult', '请填写提醒时刻,例如 09:00, 15:30', false); + return; + } + if (scheduleTimes.length > 12) { + setResult('ruleResult', '提醒时刻最多 12 个', false); + return; + } + if (document.getElementById('ruleScheduleRepeat').value === 'weekly' && !readScheduleWeekdays().length) { + setResult('ruleResult', '请至少勾选一个星期几', false); + return; + } + } else if (!Number.isFinite(value) || (type !== 'threshold' && value === 0)) { + setResult('ruleResult', '请填写有效的阈值', false); + return; + } + + const inst = instruments.find((i) => i.id === instrumentId); + const nameInput = document.getElementById('ruleName').value.trim(); + const channels = [ + document.getElementById('ruleChannelDesktop').checked ? 'desktop' : null, + document.getElementById('ruleChannelEmail').checked ? 'email' : null, + document.getElementById('ruleChannelWebhook').checked ? 'webhook' : null, + ].filter(Boolean); + if (channels.length === 0) { + setResult('ruleResult', '至少选择一个通知渠道', false); + return; + } + + // 统计区间 / 生效时段 + const windowSec = readWindowSec(); + if (type === 'change' && document.getElementById('ruleWindow').value === '-1' && windowSec <= 0) { + setResult('ruleResult', '请填写自定义的统计区间(分钟)', false); + return; + } + // 后端最长支持 12 小时,这里提前拦一下,免得填太大被静默截断 + if (type === 'change' && windowSec > 43200) { + setResult('ruleResult', '统计区间最长 12 小时(720 分钟)', false); + return; + } + const activeRange = readActiveRange(); + + const body = { + // 未填名称时直接用条件文案(条件里已含品种名,不再重复拼接) + name: nameInput || ruleConditionText({ + type, direction, value, instrumentId, compareInstrumentId, + mode: document.getElementById('ruleMode').value, + changeBasis: document.getElementById('ruleBasis').value, + windowSec, activeRange, + scheduleTimes, + scheduleRepeat: document.getElementById('ruleScheduleRepeat').value, + scheduleWeekdays: readScheduleWeekdays(), + }), + type, + instrumentId, + compareInstrumentId: type === 'spread' ? compareInstrumentId : '', + mode: document.getElementById('ruleMode').value, + // 涨跌幅阈值口径:percent(百分比)/ amount(具体变动值) + changeBasis: type === 'change' ? document.getElementById('ruleBasis').value : 'percent', + direction: type === 'schedule' ? 'abs' : direction, + value: type === 'schedule' ? 0 : value, + cooldownSec: Number(document.getElementById('ruleCooldown').value) || 1800, + repeatIntervalSec: Number(document.getElementById('ruleRepeat').value) || 0, + windowSec, + activeRange, + // 定时提醒:到点时刻(后端会再归一化一次)、重复方式、每周星期 + scheduleTimes, + scheduleRepeat: document.getElementById('ruleScheduleRepeat').value, + scheduleWeekdays: readScheduleWeekdays(), + channels, + enabled: document.getElementById('ruleEnabled').checked, + }; + + try { + const res = ui.editingRuleId + ? await api(`/api/rules/${ui.editingRuleId}`, { method: 'PUT', body }) + : await api('/api/rules', { method: 'POST', body }); + applyState(res, false); + closeModal('modalRule'); + toast(ui.editingRuleId ? '规则已更新' : '规则已创建', 'ok'); + } catch (err) { + setResult('ruleResult', err.message, false); + } +} + +/* ================================================================== + * 弹窗通用 + * ================================================================== */ + +/** 打开弹窗 */ +function openModal(id) { + document.getElementById(id).hidden = false; + document.body.style.overflow = 'hidden'; +} + +/** 关闭弹窗 */ +function closeModal(id) { + document.getElementById(id).hidden = true; + document.body.style.overflow = ''; +} + +/* ================================================================== + * 事件绑定与启动 + * ================================================================== */ + +/** 切换标签页 */ +function activateTab(name) { + const tab = document.querySelector(`.tab[data-tab="${name}"]`); + if (!tab) return; + document.querySelectorAll('.tab').forEach((t) => t.classList.toggle('active', t === tab)); + document.querySelectorAll('.panel').forEach((p) => p.classList.remove('active')); + document.querySelector(`#panel-${name}`).classList.add('active'); + ui.tab = name; + if (name === 'alerts') { + ui.seenAtMs = Date.now(); + ui.unread = 0; + } + if (name === 'channels') fillSettings(); + renderActiveTab(); + renderHeader(); +} + +/** 绑定所有交互事件 */ +function bindEvents() { + // 标签页切换 + document.getElementById('tabs').addEventListener('click', (e) => { + const tab = e.target.closest('.tab'); + if (!tab) return; + activateTab(tab.dataset.tab); + }); + + // 暂停 / 开始 + document.getElementById('btnToggleRun').addEventListener('click', async () => { + const running = !(ui.data?.running); + try { + const res = await api('/api/monitor', { method: 'POST', body: { running } }); + applyState(res, false); + toast(running ? '监控已开始' : '监控已暂停', 'ok'); + } catch (err) { + toast(err.message, 'err'); + } + }); + + // 立即刷新 + document.getElementById('btnRefresh').addEventListener('click', async (e) => { + e.target.disabled = true; + try { + const res = await api('/api/refresh', { method: 'POST' }); + applyState(res, false); + toast('已拉取最新行情', 'ok'); + } catch (err) { + toast(err.message, 'err'); + } finally { + e.target.disabled = false; + } + }); + + // 品种 + document.getElementById('btnAddInstrument').addEventListener('click', () => openInstrumentModal(null)); + document.getElementById('presetSelect').addEventListener('change', (e) => applyPreset(e.target.value)); + document.getElementById('instSource').addEventListener('change', syncInstrumentFields); + document.getElementById('btnSaveInstrument').addEventListener('click', saveInstrument); + + document.getElementById('btnTestInstrument').addEventListener('click', async () => { + const body = collectInstrument(); + setResult('instrumentResult', '正在试抓取…', null); + try { + const res = await api('/api/test/source', { method: 'POST', body }); + setResult('instrumentResult', res.detail || '抓取成功', true); + } catch (err) { + setResult('instrumentResult', err.message, false); + } + }); + + // 规则 + document.getElementById('btnAddRule').addEventListener('click', () => openRuleModal(null)); + document.getElementById('ruleType').addEventListener('change', syncRuleFields); + document.getElementById('ruleInstrument').addEventListener('change', syncRuleFields); + document.getElementById('ruleCompare').addEventListener('change', updateRuleSummary); + document.getElementById('ruleMode').addEventListener('change', syncRuleFields); + document.getElementById('ruleBasis').addEventListener('change', syncRuleFields); + document.getElementById('ruleDirection').addEventListener('change', updateRuleSummary); + document.getElementById('ruleValue').addEventListener('input', updateRuleSummary); + document.getElementById('ruleCooldown').addEventListener('input', updateRuleSummary); + // 统计区间与生效时段:改动后同步字段显隐和预览 + document.getElementById('ruleWindow').addEventListener('change', () => { + syncWindowCustom(); + updateRuleSummary(); + }); + document.getElementById('ruleWindowCustom').addEventListener('input', updateRuleSummary); + document.getElementById('ruleActiveFrom').addEventListener('change', updateRuleSummary); + document.getElementById('ruleActiveTo').addEventListener('change', updateRuleSummary); + // 定时提醒:时刻输入、重复方式、星期勾选都会影响预览 + document.getElementById('ruleScheduleTimes').addEventListener('input', updateRuleSummary); + document.getElementById('ruleScheduleRepeat').addEventListener('change', () => { + syncScheduleWeekdays(); + updateRuleSummary(); + }); + document.querySelectorAll('.js-weekday').forEach((el) => el.addEventListener('change', updateRuleSummary)); + document.getElementById('btnSaveRule').addEventListener('click', saveRule); + + // 设置保存 + document.getElementById('btnSaveSettings').addEventListener('click', async () => { + try { + await saveSettings(); + } catch (err) { + setResult('saveResult', err.message, false); + } + }); + + // 渠道自检 + document.getElementById('btnTestDesktop').addEventListener('click', async () => { + setResult('desktopTestResult', '发送中…', null); + try { + const res = await api('/api/test/desktop', { method: 'POST' }); + setResult('desktopTestResult', res.detail || '已发送', true); + } catch (err) { + setResult('desktopTestResult', err.message, false); + } + }); + + document.getElementById('btnTestEmail').addEventListener('click', async () => { + setResult('emailTestResult', '发送中,请稍候…', null); + try { + // 先把表单里的邮箱设置存下来再测,避免测的是旧配置 + await saveSettings(); + const res = await api('/api/test/email', { method: 'POST', body: {} }); + setResult('emailTestResult', res.detail || '已发送', true); + } catch (err) { + setResult('emailTestResult', err.message, false); + } + }); + + // WebHook:切换格式时同步字段显隐 + document.getElementById('webhookFormat').addEventListener('change', syncWebhookFields); + + document.getElementById('btnTestWebhook').addEventListener('click', async () => { + setResult('webhookTestResult', '推送中,请稍候…', null); + try { + // 先保存再测,避免测的是旧地址/旧格式 + await saveSettings(); + const res = await api('/api/test/webhook', { method: 'POST', body: {} }); + setResult('webhookTestResult', res.detail || '已推送', true); + } catch (err) { + setResult('webhookTestResult', err.message, false); + } + }); + + // 清空提醒 + document.getElementById('btnClearAlerts').addEventListener('click', async () => { + if (!window.confirm('确定清空页面上的提醒记录?data/alerts.jsonl 文件保留不动。')) return; + try { + await api('/api/alerts', { method: 'DELETE' }); + ui.data.alerts = []; + renderAlerts(); + renderHeader(); + } catch (err) { + toast(err.message, 'err'); + } + }); + + // 导入导出 + document.getElementById('btnExportConfig').addEventListener('click', () => { + window.location.href = '/api/config/export'; + }); + document.getElementById('btnImportConfig').addEventListener('click', () => document.getElementById('importFile').click()); + document.getElementById('importFile').addEventListener('change', async (e) => { + const file = e.target.files?.[0]; + if (!file) return; + try { + const text = await file.text(); + const json = JSON.parse(text); + const res = await api('/api/config/import', { method: 'POST', body: json }); + applyState(res, true); + fillSettings(); + toast('配置已导入', 'ok'); + } catch (err) { + toast(`导入失败:${err.message}`, 'err'); + } finally { + e.target.value = ''; + } + }); + + // 弹窗关闭(关闭按钮 / 取消按钮 / Esc) + // 点击遮罩一律不关闭:弹窗里都有表单,误点外面容易把填了一半的内容丢掉,所以只给个轻提示 + document.querySelectorAll('.modal').forEach((modal) => { + modal.addEventListener('click', (e) => { + if (e.target !== modal) return; + toast('点「取消」或右上角 ✕ 才会关闭窗口', ''); + }); + }); + document.querySelectorAll('[data-close]').forEach((btn) => { + btn.addEventListener('click', () => closeModal(btn.dataset.close)); + }); + document.addEventListener('keydown', (e) => { + if (e.key === 'Escape') { + document.querySelectorAll('.modal:not([hidden])').forEach((m) => closeModal(m.id)); + } + }); +} + +const TABS = ['market', 'rules', 'channels', 'alerts']; + +/** 启动 */ +async function boot() { + bindEvents(); + await refreshState(true); + const hashTab = (location.hash || '').replace('#', ''); + if (TABS.includes(hashTab)) activateTab(hashTab); + window.addEventListener('hashchange', () => { + const h = (location.hash || '').replace('#', ''); + if (TABS.includes(h)) activateTab(h); + }); + startPolling(); +} + +boot(); diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..c1a65b9 --- /dev/null +++ b/public/index.html @@ -0,0 +1,377 @@ + + + + + + 金价提醒 · Gold Price Watcher + + + +
+
+ +
+

金价提醒

+

Gold Price Watcher · 本地监控

+
+
+
+ 加载中… + + --:--:-- + + +
+
+ + + +
+ +
+
+
+

监控品种

+

每个品种可以单独设置刷新频率,价格变动后会按规则触发提醒。

+
+ +
+
+ +
+ + +
+
+
+

提醒规则

+

支持价格阈值、涨跌幅(可指定统计区间,如「近 10 分钟涨 0.5%」)、两个品种之间的价差、定时提醒四类规则;价格类规则还能限定生效时段并按冷却时间防轰炸,定时提醒按时刻去重。

+
+ +
+
+ +
+ + +
+
+
+

通知设置

+

桌面通知走 Windows 原生 Toast;邮件走 SMTP;WebHook 支持内置 JSON 与钉钉机器人两种格式。配置只保存在本机。

+
+
+ +
+
+
+

Windows 桌面通知

+ +
+

在右下角弹出系统通知,需要 Windows 10/11,且系统的「通知」未关闭。

+
+ + +
+
+ +
+
+

全局默认渠道

+
+

规则没有单独指定渠道时,用这里的默认设置。

+
+ + + +
+
+ +
+
+ + + +
+
+
+ +
+
+

邮箱提醒(SMTP)

+ +
+

+ 常见填写:QQ 邮箱 smtp.qq.com + 465 + 授权码;163 邮箱 smtp.163.com + 465 + 授权码; + 企业邮箱按服务商文档填写。密码处请填「授权码」而不是登录密码。 +

+
+ + + + + + + + + +
+
+ + +
+
+ +
+
+

WebHook 推送

+ +
+

+ 触发提醒时向该地址 POST 一条消息。两种格式:内置 JSON 是本工具固定的字段结构,方便自建服务或自动化脚本消费; + 钉钉机器人 直接填群机器人的 Webhook 地址即可,支持「加签」安全设置。 +

+
+ + + + + + +
+

+
+ + +
+
+ +
+

服务与安全

+
+ + + +
+
+ +
+

+
+ + + +
+
+ +
+ + +
+
+ + +
+
+
+

提醒记录

+

最近 200 条触发记录,同时写入 data/alerts.jsonl 便于追溯。

+
+ +
+
+ +
+
+ + + + + + + +
+ + + + + diff --git a/public/styles.css b/public/styles.css new file mode 100644 index 0000000..4a37cf7 --- /dev/null +++ b/public/styles.css @@ -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; } +} diff --git a/src/config-store.js b/src/config-store.js new file mode 100644 index 0000000..982da4a --- /dev/null +++ b/src/config-store.js @@ -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} 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, +}; diff --git a/src/index.js b/src/index.js new file mode 100644 index 0000000..701ad10 --- /dev/null +++ b/src/index.js @@ -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(); diff --git a/src/monitor.js b/src/monitor.js new file mode 100644 index 0000000..b24d73f --- /dev/null +++ b/src/monitor.js @@ -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} 品种定时器 */ + this.timers = new Map(); + /** @type {Map} 品种行情状态 */ + this.quotes = new Map(); + /** @type {Map} 规则触发状态 */ + 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} 更新后的行情状态 + */ + 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} 最新价:${fmtPrice(price, inst.digits)} ${inst.unit}`, + `触发条件:价格${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} 最新价:${fmtPrice(price, inst.digits)} ${inst.unit}`, + 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}:${fmtPrice(left.price, leftInst.digits)} ${leftInst.unit}`, + `${rightInst.name}:${fmtPrice(right.price, rightInst.digits)} ${rightInst.unit}`, + `价差:${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} 最新价:${fmtPrice(state.price, inst.digits)} ${inst.unit}` + : `${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 }; diff --git a/src/notify/desktop.js b/src/notify/desktop.js new file mode 100644 index 0000000..852c3a1 --- /dev/null +++ b/src/notify/desktop.js @@ -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, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + +/** + * 解码子进程输出(优先按 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) => `${escapeXml(line)}`).join(''); + return `` + + `${escapeXml(title)}${body}` + + ``; +} + +/** + * 弹出一条桌面通知(同步等待,最多 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 }; diff --git a/src/notify/email.js b/src/notify/email.js new file mode 100644 index 0000000..274fd35 --- /dev/null +++ b/src/notify/email.js @@ -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, footNote?: string}} data + * @returns {string} + */ +function renderHtml(data) { + const rows = (data.snapshot || []).map((item) => ` + + ${item.name} + ${fmtPrice(item.price, item.digits ?? 2)} ${item.unit || ''} + ${fmtPercent(item.changePercent)} + `).join(''); + + return ` +
+
+
GOLD PRICE WATCHER
+
${data.title}
+ ${data.subtitle ? `
${data.subtitle}
` : ''} +
+
+ ${(data.lines || []).map((line) => `

${line}

`).join('')} + ${rows ? `
+
当前行情快照
+ ${rows}
+
` : ''} +
+
+ ${data.footNote || '此邮件由本地「金价提醒」工具自动发送。如需调整规则,请打开配置页修改。'} +
+
+`; +} + +module.exports = { send, selfTest, validate, renderHtml, friendlyError }; diff --git a/src/notify/index.js b/src/notify/index.js new file mode 100644 index 0000000..0457a81 --- /dev/null +++ b/src/notify/index.js @@ -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>} + */ +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 }; diff --git a/src/notify/webhook.js b/src/notify/webhook.js new file mode 100644 index 0000000..e53e79f --- /dev/null +++ b/src/notify/webhook.js @@ -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 }; diff --git a/src/presets.js b/src/presets.js new file mode 100644 index 0000000..671fc82 --- /dev/null +++ b/src/presets.js @@ -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 }; diff --git a/src/server.js b/src/server.js new file mode 100644 index 0000000..43ec831 --- /dev/null +++ b/src/server.js @@ -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 }; diff --git a/src/sources/http-json.js b/src/sources/http-json.js new file mode 100644 index 0000000..b44204c --- /dev/null +++ b/src/sources/http-json.js @@ -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} + */ +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 }; diff --git a/src/sources/index.js b/src/sources/index.js new file mode 100644 index 0000000..3d1092d --- /dev/null +++ b/src/sources/index.js @@ -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} 标准化行情 + */ +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 }; diff --git a/src/sources/manual.js b/src/sources/manual.js new file mode 100644 index 0000000..dc942bc --- /dev/null +++ b/src/sources/manual.js @@ -0,0 +1,38 @@ +/** + * 手动价格数据源。 + * 适用场景:某个品种(例如某些银行积存金、线下金店报价)没有公开接口, + * 由用户自己在网页里录入价格,或让别的脚本调用 POST /api/instruments/:id/manual 推送。 + */ + +const { toNum, round } = require('../util'); + +/** + * 数据源统一入口 + * @param {object} instrument 监控项 + * @param {{getManualPrice: Function}} ctx 运行时上下文 + * @returns {Promise} + */ +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 }; diff --git a/src/sources/rijinjia.js b/src/sources/rijinjia.js new file mode 100644 index 0000000..0935ccf --- /dev/null +++ b/src/sources/rijinjia.js @@ -0,0 +1,133 @@ +/** + * 银行积存金数据源(rijiinjia 公开行情页)。 + * + * 银行积存金(含浙商银行「财富金积存」)没有公开的官方行情接口, + * 这里抓取公开行情页上已经渲染好的价格单元格,例如: + * 781.70 元/克 + * -7.03 + * -0.89% + * + * 特点:一次请求即可拿到所有银行的报价,因此做 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>} 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} + */ +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 }; diff --git a/src/sources/sina.js b/src/sources/sina.js new file mode 100644 index 0000000..3702b79 --- /dev/null +++ b/src/sources/sina.js @@ -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} */ +const pendingCodes = new Map(); +let flushTimer = null; +let flushing = false; + +/** + * 请求单个代码的行情(内部会被自动合并成批量请求) + * @param {string} code 新浪行情代码,如 SGE_AUTD + * @returns {Promise} 标准化行情对象 + */ +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} + */ +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 + * @param {string} text + * @returns {Map} + */ +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} + */ +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 }; diff --git a/src/util.js b/src/util.js new file mode 100644 index 0000000..2bece6f --- /dev/null +++ b/src/util.js @@ -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, +}; diff --git a/启动.bat b/启动.bat new file mode 100644 index 0000000..11faf3e --- /dev/null +++ b/启动.bat @@ -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 diff --git a/静默启动.vbs b/静默启动.vbs new file mode 100644 index 0000000..4291b63 --- /dev/null +++ b/静默启动.vbs @@ -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