Files
TradarrV2/scraper-service/index.js

349 lines
14 KiB
JavaScript

const { enrichArticles, canonicalURL, TOTAL_TIMEOUT_MS } = require('./article-content')
const { createFetchMetrics } = require('./fetch-metrics')
const { withDatesFromLoadedHtml } = require('./publication-date')
const { inspectLoginState, classifyLoginState, authenticatedDestination, trustedLoginOrigin, typeVisibleInput, submitInputForm } = require('./bloomberg-login')
const express = require('express')
const cheerio = require('cheerio')
const puppeteer = require('puppeteer-extra')
const StealthPlugin = require('puppeteer-extra-plugin-stealth')
puppeteer.use(StealthPlugin())
const app = express()
app.use(express.json())
const CHROME_PATH = process.env.PUPPETEER_EXECUTABLE_PATH || '/usr/bin/chromium'
const PORT = process.env.PORT || 3001
const BYPARR_URL = process.env.BYPARR_URL || ''
// ---------- Byparr helpers ----------
async function byparrRequest(body, signal) {
const resp = await fetch(`${BYPARR_URL}/v1`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
signal,
})
if (!resp.ok) {
try { await resp.body?.cancel() } catch { /* Release without reading/logging the body. */ }
throw new Error(`byparr HTTP ${resp.status}`)
}
return resp.json()
}
async function byparrFetch(url, quiet = false, options = {}) {
if (!quiet) console.log('[byparr] section request')
const data = await byparrRequest({ cmd: 'request.get', url, maxTimeout: options.timeoutMs || 60000 }, options.signal)
if (options.signal && data.solution?.url && canonicalURL(data.solution.url) !== canonicalURL(url)) throw new Error('article association unavailable')
const html = data.solution?.response
if (!html) throw new Error('byparr returned no HTML')
return { html }
}
// ---------- Article parsing ----------
function parseArticlesFromHtml(html, loadedURL) {
const $ = cheerio.load(html)
const results = []
const seen = new Set()
$('a[data-component="story-link"]').each((_, el) => {
const a = $(el)
const href = a.attr('href') || ''
const absolute = href.startsWith('http') ? href : `https://www.bloomberg.com${href}`
const clean = absolute.split('?')[0]
if (seen.has(clean)) return
if (!/\/(news\/articles|news\/features|features)\//.test(clean)) return
const title = a.find('[data-testid="headline"] span').text().trim()
if (!title || title.length < 10) return
seen.add(clean)
results.push({ title, url: clean })
})
return withDatesFromLoadedHtml(results, html, loadedURL, $)
}
// ---------- Bloomberg scraping via Byparr ----------
async function scrapeBloombergViaByparr(username, password) {
// /markets main page is excluded: live ticker widgets cause continuous network activity
// so Byparr's networkidle wait never resolves. Sub-sections below are editorial pages
// without live data — they behave like /technology and /economics (~5s each).
const byparrPages = [
'https://www.bloomberg.com/markets/stocks',
'https://www.bloomberg.com/markets/currencies',
'https://www.bloomberg.com/markets/rates-bonds',
'https://www.bloomberg.com/markets/commodities',
'https://www.bloomberg.com/technology',
'https://www.bloomberg.com/economics',
'https://www.bloomberg.com/politics',
]
const articles = []
const seen = new Set()
for (const url of byparrPages) {
try {
const { html } = await byparrFetch(url)
const items = parseArticlesFromHtml(html, url)
for (const item of items) {
if (!seen.has(item.url)) {
seen.add(item.url)
articles.push(item)
} else if (item.published_at) {
const existing = articles.find(article => article.url === item.url)
if (existing && !existing.published_at) existing.published_at = item.published_at
}
}
console.log('[bloomberg] section articles:', items.length)
} catch (e) {
console.error('[bloomberg] section unavailable')
}
}
return articles
}
// ---------- Bloomberg scraping via Puppeteer (fallback, may be blocked) ----------
function launchBrowser() {
return puppeteer.launch({
executablePath: CHROME_PATH,
headless: true,
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
'--disable-gpu',
'--window-size=1920,1080',
'--disable-blink-features=AutomationControlled',
],
})
}
async function scrapeBloombergViaPuppeteer(username, password, enrichment) {
let browser
let abortBrowser
let loginTimer
enrichment?.metrics?.setLogin('unconfirmed')
try {
const login = async () => {
browser = await launchBrowser()
if (enrichment) {
abortBrowser = () => { browser.close().catch(() => {}) }
enrichment.signal.addEventListener('abort', abortBrowser, { once: true })
if (enrichment.signal.aborted) { abortBrowser(); throw new Error('enrichment expired') }
}
const page = await browser.newPage()
await page.setViewport({ width: 1920, height: 1080 })
await page.evaluateOnNewDocument(() => {
Object.defineProperty(navigator, 'webdriver', { get: () => undefined })
window.chrome = { runtime: {} }
Object.defineProperty(navigator, 'plugins', { get: () => [1, 2, 3] })
})
console.log('[bloomberg] navigating to login page')
const loginResponse = await page.goto('https://www.bloomberg.com/account/signin', {
waitUntil: 'networkidle2',
timeout: 60000,
})
await new Promise(r => setTimeout(r, 2000))
const failLogin = reason => {
enrichment?.metrics?.setLogin(['access_denied','auth_rejected'].includes(reason) ? 'refused' : 'unconfirmed')
console.log('[bloomberg] login outcome:', reason)
throw new Error('authentication unavailable')
}
if (!loginResponse) failLogin('login_navigation_unavailable')
if (loginResponse.status() !== 200) failLogin([401,403].includes(loginResponse.status()) ? 'access_denied' : 'login_http_unavailable')
const rejectBlocked = async () => {
const reason = classifyLoginState(await page.evaluate(inspectLoginState))
if (['challenge','two_factor_required','auth_rejected'].includes(reason)) failLogin(reason)
}
await rejectBlocked()
if (!trustedLoginOrigin(page.url())) failLogin('login_origin_unavailable')
const emailOk = await typeVisibleInput(page, [
'#email-form-input',
'input[id="email-form-input"]',
'input[type="email"]',
'input[name="text-input"]',
'input[placeholder*="email" i]',
], username)
if (!emailOk) failLogin('email_form_unavailable')
await new Promise(r => setTimeout(r, 800))
const submitted = await page.evaluate(submitInputForm, emailOk)
if (!submitted) failLogin('login_form_unavailable')
try {
await page.waitForSelector('input[type="password"]', { visible:true, timeout:10000 })
} catch {
await new Promise(r => setTimeout(r, 3000))
}
await rejectBlocked()
if (!trustedLoginOrigin(page.url())) failLogin('login_origin_unavailable')
console.log('[bloomberg] email step completed')
const pwdOk = await typeVisibleInput(page, [
'input[type="password"]',
'input[name="password"]',
'input[autocomplete="current-password"]',
'input[autocomplete="password"]',
], password)
if (!pwdOk) failLogin('password_form_unavailable')
await new Promise(r => setTimeout(r, 500))
if (!await page.evaluate(submitInputForm, pwdOk)) failLogin('login_form_unavailable')
// SPA login may complete without navigation; leaving sign-in alone is
// never evidence of authentication. Wait for explicit terminal DOM state.
await page.waitForFunction(inspectLoginState, { timeout:10000 }, true).catch(() => {})
const outcome = classifyLoginState(await page.evaluate(inspectLoginState))
if (outcome !== 'authenticated') failLogin(outcome)
if (!authenticatedDestination(page.url())) failLogin('authentication_unconfirmed')
enrichment?.metrics?.setLogin('confirmed')
console.log('[bloomberg] login outcome: authenticated')
return page
}
// Enrichment reserves at least 60s of its 90s total budget for pages.
// One login/session is shared; normal list collection keeps its deadlines.
const page = enrichment
? await Promise.race([login(), new Promise((resolve, reject) => {
loginTimer = setTimeout(() => {
console.log('[bloomberg] login outcome: login_timeout')
abortBrowser?.()
reject(new Error('enrichment login expired'))
}, 30000)
})])
: await login()
if (enrichment) clearTimeout(loginTimer)
if (enrichment) {
const remaining = enrichment.deadline - Date.now()
if (remaining <= 0 || enrichment.signal.aborted) throw new Error('enrichment expired')
return await enrichArticles(enrichment.urls, async (url, options) => {
if (options.signal.aborted) throw new Error('article expired')
const articlePage = await browser.newPage()
const close = () => { articlePage.close().catch(() => {}) }
options.signal.addEventListener('abort', close, { once: true })
try {
if (options.signal.aborted) throw new Error('article expired')
const navigation = await articlePage.goto(url, { waitUntil: 'domcontentloaded', timeout: options.timeoutMs })
if (navigation) options.observeHTTPStatus?.(navigation.status())
if (!navigation || navigation.status() !== 200) throw new Error('article response unavailable')
if (canonicalURL(articlePage.url()) !== canonicalURL(url)) {options.observeIdentityMismatch?.();throw new Error('article association unavailable')}
return await articlePage.content()
} finally {
options.signal.removeEventListener('abort', close)
await articlePage.close().catch(() => {})
}
}, { concurrency: 2, totalTimeoutMs: remaining, signal: enrichment.signal, metrics:enrichment.metrics })
}
const targetPages = [
'https://www.bloomberg.com/markets',
'https://www.bloomberg.com/technology',
'https://www.bloomberg.com/economics',
]
const articles = []
const seen = new Set()
for (const url of targetPages) {
try {
console.log('[bloomberg] loading section')
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 })
await page.waitForSelector('a[data-component="story-link"]', { timeout: 15000 }).catch(() => {})
const html = await page.content()
const items = parseArticlesFromHtml(html, url)
for (const item of items) {
if (!seen.has(item.url)) {
seen.add(item.url)
articles.push(item)
} else if (item.published_at) {
const existing = articles.find(article => article.url === item.url)
if (existing && !existing.published_at) existing.published_at = item.published_at
}
}
console.log('[bloomberg] section articles:', items.length)
} catch (e) {
console.error('[bloomberg] section unavailable')
}
}
return articles
} finally {
if (enrichment) clearTimeout(loginTimer)
if (enrichment && abortBrowser) enrichment.signal.removeEventListener('abort', abortBrowser)
if (browser) await browser.close()
}
}
// ---------- Routes ----------
app.get('/health', (_, res) => res.json({ ok: true }))
app.post('/bloomberg/scrape', async (req, res) => {
const { username, password } = req.body || {}
if (!username || !password) {
return res.status(400).json({ error: 'username and password required' })
}
try {
let articles
if (BYPARR_URL) {
console.log('[bloomberg] using Byparr (nodriver) to bypass bot detection')
articles = await scrapeBloombergViaByparr(username, password)
} else {
console.log('[bloomberg] using Puppeteer (Byparr not configured)')
articles = await scrapeBloombergViaPuppeteer(username, password)
}
console.log('[bloomberg] total:', articles.length, 'articles')
res.json({ articles })
} catch (e) {
console.error('[bloomberg] scrape unavailable')
res.status(500).json({ error: 'scrape unavailable' })
}
})
// Enrichment is a separate RPC: the backend has already applied ArticleLimit.
app.post('/bloomberg/enrich', async (req, res) => {
const { username, password, urls, measure_fetches } = req.body || {}
if (!username || !password || !Array.isArray(urls) || urls.some(url => typeof url !== 'string')) return res.status(400).json({ error: 'invalid enrichment request' })
const metrics = measure_fetches === true ? createFetchMetrics() : null
const respond = articles => res.json(metrics ? {articles,fetch_metrics:metrics.finish()} : {articles})
if (!urls.length) return respond([])
const empty = () => urls.map(url => ({ url, content: '', published_at: null, content_truncated: false, content_state: 'unavailable' }))
if (!urls.some(url => canonicalURL(url))) return respond(empty())
const controller = new AbortController()
const deadline = Date.now() + TOTAL_TIMEOUT_MS
let finish
const expired = new Promise(resolve => { finish = resolve })
const stop = () => { controller.abort(); finish(empty()) }
const timer = setTimeout(stop, TOTAL_TIMEOUT_MS)
const onClose = () => { if (!res.writableEnded) stop() }
res.once?.('close', onClose)
try {
// Section discovery still uses Byparr. Article bodies require the existing
// authenticated browser session, with no anonymous transport fallback.
const operation = scrapeBloombergViaPuppeteer(username, password, { urls, signal: controller.signal, deadline, metrics })
const articles = await Promise.race([operation.catch(empty), expired])
if (!res.destroyed) respond(articles)
} finally {
clearTimeout(timer)
controller.abort()
res.removeListener?.('close', onClose)
}
})
app.listen(PORT, () => console.log(`scraper-service listening on :${PORT}`))