cut-maintainer commited on
Commit
944b7dd
·
1 Parent(s): 7a1a045

Telegram 实时监听;任务排队不再互相吞掉;按码去重推送 + 推送后立即备份;补读不漏消息;名额检查跳过过期码;备份仅在变化时上传

Browse files
Files changed (11) hide show
  1. README.md +9 -6
  2. cron.json +8 -8
  3. frontend/src/App.tsx +2 -1
  4. lib/localdb.js +89 -7
  5. lib/mystery.js +242 -109
  6. lib/notify.js +54 -23
  7. lib/realtime.js +54 -0
  8. lib/telegram.js +6 -5
  9. lib/telegramUser.js +126 -8
  10. routes/tracker.js +12 -1
  11. server.js +30 -0
README.md CHANGED
@@ -39,21 +39,24 @@ pinned: false
39
 
40
  X Cookie、Telegram 登录、企业微信地址都保存在数据库里,可以在页面「数据源设置」里随时修改。
41
 
42
- ## 定时频率
43
 
44
  | 频率 | 做什么 |
45
  | --- | --- |
46
- | 每 5 分钟 | 读取 Telegram 新消息、复查赠链名额、发现有效赠链立刻推送 |
47
- | 每 15 分钟 | 刷新 X 分享者主页 + 实时搜索(3 个关键词) |
48
- | 每 6 小时 | 全量搜索网页索引 |
 
49
 
50
- Telegram 若被限流(FLOOD_WAIT)会自动暂停读取;赠链接口被限流会自动冷却 10 分钟;企业微信只在出现有效赠链时推送,且每个赠链只推一次(多个实例并发也不会重复推送)。
 
 
51
 
52
  ## 数据库(HF 自带,不依赖平台)
53
 
54
  数据存放在应用进程内的 Postgres(PGlite)里,并加密快照到私有数据集 `Ethscriptions/cut-data`:
55
 
56
- - 线上 Space 是**唯一写入方**:每 5 分钟把变化加密后提交一次快照(密钥在 Space Secret `SNAPSHOT_KEY`)。
57
  - 容器重建时自动从快照恢复(Telegram 会话、X cookie、通知记录都在里面),所以重启不会丢数据、也不用重新登录。
58
  - 工作室预览只做只读镜像:每 5 分钟拉一次快照,并给线上发一次保活请求(避免 HF 让 Space 休眠导致定时任务停摆)。
59
 
 
39
 
40
  X Cookie、Telegram 登录、企业微信地址都保存在数据库里,可以在页面「数据源设置」里随时修改。
41
 
42
+ ## 抓取与推送节奏
43
 
44
  | 频率 | 做什么 |
45
  | --- | --- |
46
+ | **实时** | Telegram 已登录账号所在的群/频道:新消息(含编辑后的消息)一到就处理,发现赠链立即查名额、立即推送(通常几秒内) |
47
+ | 每 2 分钟 | Telegram 补读(从上次读到的消息往后读,最多 400 条,不会漏掉中间的消息)+ 名额复查 + 推送 |
48
+ | 每 15 分钟(:07/:22/:37/:52) | X 分享者主页 + 实时搜索 |
49
+ | 每 6 小时(:41) | 全网索引搜索 |
50
 
51
+ - 任务排队执行:同一时刻触发的任务不会再互相"吞掉"(旧版本里 X 抓取经常被 Telegram 检查挤掉)。
52
+ - 名额检查:新码立刻查;有名额的码每 2 分钟复查;满员未过期的码 3 天内每 30 分钟复查;已过期 / 无效的码不再查。
53
+ - 推送去重:按赠链码记录在 `gift_alerts` 表(码统一转大写),同一个码在别的群/帖子里被转发也只推一次;推送后立即备份,重启不会重推。
54
 
55
  ## 数据库(HF 自带,不依赖平台)
56
 
57
  数据存放在应用进程内的 Postgres(PGlite)里,并加密快照到私有数据集 `Ethscriptions/cut-data`:
58
 
59
+ - 线上 Space 是**唯一写入方**:数据有变化时(每 5 分钟检查一次,最多 1 小时强制一次)加密提交快照;推送后、容器停止前也会立即保存(密钥在 Space Secret `SNAPSHOT_KEY`)。
60
  - 容器重建时自动从快照恢复(Telegram 会话、X cookie、通知记录都在里面),所以重启不会丢数据、也不用重新登录。
61
  - 工作室预览只做只读镜像:每 5 分钟拉一次快照,并给线上发一次保活请求(避免 HF 让 Space 休眠导致定时任务停摆)。
62
 
