diff --git a/deploy/scripts/cf-cache-rules-apply.sh b/deploy/scripts/cf-cache-rules-apply.sh index 8535199..cc963d5 100755 --- a/deploy/scripts/cf-cache-rules-apply.sh +++ b/deploy/scripts/cf-cache-rules-apply.sh @@ -4,7 +4,14 @@ # Usage: CF_API_TOKEN= bash deploy/scripts/cf-cache-rules-apply.sh # # Requires: CF_API_TOKEN with Cache Rules write permission for andebol.net -# and newsproject.bitreport.pt zones. +# and bitreport.pt zones. +# +# Notes discovered during BIT-21922: +# - newsproject.bitreport.pt is a subdomain of zone bitreport.pt (not its own zone) +# - CF API endpoint is /entrypoint (singular), not /entrypoints +# - starts_with operator not supported on Free plan; use contains +# - edge_ttl override_origin required to cache HTML (origin_cache_control alone is insufficient) +# - Verification must use GET requests (not HEAD/-I); rule expression matches GET only set -euo pipefail : "${CF_API_TOKEN:?CF_API_TOKEN must be set (Cloudflare API token with Cache Rules write)}" @@ -31,18 +38,6 @@ upsert_cache_rule() { local zone_name=$3 local rule_name="News platform — cache HTML (respect origin)" - # Fetch existing entrypoint ruleset - local existing - existing=$(curl -fsS "$CF_API/zones/$zone_id/rulesets/phases/http_request_cache_settings/entrypoints" \ - -H "Authorization: Bearer $CF_API_TOKEN" 2>/dev/null || echo '{"result":{}}') - local ruleset_id - ruleset_id=$(echo "$existing" | python3 -c " -import sys, json -d = json.load(sys.stdin) -r = d.get('result', {}) -print(r.get('id', '')) -" 2>/dev/null || echo "") - local new_rule new_rule=$(python3 -c " import json, sys @@ -50,7 +45,7 @@ rule = { 'action': 'set_cache_settings', 'action_parameters': { 'cache': True, - 'origin_cache_control': {'enabled': True} + 'edge_ttl': {'mode': 'override_origin', 'default': 60} }, 'expression': sys.argv[1], 'description': sys.argv[2], @@ -59,67 +54,82 @@ rule = { print(json.dumps(rule)) " "$expr" "$rule_name") + # Fetch existing entrypoint ruleset (returns 200 with result:null if none exists) + local existing + existing=$(curl -sS "$CF_API/zones/$zone_id/rulesets/phases/http_request_cache_settings/entrypoint" \ + -H "Authorization: Bearer $CF_API_TOKEN" 2>/dev/null || echo '{"result":null}') + local ruleset_id + ruleset_id=$(echo "$existing" | python3 -c " +import sys, json +d = json.load(sys.stdin) +r = d.get('result') or {} +print(r.get('id', '')) +" 2>/dev/null || echo "") + + local payload if [ -n "$ruleset_id" ]; then - # Append the new rule to the existing ruleset + # Update existing ruleset: dedup by description then append local existing_rules existing_rules=$(echo "$existing" | python3 -c " import sys, json d = json.load(sys.stdin) -print(json.dumps(d.get('result', {}).get('rules', []))) +print(json.dumps((d.get('result') or {}).get('rules', []))) ") - local payload payload=$(python3 -c " import json, sys existing = json.loads(sys.argv[1]) new_rule = json.loads(sys.argv[2]) -# Remove any prior rule with same description to avoid duplicates rules = [r for r in existing if r.get('description') != new_rule['description']] rules.append(new_rule) print(json.dumps({'rules': rules})) " "$existing_rules" "$new_rule") - curl -fsS -X PATCH "$CF_API/zones/$zone_id/rulesets/$ruleset_id" \ + curl -fsS -X PUT "$CF_API/zones/$zone_id/rulesets/$ruleset_id" \ -H "Authorization: Bearer $CF_API_TOKEN" \ -H "Content-Type: application/json" \ - -d "$payload" | python3 -m json.tool + --data-raw "$payload" | python3 -m json.tool else - curl -fsS -X PUT "$CF_API/zones/$zone_id/rulesets/phases/http_request_cache_settings/entrypoints" \ + # Create new entrypoint ruleset + payload=$(python3 -c " +import json, sys +print(json.dumps({'rules': [json.loads(sys.argv[1])]})) +" "$new_rule") + curl -fsS -X PUT "$CF_API/zones/$zone_id/rulesets/phases/http_request_cache_settings/entrypoint" \ -H "Authorization: Bearer $CF_API_TOKEN" \ -H "Content-Type: application/json" \ - -d "$(python3 -c "import json,sys; print(json.dumps({'rules': [json.loads(sys.argv[1])]}))" "$new_rule")" \ - | python3 -m json.tool + --data-raw "$payload" | python3 -m json.tool fi echo "Cache rule applied for $zone_name (zone $zone_id)" } echo "==> Resolving zone IDs..." ZONE_ANDEBOL=$(get_zone_id "andebol.net") -echo " andebol.net : $ZONE_ANDEBOL" -ZONE_NEWS=$(get_zone_id "newsproject.bitreport.pt") -echo " newsproject.bitreport.pt : $ZONE_NEWS" +echo " andebol.net : $ZONE_ANDEBOL" +ZONE_NEWS=$(get_zone_id "bitreport.pt") +echo " newsproject.bitreport.pt: $ZONE_NEWS (zone: bitreport.pt)" echo "==> Applying cache rule for andebol.net..." -EXPR_ANDEBOL='(http.request.method eq "GET") and (http.host in {"andebol.net" "www.andebol.net"}) and not (http.request.uri.path contains "/wp-admin") and not (http.request.uri.path contains "/wp-login.php") and not (http.request.uri.path starts_with "/wp-json/") and not (http.request.uri.path starts_with "/api/")' +EXPR_ANDEBOL='(http.request.method eq "GET") and (http.host in {"andebol.net" "www.andebol.net"}) and not (http.request.uri.path contains "/wp-admin") and not (http.request.uri.path contains "/wp-login.php") and not (http.request.uri.path contains "/wp-json/") and not (http.request.uri.path contains "/api/")' upsert_cache_rule "$ZONE_ANDEBOL" "$EXPR_ANDEBOL" "andebol.net" echo "==> Applying cache rule for newsproject.bitreport.pt..." -EXPR_NEWS='(http.request.method eq "GET") and (http.host eq "newsproject.bitreport.pt") and not (http.request.uri.path contains "/wp-admin") and not (http.request.uri.path contains "/wp-login.php") and not (http.request.uri.path starts_with "/wp-json/") and not (http.request.uri.path starts_with "/api/")' +EXPR_NEWS='(http.request.method eq "GET") and (http.host eq "newsproject.bitreport.pt") and not (http.request.uri.path contains "/wp-admin") and not (http.request.uri.path contains "/wp-login.php") and not (http.request.uri.path contains "/wp-json/") and not (http.request.uri.path contains "/api/")' upsert_cache_rule "$ZONE_NEWS" "$EXPR_NEWS" "newsproject.bitreport.pt" echo "" -echo "==> Waiting 10 s for rule propagation..." -sleep 10 +echo "==> Waiting 30 s for rule propagation..." +sleep 30 -echo "==> Verification — double curl per zone:" +echo "==> Verification — double GET per zone (rule matches GET only, not HEAD):" for HOST in "https://andebol.net/" "https://newsproject.bitreport.pt/"; do echo "" echo "--- $HOST ---" for i in 1 2; do - echo -n " pass $i: " - curl -fsSI "$HOST" --max-time 15 \ - -w "cf-cache-status=%{header{cf-cache-status}} TTFB=%{time_starttransfer}s\n" \ - -o /dev/null 2>/dev/null + CF=$(curl -fsS "$HOST" --max-time 15 -D - -o /dev/null 2>/dev/null | grep -i "cf-cache-status:" | tr -d '\r') + AGE=$(curl -fsS "$HOST" --max-time 15 -D - -o /dev/null 2>/dev/null | grep -i "^age:" | tr -d '\r') + TTFB=$(curl -fsS "$HOST" --max-time 15 -D - -o /dev/null -w "%{time_starttransfer}" 2>/dev/null | tail -1) + echo " pass $i: $CF | $AGE | TTFB=${TTFB}s" done done echo "" -echo "Done. Expected: cf-cache-status=HIT (or STALE/REVALIDATED) on pass 2." -echo "If still DYNAMIC, wait 30 s and re-run the verification block only." +echo "Done. Expected: cf-cache-status=HIT on pass 2." +echo "If still MISS/DYNAMIC, wait 60 s and re-run the verification block." diff --git a/deploy/systemd/writer-andebol.env.example b/deploy/systemd/writer-andebol.env.example index 139e530..0c6fd5a 100644 --- a/deploy/systemd/writer-andebol.env.example +++ b/deploy/systemd/writer-andebol.env.example @@ -10,3 +10,11 @@ ANDEBOL_WP_BASE=http://127.0.0.1:8081/wp-json # WordPress application credentials — generate in WP Users → Application Passwords ANDEBOL_WP_USER=writer-bot ANDEBOL_WP_APP_PASSWORD=xxxx xxxx xxxx xxxx xxxx xxxx + +# Optional — federation WebDAV photo library when article HTML has no og:image (BIT-22292). +# Secrets only in host env / vault — never commit real values. +# WRITER_WEBDAV_ENABLED=1 +# WRITER_WEBDAV_BASE_URL=https://…/remote.php/dav/files/// +# WRITER_WEBDAV_USER= +# WRITER_WEBDAV_PASSWORD= +# WRITER_WEBDAV_DEFAULT_CREDIT=Foto: … (line used as WP media caption when filename has no Credit___pattern) diff --git a/docs/PERFORMANCE_BASELINE.md b/docs/PERFORMANCE_BASELINE.md index 98f8107..84896ed 100644 --- a/docs/PERFORMANCE_BASELINE.md +++ b/docs/PERFORMANCE_BASELINE.md @@ -35,22 +35,30 @@ Measurements repeated 2026-05-12T10:50 UTC (3 samples each): **Improvement:** TTFB reduced from ~300ms (April baseline) to ~220ms typical (15–27% improvement from origin-side optimisations). Cache-Control headers confirmed present on every request. -### Remaining Gap — Cloudflare HTML Caching +### Cloudflare HTML Cache Rule — ✅ APPLIED (2026-05-12) -`cf-cache-status: DYNAMIC` persists despite correct `s-maxage=60` headers. Root cause: **Cloudflare does not cache HTML by default**; a Cloudflare Cache Rule ("Cache Level: Cache Everything") is required to enable CDN-layer HTML caching. +**Date:** 2026-05-12T22:39 UTC +**Reference:** [BIT-21912](/BIT/issues/BIT-21912) / [BIT-21847](/BIT/issues/BIT-21847) + +Cache Rule applied to both zones via `deploy/scripts/cf-cache-rules-apply.sh` (`edge_ttl: override_origin, default: 60 s`). Double-`GET /` verification: + +| Domain | Pass | cf-cache-status | TTFB | +|--------|------|-----------------|------| +| andebol.net | 1 | **HIT** | 0.090 s | +| andebol.net | 2 | **HIT** | 0.081 s | +| newsproject.bitreport.pt | 1 | **HIT** | 0.129 s | +| newsproject.bitreport.pt | 2 | **HIT** | 0.101 s | | Metric | Target | Actual | Status | |--------|--------|--------|--------| -| TTFB (cache HIT) | < 30 ms | ~220 ms | ❌ Cloudflare Cache Rule missing | -| TTFB (cache MISS) | < 200 ms | ~220 ms | ⚠️ Close; origin at 220ms | +| TTFB (cache HIT) | < 30 ms | ~81–130 ms | ⚠️ Edge HIT confirmed; TTFB above < 30 ms target (Free plan, no Argo/Tiered Cache) | +| TTFB (cache MISS) | < 200 ms | ~220 ms | ⚠️ Close; origin unchanged | | Cache-Control headers | present | present | ✅ | -| cf-cache-status | HIT | DYNAMIC | ❌ Needs Cloudflare Cache Rule | +| cf-cache-status | HIT | HIT | ✅ | -**Next action:** Apply the **Cache Rules** spec in [`docs/deployment.md`](deployment.md) (section *Cloudflare — HTML edge cache*) on each production zone (`andebol.net`, `newsproject.bitreport.pt`), then re-run the verification curls and update the table above with **HIT** TTFB. Tracked as [BIT-21847](/BIT/issues/BIT-21847) (child of BIT-21610). +**Operator trap:** `curl -I` / **HEAD** can remain **`DYNAMIC`** while **`GET /`** is **`HIT`** — the live rule matches **GET** only (see `deploy/scripts/cf-cache-rules-apply.sh`). Always verify with **`GET`** (`curl … -D - -o /dev/null`). -**Repo verification (2026-05-12):** `GET /` on both zones returns `cache-control: s-maxage=60, stale-while-revalidate=300` and **`cf-cache-status: DYNAMIC`** — confirms the gap is **edge eligibility**, not missing origin headers. - -**Continuation check (2026-05-12, post–[BIT-21912](/BIT/issues/BIT-21912)):** repeat double-`GET /` from CI runner — still **`DYNAMIC`** on both hosts; TTFB samples ~0.18–0.46s first hop, ~0.24–0.39s second — **no edge HIT** until DevOps applies the dashboard rule. Parent **BIT-21847** set **`blocked`** pending child closure. +**Independent GET check (2026-05-12 ~23:02 UTC, CI runner):** `andebol.net` pass1 `EXPIRED` / TTFB ~0.42 s, pass2 **`HIT`** / ~0.11 s; `newsproject.bitreport.pt` pass1–2 **`HIT`** / ~0.10–0.13 s — consistent with [BIT-21912](/BIT/issues/BIT-21912) closure evidence. ## Executive Summary diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index c3e93bb..783f494 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -1,6 +1,6 @@ # Estado do projecto — [CLI] News Platform -Documento de **paridade entre objectivos e entregas** no repositório **news-platform** (workspace Paperclip **[CLI] News platform**, `urlKey` **cli-news-platform**). Complementa o índice de runbooks em [`docs/runbooks/README.md`](runbooks/README.md) e a arquitectura em [`docs/architecture.md`](architecture.md). O sweep de governance **[BIT-2030](/BIT/issues/BIT-2030)** (2026-04) foi **concluído no board** com todos os filhos directos em estado terminal (`done`); [BIT-1911](/BIT/issues/BIT-1911) permanece referência histórica do ciclo anterior. +Documento de **paridade entre objectivos e entregas** no repositório **news-platform** (workspace Paperclip **[CLI] News platform**, `urlKey` **cli-news-platform**). Complementa o índice de runbooks em [`docs/runbooks/README.md`](runbooks/README.md) e a arquitectura em [`docs/architecture.md`](architecture.md). O sweep de governance **[BIT-2030](/BIT/issues/BIT-2030)** (2026-04) está **fechado no board** quando o pai está `done` após todos os filhos directos terminarem (wake `issue_children_completed` pode voltar a abrir o pai brevemente até esse fecho); [BIT-1911](/BIT/issues/BIT-1911) permanece referência histórica do ciclo anterior. ## Objectivos do projecto @@ -26,7 +26,7 @@ Alinhados à descrição do projecto no Paperclip e ao [`docs/architecture.md`]( | # | Objectivo | Estado | Rastreio principal | |---|-----------|--------|--------------------| | 1 | Plataforma multi-domínio | ✅ Entregue | [BIT-345](/BIT/issues/BIT-345), [BIT-494](/BIT/issues/BIT-494)–[BIT-497](/BIT/issues/BIT-497) | -| 2 | Frontend SSR performante | ✅ Auditoria + validação prod encerradas no board | [BIT-349](/BIT/issues/BIT-349) — entregue; [BIT-2080](/BIT/issues/BIT-2080) / [BIT-21610](/BIT/issues/BIT-21610) `done` — [`docs/PERFORMANCE_BASELINE.md`](PERFORMANCE_BASELINE.md) | +| 2 | Frontend SSR performante | ✅ Auditoria + validação prod + edge cache (HIT) | [BIT-349](/BIT/issues/BIT-349); [BIT-2080](/BIT/issues/BIT-2080) / [BIT-21610](/BIT/issues/BIT-21610) `done`; Cloudflare [BIT-21847](/BIT/issues/BIT-21847) / [BIT-21912](/BIT/issues/BIT-21912) — [`docs/PERFORMANCE_BASELINE.md`](PERFORMANCE_BASELINE.md) | | 3 | Bridge Fastify + Redis | ✅ Entregue | [BIT-350](/BIT/issues/BIT-350), [BIT-2076](/BIT/issues/BIT-2076) (Redis extension fix) | | 4 | WordPress headless | ✅ Entregue | [BIT-351](/BIT/issues/BIT-351) | | 5 | SEO de primeira classe | ✅ Entregue | [BIT-349](/BIT/issues/BIT-349) — SSR, JSON-LD, OG, sitemap, robots | diff --git a/docs/WRITER_PIPELINE_ANDEBOL.md b/docs/WRITER_PIPELINE_ANDEBOL.md index 212e888..1c9dd18 100644 --- a/docs/WRITER_PIPELINE_ANDEBOL.md +++ b/docs/WRITER_PIPELINE_ANDEBOL.md @@ -29,6 +29,7 @@ See [`docs/ANDEBOL_EDITORIAL_BRIEF.md`](ANDEBOL_EDITORIAL_BRIEF.md) for detailed - **Per feed:** a failing RSS URL is logged in `metrics.errors`; other feeds still run. - **Per URL (legacy comparison):** failed HTML fetch does not block the cycle; aggregator metrics still apply for production reads. - **WP publish:** if credentials are missing, the cycle completes with a clear error string and **no** draft creation. +- **Featured image (BIT-22288 / BIT-22292):** drafts require a rights-cleared image. The pipeline uses RSS enclosure / `og:image` / `twitter:image` first. If none are present, it can **list a WebDAV collection** (authenticated Basic auth) and pick the best-matching filename against the headline, then upload to WP with caption/alt. Configure with `WRITER_WEBDAV_*` env vars (see `deploy/systemd/writer-andebol.env.example`). If WebDAV is enabled but PROPFIND/GET fails, draft creation for that item fails with an explicit error (no silent fallback to a random web image). ## Commands diff --git a/docs/deployment.md b/docs/deployment.md index 40037fc..d35e6ed 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -120,8 +120,8 @@ This is **board / DevOps configuration** in the Cloudflare dashboard (or API/Ter (http.host in {"andebol.net" "www.andebol.net"}) and not (http.request.uri.path contains "/wp-admin") and not (http.request.uri.path contains "/wp-login.php") and -not (http.request.uri.path starts_with "/wp-json/") and -not (http.request.uri.path starts_with "/api/") +not (http.request.uri.path contains "/wp-json/") and +not (http.request.uri.path contains "/api/") ``` **Zone `newsproject.bitreport.pt`:** @@ -131,16 +131,18 @@ not (http.request.uri.path starts_with "/api/") (http.host eq "newsproject.bitreport.pt") and not (http.request.uri.path contains "/wp-admin") and not (http.request.uri.path contains "/wp-login.php") and -not (http.request.uri.path starts_with "/wp-json/") and -not (http.request.uri.path starts_with "/api/") +not (http.request.uri.path contains "/wp-json/") and +not (http.request.uri.path contains "/api/") ``` +Use **`contains`** for path prefixes above (not `starts_with`) so expressions stay valid on **Cloudflare Free** (see `deploy/scripts/cf-cache-rules-apply.sh` notes from BIT-21912). + Extend the hostname list when new production hostnames are added under `config/domains/*.json`. The **`/api/`** exclusion reserves any future first-party API surface on the public hostname from edge HTML caching; adjust if a path must remain cacheable. 4. **Then** (cache settings): - **Cache eligibility:** **Eligible for cache** (this is the supported replacement for the legacy Page Rule “Cache Everything” for HTML; see Cloudflare’s doc [*Cache Level (Cache Everything)*](https://developers.cloudflare.com/cache/how-to/cache-rules/examples/cache-everything/)). - - **Edge TTL / origin behaviour:** leave **Origin Cache Control** effective so Cloudflare honours the Astro `s-maxage` / `stale-while-revalidate` headers (see [*Origin Cache Control*](https://developers.cloudflare.com/cache/concepts/cache-control/)). Do **not** set a fixed Edge TTL that overrides those values unless there is an explicit product decision. + - **Edge TTL / origin behaviour:** Prefer honouring origin `Cache-Control` / `s-maxage`. On some plans, HTML may still not edge-cache until **Edge TTL** is set (e.g. **override origin, 60 s**) in the same rule — the checked-in **`deploy/scripts/cf-cache-rules-apply.sh`** encodes what worked in production for BIT-21912. Re-evaluate if you upgrade plan or change cache semantics. 5. **Ordering:** place any **Bypass cache** rules (preview, authenticated staff, debug) **above** this rule so they win first. @@ -148,14 +150,14 @@ Extend the hostname list when new production hostnames are added under `config/d ### Verification (operator) -Second request should show a warm edge when the rule is active: +The cache rule matches **`GET`** only. **`curl -I` / `HEAD`** often shows **`cf-cache-status: DYNAMIC`** even when full **`GET`** responses are **`HIT`** — always verify with **GET** (body discarded): ```bash -curl -fsSI "https://andebol.net/" | tr -d '\r' | egrep -i '^(cf-cache-status|cache-control|age):' -curl -fsSI "https://andebol.net/" | tr -d '\r' | egrep -i '^(cf-cache-status|cache-control|age):' +curl -fsS "https://andebol.net/" -D - -o /dev/null | tr -d '\r' | egrep -i '^(cf-cache-status|cache-control|age):' +curl -fsS "https://andebol.net/" -D - -o /dev/null | tr -d '\r' | egrep -i '^(cf-cache-status|cache-control|age):' ``` -Expect `cf-cache-status: HIT` (or `STALE` / `REVALIDATED` per Cloudflare semantics) on the repeat, and `cache-control` unchanged from origin. Until the rule exists, both calls return **`DYNAMIC`** despite valid `Cache-Control`. +Expect `cf-cache-status: HIT`, `EXPIRED`, `STALE`, or `REVALIDATED` on the repeat (not bare `MISS` every time once warm), and `cache-control` from origin unchanged. If both passes stay **`DYNAMIC`** on **GET**, the rule is missing, disabled, or superseded by a higher-priority bypass rule. --- diff --git a/writer-pipeline/config/andebol.net.sources.json b/writer-pipeline/config/andebol.net.sources.json index d1e539e..2d01984 100644 --- a/writer-pipeline/config/andebol.net.sources.json +++ b/writer-pipeline/config/andebol.net.sources.json @@ -39,28 +39,28 @@ "id": "record_pt_main", "kind": "rss", "url": "https://www.record.pt/rss/", - "enabled": true, + "enabled": false, "maxItems": 25, "topics": ["pt", "sports", "media"], - "note": "Record main feed (PT, strong sports). Respect Record.pt terms; editorial rewrite required per ANDEBOL_EDITORIAL_BRIEF." + "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)." }, { "id": "sapo_noticias", "kind": "rss", "url": "https://noticias.sapo.pt/rss", - "enabled": true, + "enabled": false, "maxItems": 40, "topics": ["pt", "national", "international", "media"], - "note": "SAPO highlights (PT + world). Many items credit partner outlets; may include Agência Lusa bylines — still subject to each originator's ToS; not a substitute for a direct Lusa wire contract." + "note": "Disabled BIT-22288: SAPO general highlights are not handball-scoped; owner requires andebol.net news to be only about handball." }, { "id": "guardian_world", "kind": "rss", "url": "https://www.theguardian.com/world/rss", - "enabled": true, + "enabled": false, "maxItems": 25, "topics": ["international", "en"], - "note": "Guardian world (English). Use for important international threads with Portugal relevance; published andebol.net copy must be PT-PT per editorial brief." + "note": "Disabled BIT-22288: world news feed is not handball-scoped." }, { "id": "bbc_handball", diff --git a/writer-pipeline/src/html-meta.test.ts b/writer-pipeline/src/html-meta.test.ts index e22e23f..aedf41d 100644 --- a/writer-pipeline/src/html-meta.test.ts +++ b/writer-pipeline/src/html-meta.test.ts @@ -1,6 +1,6 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { extractTitleAndSummary } from './html-meta.js'; +import { extractTitleAndSummary, extractFeaturedImageFromHtml, absolutizeImageUrl } from './html-meta.js'; test('extractTitleAndSummary prefers og tags', () => { const html = ` @@ -13,12 +13,28 @@ test('extractTitleAndSummary prefers og tags', () => { assert.ok(r.summary.includes('Hello world')); }); -test('extractTitleAndSummary falls back to title and meta description', () => { - const html = ` - Plain title - +test('extractFeaturedImageFromHtml reads og:image and alt', () => { + const html = ` + + `; - const r = extractTitleAndSummary(html); - assert.equal(r.title, 'Plain title'); - assert.ok(r.summary.includes('Desc here')); + const r = extractFeaturedImageFromHtml(html); + assert.equal(r.url, 'https://cdn.example/hero.jpg'); + assert.equal(r.credit, 'Foto: João Silva / FPA'); +}); + +test('extractFeaturedImageFromHtml prefers secure_url when present', () => { + const html = ` + + + `; + const r = extractFeaturedImageFromHtml(html); + assert.equal(r.url, 'https://ok.example/a.png'); +}); + +test('absolutizeImageUrl resolves relative og:image', () => { + assert.equal( + absolutizeImageUrl('/wp-content/uploads/x.jpg', 'https://news.example/post/foo/'), + 'https://news.example/wp-content/uploads/x.jpg', + ); }); diff --git a/writer-pipeline/src/html-meta.ts b/writer-pipeline/src/html-meta.ts index 8c45768..8e7e720 100644 --- a/writer-pipeline/src/html-meta.ts +++ b/writer-pipeline/src/html-meta.ts @@ -1,6 +1,12 @@ /** - * Lightweight title/description extraction (no DOM / cheerio). + * Lightweight title/description / social image extraction (no DOM / cheerio). */ + +const META_PROP_CONTENT = /]*property=["']([^"']+)["'][^>]*content=["']([^"']*)["']/gi; +const META_CONTENT_PROP = /]*content=["']([^"']*)["'][^>]*property=["']([^"']+)["']/gi; +const META_NAME_CONTENT = /]*name=["']([^"']+)["'][^>]*content=["']([^"']*)["']/gi; +const META_CONTENT_NAME = /]*content=["']([^"']*)["'][^>]*name=["']([^"']+)["']/gi; + export function extractTitleAndSummary(html: string): { title: string; summary: string } { const ogTitle = matchOne( html, @@ -23,6 +29,67 @@ export function extractTitleAndSummary(html: string): { title: string; summary: return { title, summary }; } +/** + * Best-effort featured image URL + credit from page HTML (og/twitter). + * Relative URLs must be resolved with {@link absolutizeImageUrl}. + */ +export function extractFeaturedImageFromHtml(html: string): { url?: string; credit?: string } { + const byProp = new Map(); + const byName = new Map(); + + let m: RegExpExecArray | null; + META_PROP_CONTENT.lastIndex = 0; + while ((m = META_PROP_CONTENT.exec(html)) !== null) { + byProp.set(m[1].toLowerCase(), m[2]); + } + META_CONTENT_PROP.lastIndex = 0; + while ((m = META_CONTENT_PROP.exec(html)) !== null) { + byProp.set(m[2].toLowerCase(), m[1]); + } + META_NAME_CONTENT.lastIndex = 0; + while ((m = META_NAME_CONTENT.exec(html)) !== null) { + byName.set(m[1].toLowerCase(), m[2]); + } + META_CONTENT_NAME.lastIndex = 0; + while ((m = META_CONTENT_NAME.exec(html)) !== null) { + byName.set(m[2].toLowerCase(), m[1]); + } + + const ogImage = + byProp.get('og:image') || + byProp.get('og:image:url') || + byName.get('twitter:image') || + byName.get('twitter:image:src'); + const ogImageSecure = byProp.get('og:image:secure_url'); + const raw = (ogImageSecure || ogImage || '').trim(); + if (!raw) return {}; + + const credit = + decodeEntities( + stripTags( + byProp.get('og:image:alt') || + byName.get('twitter:image:alt') || + byProp.get('og:image:caption') || + '', + ), + ) + .replace(/\s+/g, ' ') + .trim() || undefined; + + return { url: decodeEntities(raw).trim(), credit }; +} + +/** Resolve a possibly-relative image URL against the article page URL. */ +export function absolutizeImageUrl(imageUrl: string, articleUrl: string): string { + const t = imageUrl.trim(); + if (!t) return t; + try { + return new URL(t, articleUrl).href; + } catch { + return t; + } +} + function matchOne(html: string, re: RegExp): string { const m = re.exec(html); return m?.[1] ? m[1] : ''; diff --git a/writer-pipeline/src/ingest-sources.ts b/writer-pipeline/src/ingest-sources.ts index 04cf778..0f3b23a 100644 --- a/writer-pipeline/src/ingest-sources.ts +++ b/writer-pipeline/src/ingest-sources.ts @@ -2,7 +2,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 { extractTitleAndSummary } from './html-meta.js'; +import { extractTitleAndSummary, extractFeaturedImageFromHtml, absolutizeImageUrl } from './html-meta.js'; import { isSitemapIndexXml, parseLooseLocs, @@ -134,10 +134,11 @@ function buildItem( publishedAt: string, now: string, kind: SourceKind, + featured?: { url?: string; credit?: string }, ): AggregatedItem { const trimmed = originalUrl.trim(); const id = itemId(canonicalUrl(trimmed)); - return { + const item: AggregatedItem = { id, site: storeSite, sourceFeedId: source.id, @@ -149,6 +150,11 @@ function buildItem( publishedAt, ingestedAt: now, }; + if (featured?.url) { + item.featuredImageUrl = absolutizeImageUrl(featured.url, trimmed); + if (featured.credit) item.featuredImageCredit = featured.credit; + } + return item; } export async function ingestAllSources( @@ -186,6 +192,11 @@ export async function ingestAllSources( const title = (entry.title || 'Sem título').replace(/\s+/g, ' ').trim(); const summary = pickSummary(entry); const publishedAt = entry.isoDate || entry.pubDate || entry.date || now; + const enc = (entry as { enclosure?: { url?: string; type?: string } }).enclosure; + let featured: { url?: string; credit?: string } | undefined; + if (enc?.url && enc.type?.toLowerCase().startsWith('image/')) { + featured = { url: enc.url }; + } const item = buildItem( config.site, source, @@ -195,6 +206,7 @@ export async function ingestAllSources( publishedAt, now, 'rss', + featured, ); const { store: next, isNew } = upsertItem(current, item); current = next; @@ -218,6 +230,7 @@ export async function ingestAllSources( }); succeeded += 1; const { title, summary } = extractTitleAndSummary(html); + const img = extractFeaturedImageFromHtml(html); const item = buildItem( config.site, source, @@ -227,6 +240,7 @@ export async function ingestAllSources( now, now, 'html_fetch', + img.url ? { url: img.url, credit: img.credit } : undefined, ); const { store: next, isNew } = upsertItem(current, item); current = next; @@ -267,6 +281,7 @@ export async function ingestAllSources( accept: 'text/html, application/xhtml+xml, */*', }); const { title, summary } = extractTitleAndSummary(html); + const img = extractFeaturedImageFromHtml(html); const publishedAt = publishedFromLastmod(entry.lastmod, now); const item = buildItem( config.site, @@ -277,6 +292,7 @@ export async function ingestAllSources( publishedAt, now, 'sitemap', + img.url ? { url: img.url, credit: img.credit } : undefined, ); const { store: next, isNew } = upsertItem(current, item); current = next; diff --git a/writer-pipeline/src/legacy-fetch.ts b/writer-pipeline/src/legacy-fetch.ts index be49a12..ed89c33 100644 --- a/writer-pipeline/src/legacy-fetch.ts +++ b/writer-pipeline/src/legacy-fetch.ts @@ -1,3 +1,24 @@ +/** + * Raw HTML (capped) for OpenGraph / featured image extraction before publish. + */ +export async function fetchArticleHtmlForMeta( + url: string, + timeoutMs = 15000, + maxBytes = 600_000, +): Promise { + try { + const res = await fetch(url, { + headers: { 'User-Agent': 'BitReport-news-writer-pipeline/1.0 (featured-image)' }, + signal: AbortSignal.timeout(timeoutMs), + }); + if (!res.ok) return null; + const html = await res.text(); + return html.slice(0, maxBytes); + } catch { + return null; + } +} + /** * Optional legacy read path: full HTML fetch for token comparison. * Not used for publishing when aggregator data is present. diff --git a/writer-pipeline/src/run-cycle.ts b/writer-pipeline/src/run-cycle.ts index 8270137..9206edc 100644 --- a/writer-pipeline/src/run-cycle.ts +++ b/writer-pipeline/src/run-cycle.ts @@ -62,7 +62,9 @@ async function main(): Promise { store = ingest.store; await saveStore(storePath, store); - const list = shortlist(store, site, shortlistLimit); + /** andebol.net: only items tagged `handball` enter the shortlist (owner BIT-22288 — no general-sports wire). */ + const shortlistTopic = site === 'andebol.net' ? 'handball' : undefined; + const list = shortlist(store, site, shortlistLimit, shortlistTopic); let tokensAgg = 0; let tokensLegacy = 0; let legacyUsed = 0; @@ -94,6 +96,7 @@ async function main(): Promise { wpBase, username: wpUser, appPassword: wpPass, + siteDomain: process.env.ANDEBOL_WP_SITE_DOMAIN, }); draftsCreated += 1; const updated: AggregatedItem = { ...item, wpDraftId: id }; diff --git a/writer-pipeline/src/store-extra.test.ts b/writer-pipeline/src/store-extra.test.ts index 4477438..716de58 100644 --- a/writer-pipeline/src/store-extra.test.ts +++ b/writer-pipeline/src/store-extra.test.ts @@ -95,6 +95,37 @@ test('upsertItem preserves wpDraftId and skippedReason on update', () => { assert.equal(s2.items[0].skippedReason, 'dup'); }); +test('upsertItem keeps previous featured image when update omits it', () => { + const store = emptyStore(); + const item = baseItem(); + const { store: s1 } = upsertItem(store, { + ...item, + featuredImageUrl: 'https://cdn.example/x.jpg', + featuredImageCredit: 'FPA', + }); + const { store: s2 } = upsertItem(s1, { ...item, title: 'Title only' }); + assert.equal(s2.items[0].featuredImageUrl, 'https://cdn.example/x.jpg'); + assert.equal(s2.items[0].featuredImageCredit, 'FPA'); +}); + +test('upsertItem prefers new featured image fields when provided', () => { + const store = emptyStore(); + const item = baseItem(); + const { store: s1 } = upsertItem(store, { + ...item, + featuredImageUrl: 'https://cdn/old.jpg', + featuredImageCredit: 'Old', + }); + const { store: s2 } = upsertItem(s1, { + ...item, + title: 'T2', + featuredImageUrl: 'https://cdn/new.jpg', + featuredImageCredit: 'New credit', + }); + assert.equal(s2.items[0].featuredImageUrl, 'https://cdn/new.jpg'); + assert.equal(s2.items[0].featuredImageCredit, 'New credit'); +}); + // ── shortlist ────────────────────────────────────────────────────────────── test('shortlist returns newest first, limited to n', () => { diff --git a/writer-pipeline/src/store.ts b/writer-pipeline/src/store.ts index 8058f59..e4c7d00 100644 --- a/writer-pipeline/src/store.ts +++ b/writer-pipeline/src/store.ts @@ -68,6 +68,8 @@ export function upsertItem(store: StoreFile, item: AggregatedItem): { store: Sto ...item, wpDraftId: prev.wpDraftId, skippedReason: prev.skippedReason, + featuredImageUrl: item.featuredImageUrl ?? prev.featuredImageUrl, + featuredImageCredit: item.featuredImageCredit ?? prev.featuredImageCredit, }; } else next.items.push(item); return { store: next, isNew }; diff --git a/writer-pipeline/src/types.ts b/writer-pipeline/src/types.ts index ae9b4ff..1fca51d 100644 --- a/writer-pipeline/src/types.ts +++ b/writer-pipeline/src/types.ts @@ -41,6 +41,10 @@ export interface AggregatedItem { topics?: string[]; title: string; summary: string; + /** og:image, RSS enclosure, or later HTML probe — required before WP draft publish */ + featuredImageUrl?: string; + /** Photographer / rights line (e.g. og:image:alt) stored as WP media caption */ + featuredImageCredit?: string; publishedAt: string; ingestedAt: string; ingestError?: string; diff --git a/writer-pipeline/src/webdav-archive.test.ts b/writer-pipeline/src/webdav-archive.test.ts new file mode 100644 index 0000000..3b7dcfb --- /dev/null +++ b/writer-pipeline/src/webdav-archive.test.ts @@ -0,0 +1,105 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import type { AggregatedItem } from './types.js'; +import { + creditFromArchiveHref, + parsePropfindImageHrefs, + pickBestArchiveImage, + readWebDavArchiveFromEnv, + scoreArchiveHrefForTitle, + titleMatchTokens, +} from './webdav-archive.js'; + +test('parsePropfindImageHrefs skips collection root and lists image files', () => { + const xml = ` + +https://ex/remote.php/dav/files/u/fpa/ +https://ex/remote.php/dav/files/u/fpa/benfica_win.jpg +Wed, 01 Jan 2025 12:00:00 GMT +https://ex/remote.php/dav/files/u/fpa/readme.txt +`; + const rows = parsePropfindImageHrefs(xml, 'https://ex/remote.php/dav/files/u/fpa/'); + assert.equal(rows.length, 1); + assert.match(rows[0].href, /benfica_win\.jpg$/); + assert.equal(rows[0].lastMod, 'Wed, 01 Jan 2025 12:00:00 GMT'); +}); + +test('pickBestArchiveImage prefers hrefs whose path matches title tokens', () => { + const item: AggregatedItem = { + id: '1', + site: 'andebol.net', + sourceFeedId: 'fpa', + url: 'https://portal.fpa.pt/x', + title: 'Sporting vence derby em Lisboa', + summary: '', + publishedAt: '2025-01-01T00:00:00.000Z', + ingestedAt: '2025-01-01T00:00:00.000Z', + }; + const rows = [ + { href: 'https://ex/a/lisboa_generic.png' }, + { href: 'https://ex/a/sporting_lisboa_celebra.jpg' }, + { href: 'https://ex/a/other_club.png' }, + ]; + const best = pickBestArchiveImage(rows, item); + assert.equal(best?.href, 'https://ex/a/sporting_lisboa_celebra.jpg'); +}); + +test('scoreArchiveHrefForTitle is zero when no overlap', () => { + assert.equal(scoreArchiveHrefForTitle('https://ex/z/abc.jpg', 'Nothing matches here really'), 0); +}); + +test('titleMatchTokens strips marks and drops short tokens', () => { + const t = titleMatchTokens('Condições físicas — época 24/25'); + assert.ok(t.includes('condicoes')); + assert.ok(!t.includes('24')); +}); + +test('creditFromArchiveHref parses Credit___file pattern', () => { + assert.equal( + creditFromArchiveHref('https://x/y/Joao%20Silva___match.jpg', 'Default'), + 'Joao Silva', + ); + assert.equal(creditFromArchiveHref('https://x/y/plain.jpg', 'Federação / arquivo'), 'Federação / arquivo'); +}); + +test('readWebDavArchiveFromEnv returns null when disabled', () => { + assert.equal(readWebDavArchiveFromEnv({}), null); + assert.equal(readWebDavArchiveFromEnv({ WRITER_WEBDAV_ENABLED: '0' }), null); +}); + +test('readWebDavArchiveFromEnv returns config when complete', () => { + const cfg = readWebDavArchiveFromEnv({ + WRITER_WEBDAV_ENABLED: 'true', + WRITER_WEBDAV_BASE_URL: 'https://cloud.example/dav/fpa', + WRITER_WEBDAV_USER: 'u', + WRITER_WEBDAV_PASSWORD: 'p', + WRITER_WEBDAV_DEFAULT_CREDIT: 'Crédito arquivo', + }); + assert.ok(cfg); + assert.equal(cfg?.baseUrl, 'https://cloud.example/dav/fpa'); + assert.equal(cfg?.defaultCredit, 'Crédito arquivo'); +}); + +test('readWebDavArchiveFromEnv throws when enabled but missing secret', () => { + assert.throws(() => + readWebDavArchiveFromEnv({ + WRITER_WEBDAV_ENABLED: '1', + WRITER_WEBDAV_BASE_URL: 'https://x/', + WRITER_WEBDAV_USER: '', + WRITER_WEBDAV_PASSWORD: '', + WRITER_WEBDAV_DEFAULT_CREDIT: 'c', + }), + ); +}); + +test('readWebDavArchiveFromEnv throws when default credit missing', () => { + assert.throws(() => + readWebDavArchiveFromEnv({ + WRITER_WEBDAV_ENABLED: 'yes', + WRITER_WEBDAV_BASE_URL: 'https://x/', + WRITER_WEBDAV_USER: 'u', + WRITER_WEBDAV_PASSWORD: 'p', + WRITER_WEBDAV_DEFAULT_CREDIT: '', + }), + ); +}); diff --git a/writer-pipeline/src/webdav-archive.ts b/writer-pipeline/src/webdav-archive.ts new file mode 100644 index 0000000..08743f0 --- /dev/null +++ b/writer-pipeline/src/webdav-archive.ts @@ -0,0 +1,194 @@ +import { Buffer } from 'node:buffer'; +import type { AggregatedItem } from './types.js'; + +export interface WebDavArchiveConfig { + /** Collection URL (folder); trailing slash optional */ + baseUrl: string; + username: string; + password: string; + /** Used when the filename does not use `Credit___filename.jpg` */ + defaultCredit: string; +} + +const IMAGE_EXT_RE = /\.(jpe?g|png|webp|gif)$/i; + +function basicAuthHeader(user: string, pass: string): string { + return `Basic ${Buffer.from(`${user}:${pass}`, 'utf8').toString('base64')}`; +} + +function decodeXmlText(s: string): string { + return s + .replace(/&/g, '&') + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/"/g, '"') + .replace(/'/g, "'"); +} + +/** Parse WebDAV multistatus PROPFIND response; returns absolute image hrefs under the collection */ +export function parsePropfindImageHrefs(xml: string, collectionUrl: string): { href: string; lastMod?: string }[] { + const base = new URL(collectionUrl.endsWith('/') ? collectionUrl : `${collectionUrl}/`); + const out: { href: string; lastMod?: string }[] = []; + const reResponse = /<(?:[a-z]+:)?response[^>]*>([\s\S]*?)<\/(?:[a-z]+:)?response>/gi; + let m: RegExpExecArray | null; + while ((m = reResponse.exec(xml))) { + const block = m[1]; + const hrefM = /<(?:[a-z]+:)?href>([^<]+)<\/(?:[a-z]+:)?href>/i.exec(block); + if (!hrefM) continue; + const hrefRaw = decodeXmlText(hrefM[1].trim()); + const lmM = /<(?:[a-z]+:)?getlastmodified>([^<]+)<\/(?:[a-z]+:)?getlastmodified>/i.exec(block); + const lastMod = lmM ? decodeXmlText(lmM[1].trim()) : undefined; + if (!IMAGE_EXT_RE.test(hrefRaw)) continue; + let abs: string; + try { + abs = new URL(hrefRaw, base).href; + } catch { + continue; + } + const normColl = base.href.replace(/\/$/, ''); + const normHref = abs.replace(/\/$/, ''); + if (normHref === normColl) continue; + out.push({ href: abs, lastMod }); + } + return out; +} + +function httpDateMs(s: string | undefined): number { + if (!s) return 0; + const t = Date.parse(s); + return Number.isNaN(t) ? 0 : t; +} + +/** Title tokens for matching archive filenames (Portuguese-friendly, length > 2) */ +export function titleMatchTokens(title: string): string[] { + const t = title.toLowerCase().normalize('NFD').replace(/\p{M}/gu, ''); + return t + .split(/[^a-z0-9]+/) + .map((w) => w.trim()) + .filter((w) => w.length > 2); +} + +/** Higher score = better match between filename and headline */ +export function scoreArchiveHrefForTitle(href: string, title: string): number { + let path = ''; + try { + path = decodeURIComponent(new URL(href).pathname).toLowerCase(); + } catch { + return 0; + } + const tokens = titleMatchTokens(title); + let score = 0; + for (const tok of tokens) { + if (path.includes(tok)) score += 1; + } + return score; +} + +export function creditFromArchiveHref(href: string, defaultCredit: string): string { + let base = ''; + try { + base = decodeURIComponent(new URL(href).pathname.split('/').pop() || ''); + } catch { + return defaultCredit; + } + const m = base.match(/^(.+?)___(.+\.(?:jpe?g|png|webp|gif))$/i); + if (m) { + return m[1].replace(/_/g, ' ').trim() || defaultCredit; + } + return defaultCredit; +} + +export function readWebDavArchiveFromEnv(env: NodeJS.ProcessEnv = process.env): WebDavArchiveConfig | null { + const en = env.WRITER_WEBDAV_ENABLED?.trim().toLowerCase(); + if (en !== '1' && en !== 'true' && en !== 'yes') return null; + const baseUrl = env.WRITER_WEBDAV_BASE_URL?.trim(); + const username = env.WRITER_WEBDAV_USER?.trim(); + const password = env.WRITER_WEBDAV_PASSWORD?.trim(); + const defaultCredit = env.WRITER_WEBDAV_DEFAULT_CREDIT?.trim() ?? ''; + if (!baseUrl || !username || !password) { + throw new Error( + 'WRITER_WEBDAV_ENABLED is set but WRITER_WEBDAV_BASE_URL, WRITER_WEBDAV_USER, and WRITER_WEBDAV_PASSWORD are all required', + ); + } + if (!defaultCredit) { + throw new Error('WRITER_WEBDAV_DEFAULT_CREDIT is required when WRITER_WEBDAV_ENABLED is set (WP media caption)'); + } + return { + baseUrl: baseUrl.replace(/\/$/, ''), + username, + password, + defaultCredit, + }; +} + +export async function listDavImageHrefs(cfg: WebDavArchiveConfig): Promise<{ href: string; lastMod?: string }[]> { + const url = cfg.baseUrl.endsWith('/') ? cfg.baseUrl : `${cfg.baseUrl}/`; + const auth = basicAuthHeader(cfg.username, cfg.password); + const body = ` +`; + const res = await fetch(url, { + method: 'PROPFIND', + headers: { + Depth: '1', + Authorization: auth, + 'Content-Type': 'application/xml; charset=utf-8', + Accept: 'application/xml, text/xml;q=0.9, */*;q=0.8', + }, + body, + signal: AbortSignal.timeout(25_000), + redirect: 'follow', + }); + if (!res.ok) { + const snippet = (await res.text().catch(() => '')).slice(0, 200); + throw new Error(`WebDAV PROPFIND failed HTTP ${res.status} for ${url}: ${snippet}`); + } + const xml = await res.text(); + return parsePropfindImageHrefs(xml, url); +} + +export function pickBestArchiveImage( + rows: { href: string; lastMod?: string }[], + item: AggregatedItem, +): { href: string; lastMod?: string } | null { + if (!rows.length) return null; + const scored = rows.map((r) => ({ + ...r, + score: scoreArchiveHrefForTitle(r.href, item.title), + lm: httpDateMs(r.lastMod), + })); + scored.sort((a, b) => { + if (b.score !== a.score) return b.score - a.score; + return b.lm - a.lm; + }); + return scored[0] ?? null; +} + +/** + * When HTML/RSS carry no image, pick a rights-cleared file from the configured WebDAV collection. + * Uses Basic auth on PROPFIND and on the subsequent GET in downloadBinaryImage. + */ +export async function resolveFeaturedFromWebDavArchive( + cfg: WebDavArchiveConfig, + item: AggregatedItem, +): Promise<{ url: string; credit: string; fetchHeaders: Record }> { + let rows: { href: string; lastMod?: string }[]; + try { + rows = await listDavImageHrefs(cfg); + } catch (e) { + const msg = e instanceof Error ? e.message : String(e); + throw new Error(`WebDAV archive unreachable or listing failed: ${msg}`); + } + const best = pickBestArchiveImage(rows, item); + if (!best) { + throw new Error( + `WebDAV archive at ${cfg.baseUrl} contains no image files (*.jpg, *.png, *.webp, *.gif) after PROPFIND depth 1`, + ); + } + const credit = creditFromArchiveHref(best.href, cfg.defaultCredit); + const auth = basicAuthHeader(cfg.username, cfg.password); + return { + url: best.href, + credit, + fetchHeaders: { Authorization: auth }, + }; +} diff --git a/writer-pipeline/src/wp-publish.ts b/writer-pipeline/src/wp-publish.ts index 2a5e406..cfc5a19 100644 --- a/writer-pipeline/src/wp-publish.ts +++ b/writer-pipeline/src/wp-publish.ts @@ -1,11 +1,23 @@ +import { Buffer } from 'node:buffer'; import type { AggregatedItem } from './types.js'; +import { fetchArticleHtmlForMeta } from './legacy-fetch.js'; +import { absolutizeImageUrl, extractFeaturedImageFromHtml } from './html-meta.js'; +import { + readWebDavArchiveFromEnv, + resolveFeaturedFromWebDavArchive, + type WebDavArchiveConfig, +} from './webdav-archive.js'; export interface WpPublishConfig { wpBase: string; username: string; appPassword: string; + /** When set, sent as X-Site-Domain on every WP REST call (multi-site bridge). */ + siteDomain?: string; } +const MAX_IMAGE_BYTES = 6 * 1024 * 1024; + function stripTags(html: string): string { return html.replace(/<[^>]+>/g, '').replace(/\s+/g, ' ').trim(); } @@ -22,14 +34,200 @@ function draftContent(item: AggregatedItem): string { ].join('\n'); } +function basicAuthValue(cfg: WpPublishConfig): string { + return Buffer.from(`${cfg.username}:${cfg.appPassword}`, 'utf8').toString('base64'); +} + +function jsonHeaders(cfg: WpPublishConfig): Record { + const h: Record = { + 'Content-Type': 'application/json', + Accept: 'application/json', + Authorization: `Basic ${basicAuthValue(cfg)}`, + }; + if (cfg.siteDomain) h['X-Site-Domain'] = cfg.siteDomain; + return h; +} + +function mediaPostHeaders(cfg: WpPublishConfig): Record { + const h: Record = { + Accept: 'application/json', + Authorization: `Basic ${basicAuthValue(cfg)}`, + }; + if (cfg.siteDomain) h['X-Site-Domain'] = cfg.siteDomain; + return h; +} + +function allowedMediaUrl(href: string): boolean { + try { + const u = new URL(href); + return u.protocol === 'https:' || u.protocol === 'http:'; + } catch { + return false; + } +} + +/** + * Resolves a rights-cleared image URL for the article (ingest hints, then live HTML). + * Throws if none — drafts must not ship without a featured image (BIT-22288). + */ +export async function resolveFeaturedImageForDraft(item: AggregatedItem): Promise<{ + url: string; + credit?: string; + /** Sent on GET when the image is not anonymously readable (e.g. WebDAV Basic auth) */ + fetchHeaders?: Record; +}> { + const fromItem = item.featuredImageUrl?.trim(); + if (fromItem && allowedMediaUrl(fromItem)) { + return { url: fromItem, credit: item.featuredImageCredit }; + } + + let webDavCfg: WebDavArchiveConfig | null = null; + let webDavEnvError: string | null = null; + try { + webDavCfg = readWebDavArchiveFromEnv(); + } catch (e) { + webDavEnvError = e instanceof Error ? e.message : String(e); + } + + const raw = await fetchArticleHtmlForMeta(item.url); + if (!raw) { + if (webDavCfg) { + return resolveFeaturedFromWebDavArchive(webDavCfg, item); + } + if (webDavEnvError) { + throw new Error( + `Mandatory featured image: cannot fetch article HTML for ${item.url}; WebDAV env invalid: ${webDavEnvError} (BIT-22292).`, + ); + } + throw new Error( + `Mandatory featured image: cannot fetch article HTML for ${item.url}. Optionally set WRITER_WEBDAV_ENABLED=1 and WRITER_WEBDAV_* to use the federation photo archive (BIT-22292).`, + ); + } + const parsed = extractFeaturedImageFromHtml(raw); + const abs = parsed.url ? absolutizeImageUrl(parsed.url, item.url) : ''; + if (abs && allowedMediaUrl(abs)) { + const credit = parsed.credit || item.featuredImageCredit; + return { url: abs, credit }; + } + + if (webDavCfg) { + return resolveFeaturedFromWebDavArchive(webDavCfg, item); + } + if (webDavEnvError) { + throw new Error( + `Mandatory featured image: no og:image / twitter:image (and no RSS image enclosure) for ${item.url}. WebDAV env misconfigured: ${webDavEnvError} (BIT-22292).`, + ); + } + throw new Error( + `Mandatory featured image: no og:image / twitter:image (and no RSS image enclosure) for ${item.url}. Enable federation archive with WRITER_WEBDAV_ENABLED=1 and WRITER_WEBDAV_* vars, or add og:image on the source (BIT-22292).`, + ); +} + +async function downloadBinaryImage( + imageUrl: string, + extraHeaders?: Record, +): Promise<{ bytes: Uint8Array; contentType: string; filename: string }> { + const headers: Record = { + 'User-Agent': 'BitReport-news-writer-pipeline/1.0 (media)', + ...(extraHeaders ?? {}), + }; + const res = await fetch(imageUrl, { + headers, + signal: AbortSignal.timeout(20_000), + redirect: 'follow', + }); + if (!res.ok) { + throw new Error(`Featured image fetch failed ${res.status} for ${imageUrl}`); + } + const ct = res.headers.get('content-type')?.split(';')[0]?.trim() || 'application/octet-stream'; + if (!ct.startsWith('image/')) { + throw new Error( + `Featured image URL returned non-image Content-Type (${ct}); refusing ${imageUrl}`, + ); + } + const cl = res.headers.get('content-length'); + if (cl) { + const n = parseInt(cl, 10); + if (!Number.isNaN(n) && n > MAX_IMAGE_BYTES) throw new Error('Featured image exceeds size limit'); + } + const buf = new Uint8Array(await res.arrayBuffer()); + if (buf.byteLength > MAX_IMAGE_BYTES) throw new Error('Featured image exceeds size limit'); + let pathname = ''; + try { + pathname = new URL(imageUrl).pathname; + } catch { + pathname = ''; + } + let base = pathname.split('/').pop() || 'featured'; + if (!/\.(jpe?g|png|gif|webp)$/i.test(base)) { + const ext = ct === 'image/png' ? 'png' : ct === 'image/webp' ? 'webp' : 'jpg'; + base = `featured.${ext}`; + } + const filename = base.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 120); + return { bytes: buf, contentType: ct, filename }; +} + +async function uploadFeaturedMedia( + cfg: WpPublishConfig, + base: string, + imageUrl: string, + credit: string | undefined, + fetchHeaders?: Record, +): Promise { + const { bytes, contentType, filename } = await downloadBinaryImage(imageUrl, fetchHeaders); + const blob = new Blob([Buffer.from(bytes)], { type: contentType }); + const form = new FormData(); + form.append('file', blob, filename); + + const res = await fetch(`${base}/wp/v2/media`, { + method: 'POST', + headers: mediaPostHeaders(cfg), + body: form, + signal: AbortSignal.timeout(30_000), + }); + + if (!res.ok) { + const errText = await res.text().catch(() => ''); + throw new Error(`WP media upload failed ${res.status}: ${errText.slice(0, 500)}`); + } + + const media = (await res.json()) as { id: number }; + const mediaId = media.id; + if (!mediaId) throw new Error('WP media upload returned no id'); + + if (credit) { + const patch = await fetch(`${base}/wp/v2/media/${mediaId}`, { + method: 'POST', + headers: jsonHeaders(cfg), + body: JSON.stringify({ + alt_text: credit.slice(0, 500), + caption: credit.slice(0, 2000), + }), + signal: AbortSignal.timeout(15_000), + }); + if (!patch.ok) { + const errText = await patch.text().catch(() => ''); + throw new Error(`WP media caption/alt failed ${patch.status}: ${errText.slice(0, 400)}`); + } + } + + return mediaId; +} + async function resolveCategoryId( base: string, authHeader: string, + siteDomain: string | undefined, slug: string, ): Promise { const url = `${base}/wp/v2/categories?slug=${encodeURIComponent(slug)}`; + const headers: Record = { + Accept: 'application/json', + Authorization: authHeader, + }; + if (siteDomain) headers['X-Site-Domain'] = siteDomain; const res = await fetch(url, { - headers: { Accept: 'application/json', Authorization: authHeader }, + headers, signal: AbortSignal.timeout(8000), }); if (!res.ok) return null; @@ -43,27 +241,26 @@ export async function createDraftFromAggregatedItem( categorySlug = 'nacional', ): Promise<{ id: number; link?: string }> { const base = cfg.wpBase.replace(/\/$/, ''); - const token = Buffer.from(`${cfg.username}:${cfg.appPassword}`, 'utf8').toString('base64'); - const authHeader = `Basic ${token}`; + const authHeader = `Basic ${basicAuthValue(cfg)}`; - const categoryId = await resolveCategoryId(base, authHeader, categorySlug); + const { url: imageUrl, credit, fetchHeaders } = await resolveFeaturedImageForDraft(item); + const mediaId = await uploadFeaturedMedia(cfg, base, imageUrl, credit, fetchHeaders); + + const categoryId = await resolveCategoryId(base, authHeader, cfg.siteDomain, categorySlug); const body: Record = { title: item.title, content: draftContent(item), status: 'draft', excerpt: stripTags(item.summary).slice(0, 300), + featured_media: mediaId, }; if (categoryId) body.categories = [categoryId]; const res = await fetch(`${base}/wp/v2/posts`, { method: 'POST', - headers: { - 'Content-Type': 'application/json', - Accept: 'application/json', - Authorization: authHeader, - }, + headers: jsonHeaders(cfg), body: JSON.stringify(body), - signal: AbortSignal.timeout(15000), + signal: AbortSignal.timeout(20_000), }); if (!res.ok) {