diff --git a/.env.example b/.env.example index 7e582dc..b23921c 100644 --- a/.env.example +++ b/.env.example @@ -79,6 +79,11 @@ VESSELAPI_IN_INGEST=0 ADMIN_USER= ADMIN_PASSWORD_HASH= ADMIN_SESSION_SECRET= +# Optional: force the session cookie's Secure flag (1/true/yes) when the app is +# reached over plain HTTP behind a TLS-terminating proxy that rewrites +# X-Forwarded-Proto to http (the cluster: Cloudflare tunnel -> Cilium Gateway). +# Leave unset locally so the cookie works over http://localhost. +ADMIN_COOKIE_SECURE= # ── News pipeline (scraper + summarizer, profile `ingest`) ──────────────── # Scraper crawls urls.txt continuously (default 10s between crawls). @@ -93,6 +98,25 @@ NOUS_BASE_URL=https://inference-api.nousresearch.com/v1 # Hermes-4.3-36B remains after a Postgres miss. Env wins when set. # SUMMARY_MODEL= NEWS_BATCH_SIZE=50 +# Map-phase grading: the map model scores each article 0-100, and only blocks +# with score >= SUMMARY_MIN_SCORE reach the reduce brief (best first). +# If nothing clears the bar, up to SUMMARY_FALLBACK_TOP blocks scoring at least +# SUMMARY_FALLBACK_MIN_SCORE are used; if none do, the reduce phase gets an +# empty DATA section (SUMMARY_FALLBACK_TOP=0 does the same unconditionally). +SUMMARY_MIN_SCORE=60 +SUMMARY_TOP_N=12 +SUMMARY_FALLBACK_TOP=3 +SUMMARY_FALLBACK_MIN_SCORE=40 +# Syndication dedupe: the same wire story arrives from many station domains +# (kcci.com, wtae.com, …) with an identical headline. Copies are collapsed +# before the threshold/cap, so SUMMARY_TOP_N buys distinct stories: normalised +# titles (lowercase, trailing " - KCCI"/" | CNN"/" — AP" source suffix dropped) +# count as one story when they are equal or >= SUMMARY_DEDUPE_SIMILARITY alike. +# The highest-scoring copy represents the story; the rest are still written to +# article_scores with selected=false and duplicate_of = the surviving article id. +# Set SUMMARY_DEDUPE=0 to skip dedupe entirely (old behaviour). +SUMMARY_DEDUPE=1 +SUMMARY_DEDUPE_SIMILARITY=0.85 SUMMARY_WINDOW_MINUTES=15 # Futures/markets coupling from the upstream pipeline is OFF by default # (irrelevant to OSINT). Set INCLUDE_FUTURES=1 + install yfinance to enable. diff --git a/.forgejo/workflows/build.yml b/.forgejo/workflows/build.yml index b2c2a0d..b51b488 100644 --- a/.forgejo/workflows/build.yml +++ b/.forgejo/workflows/build.yml @@ -1,21 +1,28 @@ -# Build changed OSINT images, publish to the Forgejo container registry, then -# redeploy on the Pi runner (docker.sock mounted). +# Build changed OSINT images and publish them to the Forgejo container +# registry. Deployment is NOT done here: the cluster (homek8s, namespace +# `osint`) runs amd64 images pinned by tag in apps/base/osint/*.yaml, so the +# final step prints the tag to pin and a human opens that manifest PR. # # Unchanged images are skipped. Dockerfile.pg / osint-dashboard-pg is NOT -# rebuilt or pulled on a normal merge — Postgres stays up. Rebuild it only -# when Dockerfile.pg changes, or via workflow_dispatch rebuild_pg. +# rebuilt on a normal merge — Postgres stays up. Rebuild it only when +# Dockerfile.pg changes, or via workflow_dispatch rebuild_pg. +# +# Registry endpoints +# CI push host: forgejo.forgejo.svc.cluster.local:3000 — plain HTTP +# ClusterIP, whitelisted by --insecure-registry on the amd64 +# runner's dind daemon. 127.0.0.1:3000 stopped working when +# Forgejo moved into k8s: inside an in-cluster job pod, loopback +# is the pod itself, so login died with "connection refused". +# Public pull: forgejo.siriusdevops.com (HTTPS via Cloudflare; kubelet pulls +# from here). Do NOT push here — Cloudflare 413s layers ≳100MB. # -# Public pull host: forgejo.siriusdevops.com (NOT ghcr.io) -# CI push host: 127.0.0.1:3000 — Cloudflare 413s layers ≳100MB on the public -# hostname, even from the Pi (hairpins out through the tunnel). # Images (public names): -# forgejo.siriusdevops.com/sirius/osint-dashboard -# forgejo.siriusdevops.com/sirius/osint-dashboard-pg -# forgejo.siriusdevops.com/sirius/osint-news-scraper -# forgejo.siriusdevops.com/sirius/osint-news-summarizer +# forgejo.siriusdevops.com/sirius/osint-dashboard:amd64- +# forgejo.siriusdevops.com/sirius/osint-dashboard-pg:amd64- +# forgejo.siriusdevops.com/sirius/osint-news-scraper:amd64- +# forgejo.siriusdevops.com/sirius/osint-news-summarizer:amd64- # # Optional repo variable FORGEJO_REGISTRY overrides the *public* pull host. -# Deploy still uses the local docker socket on the runner host (rpi). name: build-and-deploy @@ -35,17 +42,19 @@ on: env: PUBLIC_REGISTRY: ${{ vars.FORGEJO_REGISTRY || 'forgejo.siriusdevops.com' }} - PUSH_REGISTRY: 127.0.0.1:3000 + PUSH_REGISTRY: forgejo.forgejo.svc.cluster.local:3000 OWNER: sirius - # Keep compose project/volumes stable on the Pi - COMPOSE_PROJECT_NAME: osint-dashboard jobs: - build-push-deploy: - runs-on: docker - permissions: - contents: read - packages: write + build-push: + # `amd64` only exists on siriussec-amd64, which is also the node the + # workloads run on — so the images are built on the architecture they are + # pulled to. `runs-on: docker` matched the Pi's arm64 runner, which + # produced images the amd64 cluster could never run. + # No job-level `permissions:` block: Forgejo ignores it (it emits a + # pre-execution warning) and the push authenticates with the FORGEJO_TOKEN + # user PAT instead, because the package registry rejects the Actions token. + runs-on: amd64 steps: - name: Checkout uses: https://code.forgejo.org/actions/checkout@v4 @@ -60,7 +69,6 @@ jobs: SCRAPER=0 SUM=0 PG=0 - COMPOSE=0 mark() { case "$1" in @@ -72,8 +80,6 @@ jobs: SCRAPER=1 ;; news/summerizer/*) SUM=1 ;; - docker-compose.yml|scripts/compose-reup.sh) - COMPOSE=1 ;; esac } @@ -108,9 +114,8 @@ jobs: echo "scraper=$SCRAPER" echo "summarizer=$SUM" echo "pg=$PG" - echo "compose=$COMPOSE" } >> "$GITHUB_OUTPUT" - echo "plan app=$APP scraper=$SCRAPER summarizer=$SUM pg=$PG compose=$COMPOSE" + echo "plan app=$APP scraper=$SCRAPER summarizer=$SUM pg=$PG" - name: Image refs id: img @@ -120,10 +125,11 @@ jobs: PUB="${PUBLIC_REGISTRY}" OWN="${OWNER}" SHA="${GITHUB_SHA::12}" + TAG="amd64-${SHA}" { echo "reg=$PUSH" echo "pub=$PUB" - echo "sha=$SHA" + echo "tag=$TAG" echo "app=$PUSH/$OWN/osint-dashboard" echo "pg=$PUSH/$OWN/osint-dashboard-pg" echo "scraper=$PUSH/$OWN/osint-news-scraper" @@ -131,113 +137,69 @@ jobs: } >> "$GITHUB_OUTPUT" echo "Push registry: $PUSH" echo "Public pull: $PUB" - echo "SHA tag: $SHA" + echo "Image tag: $TAG" - name: Login to Forgejo registry if: steps.plan.outputs.app == '1' || steps.plan.outputs.scraper == '1' || steps.plan.outputs.summarizer == '1' || steps.plan.outputs.pg == '1' run: | set -euo pipefail # GITHUB_TOKEN login "succeeds" but blob uploads 401 (Forgejo packages - # reject the Actions token). Use a user PAT with write:package. - if [ -z "${{ secrets.FORGEJO_TOKEN }}" ]; then - echo "Missing repo secret FORGEJO_TOKEN (user PAT, not GITHUB_TOKEN)" + # reject the Actions token). Use a user PAT. + # The PAT must carry the `write:package` scope: Forgejo mints a push + # token even without it and then rejects every blob upload with + # `unauthorized: reqPackageAccess` (routers/api/packages/api.go + # reqPackageAccess -> AccessTokenScopeWritePackage). + # Name is REGISTRY_TOKEN, not FORGEJO_TOKEN: Forgejo reserves the + # FORGEJO_/GITHUB_ prefixes and refuses to create or update them via + # the API. + if [ -z "${{ secrets.REGISTRY_TOKEN }}" ]; then + echo "Missing repo secret REGISTRY_TOKEN (user PAT with write:package, not GITHUB_TOKEN)" exit 1 fi - echo "${{ secrets.FORGEJO_TOKEN }}" | docker login "${{ steps.img.outputs.reg }}" \ + echo "${{ secrets.REGISTRY_TOKEN }}" | docker login "${{ steps.img.outputs.reg }}" \ -u sirius --password-stdin - name: Build application image (api / ingester / cameras) if: steps.plan.outputs.app == '1' run: | set -ex - APP="${{ steps.img.outputs.app }}" - SHA="${{ steps.img.outputs.sha }}" - docker build -f Dockerfile -t "${APP}:latest" -t "${APP}:${SHA}" \ - -t "localhost/osint-dashboard:latest" . - docker push "${APP}:latest" - docker push "${APP}:${SHA}" + IMG="${{ steps.img.outputs.app }}" + TAG="${{ steps.img.outputs.tag }}" + docker build -f Dockerfile -t "${IMG}:${TAG}" . + docker push "${IMG}:${TAG}" - name: Build news-scraper image if: steps.plan.outputs.scraper == '1' run: | set -ex IMG="${{ steps.img.outputs.scraper }}" - SHA="${{ steps.img.outputs.sha }}" - docker build -f news/scraper/Dockerfile -t "${IMG}:latest" -t "${IMG}:${SHA}" \ - -t "localhost/osint-news-scraper:latest" news/scraper - docker push "${IMG}:latest" - docker push "${IMG}:${SHA}" + TAG="${{ steps.img.outputs.tag }}" + docker build -f news/scraper/Dockerfile -t "${IMG}:${TAG}" news/scraper + docker push "${IMG}:${TAG}" - name: Build news-summarizer image if: steps.plan.outputs.summarizer == '1' run: | set -ex IMG="${{ steps.img.outputs.summarizer }}" - SHA="${{ steps.img.outputs.sha }}" - docker build -f news/summerizer/Dockerfile -t "${IMG}:latest" -t "${IMG}:${SHA}" \ - -t "localhost/osint-news-summarizer:latest" news/summerizer - docker push "${IMG}:latest" - docker push "${IMG}:${SHA}" + TAG="${{ steps.img.outputs.tag }}" + docker build -f news/summerizer/Dockerfile -t "${IMG}:${TAG}" news/summerizer + docker push "${IMG}:${TAG}" - name: Build / refresh Timescale+PostGIS image if: steps.plan.outputs.pg == '1' run: | set -ex - PG="${{ steps.img.outputs.pg }}" - SHA="${{ steps.img.outputs.sha }}" - if docker build -f Dockerfile.pg -t "${PG}:latest" -t "${PG}:${SHA}" \ - -t "localhost/osint-dashboard-pg:latest" .; then - docker push "${PG}:latest" - docker push "${PG}:${SHA}" - elif docker image inspect "localhost/osint-dashboard-pg:latest" >/dev/null 2>&1; then - echo "WARN: Dockerfile.pg build failed; keeping existing local pg image" - else - echo "ERROR: cannot build or find osint-dashboard-pg image" - exit 1 - fi - - - name: Deploy on runner host (compose) - run: | - set -ex - cd "${GITHUB_WORKSPACE}" - APP="${{ steps.plan.outputs.app }}" - SCRAPER="${{ steps.plan.outputs.scraper }}" - SUM="${{ steps.plan.outputs.summarizer }}" - PG="${{ steps.plan.outputs.pg }}" - COMPOSE="${{ steps.plan.outputs.compose }}" - - SVCS=() - [ "$APP" = "1" ] && SVCS+=(app ingester camera-service) - [ "$SCRAPER" = "1" ] && SVCS+=(news-scraper) - [ "$SUM" = "1" ] && SVCS+=(news-summarizer) - if [ "$COMPOSE" = "1" ]; then - # compose/script change: bounce workers so env/command updates apply. - # Still do not bounce Postgres. - for s in app ingester camera-service news-scraper news-summarizer; do - case " ${SVCS[*]} " in - *" $s "*) ;; - *) SVCS+=("$s") ;; - esac - done - fi - - chmod +x scripts/compose-reup.sh - if [ "$PG" = "1" ]; then - FORCE_RECREATE_DB=1 COMPOSE_PROJECT_NAME=osint-dashboard COMPOSE_PROFILES=ingest \ - scripts/compose-reup.sh "${SVCS[@]}" db - elif [ "${#SVCS[@]}" -gt 0 ]; then - COMPOSE_PROJECT_NAME=osint-dashboard COMPOSE_PROFILES=ingest \ - scripts/compose-reup.sh "${SVCS[@]}" - else - echo "No image or compose changes — leave running containers alone" - docker compose --profile ingest ps - fi - docker image prune -f - echo "osint-dashboard deploy done; db image left in place unless pg=1" + IMG="${{ steps.img.outputs.pg }}" + TAG="${{ steps.img.outputs.tag }}" + docker build -f Dockerfile.pg -t "${IMG}:${TAG}" . + docker push "${IMG}:${TAG}" - name: Summary if: always() run: | + TAG="${{ steps.img.outputs.tag }}" + PUB="${{ steps.img.outputs.pub }}" { echo "## Image plan" echo "- app: \`${{ steps.plan.outputs.app }}\`" @@ -245,5 +207,23 @@ jobs: echo "- news-summarizer: \`${{ steps.plan.outputs.summarizer }}\`" echo "- pg (Timescale): \`${{ steps.plan.outputs.pg }}\`" echo - echo "Postgres is rebuilt/pulled only when \`Dockerfile.pg\` changes (or workflow_dispatch rebuild_pg)." + if [ -n "$TAG" ]; then + echo "## Pin in homek8s (apps/base/osint)" + echo "Pushed tag: \`${TAG}\`. Set the workload images in" + echo "\`apps/base/osint/kustomization.yaml\` to:" + echo + echo '```yaml' + echo "images:" + echo " - name: ${PUB}/${OWNER}/osint-dashboard" + echo " newTag: ${TAG}" + echo " - name: ${PUB}/${OWNER}/osint-news-scraper" + echo " newTag: ${TAG}" + echo " - name: ${PUB}/${OWNER}/osint-news-summarizer" + echo " newTag: ${TAG}" + echo '```' + else + echo "_No tag computed — the earlier steps failed before Image refs._" + fi + echo + echo "Postgres is rebuilt only when \`Dockerfile.pg\` changes (or workflow_dispatch rebuild_pg)." } >> "$GITHUB_STEP_SUMMARY" diff --git a/alembic/versions/012_article_scores.py b/alembic/versions/012_article_scores.py new file mode 100644 index 0000000..853ded7 --- /dev/null +++ b/alembic/versions/012_article_scores.py @@ -0,0 +1,39 @@ +"""article_scores: per-article map-phase grades for threshold tuning + +Revision ID: 012_article_scores +Revises: 011_geofence_alerts_fence +Create Date: 2026-11-13 +""" + +from alembic import op + +revision = "012_article_scores" +down_revision = "011_geofence_alerts_fence" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.execute( + """ + CREATE TABLE IF NOT EXISTS article_scores ( + article_id INTEGER NOT NULL, + summary_id INTEGER, + score INTEGER NOT NULL, + category TEXT, + selected BOOLEAN NOT NULL, + model TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + PRIMARY KEY (article_id, created_at) + ) + """ + ) + op.execute( + "CREATE INDEX IF NOT EXISTS ix_article_scores_summary " + "ON article_scores (summary_id)" + ) + + +def downgrade() -> None: + op.execute("DROP INDEX IF EXISTS ix_article_scores_summary") + op.execute("DROP TABLE IF EXISTS article_scores") diff --git a/alembic/versions/013_article_scores_duplicate_of.py b/alembic/versions/013_article_scores_duplicate_of.py new file mode 100644 index 0000000..2fcfb8b --- /dev/null +++ b/alembic/versions/013_article_scores_duplicate_of.py @@ -0,0 +1,23 @@ +"""article_scores.duplicate_of: link a syndicated copy to its representative + +Revision ID: 013_article_scores_duplicate_of +Revises: 012_article_scores +Create Date: 2026-11-13 +""" + +from alembic import op + +revision = "013_article_scores_duplicate_of" +down_revision = "012_article_scores" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.execute( + "ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS duplicate_of INTEGER" + ) + + +def downgrade() -> None: + op.execute("ALTER TABLE article_scores DROP COLUMN IF EXISTS duplicate_of") diff --git a/alembic/versions/014_article_scores_geo.py b/alembic/versions/014_article_scores_geo.py new file mode 100644 index 0000000..49ba951 --- /dev/null +++ b/alembic/versions/014_article_scores_geo.py @@ -0,0 +1,40 @@ +"""article_scores geo: per-article proximate location for /api/news/blips + +Revision ID: 014_article_scores_geo +Revises: 013_article_scores_duplicate_of +Create Date: 2026-11-19 + +Additive nullable columns on article_scores (every graded article keeps +its grading row; geo rides along when derivable). Partial bbox index for +the blips endpoint's bbox= filter. Idempotent DDL mirrors the summarizer's +ensure_tables so either start order is safe. +""" + +from alembic import op + +revision = "014_article_scores_geo" +down_revision = "013_article_scores_duplicate_of" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.execute("ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS location_name TEXT") + op.execute("ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS lat DOUBLE PRECISION") + op.execute("ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS lon DOUBLE PRECISION") + op.execute( + "ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS location_confidence TEXT" + ) + op.execute( + "CREATE INDEX IF NOT EXISTS ix_article_scores_geo_bbox " + "ON article_scores (lon, lat) " + "WHERE lat IS NOT NULL AND lon IS NOT NULL" + ) + + +def downgrade() -> None: + op.execute("DROP INDEX IF EXISTS ix_article_scores_geo_bbox") + op.execute("ALTER TABLE article_scores DROP COLUMN IF EXISTS location_confidence") + op.execute("ALTER TABLE article_scores DROP COLUMN IF EXISTS lon") + op.execute("ALTER TABLE article_scores DROP COLUMN IF EXISTS lat") + op.execute("ALTER TABLE article_scores DROP COLUMN IF EXISTS location_name") diff --git a/app/auth.py b/app/auth.py index cfdb074..a9ac75e 100644 --- a/app/auth.py +++ b/app/auth.py @@ -16,7 +16,9 @@ Design notes * **No new dependencies.** Password hashing is stdlib ``hashlib.pbkdf2_hmac`` and the session token is an HMAC-SHA256 signature over a base64url JSON payload. Cookies are HttpOnly, SameSite=Lax, Path=/, 7-day lifetime, and - ``Secure`` when the request arrived over https (``X-Forwarded-Proto``). + ``Secure`` when the request arrived over https (``X-Forwarded-Proto``) or + when ``ADMIN_COOKIE_SECURE`` is truthy (TLS-only deployments behind an + HTTP origin listener, where Envoy normalizes the header to ``http``). * **CSRF.** State-changing admin requests that carry an ``Origin``/``Referer`` are rejected when the origin host differs from the request host. Requests without either header (curl, server-to-server) are allowed — the signed, @@ -94,6 +96,7 @@ PUBLIC_GET_EXACT = frozenset({ "/api/news/summaries", "/api/news/ticker", "/api/news/map", + "/api/news/blips", # map / live layers "/api/map/layers", "/api/map/chokepoints", @@ -281,6 +284,18 @@ def _is_https(request: Request) -> bool: return request.url.scheme == "https" +_TRUTHY = {"1", "true", "yes"} + + +def cookie_secure_forced() -> bool: + """``ADMIN_COOKIE_SECURE`` marks the deployment TLS-only. + + Read on every call so tests and restarts pick up env changes; the header + inference in :func:`_is_https` stays as the fallback. + """ + return (os.getenv("ADMIN_COOKIE_SECURE") or "").strip().lower() in _TRUTHY + + def set_session_cookie(response, request: Request, token: str) -> None: response.set_cookie( COOKIE_NAME, @@ -288,7 +303,7 @@ def set_session_cookie(response, request: Request, token: str) -> None: max_age=SESSION_TTL_SECONDS, httponly=True, samesite="lax", - secure=_is_https(request), + secure=cookie_secure_forced() or _is_https(request), path="/", ) diff --git a/app/camera_config.py b/app/camera_config.py index 2ccff69..7376087 100644 --- a/app/camera_config.py +++ b/app/camera_config.py @@ -59,7 +59,8 @@ SNAPSHOT_CACHE_DIR = os.getenv("SNAPSHOT_CACHE_DIR", "/data/snapshots") SNAPSHOT_TTL_SECONDS = int(os.getenv("SNAPSHOT_TTL_SECONDS", "300")) SNAPSHOT_TIMEOUT = float(os.getenv("SNAPSHOT_TIMEOUT", "8.0")) -# NATS subject cameras are published on (consumed by the shared ingester). +# Retained so an old CAMERA_NATS_SUBJECT env does not surprise operators. +# This service does not publish on it; cameras live in the cameras table. CAMERA_NATS_SUBJECT = os.getenv("CAMERA_NATS_SUBJECT", "events.camera") diff --git a/app/camera_scraper.py b/app/camera_scraper.py index 10dde21..d1ca366 100644 --- a/app/camera_scraper.py +++ b/app/camera_scraper.py @@ -11,8 +11,8 @@ Pipeline per cycle: 2. Parse cameras (Insecam-style HTML with embedded lat/lon, or plain-text `url[|lat,lon|vendor|location]` lines). 3. Geocode missing coords via Nominatim at <=1 req/s. - 4. Publish each camera to NATS (`events.camera`) for the shared ingester, - and upsert into the `cameras` table keyed by sha256(url_hash). + 4. Upsert into the `cameras` table keyed by sha256(url_hash). + Discovery is not published as an event. Snapshots are cached locally with a TTL; nothing is fetched more often than the cache allows. diff --git a/app/config.py b/app/config.py index b2bdab8..ea89a8d 100644 --- a/app/config.py +++ b/app/config.py @@ -107,3 +107,12 @@ VESSELAPI_MAX_CALLS_PER_DAY = int(os.getenv("VESSELAPI_MAX_CALLS_PER_DAY", "5")) # Run the VesselAPI poller inside the dashboard process (default on, like AIS). VESSELAPI_IN_APP = os.getenv("VESSELAPI_IN_APP", "1").lower() in ("1", "true", "yes") VESSELAPI_IN_INGEST = os.getenv("VESSELAPI_IN_INGEST", "0").lower() in ("1", "true", "yes") + +# ADS-B (ADSB.lol, no key). The dashboard's refresh loop follows browser +# viewports; with no tab open it persisted nothing and aircraft_positions went +# silent for a day. ADSB_WATCH_ENABLED=1 makes the loop sweep the chokepoint +# presets while idle, so the hypertable keeps advancing unattended. +ADSB_REFRESH_INTERVAL = float(os.getenv("ADSB_REFRESH_INTERVAL", "8")) +ADSB_WATCH_ENABLED = os.getenv("ADSB_WATCH_ENABLED", "1").lower() in ("1", "true", "yes") +# Idle sweep cadence; 30 s over 5 preset boxes ≈ 0.17 req/s to ADSB.lol. +ADSB_WATCH_INTERVAL = float(os.getenv("ADSB_WATCH_INTERVAL", "30")) diff --git a/app/geofence.py b/app/geofence.py index f010a3f..342f1c4 100644 --- a/app/geofence.py +++ b/app/geofence.py @@ -7,6 +7,7 @@ in ``geofence_alerts`` and fan out as WS type ``geofence_alert``. from __future__ import annotations import json +import logging from datetime import datetime, timedelta, timezone from typing import Any from uuid import uuid4 @@ -15,6 +16,19 @@ from sqlalchemy import text from database import async_session +logger = logging.getLogger("osint.geofence") + +# New hit kinds. adsb/ais/firms omit ``evidence``; these three must include it. +# ``camera`` is never a hit kind. +EVIDENCE_KINDS = frozenset({"earthquake", "fire_incident", "news"}) +_CAMERA_CAP = 5 +_NEWS_CAP = 3 +# Process-local "already paged" set for polled incidents. The 5-minute +# cooldown still applies; this stops a later poll (or a restart that +# re-reads the DB check) from treating a durable hit as new. Not used +# for moving adsb/ais/firms targets. +_notified_once: set[tuple[str, str, str]] = set() + def _rings_from_geojson(geojson: dict) -> list[list[list[float]]]: if not isinstance(geojson, dict): @@ -99,6 +113,160 @@ _recent_hits: dict[tuple[str, str], datetime] = {} _HIT_COOLDOWN = timedelta(minutes=5) +def iso_z(ts: datetime) -> str: + """UTC ISO-8601 with a Z suffix so it is safe in a query string.""" + if ts.tzinfo is None: + ts = ts.replace(tzinfo=timezone.utc) + return ts.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def snapshot_path(gid: str, ts: datetime) -> str: + return f"/api/geofences/{gid}/at?ts={iso_z(ts)}" + + +def camera_evidence(row: dict) -> dict: + """Proxy path only. Never copy ``cameras.snapshot_url`` (agency / rtsp).""" + cid = str(row.get("id") or "") + name = row.get("name") + if name is None: + name = row.get("location_name") or "" + return { + "id": cid, + "name": str(name or ""), + "snapshot_url": f"/api/cameras/{cid}/snapshot", + } + + +def news_evidence(row: dict) -> dict: + return { + "headline": str(row.get("headline") or ""), + "url": str(row.get("url") or ""), + "importance": str(row.get("importance") or ""), + } + + +def evidence_pack( + gid: str, ts: datetime, cameras: list[dict], news: list[dict], +) -> dict: + return { + "cameras": [camera_evidence(r) for r in cameras[:_CAMERA_CAP]], + "news": [news_evidence(r) for r in news[:_NEWS_CAP]], + "snapshot": snapshot_path(gid, ts), + } + + +def polygon_bbox(geojson: dict) -> str | None: + """``minlon,minlat,maxlon,maxlat`` of the outer ring, or None.""" + try: + rings = _rings_from_geojson(geojson) + except (ValueError, TypeError, KeyError): + return None + pts = rings[0] + lons = [p[0] for p in pts] + lats = [p[1] for p in pts] + return f"{min(lons)},{min(lats)},{max(lons)},{max(lats)}" + + +def earthquake_entity_id(row: dict) -> str: + """Stable id shared by the insert hook and the catch-up scan.""" + raw = row.get("raw") + if isinstance(raw, str): + try: + raw = json.loads(raw) + except ValueError: + raw = None + if isinstance(raw, dict) and raw.get("usgs_id"): + return str(raw["usgs_id"]) + url = row.get("url") + if url and str(url).strip(): + return str(url).strip() + return str(row.get("id") or row.get("event_id") or "") + + +def fire_incident_entity_id(marker: dict) -> str: + """IrwinID when the feed has one, else a stable name|state|discovered key.""" + extra = marker.get("extra") or {} + for key in ("irwin_id", "unique_fire_id"): + val = extra.get(key) + if val: + return str(val) + name = marker.get("id") or marker.get("label") or "incident" + state = extra.get("state") or "" + discovered = extra.get("discovered") or "" + return f"{name}|{state}|{discovered}" + + +# Do not SELECT cameras.snapshot_url — that column is the agency/rtsp URL. +_CAMERAS_INSIDE_SQL = """ + SELECT id::text AS id, + COALESCE(location_name, '') AS name + FROM cameras + WHERE location_lat IS NOT NULL + AND location_lon IS NOT NULL + AND ST_Intersects( + (SELECT geom FROM geofences WHERE id = CAST(:gid AS uuid)), + ST_SetSRID(ST_MakePoint(location_lon, location_lat), 4326) + ) + ORDER BY ST_Distance( + ST_SetSRID(ST_MakePoint(location_lon, location_lat), 4326), + ST_SetSRID(ST_MakePoint(:lon, :lat), 4326) + ) + LIMIT :limit +""" + +_NEWS_INSIDE_SQL = """ + SELECT headline, + COALESCE(url, '') AS url, + COALESCE(importance, '') AS importance + FROM news_items + WHERE lat IS NOT NULL + AND lon IS NOT NULL + AND ST_Intersects( + (SELECT geom FROM geofences WHERE id = CAST(:gid AS uuid)), + ST_SetSRID(ST_MakePoint(lon, lat), 4326) + ) + ORDER BY created_at DESC + LIMIT :limit +""" + +_ALREADY_SQL = """ + SELECT 1 + FROM geofence_alerts + WHERE geofence_id = CAST(:gid AS uuid) + AND source_kind = :source_kind + AND entity_id = :entity_id + LIMIT 1 +""" + + +async def _rows(sql: str, params: dict) -> list[dict]: + async with async_session() as session: + result = await session.execute(text(sql), params) + return [dict(r) for r in result.mappings().all()] + + +async def build_evidence( + gid: str, *, lat: float, lon: float, now: datetime, +) -> dict: + """Cameras nearest the hit (≤5) and news most-recent (≤3) inside the fence. + + Empty arrays if none or the query fails. Snapshot is a path, not a body. + """ + cameras: list[dict] = [] + news: list[dict] = [] + try: + cameras = await _rows(_CAMERAS_INSIDE_SQL, { + "gid": gid, "lat": lat, "lon": lon, "limit": _CAMERA_CAP, + }) + except Exception: + logger.exception("evidence cameras query failed gid=%s", gid) + try: + news = await _rows(_NEWS_INSIDE_SQL, {"gid": gid, "limit": _NEWS_CAP}) + except Exception: + logger.exception("evidence news query failed gid=%s", gid) + return evidence_pack(gid, now, cameras, news) + + async def refresh_cache() -> list[dict]: global _cache async with async_session() as session: @@ -249,12 +417,24 @@ async def record_and_notify( lat: float, lon: float, payload: dict[str, Any] | None = None, + skip_existing: bool = False, ) -> int: """Insert a geofence_alerts row per hit and WS-push to viewport clients. PostGIS ST_Intersects is the source of truth. The in-process GeoJSON cache is not a reject filter — the FIRMS ingester never fills it. + + ``source_kind=camera`` is refused (no row, no WS). Earthquake, fire + incident, and news hits get an ``evidence`` object; adsb/ais/firms + keep the caller payload unchanged. + + ``skip_existing`` is for polled incidents (same id every cycle). It + does not change the 5-minute cooldown. A failed existence check + skips the hit so a broken read cannot page every fence. """ + if source_kind == "camera": + logger.warning("refusing geofence notify for source_kind=camera") + return 0 hits = await st_intersects(lon, lat) if not hits: return 0 @@ -275,6 +455,33 @@ async def record_and_notify( hits = fresh async with async_session() as session: for fence in hits: + once_key = (str(fence["id"]), source_kind, str(entity_id)) + if skip_existing: + if once_key in _notified_once: + continue + try: + existing = await session.execute( + text(_ALREADY_SQL), + { + "gid": fence["id"], + "source_kind": source_kind, + "entity_id": str(entity_id), + }, + ) + if existing.first() is not None: + _notified_once.add(once_key) + continue + except Exception: + logger.exception( + "geofence existing-hit check failed kind=%s entity=%s", + source_kind, entity_id, + ) + continue + body_payload = dict(payload or {}) + if source_kind in EVIDENCE_KINDS: + body_payload["evidence"] = await build_evidence( + str(fence["id"]), lat=lat, lon=lon, now=now, + ) aid = str(uuid4()) body = { "id": aid, @@ -284,7 +491,7 @@ async def record_and_notify( "entity_id": str(entity_id), "lat": lat, "lon": lon, - "payload": payload or {}, + "payload": body_payload, "created_at": now.isoformat(), } try: @@ -306,7 +513,7 @@ async def record_and_notify( "entity_id": str(entity_id), "lat": lat, "lon": lon, - "payload": json.dumps(payload or {}), + "payload": json.dumps(body_payload), }, ) except Exception: @@ -314,6 +521,8 @@ async def record_and_notify( sent += await manager.publish_point( "geofence_alert", body, lat=lat, lon=lon, ) + if skip_existing: + _notified_once.add(once_key) try: await session.commit() except Exception: @@ -470,3 +679,166 @@ async def snapshot_at(gid: str, ts: datetime) -> dict | None: "vessels": vessels, "fires": fires, } + + +_QUAKE_SCAN_SQL = """ + SELECT id::text AS id, url, title, location_lat, location_lon, raw + FROM events + WHERE source_type = 'earthquake' + AND location_lat IS NOT NULL + AND location_lon IS NOT NULL + AND source_timestamp >= now() - interval '7 days' + ORDER BY source_timestamp DESC + LIMIT :limit +""" + +# Same pin set as GET /api/news/map: kind=map, flagged, coords, last 24h. +_NEWS_SCAN_SQL = """ + SELECT id::text AS id, headline, url, importance, lat, lon + FROM news_items + WHERE kind = 'map' + AND lat IS NOT NULL + AND lon IS NOT NULL + AND importance IN ('critical', 'high') + AND created_at >= now() - interval '24 hours' + ORDER BY created_at DESC + LIMIT :limit +""" + + +async def scan_earthquakes(limit: int = 200) -> int: + """Catch-up: quakes already in ``events`` when a fence is drawn later.""" + try: + rows = await _rows(_QUAKE_SCAN_SQL, {"limit": int(limit)}) + except Exception: + logger.exception("earthquake geofence scan failed") + return 0 + n = 0 + for row in rows: + lat, lon = row.get("location_lat"), row.get("location_lon") + if lat is None or lon is None: + continue + eid = earthquake_entity_id(row) + if not eid: + continue + try: + n += await record_and_notify( + source_kind="earthquake", + entity_id=eid, + lat=float(lat), + lon=float(lon), + payload={"title": row.get("title"), "url": row.get("url") or ""}, + skip_existing=True, + ) + except Exception: + logger.exception("earthquake geofence notify failed entity=%s", eid) + return n + + +async def scan_news_pins(limit: int = 200) -> int: + """Read ``news_items`` map pins. Does not import the summarizer.""" + try: + rows = await _rows(_NEWS_SCAN_SQL, {"limit": int(limit)}) + except Exception: + logger.exception("news geofence scan failed") + return 0 + n = 0 + for row in rows: + lat, lon = row.get("lat"), row.get("lon") + if lat is None or lon is None: + continue + eid = str(row.get("id") or "") + if not eid: + continue + try: + n += await record_and_notify( + source_kind="news", + entity_id=eid, + lat=float(lat), + lon=float(lon), + payload={ + "headline": row.get("headline") or "", + "url": row.get("url") or "", + "importance": row.get("importance") or "", + }, + skip_existing=True, + ) + except Exception: + logger.exception("news geofence notify failed entity=%s", eid) + return n + + +async def poll_fire_incidents(fences: list[dict] | None = None) -> int: + """WFIGS incidents are not stored. Fetch each active fence's bbox. + + ``load_fire_incidents`` does not mutate the map cache or correlate + aircraft. A point in the bbox but outside the polygon is dropped + before ``record_and_notify``; ST_Intersects is still the write guard. + """ + if fences is None: + fences = [f for f in cached_fences() if f.get("active", True)] + from live_layers import load_fire_incidents + + n = 0 + seen: set[str] = set() + for fence in fences: + if not fence.get("active", True): + continue + bbox = polygon_bbox(fence.get("geojson") or {}) + if not bbox: + continue + try: + incidents = await load_fire_incidents(bbox) + except Exception: + logger.exception("wfigs fence poll failed bbox=%s", bbox) + continue + if not isinstance(incidents, list): + continue + for inc in incidents: + if not isinstance(inc, dict): + continue + lat, lon = inc.get("lat"), inc.get("lon") + if lat is None or lon is None: + continue + if not point_in_geojson(float(lon), float(lat), fence.get("geojson") or {}): + continue + eid = fire_incident_entity_id(inc) + if not eid or eid in seen: + continue + seen.add(eid) + try: + n += await record_and_notify( + source_kind="fire_incident", + entity_id=eid, + lat=float(lat), + lon=float(lon), + payload={ + "label": inc.get("label"), + "extra": inc.get("extra") or {}, + }, + skip_existing=True, + ) + except Exception: + logger.exception("fire_incident geofence notify failed entity=%s", eid) + return n + + +async def scan_geofence_feeds() -> int: + """Ingester-loop catch-up. No-op when no active fence is cached. + + Earthquakes also notify on insert (``ingestor.ingest_event``). This + scan covers rows already stored, WFIGS (not persisted), and news + pins written by the summarizer process. + """ + try: + await refresh_cache() + except Exception: + logger.exception("geofence cache refresh failed") + fences = [f for f in cached_fences() if f.get("active", True)] + if not fences: + return 0 + n = 0 + n += await scan_earthquakes() + n += await scan_news_pins() + n += await poll_fire_incidents(fences) + return n diff --git a/app/ingestor.py b/app/ingestor.py index ccf1471..8b2e07c 100644 --- a/app/ingestor.py +++ b/app/ingestor.py @@ -219,9 +219,32 @@ async def ingest_event(msg: dict): await session.commit() event_id = result.inserted_primary_key[0] # type: ignore[union-attr] logger.info("Ingested event %s from source %s", event_id, msg.get("source_type")) + # Cameras are persisted as events only. Never a geofence hit. + if event_row["source_type"] == "earthquake": + await _notify_earthquake(event_row, event_id) return event_id +async def _notify_earthquake(event_row: dict, event_id) -> None: + """One hit per new quake. Dedup already dropped replays; skip if no point.""" + lat, lon = event_row.get("location_lat"), event_row.get("location_lon") + if lat is None or lon is None: + return + try: + from geofence import earthquake_entity_id, record_and_notify + row = {**event_row, "id": str(event_id)} + await record_and_notify( + source_kind="earthquake", + entity_id=earthquake_entity_id(row), + lat=float(lat), + lon=float(lon), + payload={"title": event_row.get("title"), "url": event_row.get("url") or ""}, + skip_existing=True, + ) + except Exception: + logger.exception("earthquake geofence notify failed") + + async def start_nats_consumer(): """Start NATS JetStream consumer for OSINT events.""" nc = await nats.connect(NATS_URLS) diff --git a/app/live_layers.py b/app/live_layers.py index 99d28ac..3c1d92e 100644 --- a/app/live_layers.py +++ b/app/live_layers.py @@ -743,18 +743,25 @@ def transform_wfigs_incidents(fc: dict | None) -> list[dict]: continue props = feat.get("properties") or {} name = str(props.get("IncidentName") or "Incident").strip() + extra = { + "acres": props.get("IncidentSize"), + "contained": props.get("PercentContained"), + "state": props.get("POOState"), + "category": props.get("IncidentTypeCategory"), + "cause": props.get("FireCause"), + "discovered": props.get("FireDiscoveryDateTime"), + "src": "wfigs", + } + irwin = props.get("IrwinID") + if irwin: + extra["irwin_id"] = str(irwin) + ufi = props.get("UniqueFireIdentifier") + if ufi: + extra["unique_fire_id"] = str(ufi) out.append(to_marker( name, lat, lon, label=name, - extra={ - "acres": props.get("IncidentSize"), - "contained": props.get("PercentContained"), - "state": props.get("POOState"), - "category": props.get("IncidentTypeCategory"), - "cause": props.get("FireCause"), - "discovered": props.get("FireDiscoveryDateTime"), - "src": "wfigs", - }, + extra=extra, )) return out @@ -1084,17 +1091,27 @@ def _wfigs_params(bbox: str | None, *, offset_m: float = 250.0) -> dict: return params -async def fetch_fire_incidents(bbox: str | None, limit: int = DEFAULT_LIMIT) -> list[dict]: +_WFIGS_INCIDENT_FIELDS = ( + "IncidentName,IncidentSize,FireDiscoveryDateTime,POOState," + "PercentContained,IncidentTypeCategory,FireCause," + "IrwinID,UniqueFireIdentifier" +) + + +async def load_fire_incidents(bbox: str | None) -> list[dict]: + """WFIGS points for a bbox. No last-known mutation, no aircraft correlate.""" params = _wfigs_params(bbox) - params["outFields"] = ( - "IncidentName,IncidentSize,FireDiscoveryDateTime,POOState," - "PercentContained,IncidentTypeCategory,FireCause" - ) + params["outFields"] = _WFIGS_INCIDENT_FIELDS async def _load(): return transform_wfigs_incidents(await _get_json(WFIGS_INCIDENTS, params)) rows = await _ttl_get(f"wfigs:inc:{bbox_cell_key(bbox)}", 600.0, _load) + return list(rows or []) + + +async def fetch_fire_incidents(bbox: str | None, limit: int = DEFAULT_LIMIT) -> list[dict]: + rows = await load_fire_incidents(bbox) fire_last_known[:] = list(rows) if rows and aircraft_last_known: from fire_aircraft import correlate_and_notify diff --git a/app/main.py b/app/main.py index 2d7a3f6..00d0d6f 100644 --- a/app/main.py +++ b/app/main.py @@ -37,13 +37,13 @@ from database import async_session, init_extensions from auth import AdminAuthMiddleware, router as auth_router from models import ( alerts, documents, entities, entity_events, events, feed_sources, fires, - articles, article_summaries, news_items, + articles, article_scores, article_summaries, news_items, ) from schemas import ( AlertCreate, AlertOut, AlertSeverity, AlertType, AlertUpdate, ConflictZoneOut, ConflictsOut, DashboardSummary, EntityCreate, EntityKind, EntityOut, - EventCreate, EventOut, FireOut, NewsArticleOut, NewsMapItemOut, + EventCreate, EventOut, FireOut, NewsArticleOut, NewsBlipOut, NewsMapItemOut, NewsSummaryOut, NewsTickerItemOut, FeedSourceCreate, FeedSourceOut, FeedSourceUpdate, KeyOut, KeyValueIn, @@ -57,6 +57,7 @@ from camera_scraper import is_public_url from sources import GDELT_API, ingest_rss_feed, ingest_gdelt, ingest_earthquakes, ingest_social_signals from fire_sources import ingest_fires from keystore import KeyFormatError, delete_key, list_keys, set_key +from news_title import unwrap_cdata_title from settings_store import SettingsError, get_app_settings, list_models, set_summary_model from live_layers import ( fetch_aircraft, fetch_fire_incidents, fetch_fire_perimeters, @@ -125,14 +126,49 @@ app.include_router(auth_router) STATIC_DIR = Path(__file__).parent / "static" +def _adsb_watch_boxes() -> list[tuple[float, float, float, float]]: + """Chokepoint presets as viewport boxes (minlon, minlat, maxlon, maxlat). + + Used only while no browser viewport is registered: without it the refresh + loop persists nothing and ``aircraft_positions`` silently stalls whenever + nobody has the map open. + """ + from chokepoints import chokepoints + + out: list[tuple[float, float, float, float]] = [] + for preset in chokepoints(): + try: + # Preset bboxes are minlat,minlon,maxlat,maxlon (VesselAPI order). + minlat, minlon, maxlat, maxlon = (float(v) for v in str(preset["bbox"]).split(",")) + except (KeyError, TypeError, ValueError): + continue + out.append((minlon, minlat, maxlon, maxlat)) + return out + + async def _adsb_refresh_loop() -> None: - """Poll ADSB.lol for connected viewports — never from GET /api/aircraft.""" + """Poll ADSB.lol for connected viewports — never from GET /api/aircraft. + + When no client viewport is registered the loop sweeps the watch boxes + (chokepoint presets) at ``ADSB_WATCH_INTERVAL`` so aircraft ingest keeps + advancing with no map open. + """ from ws_manager import manager from live_layers import fetch_aircraft + from config import ADSB_REFRESH_INTERVAL, ADSB_WATCH_ENABLED, ADSB_WATCH_INTERVAL + + watch_boxes: list[tuple[float, float, float, float]] | None = None while True: + interval = ADSB_REFRESH_INTERVAL try: boxes = manager.viewports() + if not boxes and ADSB_WATCH_ENABLED: + if watch_boxes is None: + watch_boxes = _adsb_watch_boxes() + boxes = watch_boxes + interval = ADSB_WATCH_INTERVAL + logger.debug("adsb_idle_watch", boxes=len(boxes)) for box in boxes: bbox = f"{box[0]},{box[1]},{box[2]},{box[3]}" try: @@ -141,7 +177,7 @@ async def _adsb_refresh_loop() -> None: logger.warning("adsb_refresh_failed", error=str(exc)) except Exception as exc: # noqa: BLE001 logger.warning("adsb_refresh_loop", error=str(exc)) - await asyncio.sleep(8) + await asyncio.sleep(interval) class CachedStaticFiles(StaticFiles): @@ -272,7 +308,14 @@ async def _pipeline_checks(session) -> dict: await _age("SELECT max(ingested_at) FROM events", "events", 20 * 60) await _age("SELECT max(ingested_at) FROM fires", "fires", 30 * 60) - await _age("SELECT max(timestamp) FROM articles", "articles", 2 * 3600) + # Same closed-at-now window as GET /api/news. A future max() made age_s + # negative and hid a fresh list. NULL timestamps are not fresh. + await _age( + "SELECT max(timestamp) FROM articles " + "WHERE timestamp IS NOT NULL AND timestamp <= now()", + "articles", + 2 * 3600, + ) await _age("SELECT max(batch_timestamp) FROM article_summaries", "summaries", 2 * 3600) return checks @@ -298,7 +341,7 @@ async def _stats_counts() -> dict: aircraft_last_known, vessel_last_known, train_count, nws_alert_count, ) - counts: dict[str, int | str] = { + counts: dict = { "aircraft": len(aircraft_last_known), "vessels": len(vessel_last_known), "trains": train_count, @@ -330,9 +373,41 @@ async def _stats_counts() -> dict: logger.warning("stats_db_failed", error=str(exc)) counts["timestamp"] = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") + # Public booleans only. Never include the stored value, a prefix, or last-4. + counts["feeds"] = await _feed_flags() return counts +async def _key_configured(*names: str) -> bool: + """True when any named key has a non-empty value in the api_keys store. + + Uses keystore.get_api_key — not env, not a second store. The value is + discarded after the emptiness check. + """ + from keystore import get_api_key + + for name in names: + value = await get_api_key(name) + if isinstance(value, str) and value.strip(): + return True + return False + + +async def _feed_flags() -> dict: + """HUD layer flags. Fail closed (configured false) if the store is down.""" + try: + vessels = await _key_configured("AISSTREAM_API_KEY", "VESSELAPI_API_KEY") + fires = await _key_configured("FIRMS_MAP_KEY") + except Exception as exc: # noqa: BLE001 + logger.warning("stats_feed_flags_failed", error=str(exc)) + vessels = False + fires = False + return { + "vessels": {"configured": vessels}, + "fires": {"configured": fires}, + } + + @app.get("/api/stats") async def api_stats(): """Cheap HUD counters (counts only — no GeoJSON). Cached ~20 s.""" @@ -1293,7 +1368,12 @@ async def list_news( ): """Most recent scraped news articles (newest first).""" async with async_session() as session: - stmt = select(articles).order_by( + stmt = select(articles).where( + or_( + articles.c.timestamp.is_(None), + articles.c.timestamp <= func.now(), + ) + ).order_by( articles.c.timestamp.desc().nullslast() ) if domain: @@ -1304,7 +1384,7 @@ async def list_news( rows = (await session.execute(stmt)).mappings().all() return [ NewsArticleOut( - id=r["id"], title=r["title"], url=r["url"], + id=r["id"], title=unwrap_cdata_title(r["title"]), url=r["url"], content=r["content"] if include_content else None, domain=r["domain"], timestamp=r["timestamp"], ) @@ -1457,6 +1537,94 @@ async def list_news_map( ] +@app.get("/api/news/blips", response_model=list[NewsBlipOut]) +async def list_news_blips( + bbox: str | None = Query( + None, + description="Comma-separated 'minlon,minlat,maxlon,maxlat' to bound the " + "result set by article coordinates. Omit for all blips.", + ), + since: datetime | None = Query( + None, + description="Only gradings created at/after this UTC instant. " + "Defaults to the last 24 hours.", + ), + limit: int = Query(1000, ge=1, le=5000), +): + """Per-article proximate geo blips: EVERY graded article with a derivable + location (not just the critical/high map pins). Deduped by article id — + the latest grading's geo wins. Only finite lat/lon rows, newest first. + """ + if since is None: + since = datetime.now(timezone.utc) - timedelta(hours=24) + async with async_session() as session: + # DISTINCT ON (article_id) + ORDER BY article_id, created_at DESC + # keeps the latest grading per article; the outer query re-sorts + # newest-first and applies the limit. NaN is excluded explicitly: + # Postgres sorts NaN above every finite value, so range checks + # alone would let it through. prefix_with keeps this renderable on + # both SQLAlchemy 2.0 and 2.1 (requirements pin >=2.0). + stmt = ( + select( + article_scores.c.article_id.label("id"), + articles.c.title.label("headline"), + articles.c.url, + articles.c.domain, + article_scores.c.location_name, + article_scores.c.lat, + article_scores.c.lon, + article_scores.c.location_confidence, + article_scores.c.category, + article_scores.c.score, + article_scores.c.created_at, + ) + .select_from( + article_scores.join(articles, articles.c.id == article_scores.c.article_id) + ) + .where( + article_scores.c.lat.isnot(None), + article_scores.c.lon.isnot(None), + article_scores.c.lat.between(-90, 90), + article_scores.c.lon.between(-180, 180), + text("article_scores.lat <> 'NaN'::double precision"), + text("article_scores.lon <> 'NaN'::double precision"), + article_scores.c.created_at >= since, + ) + .prefix_with("DISTINCT ON (article_scores.article_id)") + .order_by(article_scores.c.article_id, article_scores.c.created_at.desc()) + ) + if bbox: + parts = [p.strip() for p in bbox.split(",")] + if len(parts) != 4: + raise HTTPException( + 422, "bbox must be 'minlon,minlat,maxlon,maxlat' (4 comma-separated values)" + ) + try: + minlon, minlat, maxlon, maxlat = (float(p) for p in parts) + except ValueError: + raise HTTPException( + 422, "bbox values must be floats: 'minlon,minlat,maxlon,maxlat'" + ) + stmt = stmt.where( + and_( + article_scores.c.lon >= minlon, article_scores.c.lon <= maxlon, + article_scores.c.lat >= minlat, article_scores.c.lat <= maxlat, + ) + ) + latest = stmt.subquery() + ordered = select(latest).order_by(latest.c.created_at.desc()).limit(limit) + rows = (await session.execute(ordered)).mappings().all() + return [ + NewsBlipOut( + id=r["id"], headline=r["headline"] or "", url=r["url"], domain=r["domain"], + location_name=r["location_name"], lat=r["lat"], lon=r["lon"], + location_confidence=r["location_confidence"], category=r["category"], + score=r["score"], created_at=r["created_at"], + ) + for r in rows + ] + + @app.get("/api/news/models", response_model=NewsModelsOut) async def list_news_models(): """Nous model catalog for the summarizer selector. Never 502s.""" @@ -1783,24 +1951,31 @@ async def api_delete_geofence(gid: str): @app.get("/api/geofences/{gid}/at") async def api_geofence_at( gid: str, - timestamp: str = Query(..., description="ISO-8601 instant for the 1-minute DVR bucket"), + timestamp: str | None = Query( + None, description="ISO-8601 instant for the 1-minute DVR bucket", + ), + ts: str | None = Query( + None, + description="Alias of timestamp. Evidence snapshot URLs use this name.", + ), ): """Aircraft/vessels/fires inside this fence at time T. Never writes.""" from geofence import snapshot_at from tracks import parse_timestamp + raw_ts = timestamp or ts try: - ts = parse_timestamp(timestamp) + ts_parsed = parse_timestamp(raw_ts) except ValueError as exc: raise HTTPException(422, str(exc)) from exc - if ts is None: + if ts_parsed is None: raise HTTPException(422, "timestamp required") try: - body = await snapshot_at(gid, ts) + body = await snapshot_at(gid, ts_parsed) except Exception: body = { "geofence_id": gid, - "timestamp": ts.isoformat(), + "timestamp": ts_parsed.isoformat(), "aircraft": [], "vessels": [], "fires": [], @@ -1815,15 +1990,23 @@ async def api_geofence_alerts( geofence_id: UUID | None = Query(None), since: str | None = Query(None, description="ISO-8601 inclusive lower bound"), until: str | None = Query(None, description="ISO-8601 inclusive upper bound"), - source_kind: str | None = Query(None, description="firms|ais|adsb"), + source_kind: str | None = Query( + None, + description="firms|ais|adsb|earthquake|fire_incident|news", + ), limit: int = Query(100, ge=1, le=500), ): """Hit log for drawn fences. Not /api/alerts (entity/keyword).""" from geofence import list_alerts from tracks import parse_timestamp - if source_kind is not None and source_kind not in ("firms", "ais", "adsb"): - raise HTTPException(422, "source_kind must be one of: firms, ais, adsb") + if source_kind is not None and source_kind not in ( + "firms", "ais", "adsb", "earthquake", "fire_incident", "news", + ): + raise HTTPException( + 422, + "source_kind must be one of: firms, ais, adsb, earthquake, fire_incident, news", + ) try: since_ts = parse_timestamp(since) if since else None until_ts = parse_timestamp(until) if until else None diff --git a/app/models.py b/app/models.py index f3b528d..4ffbb96 100644 --- a/app/models.py +++ b/app/models.py @@ -4,7 +4,7 @@ from datetime import datetime, timezone from uuid import uuid4 from sqlalchemy import ( - Column, Enum, Float, Index, Integer, String, Text, + Boolean, Column, Enum, Float, Index, Integer, String, Text, DateTime, JSON, func, Table, PrimaryKeyConstraint, ) from sqlalchemy.dialects.postgresql import UUID, TSVECTOR @@ -242,3 +242,34 @@ news_items = Table( Column("created_at", DateTime(timezone=True), server_default=func.now(), nullable=False), ) Index("ix_news_items_kind_created", news_items.c.kind, news_items.c.created_at) + + +# Per-article map-phase grades (alembic 012/013/014). One row per graded +# article per run; PK (article_id, created_at) lets re-grades accumulate. +# Geo columns are nullable: only articles with a derivable location carry +# coordinates, served by GET /api/news/blips. +article_scores = Table( + "article_scores", + metadata, + Column("article_id", Integer, nullable=False), + Column("summary_id", Integer), + Column("score", Integer, nullable=False), + Column("category", Text), + Column("selected", Boolean, nullable=False), + Column("model", Text), + Column("duplicate_of", Integer), + Column("location_name", Text), + Column("lat", Float), + Column("lon", Float), + Column("location_confidence", Text), + Column("created_at", DateTime(timezone=True), + server_default=func.now(), nullable=False), + PrimaryKeyConstraint("article_id", "created_at"), +) +Index("ix_article_scores_summary", article_scores.c.summary_id) +Index( + "ix_article_scores_geo_bbox", + article_scores.c.lon, article_scores.c.lat, + postgresql_where=article_scores.c.lat.isnot(None) + & article_scores.c.lon.isnot(None), +) diff --git a/app/news_title.py b/app/news_title.py new file mode 100644 index 0000000..29ada1d --- /dev/null +++ b/app/news_title.py @@ -0,0 +1,33 @@ +"""News title cleanup for the read path. + +Same rule as ``news/scraper/newsScraper/feed_util.py:unwrap_cdata_title``. +The API image does not include the scraper package, so the function is +copied rather than imported. Existing rows are fixed here on read; this +module does not write. +""" + +from __future__ import annotations + +import re + +# Whole-title CDATA wrapper only. Leading/trailing whitespace around the +# markers belongs to the wrapper, not the title. +_CDATA_WRAPPER = re.compile( + r"\A\s*\s*\Z", + re.DOTALL, +) + + +def unwrap_cdata_title(title: str | None) -> str | None: + """Strip a surrounding CDATA wrapper. Anything else is unchanged. + + ```` and ``\\n `` become + ``Hello``. Real HTML (``Hello``) and a title that merely contains + the markers are returned as-is. Non-strings pass through. + """ + if not isinstance(title, str): + return title + match = _CDATA_WRAPPER.match(title) + if match is None: + return title + return match.group(1).strip() diff --git a/app/run_camera_service.py b/app/run_camera_service.py index c550d04..74d774f 100644 --- a/app/run_camera_service.py +++ b/app/run_camera_service.py @@ -1,9 +1,10 @@ """Long-running camera discovery service. -Follows the existing ingest pattern: discovers cameras on an interval and -publishes each one as a NATS message (`events.camera`) so the shared NATS -> -ingester pipeline persists them; also upserts directly into the `cameras` -table (dedupe by url_hash) for the /api/cameras bbox query. +Discovers cameras on an interval and upserts them into the `cameras` table +(dedupe by url_hash) for the /api/cameras bbox query. Discovery is not an +event: this process does not publish `events.camera` messages. Those were +inserted as events rows and flooded the HUD feed. The cameras table is the +index. Env: CAMERA_SOURCE_URLS comma-separated public directory/list URLs @@ -14,7 +15,6 @@ Env: from __future__ import annotations import asyncio -import json import logging import sys from pathlib import Path @@ -22,16 +22,12 @@ from pathlib import Path sys_path = str(Path(__file__).parent) sys.path.insert(0, sys_path) -import nats # noqa: E402 - from camera_config import ( # noqa: E402 - CAMERA_SOURCE_URLS, CAMERA_SCRAPE_INTERVAL, CAMERA_NATS_SUBJECT, + CAMERA_SOURCE_URLS, CAMERA_SCRAPE_INTERVAL, SNAPSHOT_CACHE_DIR, ) -from camera_models import cameras # noqa: E402 -from camera_scraper import run_cycle, url_hash # noqa: E402 -from database import async_session, init_extensions # noqa: E402 -from config import NATS_URL # noqa: E402 +from camera_scraper import run_cycle # noqa: E402 +from database import init_extensions # noqa: E402 logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s") @@ -40,48 +36,16 @@ logger = logging.getLogger("osint.camera_service") ENABLED = sys.argv[1:] != ["--once"] -async def publish_new_cameras() -> int: - """Publish cameras seen in the latest cycle to NATS for the ingester.""" - from datetime import datetime, timezone, timedelta - cutoff = datetime.now(timezone.utc) - timedelta(seconds=CAMERA_SCRAPE_INTERVAL * 2) - published = 0 - try: - nc = await nats.connect(NATS_URL) - except Exception: # noqa: BLE001 - logger.warning("NATS unavailable — skipping publish pass") - return 0 - try: - js = nc.jetstream() - async with async_session() as session: - rows = (await session.execute( - cameras.select().where(cameras.c.last_seen >= cutoff) - )).mappings().all() - for r in rows: - msg = { - "source_type": "camera", - "title": f"Open camera ({r['vendor'] or 'unknown vendor'})", - "url": r["source_url"], - "location_lat": r["location_lat"], - "location_lon": r["location_lon"], - "location_name": r["location_name"], - "tags": ["osint", "camera", r["discovery_source"]], - "raw": { - "url_hash": r["url_hash"], - "snapshot_url": r["snapshot_url"], - "vendor": r["vendor"], - "device_type": r["device_type"], - "first_seen": r["first_seen"].isoformat(), - "last_seen": r["last_seen"].isoformat(), - }, - "source_timestamp": datetime.now(timezone.utc).isoformat(), - } - await js.publish(CAMERA_NATS_SUBJECT, json.dumps(msg).encode()) - published += 1 - if published >= 500: # per-cycle cap - break - finally: - await nc.close() - return published +async def publish_new_cameras(rows: list | None = None) -> int: + """Do not publish camera discoveries as events. + + ``run_cycle`` already upserts the cameras table, which backs + ``GET /api/cameras``. ``rows`` is newly seen cameras from a cycle or a + test; none are JetStream-published, so the ingester inserts 0 events + with source_type=camera. + """ + del rows + return 0 async def main() -> None: @@ -93,8 +57,7 @@ async def main() -> None: try: n = await run_cycle() p = await publish_new_cameras() - logger.info("cycle: %d stored, %d published to %s", - n, p, CAMERA_NATS_SUBJECT) + logger.info("cycle: %d stored, %d camera events published", n, p) except Exception: # noqa: BLE001 logger.exception("camera cycle error") if not ENABLED: # --once mode diff --git a/app/run_ingester.py b/app/run_ingester.py index 5d94389..2ef49e6 100644 --- a/app/run_ingester.py +++ b/app/run_ingester.py @@ -56,8 +56,11 @@ async def producer_loop() -> None: try: g = await ingest_gdelt(query=GDELT_QUERY, max_articles=50) logger.info("GDELT -> %d articles", g) - except Exception: # noqa: BLE001 - logger.exception("GDELT fetch failed") + except Exception as exc: # noqa: BLE001 + # Quota/backoff cases are handled inside ingest_gdelt (one clean + # line); anything reaching here is a real failure and a stack + # trace every 5 minutes is not actionable, so keep it to one line. + logger.warning("GDELT fetch failed: %s", exc) if ENABLE_QUAKES: try: q = await ingest_earthquakes() @@ -116,6 +119,24 @@ async def fire_loop() -> None: await asyncio.sleep(FIRMS_INTERVAL) +async def geofence_feed_loop() -> None: + """Hear quakes already stored, WFIGS incidents, and news map pins. + + WFIGS is not persisted — fetched per active-fence bbox here (no FIRMS + or AIS key). News pins are read from ``news_items``; the summarizer + is not imported. New earthquakes also notify from ``ingest_event``. + """ + logger.info("geofence feed loop starting (interval=%ss)", INTERVAL) + while True: + try: + from geofence import scan_geofence_feeds + n = await scan_geofence_feeds() + logger.info("geofence feeds -> %d notifies", n) + except Exception: # noqa: BLE001 + logger.exception("geofence feed scan failed") + await asyncio.sleep(INTERVAL) + + async def main() -> None: logger.info( "ingester starting (rss=%d feeds, gdelt_q=%r, quakes=%s, fires=%s, interval=%ss)", @@ -126,7 +147,9 @@ async def main() -> None: await refresh_cache() except Exception: logger.exception("geofence cache refresh failed (ST_Intersects still runs on ingest)") - tasks: list[asyncio.Task] = [] + tasks: list[asyncio.Task] = [ + asyncio.create_task(geofence_feed_loop()), + ] if ENABLE_FIRES: # Fire ingest only starts once FIRMS_MAP_KEY is set (ingest_fires logs # and idles otherwise). diff --git a/app/schemas.py b/app/schemas.py index 64676fc..1834634 100644 --- a/app/schemas.py +++ b/app/schemas.py @@ -314,6 +314,26 @@ class NewsMapItemOut(BaseModel): created_at: datetime +class NewsBlipOut(BaseModel): + """One per-article proximate geo blip as exposed by GET /api/news/blips. + + Frozen wire contract (card t_bc15eb53): every graded article with a + derivable location, deduped by article id (latest grading wins). + Unlike /api/news/map this is NOT limited to critical/high items. + """ + id: int + headline: str + url: Optional[str] = None + domain: Optional[str] = None + location_name: Optional[str] = None + lat: float + lon: float + location_confidence: Optional[str] = None + category: Optional[str] = None + score: Optional[int] = None + created_at: datetime + + class NewsModelId(BaseModel): """One model id as exposed by GET /api/news/models.""" diff --git a/app/sources.py b/app/sources.py index 7d587a5..115b55c 100644 --- a/app/sources.py +++ b/app/sources.py @@ -2,9 +2,15 @@ from __future__ import annotations +import html +import io import json import logging -from datetime import datetime, timezone +import os +import re +import time +import zipfile +from datetime import datetime, timedelta, timezone from email.utils import parsedate_to_datetime import httpx @@ -143,6 +149,61 @@ def gdelt_params(query: str = "", max_articles: int = 50) -> dict[str, str]: } +# GDELT 429 backoff state. GDELT sends no Retry-After, and its block window +# grows with request volume, so the only useful reaction to a 429 is to stop +# asking: skip whole producer cycles, doubling the wait from BASE to MAX. +GDELT_BACKOFF_BASE = int(os.getenv("GDELT_BACKOFF_BASE", "300")) +GDELT_BACKOFF_MAX = int(os.getenv("GDELT_BACKOFF_MAX", "1800")) +_gdelt_backoff_secs = 0 +_gdelt_backoff_until = 0.0 # time.monotonic() + + +def gdelt_backoff_remaining() -> float: + """Seconds left in the GDELT cooldown window (0 = ready to call).""" + return max(0.0, _gdelt_backoff_until - time.monotonic()) + + +def _gdelt_backoff_until_iso() -> str: + return ( + datetime.now(timezone.utc).replace(microsecond=0) + + timedelta(seconds=gdelt_backoff_remaining()) + ).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def _gdelt_start_backoff(retry_after: float | None = None) -> None: + global _gdelt_backoff_secs, _gdelt_backoff_until + wait = retry_after or min( + GDELT_BACKOFF_MAX, max(GDELT_BACKOFF_BASE, _gdelt_backoff_secs * 2) + ) + _gdelt_backoff_secs = int(wait) + _gdelt_backoff_until = time.monotonic() + wait + + +def _gdelt_clear_backoff() -> None: + global _gdelt_backoff_secs, _gdelt_backoff_until + _gdelt_backoff_secs = 0 + _gdelt_backoff_until = 0.0 + + +def _gdelt_retry_after(resp: httpx.Response) -> float | None: + """Retry-After as seconds (delta-seconds or HTTP-date); GDELT sends neither.""" + raw = resp.headers.get("retry-after") + if not raw: + return None + raw = raw.strip() + try: + return max(1.0, float(raw)) + except ValueError: + pass + try: + return max( + 1.0, + (parsedate_to_datetime(raw) - datetime.now(timezone.utc)).total_seconds(), + ) + except (TypeError, ValueError): + return None + + def _parse_gdelt_seendate(value: object) -> str: if isinstance(value, str) and len(value) >= 15: try: @@ -175,25 +236,59 @@ def parse_gdelt_articles(data: dict) -> list[dict]: return events -async def ingest_gdelt(query: str = "", max_articles: int = 50): - """Fetch articles from the GDELT DOC 2.0 API.""" +async def _ingest_gdelt_doc(query: str = "", max_articles: int = 50): + """Fetch articles from the GDELT DOC 2.0 API. + + GDELT enforces a per-IP quota that answers ``429`` with a plain-text body + ("Please limit requests to one every 5 seconds"), sends **no** Retry-After, + and widens the block window as request volume accumulates. So a 429 is not + retried: the ingester stops calling until a backoff window expires, and the + cycle is skipped with a single log line. See ``gdelt_backoff_remaining``. + """ + remaining = gdelt_backoff_remaining() + if remaining > 0: + logger.info( + "GDELT: cooling down (%ds left after 429); skipping this cycle", int(remaining) + ) + return 0 + params = gdelt_params(query=query, max_articles=max_articles) - data: dict = {"articles": []} async with httpx.AsyncClient( timeout=60, headers=_ua_headers(), follow_redirects=True, ) as client: try: resp = await client.get(GDELT_API, params=params) - resp.raise_for_status() - data = resp.json() - except (httpx.TransportError, httpx.HTTPStatusError) as exc: + except httpx.TransportError as exc: # gdeltproject.org certs have expired in the wild; HTTP fallback. - logger.warning("GDELT HTTPS failed (%s); retrying HTTP", exc) + # Only transport failures (TLS/connect) get the fallback — an HTTP + # error status is a quota answer and retrying it just burns the + # same per-IP budget a second time. + logger.warning("GDELT HTTPS transport error (%s); retrying HTTP", exc) http_url = GDELT_API.replace("https://", "http://", 1) resp = await client.get(http_url, params=params) + + if resp.status_code == 429: + _gdelt_start_backoff(_gdelt_retry_after(resp)) + logger.warning( + "GDELT 429 (rate limited) -> backing off until %s", + _gdelt_backoff_until_iso(), + ) + return 0 + + try: resp.raise_for_status() data = resp.json() + except (httpx.HTTPStatusError, ValueError) as exc: + # GDELT also signals errors/throttling as HTTP 200 + prose, so a + # JSON decode failure is "busy", not "no results". + _gdelt_start_backoff(_gdelt_retry_after(resp)) + logger.warning( + "GDELT unusable response (HTTP %s: %s) -> backing off until %s", + resp.status_code, str(exc).splitlines()[0][:120], _gdelt_backoff_until_iso(), + ) + return 0 + _gdelt_clear_backoff() events = parse_gdelt_articles(data if isinstance(data, dict) else {}) for event in events: await publish_event("events.gdelt", event) @@ -201,6 +296,240 @@ async def ingest_gdelt(query: str = "", max_articles: int = 50): return len(events) +# ─── GDELT 2.0 15-minute bulk files (throttle-free) ───────────────────── +# +# The DOC 2.0 API is per-IP quota'd (429, no Retry-After). The same coverage is +# published every 15 minutes as static files under /gdeltv2/ with no key and no +# quota, indexed by ``lastupdate.txt``: +# *.export.CSV.zip events (CAMEO codes) +# *.mentions.CSV.zip event->article mentions (URL + confidence, no title) +# *.gkg.csv.zip Global Knowledge Graph, one row per article: URL, source +# domain, themes, locations with lat/lon, tone, and the +# page title in the V2ExtrasXML column +# GKG is the one that carries title + geo, so map a filtered row into the same +# event shape ``parse_gdelt_articles`` produces and let the existing +# ``events.gdelt`` NATS consumer + ``event_dedup`` (URL) keep working. + +GDELT_BULK_ENABLED = os.getenv("GDELT_BULK_ENABLED", "1").lower() in ("1", "true", "yes") +GDELT_BULK_LASTUPDATE = os.getenv( + "GDELT_BULK_LASTUPDATE", "https://data.gdeltproject.org/gdeltv2/lastupdate.txt" +) +GDELT_BULK_MAX_EVENTS = int(os.getenv("GDELT_BULK_MAX_EVENTS", "100")) + +# Newest bulk file already parsed; lastupdate.txt is re-read every cycle but the +# 15-minute file behind it only changes 4x/hour. +_gdelt_bulk_last_file: str | None = None + +_PAGE_TITLE_RE = re.compile(r"(.*?)", re.DOTALL) +_PAGE_PUB_TS_RE = re.compile(r"(\d{14})<") + + +def gdelt_query_terms(query: str = "") -> list[str]: + """CONFIG GDELT query (``(unrest OR protest OR ...)``) -> plain terms. + + Used to filter bulk rows against their GKG theme tokens instead of + publishing every article in the 15-minute window. + """ + q = (query or "").strip() or GDELT_DEFAULT_QUERY + terms: list[str] = [] + for part in re.split(r"\s+OR\s+", q.strip().strip("()"), flags=re.IGNORECASE): + term = part.strip().strip('"').strip("'").strip().lower() + if term and term not in terms: + terms.append(term) + return terms + + +def _term_hits_themes(term: str, themes: str) -> bool: + """Term matches when every word of it appears in the theme token list.""" + words = [w for w in re.split(r"[\s_\-]+", term) if w] + return bool(words) and all(w in themes for w in words) + + +def select_gdelt_bulk_url(lastupdate_text: str) -> tuple[str, str] | None: + """``(filename, https_url)`` of the newest GKG file in lastupdate.txt. + + lastupdate.txt lists plain ``http://`` URLs, which 301 to https; normalise + so the fetch never follows a redirect into a stale mirror. + """ + for line in (lastupdate_text or "").splitlines(): + parts = line.split() + if len(parts) < 3 or not parts[2].endswith(".gkg.csv.zip"): + continue + url = parts[2] + if url.startswith("http://"): + url = "https://" + url[len("http://"):] + return url.rsplit("/", 1)[-1], url + return None + + +def _gkg_location(field: str) -> tuple[float | None, float | None, str | None]: + """First location in a V2Locations field -> (lat, lon, name). + + V2Locations is ``type#fullname#cc#adm1[#adm2]#lat#lon#featureid``; the + adm2 slot is sometimes dropped, so read the triple from the end. + """ + segment = (field or "").split(";", 1)[0] + parts = segment.split("#") + if len(parts) < 5: + return None, None, None + name = parts[1].strip() or None + try: + lat = float(parts[-3]) + lon = float(parts[-2]) + except (TypeError, ValueError): + return None, None, name + if not (-90 <= lat <= 90 and -180 <= lon <= 180): + return None, None, name + return lat, lon, name + + +def _gkg_tone(field: str) -> float | None: + try: + return _parse_gdelt_tone(field.split(",", 1)[0]) + except (AttributeError, IndexError): + return None + + +def _gkg_timestamp(row: list[str], extras: str) -> str: + """Article publish time: PAGE_PRECISEPUBTIMESTAMP, else the GKG window stamp.""" + stamps = [] + pub = _PAGE_PUB_TS_RE.search(extras) + if pub is not None: + stamps.append(pub.group(1)) + if len(row) > 1 and isinstance(row[1], str): + stamps.append(row[1][:14]) + for stamp in stamps: + try: + return datetime.strptime(stamp, "%Y%m%d%H%M%S").replace( + tzinfo=timezone.utc + ).isoformat() + except ValueError: + continue + return datetime.now(timezone.utc).isoformat() + + +def parse_gkg_row(row: list[str], terms: list[str], bulk_file: str = "") -> dict | None: + """Map one GKG CSV row into the ``events.gdelt`` event shape. + + Returns None when the row has no usable URL or matches none of ``terms``. + """ + if len(row) < 8: + return None + url = (row[4] or "").strip() + if not url.startswith(("http://", "https://")): + return None + + raw_themes = row[7] or "" + themes = raw_themes.lower() + matched = [t for t in terms if _term_hits_themes(t, themes)] + if not matched: + return None + + extras = row[-1] if isinstance(row[-1], str) else "" + title_match = _PAGE_TITLE_RE.search(extras) + title = html.unescape(title_match.group(1)).strip() if title_match else None + + lat = lon = loc_name = None + for idx in (9, 10): + if idx < len(row): + lat, lon, loc_name = _gkg_location(row[idx]) + if lat is not None: + break + + theme_tokens = [t for t in raw_themes.split(";") if t] + tags = matched + [ + t for t in theme_tokens + if any(w in t.lower() for w in matched) + ] + tags = list(dict.fromkeys(tags))[:10] + + return { + "source_type": "gdel-t2", + "title": title, + "body": (row[3] or "").strip() or None, + "url": url, + "location_lat": lat, + "location_lon": lon, + "location_name": loc_name, + "source_timestamp": _gkg_timestamp(row, extras), + "tags": tags, + "raw": { + "gkg_record_id": row[0], + "source_common_name": row[3], + "source_collection": row[2], + "themes": theme_tokens[:12], + "tone": _gkg_tone(row[15]) if len(row) > 15 else None, + "bulk_file": bulk_file, + }, + } + + +async def ingest_gdelt_bulk(query: str = "", max_events: int | None = None) -> int: + """Publish new articles from the newest 15-minute GKG bulk file. + + No API key, no per-IP quota, and the existing URL dedupe means re-reading + the same file after a restart publishes nothing new. + """ + global _gdelt_bulk_last_file + cap = GDELT_BULK_MAX_EVENTS if max_events is None else max_events + + async with httpx.AsyncClient( + timeout=120, headers=_ua_headers(), follow_redirects=True, + ) as client: + index = await client.get(GDELT_BULK_LASTUPDATE) + index.raise_for_status() + picked = select_gdelt_bulk_url(index.text) + if picked is None: + logger.warning("GDELT bulk: no .gkg file listed in lastupdate.txt") + return 0 + filename, url = picked + if filename == _gdelt_bulk_last_file: + logger.debug("GDELT bulk: %s already ingested; nothing new", filename) + return 0 + archive = await client.get(url) + archive.raise_for_status() + + terms = gdelt_query_terms(query) + events: list[dict] = [] + scanned = 0 + with zipfile.ZipFile(io.BytesIO(archive.content)) as zf: + member = zf.namelist()[0] + with zf.open(member) as fh: + for line in io.TextIOWrapper(fh, encoding="utf-8", errors="replace"): + if not line.strip(): + continue + scanned += 1 + event = parse_gkg_row(line.rstrip("\r\n").split("\t"), terms, filename) + if event is not None and len(events) < cap: + events.append(event) + + published = await _publish_unknown("events.gdelt", events) + _gdelt_bulk_last_file = filename + logger.info( + "GDELT bulk %s: %d/%d rows matched %s, %d new articles published", + filename, len(events), scanned, "/".join(terms), published, + ) + return published + + +async def ingest_gdelt(query: str = "", max_articles: int = 50): + """GDELT articles: throttle-free 15-minute bulk file first, DOC API fallback. + + The bulk path carries the coverage; the DOC 2.0 call (with its 429 backoff) + only runs when the bulk fetch itself fails, so the per-IP quota is no longer + on the hot path. + """ + if GDELT_BULK_ENABLED: + try: + return await ingest_gdelt_bulk(query=query) + except Exception as exc: # noqa: BLE001 — any bulk failure falls back + logger.warning( + "GDELT bulk fetch failed (%s: %s); falling back to DOC API", + type(exc).__name__, str(exc)[:160], + ) + return await _ingest_gdelt_doc(query=query, max_articles=max_articles) + + def _parse_gdelt_tone(tone: str) -> float | None: """Parse GDELT tone string to a -1..1 sentiment score.""" try: diff --git a/app/static/index.html b/app/static/index.html index acca754..28b058a 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -274,6 +274,21 @@ .marker-cluster-medium div { font-size: 11px; } .marker-cluster-large div { font-size: 12px; } + /* ── Article blip clusters (quiet violet, matches the small blips) ── */ + .marker-cluster-articles { background-color: rgba(160, 108, 213, 0.16); } + .marker-cluster-articles div { + background-color: rgba(122, 74, 160, 0.88); + color: #efe6f9; + font-weight: 600; + box-shadow: 0 0 10px rgba(160, 108, 213, 0.35), 0 0 2px rgba(3, 6, 9, 0.9); + } + .articles-sm div { font-size: 10px; } + .articles-md div { font-size: 11px; } + .articles-lg div { font-size: 12px; } + /* FIRMS heat is visual-only (no listeners) but its canvas sits on top + of the overlay pane and eats clicks meant for vector blips/pins. */ + .leaflet-heatmap-layer { pointer-events: none; } + /* ── Map hint + HUD chips ── */ .map-hint { position: absolute; left: 12px; bottom: 12px; z-index: 500; @@ -299,6 +314,7 @@ .hud-chip .c.cams { background: #4ade80; box-shadow: 0 0 6px #4ade80; } .hud-chip .c.blips { background: var(--magenta); box-shadow: 0 0 6px var(--magenta); } .hud-chip .c.news { background: var(--magenta); box-shadow: 0 0 6px var(--magenta); border-radius: 1px; transform: rotate(45deg); } + .hud-chip .c.articles { background: #a06cd5; box-shadow: 0 0 6px rgba(160,108,213,0.6); } .hud-chip.off { opacity: 0.4; } #dvr-bar { position: absolute; left: 50%; bottom: 12px; transform: translateX(-50%); @@ -357,6 +373,7 @@ .lp-dot.cams { background: #4ade80; box-shadow: 0 0 7px #4ade80; } .lp-dot.blips { background: var(--magenta); box-shadow: 0 0 7px var(--magenta); } .lp-dot.news { background: var(--cyan); box-shadow: 0 0 7px var(--cyan); } + .lp-dot.articles { background: #a06cd5; box-shadow: 0 0 7px rgba(160,108,213,0.6); } .lp-dot.weather { background: var(--amber); box-shadow: 0 0 7px var(--amber); } .lp-dot.flights { background: #7dd3fc; box-shadow: 0 0 7px #7dd3fc; } .lp-dot.mil { background: #f472b6; box-shadow: 0 0 7px #f472b6; } @@ -703,7 +720,7 @@ -webkit-mask-image: linear-gradient(90deg, transparent 0, #000 26px, #000 calc(100% - 26px), transparent 100%); } .tick-track { display: flex; width: max-content; animation: marquee 60s linear infinite; } - .ticker.news .tick-track { animation-duration: 90s; } + .ticker.news .tick-track { animation-duration: 240s; } /* fallback; JS sets constant px/s */ .tick-wrap:hover .tick-track, .tick-wrap:focus-within .tick-track { animation-play-state: paused; } @keyframes marquee { from { transform: translateX(0); } to { transform: translateX(-50%); } } .tick-group { display: flex; align-items: center; } @@ -1017,6 +1034,12 @@ 0 +
+
+ + 0 +
+
@@ -1121,6 +1144,7 @@
CAMS —
BLIPS —
NEWS —
+
ARTICLES —