cron.json CHANGED
@@ -1,29 +1,29 @@
1
  [
2
  {
3
  "id": "mystery-tracker-fast",
4
- "name": "Check Telegram messages and invite seats, push alerts",
5
- "schedule": "*/5 * * * *",
6
  "handler": "cron/mystery-fast.js",
7
  "enabled": true,
8
- "timeout": 120,
9
  "studioOnly": false
10
  },
11
  {
12
  "id": "mystery-tracker-quick",
13
  "name": "Refresh X posts, Telegram channels and invite seats",
14
- "schedule": "*/15 * * * *",
15
  "handler": "cron/mystery-quick.js",
16
  "enabled": true,
17
- "timeout": 240,
18
  "studioOnly": false
19
  },
20
  {
21
  "id": "mystery-tracker-refresh",
22
  "name": "Full rescan incl. web search index",
23
- "schedule": "0 */6 * * *",
24
  "handler": "cron/mystery-refresh.js",
25
  "enabled": true,
26
- "timeout": 280,
27
  "studioOnly": false
28
  },
29
  {
@@ -37,7 +37,7 @@
37
  {
38
  "id": "db-sync",
39
  "name": "Save / reload the HF-hosted database and keep the deployed app awake",
40
- "schedule": "*/5 * * * *",
41
  "handler": "cron/db-sync.js",
42
  "enabled": true,
43
  "timeout": 120
 
1
  [
2
  {
3
  "id": "mystery-tracker-fast",
4
+ "name": "Telegram catch-up poll (realtime listener is primary), invite seats, push alerts",
5
+ "schedule": "*/2 * * * *",
6
  "handler": "cron/mystery-fast.js",
7
  "enabled": true,
8
+ "timeout": 240,
9
  "studioOnly": false
10
  },
11
  {
12
  "id": "mystery-tracker-quick",
13
  "name": "Refresh X posts, Telegram channels and invite seats",
14
+ "schedule": "7,22,37,52 * * * *",
15
  "handler": "cron/mystery-quick.js",
16
  "enabled": true,
17
+ "timeout": 300,
18
  "studioOnly": false
19
  },
20
  {
21
  "id": "mystery-tracker-refresh",
22
  "name": "Full rescan incl. web search index",
23
+ "schedule": "41 */6 * * *",
24
  "handler": "cron/mystery-refresh.js",
25
  "enabled": true,
26
+ "timeout": 600,
27
  "studioOnly": false
28
  },
29
  {
 
37
  {
38
  "id": "db-sync",
39
  "name": "Save / reload the HF-hosted database and keep the deployed app awake",
40
+ "schedule": "3-59/5 * * * *",
41
  "handler": "cron/db-sync.js",
42
  "enabled": true,
43
  "timeout": 120
frontend/src/App.tsx CHANGED
@@ -53,8 +53,9 @@ export default function App() {
53
  if (!res.ok) throw new Error(`HTTP ${res.status}`)
54
  return res.json()
55
  },
 
56
  refetchInterval: (query) =>
57
- scanningRef.current || query.state.data?.refreshing ? 4000 : false,
58
  })
59
 
60
  async function runScan(mode: 'full' | 'quick') {
 
53
  if (!res.ok) throw new Error(`HTTP ${res.status}`)
54
  return res.json()
55
  },
56
+ // Keep the list live: new links arrive in realtime on the server.
57
  refetchInterval: (query) =>
58
+ scanningRef.current || query.state.data?.refreshing ? 4000 : 30000,
59
  })
60
 
61
  async function runScan(mode: 'full' | 'quick') {
lib/localdb.js CHANGED
@@ -31,6 +31,7 @@ const COLUMNS = {
31
  'first_seen_at', 'updated_at',
32
  ],
33
  tracker_settings: ['key', 'value', 'updated_at'],
 
34
  tracker_runs: [
35
  'id', 'started_at', 'finished_at', 'queries', 'candidates', 'new_posts',
36
  'with_link', 'errors', 'mode',
@@ -39,6 +40,22 @@ const COLUMNS = {
39
  const TABLES = Object.keys(COLUMNS)
40
  const JSON_COLUMNS = new Set(['media', 'links'])
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  const DDL = `
43
  CREATE TABLE IF NOT EXISTS mystery_posts (
44
  tweet_id text PRIMARY KEY,
@@ -79,6 +96,15 @@ const DDL = `
79
  value text,
80
  updated_at timestamptz DEFAULT now()
81
  );
 
 
 
 
 
 
 
 
 
82
  CREATE TABLE IF NOT EXISTS tracker_runs (
83
  id serial PRIMARY KEY,
84
  started_at timestamptz DEFAULT now(),
@@ -104,6 +130,7 @@ async function handle() {
104
  const db = new PGlite({ dataDir: DATA_DIR, parsers: { 20: (value) => Number(value) } })
105
  await db.waitReady
106
  await db.exec(DDL)
 
107
  return db
108
  })()
109
  }
@@ -269,6 +296,11 @@ async function load(payload, { replace = true } = {}) {
269
  if (replace) await raw(`DELETE FROM ${table}`)
270
  await writeRows(table, tables[table] || [])
271
  }
 
 
 
 
 
272
  const incoming = new Set((tables.tracker_settings || []).map((row) => row.key))
273
  for (const [key, value] of Object.entries(keep)) {
274
  if (!value || incoming.has(key)) continue
@@ -281,8 +313,55 @@ async function load(payload, { replace = true } = {}) {
281
  return counts()
282
  }
283
 
284
- /** Upload the current data to the HF dataset (the durable copy). */
285
- async function snapshot({ reason = 'auto', force = false } = {}) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
286
  const payload = await dump()
287
  const json = JSON.stringify(payload)
288
  try {
@@ -292,10 +371,10 @@ async function snapshot({ reason = 'auto', force = false } = {}) {
292
  }
293
 
294
  const now = Date.now()
295
- if (!force && json === lastSnapshotHash) return { saved: false, reason: 'unchanged' }
 
 
296
  if (!force && now - lastSnapshotAt < MIN_SNAPSHOT_GAP_MS) return { saved: false, reason: 'too-soon' }
297
- lastSnapshotHash = json
298
- lastSnapshotAt = now
299
 
300
  const token = await readToken()
301
  if (!token) return { saved: false, reason: 'no-token' }
@@ -329,7 +408,10 @@ async function snapshot({ reason = 'auto', force = false } = {}) {
329
  return { saved: false, reason: `upload-failed: ${String(retryErr?.message || retryErr).slice(0, 120)}` }
330
  }
331
  }
332
- return { saved: true, bytes: body.length, posts: (payload.tables.mystery_posts || []).length, encrypted: true }
 
 
 
333
  }
334
 
335
  /** Pull the latest snapshot into the local database. */
@@ -384,7 +466,7 @@ async function restore({ replace = true } = {}) {
384
  ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`,
385
  [String(payload.saved_at || '')]
386
  ).catch(() => {})
387
- lastSnapshotHash = json
388
  lastSnapshotAt = Date.now()
389
  return { restored: true, origin, savedAt: payload.saved_at, ...result }
390
  }
 
31
  'first_seen_at', 'updated_at',
32
  ],
33
  tracker_settings: ['key', 'value', 'updated_at'],
34
+ gift_alerts: ['gift_code', 'notified_at', 'notified_by', 'tweet_id', 'seats_left'],
35
  tracker_runs: [
36
  'id', 'started_at', 'finished_at', 'queries', 'candidates', 'new_posts',
37
  'with_link', 'errors', 'mode',
 
40
  const TABLES = Object.keys(COLUMNS)
41
  const JSON_COLUMNS = new Set(['media', 'links'])
42
 
43
+ /**
44
+ * Idempotent data fixes, run after the schema exists and after every restore
45
+ * (older snapshots predate gift_alerts and carry mixed-case codes).
46
+ */
47
+ const MIGRATE = `
48
+ UPDATE mystery_posts SET gift_code = upper(gift_code)
49
+ WHERE gift_code IS NOT NULL AND gift_code <> upper(gift_code);
50
+ INSERT INTO gift_alerts (gift_code, notified_at, notified_by, tweet_id)
51
+ SELECT DISTINCT ON (gift_code) gift_code, notified_at, notified_by, tweet_id
52
+ FROM mystery_posts
53
+ WHERE gift_code IS NOT NULL AND notified_at IS NOT NULL
54
+ ORDER BY gift_code, notified_at
55
+ ON CONFLICT (gift_code) DO NOTHING;
56
+ CREATE INDEX IF NOT EXISTS mystery_posts_link_idx ON mystery_posts (has_link) WHERE has_link;
57
+ `
58
+
59
  const DDL = `
60
  CREATE TABLE IF NOT EXISTS mystery_posts (
61
  tweet_id text PRIMARY KEY,
 
96
  value text,
97
  updated_at timestamptz DEFAULT now()
98
  );
99
+ -- One row per gift code that has been pushed. Keyed by the (upper-case) code,
100
+ -- so a link that is re-shared in another chat / post is never pushed twice.
101
+ CREATE TABLE IF NOT EXISTS gift_alerts (
102
+ gift_code text PRIMARY KEY,
103
+ notified_at timestamptz DEFAULT now(),
104
+ notified_by text,
105
+ tweet_id text,
106
+ seats_left integer
107
+ );
108
  CREATE TABLE IF NOT EXISTS tracker_runs (
109
  id serial PRIMARY KEY,
110
  started_at timestamptz DEFAULT now(),
 
130
  const db = new PGlite({ dataDir: DATA_DIR, parsers: { 20: (value) => Number(value) } })
131
  await db.waitReady
132
  await db.exec(DDL)
133
+ await db.exec(MIGRATE)
134
  return db
135
  })()
136
  }
 
296
  if (replace) await raw(`DELETE FROM ${table}`)
297
  await writeRows(table, tables[table] || [])
298
  }
299
+ try {
300
+ await (await handle()).exec(MIGRATE)
301
+ } catch (err) {
302
+ console.error('[db] migrate after restore failed:', err.message)
303
+ }
304
  const incoming = new Set((tables.tracker_settings || []).map((row) => row.key))
305
  for (const [key, value] of Object.entries(keep)) {
306
  if (!value || incoming.has(key)) continue
 
313
  return counts()
314
  }
315
 
316
+ /** Settings that change on every run without carrying real data. */
317
+ const VOLATILE_SETTINGS = new Set([
318
+ 'tg_lease',
319
+ 'telegram_last_sync',
320
+ 'timeline_cursor',
321
+ 'tg_channel_cursor',
322
+ 'invite_cooldown_until',
323
+ 'db_applied_at',
324
+ ])
325
+ const VOLATILE_POST_COLUMNS = ['link_checked_at', 'invite_checked_at', 'updated_at']
326
+ /** Even with nothing new, refresh the remote copy this often. */
327
+ const MAX_SNAPSHOT_AGE_MS = 60 * 60 * 1000
328
+
329
+ /**
330
+ * A hash of the data that matters. Bookkeeping columns (last-checked times,
331
+ * cursors, the run log) change every few minutes; uploading a 2 MB commit for
332
+ * those alone is what made the old snapshot run on every single tick.
333
+ */
334
+ function fingerprint(payload) {
335
+ const tables = payload?.tables || {}
336
+ const hash = crypto.createHash('sha256')
337
+ for (const row of tables.mystery_posts || []) {
338
+ const copy = { ...row }
339
+ for (const column of VOLATILE_POST_COLUMNS) delete copy[column]
340
+ hash.update(JSON.stringify(copy))
341
+ }
342
+ for (const row of tables.tracker_settings || []) {
343
+ if (VOLATILE_SETTINGS.has(row.key)) continue
344
+ hash.update(`${row.key}=${row.value}`)
345
+ }
346
+ for (const row of tables.gift_alerts || []) hash.update(JSON.stringify(row))
347
+ return hash.digest('hex')
348
+ }
349
+
350
+ let snapshotChain = Promise.resolve()
351
+
352
+ /**
353
+ * Upload the current data to the HF dataset (the durable copy).
354
+ * Calls are serialised so a push-triggered save never races the cron one.
355
+ */
356
+ function snapshot(options = {}) {
357
+ const next = snapshotChain.then(() => snapshotNow(options))
358
+ snapshotChain = next.catch(() => {})
359
+ return next
360
+ }
361
+
362
+ async function snapshotNow({ reason = 'auto', force = false } = {}) {
363
+ // Keep the run log short — it is only used for the "last scan" indicator.
364
+ await raw(`DELETE FROM tracker_runs WHERE id < (SELECT MAX(id) - 300 FROM tracker_runs)`).catch(() => {})
365
  const payload = await dump()
366
  const json = JSON.stringify(payload)
367
  try {
 
371
  }
372
 
373
  const now = Date.now()
374
+ const print = fingerprint(payload)
375
+ const stale = now - lastSnapshotAt > MAX_SNAPSHOT_AGE_MS
376
+ if (!force && print === lastSnapshotHash && !stale) return { saved: false, reason: 'unchanged' }
377
  if (!force && now - lastSnapshotAt < MIN_SNAPSHOT_GAP_MS) return { saved: false, reason: 'too-soon' }
 
 
378
 
379
  const token = await readToken()
380
  if (!token) return { saved: false, reason: 'no-token' }
 
408
  return { saved: false, reason: `upload-failed: ${String(retryErr?.message || retryErr).slice(0, 120)}` }
409
  }
410
  }
411
+ // Only remember a save that actually reached HF, so a failed upload retries.
412
+ lastSnapshotHash = print
413
+ lastSnapshotAt = now
414
+ return { saved: true, reason, bytes: body.length, posts: (payload.tables.mystery_posts || []).length, encrypted: true }
415
  }
416
 
417
  /** Pull the latest snapshot into the local database. */
 
466
  ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`,
467
  [String(payload.saved_at || '')]
468
  ).catch(() => {})
469
+ lastSnapshotHash = fingerprint(payload)
470
  lastSnapshotAt = Date.now()
471
  return { restored: true, origin, savedAt: payload.saved_at, ...result }
472
  }
lib/mystery.js CHANGED
@@ -56,6 +56,7 @@ const MAX_RELINK_CHECKS = 12
56
  const MAX_TIMELINE_HANDLES = 14
57
  const MAX_INVITE_CHECKS = 40
58
  const LINK_CONCURRENCY = 6
 
59
 
60
  const UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120 Safari/537.36'
61
 
@@ -80,8 +81,32 @@ async function inChunks(items, size, worker) {
80
 
81
  /* ---------------------------------------------------------------- search -- */
82
 
 
 
 
 
 
 
 
83
  /** Follow a t.co redirect without loading the destination page. */
84
  async function resolveTco(url) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  try {
86
  const res = await fetch(url, {
87
  redirect: 'manual',
@@ -115,7 +140,7 @@ async function resolveLinks(text) {
115
  function detectGift(links, text) {
116
  for (const link of links || []) {
117
  const hit = GIFT_LINK_RE.exec(link.target || '')
118
- if (hit) return { matched: true, url: link.target, code: hit[1] }
119
  }
120
  for (const link of links || []) {
121
  if (SURF_BOX_RE.test(link.target || '')) {
@@ -127,7 +152,7 @@ function detectGift(links, text) {
127
  return {
128
  matched: true,
129
  url: `https://asksurf.ai/mystery-box/g/${inline[1]}`,
