72 lines
2.8 KiB
JavaScript
72 lines
2.8 KiB
JavaScript
const cheerio = require('cheerio')
|
|
|
|
function reliableISO(value) {
|
|
if (typeof value !== 'string') return null
|
|
const m = value.trim().match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(Z|[+-]\d{2}:\d{2})$/)
|
|
if (!m) return null
|
|
const [year, month, day, hour, minute, second] = m.slice(1, 7).map(Number)
|
|
if (year < 1970 || month < 1 || month > 12 || day < 1 || hour > 23 || minute > 59 || second > 59) return null
|
|
const calendar = new Date(Date.UTC(year, month - 1, day))
|
|
if (calendar.getUTCMonth() !== month - 1 || calendar.getUTCDate() !== day) return null
|
|
if (m[7] !== 'Z') {
|
|
const [h, min] = m[7].slice(1).split(':').map(Number)
|
|
if (h > 14 || min > 59 || (h === 14 && min !== 0)) return null
|
|
}
|
|
const timestamp = Date.parse(value.trim())
|
|
return Number.isFinite(timestamp) ? new Date(timestamp).toISOString() : null
|
|
}
|
|
|
|
function extractPublicationDate(html) {
|
|
const $ = cheerio.load(html)
|
|
for (const selector of ['meta[name="iso-8601-publish-date"]', 'time[datetime]']) {
|
|
for (const element of $(selector).toArray()) {
|
|
const date = reliableISO($(element).attr(selector.startsWith('meta') ? 'content' : 'datetime'))
|
|
if (date) return date
|
|
}
|
|
}
|
|
let visited = 0
|
|
function published(node, depth = 0) {
|
|
if (!node || typeof node !== 'object' || depth > 32 || ++visited > 2000) return null
|
|
if (!Array.isArray(node)) {
|
|
const types = Array.isArray(node['@type']) ? node['@type'] : [node['@type']]
|
|
if (types.some(type => ['Article', 'NewsArticle', 'ReportageNewsArticle'].includes(type))) {
|
|
const date = reliableISO(node.datePublished)
|
|
if (date) return date
|
|
}
|
|
}
|
|
for (const child of Object.values(node)) {
|
|
const date = published(child, depth + 1)
|
|
if (date) return date
|
|
}
|
|
return null
|
|
}
|
|
for (const element of $('script[type="application/ld+json"]').toArray()) {
|
|
try {
|
|
const date = published(JSON.parse($(element).text()))
|
|
if (date) return date
|
|
} catch { /* Invalid metadata is absent; never log page content. */ }
|
|
}
|
|
return null
|
|
}
|
|
|
|
function isArticleURL(value) {
|
|
try {
|
|
const url = new URL(value)
|
|
return url.protocol === 'https:' && ['www.bloomberg.com', 'bloomberg.com'].includes(url.hostname) &&
|
|
!url.username && !url.password && !url.port &&
|
|
/^\/(news\/articles|news\/features|features)\//.test(url.pathname)
|
|
} catch { return false }
|
|
}
|
|
|
|
async function withPublicationDates(articles, loadHtml) {
|
|
const result = []
|
|
for (const article of articles) {
|
|
let published_at = null
|
|
try { if (isArticleURL(article.url)) published_at = extractPublicationDate(await loadHtml(article.url)) } catch { /* Date stays unknown. */ }
|
|
result.push({ ...article, published_at })
|
|
}
|
|
return result
|
|
}
|
|
|
|
module.exports = { extractPublicationDate, withPublicationDates }
|