File size: 5,573 Bytes
5936c9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
/**
 * 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 }