130
- code: inline[1],
131
  }
132
  }
133
  if (SURF_BOX_RE.test(text || '')) return { matched: true, url: null, code: null }
@@ -336,20 +361,25 @@ async function scanLiveSearch(existing, errors, limit) {
336
  ran += 1
337
  for (const tweet of tweets) {
338
  const id = String(tweet.id || '')
339
- if (!id) continue
340
  const known = existing.get(id)
341
- const row = await timelineToRow(tweet, tweet.handle || 'x', { resolveLinks: true })
 
 
342
  if (!row.created_at) continue
343
  const relevant =
344
  row.has_link ||
345
  SURF_BOX_RE.test(row.text_content) ||
346
  (BOX_TALK_RE.test(row.text_content) && row.links.length > 0)
347
- if (!relevant) continue
348
- row.source = 'search'
 
 
 
349
  row.matched_query = query
350
  if (row.has_link) withLink += 1
351
- if (!known) newPosts += 1
352
- await dbQuery(UPSERT_SQL, upsertParams(row))
353
  }
354
  } catch (err) {
355
  if (err.status === 401) {
@@ -360,7 +390,7 @@ async function scanLiveSearch(existing, errors, limit) {
360
  }
361
  break
362
  }
363
- await new Promise((resolve) => setTimeout(resolve, 500))
364
  }
365
 
366
  return { queries: ran, newPosts, withLink, skipped: false }
@@ -372,36 +402,39 @@ async function syncTimelines(existing, errors) {
372
  let withLink = 0
373
  let checked = 0
374
 
375
- for (const handle of list) {
 
376
  let tweets = []
377
  try {
378
  tweets = await fetchHandleTweets(handle)
379
  } catch (err) {
380
  errors.push(`@${handle}: ${err.message}`)
381
- continue
382
  }
383
  checked += 1
384
  for (const tweet of tweets) {
385
  const id = String(tweet.id || '')
386
- if (!id) continue
387
  const known = existing.get(id)
 
 
388
  if (known && known.source === 'search' && !known.has_link) continue
389
- const row = await timelineToRow(tweet, handle, {
390
- resolveLinks: !(known && known.has_link),
391
- })
392
  if (!row.created_at) continue
393
  const relevant =
394
  row.has_link ||
395
  SURF_BOX_RE.test(row.text_content) ||
396
  (BOX_TALK_RE.test(row.text_content) && row.links.length > 0) ||
397
  GIFT_TALK_RE.test(row.text_content)
398
- if (!relevant) continue
 
 
 
399
  if (row.has_link) withLink += 1
400
- if (!known) added += 1
401
- await dbQuery(UPSERT_SQL, upsertParams(row))
402
  }
403
- await new Promise((resolve) => setTimeout(resolve, 400))
404
- }
405
 
406
  return { added, withLink, handles: checked }
407
  }
@@ -418,92 +451,145 @@ async function fetchInvite(code) {
418
  err.rateLimited = true
419
  throw err
420
  }
 
 
421
  if (!res.ok) return null
422
  const body = await res.json()
423
  return body?.data || null
424
  }
425
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
426
  /**
427
- * Refresh seat availability for every gift code we have stored.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
428
  *
429
- * Runs every few minutes, so it stays gentle with the invite API: oldest
430
- * checks first (round robin across all codes), never re-check a code that was
431
- * checked in the last few minutes, a hard cap per run, and a cooldown that
432
- * kicks in if the API starts pushing back.
 
 
433
  */
434
  async function checkInvites() {
435
  const errors = []
436
 
437
  const cooldownUntil = Number(await getSetting('invite_cooldown_until')) || 0
438
  if (cooldownUntil > Date.now()) {
439
- return { checked: 0, usable: 0, pushed: [], notified: 0, cooldown: true }
 
440
  }
441
 
442
  const { rows } = await dbQuery(
443
- `SELECT gift_code, MAX(invite_checked_at) AS last_checked
444
  FROM mystery_posts
445
  WHERE gift_code IS NOT NULL
446
  GROUP BY gift_code
447
- HAVING MAX(invite_checked_at) IS NULL
448
- OR MAX(invite_checked_at) < now() - interval '4 minutes'
449
- ORDER BY MAX(invite_checked_at) NULLS FIRST
 
 
 
 
 
 
 
450
  LIMIT $1`,
451
  [MAX_INVITE_CHECKS]
452
  )
453
- let usable = 0
454
- let checked = 0
455
- let rateLimited = false
456
- let failures = 0
457
 
458
- await inChunks(rows.map((row) => row.gift_code), LINK_CONCURRENCY, async (code) => {
459
- let invite = null
460
- try {
461
- invite = await fetchInvite(code)
462
- } catch (err) {
463
- if (err.rateLimited) rateLimited = true
464
- else failures += 1
465
- return
466
- }
467
- if (!invite) {
468
- failures += 1
469
- return
470
- }
471
- checked += 1
472
- const seats = Number(invite.seats_left || 0)
473
- const status = String(invite.status || '').toUpperCase()
474
- if (seats > 0 && status !== 'EXPIRED') usable += 1
475
- await dbQuery(
476
- `UPDATE mystery_posts
477
- SET invite_status = $2, seats_left = $3, invite_expires_at = $4,
478
- inviter_name = $5, box_tier = $6, invite_checked_at = now()
479
- WHERE gift_code = $1`,
480
- [
481
- code,
482
- status || null,
483
- seats,
484
- Number(invite.expires_at || 0),
485
- invite.inviter_name || null,
486
- invite.box_tier || null,
487
- ]
488
- )
489
- })
490
 
491
  // Back off when the invite API pushes back, or when every check failed.
492
- if (rateLimited || (failures >= 5 && checked === 0)) {
493
- await setSetting('invite_cooldown_until', Date.now() + 10 * 60 * 1000)
494
- errors.push('赠链接口暂时限流,10 分钟后再试')
495
  }
496
 
497
  // Announce any code that just turned usable (once per code).
498
- let alerts = { pushed: [], errors: [], pending: 0 }
499
- try {
500
- alerts = await notify.notifyUsableGifts()
501
- for (const message of alerts.errors) errors.push(`推送失败 ${message}`)
502
- } catch (err) {
503
- errors.push(`推送失败: ${err.message}`)
504
- }
505
 
506
- return { checked, usable, pushed: alerts.pushed, notified: alerts.pushed.length }
 
 
 
 
 
 
507
  }
508
 
509
  /* ------------------------------------------------------------------- scan -- */
@@ -540,6 +626,7 @@ const UPSERT_SQL = `
540
  snippet = COALESCE(EXCLUDED.snippet, mystery_posts.snippet),
541
  link_checked_at = now(),
542
  updated_at = now()
 
543
  `
544
 
