feat(bloomberg): enrich article content for summaries (#36)
This commit is contained in:
@ -1,3 +1,4 @@
|
||||
const { enrichArticles, canonicalURL, TOTAL_TIMEOUT_MS } = require('./article-content')
|
||||
const { withDatesFromLoadedHtml } = require('./publication-date')
|
||||
const express = require('express')
|
||||
const cheerio = require('cheerio')
|
||||
@ -15,11 +16,12 @@ const BYPARR_URL = process.env.BYPARR_URL || ''
|
||||
|
||||
// ---------- Byparr helpers ----------
|
||||
|
||||
async function byparrRequest(body) {
|
||||
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. */ }
|
||||
@ -28,9 +30,10 @@ async function byparrRequest(body) {
|
||||
return resp.json()
|
||||
}
|
||||
|
||||
async function byparrFetch(url, quiet = false) {
|
||||
async function byparrFetch(url, quiet = false, options = {}) {
|
||||
if (!quiet) console.log('[byparr] section request')
|
||||
const data = await byparrRequest({ cmd: 'request.get', url, maxTimeout: 60000 })
|
||||
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 }
|
||||
@ -142,84 +145,126 @@ async function tryType(page, selectors, text) {
|
||||
return false
|
||||
}
|
||||
|
||||
async function scrapeBloombergViaPuppeteer(username, password) {
|
||||
async function scrapeBloombergViaPuppeteer(username, password, enrichment) {
|
||||
let browser
|
||||
let abortBrowser
|
||||
let loginTimer
|
||||
try {
|
||||
browser = await launchBrowser()
|
||||
const page = await browser.newPage()
|
||||
await page.setViewport({ width: 1920, height: 1080 })
|
||||
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] })
|
||||
})
|
||||
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))
|
||||
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)
|
||||
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
|
||||
}))
|
||||
)
|
||||
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')
|
||||
console.log('[bloomberg] login input count:', pageInputs.length)
|
||||
|
||||
try {
|
||||
await page.waitForFunction(
|
||||
() => document.querySelector('input[type="password"]') !== null,
|
||||
{ timeout: 10000 }
|
||||
)
|
||||
} catch {
|
||||
await new Promise(r => setTimeout(r, 3000))
|
||||
|
||||
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
|
||||
}
|
||||
console.log('[bloomberg] email step completed')
|
||||
// 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)
|
||||
|
||||
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')
|
||||
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 = [
|
||||
@ -257,6 +302,8 @@ async function scrapeBloombergViaPuppeteer(username, password) {
|
||||
|
||||
return articles
|
||||
} finally {
|
||||
if (enrichment) clearTimeout(loginTimer)
|
||||
if (enrichment && abortBrowser) enrichment.signal.removeEventListener('abort', abortBrowser)
|
||||
if (browser) await browser.close()
|
||||
}
|
||||
}
|
||||
@ -289,4 +336,32 @@ app.post('/bloomberg/scrape', async (req, res) => {
|
||||
}
|
||||
})
|
||||
|
||||
// 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}`))
|
||||
|
||||
Reference in New Issue
Block a user