Spaces:
Sleeping
Sleeping
Download lib/x/scan.js from Ethscriptions/cut: direct link, hf CLI and curl.
- Browser
- Download file 8.3 kB
-
https://huggingface.co/spaces/Ethscriptions/cut/resolve/main/lib/x/scan.js
- Command line
-
hf download hf://spaces/Ethscriptions/cut/lib/x/scan.js
-
curl -L -o scan.js https://huggingface.co/spaces/Ethscriptions/cut/resolve/main/lib/x/scan.js
8.3 kB
| /** | |
| * X source. | |
| * searchTick() — every minute: live "Latest" search (needs the user's X cookies) | |
| * profileTick() — every 3 minutes: public profile pages of known sharers (no login) | |
| */ | |
| const db = require('../db') | |
| const log = require('../log') | |
| const detect = require('../detect') | |
| const pipeline = require('../pipeline') | |
| const x = require('./client') | |
| /** Always searched (the link itself — the most precise query). */ | |
| const PRIMARY = 'asksurf.ai/mystery-box' | |
| /** One of these rides along on every tick, in rotation. */ | |
| const ROTATING = [ | |
| '"mystery-box/g"', | |
| '"Surf Mystery Box"', | |
| 'surf mystery box', | |
| 'surf 盲盒', | |
| '"Surf Pro" 会员', | |
| 'asksurf mystery', | |
| ] | |
| const SEED_HANDLES = [ | |
| 'SurfAIHQ', | |
| 'moranweb3', | |
| 'iamyourchaos', | |
| 'shadatofficial1', | |
| 'kr_dongsu', | |
| 'Syu990', | |
| 'Lecter_XFinance', | |
| 'Big_Tea_Rice', | |
| 'Phu_Prosperity8', | |
| 'AirdropAlchemis', | |
| 'kevinlilili', | |
| 'Pawan2001564157', | |
| ] | |
| const PROFILES_PER_TICK = 4 | |
| const state = { pausedUntil: 0, authFailed: false, authFails: 0, authRetryAt: 0, rotate: 0, profileCursor: 0, lastResults: 0 } | |
| const irrelevant = new Set() | |
| function remember(id) { | |
| if (irrelevant.size > 20000) irrelevant.delete(irrelevant.values().next().value) | |
| irrelevant.add(id) | |
| } | |
| /** Tweet → pipeline post (follows t.co links only when the tweet might be relevant). */ | |
| async function toPost(tweet, via) { | |
| const links = [...tweet.links] | |
| const needsResolve = links.length === 0 && tweet.tco.length > 0 | |
| if (needsResolve) { | |
| for (const tco of tweet.tco.slice(0, 3)) { | |
| const target = await x.resolveTco(tco) | |
| if (target) links.push(target) | |
| } | |
| } | |
| return { | |
| id: `x:${tweet.id}`, | |
| source: 'x', | |
| via, | |
| author: tweet.handle, | |
| author_name: tweet.name, | |
| text: tweet.text, | |
| url: `https://x.com/${tweet.handle || 'i'}/status/${tweet.id}`, | |
| created_at: tweet.created_at, | |
| views: tweet.views, | |
| likes: tweet.likes, | |
| reposts: tweet.reposts, | |
| replies: tweet.replies, | |
| media: tweet.media, | |
| links, | |
| } | |
| } | |
| /** Feed a batch of tweets through the pipeline; returns how many were kept / new. */ | |
| async function ingestTweets(tweets, via, { force = false } = {}) { | |
| let kept = 0 | |
| let fresh = 0 | |
| for (const tweet of tweets) { | |
| const id = `x:${tweet.id}` | |
| if (!force && irrelevant.has(id)) continue | |
| const known = db.get('SELECT kind FROM posts WHERE id = $id', { id }) | |
| if (!force && known?.kind === 'gift') continue | |
| const post = await toPost(tweet, via) | |
| const result = await pipeline.ingest(post) | |
| if (!result.kept) { | |
| remember(id) | |
| continue | |
| } | |
| kept += 1 | |
| if (result.isNew) fresh += 1 | |
| } | |
| return { kept, fresh } | |
| } | |
| async function searchTick({ all = false } = {}) { | |
| if (!db.getSetting('x_cookies')) { | |
| log.set('x-search', { state: 'off' }) | |
| return { skipped: 'no-session' } | |
| } | |
| // A dead session is retried every 30 minutes (X sometimes rejects a good session briefly). | |
| if (state.authFailed && Date.now() < state.authRetryAt) return { skipped: 'auth-failed' } | |
| if (state.pausedUntil > Date.now()) return { skipped: 'rate-limited' } | |
| const queries = all ? [PRIMARY, ...ROTATING] : [PRIMARY, ROTATING[state.rotate++ % ROTATING.length]] | |
| let results = 0 | |
| let kept = 0 | |
| let fresh = 0 | |
| try { | |
| for (const query of queries) { | |
| const tweets = await x.search(query, { count: 20 }) | |
| results += tweets.length | |
| const r = await ingestTweets(tweets, `X 搜索 · ${query}`) | |
| kept += r.kept | |
| fresh += r.fresh | |
| } | |
| state.lastResults = results | |
| state.authFails = 0 | |
| if (state.authFailed) { | |
| state.authFailed = false | |
| db.clearSetting('x_error') | |
| } | |
| log.ok('x-search', { state: 'live', results, fresh }) | |
| return { results, kept, fresh } | |
| } catch (err) { | |
| if (err.rateLimited) { | |
| state.pausedUntil = Math.max(Date.now() + 60000, (err.resetAt || 0) * 1000) | |
| log.fail('x-search', `X 搜索限流,${Math.ceil((state.pausedUntil - Date.now()) / 60000)} 分钟后恢复`, { state: 'paused' }) | |
| } else if (err.authFailed) { | |
| state.authFails = (state.authFails || 0) + 1 | |
| if (state.authFails >= 3 || state.authFailed) { | |
| state.authFailed = true | |
| state.authRetryAt = Date.now() + 30 * 60000 | |
| if (db.getSetting('x_error') !== err.message) db.setSetting('x_error', err.message) | |
| } | |
| log.fail('x-search', err, { state: state.authFailed ? 'expired' : 'error' }) | |
| } else { | |
| log.fail('x-search', err, { state: 'error' }) | |
| } | |
| return { error: err.message, results, kept, fresh } | |
| } | |
| } | |
| /** Sharers worth polling: the seed list plus everyone who posted a gift link recently. */ | |
| function profileHandles() { | |
| const recent = db | |
| .all( | |
| `SELECT author, MAX(created_at) AS last FROM posts | |
| WHERE source = 'x' AND kind IN ('gift', 'box') AND author IS NOT NULL AND created_at > $since | |
| GROUP BY lower(author) ORDER BY last DESC LIMIT 40`, | |
| { since: log.now() - 14 * 86400 } | |
| ) | |
| .map((row) => row.author) | |
| const seen = new Set() | |
| return [...recent, ...SEED_HANDLES].filter((handle) => { | |
| const key = handle.toLowerCase() | |
| if (seen.has(key)) return false | |
| seen.add(key) | |
| return true | |
| }) | |
| } | |
| async function profileTick({ count = PROFILES_PER_TICK } = {}) { | |
| const handles = profileHandles() | |
| if (!handles.length) return { handles: 0 } | |
| const picked = [] | |
| for (let i = 0; i < Math.min(count, handles.length); i += 1) { | |
| picked.push(handles[(state.profileCursor + i) % handles.length]) | |
| } | |
| state.profileCursor = (state.profileCursor + picked.length) % handles.length | |
| let kept = 0 | |
| let fresh = 0 | |
| let failed = 0 | |
| await Promise.all( | |
| picked.map(async (handle) => { | |
| try { | |
| const r = await ingestTweets(await x.profile(handle), `X 主页 · @${handle}`) | |
| kept += r.kept | |
| fresh += r.fresh | |
| } catch { | |
| failed += 1 | |
| } | |
| }) | |
| ) | |
| if (failed === picked.length) log.fail('x-profiles', `${failed} 个主页读取失败`) | |
| else log.ok('x-profiles', { handles: handles.length, fresh }) | |
| return { handles: picked.length, kept, fresh, failed } | |
| } | |
| /* ------------------------------------------------------------ session ---- */ | |
| async function connect(input) { | |
| const jar = x.parseCookies(input) | |
| if (!jar.auth_token) throw Object.assign(new Error('没有识别到 auth_token,请把完整 Cookie 复制进来'), { status: 400 }) | |
| if (!jar.ct0) throw Object.assign(new Error('缺少 ct0,请把完整 Cookie 复制进来'), { status: 400 }) | |
| const cookies = x.cookieHeader(jar) | |
| const who = await x.whoAmI(cookies).catch(() => ({ loggedIn: null })) | |
| if (who.loggedIn === false) throw Object.assign(new Error('Cookie 已失效或不是登录状态,请重新从浏览器复制'), { status: 400 }) | |
| // The real test: can these cookies run a live search? | |
| let tweets | |
| try { | |
| tweets = await x.search(PRIMARY, { count: 20, cookies }) | |
| } catch (err) { | |
| throw Object.assign(new Error(`登录校验没通过:${err.message}`), { status: 400 }) | |
| } | |
| db.setSetting('x_cookies', cookies) | |
| db.setSetting('x_username', who.handle || '') | |
| db.clearSetting('x_error') | |
| state.authFailed = false | |
| state.authFails = 0 | |
| state.authRetryAt = 0 | |
| state.pausedUntil = 0 | |
| await ingestTweets(tweets, `X 搜索 · ${PRIMARY}`).catch(() => {}) | |
| log.info('x-search', `X 已登录${who.handle ? ` @${who.handle}` : ''},搜索到 ${tweets.length} 条`) | |
| return status() | |
| } | |
| function disconnect() { | |
| for (const key of ['x_cookies', 'x_username', 'x_error']) db.clearSetting(key) | |
| state.authFailed = false | |
| log.set('x-search', { state: 'off', error: null }) | |
| return status() | |
| } | |
| function status() { | |
| const connected = Boolean(db.getSetting('x_cookies')) | |
| return { | |
| connected, | |
| username: db.getSetting('x_username') || null, | |
| expired: state.authFailed, | |
| error: state.authFailed ? db.getSetting('x_error') : null, | |
| pausedUntil: state.pausedUntil > Date.now() ? Math.floor(state.pausedUntil / 1000) : null, | |
| lastResults: state.lastResults, | |
| } | |
| } | |
| /** Boot: a session that was marked dead before the restart stays dead until re-login. */ | |
| function init() { | |
| state.authFailed = Boolean(db.getSetting('x_error')) | |
| state.authRetryAt = 0 | |
| } | |
| module.exports = { searchTick, profileTick, ingestTweets, connect, disconnect, status, init, PRIMARY } | |