545
  function upsertParams(row) {
@@ -558,7 +645,7 @@ function upsertParams(row) {
558
  JSON.stringify((row.links || []).filter((link) => link.target)),
559
  row.tweet_url,
560
  row.resolved_url,
561
- row.gift_code,
562
  row.has_link,
563
  row.matched_query,
564
  row.snippet,
@@ -566,6 +653,12 @@ function upsertParams(row) {
566
  ]
567
  }
568
 
 
 
 
 
 
 
569
  async function scanSearch(existing, errors) {
570
  const candidates = await discoverCandidates(errors)
571
 
@@ -596,10 +689,7 @@ async function scanSearch(existing, errors) {
596
  const links = await resolveLinks(tweet.text)
597
  const gift = detectGift(links, text)
598
  if (gift.matched) withLink += 1
599
- newPosts += 1
600
- await dbQuery(
601
- UPSERT_SQL,
602
- upsertParams({
603
  tweet_id: tweet.tweet_id,
604
  handle: tweet.author?.handle || cand.handle,
605
  author_name: tweet.author?.name || null,
@@ -620,7 +710,7 @@ async function scanSearch(existing, errors) {
620
  snippet: cand.snippet || null,
621
  source: 'search',
622
  })
623
- )
624
  })
625
 
626
  // Re-check known posts that never showed a link (link resolution is free).
@@ -639,7 +729,7 @@ async function scanSearch(existing, errors) {
639
  SET links = $2::jsonb, resolved_url = $3, gift_code = $4, has_link = true,
640
  link_checked_at = now(), updated_at = now()
641
  WHERE tweet_id = $1`,
642
- [cand.id, JSON.stringify(links.filter((l) => l.target)), gift.url, gift.code]
643
  )
644
  } else {
645
  await dbQuery(
@@ -677,17 +767,31 @@ async function run(mode) {
677
 
678
  const existing = await readExisting()
679
 
680
- if (mode === 'full') {
681
- const search = await scanSearch(existing, errors)
682
- candidates = search.candidates
683
- newPosts += search.newPosts
684
- withLink += search.withLink
 
 
 
 
685
  }
686
 
 
 
 
 
687
  let live = { queries: 0, newPosts: 0, withLink: 0 }
688
  let timeline = { added: 0, withLink: 0, handles: 0 }
689
-
690
  if (mode !== 'fast') {
 
 
 
 
 
 
 
691
  live = await scanLiveSearch(existing, errors, mode === 'full' ? 8 : 3)
692
  newPosts += live.newPosts
693
  withLink += live.withLink
@@ -695,24 +799,21 @@ async function run(mode) {
695
  timeline = await syncTimelines(existing, errors)
696
  newPosts += timeline.added
697
  withLink += timeline.withLink
698
- }
699
 
700
- // Telegram public channels need no login and no credits — always worth a pass.
701
- let telegram = { channels: 0, scanned: 0, stored: 0, withLink: 0 }
702
- try {
703
- telegram = await telegramLib.sync({ upsert: UPSERT_SQL, upsertParams })
704
- newPosts += telegram.stored
705
- withLink += telegram.withLink
706
- for (const message of telegram.errors || []) errors.push(`telegram ${message}`)
707
- } catch (err) {
708
- if (err.status !== 400) errors.push(`telegram: ${err.message}`)
709
  }
710
-
711
- const invites = await checkInvites()
712
 
713
  await dbQuery(
714
- `INSERT INTO tracker_runs (finished_at, queries, candidates, new_posts, with_link, errors, mode)
715
- VALUES (now(), $1, $2, $3, $4, $5, $6)`,
716
  [
717
  mode === 'full' ? SEARCH_QUERIES.length : 0,
718
  candidates,
@@ -720,6 +821,7 @@ async function run(mode) {
720
  withLink,
721
  errors.length ? errors.join('; ').slice(0, 900) : null,
722
  mode,
 
723
  ]
724
  )
725
 
@@ -737,12 +839,41 @@ async function run(mode) {
737
  }
738
  }
739
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
740
  function start(mode) {
741
- if (running) return running
742
- running = run(mode).finally(() => {
743
- running = null
744
- })
745
- return running
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
746
  }
747
 
748
  /** Add a single post / gift link the user pasted from X. */
@@ -834,6 +965,8 @@ function fastRefresh() {
834
  }
835
 
836
  module.exports = {
 
 
837
  refresh,
838
  quickRefresh,
839
  fastRefresh,
 
56
  const MAX_TIMELINE_HANDLES = 14
57
  const MAX_INVITE_CHECKS = 40
58
  const LINK_CONCURRENCY = 6
59
+ const TIMELINE_CONCURRENCY = 4
60
 
61
  const UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120 Safari/537.36'
62
 
 
81
 
82
  /* ---------------------------------------------------------------- search -- */
83
 
84
+ /**
85
+ * t.co targets never change, and the same irrelevant posts show up on every
86
+ * timeline poll — remember the answers so each link is only followed once.
87
+ */
88
+ const tcoCache = new Map()
89
+ const TCO_CACHE_MAX = 5000
90
+
91
  /** Follow a t.co redirect without loading the destination page. */
92
  async function resolveTco(url) {
93
+ if (tcoCache.has(url)) return tcoCache.get(url)
94
+ const target = await resolveTcoUncached(url)
95
+ if (target) {
96
+ if (tcoCache.size >= TCO_CACHE_MAX) tcoCache.delete(tcoCache.keys().next().value)
97
+ tcoCache.set(url, target)
98
+ }
99
+ return target
100
+ }
101
+
102
+ /** Posts already looked at and found irrelevant — skipped on the next poll. */
103
+ const irrelevantSeen = new Set()
104
+ function markIrrelevant(id) {
105
+ if (irrelevantSeen.size >= 20000) irrelevantSeen.delete(irrelevantSeen.values().next().value)
106
+ irrelevantSeen.add(id)
107
+ }
108
+
109
+ async function resolveTcoUncached(url) {
110
  try {
111
  const res = await fetch(url, {
112
  redirect: 'manual',
 
140
  function detectGift(links, text) {
141
  for (const link of links || []) {
142
  const hit = GIFT_LINK_RE.exec(link.target || '')
143
+ if (hit) return { matched: true, url: link.target, code: hit[1].toUpperCase() }
144
  }
145
  for (const link of links || []) {
146
  if (SURF_BOX_RE.test(link.target || '')) {
 
152
  return {
153
  matched: true,
154
  url: `https://asksurf.ai/mystery-box/g/${inline[1]}`,
155
+ code: inline[1].toUpperCase(),
156
  }
157
  }
158
  if (SURF_BOX_RE.test(text || '')) return { matched: true, url: null, code: null }
 
361
  ran += 1
362
  for (const tweet of tweets) {
363
  const id = String(tweet.id || '')
364
+ if (!id || irrelevantSeen.has(id)) continue
365
  const known = existing.get(id)
366
+ const row = await timelineToRow(tweet, tweet.handle || 'x', {
367
+ resolveLinks: !(known && known.has_link),
368
+ })
369
  if (!row.created_at) continue
370
  const relevant =
371
  row.has_link ||
372
  SURF_BOX_RE.test(row.text_content) ||
373
  (BOX_TALK_RE.test(row.text_content) && row.links.length > 0)
374
+ if (!relevant) {
375
+ markIrrelevant(id)
376
+ continue
377
+ }
378
+ row.source = known?.source || 'search'
379
  row.matched_query = query
380
  if (row.has_link) withLink += 1
381
+ if (await upsertRow(row)) newPosts += 1
382
+ existing.set(id, { tweet_id: id, has_link: row.has_link, source: row.source })
383
  }
384
  } catch (err) {
385
  if (err.status === 401) {
 
390
  }
391
  break
392
  }
393
+ await new Promise((resolve) => setTimeout(resolve, 300))
394
  }
395
 
396
  return { queries: ran, newPosts, withLink, skipped: false }
 
402
  let withLink = 0
403
  let checked = 0
404
 
405
+ // A few profiles at a time instead of strictly one by one (was ~30 s a round).
406
+ await inChunks(list, TIMELINE_CONCURRENCY, async (handle) => {
407
  let tweets = []
408
  try {
409
  tweets = await fetchHandleTweets(handle)
410
  } catch (err) {
411
  errors.push(`@${handle}: ${err.message}`)
412
+ return
413
  }
414
  checked += 1
415
  for (const tweet of tweets) {
416
  const id = String(tweet.id || '')
417
+ if (!id || irrelevantSeen.has(id)) continue
418
  const known = existing.get(id)
419
+ // Already stored with its gift link — nothing new to learn from it.
420
+ if (known && known.has_link) continue
421
  if (known && known.source === 'search' && !known.has_link) continue
422
+ const row = await timelineToRow(tweet, handle, { resolveLinks: true })
 
 
423
  if (!row.created_at) continue
424
  const relevant =
425
  row.has_link ||
426
  SURF_BOX_RE.test(row.text_content) ||
427
  (BOX_TALK_RE.test(row.text_content) && row.links.length > 0) ||
428
  GIFT_TALK_RE.test(row.text_content)
429
+ if (!relevant) {
430
+ markIrrelevant(id)
431
+ continue
432
+ }
433
  if (row.has_link) withLink += 1
434
+ if (await upsertRow(row)) added += 1
435
+ existing.set(id, { tweet_id: id, has_link: row.has_link, source: row.source })
436
  }
437
+ })
 
438
 
439
  return { added, withLink, handles: checked }
440
  }
 
451
  err.rateLimited = true
452
  throw err
453
  }
454
+ // Unknown code (typo, placeholder in a tutorial post…) — a definite answer.
455
+ if (res.status === 404) return { status: 'INVALID', seats_left: 0 }
456
  if (!res.ok) return null
457
  const body = await res.json()
458
  return body?.data || null
459
  }
460
 
461
+ /** Check one code and store the answer on every post that carries it. */
462
+ async function checkOne(code) {
463
+ let invite = null
464
+ try {
465
+ invite = await fetchInvite(code)
466
+ } catch (err) {
467
+ return err.rateLimited ? 'rate-limited' : 'failed'
468
+ }
469
+ if (!invite) return 'failed'
470
+ const seats = Number(invite.seats_left || 0)
471
+ const status = String(invite.status || '').toUpperCase()
472
+ await dbQuery(
473
+ `UPDATE mystery_posts
474
+ SET invite_status = $2, seats_left = $3, invite_expires_at = $4,
475
+ inviter_name = $5, box_tier = $6, invite_checked_at = now()
476
+ WHERE gift_code = $1`,
477
+ [
478
+ code,
479
+ status || null,
480
+ seats,
481
+ Number(invite.expires_at || 0),
482
+ invite.inviter_name || null,
483
+ invite.box_tier || null,
484
+ ]
485
+ )
486
+ return seats > 0 && status !== 'EXPIRED' && status !== 'INVALID' ? 'usable' : 'checked'
487
+ }
488
+
489
+ async function checkCodeList(codes) {
490
+ let usable = 0
491
+ let checked = 0
492
+ let rateLimited = false
493
+ let failures = 0
494
+ await inChunks(codes, LINK_CONCURRENCY, async (code) => {
495
+ const outcome = await checkOne(code)
496
+ if (outcome === 'rate-limited') rateLimited = true
497
+ else if (outcome === 'failed') failures += 1
498
+ else {
499
+ checked += 1
500
+ if (outcome === 'usable') usable += 1
501
+ }
502
+ })
503
+ return { usable, checked, rateLimited, failures }
504
+ }
505
+
506
+ async function pushAlerts(errors) {
507
+ try {
508
+ const alerts = await notify.notifyUsableGifts()
509
+ for (const message of alerts.errors) errors.push(`推送失败 ${message}`)
510
+ return alerts
511
+ } catch (err) {
512
+ errors.push(`推送失败: ${err.message}`)
513
+ return { pushed: [], errors: [], pending: 0 }
514
+ }
515
+ }
516
+
517
  /**
518
+ * Fast path for codes that just appeared (realtime Telegram listener):
519
+ * check them right away and push, without waiting for the next cron tick.
520
+ */
521
+ async function checkCodesNow(codes) {
522
+ const list = [...new Set((codes || []).filter(Boolean).map((code) => String(code).toUpperCase()))]
523
+ const errors = []
524
+ if (list.length === 0) return { checked: 0, usable: 0, pushed: [], errors }
525
+ const cooldownUntil = Number(await getSetting('invite_cooldown_until')) || 0
526
+ let result = { usable: 0, checked: 0 }
527
+ if (cooldownUntil <= Date.now()) {
528
+ result = await checkCodeList(list)
529
+ if (result.rateLimited) {
530
+ await setSetting('invite_cooldown_until', Date.now() + 2 * 60 * 1000)
531
+ }
532
+ }
533
+ const alerts = await pushAlerts(errors)
534
+ return { checked: result.checked, usable: result.usable, pushed: alerts.pushed, errors }
535
+ }
536
+
537
+ /**
538
+ * Refresh seat availability for the gift codes that can still change.
539
  *
540
+ * - new codes (or a code that just showed up in another post) first
541
+ * - codes with seats left: every 2 minutes, so the page stays accurate
542
+ * - codes that ran out but have not expired: every 30 minutes for 3 days
543
+ * - EXPIRED / INVALID codes: never again (the old version re-checked all 27
544
+ * dead codes every 5 minutes, and a few dead ones could trip the cooldown
545
+ * that then blocked checks of genuinely new links)
546
  */
