refactor(common): 通知实现搬进 common.js,所有脚本一行 require 即可用

上一版把 notify 内联在 qqmusic 脚本里,只解决了单个脚本。这次搬到仓库根的
common.js,后续任何脚本 require('../common') 就能发通知。

common.js 新增导出:
  notify(title, content, opts)   webhook + pushplus 双通道,任一成功即 ok,永不抛错
  notifyConfig(env)              读 env 并给默认值(可注入替身,方便测试)
  httpPost(url, headers, body)   通用 POST,http/https 自适应
  parseHookHeaders(raw)          一行一个 Key: Value
  buildHookBody(t, c, tpl, ct)   拼 body,JSON 不合法就重建
Env 保持原样未动(jd 与 xiequ 在用)。

顺带删掉第 1 行的 require('node-fetch') —— 它是死代码:Env 内部所有 HTTP 走的是
require('got') + require('tough-cookie'),fetch 只以 $task.fetch(...) 的形式出现在
QuantumultX 分支(宿主 API,不是 node-fetch)。留着它反而会在容器缺 node-fetch 时
让整个文件 require 抛错,连带 jd / xiequ 一起挂。

qqmusic 脚本从 125 行内联实现缩成一行 require('../common'),删掉重复的
httpPost / parseHookHeaders / buildHookBody / notify 四份副本。

测试从 qqmusic/test_notify.js 挪到仓库根 test_common_notify.js,断言从 38 加到 69:
  - parseHookHeaders 九种输入(新增重复 key 覆盖)
  - buildHookBody 五种(新增自定义模板 + urlencoded + text/plain)
  - notifyConfig 十项默认值与 trim
  - notify 八种状态(200/204/201/401/403/400/429/连不上)
  - 无配置、双通道互不牵连
  - Env 兼容性(确认 node-fetch 已移除、老接口都在)

端到端已验证:common.js 的 notify 发出的 content 与原始 desp 逐字相同(10 行完整),
title 正确,header 带 token,HTTP 204 判为成功。

README(根 + qqmusic)新增 common.js 公共库章节,列出 notify 支持的八个环境变量
与「为什么不能放 sendNotify.js」的 deps 覆盖原因。
This commit is contained in:
2026-11-07 02:10:23 +08:00
parent 6a64a7de6f
commit 23d35cd942
6 changed files with 452 additions and 300 deletions

View File

