Spaces:
Sleeping
Sleeping
Download routes/api.js from Ethscriptions/cut: direct link, hf CLI and curl.
- Browser
- Download file 7.63 kB
-
https://huggingface.co/spaces/Ethscriptions/cut/resolve/main/routes/api.js
- Command line
-
hf download hf://spaces/Ethscriptions/cut/routes/api.js
-
curl -L -o api.js https://huggingface.co/spaces/Ethscriptions/cut/resolve/main/routes/api.js
7.63 kB
| /** | |
| * 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 | |