547
  async function checkInvites() {
548
  const errors = []
549
 
550
  const cooldownUntil = Number(await getSetting('invite_cooldown_until')) || 0
551
  if (cooldownUntil > Date.now()) {
552
+ const alerts = await pushAlerts(errors)
553
+ return { checked: 0, usable: 0, pushed: alerts.pushed, notified: alerts.pushed.length, cooldown: true }
554
  }
555
 
556
  const { rows } = await dbQuery(
557
+ `SELECT gift_code
558
  FROM mystery_posts
559
  WHERE gift_code IS NOT NULL
560
  GROUP BY gift_code
561
+ HAVING bool_or(invite_checked_at IS NULL)
562
+ OR (
563
+ COALESCE(MAX(invite_status), '') NOT IN ('EXPIRED', 'INVALID')
564
+ AND (
565
+ (COALESCE(MAX(seats_left), 0) > 0 AND MAX(invite_checked_at) < now() - interval '2 minutes')
566
+ OR (MAX(invite_checked_at) < now() - interval '30 minutes'
567
+ AND MAX(created_at) > extract(epoch from now()) - 3 * 86400)
568
+ )
569
+ )
570
+ ORDER BY bool_or(invite_checked_at IS NULL) DESC, MAX(invite_checked_at) NULLS FIRST
571
  LIMIT $1`,
572
  [MAX_INVITE_CHECKS]
573
  )
 
 
 
 
574
 
575
+ const result = await checkCodeList(rows.map((row) => row.gift_code))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
576
 
577
  // Back off when the invite API pushes back, or when every check failed.
578
+ if (result.rateLimited || (result.failures >= 5 && result.checked === 0)) {
579
+ await setSetting('invite_cooldown_until', Date.now() + 5 * 60 * 1000)
580
+ errors.push('赠链接口暂时限流,5 分钟后再试')
581
  }
582
 
583
  // Announce any code that just turned usable (once per code).
584
+ const alerts = await pushAlerts(errors)
 
 
 
 
 
 
585
 
586
+ return {
587
+ checked: result.checked,
588
+ usable: result.usable,
589
+ pushed: alerts.pushed,
590
+ notified: alerts.pushed.length,
591
+ errors,
592
+ }
593
  }
594
 
595
  /* ------------------------------------------------------------------- scan -- */
 
626
  snippet = COALESCE(EXCLUDED.snippet, mystery_posts.snippet),
627
  link_checked_at = now(),
628
  updated_at = now()
629
+ RETURNING (xmax = 0) AS inserted
630
  `
631
 
632
  function upsertParams(row) {
 
645
  JSON.stringify((row.links || []).filter((link) => link.target)),
646
  row.tweet_url,
647
  row.resolved_url,
648
+ row.gift_code ? String(row.gift_code).toUpperCase() : null,
649
  row.has_link,
650
  row.matched_query,
651
  row.snippet,
 
653
  ]
654
  }
655
 
656
+ /** Insert or update one post; true when it was not stored before. */
657
+ async function upsertRow(row) {
658
+ const { rows } = await dbQuery(UPSERT_SQL, upsertParams(row))
659
+ return Boolean(rows[0]?.inserted)
660
+ }
661
+
662
  async function scanSearch(existing, errors) {
663
  const candidates = await discoverCandidates(errors)
664
 
 
689
  const links = await resolveLinks(tweet.text)
690
  const gift = detectGift(links, text)
691
  if (gift.matched) withLink += 1
692
+ const inserted = await upsertRow({
 
 
 
693
  tweet_id: tweet.tweet_id,
694
  handle: tweet.author?.handle || cand.handle,
695
  author_name: tweet.author?.name || null,
 
710
  snippet: cand.snippet || null,
711
  source: 'search',
712
  })
713
+ if (inserted) newPosts += 1
714
  })
715
 
716
  // Re-check known posts that never showed a link (link resolution is free).
 
729
  SET links = $2::jsonb, resolved_url = $3, gift_code = $4, has_link = true,
730
  link_checked_at = now(), updated_at = now()
731
  WHERE tweet_id = $1`,
732
+ [cand.id, JSON.stringify(links.filter((l) => l.target)), gift.url, gift.code ? gift.code.toUpperCase() : null]
733
  )
734
  } else {
735
  await dbQuery(
 
767
 
768
  const existing = await readExisting()
769
 
770
+ // 1) Telegram first — it is where most links show up, and it is quick.
771
+ let telegram = { channels: 0, scanned: 0, stored: 0, withLink: 0 }
772
+ try {
773
+ telegram = await telegramLib.sync({ upsert: UPSERT_SQL, upsertParams })
774
+ newPosts += telegram.stored
775
+ withLink += telegram.withLink
776
+ for (const message of telegram.errors || []) errors.push(`telegram ${message}`)
777
+ } catch (err) {
778
+ if (err.status !== 400) errors.push(`telegram: ${err.message}`)
779
  }
780
 
781
+ // 2) Seats + push straight away, so a fresh link is not held up by the X scan.
782
+ let invites = await checkInvites()
783
+
784
+ // 3) X (slower: profile pages, live search, web index).
785
  let live = { queries: 0, newPosts: 0, withLink: 0 }
786
  let timeline = { added: 0, withLink: 0, handles: 0 }
 
787
  if (mode !== 'fast') {
788
+ if (mode === 'full') {
789
+ const search = await scanSearch(existing, errors)
790
+ candidates = search.candidates
791
+ newPosts += search.newPosts
792
+ withLink += search.withLink
793
+ }
794
+
795
  live = await scanLiveSearch(existing, errors, mode === 'full' ? 8 : 3)
796
  newPosts += live.newPosts
797
  withLink += live.withLink
 
799
  timeline = await syncTimelines(existing, errors)
800
  newPosts += timeline.added
801
  withLink += timeline.withLink
 
802
 
803
+ const again = await checkInvites()
804
+ invites = {
805
+ ...again,
806
+ checked: invites.checked + again.checked,
807
+ usable: Math.max(invites.usable, again.usable),
808
+ pushed: [...invites.pushed, ...again.pushed],
809
+ notified: (invites.notified || 0) + (again.notified || 0),
810
+ }
 
811
  }
812
+ for (const message of invites.errors || []) errors.push(message)
 
813
 
814
  await dbQuery(
815
+ `INSERT INTO tracker_runs (started_at, finished_at, queries, candidates, new_posts, with_link, errors, mode)
816
+ VALUES ($7, now(), $1, $2, $3, $4, $5, $6)`,
817
  [
818
  mode === 'full' ? SEARCH_QUERIES.length : 0,
819
  candidates,
 
821
  withLink,
822
  errors.length ? errors.join('; ').slice(0, 900) : null,
823
  mode,
824
+ new Date(startedAt).toISOString(),
825
  ]
826
  )
827
 
 
839
  }
840
  }
841
 
842
+ /**
843
+ * Run scheduler.
844
+ *
845
+ * The old version returned whatever run was already in progress, so when the
846
+ * 5-minute Telegram pass and the 15-minute X pass fired on the same minute the
847
+ * X pass was silently dropped (logs showed "quick scan: 0 timelines" almost
848
+ * every time, and the 6-hourly full search never ran). Now a request is only
849
+ * merged into a running pass that covers at least as much; otherwise it waits
850
+ * for it and then runs.
851
+ */
852
+ const MODE_RANK = { fast: 0, quick: 1, full: 2 }
853
+ let runningMode = null
854
+ const queued = new Map()
855
+
856
  function start(mode) {
857
+ if (!running) {
858
+ runningMode = mode
859
+ running = run(mode).finally(() => {
860
+ running = null
861
+ runningMode = null
862
+ })
863
+ return running
864
+ }
865
+ if (MODE_RANK[runningMode] >= MODE_RANK[mode]) return running
866
+ for (const [queuedMode, promise] of queued) {
867
+ if (MODE_RANK[queuedMode] >= MODE_RANK[mode]) return promise
868
+ }
869
+ const promise = running
870
+ .catch(() => {})
871
+ .then(() => {
872
+ queued.delete(mode)
873
+ return start(mode)
874
+ })
875
+ queued.set(mode, promise)
876
+ return promise
877
  }
878
 
879
  /** Add a single post / gift link the user pasted from X. */
 
965
  }
966
 
