Spaces:
Sleeping
Sleeping
Surf Studio commited on
Commit ·
36514c5
1
Parent(s): 5936c9d
Telegram:每分钟核对所有群最新消息,补读并检测实时通道是否失效;旧数据 Telegram ID 修正
Browse files- lib/legacy.js +5 -1
- lib/scheduler.js +4 -1
- lib/tg/index.js +96 -0
- routes/api.js +3 -0
lib/legacy.js
CHANGED
|
@@ -41,7 +41,11 @@ const parseJson = (value, fallback) => {
|
|
| 41 |
function postId(row) {
|
| 42 |
const id = String(row.tweet_id || '')
|
| 43 |
const tg = /^tg_(.+)_(\d+)$/.exec(id)
|
| 44 |
-
if (tg)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
if (/^\d+$/.test(id)) return { id: `x:${id}`, source: 'x', chat: null }
|
| 46 |
return { id: `manual:${id}`, source: 'manual', chat: null }
|
| 47 |
}
|
|
|
|
| 41 |
function postId(row) {
|
| 42 |
const id = String(row.tweet_id || '')
|
| 43 |
const tg = /^tg_(.+)_(\d+)$/.exec(id)
|
| 44 |
+
if (tg) {
|
| 45 |
+
// Old rows from username-only channels were saved as tg_undefined_<n>.
|
| 46 |
+
const chat = tg[1] !== 'undefined' ? tg[1] : /t\.me\/(?:s\/)?([A-Za-z]\w{3,})\//.exec(row.tweet_url || '')?.[1] || 'unknown'
|
| 47 |
+
return { id: `tg:${chat}:${tg[2]}`, source: 'telegram', chat }
|
| 48 |
+
}
|
| 49 |
if (/^\d+$/.test(id)) return { id: `x:${id}`, source: 'x', chat: null }
|
| 50 |
return { id: `manual:${id}`, source: 'manual', chat: null }
|
| 51 |
}
|
lib/scheduler.js
CHANGED
|
@@ -46,6 +46,7 @@ function start() {
|
|
| 46 |
every('x-search', 60000, () => xscan.searchTick(), 12000)
|
| 47 |
every('x-profiles', 180000, () => xscan.profileTick(), 40000)
|
| 48 |
every('tg-watchdog', 60000, () => tg.watchdog(), 60000)
|
|
|
|
| 49 |
every('tg-catchup', 120000, () => tg.catchup(), 100000)
|
| 50 |
every('tg-global', 180000, () => tg.globalSearch(), 130000)
|
| 51 |
every('keepalive', 20 * 60000, keepAlive, 60000)
|
|
@@ -62,10 +63,11 @@ function scanNow() {
|
|
| 62 |
scanning = (async () => {
|
| 63 |
const started = Date.now()
|
| 64 |
const before = { posts: pipeline.stats.newPosts, codes: pipeline.stats.newCodes }
|
| 65 |
-
const [xs, xp, tc, tgl] = await Promise.all([
|
| 66 |
xscan.searchTick({ all: true }).catch((err) => ({ error: err.message })),
|
| 67 |
xscan.profileTick({ count: 8 }).catch((err) => ({ error: err.message })),
|
| 68 |
tg.catchup().catch((err) => ({ error: err.message })),
|
|
|
|
| 69 |
tg.globalSearch().catch((err) => ({ error: err.message })),
|
| 70 |
])
|
| 71 |
const inv = await invites.checkDue(80).catch((err) => ({ error: err.message }))
|
|
@@ -78,6 +80,7 @@ function scanNow() {
|
|
| 78 |
x: xs,
|
| 79 |
profiles: xp,
|
| 80 |
telegram: tc,
|
|
|
|
| 81 |
telegramSearch: tgl,
|
| 82 |
invites: inv,
|
| 83 |
pushed: push.pushed || [],
|
|
|
|
| 46 |
every('x-search', 60000, () => xscan.searchTick(), 12000)
|
| 47 |
every('x-profiles', 180000, () => xscan.profileTick(), 40000)
|
| 48 |
every('tg-watchdog', 60000, () => tg.watchdog(), 60000)
|
| 49 |
+
every('tg-poll', 60000, () => tg.pollDialogs(), 95000)
|
| 50 |
every('tg-catchup', 120000, () => tg.catchup(), 100000)
|
| 51 |
every('tg-global', 180000, () => tg.globalSearch(), 130000)
|
| 52 |
every('keepalive', 20 * 60000, keepAlive, 60000)
|
|
|
|
| 63 |
scanning = (async () => {
|
| 64 |
const started = Date.now()
|
| 65 |
const before = { posts: pipeline.stats.newPosts, codes: pipeline.stats.newCodes }
|
| 66 |
+
const [xs, xp, tc, tp, tgl] = await Promise.all([
|
| 67 |
xscan.searchTick({ all: true }).catch((err) => ({ error: err.message })),
|
| 68 |
xscan.profileTick({ count: 8 }).catch((err) => ({ error: err.message })),
|
| 69 |
tg.catchup().catch((err) => ({ error: err.message })),
|
| 70 |
+
tg.pollDialogs().catch((err) => ({ error: err.message })),
|
| 71 |
tg.globalSearch().catch((err) => ({ error: err.message })),
|
| 72 |
])
|
| 73 |
const inv = await invites.checkDue(80).catch((err) => ({ error: err.message }))
|
|
|
|
| 80 |
x: xs,
|
| 81 |
profiles: xp,
|
| 82 |
telegram: tc,
|
| 83 |
+
telegramPoll: tp,
|
| 84 |
telegramSearch: tgl,
|
| 85 |
invites: inv,
|
| 86 |
pushed: push.pushed || [],
|
lib/tg/index.js
CHANGED
|
@@ -41,6 +41,10 @@ const state = {
|
|
| 41 |
globalHits: 0,
|
| 42 |
floodUntil: 0,
|
| 43 |
connectedAt: null,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
}
|
| 45 |
|
| 46 |
let client = null
|
|
@@ -238,6 +242,7 @@ async function onEvent(event) {
|
|
| 238 |
state.lastEventAt = log.now()
|
| 239 |
const id = peerId(message.peerId)
|
| 240 |
if (!id) return
|
|
|
|
| 241 |
let info = chats.get(id)
|
| 242 |
if (!info) {
|
| 243 |
// Quick text check first so we only look up chats that matter.
|
|
@@ -343,6 +348,92 @@ async function watchdog() {
|
|
| 343 |
}
|
| 344 |
}
|
| 345 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 346 |
/* -------------------------------------------------------------- catch-up -- */
|
| 347 |
|
| 348 |
function ready() {
|
|
@@ -633,6 +724,10 @@ function status() {
|
|
| 633 |
lastKeptAt: state.lastKeptAt,
|
| 634 |
lastCatchup: state.lastCatchup,
|
| 635 |
lastGlobal: state.lastGlobal,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 636 |
globalHits: state.globalHits,
|
| 637 |
floodUntil: state.floodUntil > Date.now() ? Math.floor(state.floodUntil / 1000) : null,
|
| 638 |
connectedAt: state.connectedAt,
|
|
@@ -652,6 +747,7 @@ module.exports = {
|
|
| 652 |
stop,
|
| 653 |
watchdog,
|
| 654 |
catchup,
|
|
|
|
| 655 |
globalSearch,
|
| 656 |
startLogin,
|
| 657 |
submitCode,
|
|
|
|
| 41 |
globalHits: 0,
|
| 42 |
floodUntil: 0,
|
| 43 |
connectedAt: null,
|
| 44 |
+
lastPoll: null,
|
| 45 |
+
polled: 0,
|
| 46 |
+
missedByRealtime: 0,
|
| 47 |
+
realtimeResets: 0,
|
| 48 |
}
|
| 49 |
|
| 50 |
let client = null
|
|
|
|
| 242 |
state.lastEventAt = log.now()
|
| 243 |
const id = peerId(message.peerId)
|
| 244 |
if (!id) return
|
| 245 |
+
markSeen(id, message.id)
|
| 246 |
let info = chats.get(id)
|
| 247 |
if (!info) {
|
| 248 |
// Quick text check first so we only look up chats that matter.
|
|
|
|
| 348 |
}
|
| 349 |
}
|
| 350 |
|
| 351 |
+
|
| 352 |
+
/* ---------------------------------------------------------- dialog poll -- */
|
| 353 |
+
|
| 354 |
+
/**
|
| 355 |
+
* Safety net for realtime: Telegram's update stream can go quiet without any
|
| 356 |
+
* error. Every minute the dialog list (one request) tells us the newest message
|
| 357 |
+
* id in every chat; anything newer than last time is read directly. If those
|
| 358 |
+
* messages never arrived as realtime events, the update stream is restarted.
|
| 359 |
+
*/
|
| 360 |
+
const tops = new Map()
|
| 361 |
+
const seenEvents = new Set()
|
| 362 |
+
let pollBaselined = false
|
| 363 |
+
let lastReset = 0
|
| 364 |
+
let polling = null
|
| 365 |
+
|
| 366 |
+
function markSeen(chatId, msgId) {
|
| 367 |
+
seenEvents.add(`${chatId}:${msgId}`)
|
| 368 |
+
if (seenEvents.size > 5000) {
|
| 369 |
+
const first = seenEvents.values().next().value
|
| 370 |
+
seenEvents.delete(first)
|
| 371 |
+
}
|
| 372 |
+
}
|
| 373 |
+
|
| 374 |
+
function pollDialogs() {
|
| 375 |
+
if (!polling) polling = pollNow().finally(() => (polling = null))
|
| 376 |
+
return polling
|
| 377 |
+
}
|
| 378 |
+
|
| 379 |
+
async function pollNow() {
|
| 380 |
+
if (!ready()) return { skipped: true }
|
| 381 |
+
const dialogs = await client.getDialogs({ limit: 300 })
|
| 382 |
+
let changed = 0
|
| 383 |
+
let read = 0
|
| 384 |
+
let fresh = 0
|
| 385 |
+
let missed = 0
|
| 386 |
+
for (const dialog of dialogs) {
|
| 387 |
+
if (!dialog.entity || !ready()) continue
|
| 388 |
+
const info = remember(dialog.entity)
|
| 389 |
+
if (!info) continue
|
| 390 |
+
const top = Number(dialog.message?.id || 0)
|
| 391 |
+
const prev = tops.get(info.id)
|
| 392 |
+
tops.set(info.id, top)
|
| 393 |
+
if (!pollBaselined || prev === undefined || top <= prev) continue
|
| 394 |
+
changed += 1
|
| 395 |
+
if (info.type === 'user') {
|
| 396 |
+
// Private chats: only count them to judge whether realtime is alive.
|
| 397 |
+
if (!seenEvents.has(`${info.id}:${top}`)) missed += 1
|
| 398 |
+
continue
|
| 399 |
+
}
|
| 400 |
+
try {
|
| 401 |
+
const messages = await client.getMessages(dialog.entity, { minId: prev, limit: Math.min(100, top - prev) })
|
| 402 |
+
for (const message of [...messages].reverse()) {
|
| 403 |
+
if (message?.className !== 'Message') continue
|
| 404 |
+
read += 1
|
| 405 |
+
if (!seenEvents.has(`${info.id}:${message.id}`)) missed += 1
|
| 406 |
+
markSeen(info.id, message.id)
|
| 407 |
+
const result = await handleMessage(message, info, { source: 'poll' })
|
| 408 |
+
if (result?.isNew) fresh += 1
|
| 409 |
+
}
|
| 410 |
+
} catch (err) {
|
| 411 |
+
if (handleFatal(err)) break
|
| 412 |
+
}
|
| 413 |
+
}
|
| 414 |
+
pollBaselined = true
|
| 415 |
+
state.lastPoll = log.now()
|
| 416 |
+
state.polled += read
|
| 417 |
+
state.missedByRealtime += missed
|
| 418 |
+
if (fresh) log.info('telegram', `轮询补到 ${fresh} 条相关消息`)
|
| 419 |
+
// Realtime looks dead: several messages arrived that no event reported.
|
| 420 |
+
if (missed >= 3 && Date.now() - lastReset > 15 * 60000) {
|
| 421 |
+
lastReset = Date.now()
|
| 422 |
+
state.realtimeResets += 1
|
| 423 |
+
log.warn('telegram', `实时推送漏了 ${missed} 条消息,重启接收`)
|
| 424 |
+
restartUpdates().catch(() => {})
|
| 425 |
+
}
|
| 426 |
+
log.ok('tg-poll', { dialogs: dialogs.length, changed, read, fresh, missed })
|
| 427 |
+
return { dialogs: dialogs.length, changed, read, fresh, missed }
|
| 428 |
+
}
|
| 429 |
+
|
| 430 |
+
/** Re-subscribe to the update stream without logging out. */
|
| 431 |
+
async function restartUpdates() {
|
| 432 |
+
if (!client) return
|
| 433 |
+
await client.invoke(new Api.updates.GetState()).catch(() => {})
|
| 434 |
+
await client.invoke(new Api.account.UpdateStatus({ offline: false })).catch(() => {})
|
| 435 |
+
}
|
| 436 |
+
|
| 437 |
/* -------------------------------------------------------------- catch-up -- */
|
| 438 |
|
| 439 |
function ready() {
|
|
|
|
| 724 |
lastKeptAt: state.lastKeptAt,
|
| 725 |
lastCatchup: state.lastCatchup,
|
| 726 |
lastGlobal: state.lastGlobal,
|
| 727 |
+
lastPoll: state.lastPoll,
|
| 728 |
+
polled: state.polled,
|
| 729 |
+
missedByRealtime: state.missedByRealtime,
|
| 730 |
+
realtimeResets: state.realtimeResets,
|
| 731 |
globalHits: state.globalHits,
|
| 732 |
floodUntil: state.floodUntil > Date.now() ? Math.floor(state.floodUntil / 1000) : null,
|
| 733 |
connectedAt: state.connectedAt,
|
|
|
|
| 747 |
stop,
|
| 748 |
watchdog,
|
| 749 |
catchup,
|
| 750 |
+
pollDialogs,
|
| 751 |
globalSearch,
|
| 752 |
startLogin,
|
| 753 |
submitCode,
|
routes/api.js
CHANGED
|
@@ -72,6 +72,9 @@ router.get(
|
|
| 72 |
lastEventAt: t.lastEventAt,
|
| 73 |
lastCatchup: t.lastCatchup,
|
| 74 |
lastGlobal: t.lastGlobal,
|
|
|
|
|
|
|
|
|
|
| 75 |
floodUntil: t.floodUntil,
|
| 76 |
tracked: db.get('SELECT count(*) AS n FROM tg_chats').n,
|
| 77 |
},
|
|
|
|
| 72 |
lastEventAt: t.lastEventAt,
|
| 73 |
lastCatchup: t.lastCatchup,
|
| 74 |
lastGlobal: t.lastGlobal,
|
| 75 |
+
lastPoll: t.lastPoll,
|
| 76 |
+
polled: t.polled,
|
| 77 |
+
missedByRealtime: t.missedByRealtime,
|
| 78 |
floodUntil: t.floodUntil,
|
| 79 |
tracked: db.get('SELECT count(*) AS n FROM tg_chats').n,
|
| 80 |
},
|