@@ -50,25 +50,19 @@ const CARD_CALLBACK = String(process.env.QM_CARD_CALLBACK || '').trim()
// 回传鉴权 token:与平台 QL_HOOK_TOKEN 同一枚(平台 hookGuard 校验它)
const CARD_TOKEN = String(process.env.QM_CARD_TOKEN || process.env.QL_HOOK_TOKEN || '').trim()
/* ---------------- 通知:自带实现,不 require 青龙 sendNotify ----------------
* 为什么不复用青龙的 sendNotify.js(2026-11-07 真机定位):
/* ---------------- 通知:复用仓库根 common.js 的 notify() ----------------
* 为什么不 require 青龙的 sendNotify.js(2026-11-07 真机定位):
* shell/update.sh 的 gen_list_repo 复制顺序是三步 ——
* ① cp -f $file_notify_js "${dir_scripts}/${uniq_path}" 面板自带的 sendNotify.js
* ② cp -f <仓库依赖文件> "${dir_scripts}/${uniq_path}/" 仓库里的 sendNotify.js(覆盖①)
* ③ cp -rf $dir_dep/* "${dir_scripts}/${uniq_path}" /ql/data/deps/*(再覆盖②)
* $dir_dep = /ql/data/deps,share.sh 初始化时往里面拷了一份面板自带的 notify.js。
* $dir_dep = /ql/data/deps,share.sh:228 初始化时往里面拷了一份面板自带的 notify.js。
* ③ 排在最后,所以仓库里的 sendNotify.js 每轮都被覆盖,改它永远不生效。
* 自己实现 = 彻底断开这条依赖链,行为完全由本文件决定。
* 支持两路:自定义 webhook(指向平台)+ pushplus 直发。两者都没配就只打日志。 */
const WEBHOOK_URL = String(process.env.WEBHOOK_URL || '').trim()
const WEBHOOK_BODY = String(process.env.WEBHOOK_BODY || '').trim()
const WEBHOOK_METHOD = String(process.env.WEBHOOK_METHOD || 'POST').trim().toUpperCase()
const WEBHOOK_CT = String(process.env.WEBHOOK_CONTENT_TYPE || 'application/json').trim()
const WEBHOOK_HEADERS = String(process.env.WEBHOOK_HEADERS || '')
const PUSH_PLUS_TOKEN = String(process.env.PUSH_PLUS_TOKEN || '').trim()
const PUSH_PLUS_TOPIC = String(process.env.PUSH_PLUS_USER || '').trim()
// pushplus 模板:txt 不转义 html、不折叠;html 会把换行变 <br>
const PUSH_PLUS_TEMPLATE = String(process.env.PUSH_PLUS_TEMPLATE || 'txt').trim()
*
* common.js 不在 deps 里(deps 只有 notify.py 和 sendNotify.js),所以把通知实现放
* 那里是安全的,且后续任何脚本都能 require('../common') 直接用。 */
const { notify } = require('../common')
function time33(s) {
let h = 5381
@@ -746,107 +740,6 @@ function parseAccounts() {
return list
}
/** 通用 HTTP 请求(http/https 自适应),零依赖。供通知与回传共用。 */
function httpPost(urlStr, headers, body, timeoutMs = 15000) {
return new Promise((resolve) => {
let u
try { u = new URL(urlStr) } catch { return resolve({ status: 0, text: `非法 URL: ${urlStr}` }) }
const lib = u.protocol === 'http:' ? require('http') : https
const payload = Buffer.from(body, 'utf8')
const req = lib.request({
host: u.hostname,
port: u.port || (u.protocol === 'http:' ? 80 : 443),
path: u.pathname + u.search,
method: 'POST',
headers: { ...headers, 'Content-Length': payload.length },
timeout: timeoutMs,
}, (res) => {
const chunks = []
res.on('data', c => chunks.push(c))
res.on('end', () => resolve({ status: res.statusCode, text: Buffer.concat(chunks).toString('utf8') }))
})
req.on('timeout', () => { req.destroy(); resolve({ status: 0, text: 'request timeout' }) })
req.on('error', e => resolve({ status: 0, text: e.message }))
req.write(payload)
req.end()
})
}
/** 解析 WEBHOOK_HEADERS:一行一个 `Key: Value`,空行忽略。
* 注意环境变量里必须是真换行;写成字面量 \n(两个字符)整段会被当成一个 header。 */
function parseHookHeaders(raw) {
const out = {}
for (const line of String(raw || '').split('\n')) {
const s = line.trim()
if (!s) continue
const i = s.indexOf(':')
if (i <= 0) continue
out[s.slice(0, i).trim()] = s.slice(i + 1).trim()
}
return out
}
/** 拼 webhook body。WEBHOOK_BODY 支持 $title / $content 占位;
* 没配 BODY 时按 Content-Type 给默认形状。 */
function buildHookBody(title, content) {
const tpl = WEBHOOK_BODY || (WEBHOOK_CT === 'application/json' ? '{"title":"$title","content":"$content"}' : 'title=$title&content=$content')
const filled = tpl.replace(/\$title/g, title).replace(/\$content/g, content)
if (WEBHOOK_CT === 'application/json') {
// 占位替换会把内容里的引号/换行带进 JSON,必须重新序列化一次才合法
try { JSON.parse(filled); return filled } catch { /* 落下面重建 */ }
return JSON.stringify({ title, content })
}
if (WEBHOOK_CT === 'application/x-www-form-urlencoded') {
return `title=${encodeURIComponent(title)}&content=${encodeURIComponent(content)}`
}
return filled
}
/** 发通知。返回 { ok, channels: [{name, ok, detail}] },永不抛错。
* 设计要点:
* - 2xx 一律算成功。平台 /api/hooks/ql 按设计回 204,判 !== 200 会误报失败。
* - 两路都试,任一路成功即 ok(不因 pushplus 挂了就吞掉 webhook 的成功)。
* - 失败只打日志,绝不让通知问题把签到本身算失败。 */
async function notify(title, content) {
const channels = []
if (WEBHOOK_URL) {
const headers = { 'Content-Type': WEBHOOK_CT, ...parseHookHeaders(WEBHOOK_HEADERS) }
const body = buildHookBody(title, content)
const r = await httpPost(WEBHOOK_URL, headers, body)
const ok = r.status >= 200 && r.status < 300
channels.push({ name: 'webhook', ok, detail: `HTTP ${r.status || 'ERR'}` })
log(ok
? `[通知] webhook 成功(HTTP ${r.status})`
: `[通知] webhook 失败:HTTP ${r.status || 'ERR'} ${r.text.slice(0, 160)}`)
} else {
channels.push({ name: 'webhook', ok: false, detail: 'WEBHOOK_URL 未设' })
}
if (PUSH_PLUS_TOKEN) {
const payload = JSON.stringify({
token: PUSH_PLUS_TOKEN,
title,
content,
template: PUSH_PLUS_TEMPLATE,
...(PUSH_PLUS_TOPIC ? { topic: PUSH_PLUS_TOPIC } : {}),
})
const r = await httpPost('https://www.pushplus.plus/send', { 'Content-Type': 'application/json' }, payload)
let j = {}
try { j = JSON.parse(r.text) } catch { /* 非 JSON */ }
const ok = j.code === 200
channels.push({ name: 'pushplus', ok, detail: ok ? `msgId ${j.data || ''}` : `code ${j.code} ${j.msg || r.text.slice(0, 80)}` })
log(ok ? `[通知] pushplus 成功` : `[通知] pushplus 失败:${j.code} ${j.msg || ''}`)
} else {
channels.push({ name: 'pushplus', ok: false, detail: 'PUSH_PLUS_TOKEN 未设' })
}
if (!WEBHOOK_URL && !PUSH_PLUS_TOKEN) {
log('[通知] 未配置任何通道(WEBHOOK_URL / PUSH_PLUS_TOKEN 都为空),本轮不发推送')
}
return { ok: channels.some(c => c.ok), channels }
}
/** 取卡结果回传平台(可选)。平台侧 /api/hooks/card 收到后按该用户的通知目标转发到微信。
* 设计要点:
* - 只回传「取卡结果」,不含 cookie/key —— 走公网也不泄露凭证。
@@ -991,4 +884,4 @@ async function main() {
if (require.main === module) {
main().catch(e => { console.error('[QQ音乐] 未捕获异常:', e); process.exitCode = 1 })
}
module.exports = { time33, zzc, QMClient, parseAccounts, pushCardResult, notify, buildHookBody, parseHookHeaders }
module.exports = { time33, zzc, QMClient, parseAccounts, pushCardResult }