967
  module.exports = {
968
+ checkCodesNow,
969
+ upsertRow,
970
  refresh,
971
  quickRefresh,
972
  fastRefresh,
lib/notify.js CHANGED
@@ -82,43 +82,62 @@ function alertContent(post) {
82
  return clip(lines.join('\n'))
83
  }
84
 
85
- /** Codes that are usable right now and have never been announced (one row per code). */
 
 
 
 
 
 
 
86
  async function pendingAlerts() {
 
87
  const { rows } = await dbQuery(
88
- `SELECT DISTINCT ON (gift_code)
89
- tweet_id, handle, author_name, text_content, tweet_url, source, gift_code,
90
- seats_left, box_tier, invite_expires_at
91
- FROM mystery_posts
92
- WHERE gift_code IS NOT NULL
93
- AND notified_at IS NULL
94
- AND seats_left > 0
95
- AND COALESCE(invite_status, '') <> 'EXPIRED'
96
- ORDER BY gift_code, invite_checked_at DESC NULLS LAST
97
- LIMIT 5`
 
 
98
  )
99
  return rows
100
  }
101
 
102
  /**
103
- * Claim a code before pushing, so two running instances can never announce the
104
- * same gift twice. Returns true when this instance won the claim.
 
105
  */
106
  async function claim(post) {
107
  const { rows } = await dbQuery(
108
- `UPDATE mystery_posts
109
- SET notified_at = now(), notified_by = $2
110
- WHERE gift_code = $1 AND notified_at IS NULL
111
- RETURNING tweet_id`,
112
- [post.gift_code, INSTANCE]
113
  )
114
  return rows.length > 0
115
  }
116
 
 
 
117
  /**
118
  * Announce every newly usable gift code. Returns what was pushed so the caller
119
- * can surface it in the run summary.
120
  */
121
- async function notifyUsableGifts() {
 
 
 
 
 
 
122
  const pending = await pendingAlerts()
123
  const pushed = []
124
  const errors = []
@@ -129,15 +148,27 @@ async function notifyUsableGifts() {
129
  try {
130
  await send({ msgtype: 'text', text: { content: alertContent(post) } })
131
  pushed.push(post.gift_code)
 
 
 
 
 
132
  } catch (err) {
133
  errors.push(`${post.gift_code}: ${err.message}`)
134
  // Release the claim so the next round retries instead of losing the alert.
135
- await dbQuery('UPDATE mystery_posts SET notified_at = NULL WHERE gift_code = $1', [
136
- post.gift_code,
137
- ]).catch(() => {})
138
  }
139
  }
140
 
 
 
 
 
 
 
 
 
 
141
  return { pushed, errors, pending: pending.length }
142
  }
143
 
 
82
  return clip(lines.join('\n'))
83
  }
84
 
85
+ /**
86
+ * Codes that are usable right now and have never been announced.
87
+ *
88
+ * "Announced" lives in gift_alerts, keyed by the code itself — not on the post
89
+ * rows. The old per-row flag meant every re-share of an already-pushed link
90
+ * (another chat, another post) arrived with a fresh, un-notified row and was
91
+ * pushed again.
92
+ */
93
  async function pendingAlerts() {
94
+ const now = Math.floor(Date.now() / 1000)
95
  const { rows } = await dbQuery(
96
+ `SELECT DISTINCT ON (p.gift_code)
97
+ p.tweet_id, p.handle, p.author_name, p.text_content, p.tweet_url, p.source, p.gift_code,
98
+ p.seats_left, p.box_tier, p.invite_expires_at
99
+ FROM mystery_posts p
100
+ WHERE p.gift_code IS NOT NULL
101
+ AND p.seats_left > 0
102
+ AND COALESCE(p.invite_status, '') <> 'EXPIRED'
103
+ AND (COALESCE(p.invite_expires_at, 0) = 0 OR p.invite_expires_at > $1)
104
+ AND NOT EXISTS (SELECT 1 FROM gift_alerts a WHERE a.gift_code = p.gift_code)
105
+ ORDER BY p.gift_code, p.created_at ASC
106
+ LIMIT 10`,
107
+ [now]
108
  )
109
  return rows
110
  }
111
 
112
  /**
113
+ * Claim a code before pushing (primary key on gift_alerts), so overlapping
114
+ * runs — realtime listener, cron, manual refresh — can never announce the
115
+ * same gift twice. Returns true when this call won the claim.
116
  */
117
  async function claim(post) {
118
  const { rows } = await dbQuery(
119
+ `INSERT INTO gift_alerts (gift_code, notified_at, notified_by, tweet_id, seats_left)
120
+ VALUES ($1, now(), $2, $3, $4)
121
+ ON CONFLICT (gift_code) DO NOTHING
122
+ RETURNING gift_code`,
123
+ [post.gift_code, INSTANCE, post.tweet_id, post.seats_left]
124
  )
125
  return rows.length > 0
126
  }
127
 
128
+ let notifyChain = Promise.resolve()
129
+
130
  /**
131
  * Announce every newly usable gift code. Returns what was pushed so the caller
132
+ * can surface it in the run summary. Calls are serialised.
133
  */
134
+ function notifyUsableGifts() {
135
+ const next = notifyChain.then(notifyNow)
136
+ notifyChain = next.catch(() => {})
137
+ return next
138
+ }
139
+
140
+ async function notifyNow() {
141
  const pending = await pendingAlerts()
142
  const pushed = []
143
  const errors = []
 
148
  try {
149
  await send({ msgtype: 'text', text: { content: alertContent(post) } })
150
  pushed.push(post.gift_code)
151
+ await dbQuery(
152
+ `UPDATE mystery_posts SET notified_at = now(), notified_by = $2
153
+ WHERE gift_code = $1 AND notified_at IS NULL`,
154
+ [post.gift_code, INSTANCE]
155
+ ).catch(() => {})
156
  } catch (err) {
157
  errors.push(`${post.gift_code}: ${err.message}`)
158
  // Release the claim so the next round retries instead of losing the alert.
159
+ await dbQuery('DELETE FROM gift_alerts WHERE gift_code = $1', [post.gift_code]).catch(() => {})
 
 
160
  }
161
  }
162
 
163
+ // Persist the "already pushed" record right away: a restart restores from
164
+ // the snapshot, and a stale snapshot would otherwise push the same gift again.
165
+ if (pushed.length > 0 && !process.env.BASE_PATH) {
166
+ require('./localdb')
167
+ .snapshot({ reason: 'push', force: true })
168
+ .then((result) => console.log(`[db] snapshot after push → ${JSON.stringify(result)}`))
169
+ .catch((err) => console.error('[db] snapshot after push failed:', err.message))
170
+ }
171
+
172
  return { pushed, errors, pending: pending.length }
173
  }
174
 
