File size: 8,301 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
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
234
235
236
237
238
239
240
241
242
243
/**
 * 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 }