cut / lib /alerts.js
Surf Studio
重写:SQLite + 独立循环 + 实时 Telegram + 一码一推 + 新页面
5936c9d
Raw History Blame Contribute Delete
6.68 kB
/**
* WeCom (企业微信) group-robot push — once per gift code, ever.
*
* The code row itself is the lock: `pushed_at` is set *before* sending in a
* single conditional UPDATE, so two triggers (realtime + timer) can never both
* send. A failed send clears it again and the code is retried (max 5 tries).
* A successful push triggers an immediate backup, so a restart cannot resend.
*/
const db = require('./db')
const log = require('./log')
const invites = require('./invites')
const SOURCE_LABELS = { telegram: 'Telegram', x: 'X', manual: '手动添加' }
const MAX_TRIES = 5
const state = { lastPush: null, lastError: null, pushed: 0, holdUntil: null }
function webhookUrl() {
return db.getSetting('wecom_webhook') || process.env.WECOM_WEBHOOK || null
}
async function send(content) {
const url = webhookUrl()
if (!url) throw new Error('还没有配置企业微信推送地址')
const res = await fetch(url, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ msgtype: 'text', text: { content } }),
signal: AbortSignal.timeout(15000),
})
const body = await res.json().catch(() => null)
if (body && body.errcode !== 0) throw new Error(`企业微信:${body.errmsg || body.errcode}`)
if (!res.ok) throw new Error(`企业微信 HTTP ${res.status}`)
}
/** WeCom rejects text over 2048 bytes. */
function clip(text, maxBytes = 1800) {
if (Buffer.byteLength(text, 'utf8') <= maxBytes) return text
let cut = text
while (Buffer.byteLength(cut, 'utf8') > maxBytes - 3) cut = cut.slice(0, -1)
return `${cut}...`
}
function countdown(expiresAt) {
const seconds = Number(expiresAt || 0) - log.now()
if (!(seconds > 0)) return null
const days = Math.floor(seconds / 86400)
const hours = Math.floor((seconds % 86400) / 3600)
const minutes = Math.floor((seconds % 3600) / 60)
return days > 0 ? `${days}天${hours}小时` : hours > 0 ? `${hours}小时${minutes}分` : `${minutes}分钟`
}
/** The earliest post that carries the code (= where it was first shared). */
function sourcePost(code) {
return db.get(
`SELECT p.* FROM post_codes pc JOIN posts p ON p.id = pc.post_id
WHERE pc.code = $code ORDER BY p.created_at ASC LIMIT 1`,
{ code }
)
}
function message(row, post) {
const lines = [
'🎁 Surf 盲盒赠链(还有名额)',
'',
`领取:https://asksurf.ai/mystery-box/g/${row.code}`,
`剩余名额:${row.seats} 份${row.tier ? ` · ${row.tier}` : ''}`,
]
const left = countdown(row.expires_at)
if (left) lines.push(`剩余时间:${left}`)
if (row.inviter) lines.push(`赠送人:${row.inviter}`)
if (post) {
const where = post.source === 'telegram' ? post.via || post.author_name : `@${post.author}`
lines.push(`来源:${SOURCE_LABELS[post.source] || post.source} · ${where || ''}`)
const excerpt = String(post.text || '').replace(/\s+/g, ' ').trim().slice(0, 90)
if (excerpt) lines.push(`原文:${excerpt}`)
if (post.url) lines.push(`原帖:${post.url}`)
}
return clip(lines.join('\n'))
}
let chain = Promise.resolve()
/** Push every usable, not-yet-pushed code. Serialised. */
function pushPending() {
const next = chain.then(pushNow)
chain = next.catch(() => {})
return next
}
async function pushNow() {
const result = { pushed: [], errors: [] }
if (!webhookUrl()) return result
if (state.holdUntil && Date.now() < state.holdUntil * 1000) return { ...result, held: true }
const now = log.now()
const rows = db.all(
`SELECT * FROM codes WHERE pushed_at IS NULL AND push_tries < $max AND seats > 0
AND checked_at IS NOT NULL AND COALESCE(status, '') NOT IN ('EXPIRED', 'INVALID')
AND (COALESCE(expires_at, 0) = 0 OR expires_at > $now)
ORDER BY first_seen ASC LIMIT 10`,
{ max: MAX_TRIES, now }
)
for (const row of rows) {
if (!invites.isUsable(row, now)) continue
// Claim first — only one caller can flip pushed_at from NULL.
const claim = db.run(
`UPDATE codes SET pushed_at = $now, push_note = 'sending' WHERE code = $code AND pushed_at IS NULL`,
{ code: row.code, now }
)
if (claim.changes !== 1) continue
try {
await send(message(row, sourcePost(row.code)))
db.run(`UPDATE codes SET push_note = 'ok', push_tries = push_tries + 1 WHERE code = $code`, { code: row.code })
result.pushed.push(row.code)
state.pushed += 1
state.lastPush = log.now()
state.lastError = null
log.info('push', `已推送 ${row.code}(${row.seats} 份)`)
} catch (err) {
db.run(
`UPDATE codes SET pushed_at = NULL, push_note = $note, push_tries = push_tries + 1 WHERE code = $code`,
{ code: row.code, note: String(err.message).slice(0, 200) }
)
state.lastError = err.message
result.errors.push(`${row.code}: ${err.message}`)
log.error('push', `${row.code} 推送失败:${err.message}`)
}
}
if (result.pushed.length) db.changed(true)
return result
}
async function sendTest() {
await send(
`✅ Surf 赠链推送已接通\n\n发现「还有名额」的赠链会立刻推到这里,每个赠链只推一次。\n时间:${new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })}`
)
}
/**
* Started from an empty database (backup lost): treat codes from old posts as
* already announced, otherwise every still-open code would be pushed again.
*/
function silenceOld(beforeTs) {
const res = db.run(
`UPDATE codes SET pushed_at = $now, push_note = 'baseline'
WHERE pushed_at IS NULL AND code IN (
SELECT pc.code FROM post_codes pc JOIN posts p ON p.id = pc.post_id
GROUP BY pc.code HAVING MIN(p.created_at) < $before)`,
{ now: log.now(), before: beforeTs }
)
return res.changes
}
/**
* Without push history (fresh start / unreadable backup) every live code would
* look "new". Hold pushes for a while, then mark codes from posts older than
* the cutoff as already handled so only genuinely new ones go out.
*/
function holdThenBaseline(ms, cutoffTs) {
state.holdUntil = Math.floor((Date.now() + ms) / 1000)
setTimeout(() => {
const n = silenceOld(cutoffTs)
state.holdUntil = null
log.info('push', `没有推送记录,已把 ${n} 个旧赠链标记为“已处理”,之后只推新的`)
pushPending().catch(() => {})
}, ms).unref?.()
}
function status() {
const url = webhookUrl()
return {
configured: Boolean(url),
webhook: url ? url.replace(/key=([^&]{4})[^&]*/, 'key=$1****') : null,
...state,
}
}
module.exports = { pushPending, sendTest, status, message, silenceOld, holdThenBaseline, webhookUrl }