From 3f7b4eff715140953fe34b34c143bd1d920c40ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Alves?= Date: Thu, 18 Jun 2026 10:01:28 +0000 Subject: [PATCH] feat(writer-pipeline): PT imprensa ingest for andebol.net (BIT-25559) Add html_listing ingest for Record and A Bola andebol sections and revista_imprensa PDF index parsing from FPA media. Document AGGREGATOR_URL in bridge.env.example and AGGREGATOR_OPERATIONS.md. Paperclip-Issue: BIT-25559 Paperclip-Run: 0ab092e1-68ab-4e5a-90bd-4262e9c3d9fc --- deploy/systemd/bridge.env.example | 7 + docs/AGGREGATOR_OPERATIONS.md | 1 + .../config/andebol.net.sources.json | 44 +++++- writer-pipeline/package-lock.json | 35 +++++ writer-pipeline/package.json | 1 + writer-pipeline/src/html-listing.ts | 78 ++++++++++ writer-pipeline/src/imprensa-ingest.test.ts | 97 +++++++++++++ writer-pipeline/src/ingest-sources.ts | 134 ++++++++++++++++- writer-pipeline/src/revista-imprensa.ts | 137 ++++++++++++++++++ writer-pipeline/src/types.ts | 12 +- 10 files changed, 542 insertions(+), 4 deletions(-) create mode 100644 writer-pipeline/src/html-listing.ts create mode 100644 writer-pipeline/src/imprensa-ingest.test.ts create mode 100644 writer-pipeline/src/revista-imprensa.ts diff --git a/deploy/systemd/bridge.env.example b/deploy/systemd/bridge.env.example index b33d64e..8a2a3f7 100644 --- a/deploy/systemd/bridge.env.example +++ b/deploy/systemd/bridge.env.example @@ -4,6 +4,10 @@ NODE_ENV=production PORT=3200 + +# Per-host domain JSON (andebol.net, newsproject.bitreport.pt) +DOMAINS_CONFIG_PATH=/opt/news-platform/config/domains +DEFAULT_HOST=andebol.net HOST=127.0.0.1 # WordPress REST API base URL (Docker, internal) @@ -12,6 +16,9 @@ WP_API_URL=http://127.0.0.1:8080/wp-json/wp/v2 # Redis cache (installed on host) REDIS_URL=redis://127.0.0.1:6379 +# Writer-pipeline aggregator (loopback — required for /writers/:id/candidates mix) +AGGREGATOR_URL=http://127.0.0.1:3310 + # Cache TTL in seconds (default 5 min for articles, 1 min for homepage) CACHE_TTL_ARTICLES=300 CACHE_TTL_HOMEPAGE=60 diff --git a/docs/AGGREGATOR_OPERATIONS.md b/docs/AGGREGATOR_OPERATIONS.md index a61bb9d..2df739c 100644 --- a/docs/AGGREGATOR_OPERATIONS.md +++ b/docs/AGGREGATOR_OPERATIONS.md @@ -40,6 +40,7 @@ Each aggregated item includes **source** (`sourceFeedId`, optional `sourceKind`) ## Sources, copyright, and wire services (Lusa) - **Operational config:** `writer-pipeline/config/andebol.net.sources.json`. RSS feeds may set **`maxItems`** to limit how many recent entries are ingested per run (large highlight feeds such as SAPO). +- **PT imprensa (BIT-25559):** `html_listing` sources scrape handball-scoped sections (Record modalidades/andebol, A Bola /andebol). **`revista_imprensa`** parses FPA *Revista de Imprensa* PDFs from `portal.fpa.pt/media/` (Cision pressbook index) into story leads — titles + publisher labels, **without** republishing the PDF. ZeroZero listing is disabled when Cloudflare blocks the pipeline host. - **Agência Lusa:** a direct, machine-readable **public Lusa wire feed suitable for unattended ingestion is not used here** — public endpoints are often HTML/portal pages or require a **commercial licence** and contractual terms. Syndicated PT feeds (e.g. SAPO highlights) may **credit Lusa or other agencies** in bylines; that does **not** replace checking rights for republication. Editors must follow `docs/ANDEBOL_EDITORIAL_BRIEF.md` (original rewrite, attribution, no verbatim copy). - **Third-party RSS (Record, Guardian, BBC, etc.):** use only as **story leads**; comply with each site’s **terms of use** and robots/API policy; **English** items are for triage only — **andebol.net** publishes **European Portuguese (PT-PT)** only. diff --git a/writer-pipeline/config/andebol.net.sources.json b/writer-pipeline/config/andebol.net.sources.json index 04564da..8c10f29 100644 --- a/writer-pipeline/config/andebol.net.sources.json +++ b/writer-pipeline/config/andebol.net.sources.json @@ -9,6 +9,48 @@ "topics": ["handball", "pt", "fpa"], "note": "FPA portal WordPress main feed." }, + { + "id": "fpa_revista_imprensa", + "kind": "revista_imprensa", + "url": "https://portal.fpa.pt/media/", + "enabled": true, + "topics": ["handball", "pt", "revista", "fpa"], + "maxPdfs": 2, + "pageTimeoutMs": 90000, + "note": "BIT-25559: daily Cision press-clipping PDFs — parse index for PT publisher leads (no PDF republication)." + }, + { + "id": "record_andebol_html", + "kind": "html_listing", + "url": "https://www.record.pt/modalidades/andebol", + "enabled": true, + "topics": ["handball", "pt", "media"], + "maxItems": 20, + "pathIncludes": ["/modalidades/andebol/detalhe/"], + "pathExcludes": ["/iniciativas/"], + "note": "BIT-25559: Record andebol section listing (no reliable RSS)." + }, + { + "id": "abola_andebol_html", + "kind": "html_listing", + "url": "https://www.abola.pt/andebol", + "enabled": true, + "topics": ["handball", "pt", "media"], + "maxItems": 20, + "pathIncludes": ["/noticias/", "/video/"], + "urlExcludes": ["videocasts", "manifest.json", "rss-"], + "note": "BIT-25559: A Bola andebol hub — handball-scoped article links." + }, + { + "id": "zerozero_andebol_html", + "kind": "html_listing", + "url": "https://www.zerozero.pt/andebol/", + "enabled": false, + "topics": ["handball", "pt", "media"], + "maxItems": 15, + "pathIncludes": ["/andebol/"], + "note": "BIT-25559: Cloudflare 403 from pipeline host — enable when fetch path allows; revista PDF covers ZeroZero leads meanwhile." + }, { "id": "ihf_rss", "kind": "rss", @@ -44,7 +86,7 @@ "enabled": false, "maxItems": 25, "topics": ["pt", "sports", "media"], - "note": "Disabled BIT-22288: main Record feed mixes non-handball sports; shortlist is handball-tagged only. Re-enable only with a verified handball-only RSS (e.g. modalidades/andebol if Record publishes one)." + "note": "Disabled BIT-22288: main Record feed mixes non-handball sports; use record_andebol_html instead (BIT-25559)." }, { "id": "sapo_noticias", diff --git a/writer-pipeline/package-lock.json b/writer-pipeline/package-lock.json index 8fe9433..dfccedd 100644 --- a/writer-pipeline/package-lock.json +++ b/writer-pipeline/package-lock.json @@ -9,6 +9,7 @@ "version": "1.0.0", "dependencies": { "fastify": "^4.28.1", + "pdf-parse": "^1.1.1", "rss-parser": "^3.13.0" }, "devDependencies": { @@ -593,6 +594,15 @@ "node": ">= 0.6" } }, + "node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.1" + } + }, "node_modules/entities": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/entities/-/entities-2.2.0.tgz", @@ -838,6 +848,18 @@ "set-cookie-parser": "^2.4.1" } }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/node-ensure": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/node-ensure/-/node-ensure-0.0.0.tgz", + "integrity": "sha512-DRI60hzo2oKN1ma0ckc6nQWlHU69RH6xN0sjQTjMpChPfTYvKZdcQFfdYK2RWbJcKyUizSIy/l8OTGxMAM1QDw==", + "license": "MIT" + }, "node_modules/on-exit-leak-free": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz", @@ -847,6 +869,19 @@ "node": ">=14.0.0" } }, + "node_modules/pdf-parse": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/pdf-parse/-/pdf-parse-1.1.1.tgz", + "integrity": "sha512-v6ZJ/efsBpGrGGknjtq9J/oC8tZWq0KWL5vQrk2GlzLEQPUDB1ex+13Rmidl1neNN358Jn9EHZw5y07FFtaC7A==", + "license": "MIT", + "dependencies": { + "debug": "^3.1.0", + "node-ensure": "^0.0.0" + }, + "engines": { + "node": ">=6.8.1" + } + }, "node_modules/pino": { "version": "9.14.0", "resolved": "https://registry.npmjs.org/pino/-/pino-9.14.0.tgz", diff --git a/writer-pipeline/package.json b/writer-pipeline/package.json index d7574cf..d9aac82 100644 --- a/writer-pipeline/package.json +++ b/writer-pipeline/package.json @@ -17,6 +17,7 @@ }, "dependencies": { "fastify": "^4.28.1", + "pdf-parse": "^1.1.1", "rss-parser": "^3.13.0" }, "devDependencies": { diff --git a/writer-pipeline/src/html-listing.ts b/writer-pipeline/src/html-listing.ts new file mode 100644 index 0000000..53c273e --- /dev/null +++ b/writer-pipeline/src/html-listing.ts @@ -0,0 +1,78 @@ +/** + * Extract article URLs from HTML listing pages (Record/A Bola andebol sections). + */ + +const HREF_RE = /href=["']([^"']+)["']/gi; + +export interface ListingLinkOptions { + /** Keep links whose pathname includes any of these fragments */ + pathIncludes?: string[]; + /** Drop links whose pathname includes any of these fragments */ + pathExcludes?: string[]; + /** Drop links whose full URL matches any of these substrings (case-insensitive) */ + urlExcludes?: string[]; +} + +function normalizeHref(href: string, baseUrl: string): string | null { + const trimmed = href.trim(); + if (!trimmed || trimmed.startsWith('#') || trimmed.startsWith('javascript:')) return null; + try { + return new URL(trimmed, baseUrl).href; + } catch { + return null; + } +} + +function pathMatches(url: string, includes?: string[], excludes?: string[]): boolean { + try { + const path = new URL(url).pathname.toLowerCase(); + if (excludes?.some((frag) => path.includes(frag.toLowerCase()))) return false; + if (!includes?.length) return true; + return includes.some((frag) => path.includes(frag.toLowerCase())); + } catch { + return false; + } +} + +/** + * Scan listing HTML for unique article links matching path filters. + */ +export function extractListingLinks( + html: string, + listingUrl: string, + options: ListingLinkOptions = {}, +): string[] { + const seen = new Set(); + const out: string[] = []; + const urlExcludes = options.urlExcludes ?? []; + + let m: RegExpExecArray | null; + HREF_RE.lastIndex = 0; + while ((m = HREF_RE.exec(html)) !== null) { + const abs = normalizeHref(m[1], listingUrl); + if (!abs) continue; + const lower = abs.toLowerCase(); + if (urlExcludes.some((frag) => lower.includes(frag.toLowerCase()))) continue; + if (!pathMatches(abs, options.pathIncludes, options.pathExcludes)) continue; + if (seen.has(abs)) continue; + seen.add(abs); + out.push(abs); + } + return out; +} + +/** Human-readable title from a URL slug (fallback when article HTML is skipped). */ +export function titleFromArticleUrl(url: string): string { + try { + const path = new URL(url).pathname; + const slug = path.split('/').filter(Boolean).pop() ?? ''; + const base = slug.split('?')[0]; + if (!base) return 'Sem título'; + return base + .replace(/[-_]+/g, ' ') + .replace(/\b\w/g, (c) => c.toUpperCase()) + .trim(); + } catch { + return 'Sem título'; + } +} diff --git a/writer-pipeline/src/imprensa-ingest.test.ts b/writer-pipeline/src/imprensa-ingest.test.ts new file mode 100644 index 0000000..f477d23 --- /dev/null +++ b/writer-pipeline/src/imprensa-ingest.test.ts @@ -0,0 +1,97 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { + extractListingLinks, + titleFromArticleUrl, +} from './html-listing.js'; +import { + extractRevistaPdfUrls, + isHandballRevistaLead, + leadUrlForRevistaEntry, + parseRevistaIndexText, + publishedAtFromPtDate, + pdfDateFromRevistaUrl, + resolvePublisherUrl, +} from './revista-imprensa.js'; + +const RECORD_SNIPPET = ` +A +B +C +`; + +test('extractListingLinks keeps andebol detalhe URLs and drops iniciativas', () => { + const links = extractListingLinks(RECORD_SNIPPET, 'https://www.record.pt/modalidades/andebol', { + pathIncludes: ['/modalidades/andebol/detalhe/'], + pathExcludes: ['/iniciativas/'], + }); + assert.equal(links.length, 2); + assert.ok(links[0].includes('quatro-portugueses-nomeados')); + assert.ok(links[1].includes('benfica-oficializa-saida')); +}); + +test('titleFromArticleUrl humanizes slug', () => { + const title = titleFromArticleUrl( + 'https://www.record.pt/modalidades/andebol/detalhe/benfica-oficializa-saida-de-jota-gonzalez', + ); + assert.ok(title.toLowerCase().includes('benfica')); +}); + +test('parseRevistaIndexText extracts numbered index lines', () => { + const sample = ` +Revista de Imprensa +1. Marienses vence por falta de comparência do Afifense, Açoriano Oriental, 17/06/20261 +2. ANDEBOL - Portugueses nomeados para distinções europeias, Bola (A), 17/06/20262 +6. Académica fecha época no Arrabal, Diário de Coimbra, 17/06/20266 +18. ANDEBOL - EHF nomeia quarteto luso, Record, 17/06/202619 +A1 +`; + const entries = parseRevistaIndexText(sample); + assert.equal(entries.length, 4); + assert.equal(entries[1].title, 'ANDEBOL - Portugueses nomeados para distinções europeias'); + assert.equal(entries[1].source, 'Bola (A)'); + assert.equal(entries[3].source, 'Record'); +}); + +test('resolvePublisherUrl maps Record and A Bola', () => { + assert.equal(resolvePublisherUrl('Record Online'), 'https://www.record.pt/'); + assert.equal(resolvePublisherUrl('Bola (A)'), 'https://www.abola.pt/'); +}); + +test('leadUrlForRevistaEntry uses publisher host with stable path', () => { + const url = leadUrlForRevistaEntry('Record', 'https://portal.fpa.pt/media/x.pdf', { + index: 18, + title: 'EHF', + source: 'Record', + date: '17/06/2026', + }); + assert.ok(url.startsWith('https://www.record.pt/')); + assert.ok(url.includes('17-06-2026')); +}); + +test('extractRevistaPdfUrls finds absolute and relative PDF hrefs', () => { + const html = ` + x + y + `; + const urls = extractRevistaPdfUrls(html, 'https://portal.fpa.pt/media/'); + assert.equal(urls.length, 2); + assert.ok(urls[0].includes('18.06.2026')); +}); + +test('publishedAtFromPtDate parses DD/MM/YYYY', () => { + const iso = publishedAtFromPtDate('17/06/2026', '2026-01-01T00:00:00.000Z'); + assert.equal(iso.slice(0, 10), '2026-06-17'); +}); + +test('pdfDateFromRevistaUrl parses filename date', () => { + assert.equal( + pdfDateFromRevistaUrl('https://portal.fpa.pt/wp-content/uploads/2026/06/Revista-de-Imprensa-18.06.2026.pdf'), + '2026-06-18', + ); +}); + +test('isHandballRevistaLead detects andebol keywords', () => { + assert.equal(isHandballRevistaLead('Quatro andebolistas lusos', 'Golo FM'), true); + assert.equal(isHandballRevistaLead('Nuno Mendes otimista', 'Record'), false); +}); diff --git a/writer-pipeline/src/ingest-sources.ts b/writer-pipeline/src/ingest-sources.ts index 8d73068..9ba9ca5 100644 --- a/writer-pipeline/src/ingest-sources.ts +++ b/writer-pipeline/src/ingest-sources.ts @@ -1,7 +1,7 @@ import Parser from 'rss-parser'; import type { AggregatedItem, IngestSource, SiteSourcesConfig, SourceKind, StoreFile } from './types.js'; import { canonicalUrl, itemId, upsertItem } from './store.js'; -import { fetchTextWithRetry } from './http-retry.js'; +import { fetchBinaryWithRetry, fetchTextWithRetry } from './http-retry.js'; import { extractTitleAndSummary, extractFeaturedImageFromHtml, absolutizeImageUrl } from './html-meta.js'; import { isSitemapIndexXml, @@ -10,6 +10,15 @@ import { parseUrlsetEntries, type SitemapUrlEntry, } from './sitemap-parse.js'; +import { extractListingLinks, titleFromArticleUrl } from './html-listing.js'; +import { + extractRevistaPdfUrls, + isHandballRevistaLead, + leadUrlForRevistaEntry, + parseRevistaPdfBuffer, + pdfDateFromRevistaUrl, + publishedAtFromPtDate, +} from './revista-imprensa.js'; const parser = new Parser({ customFields: { @@ -266,6 +275,129 @@ export async function ingestAllSources( continue; } + if (kind === 'html_listing') { + attempted += 1; + try { + const html = await fetchTextWithRetry(source.url, { + timeoutMs, + retries, + accept: 'text/html, application/xhtml+xml, */*', + }); + const links = extractListingLinks(html, source.url, { + pathIncludes: source.pathIncludes, + pathExcludes: source.pathExcludes, + urlExcludes: source.urlExcludes, + }); + const maxItems = source.maxItems ?? 25; + const slice = links.slice(0, maxItems); + if (!slice.length) { + succeeded += 1; + errors.push(`html_listing ${source.id}: no article links after filters`); + continue; + } + const pageTimeoutMs = source.pageTimeoutMs ?? source.timeoutMs ?? 20000; + let ok = 0; + for (const link of slice) { + try { + const pageHtml = await fetchTextWithRetry(link, { + timeoutMs: pageTimeoutMs, + retries, + accept: 'text/html, application/xhtml+xml, */*', + }); + const { title, summary } = extractTitleAndSummary(pageHtml); + const img = extractFeaturedImageFromHtml(pageHtml); + const item = buildItem( + config.site, + source, + link, + title || titleFromArticleUrl(link), + summary || '(sem resumo)', + now, + now, + 'html_listing', + img.url ? { url: img.url, credit: img.credit } : undefined, + ); + const { store: next, isNew } = upsertItem(current, item); + current = next; + if (isNew) newItems += 1; + ok += 1; + } catch (e) { + const msg = e instanceof Error ? e.message : String(e); + errors.push(`html_listing ${source.id} page (${link}): ${msg}`); + } + } + if (ok > 0) succeeded += 1; + else failed += 1; + } catch (e) { + failed += 1; + const msg = e instanceof Error ? e.message : String(e); + errors.push(`html_listing ${source.id} (${source.url}): ${msg}`); + } + continue; + } + + if (kind === 'revista_imprensa') { + attempted += 1; + try { + const html = await fetchTextWithRetry(source.url, { + timeoutMs, + retries, + accept: 'text/html, application/xhtml+xml, */*', + }); + const pdfUrls = extractRevistaPdfUrls(html, source.url); + const maxPdfs = source.maxPdfs ?? 3; + const pdfs = pdfUrls.slice(0, maxPdfs); + if (!pdfs.length) { + succeeded += 1; + errors.push(`revista_imprensa ${source.id}: no Revista-de-Imprensa PDF links on page`); + continue; + } + let ok = 0; + for (const pdfUrl of pdfs) { + try { + const res = await fetchBinaryWithRetry(pdfUrl, { timeoutMs: source.pageTimeoutMs ?? 60000, retries }); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + const buf = Buffer.from(await res.arrayBuffer()); + const entries = await parseRevistaPdfBuffer(buf); + const pdfFileDate = pdfDateFromRevistaUrl(pdfUrl); + const pdfPublishedBase = + pdfFileDate ? `${pdfFileDate}T18:00:00.000Z` : now; + for (const entry of entries) { + const leadUrl = leadUrlForRevistaEntry(entry.source, pdfUrl, entry); + const publishedAt = pdfFileDate ? pdfPublishedBase : publishedAtFromPtDate(entry.date, now); + const summary = `Fonte: ${entry.source} (${entry.date}). Lead da Revista de Imprensa FPA — reescrever; não republicar PDF.`; + const item = buildItem( + config.site, + source, + leadUrl, + entry.title, + summary, + publishedAt, + now, + 'revista_imprensa', + ); + if (source.topics?.length) item.topics = [...source.topics]; + else item.topics = ['handball', 'pt', 'revista']; + const { store: next, isNew } = upsertItem(current, item); + current = next; + if (isNew) newItems += 1; + } + ok += 1; + } catch (e) { + const msg = e instanceof Error ? e.message : String(e); + errors.push(`revista_imprensa ${source.id} pdf (${pdfUrl}): ${msg}`); + } + } + if (ok > 0) succeeded += 1; + else failed += 1; + } catch (e) { + failed += 1; + const msg = e instanceof Error ? e.message : String(e); + errors.push(`revista_imprensa ${source.id} (${source.url}): ${msg}`); + } + continue; + } + if (kind === 'sitemap') { attempted += 1; try { diff --git a/writer-pipeline/src/revista-imprensa.ts b/writer-pipeline/src/revista-imprensa.ts new file mode 100644 index 0000000..02eaa74 --- /dev/null +++ b/writer-pipeline/src/revista-imprensa.ts @@ -0,0 +1,137 @@ +/** + * Parse FPA "Revista de Imprensa" press-clipping PDFs into story leads (BIT-25559). + * PDFs are ingested for metadata only — we do not republish the PDF. + */ + +import { createRequire } from 'node:module'; + +const require = createRequire(import.meta.url); +const pdfParse = require('pdf-parse') as (buffer: Buffer) => Promise<{ text?: string; numpages?: number }>; + +export interface RevistaEntry { + index: number; + title: string; + source: string; + date: string; +} + +const DATE_TAIL_RE = /,\s*(\d{2}\/\d{2}\/\d{4})\d*$/; +const ENTRY_START_RE = /^\s*(\d+)\.\s+/; + +/** Map clipping source labels to a PT publisher home URL (for dedup + bridge host diversity). */ +const SOURCE_HOST_MAP: Array<{ pattern: RegExp; url: string }> = [ + { pattern: /\brecord\b/i, url: 'https://www.record.pt/' }, + { pattern: /\bbola\b|\ba bola\b/i, url: 'https://www.abola.pt/' }, + { pattern: /\bzero\s*zero\b/i, url: 'https://www.zerozero.pt/' }, + { pattern: /\bjogo\b/i, url: 'https://www.record.pt/' }, + { pattern: /\bojogo\b/i, url: 'https://www.ojogo.pt/' }, + { pattern: /\bexpresso\b/i, url: 'https://expresso.pt/' }, + { pattern: /\bpublico\b|\bpúblico\b/i, url: 'https://www.publico.pt/' }, + { pattern: /\bdn\b|diário de notícias/i, url: 'https://www.dn.pt/' }, +]; + +const REVISTA_PDF_RE = + /https?:\/\/[^\s"'<>]*\/wp-content\/uploads\/[^"'<>]*Revista-de-Imprensa[^"'<>]*\.pdf/gi; +const REVISTA_PDF_REL_RE = /\/wp-content\/uploads\/[^"'<>]*Revista-de-Imprensa[^"'<>]*\.pdf/gi; + +export function resolvePublisherUrl(sourceLabel: string): string { + const label = sourceLabel.trim(); + for (const { pattern, url } of SOURCE_HOST_MAP) { + if (pattern.test(label)) return url; + } + return 'https://portal.fpa.pt/media/'; +} + +export function leadUrlForRevistaEntry( + sourceLabel: string, + pdfCanonicalUrl: string, + entry: RevistaEntry, +): string { + const base = resolvePublisherUrl(sourceLabel); + try { + const u = new URL(base); + u.pathname = `${u.pathname.replace(/\/$/, '')}/revista-imprensa/${entry.date.replace(/\//g, '-')}/${entry.index}`; + return u.href; + } catch { + return `${pdfCanonicalUrl}#item-${entry.index}`; + } +} + +export function parseRevistaIndexText(text: string): RevistaEntry[] { + const normalized = text.replace(/\r\n/g, '\n'); + const indexSection = normalized.split(/\n\s*A1\b/i)[0] ?? normalized; + const blocks = indexSection.split(/(?=^\s*\d+\.\s+)/m).filter((b) => ENTRY_START_RE.test(b)); + + const entries: RevistaEntry[] = []; + for (const block of blocks) { + const start = block.match(ENTRY_START_RE); + if (!start) continue; + const index = parseInt(start[1], 10); + let body = block.replace(ENTRY_START_RE, '').replace(/\s+/g, ' ').trim(); + body = body.replace(/\s+\d+\s*$/, '').trim(); + + const dateMatch = body.match(DATE_TAIL_RE); + if (!dateMatch) continue; + const date = dateMatch[1]; + const beforeDate = body.slice(0, dateMatch.index).trim(); + const lastComma = beforeDate.lastIndexOf(','); + if (lastComma < 0) continue; + const title = beforeDate.slice(0, lastComma).trim(); + const source = beforeDate.slice(lastComma + 1).trim(); + if (!title || !source) continue; + entries.push({ index, title, source, date }); + } + return entries; +} + +export function isHandballRevistaLead(title: string, source: string): boolean { + const hay = `${title} ${source}`.toLowerCase(); + return /andebol|handball|\behf\b|liga dos campeões de andebol|fpa\b/.test(hay); +} + +export function extractRevistaPdfUrls(html: string, pageUrl: string): string[] { + const seen = new Set(); + const out: string[] = []; + + const add = (raw: string) => { + try { + const href = new URL(raw, pageUrl).href; + if (!seen.has(href)) { + seen.add(href); + out.push(href); + } + } catch { + /* skip */ + } + }; + + let m: RegExpExecArray | null; + REVISTA_PDF_RE.lastIndex = 0; + while ((m = REVISTA_PDF_RE.exec(html)) !== null) add(m[0]); + + REVISTA_PDF_REL_RE.lastIndex = 0; + while ((m = REVISTA_PDF_REL_RE.exec(html)) !== null) add(m[0]); + + return out; +} + +export async function parseRevistaPdfBuffer(buffer: Buffer): Promise { + const data = await pdfParse(buffer); + const text = (data.text ?? '').trim(); + if (!text) return []; + return parseRevistaIndexText(text); +} + +export function pdfDateFromRevistaUrl(pdfUrl: string): string | null { + const m = pdfUrl.match(/Revista-de-Imprensa-(\d{2})\.(\d{2})\.(\d{4})\.pdf/i); + if (!m) return null; + return `${m[3]}-${m[2]}-${m[1]}`; +} + +export function publishedAtFromPtDate(date: string, fallback: string): string { + const m = date.match(/^(\d{2})\/(\d{2})\/(\d{4})$/); + if (!m) return fallback; + const iso = `${m[3]}-${m[2]}-${m[1]}T12:00:00.000Z`; + const d = new Date(iso); + return Number.isNaN(d.getTime()) ? fallback : d.toISOString(); +} diff --git a/writer-pipeline/src/types.ts b/writer-pipeline/src/types.ts index 77944d9..51d4195 100644 --- a/writer-pipeline/src/types.ts +++ b/writer-pipeline/src/types.ts @@ -1,4 +1,4 @@ -export type SourceKind = 'rss' | 'sitemap' | 'html_fetch'; +export type SourceKind = 'rss' | 'sitemap' | 'html_fetch' | 'html_listing' | 'revista_imprensa'; export interface IngestSource { id: string; @@ -9,8 +9,16 @@ export interface IngestSource { note?: string; /** Cap per-source items (RSS entries, sitemap URLs processed, or single html page). Default: 30 sitemap, 1 html_fetch; RSS uncapped if omitted */ maxItems?: number; - /** For sitemap: keep URLs whose path includes any of these substrings */ + /** For sitemap / html_listing: keep URLs whose path includes any of these substrings */ pathIncludes?: string[]; + /** For html_listing: drop URLs whose path includes any of these substrings */ + pathExcludes?: string[]; + /** For html_listing: drop URLs containing these substrings (e.g. sponsored blocks) */ + urlExcludes?: string[]; + /** For revista_imprensa: max recent PDFs to parse per run (default 3) */ + maxPdfs?: number; + /** For revista_imprensa: only store handball-scoped index lines (default true) */ + handballOnly?: boolean; retries?: number; /** Timeout for fetching the sitemap XML (and RSS/HTML source URL). */ timeoutMs?: number;