File size: 7,632 Bytes
5936c9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36514c5
 
 
a703121
 
fd6a697
 
5936c9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd704a9
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
/**
 * HTTP API.
 *   Public:  GET /feed, /status, /ping, POST /scan, POST /add
 *   Admin:   everything under /settings, /x, /tg, /notify (needs the admin key when one is set)
 */
const express = require('express')
const db = require('../lib/db')
const log = require('../lib/log')
const feed = require('../lib/feed')
const detect = require('../lib/detect')
const pipeline = require('../lib/pipeline')
const invites = require('../lib/invites')
const alerts = require('../lib/alerts')
const backup = require('../lib/backup')
const scheduler = require('../lib/scheduler')
const xscan = require('../lib/x/scan')
const xclient = require('../lib/x/client')
const tg = require('../lib/tg')

const router = express.Router()

const wrap = (fn) => async (req, res) => {
  try {
    res.json(await fn(req, res))
  } catch (err) {
    res.status(err.status || 500).json({ error: err.message || String(err) })
  }
}

function adminKey() {
  return db.getSetting('admin_key') || process.env.ADMIN_KEY || null
}

function requireKey(req, res, next) {
  const key = adminKey()
  if (!key) return next()
  const given = req.get('x-admin-key') || req.query.key
  if (given && String(given) === String(key)) return next()
  return res.status(401).json({ error: '需要管理密码', needsKey: true })
}

/* ---------------------------------------------------------------- public -- */

router.get('/ping', (req, res) => res.json({ ok: true, at: log.now() }))

router.get(
  '/feed',
  wrap((req) => ({
    now: log.now(),
    stats: feed.stats(),
    usable: feed.usable(),
    posts: feed.feed({ view: req.query.view, source: req.query.source, q: req.query.q, limit: req.query.limit }),
  }))
)

router.get(
  '/status',
  wrap(() => {
    const t = tg.status()
    const x = xscan.status()
    const { health, lines } = log.snapshot()
    return {
      now: log.now(),
      uptime: Math.round(process.uptime()),
      telegram: {
        enabled: t.enabled,
        phase: t.phase,
        error: t.error,
        dialogs: t.dialogs,
        events: t.events,
        kept: t.kept,
        lastEventAt: t.lastEventAt,
        lastCatchup: t.lastCatchup,
        lastGlobal: t.lastGlobal,
        lastPoll: t.lastPoll,
        polled: t.polled,
        missedByRealtime: t.missedByRealtime,
        raw: t.raw,
        rawTypes: t.rawTypes,
        wire: t.wire,
        realtimeResets: t.realtimeResets,
        floodUntil: t.floodUntil,
        tracked: db.get('SELECT count(*) AS n FROM tg_chats').n,
      },
      x: { connected: x.connected, expired: x.expired, pausedUntil: x.pausedUntil, lastResults: x.lastResults },
      push: (({ webhook, ...rest }) => rest)(alerts.status()),
      backup: (({ dataset, ...rest }) => rest)(backup.status()),
      pipeline: pipeline.stats,
      health,
      loops: scheduler.status(),
      log: lines,
    }
  })
)

router.post('/scan', wrap(() => scheduler.scanNow()))

/** Paste a tweet link, gift link(s) or a bare code. */
router.post(
  '/add',
  requireKey,
  wrap(async (req) => {
    const input = String(req.body?.input || '').trim()
    if (!input) throw Object.assign(new Error('请输入推文链接、赠链链接或赠链码'), { status: 400 })
    const status = /(?:x|twitter)\.com\/([A-Za-z0-9_]{1,20})\/status\/(\d{5,25})/.exec(input)
    let codes = []
    if (status) {
      const tweet = await xclient.tweet(status[2])
      await xscan.ingestTweets([tweet], '手动添加', { force: true })
      codes = db.all('SELECT code FROM post_codes WHERE post_id = $id', { id: `x:${tweet.id}` }).map((r) => r.code)
      if (!codes.length) {
        const kept = db.get('SELECT 1 AS ok FROM posts WHERE id = $id', { id: `x:${tweet.id}` })
        return { ok: Boolean(kept), message: kept ? '已收录这条推文(里面没有赠链码)' : '这条推文和 Surf 盲盒无关,没有收录' }
      }
    } else {
      codes = detect.codesFromInput(input)
      if (!codes.length) throw Object.assign(new Error('没有识别到赠链码'), { status: 400 })
      for (const code of codes) {
        pipeline.store({
          id: `manual:${code}`,
          source: 'manual',
          via: '手动添加',
          author: 'manual',
          author_name: '手动添加',
          text: `https://asksurf.ai/mystery-box/g/${code}`,
          url: null,
          created_at: log.now(),
          links: [`https://asksurf.ai/mystery-box/g/${code}`],
        })
      }
    }
    await invites.checkNow(codes)
    const push = await alerts.pushPending()
    const rows = codes.map((code) => db.get('SELECT * FROM codes WHERE code = $code', { code })).filter(Boolean)
    return {
      ok: true,
      codes: rows.map((row) => ({ code: row.code, status: row.status, seats: row.seats, usable: invites.isUsable(row) })),
      pushed: push.pushed,
    }
  })
)

