/** * Seat checks against Surf's public invite endpoint (no key needed). * * Every code has its own `next_check` time: * new code → right away * has seats → every 90 s (keeps the page accurate) * full, not expired → every 15 min, for 3 days after it was first seen * EXPIRED / INVALID → never again * request failed → back off 30 s, 1 min, 2 min … up to 30 min * A 429 pauses all checks briefly instead of burning through the queue. */ const db = require('./db') const log = require('./log') const API = 'https://api.asksurf.ai/muninn/v1/mystery-box/invites/' const NEVER = 4102444800 // 2100-01-01 const FINAL = new Set(['EXPIRED', 'INVALID']) const CONCURRENCY = 4 let cooldownUntil = 0 let onUsable = () => {} function isUsable(row, now = log.now()) { if (!row) return false const status = String(row.status || '').toUpperCase() if (!row.checked_at || FINAL.has(status)) return false if (!(Number(row.seats) > 0)) return false const expires = Number(row.expires_at || 0) return expires === 0 || expires > now } async function fetchInvite(code) { const res = await fetch(API + encodeURIComponent(code), { headers: { accept: 'application/json', 'user-agent': 'Mozilla/5.0 (cut tracker)' }, signal: AbortSignal.timeout(10000), }) if (res.status === 429) { const err = new Error('名额接口限流') err.rateLimited = true throw err } if (res.status === 404) return { status: 'INVALID', seats_left: 0, expires_at: 0 } if (!res.ok) throw new Error(`名额接口 HTTP ${res.status}`) const body = await res.json() if (!body?.data) { if (/NOT_FOUND|invalid/i.test(`${body?.error_code} ${body?.message}`)) { return { status: 'INVALID', seats_left: 0, expires_at: 0 } } throw new Error('名额接口返回内容无法识别') } return body.data } function nextCheckAfter(row, now) { const status = String(row.status || '').toUpperCase() if (FINAL.has(status)) return NEVER if (isUsable(row, now)) { const expires = Number(row.expires_at || 0) return expires > 0 ? Math.min(now + 90, expires + 5) : now + 90 } if (now - Number(row.first_seen || now) > 3 * 86400) return NEVER return now + 15 * 60 } /** Check one code; returns the updated row (or null when the check failed). */ async function checkOne(code) { const now = log.now() const before = db.get('SELECT * FROM codes WHERE code = $code', { code }) if (!before) return null let data try { data = await fetchInvite(code) } catch (err) { if (err.rateLimited) { cooldownUntil = Date.now() + 60000 throw err } const fails = Number(before.fails || 0) + 1 db.run('UPDATE codes SET fails = $fails, next_check = $next WHERE code = $code', { code, fails, next: now + Math.min(30 * 2 ** (fails - 1), 1800), }) throw err } const row = { ...before, status: String(data.status || '').toUpperCase() || null, seats: Number(data.seats_left ?? 0), expires_at: Number(data.expires_at || 0), inviter: data.inviter_name || before.inviter || null, tier: data.box_tier || before.tier || null, checked_at: now, fails: 0, } row.next_check = nextCheckAfter(row, now) db.run( `UPDATE codes SET status = $status, seats = $seats, expires_at = $expires_at, inviter = $inviter, tier = $tier, checked_at = $checked_at, fails = 0, next_check = $next_check WHERE code = $code`, { code, status: row.status, seats: row.seats, expires_at: row.expires_at, inviter: row.inviter, tier: row.tier, checked_at: row.checked_at, next_check: row.next_check, } ) // Status changes are worth a backup; seat counts alone are re-checked after a restart anyway. if (before.status !== row.status) db.changed() if (isUsable(row, now) && !row.pushed_at) onUsable(code) return row } async function checkList(codes) { const out = { checked: 0, usable: 0, failed: 0, rateLimited: false } const queue = [...new Set(codes)] const worker = async () => { while (queue.length) { if (cooldownUntil > Date.now()) { out.rateLimited = true return } const code = queue.shift() try { const row = await checkOne(code) if (!row) continue out.checked += 1 if (isUsable(row)) out.usable += 1 } catch (err) { if (err.rateLimited) out.rateLimited = true else out.failed += 1 } } } await Promise.all(Array.from({ length: CONCURRENCY }, worker)) return out } /** Brand-new codes: check immediately (the realtime path). */ function checkNow(codes) { return checkList(codes.map((code) => String(code).toUpperCase())) } /** Everything whose next_check has come up (unchecked codes first). */ async function checkDue(limit = 40) { if (cooldownUntil > Date.now()) return { checked: 0, usable: 0, failed: 0, rateLimited: true } const rows = db.all( `SELECT code FROM codes WHERE next_check <= $now ORDER BY (checked_at IS NULL) DESC, next_check ASC LIMIT $limit`, { now: log.now(), limit } ) const result = await checkList(rows.map((row) => row.code)) if (result.failed && !result.checked) log.fail('invites', `${result.failed} 个码检查失败`) else log.ok('invites', { lastChecked: result.checked }) return result } function setUsableHandler(fn) { onUsable = fn } module.exports = { checkNow, checkDue, isUsable, setUsableHandler, NEVER, FINAL, nextCheckAfter }