368 lines
13 KiB
JavaScript
368 lines
13 KiB
JavaScript
const { enrichArticles, canonicalURL, TOTAL_TIMEOUT_MS } = require('./article-content')
|
|
const { withDatesFromLoadedHtml } = require('./publication-date')
|
|
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 tryClick(page, selectors) {
|
|
for (const sel of selectors) {
|
|
try {
|
|
const el = await page.$(sel)
|
|
if (el) { await el.click(); return true }
|
|
} catch {}
|
|
}
|
|
await page.keyboard.press('Enter')
|
|
return false
|
|
}
|
|
|
|
async function tryType(page, selectors, text) {
|
|
for (const sel of selectors) {
|
|
try {
|
|
await page.waitForSelector(sel, { timeout: 4000 })
|
|
await page.type(sel, text, { delay: 60 })
|
|
return true
|
|
} catch {}
|
|
}
|
|
return false
|
|
}
|
|
|
|
async function scrapeBloombergViaPuppeteer(username, password, enrichment) {
|
|
let browser
|
|
let abortBrowser
|
|
let loginTimer
|
|
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')
|
|
await page.goto('https://www.bloomberg.com/account/signin', {
|
|
waitUntil: 'networkidle2',
|
|
timeout: 60000,
|
|
})
|
|
await new Promise(r => setTimeout(r, 2000))
|
|
|
|
const pageInputs = await page.evaluate(() =>
|
|
Array.from(document.querySelectorAll('input')).map(i => ({
|
|
type: i.type, name: i.name, id: i.id, placeholder: i.placeholder, visible: i.offsetParent !== null
|
|
}))
|
|
)
|
|
console.log('[bloomberg] login input count:', pageInputs.length)
|
|
|
|
|
|
const emailOk = await tryType(page, [
|
|
'#email-form-input',
|
|
'input[id="email-form-input"]',
|
|
'input[type="email"]',
|
|
'input[name="text-input"]',
|
|
'input[placeholder*="email" i]',
|
|
], username)
|
|
if (!emailOk) throw new Error('could not find email input')
|
|
|
|
await new Promise(r => setTimeout(r, 800))
|
|
|
|
const submitted = await page.evaluate(() => {
|
|
const btn = Array.from(document.querySelectorAll('button')).find(b =>
|
|
b.type === 'submit' || /continue|next|sign.?in/i.test(b.textContent)
|
|
)
|
|
if (btn) { btn.click(); return true }
|
|
const form = document.querySelector('form')
|
|
if (form) { form.submit(); return true }
|
|
return false
|
|
})
|
|
if (!submitted) await page.keyboard.press('Enter')
|
|
|
|
try {
|
|
await page.waitForFunction(
|
|
() => document.querySelector('input[type="password"]') !== null,
|
|
{ timeout: 10000 }
|
|
)
|
|
} catch {
|
|
await new Promise(r => setTimeout(r, 3000))
|
|
}
|
|
console.log('[bloomberg] email step completed')
|
|
|
|
const pwdOk = await tryType(page, [
|
|
'input[type="password"]',
|
|
'input[name="password"]',
|
|
'input[autocomplete="current-password"]',
|
|
'input[autocomplete="password"]',
|
|
], password)
|
|
if (!pwdOk) throw new Error('could not find password input')
|
|
|
|
await new Promise(r => setTimeout(r, 500))
|
|
await Promise.all([
|
|
page.waitForNavigation({ waitUntil: 'networkidle2', timeout: 20000 }).catch(() => {}),
|
|
tryClick(page, ['button[type="submit"]', 'input[type="submit"]']),
|
|
])
|
|
|
|
const currentURL = page.url()
|
|
console.log('[bloomberg] login navigation completed')
|
|
if (currentURL.includes('/account/signin')) {
|
|
throw new Error('login did not redirect')
|
|
}
|
|
|
|
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(() => {
|
|
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')
|
|
await articlePage.goto(url, { waitUntil: 'domcontentloaded', timeout: options.timeoutMs })
|
|
if (canonicalURL(articlePage.url()) !== canonicalURL(url)) 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 })
|
|
}
|
|
|
|
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 } = req.body || {}
|
|
if (!username || !password || !Array.isArray(urls) || urls.some(url => typeof url !== 'string')) return res.status(400).json({ error: 'invalid enrichment request' })
|
|
if (!urls.length) return res.json({ articles: [] })
|
|
const empty = () => urls.map(url => ({ url, content: '', published_at: null, content_truncated: false }))
|
|
if (!urls.some(url => canonicalURL(url))) return res.json({ articles: 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 {
|
|
const operation = BYPARR_URL
|
|
? enrichArticles(urls, async (url, options) => (await byparrFetch(url, true, options)).html, { signal: controller.signal })
|
|
: scrapeBloombergViaPuppeteer(username, password, { urls, signal: controller.signal, deadline })
|
|
const articles = await Promise.race([operation.catch(empty), expired])
|
|
if (!res.destroyed) res.json({ articles })
|
|
} finally {
|
|
clearTimeout(timer)
|
|
controller.abort()
|
|
res.removeListener?.('close', onClose)
|
|
}
|
|
})
|
|
|
|
app.listen(PORT, () => console.log(`scraper-service listening on :${PORT}`))
|