diff --git a/writer-pipeline/package.json b/writer-pipeline/package.json index d9aac82..8bc06db 100644 --- a/writer-pipeline/package.json +++ b/writer-pipeline/package.json @@ -13,7 +13,8 @@ "aggregator:dev": "tsx src/aggregator-server.ts", "cycle": "node dist/run-cycle.js", "cycle:dev": "tsx src/run-cycle.ts", - "backfill:featured": "node dist/backfill-featured-from-fpa.js" + "backfill:featured": "node dist/backfill-featured-from-fpa.js", + "backfill:featured-smart": "node dist/backfill-featured-smart.js" }, "dependencies": { "fastify": "^4.28.1", diff --git a/writer-pipeline/src/backfill-featured-smart.ts b/writer-pipeline/src/backfill-featured-smart.ts new file mode 100644 index 0000000..f832eeb --- /dev/null +++ b/writer-pipeline/src/backfill-featured-smart.ts @@ -0,0 +1,332 @@ +/** + * Smart backfill: attach featured images to andebol.net posts using source URL extraction. + * + * Strategy: + * 1. Fetch WP posts without featured_media (with content) + * 2. Extract source URL from post content (FPA, IHF, EHF, Handball-Planet links) + * 3. For FPA sources: query FPA WP API for the article's featured image + * 4. For other sources: scrape og:image from the source page HTML + * 5. For FPA posts without source URL: title-based search on FPA API + * 6. Upload image to WP and set featured_media + * + * Usage: + * node dist/backfill-featured-smart.js [--dry-run] [--limit N] [--post-id N] [--skip-sourceless] + * + * Requires ANDEBOL_WP_USER + ANDEBOL_WP_APP_PASSWORD (see wp-site-env.ts). + * Optional: WRITER_WEBDAV_* for WebDAV archive fallback. + */ + +import { attachFeaturedImageToPost, type WpPublishConfig } from './wp-publish.js'; +import { wpCredentialsForSite } from './wp-site-env.js'; +import { fetchArticleHtmlForMeta } from './legacy-fetch.js'; +import { absolutizeImageUrl, extractFeaturedImageFromHtml } from './html-meta.js'; +import { readWebDavArchiveFromEnv, resolveFeaturedFromWebDavArchive } from './webdav-archive.js'; + +const FPA_WP_BASE = 'https://portal.fpa.pt/wp-json'; +const SITE_DOMAIN = 'andebol.net'; + +function argFlag(name: string, argv: string[]): boolean { + return argv.includes(name); +} + +function argValue(name: string, argv: string[]): string | undefined { + const i = argv.indexOf(name); + return i >= 0 ? argv[i + 1] : undefined; +} + +function wpHeaders(cfg: WpPublishConfig): Record { + const auth = Buffer.from(`${cfg.username}:${cfg.appPassword}`, 'utf8').toString('base64'); + const h: Record = { + Accept: 'application/json', + Authorization: `Basic ${auth}`, + }; + if (cfg.siteDomain) h['X-Site-Domain'] = cfg.siteDomain; + return h; +} + +function toPublishConfig(creds: ReturnType): WpPublishConfig { + return { + wpBase: creds.wpBase, + username: creds.wpUser, + appPassword: creds.wpPass, + siteDomain: creds.siteDomain ?? SITE_DOMAIN, + }; +} + +interface WpPostRow { + id: number; + slug: string; + status: string; + featured_media: number; + title: { rendered: string }; + content: { rendered: string }; +} + +/** Extract source URLs from post content HTML */ +function extractSourceUrls(html: string): { fpa: string[]; other: string[] } { + const fpa: string[] = []; + const other: string[] = []; + const hrefRe = /href="(https?:\/\/[^"]+)"/gi; + let m: RegExpExecArray | null; + while ((m = hrefRe.exec(html)) !== null) { + const url = m[1]; + if (/portal\.fpa\.pt/.test(url) && !/\/feed\/?$/.test(url)) { + fpa.push(url); + } else if (!/andebol\.net/.test(url) && !/wordpress\.org/.test(url)) { + other.push(url); + } + } + return { + fpa: [...new Set(fpa)], + other: [...new Set(other)], + }; +} + +async function listPostsMissingFeatured(cfg: WpPublishConfig, limit: number): Promise { + const base = cfg.wpBase.replace(/\/$/, ''); + const out: WpPostRow[] = []; + let page = 1; + while (out.length < limit) { + const qs = new URLSearchParams({ + per_page: '100', + page: String(page), + status: 'publish', + _fields: 'id,slug,featured_media,status,content,title', + }); + const res = await fetch(`${base}/wp/v2/posts?${qs}`, { + headers: wpHeaders(cfg), + signal: AbortSignal.timeout(20_000), + }); + if (!res.ok) throw new Error(`WP list posts ${res.status}: ${await res.text().catch(() => '')}`); + const rows = (await res.json()) as WpPostRow[]; + if (rows.length === 0) break; + for (const row of rows) { + if (!row.featured_media && row.status === 'publish') { + out.push(row); + } + if (out.length >= limit) break; + } + if (rows.length < 100) break; + page += 1; + } + return out; +} + +/** Fetch FPA featured image by article URL (not slug) */ +async function fpaFeaturedForUrl(fpaUrl: string): Promise<{ url: string; credit?: string } | null> { + const parsed = new URL(fpaUrl); + const pathParts = parsed.pathname.replace(/^\/|\/$/g, '').split('/'); + const slug = pathParts[pathParts.length - 1] || pathParts[pathParts.length - 2]; + if (!slug) return null; + + const qs = new URLSearchParams({ slug, _embed: 'wp:featuredmedia' }); + const res = await fetch(`${FPA_WP_BASE}/wp/v2/posts?${qs}`, { + headers: { Accept: 'application/json' }, + signal: AbortSignal.timeout(15_000), + }); + if (!res.ok) return null; + const rows = (await res.json()) as Array<{ + link?: string; + _embedded?: { 'wp:featuredmedia'?: Array<{ source_url?: string; alt_text?: string }> }; + }>; + const match = rows.find(r => r.link && r.link.replace(/\/$/, '') === fpaUrl.replace(/\/$/, '')); + const row = match ?? rows[0]; + const media = row?._embedded?.['wp:featuredmedia']?.[0]; + const url = media?.source_url?.trim(); + if (!url) return null; + return { url, credit: media?.alt_text?.trim() || undefined }; +} + +/** Search FPA by title keywords */ +async function fpaFeaturedForTitle(title: string): Promise<{ url: string; credit?: string } | null> { + const clean = title + .replace(/<[^>]+>/g, '') + .replace(/[^\wÀ-ÿ\s]/g, ' ') + .replace(/\s+/g, ' ') + .trim(); + const search = clean.split(/\s+/).slice(0, 6).join('+'); + const qs = new URLSearchParams({ search, per_page: '5', _embed: 'wp:featuredmedia' }); + const res = await fetch(`${FPA_WP_BASE}/wp/v2/posts?${qs}`, { + headers: { Accept: 'application/json' }, + signal: AbortSignal.timeout(15_000), + }); + if (!res.ok) return null; + const rows = (await res.json()) as Array<{ + _embedded?: { 'wp:featuredmedia'?: Array<{ source_url?: string; alt_text?: string }> }; + }>; + if (rows.length === 0) return null; + const media = rows[0]._embedded?.['wp:featuredmedia']?.[0]; + const url = media?.source_url?.trim(); + if (!url) return null; + return { url, credit: media?.alt_text?.trim() || undefined }; +} + +/** Scrape og:image from a non-FPA source URL */ +async function scrapeFeaturedFromUrl(sourceUrl: string): Promise<{ url: string; credit?: string } | null> { + const html = await fetchArticleHtmlForMeta(sourceUrl); + if (!html) return null; + const parsed = extractFeaturedImageFromHtml(html); + if (!parsed.url) return null; + const abs = absolutizeImageUrl(parsed.url, sourceUrl); + if (!abs) return null; + return { url: abs, credit: parsed.credit }; +} + +async function main(): Promise { + const argv = process.argv.slice(2); + const dryRun = argFlag('--dry-run', argv); + const limit = Math.max(1, parseInt(argValue('--limit', argv) ?? '200', 10)); + const postIdFilter = argValue('--post-id', argv) ? parseInt(argValue('--post-id', argv)!, 10) : undefined; + const skipSourceless = argFlag('--skip-sourceless', argv); + + const creds = wpCredentialsForSite('andebol.net'); + if (!creds.wpUser || !creds.wpPass) { + console.error(`Missing credentials: set ${creds.envHint}`); + process.exit(1); + } + const cfg = toPublishConfig(creds); + + let webDavCfg = null; + try { + webDavCfg = readWebDavArchiveFromEnv(); + } catch { + // WebDAV not configured — that's fine + } + + console.log(`=== Smart Backfill: Featured Images for andebol.net ===`); + console.log(`Mode: ${dryRun ? 'DRY-RUN' : 'LIVE'}`); + console.log(`WebDAV: ${webDavCfg ? 'configured' : 'not configured'}`); + console.log(); + + const posts = await listPostsMissingFeatured(cfg, limit); + console.log(`Published posts without featured_media: ${posts.length}\n`); + + let updated = 0; + let skipped = 0; + let failed = 0; + const errors: string[] = []; + + for (const post of posts) { + if (postIdFilter && post.id !== postIdFilter) continue; + + const title = post.title.rendered.replace(/<[^>]+>/g, '').trim(); + console.log(`\n[${post.id}] ${post.slug}`); + console.log(` Title: ${title.slice(0, 80)}${title.length > 80 ? '…' : ''}`); + + const content = post.content?.rendered || ''; + const sources = extractSourceUrls(content); + let imageUrl: string | undefined; + let imageCredit: string | undefined; + let imageSource = 'none'; + + if (sources.fpa.length > 0) { + const fpaUrl = sources.fpa[0]; + console.log(` Source (FPA): ${fpaUrl}`); + const featured = await fpaFeaturedForUrl(fpaUrl); + if (featured) { + imageUrl = featured.url; + imageCredit = featured.credit; + imageSource = 'fpa-url'; + console.log(` → Found FPA featured image: ${featured.url.slice(0, 70)}…`); + } else { + console.log(` → FPA article has no featured image`); + } + } + + if (!imageUrl && sources.other.length > 0) { + for (const srcUrl of sources.other.slice(0, 3)) { + console.log(` Source (other): ${srcUrl}`); + const featured = await scrapeFeaturedFromUrl(srcUrl); + if (featured) { + imageUrl = featured.url; + imageCredit = featured.credit ?? imageCredit; + imageSource = 'og-image'; + console.log(` → Found og:image: ${featured.url.slice(0, 70)}…`); + break; + } + } + } + + if (!imageUrl && !sources.fpa.length && !sources.other.length) { + const looksPortuguese = + /[àáâãéêíóôõúüç]/i.test(title) || + /\b(e|de|do|da|no|na|em|para|com|por|segu|campe|selec|nacional|andebol)\b/i.test(title); + if (looksPortuguese && !skipSourceless) { + console.log(` Trying FPA title search for: ${title.slice(0, 50)}`); + const featured = await fpaFeaturedForTitle(title); + if (featured) { + imageUrl = featured.url; + imageCredit = featured.credit; + imageSource = 'fpa-title'; + console.log(` → Found via FPA title search: ${featured.url.slice(0, 70)}…`); + } + } + + if (!imageUrl && webDavCfg && !skipSourceless) { + console.log(` Trying WebDAV archive`); + try { + const davResult = await resolveFeaturedFromWebDavArchive(webDavCfg, { + id: `backfill-${post.id}`, + site: 'andebol.net', + title, + url: `https://andebol.net/${post.slug}/`, + sourceFeedId: 'backfill', + summary: '', + publishedAt: new Date().toISOString(), + ingestedAt: new Date().toISOString(), + }); + imageUrl = davResult.url; + imageCredit = davResult.credit; + imageSource = 'webdav'; + console.log(` → Found WebDAV image: ${davResult.url.slice(0, 70)}…`); + } catch (e) { + console.log(` → WebDAV: ${e instanceof Error ? e.message : String(e)}`); + } + } + } + + if (!imageUrl && /^(html|bit-|test)/i.test(post.slug)) { + console.log(` → Skipping test/html post`); + skipped += 1; + continue; + } + + if (!imageUrl) { + console.log( + skipSourceless ? ` → No image found (skip-sourceless)` : ` → No image found from any source`, + ); + skipped += 1; + continue; + } + + if (dryRun) { + console.log(` → [DRY-RUN] Would attach: ${imageUrl.slice(0, 80)}…`); + updated += 1; + continue; + } + + try { + const mediaId = await attachFeaturedImageToPost(post.id, imageUrl, cfg, imageCredit); + updated += 1; + console.log(` → OK: media_id=${mediaId} (source: ${imageSource})`); + } catch (e) { + const msg = e instanceof Error ? e.message : String(e); + errors.push(`${post.slug}: ${msg}`); + console.error(` → FAIL: ${msg}`); + failed += 1; + } + } + + console.log(`\n=== BACKFILL SUMMARY ===`); + console.log(JSON.stringify({ total: posts.length, updated, skipped, failed, dryRun }, null, 2)); + + if (errors.length > 0) { + console.error(`\nErrors:\n${errors.join('\n')}`); + process.exit(1); + } +} + +main().catch(e => { + console.error(e); + process.exit(1); +});