/* ----------------------------------------------------------------- admin -- */

router.get(
  '/settings',
  requireKey,
  wrap(() => ({
    locked: Boolean(adminKey()),
    x: xscan.status(),
    telegram: { ...tg.status(), chats: tg.trackedChats() },
    push: alerts.status(),
    backup: backup.status(),
  }))
)

router.post('/auth/check', requireKey, (req, res) => res.json({ ok: true }))
router.post(
  '/auth/key',
  requireKey,
  wrap((req) => {
    const key = String(req.body?.key || '').trim()
    if (key && key.length < 6) throw Object.assign(new Error('密码至少 6 位'), { status: 400 })
    if (key) db.setSetting('admin_key', key)
    else db.clearSetting('admin_key')
    return { locked: Boolean(adminKey()) }
  })
)

router.post('/x/connect', requireKey, wrap((req) => xscan.connect(req.body?.cookies)))
router.delete('/x', requireKey, wrap(() => xscan.disconnect()))

router.post('/tg/login/start', requireKey, wrap((req) => tg.startLogin(req.body?.phone)))
router.post('/tg/login/code', requireKey, wrap((req) => tg.submitCode(req.body || {})))
router.post('/tg/logout', requireKey, wrap(() => tg.logout()))
router.post('/tg/reconnect', requireKey, wrap(() => tg.reconnect()))
router.get('/tg/dialogs', requireKey, wrap(() => tg.dialogs()))
router.get('/tg/sessions', requireKey, wrap(() => tg.sessions()))
router.post(
  '/tg/chats',
  requireKey,
  wrap(async (req) => {
    if (req.body?.link) return { added: await tg.addByLink(req.body.link), chats: tg.trackedChats() }
    const added = tg.addRows(Array.isArray(req.body?.items) ? req.body.items : [])
    return { added, chats: tg.trackedChats() }
  })
)
router.delete(
  '/tg/chats/:id',
  requireKey,
  wrap((req) => {
    tg.removeChat(req.params.id)
    return { chats: tg.trackedChats() }
  })
)
router.post(
  '/tg/chats/:id/full',
  requireKey,
  wrap((req) => {
    tg.setFull(req.params.id, Boolean(req.body?.full))
    return { chats: tg.trackedChats() }
  })
)

router.post(
  '/notify',
  requireKey,
  wrap((req) => {
    const url = String(req.body?.webhook || '').trim()
    if (url && !/^https:\/\/qyapi\.weixin\.qq\.com\/cgi-bin\/webhook\/send\?key=/.test(url)) {
      throw Object.assign(new Error('请填写企业微信群机器人的 Webhook 地址'), { status: 400 })
    }
    if (url) db.setSetting('wecom_webhook', url)
    else db.clearSetting('wecom_webhook')
    // Codes that failed because the old address was broken get another chance.
    db.run(`UPDATE codes SET push_tries = 0 WHERE pushed_at IS NULL`)
    alerts.pushPending().catch(() => {})
    return alerts.status()
  })
)
router.post(
  '/notify/test',
  requireKey,
  wrap(async () => {
    await alerts.sendTest()
    return { ok: true }
  })
)

router.post('/backup', requireKey, wrap(() => backup.save('manual')))

module.exports = router