/** * Local database: one SQLite file (bun:sqlite, synchronous, in-process). * * The unit of tracking is the *gift code*, not the post: * posts — every relevant X post / Telegram message we have seen * post_codes — which codes a post carries (a post can carry several) * codes — one row per code: seats, expiry, next check time, push state * tg_chats — Telegram chats we catch up on (realtime covers all chats) * settings — credentials and small key/value state * * The file is backed up (encrypted) to a private HF dataset, see backup.js. */ const fs = require('node:fs') const path = require('node:path') const { Database } = require('bun:sqlite') const log = require('./log') const DB_PATH = process.env.DB_PATH || '/tmp/cut/data.sqlite' const SCHEMA = ` CREATE TABLE IF NOT EXISTS posts ( id TEXT PRIMARY KEY, source TEXT NOT NULL, via TEXT, chat_id TEXT, author TEXT, author_name TEXT, text TEXT, url TEXT, kind TEXT NOT NULL, created_at INTEGER NOT NULL, seen_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, views INTEGER DEFAULT 0, likes INTEGER DEFAULT 0, reposts INTEGER DEFAULT 0, replies INTEGER DEFAULT 0, media TEXT, links TEXT ); CREATE INDEX IF NOT EXISTS posts_created ON posts (created_at DESC); CREATE INDEX IF NOT EXISTS posts_kind ON posts (kind, created_at DESC); CREATE TABLE IF NOT EXISTS post_codes ( post_id TEXT NOT NULL, code TEXT NOT NULL, PRIMARY KEY (post_id, code) ); CREATE INDEX IF NOT EXISTS post_codes_code ON post_codes (code); CREATE TABLE IF NOT EXISTS codes ( code TEXT PRIMARY KEY, first_seen INTEGER NOT NULL, first_post TEXT, status TEXT, seats INTEGER, expires_at INTEGER, inviter TEXT, tier TEXT, checked_at INTEGER, next_check INTEGER NOT NULL DEFAULT 0, fails INTEGER NOT NULL DEFAULT 0, pushed_at INTEGER, push_note TEXT, push_tries INTEGER NOT NULL DEFAULT 0 ); CREATE INDEX IF NOT EXISTS codes_next ON codes (next_check); CREATE TABLE IF NOT EXISTS tg_chats ( id TEXT PRIMARY KEY, username TEXT, title TEXT, type TEXT, full INTEGER NOT NULL DEFAULT 0, last_id INTEGER NOT NULL DEFAULT 0, hits INTEGER NOT NULL DEFAULT 0, auto INTEGER NOT NULL DEFAULT 0, added_at INTEGER ); CREATE TABLE IF NOT EXISTS settings ( key TEXT PRIMARY KEY, value TEXT, updated_at INTEGER ); ` let db = null const listeners = new Set() function open(file = DB_PATH) { if (db) return db fs.mkdirSync(path.dirname(file), { recursive: true }) db = new Database(file, { create: true, strict: true }) db.exec('PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA busy_timeout = 3000;') db.exec(SCHEMA) return db } function close() { if (!db) return try { db.close() } catch { /* already closed */ } db = null } function handle() { if (!db) open() return db } const all = (sql, params = {}) => handle().query(sql).all(params) const get = (sql, params = {}) => handle().query(sql).get(params) const run = (sql, params = {}) => handle().query(sql).run(params) const tx = (fn) => handle().transaction(fn)() /** Something durable changed → the backup should run soon (urgent = within seconds). */ function changed(urgent = false) { for (const fn of listeners) fn(urgent) } function onChange(fn) { listeners.add(fn) } /* -------------------------------------------------------------- settings -- */ function getSetting(key) { return get('SELECT value FROM settings WHERE key = $key', { key })?.value ?? null } function setSetting(key, value, { quiet = false } = {}) { if (value === null || value === undefined) return clearSetting(key) run( `INSERT INTO settings (key, value, updated_at) VALUES ($key, $value, $now) ON CONFLICT (key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`, { key, value: String(value), now: log.now() } ) if (!quiet) changed() } function clearSetting(key) { run('DELETE FROM settings WHERE key = $key', { key }) changed() } function getJson(key, fallback) { try { const raw = getSetting(key) return raw ? JSON.parse(raw) : fallback } catch { return fallback } } /** Raw bytes of the database (for the encrypted backup). */ function serialize() { const h = handle() h.exec('PRAGMA wal_checkpoint(TRUNCATE);') return h.serialize() } function counts() { return get(`SELECT (SELECT count(*) FROM posts) AS posts, (SELECT count(*) FROM codes) AS codes, (SELECT count(*) FROM settings) AS settings, (SELECT count(*) FROM tg_chats) AS chats`) } module.exports = { DB_PATH, open, close, handle, all, get, run, tx, changed, onChange, getSetting, setSetting, clearSetting, getJson, serialize, counts, }