/** * One-time import of the old PGlite snapshot (snapshot.json, tables * mystery_posts / tracker_settings / gift_alerts) into the new schema. */ const db = require('./db') const log = require('./log') const detect = require('./detect') const invites = require('./invites') /** Settings worth carrying over (credentials and preferences only). */ const KEEP_SETTINGS = [ 'tg_session', 'tg_session_bad', 'tg_api_id', 'tg_api_hash', 'x_cookies', 'x_username', 'x_query_id', 'x_bearer', 'wecom_webhook', 'admin_key', ] const toTs = (value) => { if (value === null || value === undefined || value === '') return null if (typeof value === 'number') return value > 1e12 ? Math.floor(value / 1000) : value const ms = Date.parse(value) return Number.isFinite(ms) ? Math.floor(ms / 1000) : null } const parseJson = (value, fallback) => { if (value === null || value === undefined) return fallback if (typeof value !== 'string') return value try { return JSON.parse(value) } catch { return fallback } } function postId(row) { const id = String(row.tweet_id || '') const tg = /^tg_(.+)_(\d+)$/.exec(id) if (tg) { // Old rows from username-only channels were saved as tg_undefined_. const chat = tg[1] !== 'undefined' ? tg[1] : /t\.me\/(?:s\/)?([A-Za-z]\w{3,})\//.exec(row.tweet_url || '')?.[1] || 'unknown' return { id: `tg:${chat}:${tg[2]}`, source: 'telegram', chat } } if (/^\d+$/.test(id)) return { id: `x:${id}`, source: 'x', chat: null } return { id: `manual:${id}`, source: 'manual', chat: null } } function importLegacy(payload) { const tables = payload?.tables || {} const settings = new Map((tables.tracker_settings || []).map((row) => [row.key, row.value])) const now = log.now() const out = { posts: 0, codes: 0, pushed: 0, chats: 0, settings: 0 } db.tx(() => { for (const key of KEEP_SETTINGS) { const value = settings.get(key) if (value) { db.setSetting(key, value, { quiet: true }) out.settings += 1 } } for (const chat of parseJson(settings.get('telegram_channels'), []) || []) { const username = chat.username || (/^[A-Za-z]\w{3,}$/.test(String(chat.ref || '')) ? chat.ref : null) const id = /^\d+$/.test(String(chat.id || '')) ? String(chat.id) : username if (!id) continue db.run( `INSERT OR IGNORE INTO tg_chats (id, username, title, type, full, last_id, hits, auto, added_at) VALUES ($id, $username, $title, $type, $full, $last_id, $hits, $auto, $added)`, { id, username, title: chat.title || username || id, type: chat.type || chat.kind || null, full: chat.full ? 1 : 0, last_id: Number(chat.lastId || 0), hits: Number(chat.hits || 0), auto: chat.auto ? 1 : 0, added: toTs(chat.addedAt) || now, } ) out.chats += 1 } const codeInfo = new Map() for (const row of tables.mystery_posts || []) { const { id, source, chat } = postId(row) const links = (parseJson(row.links, []) || []).map((link) => link?.target || link?.tco).filter(Boolean) if (row.resolved_url) links.push(row.resolved_url) let text = row.text_content || '' for (const link of parseJson(row.links, []) || []) { if (link?.tco && link?.target) text = text.split(link.tco).join(link.target) } const codes = detect.extractCodes(text, links) if (row.gift_code) codes.push(detect.normalizeCode(row.gift_code)) const unique = [...new Set(codes)] // Re-judge every old row with today's rules: the old tracker kept ~300 unrelated // chat messages because "surf" appeared in a group's name. const kind = unique.length ? 'gift' : detect.classify({ text, links }, { full: source === 'telegram' }).kind if (!kind) { out.dropped = (out.dropped || 0) + 1 continue } const created = Number(row.created_at) || now db.run( `INSERT OR IGNORE INTO posts (id, source, via, chat_id, author, author_name, text, url, kind, created_at, seen_at, updated_at, views, likes, reposts, replies, media, links) VALUES ($id, $source, $via, $chat, $author, $author_name, $text, $url, $kind, $created, $seen, $seen, $views, $likes, $reposts, $replies, $media, $links)`, { id, source, via: source === 'telegram' ? row.author_name || row.handle : row.matched_query || row.source || null, chat, author: row.handle || null, author_name: row.author_name || null, text, url: row.tweet_url || null, kind, created, seen: toTs(row.first_seen_at) || created, views: Number(row.views || 0), likes: Number(row.likes || 0), reposts: Number(row.reposts || 0), replies: Number(row.replies || 0), media: JSON.stringify(parseJson(row.media, []) || []), links: JSON.stringify([...new Set(links)]), } ) out.posts += 1 for (const code of unique) { db.run('INSERT OR IGNORE INTO post_codes (post_id, code) VALUES ($id, $code)', { id, code }) const info = codeInfo.get(code) || { code, firstSeen: created, firstPost: id } if (created < info.firstSeen) Object.assign(info, { firstSeen: created, firstPost: id }) // Invite fields were written to every post carrying the code; keep the newest check. const checked = toTs(row.invite_checked_at) if (row.gift_code && detect.normalizeCode(row.gift_code) === code && checked && checked >= (info.checked || 0)) { Object.assign(info, { checked, status: row.invite_status ? String(row.invite_status).toUpperCase() : null, seats: row.seats_left === null || row.seats_left === undefined ? null : Number(row.seats_left), expires: Number(row.invite_expires_at || 0), inviter: row.inviter_name || null, tier: row.box_tier || null, }) } const notified = toTs(row.notified_at) if (notified) info.pushed = Math.min(info.pushed || notified, notified) codeInfo.set(code, info) } } for (const alert of tables.gift_alerts || []) { const code = detect.normalizeCode(alert.gift_code) if (!code) continue const info = codeInfo.get(code) || { code, firstSeen: toTs(alert.notified_at) || now, firstPost: null } info.pushed = toTs(alert.notified_at) || now codeInfo.set(code, info) } for (const info of codeInfo.values()) { const row = { status: info.status || null, seats: info.seats ?? null, expires_at: info.expires || 0, first_seen: info.firstSeen, checked_at: info.checked || null, } // Final codes are never checked again; everything else gets a fresh check right away. const next = invites.FINAL.has(String(row.status || '')) ? invites.NEVER : 0 db.run( `INSERT OR REPLACE INTO codes (code, first_seen, first_post, status, seats, expires_at, inviter, tier, checked_at, next_check, fails, pushed_at, push_note, push_tries) VALUES ($code, $first_seen, $first_post, $status, $seats, $expires_at, $inviter, $tier, $checked_at, $next, 0, $pushed, $note, $tries)`, { code: info.code, first_seen: info.firstSeen, first_post: info.firstPost, status: row.status, seats: row.seats, expires_at: row.expires_at, inviter: info.inviter || null, tier: info.tier || null, checked_at: row.checked_at, next, pushed: info.pushed || null, note: info.pushed ? 'legacy' : null, tries: info.pushed ? 1 : 0, } ) out.codes += 1 if (info.pushed) out.pushed += 1 } }) log.info('backup', `已导入旧版数据:${out.posts} 条帖子、${out.codes} 个赠链(${out.pushed} 个已推送过)、${out.chats} 个 Telegram 群`) return out } module.exports = { importLegacy }