File size: 4,960 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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
/**
 * 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,
}