lib/realtime.js ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Wires the realtime Telegram listener to storage, seat checks and pushes.
3
+ *
4
+ * A new gift link posted in a watched chat is stored, checked against the
5
+ * invite API and (if it still has seats) pushed to WeCom within seconds —
6
+ * the 5-minute cron used to be the only path.
7
+ */
8
+ const telegramUser = require('./telegramUser')
9
+ const mystery = require('./mystery')
10
+
11
+ let chain = Promise.resolve()
12
+ let timer = null
13
+
14
+ function handleRow(row) {
15
+ // One message at a time: keeps the invite API and the webhook calm when a
16
+ // chat suddenly gets busy, and keeps the order of pushes sensible.
17
+ chain = chain
18
+ .then(async () => {
19
+ const inserted = await mystery.upsertRow(row)
20
+ if (!row.gift_code) return
21
+ const started = Date.now()
22
+ const result = await mystery.checkCodesNow([row.gift_code])
23
+ console.log(
24
+ `[tg realtime] ${row.gift_code} in ${row.author_name || row.handle} ` +
25
+ `(${inserted ? 'new' : 'seen'}): usable=${result.usable} pushed=${result.pushed.join(',') || '-'} ` +
26
+ `in ${Date.now() - started} ms${result.errors.length ? ` errors=${result.errors.join('; ')}` : ''}`
27
+ )
28
+ })
29
+ .catch((err) => console.error('[tg realtime] failed:', err?.message || err))
30
+ return chain
31
+ }
32
+
33
+ let lastProblem = ''
34
+ async function ensure() {
35
+ try {
36
+ const state = await telegramUser.watch(handleRow)
37
+ const problem = state.watching ? '' : state.reason
38
+ if (problem && problem !== lastProblem) console.log(`[tg realtime] not listening: ${problem}`)
39
+ lastProblem = problem
40
+ } catch (err) {
41
+ const message = err?.message || String(err)
42
+ if (message !== lastProblem) console.error(`[tg realtime] ${message}`)
43
+ lastProblem = message
44
+ }
45
+ }
46
+
47
+ function start() {
48
+ if (timer || !telegramUser.readerEnabled()) return false
49
+ setTimeout(ensure, 10000)
50
+ timer = setInterval(ensure, 60 * 1000)
51
+ return true
52
+ }
53
+
54
+ module.exports = { start, handleRow }
lib/telegram.js CHANGED
@@ -58,7 +58,7 @@ function parseViews(text) {
58
  function detectGift(links, text) {
59
  for (const url of links) {
60
  const hit = GIFT_LINK_RE.exec(url)
61
- if (hit) return { matched: true, url, code: hit[1] }
62
  }
63
  for (const url of links) {
64
  if (SURF_BOX_RE.test(url)) return { matched: true, url, code: null }
@@ -67,8 +67,8 @@ function detectGift(links, text) {
67
  if (inline) {
68
  return {
69
  matched: true,
70
- url: `https://asksurf.ai/mystery-box/g/${inline[1]}`,
71
- code: inline[1],
72
  }
73
  }
74
  return { matched: false, url: null, code: null }
@@ -296,8 +296,8 @@ async function sync({ upsert, upsertParams, takeover = false }) {
296
  if (!SURF_BOX_RE.test(row.text_content) && !BOX_TALK_RE.test(row.text_content)) continue
297
  if (row.created_at < cutoff) continue
298
  if (row.has_link) withLink += 1
299
- stored += 1
300
- await dbQuery(upsert, upsertParams(row))
301
  }
302
  const title = rows.find((row) => row.author_name)?.author_name
303
  if (title && title !== item.title) item.title = title
@@ -319,6 +319,7 @@ module.exports = {
319
  remoteHint: () => telegramUser.remoteHint,
320
  inspect: (...args) => telegramUser.inspect(...args),
321
  instanceId: () => telegramUser.instanceId,
 
322
  listDialogs: (...args) => telegramUser.listDialogs(...args),
323
  searchPublicChats: (...args) => telegramUser.searchPublicChats(...args),
324
  importChannels: (...args) => telegramUser.importChannels(...args),
 
58
  function detectGift(links, text) {
59
  for (const url of links) {
60
  const hit = GIFT_LINK_RE.exec(url)
61
+ if (hit) return { matched: true, url, code: hit[1].toUpperCase() }
62
  }
63
  for (const url of links) {
64
  if (SURF_BOX_RE.test(url)) return { matched: true, url, code: null }
 
67
  if (inline) {
68
  return {
69
  matched: true,
70
+ url: `https://asksurf.ai/mystery-box/g/${inline[1].toUpperCase()}`,
71
+ code: inline[1].toUpperCase(),
72
  }
73
  }
74
  return { matched: false, url: null, code: null }
 
296
  if (!SURF_BOX_RE.test(row.text_content) && !BOX_TALK_RE.test(row.text_content)) continue
297
  if (row.created_at < cutoff) continue
298
  if (row.has_link) withLink += 1
299
+ const { rows: saved } = await dbQuery(upsert, upsertParams(row))
300
+ if (saved[0]?.inserted) stored += 1
301
  }
302
  const title = rows.find((row) => row.author_name)?.author_name
303
  if (title && title !== item.title) item.title = title
 
319
  remoteHint: () => telegramUser.remoteHint,
320
  inspect: (...args) => telegramUser.inspect(...args),
321
  instanceId: () => telegramUser.instanceId,
322
+ realtimeStatus: () => telegramUser.realtimeStatus(),
323
  listDialogs: (...args) => telegramUser.listDialogs(...args),
324
  searchPublicChats: (...args) => telegramUser.searchPublicChats(...args),
325
  importChannels: (...args) => telegramUser.importChannels(...args),
lib/telegramUser.js CHANGED
@@ -9,6 +9,8 @@
9
  const { TelegramClient, Api } = require('telegram')
10
  const { StringSession } = require('telegram/sessions')
11
  const { computeCheck } = require('telegram/Password')
 
 
12
  const { dbQuery } = require('./localdb')
13
  const { getSetting, setSetting, clearSetting, getJson } = require('./settings')
14
 
@@ -31,6 +33,16 @@ const MESSAGES_PER_CHANNEL_HOT = 60
31
  const INSTANCE_ID = `${process.env.INSTANCE_ID || process.env.HOSTNAME || 'node'}-${Math.random()
32
  .toString(36)
33
  .slice(2, 8)}`
 
 
 
 
 
 
 
 
 
 
34
  const LEASE_KEY = 'tg_lease'
35
  const LEASE_TTL_MS = 10 * 60 * 1000
36
 
@@ -70,6 +82,12 @@ function leaseError(lease) {
70
  return err
71
  }
72
  const MESSAGES_PER_CHANNEL = 50
 
 
 
 
 
 
73
 
74
  const GIFT_LINK_RE = /asksurf\.ai\/mystery-box\/g\/([A-Za-z0-9]+)/i
75
  const SURF_BOX_RE = /asksurf\.ai\/mystery-box/i
@@ -651,15 +669,15 @@ function messageToRow(message, channel) {
651
  const gift = (() => {
652
  for (const url of links) {
653
  const hit = GIFT_LINK_RE.exec(url)
654
- if (hit) return { matched: true, url, code: hit[1] }
655
  }
656
  for (const url of links) if (SURF_BOX_RE.test(url)) return { matched: true, url, code: null }
657
  const inline = GIFT_LINK_RE.exec(text)
658
  if (inline) {
659
  return {
660
  matched: true,
661
- url: `https://asksurf.ai/mystery-box/g/${inline[1]}`,
662
- code: inline[1],
663
  }
664
  }
665
  return { matched: false, url: null, code: null }
@@ -800,6 +818,9 @@ async function sync({ upsert, upsertParams, takeover = false }) {
800
  err.status = 400
801
  throw err
802
  }
 
 
 
803
 
804
  // Telegram asked us to slow down earlier — respect it before touching the API.
805
  const floodUntil = Number(await getSetting('tg_flood_until')) || 0
@@ -833,19 +854,30 @@ async function sync({ upsert, upsertParams, takeover = false }) {
833
  continue
834
  }
835
  const entity = await resolveEntity(c, target)
 
836
  const depth = Number(channel.hits || 0) > 0 ? MESSAGES_PER_CHANNEL_HOT : MESSAGES_PER_CHANNEL
837
- const messages = await c.getMessages(entity, { limit: depth })
 
 
 
 
838
  scanned += messages.length
 
839
  for (const message of messages) {
840
- if (!message || message.className !== 'Message') continue
 
 
841
  const row = messageToRow(message, channel)
842
  if (row.created_at < cutoff) continue
843
  if (!isRelevant(row, channel)) continue
844
  if (row.has_link) withLink += 1
845
- stored += 1
846
- channel.hits = Number(channel.hits || 0) + 1
847
- await dbQuery(upsert, upsertParams(row))
 
 
848
  }
 
849
  // Space the channel reads out so a long list never looks like a burst.
850
  await new Promise((resolve) => setTimeout(resolve, 400))
851
  } catch (err) {
@@ -878,6 +910,89 @@ async function sync({ upsert, upsertParams, takeover = false }) {
878
  }
879
  }
880
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
881
  // A freshly booted reader owns the lease immediately (a dead process cannot
882
  // hold it). Non-readers never claim, so the deployed app always wins.
883
  if (readerEnabled()) {
@@ -887,6 +1002,9 @@ if (readerEnabled()) {
887
  }
888
 
889
  module.exports = {
 
 
 
890
  status,
891
  setChannelFull,
892
  readerEnabled,
 
9
  const { TelegramClient, Api } = require('telegram')
10
  const { StringSession } = require('telegram/sessions')
11
  const { computeCheck } = require('telegram/Password')
12
+ const { NewMessage } = require('telegram/events')
13
+ const { EditedMessage } = require('telegram/events/EditedMessage')
14
  const { dbQuery } = require('./localdb')
15
  const { getSetting, setSetting, clearSetting, getJson } = require('./settings')
16
 
 
33
  const INSTANCE_ID = `${process.env.INSTANCE_ID || process.env.HOSTNAME || 'node'}-${Math.random()
34
  .toString(36)
35
  .slice(2, 8)}`
36
+ /**
37
+ * During a redeploy Hugging Face keeps the old container running until the new
38
+ * one answers. Two live connections on one login session is exactly what makes
39
+ * Telegram kill it (AUTH_KEY_DUPLICATED), so background reads wait a bit after
40
+ * boot; the old container disconnects on SIGTERM.
41
+ */
42
+ const BOOT_GRACE_MS = Number(process.env.TG_BOOT_GRACE_MS || 120000)
43
+ function inBootGrace() {
44
+ return process.uptime() * 1000 < BOOT_GRACE_MS
45
+ }
46
  const LEASE_KEY = 'tg_lease'
47
  const LEASE_TTL_MS = 10 * 60 * 1000
48
 
 
82
  return err
83
  }
84
  const MESSAGES_PER_CHANNEL = 50
85
+ /**
86
+ * After the first read we only ask for messages newer than the last one seen,
87
+ * up to this many — a busy group no longer loses whatever scrolled past the
88
+ * newest 50 between two polls.
89
+ */
90
+ const MAX_CATCHUP_MESSAGES = 400
91
 
92
  const GIFT_LINK_RE = /asksurf\.ai\/mystery-box\/g\/([A-Za-z0-9]+)/i
93
  const SURF_BOX_RE = /asksurf\.ai\/mystery-box/i
 
669
  const gift = (() => {
670
  for (const url of links) {
671
  const hit = GIFT_LINK_RE.exec(url)
672
+ if (hit) return { matched: true, url, code: hit[1].toUpperCase() }
673
  }
674
  for (const url of links) if (SURF_BOX_RE.test(url)) return { matched: true, url, code: null }
675
  const inline = GIFT_LINK_RE.exec(text)
676
  if (inline) {
677
  return {
678
  matched: true,
679
+ url: `https://asksurf.ai/mystery-box/g/${inline[1].toUpperCase()}`,
680
+ code: inline[1].toUpperCase(),
681
  }
682
  }
683
  return { matched: false, url: null, code: null }
 
818
  err.status = 400
819
  throw err
820
  }
821
+ if (inBootGrace() && !takeover) {
822
+ return { channels: 0, totalChannels: list.length, scanned: 0, stored: 0, withLink: 0, errors: [], skipped: 'boot-grace' }
823
+ }
824
 
825
  // Telegram asked us to slow down earlier — respect it before touching the API.
826
  const floodUntil = Number(await getSetting('tg_flood_until')) || 0
 
854
  continue
855
  }
856
  const entity = await resolveEntity(c, target)
857
+ const lastId = Number(channel.lastId || 0)
858
  const depth = Number(channel.hits || 0) > 0 ? MESSAGES_PER_CHANNEL_HOT : MESSAGES_PER_CHANNEL
859
+ // Everything since the last message we saw (not just the newest 50).
860
+ const messages =
861
+ lastId > 0
862
+ ? await c.getMessages(entity, { minId: lastId, limit: MAX_CATCHUP_MESSAGES })
863
+ : await c.getMessages(entity, { limit: depth })
864
  scanned += messages.length
865
+ let maxId = lastId
866
  for (const message of messages) {
867
+ if (!message) continue
868
+ maxId = Math.max(maxId, Number(message.id || 0))
869
+ if (message.className !== 'Message') continue
870
  const row = messageToRow(message, channel)
871
  if (row.created_at < cutoff) continue
872
  if (!isRelevant(row, channel)) continue
873
  if (row.has_link) withLink += 1
874
+ const { rows } = await dbQuery(upsert, upsertParams(row))
875
+ if (rows[0]?.inserted) {
876
+ stored += 1
877
+ channel.hits = Number(channel.hits || 0) + 1
878
+ }
879
  }
880
+ if (maxId > lastId) channel.lastId = maxId
881
  // Space the channel reads out so a long list never looks like a burst.
882
  await new Promise((resolve) => setTimeout(resolve, 400))
883
  } catch (err) {
 
910
  }
911
  }
912
 
913
+ /* --------------------------------------------------------------- realtime -- */
914
+
915
+ /**
916
+ * Realtime listener: the logged-in account already receives every new message
917
+ * of the chats it is in, so instead of waiting up to 5 minutes for the next
918
+ * poll we handle each relevant message the moment Telegram delivers it.
919
+ * The poll keeps running as a safety net (it catches up from lastId).
920
+ */
921
+ const watchedClients = new WeakSet()
922
+ const resolvedIds = new Map()
923
+ let watchTargets = new Map()
924
+ let realtimeHandler = null
925
+ let realtimeStats = { events: 0, kept: 0, lastEventAt: null, lastKeptAt: null }
926
+
927
+ function peerKey(peer) {
928
+ if (!peer) return null
929
+ if (peer.channelId !== undefined && peer.channelId !== null) return String(peer.channelId)
930
+ if (peer.chatId !== undefined && peer.chatId !== null) return String(peer.chatId)
931
+ if (peer.userId !== undefined && peer.userId !== null) return String(peer.userId)
932
+ return null
933
+ }
934
+
935
+ async function onRealtimeEvent(event) {
936
+ const message = event?.message
937
+ if (!message || message.className !== 'Message' || !realtimeHandler) return
938
+ const channel = watchTargets.get(peerKey(message.peerId))
939
+ if (!channel) return
940
+ realtimeStats.events += 1
941
+ realtimeStats.lastEventAt = new Date().toISOString()
942
+ const row = messageToRow(message, channel)
943
+ if (!isRelevant(row, channel)) return
944
+ realtimeStats.kept += 1
945
+ realtimeStats.lastKeptAt = realtimeStats.lastEventAt
946
+ await realtimeHandler(row, channel)
947
+ }
948
+
949
+ /** Attach (or re-attach after a reconnect) the listener. Safe to call often. */
950
+ async function watch(onRow) {
951
+ if (!readerEnabled()) return { watching: false, reason: 'not-reader' }
952
+ const session = await getSetting('tg_session')
953
+ if (!session) return { watching: false, reason: 'no-session' }
954
+ if (await getSetting('tg_session_bad')) return { watching: false, reason: 'session-bad' }
955
+ if (inBootGrace()) return { watching: false, reason: 'boot-grace' }
956
+ const floodUntil = Number(await getSetting('tg_flood_until')) || 0
957
+ if (floodUntil > Date.now()) return { watching: false, reason: 'flood-wait' }
958
+ realtimeHandler = onRow
959
+
960
+ const c = await client(session)
961
+ const list = await getJson('telegram_channels', [])
962
+ const targets = new Map()
963
+ for (const channel of list) {
964
+ const ref = String(channel.ref || channel.username || channel.id || '')
965
+ let id = /^\d+$/.test(String(channel.id || '')) ? String(channel.id) : resolvedIds.get(ref)
966
+ if (!id && ref) {
967
+ try {
968
+ const entity = await resolveEntity(c, ref)
969
+ id = String(entity.id)
970
+ resolvedIds.set(ref, id)
971
+ } catch {
972
+ /* the poll will report it */
973
+ }
974
+ }
975
+ if (id) targets.set(id, channel)
976
+ }
977
+ watchTargets = targets
978
+
979
+ if (!watchedClients.has(c)) {
980
+ watchedClients.add(c)
981
+ const handler = (event) =>
982
+ onRealtimeEvent(event).catch((err) => console.error('[tg realtime]', err?.message || err))
983
+ c.addEventHandler(handler, new NewMessage({}))
984
+ c.addEventHandler(handler, new EditedMessage({}))
985
+ // Make sure Telegram starts pushing updates to this connection.
986
+ await c.invoke(new Api.updates.GetState()).catch(() => {})
987
+ console.log(`[tg realtime] listening to ${targets.size} chats`)
988
+ }
989
+ return { watching: true, chats: targets.size, ...realtimeStats }
990
+ }
991
+
992
+ function realtimeStatus() {
993
+ return { chats: watchTargets.size, ...realtimeStats }
994
+ }
995
+
996
  // A freshly booted reader owns the lease immediately (a dead process cannot
997
  // hold it). Non-readers never claim, so the deployed app always wins.
998
  if (readerEnabled()) {
 
1002
  }
1003
 
1004
  module.exports = {
1005
+ releaseClient,
1006
+ watch,
1007
+ realtimeStatus,
1008
  status,
1009
  setChannelFull,
1010
  readerEnabled,
routes/tracker.js CHANGED
@@ -42,6 +42,8 @@ router.get('/db', async (_req, res) => {
42
  process.env.SNAPSHOT_KEY || settings.snapshot_key || require('node:fs').existsSync('/tmp/snapshot.key')
43
  ),
44
  role: process.env.BASE_PATH ? 'studio-readonly' : 'deployed-writer',
 
 
45
  })
46
  } catch (err) {
47
  res.status(500).json({ error: err.message })
@@ -50,8 +52,17 @@ router.get('/db', async (_req, res) => {
50
 
51
  router.get('/', async (_req, res) => {
52
  try {
 
 
53
  const { rows: posts } = await dbQuery(
54
- `SELECT ${POST_COLUMNS} FROM mystery_posts ORDER BY created_at DESC LIMIT 300`
 
 
 
 
 
 
 
55
  )
56
  const { rows: runs } = await dbQuery(
57
  'SELECT * FROM tracker_runs ORDER BY id DESC LIMIT 1'
 
42
  process.env.SNAPSHOT_KEY || settings.snapshot_key || require('node:fs').existsSync('/tmp/snapshot.key')
43
  ),
44
  role: process.env.BASE_PATH ? 'studio-readonly' : 'deployed-writer',
45
+ realtime: require('../lib/telegramUser').realtimeStatus(),
46
+ alerts: (await dbQuery('SELECT count(*)::int AS n FROM gift_alerts')).rows[0]?.n ?? null,
47
  })
48
  } catch (err) {
49
  res.status(500).json({ error: err.message })
 
52
 
53
  router.get('/', async (_req, res) => {
54
  try {
55
+ // Newest 300 posts, plus every gift-link post of the last 30 days: busy
56
+ // "全部消息" chats used to push the actual gift links off the list.
57
  const { rows: posts } = await dbQuery(
58
+ `SELECT ${POST_COLUMNS} FROM (
59
+ (SELECT * FROM mystery_posts ORDER BY created_at DESC LIMIT 300)
60
+ UNION
61
+ (SELECT * FROM mystery_posts
62
+ WHERE (gift_code IS NOT NULL OR has_link)
63
+ AND created_at > extract(epoch from now()) - 30 * 86400)
64
+ ) p
65
+ ORDER BY created_at DESC`
66
  )
67
  const { rows: runs } = await dbQuery(
68
  'SELECT * FROM tracker_runs ORDER BY id DESC LIMIT 1'
server.js CHANGED
@@ -23,8 +23,38 @@ app.use((req, res, next) => {
23
  start()
24
  .then(() => {
25
  console.log(`Serving ${publicDir} + /api on port ${port}`)
 
 
26
  })
27
  .catch((err) => {
28
  console.error('Failed to start server:', err)
29
  process.exit(1)
30
  })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  start()
24
  .then(() => {
25
  console.log(`Serving ${publicDir} + /api on port ${port}`)
26
+ // Realtime Telegram listener (only on the instance that reads Telegram).
27
+ if (require('./lib/realtime').start()) console.log('[tg realtime] enabled')
28
  })
29
  .catch((err) => {
30
  console.error('Failed to start server:', err)
31
  process.exit(1)
32
  })
33
+
34
+ // Hugging Face stops the old container on restart / redeploy: save the latest
35
+ // data first so the new one does not restore an older copy (which used to
36
+ // resend recent pushes and re-read old messages).
37
+ let stopping = false
38
+ async function saveAndExit(signal) {
39
+ if (stopping) return
40
+ stopping = true
41
+ try {
42
+ await require('./lib/telegramUser').releaseClient()
43
+ } catch {
44
+ /* not connected */
45
+ }
46
+ if (!process.env.BASE_PATH) {
47
+ try {
48
+ const result = await Promise.race([
49
+ require('./lib/localdb').snapshot({ reason: `shutdown-${signal}`, force: true }),
50
+ new Promise((resolve) => setTimeout(() => resolve({ saved: false, reason: 'timeout' }), 20000)),
51
+ ])
52
+ console.log(`[db] snapshot on ${signal} → ${JSON.stringify(result)}`)
53
+ } catch (err) {
54
+ console.error(`[db] snapshot on ${signal} failed:`, err.message)
55
+ }
56
+ }
57
+ process.exit(0)
58
+ }
59
+ process.on('SIGTERM', () => saveAndExit('SIGTERM'))
60
+ process.on('SIGINT', () => saveAndExit('SIGINT'))