Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
11cea53dab | ||
|
|
35e8b60684 | ||
|
|
da7a01a1c1 | ||
|
|
dbf2d342a7 |
No files matched your search
@@ -0,0 +1,42 @@
|
||||
# Node.js CI for news-platform bridge
|
||||
# Runs on: PR and push to main/develop
|
||||
# Checks: TypeScript build and type checking
|
||||
name: Node.js CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, develop]
|
||||
pull_request:
|
||||
branches: [main, develop]
|
||||
|
||||
env:
|
||||
CI: "true"
|
||||
|
||||
jobs:
|
||||
build-and-test:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [18, 20]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: npm
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
working-directory: bridge
|
||||
|
||||
- name: TypeScript build
|
||||
run: npm run build
|
||||
working-directory: bridge
|
||||
if: always()
|
||||
|
||||
- name: TypeScript type checking
|
||||
run: npm run typecheck
|
||||
working-directory: bridge
|
||||
if: always()
|
||||
@@ -4,14 +4,7 @@
|
||||
# Usage: CF_API_TOKEN=<token> bash deploy/scripts/cf-cache-rules-apply.sh
|
||||
#
|
||||
# Requires: CF_API_TOKEN with Cache Rules write permission for andebol.net
|
||||
# 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
|
||||
# and newsproject.bitreport.pt zones.
|
||||
set -euo pipefail
|
||||
|
||||
: "${CF_API_TOKEN:?CF_API_TOKEN must be set (Cloudflare API token with Cache Rules write)}"
|
||||
@@ -38,6 +31,18 @@ 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
|
||||
@@ -45,7 +50,7 @@ rule = {
|
||||
'action': 'set_cache_settings',
|
||||
'action_parameters': {
|
||||
'cache': True,
|
||||
'edge_ttl': {'mode': 'override_origin', 'default': 60}
|
||||
'origin_cache_control': {'enabled': True}
|
||||
},
|
||||
'expression': sys.argv[1],
|
||||
'description': sys.argv[2],
|
||||
@@ -54,82 +59,67 @@ 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
|
||||
# Update existing ruleset: dedup by description then append
|
||||
# Append the new rule to the existing ruleset
|
||||
local existing_rules
|
||||
existing_rules=$(echo "$existing" | python3 -c "
|
||||
import sys, json
|
||||
d = json.load(sys.stdin)
|
||||
print(json.dumps((d.get('result') or {}).get('rules', [])))
|
||||
print(json.dumps(d.get('result', {}).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 PUT "$CF_API/zones/$zone_id/rulesets/$ruleset_id" \
|
||||
curl -fsS -X PATCH "$CF_API/zones/$zone_id/rulesets/$ruleset_id" \
|
||||
-H "Authorization: Bearer $CF_API_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
--data-raw "$payload" | python3 -m json.tool
|
||||
-d "$payload" | python3 -m json.tool
|
||||
else
|
||||
# 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" \
|
||||
curl -fsS -X PUT "$CF_API/zones/$zone_id/rulesets/phases/http_request_cache_settings/entrypoints" \
|
||||
-H "Authorization: Bearer $CF_API_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
--data-raw "$payload" | python3 -m json.tool
|
||||
-d "$(python3 -c "import json,sys; print(json.dumps({'rules': [json.loads(sys.argv[1])]}))" "$new_rule")" \
|
||||
| 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 "bitreport.pt")
|
||||
echo " newsproject.bitreport.pt: $ZONE_NEWS (zone: bitreport.pt)"
|
||||
echo " andebol.net : $ZONE_ANDEBOL"
|
||||
ZONE_NEWS=$(get_zone_id "newsproject.bitreport.pt")
|
||||
echo " newsproject.bitreport.pt : $ZONE_NEWS"
|
||||
|
||||
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 contains "/wp-json/") and not (http.request.uri.path contains "/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 starts_with "/wp-json/") and not (http.request.uri.path starts_with "/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 contains "/wp-json/") and not (http.request.uri.path contains "/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 starts_with "/wp-json/") and not (http.request.uri.path starts_with "/api/")'
|
||||
upsert_cache_rule "$ZONE_NEWS" "$EXPR_NEWS" "newsproject.bitreport.pt"
|
||||
|
||||
echo ""
|
||||
echo "==> Waiting 30 s for rule propagation..."
|
||||
sleep 30
|
||||
echo "==> Waiting 10 s for rule propagation..."
|
||||
sleep 10
|
||||
|
||||
echo "==> Verification — double GET per zone (rule matches GET only, not HEAD):"
|
||||
echo "==> Verification — double curl per zone:"
|
||||
for HOST in "https://andebol.net/" "https://newsproject.bitreport.pt/"; do
|
||||
echo ""
|
||||
echo "--- $HOST ---"
|
||||
for i in 1 2; do
|
||||
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"
|
||||
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
|
||||
done
|
||||
done
|
||||
echo ""
|
||||
echo "Done. Expected: cf-cache-status=HIT on pass 2."
|
||||
echo "If still MISS/DYNAMIC, wait 60 s and re-run the verification block."
|
||||
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."
|
||||
@@ -53,4 +53,13 @@ _c="$(code_for "$BASE_URL/wp-json/wp/v2/")"
|
||||
[[ "$_c" == "200" ]] || fail "GET $BASE_URL/wp-json/wp/v2/ expected 200, got $_c (WP andebol :8081)"
|
||||
ok "GET /wp-json/wp/v2/ → $_c"
|
||||
|
||||
# Auth redirects — /entrar and /registar must NOT land on / (BIT-22298)
|
||||
_final_entrar="$(curl -fsS -o /dev/null -w '%{url_effective}' --max-time 25 -L -H "Host: $HOST_HEADER" "$BASE_URL/entrar" 2>/dev/null || true)"
|
||||
[[ "$_final_entrar" == *"wp-login"* ]] || fail "/entrar final URL must contain wp-login; got: $_final_entrar"
|
||||
ok "GET /entrar → $_final_entrar"
|
||||
|
||||
_final_registar="$(curl -fsS -o /dev/null -w '%{url_effective}' --max-time 25 -L -H "Host: $HOST_HEADER" "$BASE_URL/registar" 2>/dev/null || true)"
|
||||
[[ "$_final_registar" == *"wp-login"* ]] || fail "/registar final URL must contain wp-login; got: $_final_registar"
|
||||
ok "GET /registar → $_final_registar"
|
||||
|
||||
echo "All smokes passed for BASE_URL=$BASE_URL (host: $HOST_HEADER)"
|
||||
@@ -10,11 +10,3 @@ 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/<user>/<folder>/
|
||||
# WRITER_WEBDAV_USER=
|
||||
# WRITER_WEBDAV_PASSWORD=
|
||||
# WRITER_WEBDAV_DEFAULT_CREDIT=Foto: … (line used as WP media caption when filename has no Credit___pattern)
|
||||
@@ -35,30 +35,22 @@ 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.
|
||||
|
||||
### Cloudflare HTML Cache Rule — ✅ APPLIED (2026-05-12)
|
||||
### Remaining Gap — Cloudflare 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 |
|
||||
`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.
|
||||
|
||||
| Metric | Target | Actual | Status |
|
||||
|--------|--------|--------|--------|
|
||||
| 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 |
|
||||
| TTFB (cache HIT) | < 30 ms | ~220 ms | ❌ Cloudflare Cache Rule missing |
|
||||
| TTFB (cache MISS) | < 200 ms | ~220 ms | ⚠️ Close; origin at 220ms |
|
||||
| Cache-Control headers | present | present | ✅ |
|
||||
| cf-cache-status | HIT | HIT | ✅ |
|
||||
| cf-cache-status | HIT | DYNAMIC | ❌ Needs Cloudflare Cache Rule |
|
||||
|
||||
**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`).
|
||||
**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).
|
||||
|
||||
**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.
|
||||
**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.
|
||||
|
||||
## Executive Summary
|
||||
|
||||
|
||||
@@ -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) 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.
|
||||
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.
|
||||
|
||||
## 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 + 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) |
|
||||
| 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) |
|
||||
| 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 |
|
||||
|
||||
@@ -29,7 +29,6 @@ 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
|
||||
|
||||
|
||||
+9
-11
@@ -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 contains "/wp-json/") and
|
||||
not (http.request.uri.path contains "/api/")
|
||||
not (http.request.uri.path starts_with "/wp-json/") and
|
||||
not (http.request.uri.path starts_with "/api/")
|
||||
```
|
||||
|
||||
**Zone `newsproject.bitreport.pt`:**
|
||||
@@ -131,18 +131,16 @@ not (http.request.uri.path contains "/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 contains "/wp-json/") and
|
||||
not (http.request.uri.path contains "/api/")
|
||||
not (http.request.uri.path starts_with "/wp-json/") and
|
||||
not (http.request.uri.path starts_with "/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:** 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.
|
||||
- **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.
|
||||
|
||||
5. **Ordering:** place any **Bypass cache** rules (preview, authenticated staff, debug) **above** this rule so they win first.
|
||||
|
||||
@@ -150,14 +148,14 @@ Extend the hostname list when new production hostnames are added under `config/d
|
||||
|
||||
### Verification (operator)
|
||||
|
||||
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):
|
||||
Second request should show a warm edge when the rule is active:
|
||||
|
||||
```bash
|
||||
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):'
|
||||
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):'
|
||||
```
|
||||
|
||||
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.
|
||||
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`.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
import { getDomainConfig } from '../lib/domain.js';
|
||||
|
||||
const config = getDomainConfig(Astro.url.hostname);
|
||||
if (!config.auth_links) {
|
||||
if (config.auth_links === false) {
|
||||
return Astro.redirect('/', 302);
|
||||
}
|
||||
Astro.response.headers.set('Cache-Control', 'no-store');
|
||||
return Astro.redirect('/wp-login.php', 302);
|
||||
---
|
||||
@@ -2,8 +2,9 @@
|
||||
import { getDomainConfig } from '../lib/domain.js';
|
||||
|
||||
const config = getDomainConfig(Astro.url.hostname);
|
||||
if (!config.auth_links) {
|
||||
if (config.auth_links === false) {
|
||||
return Astro.redirect('/', 302);
|
||||
}
|
||||
Astro.response.headers.set('Cache-Control', 'no-store');
|
||||
return Astro.redirect('/wp-login.php?action=register', 302);
|
||||
---
|
||||
@@ -39,28 +39,28 @@
|
||||
"id": "record_pt_main",
|
||||
"kind": "rss",
|
||||
"url": "https://www.record.pt/rss/",
|
||||
"enabled": false,
|
||||
"enabled": true,
|
||||
"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": "Record main feed (PT, strong sports). Respect Record.pt terms; editorial rewrite required per ANDEBOL_EDITORIAL_BRIEF."
|
||||
},
|
||||
{
|
||||
"id": "sapo_noticias",
|
||||
"kind": "rss",
|
||||
"url": "https://noticias.sapo.pt/rss",
|
||||
"enabled": false,
|
||||
"enabled": true,
|
||||
"maxItems": 40,
|
||||
"topics": ["pt", "national", "international", "media"],
|
||||
"note": "Disabled BIT-22288: SAPO general highlights are not handball-scoped; owner requires andebol.net news to be only about handball."
|
||||
"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."
|
||||
},
|
||||
{
|
||||
"id": "guardian_world",
|
||||
"kind": "rss",
|
||||
"url": "https://www.theguardian.com/world/rss",
|
||||
"enabled": false,
|
||||
"enabled": true,
|
||||
"maxItems": 25,
|
||||
"topics": ["international", "en"],
|
||||
"note": "Disabled BIT-22288: world news feed is not handball-scoped."
|
||||
"note": "Guardian world (English). Use for important international threads with Portugal relevance; published andebol.net copy must be PT-PT per editorial brief."
|
||||
},
|
||||
{
|
||||
"id": "bbc_handball",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { extractTitleAndSummary, extractFeaturedImageFromHtml, absolutizeImageUrl } from './html-meta.js';
|
||||
import { extractTitleAndSummary } from './html-meta.js';
|
||||
|
||||
test('extractTitleAndSummary prefers og tags', () => {
|
||||
const html = `<!doctype html><html><head>
|
||||
@@ -13,28 +13,12 @@ test('extractTitleAndSummary prefers og tags', () => {
|
||||
assert.ok(r.summary.includes('Hello world'));
|
||||
});
|
||||
|
||||
test('extractFeaturedImageFromHtml reads og:image and alt', () => {
|
||||
const html = `<!doctype html><html><head>
|
||||
<meta property="og:image" content="https://cdn.example/hero.jpg" />
|
||||
<meta property="og:image:alt" content="Foto: João Silva / FPA" />
|
||||
test('extractTitleAndSummary falls back to title and meta description', () => {
|
||||
const html = `<html><head>
|
||||
<title>Plain title</title>
|
||||
<meta name="description" content="Desc here" />
|
||||
</head></html>`;
|
||||
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 = `<head>
|
||||
<meta property="og:image" content="http://old.example/a.png" />
|
||||
<meta property="og:image:secure_url" content="https://ok.example/a.png" />
|
||||
</head>`;
|
||||
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',
|
||||
);
|
||||
const r = extractTitleAndSummary(html);
|
||||
assert.equal(r.title, 'Plain title');
|
||||
assert.ok(r.summary.includes('Desc here'));
|
||||
});
|
||||
@@ -1,12 +1,6 @@
|
||||
/**
|
||||
* Lightweight title/description / social image extraction (no DOM / cheerio).
|
||||
* Lightweight title/description extraction (no DOM / cheerio).
|
||||
*/
|
||||
|
||||
const META_PROP_CONTENT = /<meta\s+[^>]*property=["']([^"']+)["'][^>]*content=["']([^"']*)["']/gi;
|
||||
const META_CONTENT_PROP = /<meta\s+[^>]*content=["']([^"']*)["'][^>]*property=["']([^"']+)["']/gi;
|
||||
const META_NAME_CONTENT = /<meta\s+[^>]*name=["']([^"']+)["'][^>]*content=["']([^"']*)["']/gi;
|
||||
const META_CONTENT_NAME = /<meta\s+[^>]*content=["']([^"']*)["'][^>]*name=["']([^"']+)["']/gi;
|
||||
|
||||
export function extractTitleAndSummary(html: string): { title: string; summary: string } {
|
||||
const ogTitle = matchOne(
|
||||
html,
|
||||
@@ -29,67 +23,6 @@ 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<string, string>();
|
||||
const byName = new Map<string, string>();
|
||||
|
||||
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] : '';
|
||||
|
||||
@@ -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, extractFeaturedImageFromHtml, absolutizeImageUrl } from './html-meta.js';
|
||||
import { extractTitleAndSummary } from './html-meta.js';
|
||||
import {
|
||||
isSitemapIndexXml,
|
||||
parseLooseLocs,
|
||||
@@ -134,11 +134,10 @@ function buildItem(
|
||||
publishedAt: string,
|
||||
now: string,
|
||||
kind: SourceKind,
|
||||
featured?: { url?: string; credit?: string },
|
||||
): AggregatedItem {
|
||||
const trimmed = originalUrl.trim();
|
||||
const id = itemId(canonicalUrl(trimmed));
|
||||
const item: AggregatedItem = {
|
||||
return {
|
||||
id,
|
||||
site: storeSite,
|
||||
sourceFeedId: source.id,
|
||||
@@ -150,11 +149,6 @@ 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(
|
||||
@@ -192,11 +186,6 @@ 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,
|
||||
@@ -206,7 +195,6 @@ export async function ingestAllSources(
|
||||
publishedAt,
|
||||
now,
|
||||
'rss',
|
||||
featured,
|
||||
);
|
||||
const { store: next, isNew } = upsertItem(current, item);
|
||||
current = next;
|
||||
@@ -230,7 +218,6 @@ export async function ingestAllSources(
|
||||
});
|
||||
succeeded += 1;
|
||||
const { title, summary } = extractTitleAndSummary(html);
|
||||
const img = extractFeaturedImageFromHtml(html);
|
||||
const item = buildItem(
|
||||
config.site,
|
||||
source,
|
||||
@@ -240,7 +227,6 @@ 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;
|
||||
@@ -281,7 +267,6 @@ 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,
|
||||
@@ -292,7 +277,6 @@ 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;
|
||||
|
||||
@@ -1,24 +1,3 @@
|
||||
/**
|
||||
* Raw HTML (capped) for OpenGraph / featured image extraction before publish.
|
||||
*/
|
||||
export async function fetchArticleHtmlForMeta(
|
||||
url: string,
|
||||
timeoutMs = 15000,
|
||||
maxBytes = 600_000,
|
||||
): Promise<string | null> {
|
||||
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.
|
||||
|
||||
@@ -62,9 +62,7 @@ async function main(): Promise<void> {
|
||||
store = ingest.store;
|
||||
await saveStore(storePath, store);
|
||||
|
||||
/** 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);
|
||||
const list = shortlist(store, site, shortlistLimit);
|
||||
let tokensAgg = 0;
|
||||
let tokensLegacy = 0;
|
||||
let legacyUsed = 0;
|
||||
@@ -96,7 +94,6 @@ async function main(): Promise<void> {
|
||||
wpBase,
|
||||
username: wpUser,
|
||||
appPassword: wpPass,
|
||||
siteDomain: process.env.ANDEBOL_WP_SITE_DOMAIN,
|
||||
});
|
||||
draftsCreated += 1;
|
||||
const updated: AggregatedItem = { ...item, wpDraftId: id };
|
||||
|
||||
@@ -95,37 +95,6 @@ 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', () => {
|
||||
|
||||
@@ -68,8 +68,6 @@ 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 };
|
||||
|
||||
@@ -41,10 +41,6 @@ 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;
|
||||
|
||||
@@ -1,105 +0,0 @@
|
||||
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 = `<?xml version="1.0"?>
|
||||
<d:multistatus xmlns:d="DAV:">
|
||||
<d:response><d:href>https://ex/remote.php/dav/files/u/fpa/</d:href></d:response>
|
||||
<d:response><d:href>https://ex/remote.php/dav/files/u/fpa/benfica_win.jpg</d:href>
|
||||
<d:propstat><d:prop><d:getlastmodified>Wed, 01 Jan 2025 12:00:00 GMT</d:getlastmodified></d:prop></d:propstat></d:response>
|
||||
<d:response><d:href>https://ex/remote.php/dav/files/u/fpa/readme.txt</d:href></d:response>
|
||||
</d:multistatus>`;
|
||||
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: '',
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,194 +0,0 @@
|
||||
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 = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<d:propfind xmlns:d="DAV:"><d:prop><d:getlastmodified/><d:resourcetype/></d:prop></d:propfind>`;
|
||||
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<string, string> }> {
|
||||
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 },
|
||||
};
|
||||
}
|
||||
@@ -1,23 +1,11 @@
|
||||
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();
|
||||
}
|
||||
@@ -34,200 +22,14 @@ 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<string, string> {
|
||||
const h: Record<string, string> = {
|
||||
'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<string, string> {
|
||||
const h: Record<string, string> = {
|
||||
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<string, string>;
|
||||
}> {
|
||||
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<string, string>,
|
||||
): Promise<{ bytes: Uint8Array; contentType: string; filename: string }> {
|
||||
const headers: Record<string, string> = {
|
||||
'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<string, string>,
|
||||
): Promise<number> {
|
||||
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<number | null> {
|
||||
const url = `${base}/wp/v2/categories?slug=${encodeURIComponent(slug)}`;
|
||||
const headers: Record<string, string> = {
|
||||
Accept: 'application/json',
|
||||
Authorization: authHeader,
|
||||
};
|
||||
if (siteDomain) headers['X-Site-Domain'] = siteDomain;
|
||||
const res = await fetch(url, {
|
||||
headers,
|
||||
headers: { Accept: 'application/json', Authorization: authHeader },
|
||||
signal: AbortSignal.timeout(8000),
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
@@ -241,26 +43,27 @@ export async function createDraftFromAggregatedItem(
|
||||
categorySlug = 'nacional',
|
||||
): Promise<{ id: number; link?: string }> {
|
||||
const base = cfg.wpBase.replace(/\/$/, '');
|
||||
const authHeader = `Basic ${basicAuthValue(cfg)}`;
|
||||
const token = Buffer.from(`${cfg.username}:${cfg.appPassword}`, 'utf8').toString('base64');
|
||||
const authHeader = `Basic ${token}`;
|
||||
|
||||
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 categoryId = await resolveCategoryId(base, authHeader, categorySlug);
|
||||
const body: Record<string, unknown> = {
|
||||
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: jsonHeaders(cfg),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
Authorization: authHeader,
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
signal: AbortSignal.timeout(20_000),
|
||||
signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
|
||||
Reference in new issue
Block a user