Compare commits

...
175 changed files with 0 additions and 72481 deletions

View file

@ -1,9 +0,0 @@
__pycache__/
*.pyc
.git/
.gitignore
.env
.env.example
.forgejo/
README.md
*.md

View file

@ -1,143 +0,0 @@
# OSINT Dashboard — environment configuration
# Copy to `.env` and adjust. All values have safe defaults for local compose.
# ── PostgreSQL / TimescaleDB ───────────────────────────────────────────────
DB_USER=osint
DB_PASSWORD=osint
DB_HOST=db
DB_PORT=5432
DB_NAME=osint_data
# ── NATS JetStream (optional — only needed when profile `ingest` is used) ──
NATS_URL=nats://nats:4222
# ── MinIO (optional — document storage; endpoint used if wired later) ──────
MINIO_ENDPOINT=minio:9000
MINIO_ACCESS_KEY=
MINIO_SECRET_KEY=
# "true" for TLS endpoints (e.g. S3-compatible prod); "false" for local HTTP.
MINIO_SECURE=false
# ── Camera discovery scraper ───────────────────────────────────────────────
# Comma-separated public directory/list/API URLs (Insecam-style pages,
# plain-text lists, or the ALERTWest JSON API). Empty = built-in defaults
# (public-ip-cams README + ALERTCalifornia/ALERTWest official JPEGs +
# Live-Environment-Streams HLS/YouTube GeoJSON).
CAMERA_SOURCE_URLS=
CAMERA_SCRAPE_INTERVAL=3600
CAMERA_REQUEST_DELAY=2.0
CAMERA_MAX_PER_SOURCE=20000
NOMINATIM_URL=https://nominatim.openstreetmap.org
NOMINATIM_MIN_INTERVAL=1.1
SNAPSHOT_TTL_SECONDS=300
# ── NASA FIRMS (active fire / hotspot ingest) ──────────────────────────────
# MAP_KEY is FREE — get one at https://firms.modaps.eosdis.nasa.gov/api/map_key_info/
# (1-minute signup, no payment). Leave blank to keep fire ingest idle.
FIRMS_MAP_KEY=
# NRT VIIRS S-NPP 375m active fire detection (near-real-time).
FIRMS_DATASET=VIIRS_SNPP_NRT
# Area to poll as "minlon,minlat,maxlon,maxlat". Narrow it to reduce payload
# (e.g. CONUS "-125,24,-66,50"). Default covers most of the inhabited globe.
FIRMS_BBOX=-180,-60,180,75
# Poll cadence in seconds (~15 min). FIRMS NRT updates every ~5-10 min.
FIRMS_INTERVAL=900
# Set to 0 to disable the fire loop entirely.
INGEST_FIRES=1
# ── VesselAPI (commercial REST AIS — Hormuz, 5×/day, 150 calls/mo cap) ─────
# Independent of AISStream (open/shared live US-coast WebSocket). Both stay
# on when their keys are set; missing one never disables the other.
# Prefer pasting VESSELAPI_API_KEY on the dashboard Keys page.
# The poller idles when the key is unset. Never called from map pans
# (GET /api/vessels serves the shared last-known cache only).
VESSELAPI_API_KEY=
# Bounding box(es) as minlat,minlon,maxlat,maxlon (lat/lon order). Semicolon-
# separated for multiple boxes. Default = Strait of Hormuz (span 3.6 ≤ 4° cap).
VESSELAPI_BBOX=25.5,55.4,27.3,57.2
# Poll cadence in seconds (17280 = 4.8h → 5 polls/day = 150/mo).
VESSELAPI_INTERVAL=17280
# Local hard cap on successful 2xx calls per UTC day (persisted in Postgres).
VESSELAPI_MAX_CALLS_PER_DAY=5
# 1 = run the poller inside the dashboard process (default); ingester off.
VESSELAPI_IN_APP=1
VESSELAPI_IN_INGEST=0
# ── API keys (managed from the dashboard UI) ──────────────────────────────
# Keys such as NOUS_API_KEY and TELEGRAM_TOKEN are stored in the Postgres
# `api_keys` table and managed from the dashboard's "Keys" tab
# (GET/POST/DELETE /api/keys/{name}) — see app/keystore.py. The FIRMS ingestor
# currently reads FIRMS_MAP_KEY from .env (above); wiring the Keys-UI store as
# its lookup/fallback is a planned follow-up.
#
# Key management is ADMIN-ONLY (single admin, no user table). Visitors get a
# read-only map + news. Configure the three vars below or admin endpoints
# answer 403 {"detail": "admin auth not configured"} (fail closed — the public
# site keeps working). In the cluster they come from Secret `osint-admin`.
# Generate the hash: python app/auth.py hash 'your password'
# Generate the secret: python -c 'import secrets; print(secrets.token_urlsafe(48))'
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).
# Summarizer runs Nous map-reduce every 15 min (NEWS_SUMMARIZE_INTERVAL_S=900).
# NOUS_API_KEY is also (preferably) set in the Keys UI; env is an override.
# Unset in both env and api_keys = summarizer logs and idles (never crashes).
NOUS_API_KEY=
NOUS_BASE_URL=https://inference-api.nousresearch.com/v1
# Optional LLM knobs
# SUMMARY_MODEL is an optional override. Leave unset so Settings
# (app_settings.SUMMARY_MODEL) can reach the summarizer. Code default
# 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.
INCLUDE_FUTURES=0
NEWS_SCRAPE_INTERVAL_S=10
NEWS_SUMMARIZE_INTERVAL_S=900
NEWS_SCRAPE_RUN_ON_START=1
NEWS_SUMMARIZE_RUN_ON_START=1
# "1" ignores the interval idempotency skip (double-pins on recreate).
NEWS_SUMMARIZE_FORCE=0
NEWS_LOG_LEVEL=INFO
# Reserved for the (out-of-scope) Telegram delivery bot.
TELEGRAM_TOKEN=
TELEGRAM_CHAT_ID=
# =============================================================================
# Forgejo container registry (CI publishes here; NOT ghcr.io)
# =============================================================================
# forgejo.siriusdevops.com/sirius/osint-dashboard[:tag]
# forgejo.siriusdevops.com/sirius/osint-dashboard-pg[:tag]
# forgejo.siriusdevops.com/sirius/osint-news-scraper[:tag]
# forgejo.siriusdevops.com/sirius/osint-news-summarizer[:tag]
FORGEJO_REGISTRY=forgejo.siriusdevops.com
FORGEJO_OWNER=sirius

View file

@ -1,229 +0,0 @@
# 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 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.
#
# Images (public names):
# forgejo.siriusdevops.com/sirius/osint-dashboard:amd64-<sha12>
# forgejo.siriusdevops.com/sirius/osint-dashboard-pg:amd64-<sha12>
# forgejo.siriusdevops.com/sirius/osint-news-scraper:amd64-<sha12>
# forgejo.siriusdevops.com/sirius/osint-news-summarizer:amd64-<sha12>
#
# Optional repo variable FORGEJO_REGISTRY overrides the *public* pull host.
name: build-and-deploy
on:
push:
branches: [main, master]
workflow_dispatch:
inputs:
rebuild_pg:
description: Rebuild Timescale+PostGIS (Dockerfile.pg)
type: boolean
default: false
rebuild_all:
description: Rebuild every app image (ignore path filter)
type: boolean
default: false
env:
PUBLIC_REGISTRY: ${{ vars.FORGEJO_REGISTRY || 'forgejo.siriusdevops.com' }}
PUSH_REGISTRY: forgejo.forgejo.svc.cluster.local:3000
OWNER: sirius
jobs:
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
with:
fetch-depth: 50
- name: Plan image builds
id: plan
run: |
set -euo pipefail
APP=0
SCRAPER=0
SUM=0
PG=0
mark() {
case "$1" in
Dockerfile.pg)
PG=1 ;;
Dockerfile|app/*|alembic/*|alembic.ini)
APP=1 ;;
news/scraper/*)
SCRAPER=1 ;;
news/summerizer/*)
SUM=1 ;;
esac
}
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
APP=1; SCRAPER=1; SUM=1
if [ "${{ github.event.inputs.rebuild_all }}" = "true" ]; then
APP=1; SCRAPER=1; SUM=1; PG=1
fi
if [ "${{ github.event.inputs.rebuild_pg }}" = "true" ]; then
PG=1
fi
else
BEFORE="${{ github.event.before }}"
SHA="${GITHUB_SHA}"
ZEROS="0000000000000000000000000000000000000000"
if [ -z "$BEFORE" ] || [ "$BEFORE" = "$ZEROS" ]; then
echo "No previous SHA — build app images, skip pg"
APP=1; SCRAPER=1; SUM=1
elif ! git cat-file -e "${BEFORE}^{commit}" 2>/dev/null; then
echo "Previous SHA $BEFORE not in history — build app images, skip pg"
APP=1; SCRAPER=1; SUM=1
else
while IFS= read -r f; do
[ -z "$f" ] && continue
mark "$f"
done < <(git diff --name-only "$BEFORE" "$SHA")
fi
fi
{
echo "app=$APP"
echo "scraper=$SCRAPER"
echo "summarizer=$SUM"
echo "pg=$PG"
} >> "$GITHUB_OUTPUT"
echo "plan app=$APP scraper=$SCRAPER summarizer=$SUM pg=$PG"
- name: Image refs
id: img
run: |
set -euo pipefail
PUSH="${PUSH_REGISTRY}"
PUB="${PUBLIC_REGISTRY}"
OWN="${OWNER}"
SHA="${GITHUB_SHA::12}"
TAG="amd64-${SHA}"
{
echo "reg=$PUSH"
echo "pub=$PUB"
echo "tag=$TAG"
echo "app=$PUSH/$OWN/osint-dashboard"
echo "pg=$PUSH/$OWN/osint-dashboard-pg"
echo "scraper=$PUSH/$OWN/osint-news-scraper"
echo "summarizer=$PUSH/$OWN/osint-news-summarizer"
} >> "$GITHUB_OUTPUT"
echo "Push registry: $PUSH"
echo "Public pull: $PUB"
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.
# 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.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
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 }}"
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 }}"
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
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 }}\`"
echo "- news-scraper: \`${{ steps.plan.outputs.scraper }}\`"
echo "- news-summarizer: \`${{ steps.plan.outputs.summarizer }}\`"
echo "- pg (Timescale): \`${{ steps.plan.outputs.pg }}\`"
echo
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"

8
.gitignore vendored
View file

@ -1,8 +0,0 @@
__pycache__/
*.py[cod]
*.egg-info/
.venv/
venv/
.venv*/
.env
.pytest_cache/

View file

@ -1,19 +0,0 @@
FROM python:3.13-slim AS base
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends \
gcc libpq-dev ffmpeg \
&& rm -rf /var/lib/apt/lists/*
COPY app/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app/ ./app/
COPY alembic.ini ./alembic.ini
COPY alembic/ ./alembic/
RUN chmod +x /app/app/docker-entrypoint.sh
EXPOSE 8000
ENV PYTHONPATH=/app/app
ENTRYPOINT ["/app/app/docker-entrypoint.sh"]

View file

@ -1,18 +0,0 @@
# Custom arm64 PostgreSQL 16 image with PostGIS 3 + TimescaleDB 2.
# Based on the official postgres:16 image so POSTGRES_USER/DB/PASSWORD env
# vars and host-auth (md5) work out of the box. Timescale's published
# timescaledb-postgis image is amd64-only, so we install the extensions here.
FROM postgres:16
# Install TimescaleDB + PostGIS from the respective apt repos.
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates curl gnupg lsb-release && \
curl -fsSL https://packagecloud.io/install/repositories/timescale/timescaledb/script.deb.sh | bash && \
apt-get update && apt-get install -y --no-install-recommends \
postgresql-16-postgis-3 timescaledb-2-postgresql-16 && \
mkdir -p /etc/postgresql/16/main/conf.d && \
echo "shared_preload_libraries = 'timescaledb'" > /etc/postgresql/16/main/conf.d/timescaledb.conf && \
rm -rf /var/lib/apt/lists/*
# The official postgres entrypoint remains the CMD and handles
# POSTGRES_USER / POSTGRES_DB / POSTGRES_PASSWORD and pg_hba setup.

View file

@ -1 +0,0 @@
redesign the osing dashboard front end

View file

@ -1,36 +0,0 @@
[alembic]
script_location = alembic
sqlalchemy.url = postgresql+asyncpg://user:pass@host:5432/dbname
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S

View file

@ -1,58 +0,0 @@
import sys
from logging.config import fileConfig
from pathlib import Path
from sqlalchemy import pool
from sqlalchemy.ext.asyncio import async_engine_from_config
from alembic import context
# Add app directory to path so we can import models/database
sys.path.insert(0, str(Path(__file__).parent.parent / "app"))
from database import metadata, DATABASE_URL
config = context.config
# Prefer the app's env-driven DATABASE_URL over the ini placeholder so
# migrations always target the same database the app connects to.
config.set_main_option("sqlalchemy.url", DATABASE_URL)
if config.config_file_name is not None:
fileConfig(config.config_file_name)
target_metadata = metadata
def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode."""
url = config.get_main_option("sqlalchemy.url")
context.configure(url=url, target_metadata=target_metadata, literal_binds=True)
with context.begin_transaction():
context.run_migrations()
def do_run_migrations(connection):
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
async def run_async_migrations():
connectable = async_engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
async with connectable.connect() as connection:
await connection.run_sync(do_run_migrations)
await connectable.dispose()
def run_migrations_online() -> None:
"""Run migrations in 'online' mode."""
import asyncio
asyncio.run(run_async_migrations())
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()

View file

@ -1,28 +0,0 @@
<%%doc>Template for rendering a Multiple Migration Revision Identifier.</%%doc>
<%%-
from alembic import context
context.configure()
-%>
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma_n, trim}
Create Date: ${create_date}
"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade() -> None:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}

View file

@ -1,164 +0,0 @@
"""initial schema
Revision ID: 001_initial
Revises:
Create Date: 2026-05-18
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import UUID, TSVECTOR, ENUM
# revision identifiers, used by Alembic.
revision = '001_initial'
down_revision = None
branch_labels = None
depends_on = None
def upgrade() -> None:
# Enums are created implicitly by the sa.Enum(name=...) columns below.
# (Explicit CREATE TYPE here would collide with SQLAlchemy's own DDL.)
# Extensions
op.execute("CREATE EXTENSION IF NOT EXISTS postgis")
op.execute("CREATE EXTENSION IF NOT EXISTS timescaledb")
# feed_sources
op.create_table(
'feed_sources',
sa.Column('id', UUID(as_uuid=True), primary_key=True),
sa.Column('name', sa.String(256), nullable=False),
sa.Column('source_type', sa.Enum('rss', 'gdel-t2', 'social', 'earthquake', 'disaster', 'weather', 'fire', 'satellite', name='feed_source_type'), nullable=False),
sa.Column('url', sa.Text()),
sa.Column('config', sa.JSON()),
sa.Column('enabled', sa.Integer, server_default='1', nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.func.now()),
)
# events (will become hypertable)
# NOTE: TimescaleDB requires the partitioning column (ingested_at) to be
# part of the primary key / any unique index, so the PK is composite.
op.create_table(
'events',
sa.Column('id', UUID(as_uuid=True), nullable=False),
sa.Column('source_type', sa.Enum('rss', 'gdel-t2', 'social', 'earthquake', 'disaster', 'weather', 'fire', 'satellite', name='event_source_type'), nullable=False, index=True),
sa.Column('source_id', UUID(as_uuid=True)),
sa.Column('title', sa.Text()),
sa.Column('body', sa.Text()),
sa.Column('url', sa.Text()),
sa.Column('sentiment_score', sa.Float()),
sa.Column('sentiment_label', sa.Enum('positive', 'neutral', 'negative', name='sentiment_label')),
sa.Column('location_lat', sa.Float()),
sa.Column('location_lon', sa.Float()),
sa.Column('location_name', sa.String(512)),
sa.Column('entities', sa.JSON()),
sa.Column('tags', sa.JSON()),
sa.Column('raw', sa.JSON()),
sa.Column('ingested_at', sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
sa.Column('source_timestamp', sa.DateTime(timezone=True), nullable=False),
sa.Column('search_vector', TSVECTOR),
sa.PrimaryKeyConstraint('id', 'ingested_at'),
)
# Convert events to TimescaleDB hypertable
op.execute("SELECT create_hypertable('events', 'ingested_at', if_not_exists => TRUE)")
# Keep search_vector populated from title + body on every insert/update.
op.execute("""
CREATE OR REPLACE FUNCTION events_search_vector_update() RETURNS trigger AS $$
BEGIN
NEW.search_vector :=
setweight(to_tsvector('english', coalesce(NEW.title, '')), 'A') ||
setweight(to_tsvector('english', coalesce(NEW.body, '')), 'B');
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
""")
op.execute("""
CREATE TRIGGER events_search_vector_trigger
BEFORE INSERT OR UPDATE ON events
FOR EACH ROW EXECUTE FUNCTION events_search_vector_update();
""")
# GIN index for full-text search
op.create_index('ix_events_search_vector', 'events', ['search_vector'], postgresql_using='gin')
# Spatial index
op.create_index('ix_events_location', 'events', ['location_lat', 'location_lon'])
# entities
op.create_table(
'entities',
sa.Column('id', UUID(as_uuid=True), primary_key=True),
sa.Column('name', sa.String(512), nullable=False, index=True),
sa.Column('entity_type', sa.Enum('person', 'organization', 'location', 'topic', 'asset', name='entity_type'), nullable=False),
sa.Column('aliases', sa.JSON()),
sa.Column('description', sa.Text()),
sa.Column('metadata', sa.JSON()),
sa.Column('location_lat', sa.Float()),
sa.Column('location_lon', sa.Float()),
sa.Column('event_count', sa.Integer, server_default='0'),
sa.Column('first_seen', sa.DateTime(timezone=True), server_default=sa.func.now()),
sa.Column('last_seen', sa.DateTime(timezone=True), server_default=sa.func.now()),
)
# entity_events
op.create_table(
'entity_events',
sa.Column('entity_id', UUID(as_uuid=True), primary_key=True),
sa.Column('event_id', UUID(as_uuid=True), primary_key=True),
sa.Column('relevance_score', sa.Float()),
sa.Column('linked_at', sa.DateTime(timezone=True), server_default=sa.func.now()),
)
# alerts
op.create_table(
'alerts',
sa.Column('id', UUID(as_uuid=True), primary_key=True),
sa.Column('alert_type', sa.Enum('entity_mention', 'sentiment_shift', 'geo_proximity', 'keyword_match', 'threshold', 'anomaly', name='alert_type'), nullable=False),
sa.Column('entity_id', UUID(as_uuid=True)),
sa.Column('event_id', UUID(as_uuid=True)),
sa.Column('severity', sa.Enum('low', 'medium', 'high', 'critical', name='alert_severity'), nullable=False),
sa.Column('title', sa.Text(), nullable=False),
sa.Column('message', sa.Text()),
sa.Column('context', sa.JSON()),
sa.Column('acknowledged', sa.Integer, server_default='0'),
sa.Column('acknowledged_by', sa.String(256)),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
sa.Column('resolved_at', sa.DateTime(timezone=True)),
)
op.create_index('ix_alerts_severity_created', 'alerts', ['severity', 'created_at'])
op.create_index('ix_alerts_entity', 'alerts', ['entity_id'])
# documents
op.create_table(
'documents',
sa.Column('id', UUID(as_uuid=True), primary_key=True),
sa.Column('bucket', sa.String(256), nullable=False),
sa.Column('object_key', sa.String(1024), nullable=False),
sa.Column('content_type', sa.String(256)),
sa.Column('size_bytes', sa.Integer()),
sa.Column('description', sa.Text()),
sa.Column('tags', sa.JSON()),
sa.Column('event_id', UUID(as_uuid=True)),
sa.Column('uploaded_at', sa.DateTime(timezone=True), server_default=sa.func.now()),
)
def downgrade() -> None:
op.drop_table('documents')
op.drop_table('alerts')
op.drop_table('entity_events')
op.drop_table('entities')
op.execute("SELECT drop_hypertable('events', cascade => TRUE)")
op.drop_table('events')
op.drop_table('feed_sources')
# Drop enums
op.execute("DROP TYPE IF EXISTS feed_source_type")
op.execute("DROP TYPE IF EXISTS event_source_type")
op.execute("DROP TYPE IF EXISTS sentiment_label")
op.execute("DROP TYPE IF EXISTS entity_type")
op.execute("DROP TYPE IF EXISTS alert_type")
op.execute("DROP TYPE IF EXISTS alert_severity")

View file

@ -1,43 +0,0 @@
"""cameras table for open-camera discovery
Revision ID: 002_cameras
Revises: 002_fires
Create Date: 2026-08-24
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import UUID
revision = '002_cameras'
down_revision = '002_fires'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
'cameras',
sa.Column('id', UUID(as_uuid=True), primary_key=True),
sa.Column('url_hash', sa.String(64), nullable=False),
sa.Column('source_url', sa.Text(), nullable=False),
sa.Column('snapshot_url', sa.Text()),
sa.Column('discovery_source', sa.String(128), nullable=False),
sa.Column('location_lat', sa.Float()),
sa.Column('location_lon', sa.Float()),
sa.Column('location_name', sa.String(512)),
sa.Column('vendor', sa.String(128)),
sa.Column('device_type', sa.String(64)),
sa.Column('first_seen', sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
sa.Column('last_seen', sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
sa.Column('raw', sa.JSON()),
)
op.create_index('ix_cameras_location', 'cameras', ['location_lat', 'location_lon'])
op.create_index('ix_cameras_last_seen', 'cameras', ['last_seen'])
# Dedupe key. NOTE: cameras is intentionally NOT a Timescale hypertable —
# it holds current state per camera (one row per url_hash), not time-series.
op.create_index('ix_cameras_url_hash', 'cameras', ['url_hash'], unique=True)
def downgrade() -> None:
op.drop_table('cameras')

View file

@ -1,60 +0,0 @@
"""fires hypertable: NASA FIRMS active fire/hotspot detections
Revision ID: 002_fires
Revises: 001_initial
Create Date: 2026-08-24
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '002_fires'
down_revision = '001_initial'
branch_labels = None
depends_on = None
def upgrade() -> None:
# The PK IS the idempotency natural key (latitude, longitude, acq_time,
# satellite). acq_time is the hypertable partitioning column and is part of
# the PK, which satisfies TimescaleDB's requirement that every unique index
# include all partitioning columns.
op.create_table(
'fires',
sa.Column('latitude', sa.Float(), nullable=False),
sa.Column('longitude', sa.Float(), nullable=False),
sa.Column('brightness', sa.Float(), nullable=False), # bright_ti4, K
sa.Column('confidence', sa.String(10), nullable=False), # n/l/h or %
sa.Column('acq_time', sa.DateTime(timezone=True), nullable=False),
sa.Column('satellite', sa.String(16), nullable=False),
sa.Column('instrument', sa.String(16)),
sa.Column('bright_ti5', sa.Float()),
sa.Column('frp', sa.Float()),
sa.Column('daynight', sa.String(1)),
sa.Column('scan', sa.Float()),
sa.Column('track', sa.Float()),
sa.Column('version', sa.String(32)),
sa.Column('raw', sa.JSON()),
sa.Column('ingested_at', sa.DateTime(timezone=True),
server_default=sa.func.now(), nullable=False),
sa.PrimaryKeyConstraint(
'latitude', 'longitude', 'acq_time', 'satellite',
name='pk_fires_natural_key',
),
)
# 1-day chunks keep retention/drop_chunks operations cheap and scans local.
# (TimescaleDB auto-creates an index on the partition column acq_time.)
op.execute(
"SELECT create_hypertable('fires', 'acq_time', "
"if_not_exists => TRUE, chunk_time_interval => INTERVAL '1 day')"
)
op.create_index('ix_fires_bbox', 'fires', ['longitude', 'latitude'])
def downgrade() -> None:
op.drop_index('ix_fires_bbox', table_name='fires')
op.execute("SELECT drop_hypertable('fires', if_exists => TRUE)")
op.drop_table('fires')

View file

@ -1,57 +0,0 @@
"""news tables: scraped articles + LLM article_summaries
Revision ID: 003_news
Revises: 002_cameras
Create Date: 2026-08-24
"""
from alembic import op
import sqlalchemy as sa # noqa: F401
# revision identifiers, used by Alembic.
revision = '003_news'
down_revision = '002_cameras'
branch_labels = None
depends_on = None
def upgrade() -> None:
# Idempotent DDL: the news scraper's Scrapy pipeline also issues
# `CREATE TABLE IF NOT EXISTS articles`, so either the scraper or the app
# may create these first depending on container startup order. IF NOT
# EXISTS makes both orders safe — whichever runs first wins, the other
# no-ops. Same table shapes as the upstream newsPipeline services.
op.execute(
"""
CREATE TABLE IF NOT EXISTS articles (
id SERIAL PRIMARY KEY,
title TEXT,
url TEXT UNIQUE,
content TEXT,
domain TEXT,
timestamp TIMESTAMPTZ
)
"""
)
op.execute(
"CREATE INDEX IF NOT EXISTS ix_articles_timestamp ON articles (timestamp)"
)
op.execute(
"""
CREATE TABLE IF NOT EXISTS article_summaries (
id SERIAL PRIMARY KEY,
summary_text TEXT NOT NULL,
batch_timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
"""
)
op.execute(
"CREATE INDEX IF NOT EXISTS ix_article_summaries_batch_timestamp "
"ON article_summaries (batch_timestamp)"
)
def downgrade() -> None:
op.execute("DROP TABLE IF EXISTS article_summaries")
op.execute("DROP TABLE IF EXISTS articles")

View file

@ -1,36 +0,0 @@
"""events.camera source type
Revision ID: 004_camera_enum
Revises: 003_news
Create Date: 2026-08-25
"""
from alembic import op
revision = '004_camera_enum'
down_revision = '003_news'
branch_labels = None
depends_on = None
def upgrade() -> None:
# Postgres enums have no IF NOT EXISTS for values — guard manually so the
# migration stays idempotent across restarts.
op.execute("""
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_enum e
JOIN pg_type t ON t.oid = e.enumtypid
WHERE t.typname = 'event_source_type' AND e.enumlabel = 'camera'
) THEN
ALTER TYPE event_source_type ADD VALUE 'camera';
END IF;
END
$$;
""")
def downgrade() -> None:
# Enum value removal is not supported by Postgres; leave it in place.
pass

View file

@ -1,64 +0,0 @@
"""news_items table + article_summaries.model
Revision ID: 005_news_items
Revises: 004_camera_enum
Create Date: 2026-08-28
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = "005_news_items"
down_revision = "004_camera_enum"
branch_labels = None
depends_on = None
def upgrade() -> None:
# Idempotent DDL: ingest (summarizer ensure_tables) may create the same
# shapes first depending on container startup order. IF NOT EXISTS makes
# both orders safe — whichever runs first wins, the other no-ops.
# One statement per op.execute: asyncpg rejects multi-command prepared
# statements (same style as 003_news).
op.execute(
"""
ALTER TABLE article_summaries
ADD COLUMN IF NOT EXISTS model TEXT
"""
)
op.execute(
"""
CREATE TABLE IF NOT EXISTS news_items (
id SERIAL PRIMARY KEY,
summary_id INTEGER REFERENCES article_summaries(id) ON DELETE CASCADE,
kind TEXT NOT NULL,
headline TEXT NOT NULL,
importance TEXT NOT NULL,
location_name TEXT,
lat DOUBLE PRECISION,
lon DOUBLE PRECISION,
location_confidence TEXT,
category TEXT,
url TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
"""
)
op.execute(
"""
CREATE INDEX IF NOT EXISTS ix_news_items_kind_created
ON news_items (kind, created_at DESC)
"""
)
op.execute(
"""
CREATE INDEX IF NOT EXISTS ix_news_items_map_bbox
ON news_items (lon, lat)
WHERE kind = 'map' AND lat IS NOT NULL AND lon IS NOT NULL
"""
)
def downgrade() -> None:
op.execute("DROP TABLE IF EXISTS news_items")
op.execute("ALTER TABLE article_summaries DROP COLUMN IF EXISTS model")

View file

@ -1,196 +0,0 @@
"""phase 2: geofences, 1-min track CAGGs, fire/aircraft hits
Revision ID: 005_phase2
Revises: 004_camera_enum
Create Date: 2026-08-28
"""
from alembic import op
revision = "005_phase2"
down_revision = "004_camera_enum"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.execute("CREATE EXTENSION IF NOT EXISTS postgis")
op.execute("CREATE EXTENSION IF NOT EXISTS timescaledb")
op.execute("""
CREATE TABLE IF NOT EXISTS geofences (
id UUID PRIMARY KEY,
name TEXT NOT NULL,
geojson JSONB NOT NULL,
geom geometry(Polygon, 4326),
active INTEGER NOT NULL DEFAULT 1,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
)
""")
op.execute("""
CREATE INDEX IF NOT EXISTS ix_geofences_geom
ON geofences USING gist (geom)
""")
op.execute("""
CREATE TABLE IF NOT EXISTS geofence_alerts (
id UUID PRIMARY KEY,
geofence_id UUID NOT NULL,
source_kind TEXT NOT NULL,
entity_id TEXT NOT NULL,
lat DOUBLE PRECISION,
lon DOUBLE PRECISION,
payload JSONB,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
)
""")
op.execute("""
CREATE INDEX IF NOT EXISTS ix_geofence_alerts_created
ON geofence_alerts (created_at DESC)
""")
op.execute("""
CREATE TABLE IF NOT EXISTS vessel_positions (
mmsi TEXT NOT NULL,
ts TIMESTAMPTZ NOT NULL,
lat DOUBLE PRECISION NOT NULL,
lon DOUBLE PRECISION NOT NULL,
heading DOUBLE PRECISION,
speed DOUBLE PRECISION,
label TEXT,
extra JSONB,
PRIMARY KEY (mmsi, ts)
)
""")
op.execute("""
SELECT create_hypertable(
'vessel_positions', 'ts', if_not_exists => TRUE
)
""")
op.execute("""
CREATE INDEX IF NOT EXISTS ix_vessel_positions_bbox
ON vessel_positions (lon, lat)
""")
op.execute("""
CREATE TABLE IF NOT EXISTS aircraft_positions (
hex TEXT NOT NULL,
ts TIMESTAMPTZ NOT NULL,
lat DOUBLE PRECISION NOT NULL,
lon DOUBLE PRECISION NOT NULL,
heading DOUBLE PRECISION,
speed DOUBLE PRECISION,
label TEXT,
extra JSONB,
PRIMARY KEY (hex, ts)
)
""")
op.execute("""
SELECT create_hypertable(
'aircraft_positions', 'ts', if_not_exists => TRUE
)
""")
op.execute("""
CREATE INDEX IF NOT EXISTS ix_aircraft_positions_bbox
ON aircraft_positions (lon, lat)
""")
op.execute("""
CREATE TABLE IF NOT EXISTS fire_aircraft_hits (
id UUID NOT NULL,
fire_id TEXT NOT NULL,
fire_lat DOUBLE PRECISION NOT NULL,
fire_lon DOUBLE PRECISION NOT NULL,
aircraft_hex TEXT NOT NULL,
aircraft_type TEXT,
aircraft_lat DOUBLE PRECISION NOT NULL,
aircraft_lon DOUBLE PRECISION NOT NULL,
distance_mi DOUBLE PRECISION NOT NULL,
seen_at TIMESTAMPTZ NOT NULL,
PRIMARY KEY (fire_id, aircraft_hex, seen_at)
)
""")
op.execute("""
CREATE INDEX IF NOT EXISTS ix_fire_aircraft_hits_seen
ON fire_aircraft_hits (seen_at DESC)
""")
# 1-minute continuous aggregates (Timescale). last() keeps the newest
# sample in each bucket — the DVR slider reads these, not the raw table.
op.execute("""
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM timescaledb_information.continuous_aggregates
WHERE view_name = 'vessel_tracks_1min'
) THEN
EXECUTE $v$
CREATE MATERIALIZED VIEW vessel_tracks_1min
WITH (timescaledb.continuous) AS
SELECT time_bucket('1 minute', ts) AS bucket,
mmsi,
last(lat, ts) AS lat,
last(lon, ts) AS lon,
last(heading, ts) AS heading,
last(speed, ts) AS speed,
last(label, ts) AS label
FROM vessel_positions
GROUP BY bucket, mmsi
WITH NO DATA
$v$;
END IF;
IF NOT EXISTS (
SELECT 1 FROM timescaledb_information.continuous_aggregates
WHERE view_name = 'aircraft_tracks_1min'
) THEN
EXECUTE $a$
CREATE MATERIALIZED VIEW aircraft_tracks_1min
WITH (timescaledb.continuous) AS
SELECT time_bucket('1 minute', ts) AS bucket,
hex,
last(lat, ts) AS lat,
last(lon, ts) AS lon,
last(heading, ts) AS heading,
last(speed, ts) AS speed,
last(label, ts) AS label
FROM aircraft_positions
GROUP BY bucket, hex
WITH NO DATA
$a$;
END IF;
END
$$;
""")
op.execute("""
DO $$
BEGIN
PERFORM add_continuous_aggregate_policy(
'vessel_tracks_1min',
start_offset => INTERVAL '3 hours',
end_offset => INTERVAL '1 minute',
schedule_interval => INTERVAL '1 minute',
if_not_exists => TRUE
);
PERFORM add_continuous_aggregate_policy(
'aircraft_tracks_1min',
start_offset => INTERVAL '3 hours',
end_offset => INTERVAL '1 minute',
schedule_interval => INTERVAL '1 minute',
if_not_exists => TRUE
);
EXCEPTION WHEN OTHERS THEN
NULL;
END
$$;
""")
def downgrade() -> None:
op.execute("DROP MATERIALIZED VIEW IF EXISTS aircraft_tracks_1min CASCADE")
op.execute("DROP MATERIALIZED VIEW IF EXISTS vessel_tracks_1min CASCADE")
op.execute("DROP TABLE IF EXISTS fire_aircraft_hits")
op.execute("DROP TABLE IF EXISTS aircraft_positions")
op.execute("DROP TABLE IF EXISTS vessel_positions")
op.execute("DROP TABLE IF EXISTS geofence_alerts")
op.execute("DROP TABLE IF EXISTS geofences")

View file

@ -1,24 +0,0 @@
"""merge 005_phase2 and 005_news_items
Revision ID: 006_merge_heads
Revises: 005_phase2, 005_news_items
Create Date: 2026-08-28
Two PRs both parented 004_camera_enum (phase2 geofences + news_items).
`alembic upgrade head` then fails and crash-loops the dashboard.
"""
from alembic import op # noqa: F401
revision = "006_merge_heads"
down_revision = ("005_phase2", "005_news_items")
branch_labels = None
depends_on = None
def upgrade() -> None:
pass
def downgrade() -> None:
pass

View file

@ -1,115 +0,0 @@
"""event_dedup + Timescale compression/retention
Revision ID: 007_event_dedup
Revises: 006_merge_heads
Create Date: 2026-08-28
"""
from alembic import op
revision = "007_event_dedup"
down_revision = "006_merge_heads"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.execute("""
CREATE TABLE IF NOT EXISTS event_dedup (
url TEXT PRIMARY KEY,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
)
""")
# Keep the earliest row per URL, drop the 10× USGS/camera dupes.
op.execute("""
DELETE FROM events a
USING events b
WHERE a.url IS NOT NULL AND a.url <> ''
AND a.url = b.url
AND (a.ingested_at, a.id) > (b.ingested_at, b.id)
""")
op.execute("""
INSERT INTO event_dedup (url)
SELECT DISTINCT url FROM events
WHERE url IS NOT NULL AND url <> ''
ON CONFLICT (url) DO NOTHING
""")
# Compression + retention. Policies no-op if Timescale rejects (fresh PG).
op.execute("""
DO $$
BEGIN
PERFORM add_compression_policy('events', INTERVAL '7 days', if_not_exists => TRUE);
EXCEPTION WHEN OTHERS THEN
BEGIN
ALTER TABLE events SET (
timescaledb.compress,
timescaledb.compress_segmentby = 'source_type',
timescaledb.compress_orderby = 'ingested_at DESC'
);
PERFORM add_compression_policy('events', INTERVAL '7 days', if_not_exists => TRUE);
EXCEPTION WHEN OTHERS THEN
NULL;
END;
END
$$;
""")
op.execute("""
DO $$
BEGIN
PERFORM add_retention_policy('events', INTERVAL '180 days', if_not_exists => TRUE);
EXCEPTION WHEN OTHERS THEN
NULL;
END
$$;
""")
op.execute("""
DO $$
BEGIN
ALTER TABLE fires SET (
timescaledb.compress,
timescaledb.compress_segmentby = 'satellite',
timescaledb.compress_orderby = 'acq_time DESC'
);
PERFORM add_compression_policy('fires', INTERVAL '7 days', if_not_exists => TRUE);
PERFORM add_retention_policy('fires', INTERVAL '90 days', if_not_exists => TRUE);
EXCEPTION WHEN OTHERS THEN
NULL;
END
$$;
""")
op.execute("""
DO $$
BEGIN
ALTER TABLE aircraft_positions SET (
timescaledb.compress,
timescaledb.compress_segmentby = 'hex',
timescaledb.compress_orderby = 'ts DESC'
);
PERFORM add_compression_policy('aircraft_positions', INTERVAL '1 day', if_not_exists => TRUE);
PERFORM add_retention_policy('aircraft_positions', INTERVAL '14 days', if_not_exists => TRUE);
EXCEPTION WHEN OTHERS THEN
NULL;
END
$$;
""")
op.execute("""
DO $$
BEGIN
ALTER TABLE vessel_positions SET (
timescaledb.compress,
timescaledb.compress_segmentby = 'mmsi',
timescaledb.compress_orderby = 'ts DESC'
);
PERFORM add_compression_policy('vessel_positions', INTERVAL '1 day', if_not_exists => TRUE);
PERFORM add_retention_policy('vessel_positions', INTERVAL '14 days', if_not_exists => TRUE);
EXCEPTION WHEN OTHERS THEN
NULL;
END
$$;
""")
def downgrade() -> None:
op.execute("DROP TABLE IF EXISTS event_dedup")

View file

@ -1,26 +0,0 @@
"""article_summaries.kind — interval vs daily_recap
Revision ID: 008_summary_kind
Revises: 007_event_dedup
Create Date: 2026-08-28
"""
from alembic import op
revision = "008_summary_kind"
down_revision = "007_event_dedup"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.execute(
"""
ALTER TABLE article_summaries
ADD COLUMN IF NOT EXISTS kind TEXT
"""
)
def downgrade() -> None:
op.execute("ALTER TABLE article_summaries DROP COLUMN IF EXISTS kind")

View file

@ -1,41 +0,0 @@
"""vessels — daily VesselAPI snapshots for DVR as-of
Revision ID: 009_vessels
Revises: 008_summary_kind
Create Date: 2026-08-29
"""
from alembic import op
revision = "009_vessels"
down_revision = "008_summary_kind"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.execute(
"""
CREATE TABLE IF NOT EXISTS vessels (
mmsi TEXT NOT NULL,
poll_at TIMESTAMPTZ NOT NULL,
lat DOUBLE PRECISION NOT NULL,
lon DOUBLE PRECISION NOT NULL,
heading DOUBLE PRECISION,
speed DOUBLE PRECISION,
label TEXT,
extra JSONB,
PRIMARY KEY (mmsi, poll_at)
)
"""
)
op.execute(
"CREATE INDEX IF NOT EXISTS ix_vessels_poll_at ON vessels (poll_at DESC)"
)
op.execute(
"CREATE INDEX IF NOT EXISTS ix_vessels_bbox ON vessels (lon, lat)"
)
def downgrade() -> None:
op.execute("DROP TABLE IF EXISTS vessels")

View file

@ -1,29 +0,0 @@
"""GIST bbox indexes for events/fires map-pan queries.
Revision ID: 010_bbox_gist
Revises: 009_vessels
Create Date: 2026-09-01
"""
from alembic import op
revision = "010_bbox_gist"
down_revision = "009_vessels"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.execute(
"CREATE INDEX IF NOT EXISTS ix_events_geom_gist ON events "
"USING gist (ST_SetSRID(ST_MakePoint(location_lon, location_lat), 4326))"
)
op.execute(
"CREATE INDEX IF NOT EXISTS ix_fires_geom_gist ON fires "
"USING gist (ST_SetSRID(ST_MakePoint(longitude, latitude), 4326))"
)
def downgrade() -> None:
op.execute("DROP INDEX IF EXISTS ix_fires_geom_gist")
op.execute("DROP INDEX IF EXISTS ix_events_geom_gist")

View file

@ -1,24 +0,0 @@
"""geofence_alerts (geofence_id, created_at DESC) for fence-scoped hit log
Revision ID: 011_geofence_alerts_fence
Revises: 010_bbox_gist
Create Date: 2026-09-01
"""
from alembic import op
revision = "011_geofence_alerts_fence"
down_revision = "010_bbox_gist"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.execute(
"CREATE INDEX IF NOT EXISTS ix_geofence_alerts_fence_created "
"ON geofence_alerts (geofence_id, created_at DESC)"
)
def downgrade() -> None:
op.execute("DROP INDEX IF EXISTS ix_geofence_alerts_fence_created")

View file

@ -1,39 +0,0 @@
"""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")

View file

@ -1,23 +0,0 @@
"""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")

View file

@ -1,40 +0,0 @@
"""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")

View file

@ -1,154 +0,0 @@
"""AISStream WebSocket worker — server-side only.
aisstream.io forbids browser clients. Connect from the FastAPI/ingest
process, upsert last-known positions, and expose them via GET /api/vessels.
Idle (no crash) when AISSTREAM_API_KEY is unset. Reconnect with jittered
backoff and resend the full subscription within 3 seconds of each connect.
"""
from __future__ import annotations
import asyncio
import json
import logging
import os
import random
import time
from config import AISSTREAM_API_KEY, AISSTREAM_BBOX
from keystore import get_api_key
from live_layers import transform_ais_frame, upsert_vessel
logger = logging.getLogger("osint.aisstream")
WS_URL = "wss://stream.aisstream.io/v0/stream"
FILTER_TYPES = [
"PositionReport",
"StandardClassBPositionReport",
"ExtendedClassBPositionReport",
"ShipStaticData",
]
# ── Viewport-following ─────────────────────────────────────────────────────
# The frontend POSTs its current viewport box to /api/vessels/subscribe; the
# worker retunes the AISStream subscription to it (throttled to 1/s, the
# service's subscription-update cap). ``None`` keeps the env AISSTREAM_BBOX
# default. Last writer wins; the key never reaches the browser.
_desired_boxes: list[list[list[float]]] | None = None
_bbox_guard = asyncio.Lock()
async def request_viewport_bbox(
minlon: float, minlat: float, maxlon: float, maxlat: float
) -> None:
"""Retune the live subscription to a viewport box (lon/lat input order)."""
global _desired_boxes
box = [[minlat, minlon], [maxlat, maxlon]] # AISStream wants [lat, lon] corners
async with _bbox_guard:
_desired_boxes = [box]
async def reset_viewport_bbox() -> None:
"""Fall back to the env AISSTREAM_BBOX default."""
global _desired_boxes
async with _bbox_guard:
_desired_boxes = None
async def _take_desired_boxes() -> list[list[list[float]]] | None:
async with _bbox_guard:
return _desired_boxes
def _parse_boxes(raw: str) -> list[list[list[float]]]:
"""Env format: minlat,minlon,maxlat,maxlon[; ...]. AIS wants [[lat,lon],[lat,lon]]."""
boxes = []
for chunk in (raw or "").split(";"):
parts = [p.strip() for p in chunk.split(",") if p.strip()]
if len(parts) != 4:
continue
minlat, minlon, maxlat, maxlon = (float(p) for p in parts)
boxes.append([[minlat, minlon], [maxlat, maxlon]])
return boxes or [[[24.0, -125.0], [50.0, -66.0]]]
async def _resolve_key() -> str:
return (os.getenv("AISSTREAM_API_KEY") or AISSTREAM_API_KEY
or (await get_api_key("AISSTREAM_API_KEY")) or "").strip()
async def run_ais_worker() -> None:
"""Long-lived reconnect loop. Safe to spawn as an asyncio task."""
try:
import websockets
except ImportError:
logger.warning("websockets package not installed — AIS worker disabled")
return
backoff = 2.0
while True:
key = await _resolve_key()
if not key:
logger.warning(
"AISSTREAM_API_KEY not set — AIS ingest idle. "
"Create a free key at https://aisstream.io/account"
)
await asyncio.sleep(60)
continue
boxes = await _take_desired_boxes() or _parse_boxes(AISSTREAM_BBOX)
try:
async with websockets.connect(
WS_URL,
max_size=2 ** 22,
ping_interval=20,
ping_timeout=20,
compression="deflate",
) as ws:
sub = {
"APIKey": key,
"BoundingBoxes": boxes,
"FilterMessageTypes": FILTER_TYPES,
}
await ws.send(json.dumps(sub))
logger.info("AISStream subscribed (%d bbox(es))", len(boxes))
backoff = 2.0
last_submit = time.monotonic()
while True:
# Follow the client viewport: coalesce to the latest request
# and honor AISStream's 1 subscription-update/s cap.
desired = await _take_desired_boxes()
if (
desired is not None
and desired != boxes
and time.monotonic() - last_submit >= 1.0
):
boxes = desired
sub["BoundingBoxes"] = boxes
await ws.send(json.dumps(sub))
last_submit = time.monotonic()
logger.info(
"AISStream re-subscribed to viewport (%d bbox)",
len(boxes),
)
try:
raw = await asyncio.wait_for(ws.recv(), timeout=0.25)
except asyncio.TimeoutError:
continue
if isinstance(raw, bytes):
raw = raw.decode("utf-8", errors="replace")
try:
frame = json.loads(raw)
except json.JSONDecodeError:
continue
marker = transform_ais_frame(frame)
if marker:
await upsert_vessel(marker)
except asyncio.CancelledError:
raise
except Exception: # noqa: BLE001
logger.exception("AISStream disconnected")
delay = backoff + random.uniform(0, 1.5)
logger.info("AISStream reconnect in %.1fs", delay)
await asyncio.sleep(delay)
backoff = min(60.0, backoff * 1.7)

View file

@ -1,589 +0,0 @@
"""Single-admin authentication for the OSINT dashboard.
The public site stays read-only for anonymous visitors; the one admin (the
operator) unlocks API-key management, settings and every state-changing route.
Design notes
------------
* **Deny by default.** :class:`AdminAuthMiddleware` inspects every ``/api/*``
request. Only the explicit read allowlist below is reachable without a
session; everything else needs a valid signed cookie. ``/api/auth/*`` is the
bootstrap surface and handles its own checks.
* **Fail closed.** With ``ADMIN_PASSWORD_HASH`` or ``ADMIN_SESSION_SECRET``
unset/empty, admin endpoints answer ``403 {"detail": "admin auth not
configured"}``. There is no default password and no bypass; public reads and
the HUD keep working.
* **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``) 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,
SameSite=Lax session cookie is what authenticates them.
Environment (exact names, supplied by the ``osint-admin`` Secret):
``ADMIN_USER``
Admin username.
``ADMIN_PASSWORD_HASH``
``pbkdf2_sha256$<iterations>$<salt_b64>$<hash_b64>``. Generate with::
python app/auth.py hash 'your password'
``ADMIN_SESSION_SECRET``
HMAC key for session tokens. Generate with::
python -c 'import secrets; print(secrets.token_urlsafe(48))'
"""
from __future__ import annotations
import base64
import hashlib
import hmac
import json
import os
import re
import secrets
import time
from collections import deque
from urllib.parse import parse_qs, urlparse
from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse, JSONResponse
# ── Constants ────────────────────────────────────────────────────────────────
COOKIE_NAME = "osint_session"
SESSION_TTL_SECONDS = 7 * 24 * 60 * 60
PBKDF2_ALGORITHM = "pbkdf2_sha256"
PBKDF2_ITERATIONS = 260_000
_ITERATIONS_FLOOR, _ITERATIONS_CEIL = 1_000, 5_000_000
LOGIN_WINDOW_SECONDS = 15 * 60
LOGIN_MAX_FAILURES = 5
_STATE_CHANGING = frozenset({"POST", "PUT", "PATCH", "DELETE"})
# ── Public read allowlist ────────────────────────────────────────────────────
# Anonymous visitors get the map + news HUD. Every path here was audited as a
# pure read (no writes, no spend of a stored API key). Anything absent requires
# the admin session.
PUBLIC_GET_EXACT = frozenset({
# core
"/api/health",
"/api/ready",
"/api/stats",
# events / sources / entities / alerts / documents
"/api/sources",
"/api/events",
"/api/fires",
"/api/entities",
"/api/alerts",
"/api/documents",
# analytics
"/api/analytics/summary",
"/api/analytics/timeline",
"/api/analytics/sentiment/by-source",
# cameras
"/api/cameras",
# news
"/api/news",
"/api/news/summaries",
"/api/news/ticker",
"/api/news/map",
"/api/news/blips",
# map / live layers
"/api/map/layers",
"/api/map/chokepoints",
"/api/map/radar",
"/api/map/sentinel1",
"/api/map/gpsjam",
"/api/map/times",
"/api/conflicts",
"/api/aircraft",
"/api/aircraft/photo",
"/api/trains",
"/api/vessels",
"/api/tracks/range",
"/api/satellites",
"/api/infrastructure",
"/api/place",
# geofences (reads only — create/patch/delete stay admin)
"/api/geofences",
"/api/geofence-alerts",
# fire / weather overlays
"/api/fire-aircraft",
"/api/fire-incidents",
"/api/fire-perimeters",
"/api/weather-alerts",
"/api/storms",
})
PUBLIC_GET_PATTERNS = tuple(re.compile(p) for p in (
r"^/api/events/[^/]+$",
r"^/api/entities/[^/]+$",
r"^/api/entities/[^/]+/events$",
r"^/api/cameras/[^/]+$",
r"^/api/cameras/[^/]+/(?:snapshot|stream|hls\.m3u8|hlsseg)$",
r"^/api/geofences/[^/]+/at$",
))
# POST is only public for the read-only query endpoint.
PUBLIC_POST_EXACT = frozenset({"/api/search"})
def is_public(path: str, method: str) -> bool:
"""True when ``method path`` may be served without an admin session."""
if not path.startswith("/api/"):
return True
if path.startswith("/api/auth/"):
return True
norm = path.rstrip("/") or "/"
if method in ("GET", "HEAD"):
if norm in PUBLIC_GET_EXACT:
return True
return any(p.match(norm) for p in PUBLIC_GET_PATTERNS)
if method == "POST":
return norm in PUBLIC_POST_EXACT
return False
# ── Config (read per call so tests and reloads pick up env changes) ─────────
def _env(name: str) -> str:
return (os.environ.get(name) or "").strip()
def admin_user() -> str:
return _env("ADMIN_USER")
def admin_password_hash() -> str:
return _env("ADMIN_PASSWORD_HASH")
def session_secret() -> str:
return _env("ADMIN_SESSION_SECRET")
def auth_configured() -> bool:
"""Fail closed: both the password hash and the signing key must be set."""
return bool(admin_password_hash() and session_secret())
# ── Password hashing (stdlib PBKDF2-SHA256) ─────────────────────────────────
def _b64e(raw: bytes) -> str:
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
def _b64d(text: str) -> bytes:
pad = "=" * (-len(text) % 4)
return base64.urlsafe_b64decode(text + pad)
def hash_password(password: str, *, iterations: int = PBKDF2_ITERATIONS,
salt: bytes | None = None) -> str:
"""Return ``pbkdf2_sha256$<iters>$<salt_b64>$<hash_b64>``."""
salt = salt if salt is not None else secrets.token_bytes(16)
dk = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, iterations)
return f"{PBKDF2_ALGORITHM}${iterations}${_b64e(salt)}${_b64e(dk)}"
def verify_password(password: str, stored: str) -> bool:
"""Constant-time check of ``password`` against a stored PBKDF2 string."""
if not stored:
return False
try:
algorithm, iterations_s, salt_b64, hash_b64 = stored.split("$", 3)
iterations = int(iterations_s)
salt = _b64d(salt_b64)
expected = _b64d(hash_b64)
except (ValueError, TypeError):
return False
if algorithm != PBKDF2_ALGORITHM:
return False
if not (_ITERATIONS_FLOOR <= iterations <= _ITERATIONS_CEIL):
return False
dk = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, iterations)
return hmac.compare_digest(dk, expected)
def _const_eq(a: str, b: str) -> bool:
return hmac.compare_digest(a.encode("utf-8"), b.encode("utf-8"))
# ── Session tokens ───────────────────────────────────────────────────────────
def _sign(body: str, secret: str) -> str:
digest = hmac.new(secret.encode("utf-8"), body.encode("ascii"), hashlib.sha256).digest()
return _b64e(digest)
def create_session_token(user: str, *, now: float | None = None) -> str:
secret = session_secret()
if not secret:
raise RuntimeError("ADMIN_SESSION_SECRET is not configured")
issued = int(now if now is not None else time.time())
payload = {"v": 1, "sub": user, "iat": issued, "exp": issued + SESSION_TTL_SECONDS}
body = _b64e(json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8"))
return f"{body}.{_sign(body, secret)}"
def verify_session_token(token: str | None, *, now: float | None = None) -> str | None:
"""Return the username for a valid token, else ``None``. Never raises."""
if not token or "." not in token:
return None
secret = session_secret()
if not secret:
return None
body, signature = token.rsplit(".", 1)
try:
expected = _sign(body, secret)
if not hmac.compare_digest(signature.encode("utf-8"), expected.encode("utf-8")):
return None
except (UnicodeEncodeError, ValueError, TypeError):
return None
try:
payload = json.loads(_b64d(body))
version = payload["v"]
subject = str(payload["sub"])
issued = int(payload["iat"])
expires = int(payload["exp"])
except (ValueError, KeyError, TypeError):
return None
now_s = int(now if now is not None else time.time())
if version != 1:
return None
if expires <= now_s or issued > now_s + 300:
return None
expected = admin_user()
if not expected or not _const_eq(subject, expected):
return None
return subject
def current_user(request: Request) -> str | None:
"""The authenticated admin username for this request, else ``None``."""
if not auth_configured():
return None
return verify_session_token(request.cookies.get(COOKIE_NAME))
# ── Cookie helpers ───────────────────────────────────────────────────────────
def _is_https(request: Request) -> bool:
proto = (request.headers.get("x-forwarded-proto") or "").split(",")[0].strip().lower()
if proto:
return proto == "https"
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,
token,
max_age=SESSION_TTL_SECONDS,
httponly=True,
samesite="lax",
secure=cookie_secure_forced() or _is_https(request),
path="/",
)
def clear_session_cookie(response) -> None:
response.delete_cookie(COOKIE_NAME, path="/", httponly=True, samesite="lax")
# ── Login rate limiting (in-memory; single replica) ─────────────────────────
_failures: dict[str, deque[float]] = {}
def client_ip(request: Request) -> str:
forwarded = request.headers.get("x-forwarded-for") or ""
first = forwarded.split(",")[0].strip()
if first:
return first
return request.client.host if request.client else "unknown"
def _prune(bucket: deque[float], now: float) -> None:
while bucket and now - bucket[0] > LOGIN_WINDOW_SECONDS:
bucket.popleft()
def rate_limited(ip: str, *, now: float | None = None) -> bool:
now_s = time.time() if now is None else now
bucket = _failures.get(ip)
if not bucket:
return False
_prune(bucket, now_s)
return len(bucket) >= LOGIN_MAX_FAILURES
def record_failure(ip: str, *, now: float | None = None) -> None:
now_s = time.time() if now is None else now
if len(_failures) > 10_000: # bound memory against IP spraying
for key in [k for k, v in _failures.items() if not v or now_s - v[-1] > LOGIN_WINDOW_SECONDS]:
_failures.pop(key, None)
bucket = _failures.setdefault(ip, deque())
_prune(bucket, now_s)
bucket.append(now_s)
def reset_failures(ip: str | None = None) -> None:
"""Clear the limiter (used by logout success and tests)."""
if ip is None:
_failures.clear()
else:
_failures.pop(ip, None)
# ── CSRF (origin host must match the request host when supplied) ────────────
def origin_allowed(request: Request) -> bool:
if request.method.upper() not in _STATE_CHANGING:
return True
origin = request.headers.get("origin") or request.headers.get("referer")
if not origin:
return True # no browser context: session cookie is the credential
host = (request.headers.get("x-forwarded-host") or request.headers.get("host") or "")
host = host.split(",")[0].strip().lower()
try:
origin_host = urlparse(origin).netloc.strip().lower()
except ValueError:
return False
if not host or not origin_host:
return False
return origin_host == host
# ── Middleware ───────────────────────────────────────────────────────────────
def _json_response(status: int, detail: str) -> JSONResponse:
return JSONResponse({"detail": detail}, status_code=status)
class AdminAuthMiddleware:
"""Deny-by-default gate for ``/api/*`` (pure ASGI; keeps streaming intact)."""
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
if scope.get("type") != "http":
return await self.app(scope, receive, send)
path = scope.get("path") or ""
method = (scope.get("method") or "GET").upper()
if not path.startswith("/api/") or is_public(path, method):
return await self.app(scope, receive, send)
request = Request(scope)
if not auth_configured():
return await _json_response(403, "admin auth not configured")(scope, receive, send)
if current_user(request) is None:
return await _json_response(401, "admin authentication required")(scope, receive, send)
if not origin_allowed(request):
return await _json_response(403, "cross-origin admin request blocked")(scope, receive, send)
return await self.app(scope, receive, send)
# ── Auth routes ─────────────────────────────────────────────────────────────
router = APIRouter()
@router.get("/api/auth/me")
async def auth_me(request: Request):
"""Always 200 — the HUD uses this to show/hide admin UI."""
user = current_user(request)
return {"authenticated": user is not None, "admin": user is not None}
async def _read_credentials(request: Request) -> dict:
"""Accept form-encoded or JSON bodies (never trust the claimed type)."""
raw = await request.body()
if not raw:
return {}
ctype = (request.headers.get("content-type") or "").lower()
if "json" in ctype:
try:
payload = json.loads(raw)
except (ValueError, TypeError):
return {}
return payload if isinstance(payload, dict) else {}
if "form" in ctype or "urlencoded" in ctype:
try:
parsed = parse_qs(raw.decode("utf-8", "replace"))
except (ValueError, TypeError):
return {}
return {k: v[0] for k, v in parsed.items() if v}
# Unknown content type: try JSON, then form.
try:
payload = json.loads(raw)
if isinstance(payload, dict):
return payload
except (ValueError, TypeError):
pass
try:
parsed = parse_qs(raw.decode("utf-8", "replace"))
except (ValueError, TypeError):
return {}
return {k: v[0] for k, v in parsed.items() if v}
@router.post("/api/auth/login")
async def auth_login(request: Request):
ip = client_ip(request)
if not auth_configured():
return _json_response(403, "admin auth not configured")
if rate_limited(ip):
return _json_response(429, "too many failed login attempts")
data = await _read_credentials(request)
username = str(data.get("username") or data.get("user") or "")
password = str(data.get("password") or "")
user_ok = bool(username) and bool(admin_user()) and _const_eq(username, admin_user())
pass_ok = verify_password(password, admin_password_hash())
if not (user_ok and pass_ok):
record_failure(ip)
return _json_response(401, "invalid credentials")
reset_failures(ip)
response = JSONResponse({"authenticated": True, "admin": True})
set_session_cookie(response, request, create_session_token(admin_user()))
return response
@router.post("/api/auth/logout")
async def auth_logout(request: Request):
# NOTE: never clear the login limiter here — logout is unauthenticated and
# would otherwise let an attacker reset the rate limit between guesses.
response = JSONResponse({"authenticated": False, "admin": False})
clear_session_cookie(response)
return response
_LOGIN_PAGE = """<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex">
<title>Admin sign-in · OSINT//</title>
<style>
:root { --bg:#05070c; --panel:#0b1018; --line:#1c2735; --cyan:#35e0ff; --magenta:#ff2e97; --text:#d7e3f2; --dim:#7d8ea3; }
* { box-sizing:border-box; }
body { margin:0; min-height:100vh; display:grid; place-items:center; background:
radial-gradient(1000px 500px at 50% -10%, rgba(53,224,255,.10), transparent 60%),
radial-gradient(700px 400px at 90% 110%, rgba(255,46,151,.08), transparent 60%), var(--bg);
color:var(--text); font:15px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; }
.box { width:100%; max-width:360px; padding:2rem 1.6rem; border:1px solid var(--line);
border-radius:8px; background:linear-gradient(180deg, var(--panel), #070b12);
box-shadow:0 0 0 1px rgba(53,224,255,.06), 0 24px 60px rgba(0,0,0,.6); }
.brand { letter-spacing:.24em; font-size:.8rem; color:var(--dim); margin-bottom:1.4rem; }
.brand b { color:var(--cyan); }
h1 { font-size:1rem; letter-spacing:.12em; margin:0 0 1.2rem; text-transform:uppercase; }
label { display:block; font-size:.68rem; letter-spacing:.16em; color:var(--dim);
text-transform:uppercase; margin:.9rem 0 .35rem; }
input { width:100%; padding:.6rem .7rem; background:#04070d; color:var(--text);
border:1px solid var(--line); border-radius:4px; font:inherit; }
input:focus { outline:none; border-color:var(--cyan); box-shadow:0 0 0 2px rgba(53,224,255,.14); }
button { width:100%; margin-top:1.4rem; padding:.65rem; background:var(--cyan); color:#02121a;
border:0; border-radius:4px; font:inherit; font-weight:700; letter-spacing:.12em; cursor:pointer; }
button:hover { background:#6becff; }
button:disabled { opacity:.5; cursor:default; }
.msg { min-height:1.2rem; margin-top:.9rem; font-size:.8rem; color:var(--magenta); }
.note { margin-top:1.1rem; font-size:.74rem; color:var(--dim); }
a { color:var(--cyan); text-decoration:none; }
</style>
</head>
<body>
<form class="box" id="login-form">
<div class="brand">OSINT<b>//</b> ADMIN</div>
<h1>Sign in</h1>
<label for="username">Username</label>
<input id="username" name="username" type="text" autocomplete="username" required autofocus>
<label for="password">Password</label>
<input id="password" name="password" type="password" autocomplete="current-password" required>
<button id="submit" type="submit">AUTHENTICATE</button>
<div class="msg" id="msg" role="alert"></div>
<div class="note"><a href="/">← Back to dashboard</a></div>
</form>
<script>
const form = document.getElementById('login-form');
const msg = document.getElementById('msg');
const submit = document.getElementById('submit');
form.addEventListener('submit', async (ev) => {
ev.preventDefault();
msg.textContent = '';
submit.disabled = true;
try {
const r = await fetch('/api/auth/login', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: new URLSearchParams(new FormData(form)),
});
const data = await r.json().catch(() => ({}));
if (r.ok) { window.location.replace('/'); return; }
msg.textContent = r.status === 429 ? 'Too many attempts. Try again later.'
: (data && data.detail ? String(data.detail) : 'Sign-in failed.');
} catch (e) {
msg.textContent = 'Network error.';
} finally {
submit.disabled = false;
}
});
</script>
</body>
</html>
"""
_NOT_CONFIGURED = ('<div class="msg">Admin auth is not configured on this server. '
'Set ADMIN_PASSWORD_HASH and ADMIN_SESSION_SECRET.</div>')
@router.get("/login", response_class=HTMLResponse)
async def login_page():
html = _LOGIN_PAGE
if not auth_configured():
html = html.replace('<div class="msg" id="msg" role="alert"></div>',
_NOT_CONFIGURED.replace('class="msg"', 'class="msg" id="msg" role="alert"'))
response = HTMLResponse(html)
response.headers["Cache-Control"] = "no-store"
return response
# ── CLI: generate a password hash ────────────────────────────────────────────
def _main(argv: list[str]) -> int:
if len(argv) != 2 or argv[0] != "hash":
print("usage: python app/auth.py hash '<password>'")
return 2
print(hash_password(argv[1]))
return 0
if __name__ == "__main__":
import sys
raise SystemExit(_main(sys.argv[1:]))

View file

@ -1,72 +0,0 @@
"""Background ffmpeg — never block a FastAPI request on a frame grab.
ffmpeg frame grabs are scheduled with asyncio.create_task and shared per URL.
"""
from __future__ import annotations
import asyncio
import shutil
from cachetools import TTLCache
_ffmpeg_cache: TTLCache = TTLCache(maxsize=100, ttl=300)
_ffmpeg_tasks: dict[str, asyncio.Task] = {}
_FFMPEG = shutil.which("ffmpeg")
def cached_ffmpeg_jpeg(url: str) -> bytes | None:
return _ffmpeg_cache.get(url)
def schedule_ffmpeg_snapshot(url: str, timeout: float = 8.0) -> asyncio.Task:
"""Start (or reuse) an ffmpeg JPEG grab. Caller may await the task."""
existing = _ffmpeg_tasks.get(url)
if existing is not None and not existing.done():
return existing
task = asyncio.create_task(_ffmpeg_grab_and_cache(url, timeout))
_ffmpeg_tasks[url] = task
return task
async def _ffmpeg_grab(url: str, timeout: float = 8.0) -> bytes | None:
"""Grab one JPEG frame. Isolated so tests can stub it."""
if not _FFMPEG or not url.lower().startswith("rtsp://"):
return None
cmd = [
_FFMPEG, "-hide_banner", "-loglevel", "error", "-nostdin",
"-rtsp_transport", "tcp",
"-timeout", "4000000",
"-i", url,
"-frames:v", "1",
"-f", "image2pipe", "-vcodec", "mjpeg",
"pipe:1",
]
try:
proc = await asyncio.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
)
except FileNotFoundError:
return None
try:
stdout, _ = await asyncio.wait_for(proc.communicate(), timeout=timeout)
except asyncio.TimeoutError:
proc.kill()
try:
await proc.wait()
except Exception: # noqa: BLE001
pass
return None
if proc.returncode not in (0, None) or not stdout or len(stdout) < 64:
return None
if stdout[:2] != b"\xff\xd8":
return None
return stdout
async def _ffmpeg_grab_and_cache(url: str, timeout: float) -> bytes | None:
data = await _ffmpeg_grab(url, timeout)
if data:
_ffmpeg_cache[url] = data
return data

View file

@ -1,76 +0,0 @@
"""Camera discovery configuration (12-factor, env-driven).
All knobs read from the environment with container-friendly defaults.
"""
from __future__ import annotations
import os
# ── Camera scraper ─────────────────────────────────────────────────────────
# Comma-separated public directory/list/API URLs to scrape.
# Formats: Insecam-style HTML, plain-text URL lists, ALERTWest JSON.
# NOTE: docker-compose always defines CAMERA_SOURCE_URLS (empty when no .env),
# so os.getenv()'s default would never apply — use `or` semantics instead.
CALTRANS_CCTV_URLS = tuple(
f"https://cwwp2.dot.ca.gov/data/d{n}/cctv/cctvStatusD{n:02d}.json"
for n in range(1, 13)
)
# MDOT MiDrive official DOT CCTV list (fields carry rendered HTML).
MDOT_CAMERA_URL = "https://mdotjboss.state.mi.us/MiDrive/camera/list"
_DEFAULT_SOURCE_URL = ",".join((
# Publicly published open-camera list (markdown bullets of stream URLs).
"https://raw.githubusercontent.com/fury999io/public-ip-cams/main/README.md",
# ALERTCalifornia / ALERTWest official public JPEG API (wildfire + DOT + FAA).
"https://api.cdn.prod.alertwest.com/api/getCameraDataByLoc",
# Curated global outdoor streams (HLS / YouTube / JPEG) — VDOT, MDSHA, etc.
"https://raw.githubusercontent.com/willytop8/Live-Environment-Streams/main/streams.geojson",
# Official Caltrans CWWP2 JPEG + HLS CCTV (districts 1–12).
*CALTRANS_CCTV_URLS,
# Oregon DOT TripCheck public CCTV JPEG inventory (Esri JSON).
"https://www.tripcheck.com/Scripts/map/data/cctvinventory.js",
# Official MDOT MiDrive CCTV (JPEG stills, Michigan).
MDOT_CAMERA_URL,
))
CAMERA_SOURCE_URLS = [
u.strip()
for u in (os.getenv("CAMERA_SOURCE_URLS") or _DEFAULT_SOURCE_URL).split(",")
if u.strip() # empty env var → fall back to the default above
]
# Seconds between full scrape cycles of every source.
CAMERA_SCRAPE_INTERVAL = int(os.getenv("CAMERA_SCRAPE_INTERVAL", "3600"))
# Politeness: minimum seconds between consecutive requests to the SAME host.
CAMERA_REQUEST_DELAY = float(os.getenv("CAMERA_REQUEST_DELAY", "2.0"))
# Max cameras accepted per scrape cycle per source (safety cap).
CAMERA_MAX_PER_SOURCE = int(os.getenv("CAMERA_MAX_PER_SOURCE", "20000"))
# ── Geocoding (Nominatim — free, 1 req/s hard politeness limit) ────────────
NOMINATIM_URL = os.getenv("NOMINATIM_URL", "https://nominatim.openstreetmap.org")
NOMINATIM_MIN_INTERVAL = float(os.getenv("NOMINATIM_MIN_INTERVAL", "1.0"))
USER_AGENT = os.getenv(
"OSINT_USER_AGENT", "osint-dashboard-camera-scraper/1.0 (self-hosted)"
)
# ── Snapshot cache ─────────────────────────────────────────────────────────
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"))
# 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")
# ── UDOT IBI 511 traffic cameras ──────────────────────────────────────────
# DataTables endpoint (POST form-encoded; server caps at 100 rows/page no
# matter what `length` is sent). No API key. Snapshot stills live at a stable
# /map/Cctv/{id} URL — same URL always serves the latest frame, so we store
# the URL and never scrape every frame ourselves.
UDOT_IBI_URL = "https://prod-ut.ibi511.com/List/GetData/Cameras"
UDOT_IBI_BASE = "https://prod-ut.ibi511.com"
UDOT_IBI_PAGE_SIZE = 100
# Safety cap on pages per cycle so a runaway recordsTotal cannot fan out.
UDOT_IBI_MAX_PAGES = int(os.getenv("UDOT_IBI_MAX_PAGES", "40"))

View file

@ -1,112 +0,0 @@
"""HLS playlist rewriter so the in-page player can play CORS-blocked feeds.
The browser talks only to /api/cameras/{id}/hls.m3u8 and /hlsseg. We fetch
the real playlist, rewrite every URI to our proxy, and remember the hosts
that appeared so /hlsseg cannot be used as an open proxy.
"""
from __future__ import annotations
import re
import time
from urllib.parse import quote, unquote, urljoin, urlparse
import httpx
from fastapi import HTTPException
from fastapi.responses import Response
from camera_scraper import is_public_url
_UA = {"User-Agent": "osint-dashboard-hls/1.0"}
# camera_id -> (expiry_epoch, allowed_hosts)
_ALLOWED: dict[str, tuple[float, set[str]]] = {}
_TTL = 600.0
_URI_ATTR = re.compile(r'URI="([^"]+)"', re.I)
def _remember(camera_id: str, url: str) -> None:
host = urlparse(url).hostname
if not host:
return
now = time.monotonic()
exp, hosts = _ALLOWED.get(camera_id, (now + _TTL, set()))
hosts.add(host.lower())
_ALLOWED[camera_id] = (now + _TTL, hosts)
def _host_ok(camera_id: str, url: str) -> bool:
host = (urlparse(url).hostname or "").lower()
if not host:
return False
rec = _ALLOWED.get(camera_id)
if not rec or rec[0] < time.monotonic():
return False
return host in rec[1]
def _proxied(camera_id: str, abs_url: str) -> str:
_remember(camera_id, abs_url)
return f"/api/cameras/{camera_id}/hlsseg?u={quote(abs_url, safe='')}"
def rewrite_m3u8(text: str, base: str, camera_id: str) -> str:
out: list[str] = []
for line in text.splitlines():
stripped = line.strip()
if not stripped:
out.append(line)
continue
if stripped.startswith("#"):
def repl(m: re.Match[str]) -> str:
return f'URI="{_proxied(camera_id, urljoin(base, m.group(1)))}"'
out.append(_URI_ATTR.sub(repl, line))
continue
out.append(_proxied(camera_id, urljoin(base, stripped)))
return "\n".join(out) + "\n"
async def fetch_playlist(camera_id: str, url: str) -> Response:
if not is_public_url(url):
raise HTTPException(400, "HLS URL is not public")
_remember(camera_id, url)
try:
async with httpx.AsyncClient(timeout=15, follow_redirects=True, headers=_UA) as c:
r = await c.get(url)
except Exception as exc: # noqa: BLE001
raise HTTPException(502, "HLS playlist unavailable") from exc
if r.status_code != 200:
raise HTTPException(502, "HLS playlist unavailable")
base = str(r.url)
body = rewrite_m3u8(r.text, base, camera_id)
return Response(
content=body,
media_type="application/vnd.apple.mpegurl",
headers={"Cache-Control": "no-store"},
)
async def fetch_segment(camera_id: str, raw_url: str) -> Response:
url = unquote(raw_url)
if not url.lower().startswith(("http://", "https://")):
raise HTTPException(400, "invalid segment URL")
if not is_public_url(url):
raise HTTPException(400, "segment URL is not public")
if not _host_ok(camera_id, url):
raise HTTPException(400, "segment host not in playlist")
try:
async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=_UA) as c:
r = await c.get(url)
except Exception as exc: # noqa: BLE001
raise HTTPException(502, "HLS segment unavailable") from exc
if r.status_code != 200:
raise HTTPException(502, "HLS segment unavailable")
ctype = (r.headers.get("content-type") or "").lower()
if "mpegurl" in ctype or "m3u8" in url.lower().split("?")[0]:
body = rewrite_m3u8(r.text, str(r.url), camera_id)
return Response(content=body, media_type="application/vnd.apple.mpegurl",
headers={"Cache-Control": "no-store"})
return Response(
content=r.content,
media_type=r.headers.get("content-type") or "application/octet-stream",
headers={"Cache-Control": "no-store"},
)

View file

@ -1,43 +0,0 @@
"""Open IP camera discovery — models and migration helpers.
Cameras are stored in their own `cameras` table (TimescaleDB hypertable on
last_seen) alongside the existing `events` feed, deduped by URL hash.
"""
from __future__ import annotations
from sqlalchemy import (
Column, Float, Index, Integer, String, Text, DateTime, JSON,
func, Table, BigInteger,
)
from sqlalchemy.dialects.postgresql import UUID
import uuid
from database import metadata
cameras = Table(
"cameras",
metadata,
Column("id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4),
# sha256 hex of the camera's source/snapshot URL — the dedupe key.
Column("url_hash", String(64), nullable=False, index=True),
Column("source_url", Text, nullable=False),
# Snapshot endpoint (may differ from the directory listing URL).
Column("snapshot_url", Text),
# Which discovery feed produced this record (e.g. "insecam", "camera_list").
Column("discovery_source", String(128), nullable=False, index=True),
Column("location_lat", Float),
Column("location_lon", Float),
Column("location_name", String(512)),
# Vendor / device type when detectable from the directory page or URL.
Column("vendor", String(128)),
Column("device_type", String(64)), # e.g. ip-cam, rtsp, mjpeg
Column("first_seen", DateTime(timezone=True), server_default=func.now(), nullable=False),
Column("last_seen", DateTime(timezone=True), server_default=func.now(), nullable=False),
Column("raw", JSON),
)
Index("ix_cameras_location", cameras.c.location_lat, cameras.c.location_lon)
Index("ix_cameras_last_seen", cameras.c.last_seen)

View file

@ -1,187 +0,0 @@
"""Resolve a browser-renderable preview for a camera.
HTTP/MJPEG cameras already expose a snapshot_url the existing proxy can
stream. Some scraper sources store `rtsp://` URLs with no snapshot_url, so
the map popup used to skip the <img> entirely and the leftover source link
handed the browser an rtsp:// URL (which opens VLC).
This module:
1. Tries a short list of unauthenticated HTTP snapshot paths (fast).
2. Falls back to grabbing one JPEG frame from RTSP via ffmpeg (no auth).
3. Remembers the first URL that worked on the camera row so the next
popup is a cache hit.
No credentials are ever tried.
"""
from __future__ import annotations
import asyncio
import logging
import shutil
from urllib.parse import urlparse
import httpx
from camera_config import USER_AGENT
from camera_models import cameras
from camera_scraper import fetch_snapshot
from database import async_session
logger = logging.getLogger("osint.camera_preview")
# Most common unauthenticated still-image endpoints on consumer NVRs/IP cams.
# Keep this list SHORT — it runs on popup click.
_HTTP_PATHS = (
"/snapshot.jpg",
"/cgi-bin/snapshot.cgi",
"/jpg/image.jpg",
"/image.jpg",
"/onvif/snapshot",
"/axis-cgi/jpg/image.cgi",
"/tmpfs/auto.jpg",
)
_FFMPEG = shutil.which("ffmpeg")
def _host_from_url(url: str) -> str | None:
try:
return urlparse(url).hostname
except Exception: # noqa: BLE001
return None
def _looks_like_jpeg(data: bytes) -> bool:
return bool(data) and len(data) >= 64 and data[:2] == b"\xff\xd8"
async def _http_get_image(url: str, timeout: float = 2.5) -> bytes | None:
try:
async with httpx.AsyncClient(
timeout=timeout, follow_redirects=True,
headers={"User-Agent": USER_AGENT},
) as c:
r = await c.get(url)
if r.status_code != 200:
return None
ctype = (r.headers.get("content-type") or "").lower()
if "html" in ctype or "text/" in ctype:
return None
if not _looks_like_jpeg(r.content) and "image/" not in ctype:
return None
if len(r.content) < 64:
return None
return r.content
except Exception: # noqa: BLE001
return None
async def ffmpeg_snapshot(url: str, timeout: float = 8.0) -> bytes | None:
"""Grab a single JPEG frame from an RTSP URL. None if ffmpeg missing/fails.
The subprocess is scheduled via asyncio.create_task (shared per URL) so
concurrent popup clicks do not stack ffmpeg processes on the request path.
"""
from bg_jobs import cached_ffmpeg_jpeg, schedule_ffmpeg_snapshot
hit = cached_ffmpeg_jpeg(url)
if hit:
return hit
return await schedule_ffmpeg_snapshot(url, timeout)
async def ffmpeg_mjpeg_stream(url: str):
"""Yield an MJPEG multipart body transcoded from RTSP. Caller streams it."""
if not _FFMPEG:
return
cmd = [
_FFMPEG, "-hide_banner", "-loglevel", "error", "-nostdin",
]
if url.lower().startswith("rtsp://"):
cmd += ["-rtsp_transport", "tcp", "-timeout", "4000000"]
cmd += [
"-i", url,
"-an", "-c:v", "mjpeg", "-q:v", "8",
"-f", "mpjpeg", "pipe:1",
]
proc = await asyncio.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
)
try:
assert proc.stdout is not None
while True:
chunk = await proc.stdout.read(64 * 1024)
if not chunk:
break
yield chunk
finally:
if proc.returncode is None:
proc.kill()
try:
await proc.wait()
except Exception: # noqa: BLE001
pass
async def _remember(camera_id, url: str) -> None:
try:
async with async_session() as session:
await session.execute(
cameras.update()
.where(cameras.c.id == camera_id)
.values(snapshot_url=url)
)
await session.commit()
except Exception: # noqa: BLE001
logger.warning("failed to persist snapshot_url for %s", camera_id,
exc_info=True)
async def resolve_preview(row) -> tuple[bytes | None, str | None]:
"""Return (jpeg_bytes, working_url) for a cameras-table row.
Tries, in order:
* existing HTTP snapshot_url (via the TTL cache)
* common HTTP still-image paths on the host
* ffmpeg frame grab from the stored RTSP URL, then common RTSP paths
"""
snap = row.get("snapshot_url") or ""
source = row.get("source_url") or ""
host = _host_from_url(snap) or _host_from_url(source)
if not host:
return None, None
# 1. Known HTTP snapshot — go through the existing TTL cache.
if snap.lower().startswith(("http://", "https://")):
data = await fetch_snapshot(snap)
if data:
return data, snap
# 2. Probe unauthenticated HTTP stills in parallel (fast fail) BEFORE
# any ffmpeg — most open cams that preview at all do it over HTTP.
http_urls = [f"http://{host}{p}" for p in _HTTP_PATHS]
http_urls.append(f"http://{host}:8080/shot.jpg")
results = await asyncio.gather(
*(_http_get_image(u) for u in http_urls),
return_exceptions=True,
)
for url, data in zip(http_urls, results):
if isinstance(data, (bytes, bytearray)) and data:
await _remember(row["id"], url)
return bytes(data), url
# 3. One ffmpeg grab of the stored RTSP URL. Path-walking is too slow
# for a popup click; unauthenticated RTSP often needs a vendor path
# and/or credentials we will not try.
rtsp_url = snap if snap.lower().startswith("rtsp://") else source
if rtsp_url.lower().startswith("rtsp://"):
data = await ffmpeg_snapshot(rtsp_url, timeout=5.0)
if data:
if not snap:
await _remember(row["id"], rtsp_url)
return data, rtsp_url
return None, None

View file

@ -1,875 +0,0 @@
"""Camera discovery scraper — finds publicly listed open IP cameras.
Ethics/scope (hard constraints, enforced in code):
* Only indexes cameras that appear in PUBLIC directories/lists.
* No credential brute-forcing, no login attempts of any kind.
* No active scanning — never probes private (RFC1918/loopback/link-local)
ranges; private-range URLs found in public lists are dropped.
Pipeline per cycle:
1. Fetch each configured public source page/list.
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. 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.
"""
from __future__ import annotations
import asyncio
import hashlib
import ipaddress
import json
import logging
import math
import re
import time
from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import urlparse
import httpx
from camera_config import (
CAMERA_SOURCE_URLS, CAMERA_REQUEST_DELAY, CAMERA_MAX_PER_SOURCE,
NOMINATIM_URL, NOMINATIM_MIN_INTERVAL, USER_AGENT,
SNAPSHOT_CACHE_DIR, SNAPSHOT_TTL_SECONDS, SNAPSHOT_TIMEOUT,
UDOT_IBI_URL, UDOT_IBI_BASE, UDOT_IBI_PAGE_SIZE, UDOT_IBI_MAX_PAGES,
)
from camera_models import cameras
from database import async_session
logger = logging.getLogger("osint.camera_scraper")
# ── Private-range guard ────────────────────────────────────────────────────
_public_host_cache: dict[str, bool] = {}
def is_public_url(url: str) -> bool:
"""True only if the URL host resolves to a globally-routable address.
Hostnames that cannot be resolved are treated as not-public (fail closed).
"""
try:
parsed = urlparse(url)
if parsed.scheme not in ("http", "https", "rtsp", "rtsps"):
return False
host = parsed.hostname
if not host:
return False
# Literal IPs: check directly.
try:
addr = ipaddress.ip_address(host)
return addr.is_global and not addr.is_private
except ValueError:
pass
if host in _public_host_cache:
return _public_host_cache[host]
# Private-name quick rejects before any DNS work.
if (host.endswith(".local") or host.endswith(".internal")
or host == "localhost" or re.fullmatch(r"10\..*|172\.(1[6-9]|2\d|3[01])\..*|192\.168\..*", host)):
_public_host_cache[host] = False
return False
import socket
ok = True
for info in socket.getaddrinfo(host, None):
addr = ipaddress.ip_address(info[4][0])
if not (addr.is_global and not addr.is_private):
ok = False
break
_public_host_cache[host] = ok
return ok
except Exception: # noqa: BLE001
return False
# ── Dedupe key ─────────────────────────────────────────────────────────────
def url_hash(url: str) -> str:
return hashlib.sha256(url.strip().lower().encode()).hexdigest()
# ── Politeness-limited fetcher ─────────────────────────────────────────────
class RateLimitedClient:
"""httpx client wrapper enforcing a per-host minimum request interval."""
def __init__(self, min_delay: float = CAMERA_REQUEST_DELAY):
self._delay = min_delay
self._last: dict[str, float] = {}
self.client = httpx.AsyncClient(
timeout=60, follow_redirects=True,
headers={"User-Agent": USER_AGENT},
)
async def get(self, url: str, **kw) -> httpx.Response:
host = urlparse(url).netloc
now = time.monotonic()
wait = self._last.get(host, 0.0) + self._delay - now
if wait > 0:
await asyncio.sleep(wait)
self._last[host] = time.monotonic()
return await self.client.get(url, **kw)
async def post(self, url: str, **kw) -> httpx.Response:
host = urlparse(url).netloc
now = time.monotonic()
wait = self._last.get(host, 0.0) + self._delay - now
if wait > 0:
await asyncio.sleep(wait)
self._last[host] = time.monotonic()
return await self.client.post(url, **kw)
async def aclose(self):
await self.client.aclose()
# ── Nominatim geocoding (1 req/s politeness) ───────────────────────────────
class Geocoder:
def __init__(self):
self._min_interval = NOMINATIM_MIN_INTERVAL
self._last = 0.0
self._cache: dict[str, tuple[float | None, float | None]] = {}
self._lock = asyncio.Lock()
async def geocode(self, place: str) -> tuple[float | None, float | None]:
place = place.strip()
if not place:
return None, None
if place in self._cache:
return self._cache[place]
async with self._lock:
wait = self._last + self._min_interval - time.monotonic()
if wait > 0:
await asyncio.sleep(wait)
try:
async with httpx.AsyncClient(timeout=15) as c:
r = await c.get(
f"{NOMINATIM_URL}/search",
params={"q": place, "format": "json", "limit": 1},
headers={"User-Agent": USER_AGENT},
)
r.raise_for_status()
data = r.json()
result = (
(float(data[0]["lat"]), float(data[0]["lon"]))
if data else (None, None)
)
except Exception: # noqa: BLE001
logger.warning("geocode failed for %r", place, exc_info=True)
result = (None, None)
self._last = time.monotonic()
self._cache[place] = result
return result
# ── Snapshot cache (local disk, TTL'd) ─────────────────────────────────────
_snapshot_lock = asyncio.Lock()
async def fetch_snapshot(url: str) -> bytes | None:
"""Fetch a snapshot image through the local TTL cache. Returns raw bytes."""
key = url_hash(url)[:24]
path = Path(SNAPSHOT_CACHE_DIR) / f"{key}.bin"
meta = Path(SNAPSHOT_CACHE_DIR) / f"{key}.meta"
async with _snapshot_lock:
try:
if path.exists() and meta.exists():
age = time.time() - path.stat().st_mtime
if age < SNAPSHOT_TTL_SECONDS:
return path.read_bytes()
except OSError:
pass
try:
async with httpx.AsyncClient(timeout=SNAPSHOT_TIMEOUT, follow_redirects=True) as c:
r = await c.get(url, headers={"User-Agent": USER_AGENT})
if r.status_code != 200 or len(r.content) < 64:
return None
data = r.content
except Exception: # noqa: BLE001
return None
async with _snapshot_lock:
try:
Path(SNAPSHOT_CACHE_DIR).mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
meta.write_text(json.dumps({"url": url, "fetched": time.time()}))
except OSError:
logger.warning("snapshot cache write failed", exc_info=True)
return data
# ── Source parsers ─────────────────────────────────────────────────────────
# Insecam-style pages embed camera entries like:
# <a href="/view/..."> ... latitude: 48.85 / longitude: 2.35 ... title="Paris"
# We parse generically: find lat/lon pairs plus nearby snapshot <img> sources.
_LATLON_RE = re.compile(
r"(?:latitude|lat)[\"'\s:=]+(-?\d{1,2}\.\d+).{0,200}?(?:longitude|lon)[\"'\s:=]+(-?\d{1,3}\.\d+)",
re.I | re.S,
)
_IMG_RE = re.compile(r"<img[^>]+src=[\"']([^\"']+\.(?:jpg|jpeg|png|mjpeg))[\"']", re.I)
_TITLE_RE = re.compile(r"<title>([^<]+)</title>", re.I)
def _vendor_from_url(url: str) -> str | None:
u = url.lower()
for vendor, marker in [
("hikvision", "hikvision"), ("dahua", "dahua"),
("axis", "axis-cgi"), ("foscam", "foscam"),
("tplink", "tplink"), ("tp-link", "tp-link"),
("mjpeg", "mjpeg"), ("rtsp", "rtsp://"),
]:
if marker in u:
return vendor
return None
def parse_plain_list(text: str, source_name: str) -> list[dict]:
"""Parse camera URLs from a plain-text or markdown list.
Accepted line shapes:
* `url[|lat,lon|vendor|location_name]` (strict form)
* markdown bullets / bare lines that merely CONTAIN a URL
(e.g. `* http://1.2.3.4/mjpg/video.mjpg`) — coords/vendor unknown.
"""
cams = []
url_re = re.compile(r'(?:https?|rtsp)://[^\s\)\]>"\']+', re.I)
for line in text.splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
m = url_re.search(line)
if not m:
continue
# Reuse strict parsing when the URL is pipe-delimited with metadata;
# otherwise take just the URL and leave metadata empty.
if "|" in line:
parts = [p.strip() for p in line.split("|")]
url = parts[0]
lat = lon = vendor = loc = None
if len(parts) > 1 and "," in parts[1]:
try:
la, lo = parts[1].split(",", 1)
lat, lon = float(la), float(lo)
except ValueError:
pass
if len(parts) > 2 and parts[2]:
vendor = parts[2]
if len(parts) > 3 and parts[3]:
loc = parts[3]
else:
url = m.group(0)
lat = lon = vendor = loc = None
cams.append({
"source_url": url,
"snapshot_url": url,
"discovery_source": source_name,
"location_lat": lat, "location_lon": lon,
"location_name": loc, "vendor": vendor,
})
return cams
def parse_alertwest_json(text: str, source_name: str) -> list[dict]:
"""Parse ALERTWest / ALERTCalifornia getCameraDataByLoc JSON.
Official public JPEG stills (wildfire, DOT, FAA). Skip private + offline.
Image URL formula from their docs:
https://img.cdn.prod.alertwest.com/data/img/{cid}/{yyyy}/{mm}/{dd}/{img}
with yyyy/mm/dd taken from the epoch embedded in the filename.
"""
try:
payload = json.loads(text)
except (json.JSONDecodeError, ValueError):
return []
data = (payload or {}).get("data") or {}
locs = {loc.get("id"): loc for loc in (data.get("locs") or {}).get("data") or []}
cams_in = (data.get("cams") or {}).get("data") or []
epoch_re = re.compile(r"_(\d{10,})_\d+")
out: list[dict] = []
for cam in cams_in:
if cam.get("pv") not in (0, "0", None):
continue
if cam.get("off") not in (0, "0", None):
continue
img = cam.get("img") or ""
cid = cam.get("id")
if not img or cid is None:
continue
m = epoch_re.search(img)
if not m:
continue
try:
dt = datetime.fromtimestamp(int(m.group(1)), timezone.utc)
except (OSError, ValueError, OverflowError):
continue
snap = (
f"https://img.cdn.prod.alertwest.com/data/img/"
f"{cid}/{dt:%Y}/{dt:%m}/{dt:%d}/{img}"
)
# Stable identity (the JPEG filename changes every capture).
ident = f"https://img.cdn.prod.alertwest.com/cam/{cid}"
loc = locs.get(cam.get("lid")) or {}
try:
lat = float(loc["lat"]) if loc.get("lat") is not None else None
lon = float(loc["lon"]) if loc.get("lon") is not None else None
except (TypeError, ValueError):
lat = lon = None
bits = [cam.get("cn"), cam.get("co"), loc.get("st") or cam.get("st")]
name = ", ".join(str(b) for b in bits if b)
out.append({
"source_url": ident,
"snapshot_url": snap,
"discovery_source": source_name,
"location_lat": lat,
"location_lon": lon,
"location_name": name or None,
"vendor": cam.get("pr") or cam.get("cc"),
"device_type": cam.get("cc") or "cctv",
})
return out
def parse_caltrans_json(text: str, source_name: str) -> list[dict]:
"""Parse Caltrans CWWP2 cctvStatus JSON (districts 1–12, same schema).
Skip cameras that are not in service. Store the JPEG still as snapshot_url
(map thumbs) and the HLS playlist as source_url when present. Never RTSP.
"""
try:
payload = json.loads(text)
except (json.JSONDecodeError, ValueError):
return []
rows = payload.get("data") if isinstance(payload, dict) else None
if not isinstance(rows, list):
return []
out: list[dict] = []
for row in rows:
cctv = (row or {}).get("cctv") or row or {}
loc = cctv.get("location") or {}
in_service = str(cctv.get("inService") or "").strip().lower()
if in_service not in ("true", "1", "yes"):
continue
img = ((cctv.get("imageData") or {}).get("static") or {})
jpeg = (img.get("currentImageURL") or img.get("currentImageUrl") or "").strip()
hls = str((cctv.get("imageData") or {}).get("streamingVideoURL") or "").strip()
if hls.lower().startswith("rtsp://") or jpeg.lower().startswith("rtsp://"):
continue
if not jpeg and not hls:
continue
try:
lat = float(loc["latitude"]) if loc.get("latitude") not in (None, "") else None
lon = float(loc["longitude"]) if loc.get("longitude") not in (None, "") else None
except (TypeError, ValueError):
lat = lon = None
bits = [
loc.get("locationName"),
loc.get("route") and f"SR-{loc.get('route')}",
loc.get("nearbyPlace") or loc.get("county"),
]
name = ", ".join(str(b) for b in bits if b)
ident = hls or jpeg
dtype = "hls" if hls else "http"
out.append({
"source_url": ident,
"snapshot_url": jpeg or hls,
"discovery_source": "caltrans",
"location_lat": lat,
"location_lon": lon,
"location_name": name or None,
"vendor": "Caltrans",
"device_type": dtype,
})
return out
# ── UDOT IBI 511 ──────────────────────────────────────────────────────────
# Utah bbox (lat 36.9–42.1, lon -114.2–-108.9). WKT is `POINT (lng lat)`.
_UDOT_IBI_MIN_LAT, _UDOT_IBI_MAX_LAT = 36.9, 42.1
_UDOT_IBI_MIN_LON, _UDOT_IBI_MAX_LON = -114.2, -108.9
_UDOT_WKT_POINT_RE = re.compile(
r"POINT\s*\(\s*(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)\s*\)", re.I,
)
def parse_udot_ibi_page(text: str, source_name: str = "udot") -> list[dict]:
"""Parse one UDOT IBI 511 DataTables camera page (`{"data": [...]}`).
Skips rows whose first image is `blocked` or `disabled`, and drops any
point outside the Utah bbox. The `/map/Cctv/{id}` URL is a stable identity
(always serves the latest frame), so it is stored as both source_url and
snapshot_url — we never scrape frames ourselves.
"""
try:
payload = json.loads(text)
except (json.JSONDecodeError, ValueError):
return []
rows = payload.get("data") if isinstance(payload, dict) else None
if not isinstance(rows, list):
return []
out: list[dict] = []
for row in rows:
if not isinstance(row, dict):
continue
cam_id = row.get("id")
images = row.get("images") or []
if cam_id is None or not images:
continue
img = images[0] or {}
if img.get("blocked") or img.get("disabled"):
continue
lon = lat = None
try:
wkt = (row.get("latLng") or {}).get("geography") or {}
wkt = wkt.get("wellKnownText") or ""
m = _UDOT_WKT_POINT_RE.match(str(wkt).strip())
if m:
lon, lat = float(m.group(1)), float(m.group(2))
except (AttributeError, TypeError, ValueError):
lon = lat = None
if lat is None or lon is None:
continue
if not (_UDOT_IBI_MIN_LAT <= lat <= _UDOT_IBI_MAX_LAT
and _UDOT_IBI_MIN_LON <= lon <= _UDOT_IBI_MAX_LON):
continue
snap = f"{UDOT_IBI_BASE}/map/Cctv/{cam_id}"
roadway, direction, location = (
row.get("roadway"), row.get("direction"), row.get("location"),
)
name = ", ".join(
str(b) for b in (roadway, direction, location)
if b and str(b).strip() and str(b).strip().lower() != "unknown"
) or None
out.append({
"source_url": snap,
"snapshot_url": snap,
"discovery_source": source_name,
"location_lat": lat,
"location_lon": lon,
"location_name": name,
"vendor": "UDOT",
"device_type": "http",
"raw": {
"udot_id": cam_id,
"agency": row.get("source"),
"source_id": row.get("sourceId"),
"roadway": roadway,
"direction": direction,
},
})
return out
# Oregon DOT TripCheck inventory bounding box (approx state extent).
ODOT_BBOX = (41.9, 46.3, -124.6, -116.4) # lat_min, lat_max, lon_min, lon_max
def parse_odot_json(text: str, source_name: str) -> list[dict]:
"""Parse Oregon DOT TripCheck cctvinventory Esri-style JSON.
Store the JPEG still as snapshot_url (map thumbs); never RTSP. Keep only
rows with finite coordinates inside Oregon and a usable filename.
"""
try:
payload = json.loads(text)
except (json.JSONDecodeError, ValueError):
return []
lat_min, lat_max, lon_min, lon_max = ODOT_BBOX
out: list[dict] = []
for feat in payload.get("features") or []:
attrs = (feat or {}).get("attributes") or {}
filename = (attrs.get("filename") or "").strip()
if not filename:
continue
try:
lat = float(attrs.get("latitude"))
lon = float(attrs.get("longitude"))
except (TypeError, ValueError):
continue
if not (math.isfinite(lat) and math.isfinite(lon)):
continue
if not (lat_min <= lat <= lat_max and lon_min <= lon <= lon_max):
continue
jpeg = f"https://tripcheck.com/RoadCams/cams/{filename}"
title = (attrs.get("title") or "").strip()
out.append({
"source_url": jpeg,
"snapshot_url": jpeg,
"discovery_source": "odot",
"location_lat": lat,
"location_lon": lon,
"location_name": title or None,
"vendor": "ODOT",
"device_type": "http",
})
return out
# MDOT MiDrive field extractors (fields carry rendered HTML).
_MDOT_LAT_RE = re.compile(r"lat=(-?\d+(?:\.\d+)?)", re.I)
_MDOT_LON_RE = re.compile(r"lon=(-?\d+(?:\.\d+)?)", re.I)
_MDOT_ID_RE = re.compile(r"[?&]id=(\d+)", re.I)
_MDOT_IMG_RE = re.compile(r'<img[^>]+src=["\']([^"\']+)["\']', re.I)
# Michigan bbox (docs/osiris-ideas.md §3.2): lat 41.6–48.3, lon -90.5–-82.1.
MDOT_LAT_RANGE = (41.6, 48.3)
MDOT_LON_RANGE = (-90.5, -82.1)
def parse_mdot_json(text: str, source_name: str) -> list[dict]:
"""Parse MDOT MiDrive `camera/list` JSON (fields carry rendered HTML).
Coordinates and the stable id live in the `county` field's map link
(`/MiDrive/map?...lat=&lon=&id=`); the `image` field carries an `<img>`
whose src is the JPEG still. Out-of-bbox and coord-less rows are dropped.
"""
try:
payload = json.loads(text)
except (json.JSONDecodeError, ValueError):
return []
if not isinstance(payload, list):
return []
out: list[dict] = []
for row in payload:
if not isinstance(row, dict):
continue
county_html = row.get("county") or ""
m_lat = _MDOT_LAT_RE.search(county_html)
m_lon = _MDOT_LON_RE.search(county_html)
m_id = _MDOT_ID_RE.search(county_html)
if not (m_lat and m_lon and m_id):
continue # missing coordinates / stable id → drop
try:
lat = float(m_lat.group(1))
lon = float(m_lon.group(1))
except ValueError:
continue
if not (MDOT_LAT_RANGE[0] <= lat <= MDOT_LAT_RANGE[1]
and MDOT_LON_RANGE[0] <= lon <= MDOT_LON_RANGE[1]):
continue # out of Michigan bbox → drop
img_m = _MDOT_IMG_RE.search(row.get("image") or "")
if not img_m:
continue
snap = img_m.group(1).strip()
low = snap.lower()
if not (low.startswith("http://") or low.startswith("https://")):
continue
if low.startswith("rtsp"):
continue
cam_id = m_id.group(1)
route = (row.get("route") or "").strip()
loc = (row.get("location") or "").strip().lstrip("@").strip()
county_name = county_html.split("<a", 1)[0].strip()
bits = [
f"{route} @ {loc}" if (route and loc) else (route or loc or None),
county_name or None,
]
name = ", ".join(b for b in bits if b) or None
out.append({
"source_url": f"https://mdotjboss.state.mi.us/MiDrive/camera/{cam_id}",
"snapshot_url": snap,
"discovery_source": "mdot",
"location_lat": lat,
"location_lon": lon,
"location_name": name,
"vendor": "MDOT",
"device_type": "http",
})
return out
def parse_live_streams_geojson(text: str, source_name: str) -> list[dict]:
"""Parse willytop8/Live-Environment-Streams GeoJSON.
Only direct, playable URLs: HLS, YouTube, HTTP stills. Skip html_page
feeds that need token extraction or a headless browser.
"""
try:
payload = json.loads(text)
except (json.JSONDecodeError, ValueError):
return []
usable = {"hls", "youtube", "http_image"}
out: list[dict] = []
for feat in payload.get("features") or []:
props = feat.get("properties") or {}
ut = (props.get("url_type") or "").lower()
if ut not in usable:
continue
if props.get("source_url_requires"):
continue
url = (props.get("url") or "").strip()
if not url:
continue
coords = (feat.get("geometry") or {}).get("coordinates") or []
lon = lat = None
if len(coords) >= 2:
try:
lon, lat = float(coords[0]), float(coords[1])
except (TypeError, ValueError):
lon = lat = None
dtype = "ip-cam" if ut == "http_image" else ut
out.append({
"source_url": url,
"snapshot_url": url,
"discovery_source": source_name,
"location_lat": lat,
"location_lon": lon,
"location_name": props.get("display_name") or props.get("name"),
"vendor": props.get("source_family"),
"device_type": dtype,
})
return out
def parse_directory_html(html: str, base_url: str, source_name: str) -> list[dict]:
"""Generic Insecam-style directory parser."""
cams = []
imgs = _IMG_RE.findall(html)
for m in _LATLON_RE.finditer(html):
lat, lon = float(m.group(1)), float(m.group(2))
# nearest img tag after the match → best-effort snapshot endpoint
tail = html[m.end(): m.end() + 800]
img_m = _IMG_RE.search(tail)
snap = img_m.group(1) if img_m else (imgs[0] if imgs else None)
if snap and snap.startswith("/"):
from urllib.parse import urljoin
snap = urljoin(base_url, snap)
cams.append({
"source_url": base_url,
"snapshot_url": snap,
"discovery_source": source_name,
"location_lat": lat, "location_lon": lon,
"location_name": None, "vendor": None,
})
return cams
# ── Batch IP geolocation (ip-api.com — free, 100 IPs per batch call) ───────
IPAPI_BATCH_URL = "http://ip-api.com/batch"
IPAPI_BATCH_SIZE = 100
async def geolocate_ips(ips: list[str]) -> dict[str, tuple[float, float]]:
"""Resolve public IPs → (lat, lon). Unresolvable IPs are simply absent."""
out: dict[str, tuple[float, float]] = {}
async with httpx.AsyncClient(timeout=15) as c:
for i in range(0, len(ips), IPAPI_BATCH_SIZE):
chunk = ips[i: i + IPAPI_BATCH_SIZE]
try:
fields = "status,country,city,lat,lon,query"
r = await c.post(IPAPI_BATCH_URL, json=[
{"query": ip, "fields": fields} for ip in chunk
])
r.raise_for_status()
for row in r.json():
if (row.get("status") == "success"
and row.get("lat") is not None):
out[row["query"]] = (
float(row["lat"]), float(row["lon"]))
except Exception: # noqa: BLE001
logger.warning("ip-api batch failed", exc_info=True)
if i + IPAPI_BATCH_SIZE < len(ips):
await asyncio.sleep(2) # stay well under the free rate limit
return out
async def scrape_source(client: RateLimitedClient, geo: Geocoder,
src_url: str) -> list[dict]:
"""Fetch one source and return normalized camera dicts (public only)."""
try:
resp = await client.get(src_url)
resp.raise_for_status()
except Exception: # noqa: BLE001
logger.exception("failed to fetch source %s", src_url)
return []
name = urlparse(src_url).netloc
ctype = resp.headers.get("content-type", "")
body = resp.text
if "cwwp2.dot.ca.gov" in src_url or "cctvStatus" in src_url:
cams = parse_caltrans_json(body, name)
elif "cctvinventory" in src_url or "tripcheck.com" in src_url:
cams = parse_odot_json(body, name)
elif "mdotjboss.state.mi.us" in src_url or "/MiDrive/camera/list" in src_url:
cams = parse_mdot_json(body, name)
elif ("getCameraDataByLoc" in src_url
or ("json" in ctype and '"locs"' in body[:4000] and '"cams"' in body[:8000])):
cams = parse_alertwest_json(body, name)
elif (src_url.endswith(".geojson") or src_url.endswith("/streams.geojson")
or '"FeatureCollection"' in body[:400]):
cams = parse_live_streams_geojson(body, name)
elif "html" in ctype:
cams = parse_directory_html(body, str(resp.url), name)
else:
cams = parse_plain_list(body, name)
out: list[dict] = []
seen_in_batch: set[str] = set()
# Batch-geolocate coordinate-less camera hosts via ip-api (one call per
# 100 IPs) instead of dropping them — raw-IP lists have no embedded coords.
need_geo: dict[str, str] = {}
for cam in cams[:CAMERA_MAX_PER_SOURCE]:
url = cam["source_url"]
h = url_hash(url)
if h in seen_in_batch:
continue
seen_in_batch.add(h)
if not is_public_url(url):
continue
if (cam["location_lat"] is None and cam["location_name"] is None):
host = urlparse(url).hostname or ""
try:
ipaddress.ip_address(host)
need_geo.setdefault(host, url)
except ValueError:
pass # hostname-only: Nominatim fallback below handles it
geo_by_ip = await geolocate_ips(list(need_geo)) if need_geo else {}
for cam in cams:
if url_hash(cam["source_url"]) not in seen_in_batch:
continue # didn't survive dedupe/public-range filtering above
if cam["location_lat"] is None and cam["location_name"]:
cam["location_lat"], cam["location_lon"] = await geo.geocode(
cam["location_name"])
if (cam["location_lat"] is None and cam["location_lon"] is None):
host = urlparse(cam["source_url"]).hostname or ""
coords = geo_by_ip.get(host)
if coords is None:
continue # map display requires coordinates
cam["location_lat"], cam["location_lon"] = coords
cam["location_name"] = f"{host} (IP-geo)"
cam.setdefault("vendor", None)
if not cam.get("vendor"):
cam["vendor"] = _vendor_from_url(cam["snapshot_url"] or cam["source_url"])
if not cam.get("device_type"):
cam["device_type"] = (
"rtsp" if (cam["snapshot_url"] or "").startswith("rtsp") else "ip-cam"
)
cam.setdefault("raw", {"discovered_via": src_url})
out.append(cam)
logger.info("source %s yielded %d public cameras", src_url, len(out))
return out
# ── UDOT IBI 511 paginated fetcher ────────────────────────────────────────
async def scrape_udot_ibi(client: RateLimitedClient) -> list[dict]:
"""Page through the UDOT IBI 511 DataTables endpoint and normalize.
POSTs `start`/`length` form fields (server caps at 100 rows/page), walking
pages until `recordsTotal` is exhausted or UDOT_IBI_MAX_PAGES is hit.
"""
out: list[dict] = []
seen: set[str] = set()
start = 0
for _ in range(UDOT_IBI_MAX_PAGES):
try:
resp = await client.post(
UDOT_IBI_URL,
data={
"start": str(start),
"length": str(UDOT_IBI_PAGE_SIZE),
"lang": "en-US",
},
headers={"X-Requested-With": "XMLHttpRequest"},
)
resp.raise_for_status()
body = resp.text
except Exception: # noqa: BLE001
logger.exception("failed to fetch UDOT IBI page start=%d", start)
break
try:
payload = json.loads(body)
except ValueError:
logger.warning("UDOT IBI non-JSON response at start=%d", start)
break
total = int(payload.get("recordsTotal") or 0)
rows = payload.get("data") or []
if not isinstance(rows, list) or not rows:
break
for cam in parse_udot_ibi_page(body, "udot"):
if cam["source_url"] in seen:
continue
seen.add(cam["source_url"])
out.append(cam)
if start + len(rows) >= total:
break
start += len(rows)
logger.info("UDOT IBI yielded %d cameras", len(out))
return out
# ── Persistence ────────────────────────────────────────────────────────────
async def upsert_cameras(cams: list[dict]) -> int:
"""Insert-or-update cameras keyed by url_hash. Returns rows written."""
now = datetime.now(timezone.utc)
written = 0
async with async_session() as session:
for cam in cams:
values = {
"url_hash": url_hash(cam["source_url"]),
"source_url": cam["source_url"],
"snapshot_url": cam.get("snapshot_url"),
"discovery_source": cam["discovery_source"],
"location_lat": cam.get("location_lat"),
"location_lon": cam.get("location_lon"),
"location_name": cam.get("location_name"),
"vendor": cam.get("vendor"),
"device_type": cam.get("device_type"),
"last_seen": now,
"raw": cam.get("raw"),
}
from sqlalchemy.dialects.postgresql import insert as pg_insert
stmt = pg_insert(cameras).values(**values)
stmt = stmt.on_conflict_do_update(
index_elements=[cameras.c.url_hash],
set_={
"last_seen": now,
"snapshot_url": values["snapshot_url"],
"location_lat": values["location_lat"],
"location_lon": values["location_lon"],
"location_name": values["location_name"],
"vendor": values["vendor"],
"device_type": values["device_type"],
"raw": values["raw"],
},
)
await session.execute(stmt)
written += 1
await session.commit()
return written
# ── Cycle driver ───────────────────────────────────────────────────────────
async def run_cycle() -> int:
client = RateLimitedClient()
geo = Geocoder()
total = 0
try:
results = await asyncio.gather(
*(scrape_source(client, geo, s) for s in CAMERA_SOURCE_URLS),
scrape_udot_ibi(client),
return_exceptions=True,
)
all_cams: list[dict] = []
for r in results:
if isinstance(r, BaseException):
logger.error("scrape task failed: %s", r)
else:
all_cams.extend(r)
if all_cams:
total = await upsert_cameras(all_cams)
finally:
await client.aclose()
logger.info("camera cycle complete: %d cameras stored", total)
return total

View file

@ -1,62 +0,0 @@
"""Static chokepoint preset catalog — one-tap fly-to targets for the map.
Pure data, no upstream calls and no VesselAPI quota spend. ``vesselapi`` is
``True`` only for Hormuz (the single box the VesselAPI poller already covers);
every other strait is AISStream-only until a human later spends quota. Never
call VesselAPI from here.
Bounding boxes are ``minlat,minlon,maxlat,maxlon`` (VesselAPI order) and each
stays within the ``|dLat|+|dLon| <= 4`` span rule enforced by
``vesselapi.validate_bbox_span``.
"""
from __future__ import annotations
# id → preset. ``center`` is ``[lat, lon]`` for Leaflet ``setView``.
_CHOKEPOINTS: tuple[dict, ...] = (
{
"id": "hormuz",
"title": "Strait of Hormuz",
"bbox": "25.5,55.4,27.3,57.2",
"center": [26.4, 56.5],
"zoom": 9,
"vesselapi": True,
},
{
"id": "bab_el_mandeb",
"title": "Bab el-Mandeb",
"bbox": "12.0,42.8,13.5,44.3",
"center": [12.7, 43.4],
"zoom": 9,
"vesselapi": False,
},
{
"id": "suez",
"title": "Suez / N. Red Sea",
"bbox": "29.5,32.0,31.0,33.5",
"center": [30.0,32.5],
"zoom": 9,
"vesselapi": False,
},
{
"id": "malacca",
"title": "Malacca / Singapore",
"bbox": "1.0,103.0,2.5,104.5",
"center": [1.3, 103.8],
"zoom": 9,
"vesselapi": False,
},
{
"id": "taiwan",
"title": "Taiwan Strait",
"bbox": "23.5,119.0,25.0,120.5",
"center": [24.2, 119.8],
"zoom": 9,
"vesselapi": False,
},
)
def chokepoints() -> list[dict]:
"""Return a fresh copy of the catalog (callers must not mutate the source)."""
return [dict(p) for p in _CHOKEPOINTS]

View file

@ -1,118 +0,0 @@
"""OSINT Dashboard — centralized configuration (12-factor, env-driven).
All infrastructure endpoints are read from the environment with
container-friendly defaults. No secrets, hostnames, or cluster-specific
addresses are hardcoded anywhere in the codebase.
Override per environment via environment variables (docker-compose,
k8s ConfigMap/Secret, or systemd):
DB_USER, DB_PASSWORD, DB_HOST, DB_PORT, DB_NAME
NATS_URL
MINIO_ENDPOINT, MINIO_ACCESS_KEY, MINIO_SECRET_KEY, MINIO_SECURE
"""
from __future__ import annotations
import os
from urllib.parse import quote_plus
# ── PostgreSQL ────────────────────────────────────────────────────────────
# Defaults assume docker-compose/k8s service names. Override for your stack.
DB_USER = os.getenv("DB_USER", "osint")
DB_PASSWORD = os.getenv("DB_PASSWORD", "")
DB_HOST = os.getenv("DB_HOST", "postgres")
DB_PORT = os.getenv("DB_PORT", "5432")
DB_NAME = os.getenv("DB_NAME", "osint_data")
# Async SQLAlchemy URL. Password is URL-encoded so special chars are safe.
DATABASE_URL = (
f"postgresql+asyncpg://"
f"{DB_USER}:{quote_plus(DB_PASSWORD)}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
)
# ── NATS JetStream ─────────────────────────────────────────────────────────
NATS_URL = os.getenv("NATS_URL", "nats://nats:4222")
# ── MinIO (document storage) ────────────────────────────────────────────────
MINIO_ENDPOINT = os.getenv("MINIO_ENDPOINT", "minio:9000")
MINIO_ACCESS_KEY = os.getenv("MINIO_ACCESS_KEY", "")
MINIO_SECRET_KEY = os.getenv("MINIO_SECRET_KEY", "")
# "false" / "0" / "no" (case-insensitive) → plain HTTP (e.g. local compose).
MINIO_SECURE = os.getenv("MINIO_SECURE", "false").lower() not in ("false", "0", "no")
# ── NASA FIRMS (active fire / hotspot ingest) ───────────────────────────────
# MAP_KEY is free; obtain one at https://firms.modaps.eosdis.nasa.gov/api/map_key_info/
# and set FIRMS_MAP_KEY in .env. Until it is set, the fire ingestor logs a
# warning and stays idle (no crash).
FIRMS_MAP_KEY = os.getenv("FIRMS_MAP_KEY", "")
# NRT VIIRS S-NPP active fire/hotspot detection (375m).
# NASA stops Suomi NPP product delivery on 2026-11-01 — default to NOAA-20.
FIRMS_DATASET = os.getenv("FIRMS_DATASET", "VIIRS_NOAA20_NRT")
# Area bounding box as "minlon,minlat,maxlon,maxlat". Default covers most of
# the inhabited globe; narrow it (e.g. CONUS "-125,24,-66,50") to shrink
# payloads and the Postgres write volume.
FIRMS_BBOX = os.getenv("FIRMS_BBOX", "-180,-60,180,75")
# Poll cadence in seconds. FIRMS NRT updates every ~5-10 min; 900 = 15 min.
FIRMS_INTERVAL = int(os.getenv("FIRMS_INTERVAL", "900"))
# Day range for the area-CSV request. FIRMS accepts [1..5] days of NRT
# detections; the API 400s when this parameter is omitted. Keep >=2: at
# some hours "1" returns zero detections due to NRT data latency.
FIRMS_DAYS = int(os.getenv("FIRMS_DAYS", "2"))
# Outbound HTTP timeout for the FIRMS CSV download.
FIRMS_TIMEOUT = float(os.getenv("FIRMS_TIMEOUT", "60"))
# Comma-separated FIRMS products to dual-write. S-NPP delivery ends 2026-11-01;
# default to NOAA-20 + NOAA-21 NRT. FIRMS_DATASET is still honored when
# FIRMS_DATASETS is unset (empty string means "use FIRMS_DATASET only").
_FIRMS_DATASETS_RAW = os.getenv("FIRMS_DATASETS", "VIIRS_NOAA20_NRT,VIIRS_NOAA21_NRT")
FIRMS_DATASETS = [d.strip() for d in _FIRMS_DATASETS_RAW.split(",") if d.strip()] or [FIRMS_DATASET]
# Identifying User-Agent for NWS / Amtraker / Nominatim (mandatory on some APIs).
OSINT_USER_AGENT = os.getenv(
"OSINT_USER_AGENT", "osint-dashboard/1.0 (self-hosted; [email protected])"
)
# Nominatim reverse (GET /api/place). Camera scraper has its own copy in camera_config.
NOMINATIM_URL = os.getenv("NOMINATIM_URL", "https://nominatim.openstreetmap.org")
NOMINATIM_MIN_INTERVAL = float(os.getenv("NOMINATIM_MIN_INTERVAL", "1.0"))
# Self-hosted TiTiler (warps Sentinel-1 signed COGs into XYZ tiles on the Pi).
# TITILER_PUBLIC_BASE is the same-origin path prefix the browser hits through
# the osint.rpi.local nginx vhost (`location /titiler/` → 127.0.0.1:8001).
# TITILER_INTERNAL_URL is the compose-DNS address, used only for health checks.
TITILER_PUBLIC_BASE = os.getenv("TITILER_PUBLIC_BASE", "/titiler").rstrip("/")
TITILER_INTERNAL_URL = os.getenv("TITILER_INTERNAL_URL", "http://titiler:8000")
# AISStream (server-side WebSocket only). Idle when unset.
AISSTREAM_API_KEY = os.getenv("AISSTREAM_API_KEY", "")
# Bounding box(es) as minlat,minlon,maxlat,maxlon — note lat/lon order (AISStream).
# Default: CONUS coasts + Great Lakes, not the world.
AISSTREAM_BBOX = os.getenv("AISSTREAM_BBOX", "24,-125,50,-66")
# Run the AIS worker inside the dashboard process (default on so vessels work
# without the ingest profile). Set 0 if the ingester owns the only connection.
AISSTREAM_IN_APP = os.getenv("AISSTREAM_IN_APP", "1").lower() in ("1", "true", "yes")
AISSTREAM_IN_INGEST = os.getenv("AISSTREAM_IN_INGEST", "0").lower() in ("1", "true", "yes")
# VesselAPI (quota-capped REST AIS poller — free tier 150 calls/mo).
# AISStream keeps US coasts; VesselAPI fills the Middle East blind spot. The
# poller idles when VESSELAPI_API_KEY is unset (never from GET /api/vessels).
VESSELAPI_API_KEY = os.getenv("VESSELAPI_API_KEY", "")
# Bounding box(es) as minlat,minlon,maxlat,maxlon — note lat/lon order (same as
# AISSTREAM_BBOX). Semicolon-separated for multiple boxes. Default: Strait of
# Hormuz (|dLat|+|dLon| = 3.6 ≤ 4° span cap). VesselAPI 400s any box over 4°.
VESSELAPI_BBOX = os.getenv("VESSELAPI_BBOX", "25.5,55.4,27.3,57.2")
# Poll cadence in seconds. 17280 = 4.8h → 5 polls/day (150/mo free tier).
VESSELAPI_INTERVAL = int(os.getenv("VESSELAPI_INTERVAL", "17280"))
# Local hard cap on successful 2xx calls per UTC day (persisted in Postgres).
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"))

View file

@ -1,168 +0,0 @@
"""Curated OSINT conflict-zone catalog + point-in-bbox event counting.
A static, human-curated list of active conflict theatres (war / high /
elevated). Purely descriptive — this is a catalog, not a live feed and not a
scrape of LiveUAMap or any other source. Severity and descriptions are
editorial judgement kept short and factual.
Each zone carries an internal ``bbox`` (``min_lat, min_lon, max_lat, max_lon``)
used only to count pre-existing geocoded news/GDELT/``/api/news/map`` rows that
fall inside it. The bbox is not part of the API response; callers get the
``eventCount`` roll-up instead.
Never call an upstream API from here — event counts come from rows already in
the local database (``events`` with geocoords + ``news_items`` map pins).
"""
from __future__ import annotations
from datetime import datetime
# id → zone. ``lat``/``lon`` is the fly-to anchor; ``bbox`` is the internal
# count window in ``min_lat, min_lon, max_lat, max_lon`` order.
_ZONES: tuple[dict, ...] = (
{
"id": "ukraine",
"label": "Ukraine",
"severity": "war",
"lat": 48.5,
"lon": 31.0,
"description": "Full-scale Russian invasion since 2022; active front lines in the east and south.",
"bbox": (44.3, 22.1, 52.4, 40.2),
},
{
"id": "gaza",
"label": "Gaza",
"severity": "war",
"lat": 31.4,
"lon": 34.4,
"description": "Israel–Hamas war; sustained fighting and a severe humanitarian crisis in the Gaza Strip.",
"bbox": (31.0, 34.1, 31.8, 34.7),
},
{
"id": "sudan",
"label": "Sudan",
"severity": "war",
"lat": 15.5,
"lon": 30.0,
"description": "Civil war between the SAF and RSF since 2023, with mass displacement across the country.",
"bbox": (8.7, 21.8, 22.0, 38.6),
},
{
"id": "myanmar",
"label": "Myanmar",
"severity": "war",
"lat": 21.5,
"lon": 96.0,
"description": "Post-2021 coup conflict pitting the junta against resistance and ethnic armed groups.",
"bbox": (9.5, 92.2, 28.5, 101.2),
},
{
"id": "drc",
"label": "DR Congo",
"severity": "war",
"lat": -1.5,
"lon": 28.0,
"description": "Eastern DRC conflict involving M23 and other armed groups; heavy displacement around Goma.",
"bbox": (-5.0, 26.0, 3.0, 31.0),
},
{
"id": "yemen",
"label": "Yemen",
"severity": "war",
"lat": 15.5,
"lon": 47.5,
"description": "Protracted Houthi–government/coalition war with one of the world's worst humanitarian emergencies.",
"bbox": (12.6, 42.5, 19.0, 54.0),
},
{
"id": "syria",
"label": "Syria",
"severity": "war",
"lat": 34.5,
"lon": 38.5,
"description": "Multi-sided civil war; government, opposition, and external actors continue to engage.",
"bbox": (32.3, 35.7, 37.3, 42.4),
},
{
"id": "lebanon",
"label": "Lebanon",
"severity": "high",
"lat": 33.9,
"lon": 35.9,
"description": "Israel–Hezbollah hostilities with periodic escalation along the southern border.",
"bbox": (33.0, 35.0, 34.7, 36.6),
},
{
"id": "sahel",
"label": "Sahel",
"severity": "high",
"lat": 14.5,
"lon": 0.0,
"description": "Jihadist insurgencies across Mali, Burkina Faso, and Niger destabilising the central Sahel.",
"bbox": (10.0, -10.0, 20.0, 12.0),
},
{
"id": "somalia",
"label": "Somalia",
"severity": "high",
"lat": 6.0,
"lon": 45.0,
"description": "Al-Shabaab insurgency against the federal government and security forces.",
"bbox": (-2.0, 41.0, 12.0, 51.5),
},
{
"id": "red_sea",
"label": "Red Sea",
"severity": "high",
"lat": 18.0,
"lon": 40.0,
"description": "Houthi attacks on commercial shipping transiting the Red Sea corridor.",
"bbox": (12.0, 34.0, 22.0, 44.0),
},
{
"id": "taiwan_strait",
"label": "Taiwan Strait",
"severity": "elevated",
"lat": 24.5,
"lon": 119.5,
"description": "Heightened military standoff between China and Taiwan, including deterrence patrols.",
"bbox": (21.9, 117.0, 26.5, 122.0),
},
{
"id": "korean_dmz",
"label": "Korean DMZ",
"severity": "elevated",
"lat": 38.3,
"lon": 127.0,
"description": "Heavily fortified inter-Korean border with periodic tensions and military drills.",
"bbox": (37.5, 126.0, 39.0, 128.5),
},
)
SEVERITIES: frozenset[str] = frozenset({"war", "high", "elevated"})
def conflict_zones() -> list[dict]:
"""Return a fresh shallow copy of the catalog (callers must not mutate)."""
return [dict(z) for z in _ZONES]
def zone_event_stats(
points: list[tuple[float, float, datetime | None]],
bbox: tuple[float, float, float, float],
) -> tuple[int, datetime | None]:
"""Count points inside ``bbox`` and return (count, latest timestamp).
``points`` is an iterable of ``(lat, lon, ts)``; ``ts`` may be ``None``.
``bbox`` is ``(min_lat, min_lon, max_lat, max_lon)``.
"""
min_lat, min_lon, max_lat, max_lon = bbox
count = 0
latest: datetime | None = None
for lat, lon, ts in points:
if min_lat <= lat <= max_lat and min_lon <= lon <= max_lon:
count += 1
if ts is not None and (latest is None or ts > latest):
latest = ts
return count, latest

View file

@ -1,32 +0,0 @@
import os
from sqlalchemy import MetaData, event, text
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.pool import NullPool
from config import DATABASE_URL
# Pooled connections are bound to the event loop they were created on. Long-lived
# servers (uvicorn, the ingester) want a pool; short-lived / test processes that
# open a fresh event loop per unit (asyncio.run, pytest) must not reuse pooled
# connections across loops, so allow a NullPool (new connection per session).
_NULL_POOL = os.getenv("DB_NULL_POOL", "").lower() in ("1", "true", "yes")
engine = create_async_engine(
DATABASE_URL,
echo=False,
**({"poolclass": NullPool} if _NULL_POOL else
{"pool_size": 5, "max_overflow": 10, "pool_recycle": 300}),
)
async_session = async_sessionmaker(
engine, class_=AsyncSession, expire_on_commit=False
)
metadata = MetaData()
async def init_extensions():
"""Initialize PostGIS and TimescaleDB extensions on first connection."""
async with engine.connect() as conn:
await conn.execute(text("CREATE EXTENSION IF NOT EXISTS postgis"))
await conn.execute(text("CREATE EXTENSION IF NOT EXISTS timescaledb"))
await conn.commit()

View file

@ -1,12 +0,0 @@
#!/usr/bin/env bash
# App entrypoint: apply migrations, then launch the API.
set -e
cd /app
echo "[entrypoint] running migrations..."
# `heads` (plural): parallel PRs can fork the chain (005_phase2 + 005_news_items).
# `upgrade head` then exits 255 and crash-loops the container.
alembic upgrade heads
echo "[entrypoint] starting uvicorn..."
exec uvicorn app.main:app --host 0.0.0.0 --port 8000

View file

@ -1,186 +0,0 @@
"""Flag firefighting ADS-B aircraft within 20 miles of an active fire."""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
from uuid import uuid4
from sqlalchemy import text
from database import async_session
from live_layers import _haversine_km
RADIUS_MILES = 20.0
RADIUS_KM = RADIUS_MILES * 1.609344
_recent: dict[tuple[str, str], datetime] = {}
_COOLDOWN = timedelta(minutes=5)
# ICAO type designators commonly used on wildfire air tankers, scoopers,
# helitack, and air-attack platforms. Uppercase; compared case-insensitively.
FIREFIGHTER_ICAO = frozenset({
"AT802", "AT8T", "AT8P", "AT8B",
"C130", "C30J", "C130J",
"DC10", "MD10", "MD11", "MD87",
"B737", "B38M",
"CL2T", "CL215", "CL415", "CL5T",
"S64", "SK64",
"UH1", "UH1Y", "UH60", "H60", "S70",
"B412", "B212", "B205",
"AS50", "AS350", "A119", "A109",
"B350", "BE20",
"OV10",
"RJ85", "RJ1H", "B461", "B462", "B463",
"PC12",
"TBM7", "TBM8", "TBM9",
"C208",
"DH8D", "Q400",
})
def _icao(marker: dict) -> str:
extra = marker.get("extra") or {}
return str(extra.get("type") or extra.get("t") or "").strip().upper()
def is_firefighter(marker: dict) -> bool:
return _icao(marker) in FIREFIGHTER_ICAO
def _haversine_mi(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
return _haversine_km(lat1, lon1, lat2, lon2) / 1.609344
def correlate_aircraft_to_fires(
fires: list[dict],
aircraft: list[dict],
radius_mi: float = RADIUS_MILES,
) -> list[dict]:
hits: list[dict] = []
for fire in fires:
flat, flon = fire.get("lat"), fire.get("lon")
if flat is None or flon is None:
continue
fid = str(fire.get("id") or fire.get("label") or "fire")
for ac in aircraft:
if not is_firefighter(ac):
continue
alat, alon = ac.get("lat"), ac.get("lon")
if alat is None or alon is None:
continue
dist = _haversine_mi(float(flat), float(flon), float(alat), float(alon))
if dist > radius_mi:
continue
hits.append({
"fire_id": fid,
"fire_lat": float(flat),
"fire_lon": float(flon),
"aircraft_hex": str(ac.get("id")),
"aircraft_type": _icao(ac),
"aircraft_lat": float(alat),
"aircraft_lon": float(alon),
"distance_mi": round(dist, 2),
"label": ac.get("label") or ac.get("id"),
})
return hits
async def persist_hits(hits: list[dict], seen_at: datetime | None = None) -> int:
if not hits:
return 0
ts = seen_at or datetime.now(timezone.utc)
n = 0
async with async_session() as session:
for h in hits:
try:
await session.execute(
text(
"""
INSERT INTO fire_aircraft_hits
(id, fire_id, fire_lat, fire_lon,
aircraft_hex, aircraft_type, aircraft_lat, aircraft_lon,
distance_mi, seen_at)
VALUES (
CAST(:id AS uuid), :fire_id, :fire_lat, :fire_lon,
:aircraft_hex, :aircraft_type, :aircraft_lat, :aircraft_lon,
:distance_mi, :seen_at
)
ON CONFLICT (fire_id, aircraft_hex, seen_at) DO NOTHING
"""
),
{
"id": str(uuid4()),
"fire_id": h["fire_id"],
"fire_lat": h["fire_lat"],
"fire_lon": h["fire_lon"],
"aircraft_hex": h["aircraft_hex"],
"aircraft_type": h["aircraft_type"],
"aircraft_lat": h["aircraft_lat"],
"aircraft_lon": h["aircraft_lon"],
"distance_mi": h["distance_mi"],
"seen_at": ts.replace(microsecond=0),
},
)
n += 1
except Exception:
continue
try:
await session.commit()
except Exception:
return 0
return n
async def recent_hits(limit: int = 200) -> list[dict]:
try:
async with async_session() as session:
rows = (await session.execute(
text(
"""
SELECT fire_id, fire_lat, fire_lon,
aircraft_hex, aircraft_type, aircraft_lat, aircraft_lon,
distance_mi, seen_at
FROM fire_aircraft_hits
ORDER BY seen_at DESC
LIMIT :limit
"""
),
{"limit": limit},
)).mappings().all()
out = []
for r in rows:
item = dict(r)
if item.get("seen_at") is not None:
item["seen_at"] = item["seen_at"].isoformat()
out.append(item)
return out
except Exception:
return []
async def correlate_and_notify(fires: list[dict], aircraft: list[dict]) -> list[dict]:
hits = correlate_aircraft_to_fires(fires, aircraft)
if not hits:
return []
now = datetime.now(timezone.utc)
fresh = []
for h in hits:
key = (h["fire_id"], h["aircraft_hex"])
prev = _recent.get(key)
if prev is not None and now - prev < _COOLDOWN:
continue
_recent[key] = now
fresh.append(h)
if not fresh:
return []
await persist_hits(fresh, seen_at=now)
from ws_manager import manager
for h in fresh:
body = {**h, "seen_at": now.isoformat()}
await manager.publish_point(
"fire_aircraft", body, lat=h["aircraft_lat"], lon=h["aircraft_lon"],
)
await manager.publish_point(
"fire_aircraft", body, lat=h["fire_lat"], lon=h["fire_lon"],
)
return fresh

View file

@ -1,256 +0,0 @@
"""NASA FIRMS active fire / hotspot ingestor.
Fetches the VIIRS active-fire detection CSV for an area from NASA FIRMS and
publishes each hotspot to NATS JetStream on the ``events.fire`` subject. The
NATS consumer (app/ingestor.py) routes those messages to the ``fires``
TimescaleDB hypertable, deduped by the natural key (lat, lon, acq_time,
satellite).
Zero-cost data: the FIRMS MAP_KEY is free (https://firms.modaps.eosdis.nasa.gov/api/map_key_info/)
and the CSV area endpoint is unlimited for personal/research use.
Endpoint (documented at https://firms.modaps.eosdis.nasa.gov/api/area/csv/):
https://firms.modaps.eosdis.nasa.gov/api/area/csv/{MAP_KEY}/{DATASET}/{bbox}
bbox = "minlon,minlat,maxlon,maxlat" (e.g. "-125,24,-66,50")
CSV columns (VIIRS): latitude, longitude, bright_ti4, scan, track, acq_date,
acq_time, satellite, instrument, confidence, version, bright_ti5, frp, daynight.
``acq_time`` is an integer HHMM in UTC (seconds are 0); ``acq_date`` is the
UTC date (YYYY-MM-DD).
"""
from __future__ import annotations
import csv
import hashlib
import io
import json
import logging
import os
from datetime import datetime, timezone
import httpx
import nats
from config import (
FIRMS_BBOX,
FIRMS_DATASET,
FIRMS_DATASETS,
FIRMS_DAYS,
FIRMS_TIMEOUT,
NATS_URL,
)
from keystore import get_api_key
from upstream_cache import firms_cache
logger = logging.getLogger("osint.firms")
# In-process poll state: skip byte-identical CSVs, persist only new hotspots.
# Survives the 15-minute loop; one full ON CONFLICT after process start.
_csv_digest: dict[tuple, bytes] = {}
_seen_ids: dict[tuple, set[int]] = {}
# ── FIRMS API ─────────────────────────────────────────────────────────────
FIRMS_AREA_CSV = (
"https://firms.modaps.eosdis.nasa.gov/api/area/csv/{key}/{dataset}/{bbox}/{days}"
)
# The canonical VIIRS CSV header FIRMS returns. Used to (a) locate the real
# header row if FIRMS ever prepends a legend line and (b) validate a download.
FIRMS_CSV_COLUMNS = (
"latitude", "longitude", "bright_ti4", "scan", "track", "acq_date",
"acq_time", "satellite", "instrument", "confidence", "version",
"bright_ti5", "frp", "daynight",
)
def _to_float(value: object) -> float | None:
"""Best-effort float conversion; returns None on empty/garbage values."""
if value is None:
return None
try:
return float(value)
except (ValueError, TypeError):
return None
def normalize_acq_time(acq_date: object, acq_time: object) -> datetime | None:
"""Combine FIRMS acq_date + acq_time into a timezone-aware UTC datetime.
acq_date is 'YYYY-MM-DD'; acq_time is an integer HHMM in UTC with seconds
truncated. Returns None when the values can't be parsed (dropped).
"""
if not acq_date or acq_time is None or acq_time == "":
return None
try:
hhmm = str(int(acq_time)).zfill(4)
return datetime.strptime(
f"{acq_date} {hhmm}", "%Y-%m-%d %H%M"
).replace(tzinfo=timezone.utc)
except (ValueError, TypeError):
return None
def _hotspot_id(lat: float, lon: float, acq_iso: str, satellite: str) -> int:
return hash((round(lat, 5), round(lon, 5), acq_iso, satellite))
def parse_firms_csv_delta(
text: str, skip_ids: set[int] | None = None,
) -> tuple[list[dict], set[int]]:
"""Parse FIRMS CSV; optionally drop hotspots already seen this process.
Returns (new_or_all_points, ids_for_every_valid_row). Streaming — does not
materialize the raw CSV as a list of lists.
"""
reader = csv.reader(io.StringIO(text))
header = None
for row in reader:
if row and row[0].strip().lower() == "latitude" and len(row) >= 4:
header = [c.strip().lower() for c in row]
break
if not header or "latitude" not in header or "longitude" not in header:
logger.warning(
"FIRMS payload does not look like a hotspot CSV (first row: %r)",
(header or [])[:6],
)
return [], set()
points: list[dict] = []
ids: set[int] = set()
for row in reader:
if len(row) < len(header):
continue
rec = dict(zip(header, row))
lat = _to_float(rec.get("latitude"))
lon = _to_float(rec.get("longitude"))
if lat is None or lon is None:
continue
acq_time = normalize_acq_time(rec.get("acq_date"), rec.get("acq_time"))
if acq_time is None:
continue
sat = str(rec.get("satellite") or "").strip()
acq_iso = acq_time.isoformat()
hid = _hotspot_id(lat, lon, acq_iso, sat)
ids.add(hid)
if skip_ids is not None and hid in skip_ids:
continue
points.append({
"latitude": lat,
"longitude": lon,
"brightness": _to_float(rec.get("bright_ti4")),
"confidence": str(rec.get("confidence") or "").strip(),
"acq_time": acq_iso,
"satellite": sat,
"instrument": str(rec.get("instrument") or "").strip(),
"bright_ti5": _to_float(rec.get("bright_ti5")),
"frp": _to_float(rec.get("frp")),
"daynight": str(rec.get("daynight") or "").strip(),
"scan": _to_float(rec.get("scan")),
"track": _to_float(rec.get("track")),
"version": str(rec.get("version") or "").strip(),
})
return points, ids
def parse_firms_csv(text: str) -> list[dict]:
"""Parse a FIRMS area CSV payload into normalized fire messages.
Returns one dict per hotspot with the fields stored in the ``fires`` table
(acq_time already combined into a UTC ISO timestamp). Rows that don't look
like valid VIIRS detections are skipped rather than failing the whole poll.
"""
points, _ids = parse_firms_csv_delta(text)
return points
async def publish_fire_batch(points: list[dict]) -> int:
"""Publish a batch of hotspot messages to NATS JetStream in one connection.
Fires are bulk data (thousands of detections per poll), so opening a NATS
connection per message — as the RSS/GDELT path does — would be wasteful.
One connection, one JetStream context, one close, with the batch flushed
before returning so a crash mid-write can't silently drop half a poll.
"""
if not points:
return 0
nc = await nats.connect(NATS_URL)
js = nc.jetstream()
try:
for pt in points:
msg = {"source_type": "fire", **pt}
await js.publish("events.fire", json.dumps(msg).encode())
finally:
await nc.close()
return len(points)
async def persist_hotspots(points: list[dict]) -> int:
"""Write a FIRMS poll to Postgres in one ON CONFLICT batch.
NATS-per-row was 93k commits + geofence/correlation per hotspot.
"""
from ingestor import ingest_fire_rows
return await ingest_fire_rows(points)
async def ingest_fires(bbox: str | None = None) -> int:
"""Fetch the FIRMS hotspot CSV for an area and publish it to NATS.
Returns the number of hotspot messages published. Idle (0) and a logged
warning when FIRMS_MAP_KEY is not set, so the ingester keeps running for
the other sources.
"""
# Key resolution: env var first (12-factor), then the shared Postgres
# api_keys table so a key saved via the dashboard Keys page is picked up
# on the next poll without a restart.
map_key = os.getenv("FIRMS_MAP_KEY", "") or await get_api_key("FIRMS_MAP_KEY")
if not map_key:
logger.warning(
"FIRMS_MAP_KEY not set — fire ingest disabled. "
"Set it in the dashboard Keys page or .env. "
"Free key: https://firms.modaps.eosdis.nasa.gov/api/map_key_info/"
)
return 0
area = bbox or FIRMS_BBOX
datasets = FIRMS_DATASETS or [FIRMS_DATASET]
total_published = 0
async with httpx.AsyncClient(timeout=FIRMS_TIMEOUT) as client:
for dataset in datasets:
cache_key = (dataset, area, FIRMS_DAYS)
text = firms_cache.get(cache_key)
if text is None:
url = FIRMS_AREA_CSV.format(
key=map_key, dataset=dataset, bbox=area, days=FIRMS_DAYS
)
resp = await client.get(url)
resp.raise_for_status()
text = resp.text
firms_cache[cache_key] = text
# FIRMS returns HTTP 200 with a plain-text error for some failure modes
# (bad key, invalid bbox); surface the first line for debuggability.
if "latitude" not in text.lower()[:4096]:
first_line = text.strip().splitlines()[0][:200] if text.strip() else "(empty)"
logger.warning(
"FIRMS CSV download returned no hotspot data for %s (%s)",
dataset, first_line,
)
continue
poll_key = (dataset, area, FIRMS_DAYS)
digest = hashlib.sha256(text.encode("utf-8", "surrogatepass")).digest()
if _csv_digest.get(poll_key) == digest:
logger.info("FIRMS %s CSV unchanged, skip parse/insert", dataset)
continue
points, ids = parse_firms_csv_delta(text, skip_ids=_seen_ids.get(poll_key))
published = await persist_hotspots(points) if points else 0
_csv_digest[poll_key] = digest
_seen_ids[poll_key] = ids
total_published += published
logger.info(
"FIRMS: fetched %d hotspot(s) for bbox=%s (%s), published %d",
len(ids), area, dataset, published,
)
return total_published

View file

@ -1,844 +0,0 @@
"""Geofences: GeoJSON polygons, ST_Intersects on ingest, WS alerts.
``/api/alerts`` is the dashboard entity/keyword table — geofence hits live
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
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):
raise ValueError("geojson must be an object")
gj = geojson
if gj.get("type") == "Feature":
gj = gj.get("geometry") or {}
if gj.get("type") == "FeatureCollection":
raise ValueError("FeatureCollection is not a single polygon")
if gj.get("type") != "Polygon":
raise ValueError("geojson must be a Polygon")
coords = gj.get("coordinates")
if not isinstance(coords, list) or not coords:
raise ValueError("polygon has no rings")
rings: list[list[list[float]]] = []
for ring in coords:
if not isinstance(ring, list) or len(ring) < 4:
raise ValueError("polygon ring needs ≥4 positions (closed)")
pts = []
for pt in ring:
if not isinstance(pt, (list, tuple)) or len(pt) < 2:
raise ValueError("position must be [lon, lat]")
pts.append([float(pt[0]), float(pt[1])])
rings.append(pts)
return rings
def validate_polygon_geojson(geojson: dict) -> dict:
"""Return a canonical Polygon GeoJSON or raise ValueError."""
rings = _rings_from_geojson(geojson)
return {"type": "Polygon", "coordinates": rings}
def _ring_contains(lon: float, lat: float, ring: list[list[float]]) -> bool:
"""Ray-cast even-odd rule. Ring is [lon, lat] positions."""
inside = False
n = len(ring)
if n < 4:
return False
j = n - 1
for i in range(n):
xi, yi = ring[i][0], ring[i][1]
xj, yj = ring[j][0], ring[j][1]
intersects = ((yi > lat) != (yj > lat)) and (
lon < (xj - xi) * (lat - yi) / ((yj - yi) or 1e-16) + xi
)
if intersects:
inside = not inside
j = i
return inside
def point_in_geojson(lon: float, lat: float, geojson: dict) -> bool:
"""True if (lon, lat) is inside the outer ring and outside holes."""
try:
rings = _rings_from_geojson(geojson)
except (ValueError, TypeError, KeyError):
return False
if not _ring_contains(lon, lat, rings[0]):
return False
for hole in rings[1:]:
if _ring_contains(lon, lat, hole):
return False
return True
def matching_geofences(lon: float, lat: float, fences: list[dict]) -> list[dict]:
hits = []
for fence in fences:
if not fence.get("active", True):
continue
gj = fence.get("geojson") or {}
if point_in_geojson(lon, lat, gj):
hits.append(fence)
return hits
# In-process copy of active fences so ingest does not round-trip Postgres
# on every AIS frame. CRUD endpoints refresh this list.
_cache: list[dict] = []
_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:
rows = (await session.execute(text(
"SELECT id::text, name, geojson, active FROM geofences"
))).mappings().all()
_cache = [
{
"id": r["id"],
"name": r["name"],
"geojson": r["geojson"] if isinstance(r["geojson"], dict)
else json.loads(r["geojson"] or "{}"),
"active": bool(r["active"]),
}
for r in rows
]
return _cache
def cached_fences() -> list[dict]:
return list(_cache)
async def list_geofences() -> list[dict]:
if not _cache:
try:
await refresh_cache()
except Exception:
return []
return cached_fences()
async def create_geofence(name: str, geojson: dict, active: bool = True) -> dict:
polygon = validate_polygon_geojson(geojson)
gid = str(uuid4())
gj = json.dumps(polygon)
async with async_session() as session:
await session.execute(
text(
"""
INSERT INTO geofences (id, name, geojson, geom, active)
VALUES (
:id, :name, CAST(:geojson AS jsonb),
ST_SetSRID(ST_GeomFromGeoJSON(:geojson), 4326),
:active
)
"""
),
{"id": gid, "name": name, "geojson": gj, "active": 1 if active else 0},
)
await session.commit()
row = {"id": gid, "name": name, "geojson": polygon, "active": active}
_cache.append(row)
return row
async def update_geofence(gid: str, *, name: str | None = None,
geojson: dict | None = None,
active: bool | None = None) -> dict | None:
current = next((f for f in _cache if f["id"] == gid), None)
if current is None:
await refresh_cache()
current = next((f for f in _cache if f["id"] == gid), None)
if current is None:
return None
if name is not None:
current["name"] = name
if geojson is not None:
current["geojson"] = validate_polygon_geojson(geojson)
if active is not None:
current["active"] = active
gj = json.dumps(current["geojson"])
async with async_session() as session:
await session.execute(
text(
"""
UPDATE geofences SET
name = :name,
geojson = CAST(:geojson AS jsonb),
geom = ST_SetSRID(ST_GeomFromGeoJSON(:geojson), 4326),
active = :active,
updated_at = now()
WHERE id = CAST(:id AS uuid)
"""
),
{
"id": gid,
"name": current["name"],
"geojson": gj,
"active": 1 if current["active"] else 0,
},
)
await session.commit()
return current
async def delete_geofence(gid: str) -> bool:
async with async_session() as session:
result = await session.execute(
text("DELETE FROM geofences WHERE id = CAST(:id AS uuid)"),
{"id": gid},
)
await session.commit()
_cache[:] = [f for f in _cache if f["id"] != gid]
return bool(result.rowcount)
async def st_intersects(lon: float, lat: float) -> list[dict]:
"""PostGIS ST_Intersects against active geofences.
Falls back to the in-memory GeoJSON test if the DB is unreachable so
ingest never dies because a fence check failed.
"""
try:
async with async_session() as session:
rows = (await session.execute(
text(
"""
SELECT id::text, name, geojson, active
FROM geofences
WHERE active = 1
AND ST_Intersects(
geom,
ST_SetSRID(ST_MakePoint(:lon, :lat), 4326)
)
"""
),
{"lon": lon, "lat": lat},
)).mappings().all()
return [
{
"id": r["id"],
"name": r["name"],
"geojson": r["geojson"] if isinstance(r["geojson"], dict)
else json.loads(r["geojson"] or "{}"),
"active": True,
}
for r in rows
]
except Exception:
return matching_geofences(lon, lat, cached_fences())
async def record_and_notify(
*,
source_kind: str,
entity_id: str,
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
from ws_manager import manager
sent = 0
now = datetime.now(timezone.utc)
fresh = []
for fence in hits:
key = (str(fence["id"]), str(entity_id))
prev = _recent_hits.get(key)
if prev is not None and now - prev < _HIT_COOLDOWN:
continue
_recent_hits[key] = now
fresh.append(fence)
if not fresh:
return 0
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,
"geofence_id": fence["id"],
"geofence_name": fence.get("name"),
"source_kind": source_kind,
"entity_id": str(entity_id),
"lat": lat,
"lon": lon,
"payload": body_payload,
"created_at": now.isoformat(),
}
try:
await session.execute(
text(
"""
INSERT INTO geofence_alerts
(id, geofence_id, source_kind, entity_id, lat, lon, payload)
VALUES (
CAST(:id AS uuid), CAST(:geofence_id AS uuid),
:source_kind, :entity_id, :lat, :lon, CAST(:payload AS jsonb)
)
"""
),
{
"id": aid,
"geofence_id": fence["id"],
"source_kind": source_kind,
"entity_id": str(entity_id),
"lat": lat,
"lon": lon,
"payload": json.dumps(body_payload),
},
)
except Exception:
pass
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:
pass
return sent
async def list_alerts(
*,
geofence_id: str | None = None,
since: datetime | None = None,
until: datetime | None = None,
source_kind: str | None = None,
limit: int = 100,
) -> list[dict]:
"""Filterable hit log. Empty list if the DB is down — never raises."""
where = ["TRUE"]
params: dict[str, Any] = {"limit": int(limit)}
if geofence_id:
where.append("geofence_id = CAST(:geofence_id AS uuid)")
params["geofence_id"] = geofence_id
if since is not None:
where.append("created_at >= :since")
params["since"] = since
if until is not None:
where.append("created_at <= :until")
params["until"] = until
if source_kind:
where.append("source_kind = :source_kind")
params["source_kind"] = source_kind
sql = f"""
SELECT id::text, geofence_id::text, source_kind, entity_id,
lat, lon, payload, created_at
FROM geofence_alerts
WHERE {' AND '.join(where)}
ORDER BY created_at DESC
LIMIT :limit
"""
try:
async with async_session() as session:
rows = (await session.execute(text(sql), params)).mappings().all()
out = []
for r in rows:
item = dict(r)
if item.get("created_at") is not None:
item["created_at"] = item["created_at"].isoformat()
out.append(item)
return out
except Exception:
return []
async def get_geofence(gid: str) -> dict | None:
current = next((f for f in _cache if f["id"] == gid), None)
if current is not None:
return current
try:
await refresh_cache()
except Exception:
return None
return next((f for f in _cache if f["id"] == gid), None)
def _marker_from_track(row) -> dict:
from live_layers import to_marker
extra = {"bucket": row["bucket"].isoformat() if row.get("bucket") else None, "dvr": True}
return to_marker(
row["id"], row["lat"], row["lon"],
heading=row.get("heading"), speed=row.get("speed"),
label=row.get("label") or row["id"],
extra=extra,
)
async def _cagg_inside(gid: str, kind: str, bucket: datetime, limit: int = 2000) -> list[dict]:
table = "aircraft_tracks_1min" if kind == "aircraft" else "vessel_tracks_1min"
id_col = "hex" if kind == "aircraft" else "mmsi"
sql = f"""
SELECT {id_col} AS id, lat, lon, heading, speed, label, bucket
FROM {table}
WHERE bucket = :bucket
AND ST_Intersects(
(SELECT geom FROM geofences WHERE id = CAST(:gid AS uuid)),
ST_SetSRID(ST_MakePoint(lon, lat), 4326)
)
LIMIT :limit
"""
try:
async with async_session() as session:
rows = (await session.execute(
text(sql), {"bucket": bucket, "gid": gid, "limit": limit},
)).mappings().all()
return [
_marker_from_track(r)
for r in rows
if r["lat"] is not None and r["lon"] is not None
]
except Exception:
return []
async def _fires_inside(gid: str, ts: datetime, limit: int = 2000) -> list[dict]:
from tracks import minute_bucket
bucket = minute_bucket(ts)
t1 = bucket + timedelta(minutes=1)
sql = """
SELECT latitude, longitude, brightness, confidence, acq_time, satellite,
instrument, bright_ti5, frp, daynight
FROM fires
WHERE acq_time >= :t0 AND acq_time < :t1
AND ST_Intersects(
(SELECT geom FROM geofences WHERE id = CAST(:gid AS uuid)),
ST_SetSRID(ST_MakePoint(longitude, latitude), 4326)
)
LIMIT :limit
"""
try:
async with async_session() as session:
rows = (await session.execute(
text(sql),
{"t0": bucket, "t1": t1, "gid": gid, "limit": limit},
)).mappings().all()
out = []
for r in rows:
item = dict(r)
if item.get("acq_time") is not None:
item["acq_time"] = item["acq_time"].isoformat()
out.append(item)
return out
except Exception:
return []
async def snapshot_at(gid: str, ts: datetime) -> dict | None:
"""Positions inside the fence at time T. None if the fence is missing.
Does not persist or notify. Empty lists if track/fire queries fail.
"""
fence = await get_geofence(gid)
if fence is None:
return None
from tracks import minute_bucket
bucket = minute_bucket(ts)
aircraft = await _cagg_inside(gid, "aircraft", bucket)
vessels = await _cagg_inside(gid, "vessel", bucket)
fires = await _fires_inside(gid, ts)
return {
"geofence_id": gid,
"timestamp": ts.isoformat(),
"aircraft": aircraft,
"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

View file

@ -1,170 +0,0 @@
"""NASA GIBS basemap catalog + time-domain helper for the OSINT map tab.
GIBS (Global Imagery Browse Services) is what worldview.earthdata.nasa.gov
renders from. Tiles are plain XYZ/WebMercator WMTS rasters, CORS-open
(access-control-allow-origin: *), so the browser can pull them directly —
no tile proxy needed.
Layer metadata is curated here (identifier, display title, tile matrix set,
format, whether it has a Time dimension). Available time windows per layer
come from GIBS' per-layer Domains XML endpoint (tiny), fetched on demand and
cached for a few hours.
Tile URL template (RESTful WMTS):
https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/{layer}/default/{time}/{tms}/{z}/{y}/{x}.{ext}
The {time} path segment is omitted entirely for static layers (no Time dim).
"""
from __future__ import annotations
import asyncio
import re
import time
from datetime import date, datetime, timedelta, timezone
import httpx
GIBS_BASE = "https://gibs.earthdata.nasa.gov/wmts/epsg3857/best"
GIBS_TIMEOUT = 30.0
# ── Curated basemap catalog ────────────────────────────────────────────────
# has_time: True → tile URL includes /default/{time}/; the /api/map/times
# endpoint returns the valid date windows. False → static basemap.
MAP_LAYERS = [
{
"id": "BlueMarble_ShadedRelief_Bathymetry",
"title": "Blue Marble (shaded relief + bathymetry)",
"subtitle": "Static MODIS composite basemap",
"tms": "GoogleMapsCompatible_Level8",
"format": "jpeg",
"has_time": False,
"max_zoom": 8,
},
{
"id": "VIIRS_SNPP_CorrectedReflectance_TrueColor",
"title": "VIIRS S-NPP True Color (daily)",
"subtitle": "Suomi NPP corrected reflectance",
"tms": "GoogleMapsCompatible_Level9",
"format": "jpeg",
"has_time": True,
"max_zoom": 9,
},
{
"id": "MODIS_Terra_CorrectedReflectance_TrueColor",
"title": "MODIS Terra True Color (daily)",
"subtitle": "Terra corrected reflectance",
"tms": "GoogleMapsCompatible_Level9",
"format": "jpeg",
"has_time": True,
"max_zoom": 9,
},
{
"id": "MODIS_Aqua_CorrectedReflectance_TrueColor",
"title": "MODIS Aqua True Color (daily)",
"subtitle": "Aqua corrected reflectance",
"tms": "GoogleMapsCompatible_Level9",
"format": "jpeg",
"has_time": True,
"max_zoom": 9,
},
{
"id": "VIIRS_SNPP_DayNightBand_ENCC",
"title": "VIIRS Night Lights (DNB)",
"subtitle": "Earth at night, enhanced near-constant contrast",
"tms": "GoogleMapsCompatible_Level8",
"format": "png",
"has_time": True,
"max_zoom": 8,
},
]
_LAYER_BY_ID = {l["id"]: l for l in MAP_LAYERS}
# ── Time-domain cache (per layer) ──────────────────────────────────────────
# GIBS Domains XML gives a comma-joined list of ISO ranges: START/END/PERIOD
_DOMAIN_CACHE: dict[str, tuple[float, dict]] = {}
_DOMAIN_TTL = 6 * 3600 # 6h
_HTTPS_LOCK = asyncio.Lock()
# e.g. 2026-07-16/2026-08-24/P1D
_TIME_RANGE_RE = re.compile(
r"^(\d{4}-\d{2}-\d{2})/(\d{4}-\d{2}-\d{2})/(P\d+D|P\d+M|PT\d+H)$"
)
def _parse_time_domain(domain: str) -> dict:
"""Expand a Domains XML <Domain> string into usable date metadata.
Returns {min, max, latest, ranges:[{start,end}]} where ranges keep the
raw GIBS windows so the frontend can warn when a picked date is outside
every window (GIBS still serves nearest-time tiles, but this is honest).
GIBS' published windows include the current UTC day as soon as it starts,
but daily mosaics (MODIS/VIIRS true color, night lights) aren't actually
ingested until hours later — tiles for "today" 404 until then. So we clamp
daily-layer window ends to *yesterday* UTC: 'latest' then always points at
imagery that really exists.
"""
windows = []
min_d, max_d = None, None
# 00:00–~03:00+ UTC the newest full day is always yesterday; use a small
# margin so we never advertise a same-day mosaic that isn't ingested yet.
cutoff = datetime.now(timezone.utc).date() - timedelta(days=1)
for part in domain.split(","):
part = part.strip()
m = _TIME_RANGE_RE.match(part)
if not m:
continue
start = date.fromisoformat(m.group(1))
end = date.fromisoformat(m.group(2))
if m.group(3) == "P1D" and end > cutoff:
end = cutoff
if start > end:
continue # whole window was "not yet ingested" days
windows.append({"start": start.isoformat(), "end": end.isoformat()})
if min_d is None or start < min_d:
min_d = start
if max_d is None or end > max_d:
max_d = end
return {
"min": min_d.isoformat() if min_d else None,
"max": max_d.isoformat() if max_d else None,
"latest": max_d.isoformat() if max_d else None,
"ranges": windows,
}
async def fetch_layer_domain(layer_id: str, tms: str) -> dict:
"""Return parsed time domain for a layer, cached for _DOMAIN_TTL."""
now = time.time()
hit = _DOMAIN_CACHE.get(layer_id)
if hit and now - hit[0] < _DOMAIN_TTL:
return hit[1]
url = (
f"{GIBS_BASE}/1.0.0/{layer_id}/default/{tms}/all/all.xml"
)
# One in-flight request per layer; serialize so a burst of layer switches
# doesn't fan out parallel GIBS hits.
async with _HTTPS_LOCK:
hit = _DOMAIN_CACHE.get(layer_id)
if hit and time.time() - hit[0] < _DOMAIN_TTL:
return hit[1]
async with httpx.AsyncClient(timeout=GIBS_TIMEOUT) as client:
resp = await client.get(url)
resp.raise_for_status()
m = re.search(r"<Domain>([^<]+)</Domain>", resp.text)
if not m:
raise ValueError(f"No time <Domain> in GIBS response for {layer_id}")
parsed = _parse_time_domain(m.group(1))
_DOMAIN_CACHE[layer_id] = (time.time(), parsed)
return parsed
def default_time_for(layer_id: str) -> str | None:
"""Most recent data date for a time-aware layer (best effort, from cache)."""
hit = _DOMAIN_CACHE.get(layer_id)
if not hit:
return None
latest = hit[1].get("latest")
return latest or None

View file

@ -1,46 +0,0 @@
"""CronJob entry point for scheduled ingestion."""
import asyncio
import os
import sys
from pathlib import Path
# Add app dir to path
sys.path.insert(0, str(Path(__file__).parent))
from sources import ingest_rss_feed, ingest_gdelt, ingest_earthquakes
from ingestor import fetch_and_process
INGESTOR_TYPE = os.getenv("INGESTOR_TYPE", "rss")
RSS_URL = os.getenv("RSS_URL", "")
async def main():
print(f"Starting ingester: {INGESTOR_TYPE}")
if INGESTOR_TYPE == "rss":
if not RSS_URL:
print("No RSS_URL set, skipping")
return
count = await ingest_rss_feed(RSS_URL)
print(f"RSS: ingested {count} items")
elif INGESTOR_TYPE == "gdelt":
count = await ingest_gdelt(max_articles=50)
print(f"GDELT: ingested {count} articles")
elif INGESTOR_TYPE == "earthquake":
count = await ingest_earthquakes()
print(f"Earthquakes: ingested {count} events")
elif INGESTOR_TYPE == "nats":
count = await fetch_and_process(batch_size=500)
print(f"NATS: processed {count} messages")
else:
print(f"Unknown ingestor type: {INGESTOR_TYPE}")
sys.exit(1)
if __name__ == "__main__":
asyncio.run(main())

View file

@ -1,303 +0,0 @@
"""NATS JetStream consumer — ingests OSINT events from NATS streams."""
from __future__ import annotations
import json
import logging
import uuid
from datetime import datetime, timezone
import nats
from nats.errors import TimeoutError
from sqlalchemy.dialects.postgresql import insert as pg_insert
from database import async_session
from models import events as events_table
from models import fires as fires_table
from models import event_dedup as event_dedup_table
from config import NATS_URL
from sources import event_dedup_key
logger = logging.getLogger("osint.ingestor")
# asyncpg rejects statements with >32767 bind params. A FIRMS poll is ~90k
# rows × 14 columns. Chunk inserts; still one transaction / one commit.
FIRE_ROW_BIND_PARAMS = 14
FIRE_INSERT_CHUNK = 2000
# NATS connection settings
NATS_URLS = NATS_URL
NATS_STREAM = "events"
NATS_DURABLE = "osint-ingestor"
# ── Active fire / hotspot routing ─────────────────────────────────────────
def _fire_row_from_msg(msg: dict) -> dict | None:
"""Map a NATS fire message to a ``fires`` table row (pre-DB, unit-testable).
Returns None (dropped) when the idempotency key fields — latitude,
longitude, acq_time, satellite — are missing or unparseable.
"""
row = {
"latitude": msg.get("latitude"),
"longitude": msg.get("longitude"),
"brightness": msg.get("brightness"),
"confidence": msg.get("confidence"),
"acq_time": msg.get("acq_time"),
"satellite": msg.get("satellite"),
"instrument": msg.get("instrument"),
"bright_ti5": msg.get("bright_ti5"),
"frp": msg.get("frp"),
"daynight": msg.get("daynight"),
"scan": msg.get("scan"),
"track": msg.get("track"),
"version": msg.get("version"),
"raw": msg.get("raw"),
}
# Idempotency key must be complete; brightness/confidence may be absent in
# malformed feeds but lat/lon/time/satellite are required for dedupe.
if (
row["latitude"] is None or row["longitude"] is None
or row["acq_time"] is None or not row["satellite"]
):
logger.warning(
"dropping malformed fire message (missing natural key): %s",
{k: msg.get(k) for k in ("latitude", "longitude", "acq_time", "satellite")},
)
return None
if isinstance(row["acq_time"], str):
try:
row["acq_time"] = datetime.fromisoformat(row["acq_time"])
except ValueError:
logger.warning("dropping fire message with bad acq_time %r", row["acq_time"])
return None
if not isinstance(row["acq_time"], datetime):
row["acq_time"] = datetime.fromisoformat(str(row["acq_time"]))
return row
async def ingest_fire_row(msg: dict) -> bool:
"""Persist one FIRMS hotspot, idempotently.
The (latitude, longitude, acq_time, satellite) primary key doubles as the
dedupe key: ON CONFLICT DO NOTHING means a hotspot re-delivered on a later
15-minute poll is silently ignored. Returns True if a new row was inserted,
False if it was a duplicate (or dropped).
"""
row = _fire_row_from_msg(msg)
if row is None:
return False
async with async_session() as session:
stmt = (
pg_insert(fires_table)
.values(**row)
.on_conflict_do_nothing(constraint="pk_fires_natural_key")
)
result = await session.execute(stmt)
await session.commit()
inserted = bool(result.rowcount)
if inserted:
logger.info(
"ingested fire %.5f,%.5f %s satellite=%s",
row["latitude"], row["longitude"], row["acq_time"], row["satellite"],
)
lat, lon = row["latitude"], row["longitude"]
from geofence import record_and_notify
await record_and_notify(
source_kind="firms",
entity_id=f"{lat},{lon},{row['satellite']}",
lat=lat, lon=lon, payload={"satellite": row["satellite"]},
)
from live_layers import aircraft_last_known
from fire_aircraft import correlate_and_notify
from tracks import recent_markers
acs = list(aircraft_last_known.values()) or await recent_markers("aircraft")
if acs:
fire = {
"id": f"firms:{lat:.4f},{lon:.4f}",
"lat": lat, "lon": lon, "label": "FIRMS",
}
await correlate_and_notify([fire], acs)
return inserted
async def ingest_fire_rows(msgs: list[dict]) -> int:
"""Bulk-insert FIRMS hotspots: one INSERT, one ON CONFLICT, one commit."""
rows = []
for msg in msgs:
row = _fire_row_from_msg(msg)
if row is not None:
rows.append(row)
if not rows:
return 0
inserted = 0
async with async_session() as session:
for i in range(0, len(rows), FIRE_INSERT_CHUNK):
chunk = rows[i:i + FIRE_INSERT_CHUNK]
stmt = (
pg_insert(fires_table)
.values(chunk)
.on_conflict_do_nothing(constraint="pk_fires_natural_key")
)
result = await session.execute(stmt)
inserted += int(result.rowcount or 0)
await session.commit()
if inserted:
logger.info("bulk ingested %d/%d FIRMS hotspots", inserted, len(rows))
from live_layers import aircraft_last_known
from fire_aircraft import correlate_and_notify
from tracks import recent_markers
acs = list(aircraft_last_known.values()) or await recent_markers("aircraft")
if acs:
fires = [
{
"id": f"firms:{r['latitude']:.4f},{r['longitude']:.4f}",
"lat": r["latitude"], "lon": r["longitude"], "label": "FIRMS",
}
for r in rows[:500]
]
await correlate_and_notify(fires, acs)
return inserted
async def ingest_event(msg: dict):
"""Ingest a single event from NATS into PostgreSQL."""
# Active fire/hotspot messages carry a dedicated schema and land in the
# `fires` hypertable (idempotent natural key), not the generic events feed.
if msg.get("source_type") == "fire":
return await ingest_fire_row(msg)
# source_id links to a feed_sources UUID; tolerate non-UUID / missing values
# (e.g. legacy messages that carried a URL) by coercing to None.
raw_source_id = msg.get("source_id")
source_id = None
if raw_source_id is not None:
try:
source_id = str(uuid.UUID(str(raw_source_id)))
except (ValueError, AttributeError, TypeError):
source_id = None
event_row = {
"source_type": msg.get("source_type", "rss"),
"source_id": source_id,
"title": msg.get("title"),
"body": msg.get("body"),
"url": msg.get("url"),
"sentiment_score": msg.get("sentiment_score"),
"sentiment_label": msg.get("sentiment_label"),
"location_lat": msg.get("location_lat"),
"location_lon": msg.get("location_lon"),
"location_name": msg.get("location_name"),
"entities": msg.get("entities", []),
"tags": msg.get("tags", []),
"raw": msg.get("raw"),
"source_timestamp": msg.get("source_timestamp", datetime.now(timezone.utc).isoformat()),
}
# Parse timestamp if string
ts = event_row["source_timestamp"]
if isinstance(ts, str):
ts = datetime.fromisoformat(ts.replace("Z", "+00:00"))
if isinstance(ts, datetime) and ts.tzinfo is None:
ts = ts.replace(tzinfo=timezone.utc)
event_row["source_timestamp"] = ts
key = event_dedup_key(event_row)
async with async_session() as session:
if key:
dedup = (
pg_insert(event_dedup_table)
.values(url=key)
.on_conflict_do_nothing(index_elements=["url"])
)
claimed = await session.execute(dedup)
if not claimed.rowcount:
await session.commit()
logger.debug("skip duplicate event url=%s", key)
return None
result = await session.execute(events_table.insert().values(**event_row))
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)
js = nc.jetstream()
# Create stream if not exists; if it exists, UPDATE its subject list so
# newly added event types (e.g. events.camera) are actually covered.
from nats.js.api import StreamConfig
stream_cfg = StreamConfig(
name=NATS_STREAM,
subjects=[
"events.gdelt", "events.rss", "events.social",
"events.earthquake", "events.disaster", "events.weather",
"events.fire", "events.satellite", "events.new", "events.alert",
"events.camera",
],
retention=nats.js.api.RetentionPolicy.LIMITS,
max_msgs=1_000_000,
)
try:
await js.add_stream(stream_cfg)
logger.info("Created NATS stream %s", NATS_STREAM)
except Exception:
await js.update_stream(stream_cfg)
logger.info("Updated NATS stream %s subjects", NATS_STREAM)
# Create durable consumer
sub = await js.pull_subscribe(
subject="events.>",
durable=NATS_DURABLE,
)
logger.info("NATS consumer started, durable=%s", NATS_DURABLE)
return nc, sub
async def fetch_and_process(batch_size: int = 100):
"""Fetch a batch of messages and process them."""
nc, sub = await start_nats_consumer()
js = nc.jetstream()
msgs = await sub.fetch(batch_size, timeout=5)
processed = 0
for msg in msgs:
try:
data = json.loads(msg.data)
await ingest_event(data)
await msg.ack()
processed += 1
except Exception:
logger.error("Failed to process message: %s", msg.data, exc_info=True)
await nc.close()
logger.info("Processed %d messages in batch", processed)
return processed

View file

@ -1,230 +0,0 @@
"""OSINT Dashboard — API key store (keyv-style Postgres table).
Keys live in the ``api_keys`` table, shared between the dashboard app and the
ingest services (both connect to the same Postgres). Only the app WRITES keys
via the management API; ingest services read them with :func:`get_api_key`.
Storage: the table is created lazily with ``CREATE TABLE IF NOT EXISTS`` on
first use in each process (no alembic migration, so it can never fork the
migration chain or block container startup). DDL is idempotent and safe when
the app and ingester containers race on first boot.
Security contract:
* Values are stored in Postgres, never in the container image or frontend.
* ``GET /api/keys`` returns only set/missing status plus a masked
"****last4" hint. Full values are NEVER returned by the API.
* Registered keys get cheap format validation on save (regex), e.g. the
FIRMS map key must be a 32-char hex string.
"""
from __future__ import annotations
import asyncio
import re
from datetime import datetime, timezone
from sqlalchemy import Column, DateTime, String, Table, Text, func, select, text
from database import async_session, engine, metadata
# ── Table definition (bound to the shared metadata; created lazily) ───────
api_keys = Table(
"api_keys",
metadata,
Column("name", String(128), primary_key=True),
Column("value", Text, nullable=False),
Column("created_at", DateTime(timezone=True), server_default=func.now(), nullable=False),
Column("updated_at", DateTime(timezone=True), server_default=func.now(), nullable=False),
)
_CREATE_TABLE_SQL = text(
"""
CREATE TABLE IF NOT EXISTS api_keys (
name VARCHAR(128) PRIMARY KEY,
value TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
)
"""
)
# ── Registry of keys the ingest services understand ───────────────────────
# Each entry: human description (shown in the UI) + optional ``pattern`` for
# cheap format validation and an ``example`` for error/placeholder text.
KEY_REGISTRY: dict[str, dict] = {
"FIRMS_MAP_KEY": {
"description": "NASA FIRMS API key — active fire / satellite ingest.",
"pattern": r"^[0-9a-fA-F]{32}$",
"example": "32-char hex string (e.g. 5f3c…9a02)",
},
"NOUS_API_KEY": {
"description": "Nous Portal API key — 15-min news summarizer (inference-api.nousresearch.com).",
"pattern": r"^.{16,}$",
"example": "key from https://portal.nousresearch.com (API keys page)",
},
"TELEGRAM_TOKEN": {
"description": "Telegram bot token — push alert notifications to a channel.",
"pattern": r"^\d{8,10}:[0-9A-Za-z_-]{35}$",
"example": "123456789:AA… (bot token from @BotFather)",
},
"AISSTREAM_API_KEY": {
"description": "AISStream (open/shared) — live US-coast AIS. Server-side WebSocket only.",
"pattern": r"^.{8,}$",
"example": "key from https://aisstream.io/account (GitHub login)",
},
"VESSELAPI_API_KEY": {
"description": "VesselAPI (commercial) — Strait of Hormuz AIS, 5×/day cache. Paste the Bearer token from dashboard.vesselapi.com. Not a US-coast feed.",
"pattern": r"^.{8,}$",
"example": "Bearer token from https://dashboard.vesselapi.com/",
},
"OPENSKY_CLIENT_ID": {
"description": "OpenSky OAuth client id — optional ADS-B fallback (unused until enabled).",
"example": "client id from opensky-network.org account",
},
"OPENSKY_CLIENT_SECRET": {
"description": "OpenSky OAuth client secret — optional ADS-B fallback.",
"example": "client secret from the OpenSky account page",
},
}
# Any stored key must at least be a sane UPPER_SNAKE name.
_NAME_RE = re.compile(r"^[A-Z][A-Z0-9_]{1,63}$")
class KeyFormatError(ValueError):
"""Raised when a key name or value fails format validation."""
# ── Lazy table bootstrap ──────────────────────────────────────────────────
_ensure_lock = asyncio.Lock()
_ensured = False
async def ensure_api_keys_table() -> None:
"""Create the api_keys table if it doesn't exist (idempotent, per process)."""
global _ensured
if _ensured:
return
async with _ensure_lock:
if _ensured:
return
async with engine.begin() as conn:
await conn.execute(_CREATE_TABLE_SQL)
_ensured = True
# ── Validation ────────────────────────────────────────────────────────────
def is_registered(name: str) -> bool:
"""True if ``name`` has an entry in the registry (gets format validation)."""
return name in KEY_REGISTRY
def validate_name(name: str) -> None:
"""Reject malformed key names (must be UPPER_SNAKE)."""
if not _NAME_RE.match(name or ""):
raise KeyFormatError(
"Invalid key name — use UPPER_SNAKE_CASE (e.g. FIRMS_MAP_KEY)."
)
def validate_value(name: str, value: str) -> None:
"""Cheap format validation for registered keys; rejects empty values."""
if not value or not value.strip():
raise KeyFormatError("Value must not be empty.")
info = KEY_REGISTRY.get(name)
pattern = (info or {}).get("pattern")
if pattern and not re.match(pattern, value.strip()):
example = (info or {}).get("example", "a matching value")
raise KeyFormatError(f"'{name}' has an invalid format — expected {example}.")
def mask_value(value: str | None) -> str:
"""Mask a stored value as '****last4' (or '****' when shorter than 4)."""
if not value:
return ""
v = value.strip()
tail = v[-4:] if len(v) >= 4 else ""
return f"****{tail}"
# ── Store operations ──────────────────────────────────────────────────────
async def list_keys() -> list[dict]:
"""Registry keys + any extra stored keys, with masked set-status only."""
await ensure_api_keys_table()
async with async_session() as session:
rows = (await session.execute(select(api_keys))).mappings().all()
stored = {r["name"]: r["value"] for r in rows}
names = list(KEY_REGISTRY) + [n for n in stored if n not in KEY_REGISTRY]
out = []
for name in names:
value = stored.get(name)
info = KEY_REGISTRY.get(name, {})
out.append(
{
"name": name,
"set": value is not None,
"masked": mask_value(value) if value is not None else None,
"description": info.get("description", ""),
"example": info.get("example", ""),
"validated": name in KEY_REGISTRY,
}
)
out.sort(key=lambda k: k["name"].lower())
return out
async def set_key(name: str, value: str) -> dict:
"""Upsert a key value. Validates registered formats; rejects bad names.
Returns the masked status (never the raw value).
"""
validate_name(name)
validate_value(name, value)
value = value.strip()
now = datetime.now(timezone.utc)
await ensure_api_keys_table()
async with async_session() as session:
existing = (
await session.execute(select(api_keys).where(api_keys.c.name == name))
).mappings().one_or_none()
if existing:
await session.execute(
api_keys.update()
.where(api_keys.c.name == name)
.values(value=value, updated_at=now)
)
else:
await session.execute(
api_keys.insert().values(name=name, value=value, updated_at=now)
)
await session.commit()
return {"name": name, "set": True, "masked": mask_value(value)}
async def delete_key(name: str) -> bool:
"""Remove a stored key. Returns True if something was deleted."""
await ensure_api_keys_table()
async with async_session() as session:
result = await session.execute(api_keys.delete().where(api_keys.c.name == name))
await session.commit()
return bool(result.rowcount)
async def get_api_key(name: str) -> str | None:
"""Read a stored key value — used by ingest services, never by the API.
Returns the raw value (or None when unset) so producers can pass it to
external APIs (FIRMS, Nous, Telegram, …). Reads live from Postgres, so a
key set via the dashboard is picked up on the next poll — no restart.
"""
await ensure_api_keys_table()
async with async_session() as session:
row = (
await session.execute(select(api_keys).where(api_keys.c.name == name))
).mappings().one_or_none()
return row["value"] if row else None

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,275 +0,0 @@
"""OSINT Dashboard — SQLAlchemy models (async, declarative)."""
from datetime import datetime, timezone
from uuid import uuid4
from sqlalchemy import (
Boolean, Column, Enum, Float, Index, Integer, String, Text,
DateTime, JSON, func, Table, PrimaryKeyConstraint,
)
from sqlalchemy.dialects.postgresql import UUID, TSVECTOR
from database import metadata
# ── Feed Sources ──────────────────────────────────────────────────────────
feed_sources = Table(
"feed_sources",
metadata,
Column("id", UUID(as_uuid=True), primary_key=True, default=uuid4),
Column("name", String(256), nullable=False),
Column("source_type", Enum(
"rss", "gdel-t2", "social", "earthquake", "disaster",
"weather", "fire", "satellite", name="feed_source_type"
), nullable=False),
Column("url", Text),
Column("config", JSON),
Column("enabled", Integer, server_default="1", nullable=False),
Column("created_at", DateTime(timezone=True), server_default=func.now(), nullable=False),
Column("updated_at", DateTime(timezone=True), server_default=func.now(), onupdate=func.now()),
)
# ── Events (hypertable via TimescaleDB) ──────────────────────────────────
events = Table(
"events",
metadata,
Column("id", UUID(as_uuid=True), primary_key=True, default=uuid4),
Column("source_type", Enum(
"rss", "gdel-t2", "social", "earthquake", "disaster",
"weather", "fire", "satellite", "camera", name="event_source_type"
), nullable=False, index=True),
Column("source_id", UUID(as_uuid=True)),
Column("title", Text),
Column("body", Text),
Column("url", Text),
Column("sentiment_score", Float),
Column("sentiment_label", Enum("positive", "neutral", "negative", name="sentiment_label")),
Column("location_lat", Float),
Column("location_lon", Float),
Column("location_name", String(512)),
Column("entities", JSON),
Column("tags", JSON),
Column("raw", JSON),
Column("ingested_at", DateTime(timezone=True), server_default=func.now(), nullable=False),
Column("source_timestamp", DateTime(timezone=True), nullable=False),
# Full-text search vector
Column(
"search_vector",
TSVECTOR,
nullable=True,
),
)
# GIN index for full-text search
Index("ix_events_search_vector", events.c.search_vector, postgresql_using="gin")
# Spatial index on location
Index("ix_events_location", events.c.location_lat, events.c.location_lon)
# Timescale unique indexes must include the partition column, so URL
# idempotency lives on a regular table — not the events hypertable.
event_dedup = Table(
"event_dedup",
metadata,
Column("url", Text, primary_key=True),
Column("created_at", DateTime(timezone=True), server_default=func.now(), nullable=False),
)
# ── Entities (people, organizations, locations of interest) ──────────────
entities = Table(
"entities",
metadata,
Column("id", UUID(as_uuid=True), primary_key=True, default=uuid4),
Column("name", String(512), nullable=False, index=True),
Column("entity_type", Enum(
"person", "organization", "location", "topic", "asset",
name="entity_type"
), nullable=False),
Column("aliases", JSON),
Column("description", Text),
Column("metadata", JSON),
Column("location_lat", Float),
Column("location_lon", Float),
Column("event_count", Integer, server_default="0"),
Column("first_seen", DateTime(timezone=True), server_default=func.now()),
Column("last_seen", DateTime(timezone=True), server_default=func.now()),
)
# ── Entity-Event Link ────────────────────────────────────────────────────
entity_events = Table(
"entity_events",
metadata,
Column("entity_id", UUID(as_uuid=True), primary_key=True),
Column("event_id", UUID(as_uuid=True), primary_key=True),
Column("relevance_score", Float),
Column("linked_at", DateTime(timezone=True), server_default=func.now()),
)
# ── Alerts ───────────────────────────────────────────────────────────────
alerts = Table(
"alerts",
metadata,
Column("id", UUID(as_uuid=True), primary_key=True, default=uuid4),
Column("alert_type", Enum(
"entity_mention", "sentiment_shift", "geo_proximity",
"keyword_match", "threshold", "anomaly",
name="alert_type"
), nullable=False),
Column("entity_id", UUID(as_uuid=True)),
Column("event_id", UUID(as_uuid=True)),
Column("severity", Enum("low", "medium", "high", "critical", name="alert_severity"), nullable=False),
Column("title", Text, nullable=False),
Column("message", Text),
Column("context", JSON),
Column("acknowledged", Integer, server_default="0"),
Column("acknowledged_by", String(256)),
Column("created_at", DateTime(timezone=True), server_default=func.now(), nullable=False),
Column("resolved_at", DateTime(timezone=True)),
)
Index("ix_alerts_severity_created", alerts.c.severity, alerts.c.created_at.desc())
Index("ix_alerts_entity", alerts.c.entity_id)
# ── Documents (stored in MinIO, indexed here) ────────────────────────────
documents = Table(
"documents",
metadata,
Column("id", UUID(as_uuid=True), primary_key=True, default=uuid4),
Column("bucket", String(256), nullable=False),
Column("object_key", String(1024), nullable=False),
Column("content_type", String(256)),
Column("size_bytes", Integer),
Column("description", Text),
Column("tags", JSON),
Column("event_id", UUID(as_uuid=True)),
Column("uploaded_at", DateTime(timezone=True), server_default=func.now()),
)
# ── Active Fires / Hotspots (NASA FIRMS) ──────────────────────────────────
# VIIRS active fire/hotspot detections from NASA FIRMS. The primary key IS the
# natural key (latitude, longitude, acq_time, satellite) so repeated 15-minute
# polls of the same detection are idempotent (INSERT ... ON CONFLICT DO NOTHING
# silently ignores duplicates). acq_time is the partitioning column of the
# TimescaleDB hypertable, and since it is part of the PK, TimescaleDB's
# "all unique indexes must include the partitioning column" rule is satisfied.
# No surrogate id is needed — the natural key is the identity of a detection.
fires = Table(
"fires",
metadata,
Column("latitude", Float, nullable=False),
Column("longitude", Float, nullable=False),
Column("brightness", Float, nullable=False), # bright_ti4, Kelvin
Column("confidence", String(10), nullable=False), # VIIRS: n/l/h, MODIS: %
Column("acq_time", DateTime(timezone=True), nullable=False), # UTC acquisition
Column("satellite", String(16), nullable=False), # e.g. N (S-NPP), N20, N21
Column("instrument", String(16)),
Column("bright_ti5", Float), # 12µm brightness, Kelvin
Column("frp", Float), # fire radiative power, MW
Column("daynight", String(1)), # D / N
Column("scan", Float),
Column("track", Float),
Column("version", String(32)), # e.g. 2.0NRT / 2.0URT
Column("raw", JSON),
Column("ingested_at", DateTime(timezone=True), server_default=func.now(), nullable=False),
PrimaryKeyConstraint(
"latitude", "longitude", "acq_time", "satellite",
name="pk_fires_natural_key",
),
)
# Bounding-box index for `bbox=` filtering (lon first for max/min-lon scans).
Index("ix_fires_bbox", fires.c.longitude, fires.c.latitude)
# ── News pipeline (scraper + summarizer) ──────────────────────────────────
# Written by the vendored news-scraper (Scrapy) / news-summarizer services;
# schema must match the idempotent alembic migrations 003_news + 005_news_items.
articles = Table(
"articles",
metadata,
Column("id", Integer, primary_key=True, autoincrement=True),
Column("title", Text),
Column("url", Text, unique=True), # dedup key
Column("content", Text), # full extracted article text
Column("domain", Text), # source domain
Column("timestamp", DateTime(timezone=True)), # capture time
)
Index("ix_articles_timestamp", articles.c.timestamp)
article_summaries = Table(
"article_summaries",
metadata,
Column("id", Integer, primary_key=True, autoincrement=True),
Column("summary_text", Text, nullable=False),
Column("batch_timestamp", DateTime(timezone=True),
server_default=func.now(), nullable=False),
Column("model", Text), # LLM id used for this batch; nullable for old rows
Column("kind", Text), # interval | daily_recap; nullable for old rows
)
Index("ix_article_summaries_batch_timestamp", article_summaries.c.batch_timestamp)
news_items = Table(
"news_items",
metadata,
Column("id", Integer, primary_key=True, autoincrement=True),
Column("summary_id", Integer),
Column("kind", Text, nullable=False),
Column("headline", Text, nullable=False),
Column("importance", Text, nullable=False),
Column("location_name", Text),
Column("lat", Float),
Column("lon", Float),
Column("location_confidence", Text),
Column("category", Text),
Column("url", Text),
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),
)

View file

@ -1,33 +0,0 @@
"""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*<!\[CDATA\[(.*?)\]\]>\s*\Z",
re.DOTALL,
)
def unwrap_cdata_title(title: str | None) -> str | None:
"""Strip a surrounding CDATA wrapper. Anything else is unchanged.
``<![CDATA[Hello]]>`` and ``\\n <![CDATA[Hello]]>`` become
``Hello``. Real HTML (``<b>Hello</b>``) 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()

View file

@ -1,99 +0,0 @@
"""Nominatim reverse-geocode proxy for the map place dossier.
Browser clients cannot set an identifying User-Agent, and Nominatim typically
blocks CORS — so the HUD calls GET /api/place instead of talking to OSM
directly. Cache 60s / 500 keys; never exceed 1 req/s upstream.
"""
from __future__ import annotations
import asyncio
import time
import httpx
from cachetools import TTLCache
from config import NOMINATIM_MIN_INTERVAL, NOMINATIM_URL, OSINT_USER_AGENT
_NOMINATIM = NOMINATIM_URL.rstrip("/")
place_cache: TTLCache = TTLCache(maxsize=500, ttl=60)
_lock = asyncio.Lock()
_last_req = 0.0
_ADDR_KEEP = (
"house_number", "road", "neighbourhood", "suburb", "city", "town",
"village", "hamlet", "county", "state", "postcode", "country", "country_code",
)
def cache_key(lat: float, lon: float) -> str:
return f"{lat:.4f},{lon:.4f}"
def slim_place(lat: float, lon: float, data: dict | None) -> dict:
data = data or {}
raw_addr = data.get("address")
addr_in: dict = raw_addr if isinstance(raw_addr, dict) else {}
address = {k: addr_in[k] for k in _ADDR_KEEP if addr_in.get(k)}
err = data.get("error")
display = None if err else (data.get("display_name") or None)
name = None if err else (data.get("name") or address.get("city")
or address.get("town") or address.get("village") or None)
return {
"lat": lat,
"lon": lon,
"display_name": display,
"name": name,
"address": address,
"osm_type": None if err else data.get("osm_type"),
"osm_id": None if err else data.get("osm_id"),
"attribution": "© OpenStreetMap contributors",
}
async def reverse_geocode(lat: float, lon: float) -> dict:
"""Reverse-geocode a point. Cache hits skip Nominatim entirely."""
if not (-90.0 <= lat <= 90.0 and -180.0 <= lon <= 180.0):
raise ValueError("lat/lon out of range")
key = cache_key(lat, lon)
qlat, qlon = (float(p) for p in key.split(","))
async with _lock:
hit = place_cache.get(key)
if hit is not None:
return hit
global _last_req
wait = _last_req + NOMINATIM_MIN_INTERVAL - time.monotonic()
if wait > 0:
await asyncio.sleep(wait)
body = await _fetch_nominatim(qlat, qlon)
_last_req = time.monotonic()
place_cache[key] = body
return body
async def _fetch_nominatim(lat: float, lon: float) -> dict:
headers = {
"User-Agent": OSINT_USER_AGENT,
"Accept": "application/json",
}
url = f"{_NOMINATIM}/reverse"
params = {
"lat": f"{lat:.6f}",
"lon": f"{lon:.6f}",
"format": "jsonv2",
"addressdetails": "1",
"zoom": "18",
}
async with _http_client(timeout=10.0, follow_redirects=True) as client:
r = await client.get(url, params=params, headers=headers)
r.raise_for_status()
data = r.json()
if not isinstance(data, dict):
data = {}
return slim_place(lat, lon, data)
def _http_client(**kwargs):
return httpx.AsyncClient(**kwargs)

View file

@ -1,16 +0,0 @@
fastapi>=0.115
uvicorn[standard]>=0.34
sqlalchemy[asyncio]>=2.0
asyncpg>=0.30
nats-py>=2.9
minio>=7.2
pydantic>=2.10
alembic>=1.14
httpx>=0.28
feedparser>=6.0
python-dateutil>=2.9
structlog>=24.4
websockets>=14
cachetools>=5.5
h3>=4.0
sgp4>=2.23

View file

@ -1,69 +0,0 @@
"""Long-running camera discovery service.
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
CAMERA_SCRAPE_INTERVAL seconds between cycles (default 3600)
CAMERA_ENABLED "0" to disable (default "1")
"""
from __future__ import annotations
import asyncio
import logging
import sys
from pathlib import Path
sys_path = str(Path(__file__).parent)
sys.path.insert(0, sys_path)
from camera_config import ( # noqa: E402
CAMERA_SOURCE_URLS, CAMERA_SCRAPE_INTERVAL,
SNAPSHOT_CACHE_DIR,
)
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")
logger = logging.getLogger("osint.camera_service")
ENABLED = sys.argv[1:] != ["--once"]
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:
logger.info("camera discovery starting (%d sources, interval=%ss)",
len(CAMERA_SOURCE_URLS), CAMERA_SCRAPE_INTERVAL)
Path(SNAPSHOT_CACHE_DIR).mkdir(parents=True, exist_ok=True)
await init_extensions()
while True:
try:
n = await run_cycle()
p = await publish_new_cameras()
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
return
await asyncio.sleep(CAMERA_SCRAPE_INTERVAL)
if __name__ == "__main__":
asyncio.run(main())

View file

@ -1,167 +0,0 @@
"""Long-running ingester: pulls OSINT sources into NATS JetStream and
consumes NATS messages into PostgreSQL.
Runs forever (one process, two concurrent tasks):
* producer loop — fetch RSS / GDELT / USGS on an interval, publish to NATS
* consumer loop — pull from the NATS `events.>` stream, write to Postgres
Env (all optional, 12-factor):
RSS_URL comma-separated feed URLs to poll (default: none)
INGEST_INTERVAL seconds between producer cycles (default: 300)
GDELT_QUERY GDELT search term (default: "")
INGEST_EARTHQUAKES "1"/"true" to enable USGS feed (default: "1")
"""
from __future__ import annotations
import asyncio
import logging
import os
from pathlib import Path
sys_path = str(Path(__file__).parent)
import sys
sys.path.insert(0, sys_path)
from config import NATS_URL, FIRMS_INTERVAL, FIRMS_DATASET, AISSTREAM_IN_INGEST, VESSELAPI_IN_INGEST # noqa: E402
from sources import ingest_rss_feed, ingest_gdelt, ingest_earthquakes, ingest_eonet, ingest_cisa_kev # noqa: E402
from fire_sources import ingest_fires # noqa: E402
from ingestor import ingest_event, start_nats_consumer # noqa: E402
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
logger = logging.getLogger("osint.ingester")
RSS_URLS = [u.strip() for u in os.getenv("RSS_URL", "").split(",") if u.strip()]
INTERVAL = int(os.getenv("INGEST_INTERVAL", "300"))
GDELT_QUERY = os.getenv("GDELT_QUERY", "")
ENABLE_QUAKES = os.getenv("INGEST_EARTHQUAKES", "1").lower() in ("1", "true", "yes")
ENABLE_FIRES = os.getenv("INGEST_FIRES", "1").lower() in ("1", "true", "yes")
ENABLE_EONET = os.getenv("INGEST_EONET", "1").lower() in ("1", "true", "yes")
ENABLE_KEV = os.getenv("INGEST_KEV", "1").lower() in ("1", "true", "yes")
NATS_STREAM = "events"
async def producer_loop() -> None:
"""Periodically fetch external sources and publish to NATS."""
while True:
try:
for url in RSS_URLS:
try:
n = await ingest_rss_feed(url)
logger.info("RSS %s -> %d items", url, n)
except Exception: # noqa: BLE001
logger.exception("RSS fetch failed: %s", url)
try:
g = await ingest_gdelt(query=GDELT_QUERY, max_articles=50)
logger.info("GDELT -> %d articles", g)
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()
logger.info("USGS -> %d events", q)
except Exception: # noqa: BLE001
logger.exception("USGS fetch failed")
if ENABLE_EONET:
try:
n = await ingest_eonet()
logger.info("EONET -> %d events", n)
except Exception: # noqa: BLE001
logger.exception("EONET fetch failed")
if ENABLE_KEV:
try:
k = await ingest_cisa_kev()
logger.info("CISA KEV -> %d events", k)
except Exception: # noqa: BLE001
logger.exception("CISA KEV fetch failed")
except Exception: # noqa: BLE001
logger.exception("producer cycle error")
await asyncio.sleep(INTERVAL)
async def consumer_loop() -> None:
"""Continuously pull NATS messages and persist to Postgres."""
_, sub = await start_nats_consumer()
while True:
try:
msgs = await sub.fetch(100, timeout=5)
except Exception: # noqa: BLE001 (TimeoutError / no messages)
continue
for msg in msgs:
try:
import json
data = json.loads(msg.data)
await ingest_event(data)
await msg.ack()
except Exception: # noqa: BLE001
logger.exception("failed to process message")
async def fire_loop() -> None:
"""Poll NASA FIRMS active fires on the ~15-minute cadence.
Runs as its own task so its slower cadence (FIRMS_INTERVAL, default 900s)
is independent of the RSS/GDELT/USGS producer cycle (INGEST_INTERVAL).
"""
logger.info("fire loop starting (interval=%ss, dataset=%s)", FIRMS_INTERVAL, FIRMS_DATASET)
while True:
try:
n = await ingest_fires()
logger.info("FIRMS -> %d hotspots", n)
except Exception: # noqa: BLE001 — keep the loop alive across transient failures
logger.exception("FIRMS fetch failed")
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)",
len(RSS_URLS), GDELT_QUERY, ENABLE_QUAKES, ENABLE_FIRES, INTERVAL,
)
try:
from geofence import refresh_cache
await refresh_cache()
except Exception:
logger.exception("geofence cache refresh failed (ST_Intersects still runs on ingest)")
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).
tasks.append(asyncio.create_task(fire_loop()))
if AISSTREAM_IN_INGEST:
from ais_stream import run_ais_worker # noqa: E402
tasks.append(asyncio.create_task(run_ais_worker()))
if VESSELAPI_IN_INGEST:
from vesselapi import run_vesselapi_worker # noqa: E402
tasks.append(asyncio.create_task(run_vesselapi_worker()))
await asyncio.gather(producer_loop(), consumer_loop(), *tasks)
if __name__ == "__main__":
asyncio.run(main())

View file

@ -1,289 +0,0 @@
"""CelesTrak satellites last-known overlay.
Fetches GP **JSON** (OMM mean elements — not TLE) per group at most once per
2 hours, caches the element blob, and propagates positions with a real SGP4
library on every request. Positions move every second; the *element set* is
what we cache, not the derived lat/lon.
Catalog numbers >= 100000 only fit OMM/JSON, never a 5-column TLE field, so
elements are initialized through :func:`sgp4.omm.initialize` (which consumes
the CelesTrak GP JSON fields verbatim) rather than round-tripping to TLE.
CelesTrak usage policy is non-negotiable: fetch the GP JSON blob at most once
per 2 hours per group, never fan out every GROUP, never also fetch
``GROUP=active`` plus subsets, and identify with ``OSINT_USER_AGENT``.
"""
from __future__ import annotations
import logging
import math
from datetime import datetime, timezone
from urllib.parse import quote
logger = logging.getLogger("osint.satellites")
CELESTRAK_GP = "https://celestrak.org/NORAD/elements/gp.php"
SATNOGS_TLE = "https://db.satnogs.org/api/tle/"
DEFAULT_GROUPS = ("stations", "weather")
ALLOWED_GROUPS = ("stations", "weather", "gps-ops", "starlink")
# CelesTrak policy: do not hit gp.php more than once per 2 hours per group.
SATELLITE_TTL = 2 * 3600.0
SOURCE_CELESTRAK = "celestrak"
SOURCE_SATNOGS = "satnogs"
DEFAULT_LIMIT = 2000
# WGS-84 ellipsoid for TEME -> geodetic.
_WGS84_A = 6378.137
_WGS84_F = 1.0 / 298.257223563
# Last-good element blob per group, kept past TTL so a 403 / "has not updated
# since ..." still serves the previous set instead of failing the overlay.
_last_good: dict[str, list[dict]] = {}
def parse_groups(raw: str | None) -> list[str]:
"""Validate + normalize a comma-separated group list. Raises ValueError.
Starlink is allowed only when explicitly requested (never in the default);
it is a large supplemental feed, not part of the stations/weather default.
"""
groups = [g.strip().lower() for g in (raw or "").split(",") if g.strip()]
if not groups:
raise ValueError("groups must be a non-empty comma-separated list")
bad = [g for g in groups if g not in ALLOWED_GROUPS]
if bad:
raise ValueError(f"unknown group(s): {', '.join(bad)}")
# Dedup, preserve order.
seen: set[str] = set()
out: list[str] = []
for g in groups:
if g not in seen:
seen.add(g)
out.append(g)
return out
def _teme_to_geodetic(
r: tuple[float, float, float],
jd: float,
fr: float,
) -> tuple[float, float, float]:
"""SGP4 TEME position (km) -> geodetic (lat_deg, lon_deg, alt_km).
Rotate TEME into an Earth-fixed frame via GMST, then iterate the WGS-84
geodetic conversion. Good to well under a km for a ground-track overlay.
"""
# GMST (radians) from UT1 ~= UTC here (sub-second error is negligible).
d = (jd + fr) - 2451545.0
t = d / 36525.0
gmst_s = (
67310.54841
+ (876600.0 * 3600.0 + 8640184.812866) * t
+ 0.093104 * t * t
- 6.2e-6 * t * t * t
)
theta = math.radians((gmst_s % 86400.0) / 240.0)
x, y, z = r
xe = x * math.cos(theta) + y * math.sin(theta)
ye = -x * math.sin(theta) + y * math.cos(theta)
ze = z
e2 = _WGS84_F * (2.0 - _WGS84_F)
p = math.sqrt(xe * xe + ye * ye)
lon = math.atan2(ye, xe)
lat = math.atan2(ze, p * (1.0 - e2))
alt = 0.0
for _ in range(10):
n = _WGS84_A / math.sqrt(1.0 - e2 * math.sin(lat) ** 2)
alt = p / math.cos(lat) - n
lat = math.atan2(ze, p * (1.0 - e2 * n / (n + alt)))
n = _WGS84_A / math.sqrt(1.0 - e2 * math.sin(lat) ** 2)
alt = p / math.cos(lat) - n
return math.degrees(lat), math.degrees(lon), alt
def propagate_gp(
elements: list[dict],
group: str,
now: datetime,
) -> list[dict]:
"""Propagate CelesTrak GP JSON elements to geodetic positions at ``now``.
Pure and deterministic given ``now``. Returns ``[{id, name, lat, lon,
alt_km, group}]``; malformed elements and propagation errors are skipped.
"""
from sgp4.api import Satrec, jday
import sgp4.omm as omm
jd, fr = jday(
now.year, now.month, now.day,
now.hour, now.minute, now.second + now.microsecond / 1e6,
)
out: list[dict] = []
for rec in elements:
if not isinstance(rec, dict):
continue
sat = Satrec()
try:
omm.initialize(sat, rec)
except (KeyError, ValueError, TypeError):
continue
err, r, _v = sat.sgp4(jd, fr)
if err != 0:
continue
lat, lon, alt = _teme_to_geodetic(r, jd, fr)
norad = rec.get("NORAD_CAT_ID")
out.append({
"id": str(norad) if norad is not None else "",
"name": rec.get("OBJECT_NAME") or str(norad or ""),
"lat": round(lat, 5),
"lon": round(lon, 5),
"alt_km": round(alt, 2),
"group": group,
})
return out
def _max_epoch(elements: list[dict]) -> str | None:
"""Most recent EPOCH across an element set (ISO-8601 lexical max)."""
epochs = [
str(e["EPOCH"]) for e in elements
if isinstance(e, dict) and e.get("EPOCH")
]
return max(epochs) if epochs else None
def propagate_satnogs_tle(
payload: list[dict],
group: str,
now: datetime,
) -> tuple[list[dict], str | None]:
"""Fallback parser for SatNOGS TLE JSON (``[{tle0,tle1,tle2,updated}]``).
Returns ``(satellites, epoch)`` where epoch is the max ``updated`` time.
Only used when the CelesTrak cache is completely empty.
"""
from sgp4.api import Satrec, jday
jd, fr = jday(
now.year, now.month, now.day,
now.hour, now.minute, now.second + now.microsecond / 1e6,
)
out: list[dict] = []
epochs: list[str] = []
for rec in payload or []:
if not isinstance(rec, dict):
continue
line1 = rec.get("tle1")
line2 = rec.get("tle2")
if not line1 or not line2:
continue
try:
sat = Satrec.twoline2rv(line1, line2)
except (ValueError, TypeError):
continue
e, r, _v = sat.sgp4(jd, fr)
if e != 0:
continue
lat, lon, alt = _teme_to_geodetic(r, jd, fr)
satnum = getattr(sat, "satnum_str", None) or rec.get("norad_cat_id")
name = (rec.get("tle0") or "").strip().lstrip("0").strip() or str(satnum or "")
out.append({
"id": str(satnum).strip() or "",
"name": name,
"lat": round(lat, 5),
"lon": round(lon, 5),
"alt_km": round(alt, 2),
"group": group,
})
if rec.get("updated"):
epochs.append(str(rec["updated"]))
return out, (max(epochs) if epochs else None)
async def _group_elements(group: str) -> tuple[list[dict], str | None]:
"""CelesTrak GP blob for one group, TTL-cached with a last-good fallback.
Returns ``(elements, epoch)``. On a fetch failure (403 / "has not updated
since ...") falls back to the previous successful blob for that group.
"""
from live_layers import _get_json, _ttl_get
url = f"{CELESTRAK_GP}?GROUP={quote(group)}&FORMAT=JSON"
async def _load() -> list[dict]:
data = await _get_json(url)
if not isinstance(data, list):
raise ValueError(f"unexpected CelesTrak payload for {group}")
if data:
_last_good[group] = data
return data
key = f"celestrak:gp:{group}"
try:
elements = await _ttl_get(key, SATELLITE_TTL, _load)
except Exception as exc: # noqa: BLE001
logger.warning("celestrak_fetch_failed group=%s: %s", group, exc)
elements = _last_good.get(group, [])
if not elements:
return [], None
return elements, _max_epoch(elements)
async def fetch_satellites(
groups: list[str],
bbox: str | None = None,
limit: int = DEFAULT_LIMIT,
) -> dict:
"""Assemble the ``/api/satellites`` payload for the requested groups."""
from live_layers import _get_json, _ttl_get, filter_points_bbox, parse_bbox
now = datetime.now(timezone.utc)
satellites: list[dict] = []
epoch: str | None = None
source = SOURCE_CELESTRAK
for group in groups:
elements, group_epoch = await _group_elements(group)
if not elements:
continue
if group_epoch and (epoch is None or group_epoch > epoch):
epoch = group_epoch
satellites.extend(propagate_gp(elements, group, now))
if not satellites:
# Fallback only when the CelesTrak cache is entirely empty — never
# poll both providers every cycle.
async def _load_satnogs() -> list[dict]:
data = await _get_json(SATNOGS_TLE, params={"format": "json"})
return data if isinstance(data, list) else []
try:
satnogs = await _ttl_get("satnogs:tle", SATELLITE_TTL, _load_satnogs)
except Exception as exc: # noqa: BLE001
logger.warning("satnogs_fetch_failed: %s", exc)
satnogs = []
if satnogs:
source = SOURCE_SATNOGS
for group in groups:
rows, sn_epoch = propagate_satnogs_tle(satnogs, group, now)
if sn_epoch and (epoch is None or sn_epoch > epoch):
epoch = sn_epoch
satellites.extend(rows)
if bbox:
minlon, minlat, maxlon, maxlat = parse_bbox(bbox)
satellites = filter_points_bbox(
satellites, minlon, minlat, maxlon, maxlat, limit,
)
else:
satellites = satellites[:limit]
return {
"satellites": satellites,
"source": source,
"tle_epoch": epoch,
"timestamp": now.isoformat(),
}

View file

@ -1,440 +0,0 @@
"""OSINT Dashboard — Pydantic schemas."""
from __future__ import annotations
from datetime import datetime
from enum import Enum
from typing import Literal, Optional
from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field, field_validator
# ─── Enums ───────────────────────────────────────────────────────────────
class SourceType(str, Enum):
rss = "rss"
gdel_t2 = "gdel-t2"
social = "social"
earthquake = "earthquake"
disaster = "disaster"
weather = "weather"
fire = "fire"
satellite = "satellite"
camera = "camera"
class EntityKind(str, Enum):
person = "person"
organization = "organization"
location = "location"
topic = "topic"
asset = "asset"
class Sentiment(str, Enum):
positive = "positive"
neutral = "neutral"
negative = "negative"
class AlertType(str, Enum):
entity_mention = "entity_mention"
sentiment_shift = "sentiment_shift"
geo_proximity = "geo_proximity"
keyword_match = "keyword_match"
threshold = "threshold"
anomaly = "anomaly"
class AlertSeverity(str, Enum):
low = "low"
medium = "medium"
high = "high"
critical = "critical"
# ─── Feed Sources ───────────────────────────────────────────────────────
class FeedSourceCreate(BaseModel):
name: str
source_type: SourceType
url: Optional[str] = None
config: Optional[dict] = None
class FeedSourceUpdate(BaseModel):
"""PATCH /api/sources/{id} — only these keys may be set."""
model_config = ConfigDict(extra="forbid")
name: Optional[str] = None
url: Optional[str] = None
config: Optional[dict] = None
enabled: Optional[bool] = None
class FeedSourceOut(BaseModel):
id: UUID
name: str
source_type: SourceType
url: Optional[str]
config: Optional[dict]
enabled: bool
created_at: datetime
# ─── Events ─────────────────────────────────────────────────────────────
class EventCreate(BaseModel):
source_type: SourceType
source_id: Optional[UUID] = None
title: Optional[str] = None
body: Optional[str] = None
url: Optional[str] = None
sentiment_score: Optional[float] = None
sentiment_label: Optional[Sentiment] = None
location_lat: Optional[float] = None
location_lon: Optional[float] = None
location_name: Optional[str] = None
entities: Optional[list[dict]] = None
tags: Optional[list[str]] = None
raw: Optional[dict] = None
source_timestamp: Optional[datetime] = None
class EventOut(BaseModel):
id: UUID
source_type: SourceType
source_id: Optional[UUID]
title: Optional[str]
body: Optional[str]
url: Optional[str]
sentiment_score: Optional[float]
sentiment_label: Optional[Sentiment]
location_lat: Optional[float]
location_lon: Optional[float]
location_name: Optional[str]
entities: Optional[list[dict]]
tags: Optional[list[str]]
ingested_at: datetime
source_timestamp: datetime
# ─── Search ──────────────────────────────────────────────────────────────
class SearchQuery(BaseModel):
q: str = Field(..., min_length=1, max_length=500)
source_type: Optional[SourceType] = None
entity_id: Optional[UUID] = None
sentiment: Optional[Sentiment] = None
min_date: Optional[datetime] = None
max_date: Optional[datetime] = None
min_lat: Optional[float] = None
max_lat: Optional[float] = None
min_lon: Optional[float] = None
max_lon: Optional[float] = None
limit: int = Field(50, ge=1, le=500)
offset: int = Field(0, ge=0)
class SearchResult(BaseModel):
events: list[EventOut]
total: int
has_more: bool
# ─── Entities ────────────────────────────────────────────────────────────
class EntityCreate(BaseModel):
name: str
entity_type: EntityKind
aliases: Optional[list[str]] = None
description: Optional[str] = None
metadata: Optional[dict] = None
location_lat: Optional[float] = None
location_lon: Optional[float] = None
class EntityOut(BaseModel):
id: UUID
name: str
entity_type: EntityKind
aliases: Optional[list[str]]
description: Optional[str]
metadata: Optional[dict]
location_lat: Optional[float]
location_lon: Optional[float]
event_count: int
first_seen: datetime
last_seen: datetime
# ─── Alerts ──────────────────────────────────────────────────────────────
class AlertCreate(BaseModel):
alert_type: AlertType
entity_id: Optional[UUID] = None
event_id: Optional[UUID] = None
severity: AlertSeverity
title: str
message: Optional[str] = None
context: Optional[dict] = None
class AlertUpdate(BaseModel):
acknowledged: Optional[bool] = None
acknowledged_by: Optional[str] = None
resolved_at: Optional[datetime] = None
class AlertOut(BaseModel):
id: UUID
alert_type: AlertType
entity_id: Optional[UUID]
event_id: Optional[UUID]
severity: AlertSeverity
title: str
message: Optional[str]
context: Optional[dict]
acknowledged: bool
acknowledged_by: Optional[str]
created_at: datetime
resolved_at: Optional[datetime]
# ─── Documents ───────────────────────────────────────────────────────────
class DocumentCreate(BaseModel):
bucket: str
object_key: str
content_type: Optional[str] = None
size_bytes: Optional[int] = None
description: Optional[str] = None
tags: Optional[list[str]] = None
event_id: Optional[UUID] = None
class DocumentOut(BaseModel):
id: UUID
bucket: str
object_key: str
content_type: Optional[str]
size_bytes: Optional[int]
description: Optional[str]
tags: Optional[list[str]]
event_id: Optional[UUID]
uploaded_at: datetime
# ─── API Keys ────────────────────────────────────────────────────────────
class KeyValueIn(BaseModel):
"""Body for POST /api/keys/{name} — the value to store.
The raw value is accepted only on write; it is never read back out.
"""
value: str = Field(..., min_length=1, max_length=4096)
class KeyOut(BaseModel):
"""One key's status as exposed by GET /api/keys.
``masked`` is the "****last4" hint; the full value is NEVER included.
"""
name: str
set: bool
masked: Optional[str] = None
description: Optional[str] = None
example: Optional[str] = None
validated: bool = True
# ─── Active fires / hotspots (NASA FIRMS) ────────────────────────────────
class FireOut(BaseModel):
latitude: float
longitude: float
brightness: float # bright_ti4 brightness temperature, Kelvin
confidence: str # VIIRS: n (nominal) / l (low) / h (high)
acq_time: datetime
satellite: str
instrument: Optional[str] = None
bright_ti5: Optional[float] = None # 12µm brightness temperature, Kelvin
frp: Optional[float] = None # fire radiative power, MW
daynight: Optional[str] = None # D / N
# ─── News pipeline (scraper + summarizer) ────────────────────────────────
class NewsArticleOut(BaseModel):
"""One scraped article as exposed by GET /api/news."""
id: int
title: Optional[str] = None
url: Optional[str] = None
content: Optional[str] = None
domain: Optional[str] = None
timestamp: Optional[datetime] = None
class NewsSummaryOut(BaseModel):
"""One master LLM summary as exposed by GET /api/news/summaries."""
id: int
summary_text: str
batch_timestamp: datetime
model: Optional[str] = None
kind: Optional[str] = None
class NewsTickerItemOut(BaseModel):
"""One flagged ticker row as exposed by GET /api/news/ticker."""
id: int
headline: str
importance: str
location_name: Optional[str] = None
url: Optional[str] = None
created_at: datetime
class NewsMapItemOut(BaseModel):
"""One flagged map pin as exposed by GET /api/news/map."""
id: int
headline: str
importance: str
location_name: Optional[str] = None
lat: float
lon: float
location_confidence: Optional[str] = None
category: Optional[str] = None
url: Optional[str] = None
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."""
id: str
class NewsModelsOut(BaseModel):
"""Catalog for the summarizer model selector."""
source: str
models: list[NewsModelId]
class SettingsIn(BaseModel):
"""Body for PUT /api/settings. ``nous_base_url`` is not writable."""
summary_model: str = Field(..., min_length=1, max_length=128)
@field_validator("summary_model")
@classmethod
def summary_model_not_blank(cls, v: str) -> str:
stripped = v.strip()
if not stripped:
raise ValueError("summary_model must be 1–128 chars, not whitespace-only")
if len(stripped) > 128:
raise ValueError("summary_model must be 1–128 chars, not whitespace-only")
return stripped
class SettingsOut(BaseModel):
"""Current summarizer settings. ``nous_base_url`` is read-only."""
summary_model: str
nous_base_url: str
# ─── Aggregations ────────────────────────────────────────────────────────
class SentimentSummary(BaseModel):
period: str
positive_count: int
neutral_count: int
negative_count: int
avg_score: float
class TimelinePoint(BaseModel):
timestamp: datetime
event_count: int
avg_sentiment: float
class DashboardSummary(BaseModel):
total_events: int
events_last_24h: int
active_sources: int
open_alerts: int
tracked_entities: int
sentiment: SentimentSummary
top_entities: list[EntityOut]
class VesselBboxUpdate(BaseModel):
"""Retune the server-side AISStream subscription to a client viewport box.
``bbox`` is "minlon,minlat,maxlon,maxlat" (Leaflet order). ``None``/empty
resets to the env AISSTREAM_BBOX default.
"""
bbox: str | None = None
class GeofenceCreate(BaseModel):
name: str
geojson: dict
active: bool = True
class GeofenceUpdate(BaseModel):
name: Optional[str] = None
geojson: Optional[dict] = None
active: Optional[bool] = None
class ConflictZoneOut(BaseModel):
"""One curated conflict theatre as exposed by GET /api/conflicts."""
id: str
label: str
severity: Literal["war", "high", "elevated"]
lat: float
lon: float
description: str
eventCount: int
lastUpdated: Optional[datetime] = None
class ConflictsOut(BaseModel):
"""Response envelope for GET /api/conflicts."""
zones: list[ConflictZoneOut]
timestamp: datetime

View file

@ -1,219 +0,0 @@
"""OSINT Dashboard — non-secret app settings (keyv-style Postgres table).
Model choice lives here so the summarizer container can read it from Postgres.
Only whitelisted names are stored — this is not a generic dump.
Storage: the table is created lazily with ``CREATE TABLE IF NOT EXISTS`` on
first use in each process (same bootstrap pattern as ``api_keys``).
"""
from __future__ import annotations
import asyncio
import os
import time
from datetime import datetime, timezone
import httpx
from sqlalchemy import Column, DateTime, String, Table, Text, func, select, text
import keystore
from database import async_session, engine, metadata
DEFAULT_NOUS_BASE_URL = "https://inference-api.nousresearch.com/v1"
DEFAULT_SUMMARY_MODEL = "Hermes-4.3-36B"
SETTING_SUMMARY_MODEL = "SUMMARY_MODEL"
ALLOWED_SETTINGS = frozenset({SETTING_SUMMARY_MODEL})
MODELS_CACHE_TTL_S = 600.0
MODELS_TIMEOUT_S = 8.0
DEFAULT_MODELS_USER_AGENT = "osint-dashboard-news-summarizer"
FALLBACK_MODELS = [
"Hermes-4.3-36B",
"Hermes-4-70B",
"google/gemini-2.5-flash",
"anthropic/claude-haiku-4.5",
"openai/gpt-4.1-mini",
"x-ai/grok-4",
]
app_settings = Table(
"app_settings",
metadata,
Column("name", String(128), primary_key=True),
Column("value", Text, nullable=False),
Column("updated_at", DateTime(timezone=True), server_default=func.now(), nullable=False),
)
_CREATE_TABLE_SQL = text(
"""
CREATE TABLE IF NOT EXISTS app_settings (
name VARCHAR(128) PRIMARY KEY,
value TEXT NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
)
"""
)
_ensure_lock = asyncio.Lock()
_ensured = False
_models_cache: tuple[float, dict] | None = None
class SettingsError(ValueError):
"""Raised when a setting name or value fails validation."""
async def ensure_app_settings_table() -> None:
"""Create the app_settings table if it doesn't exist (idempotent, per process)."""
global _ensured
if _ensured:
return
async with _ensure_lock:
if _ensured:
return
async with engine.begin() as conn:
await conn.execute(_CREATE_TABLE_SQL)
_ensured = True
def nous_base_url() -> str:
"""Read-only Nous inference base URL (env, never writable from the UI)."""
raw = (os.getenv("NOUS_BASE_URL") or "").strip().rstrip("/")
return raw or DEFAULT_NOUS_BASE_URL
def _validate_summary_model(value: str) -> str:
stripped = (value or "").strip()
if not stripped or len(stripped) > 128:
raise SettingsError("summary_model must be 1–128 chars, not whitespace-only")
return stripped
async def get_summary_model() -> str:
"""Stored SUMMARY_MODEL, else env, else Hermes-4.3-36B."""
await ensure_app_settings_table()
async with async_session() as session:
row = (
await session.execute(
select(app_settings).where(app_settings.c.name == SETTING_SUMMARY_MODEL)
)
).mappings().one_or_none()
if row and row["value"]:
return row["value"]
return os.getenv("SUMMARY_MODEL", DEFAULT_SUMMARY_MODEL)
async def set_summary_model(value: str) -> dict:
"""Upsert SUMMARY_MODEL and return the public settings payload."""
value = _validate_summary_model(value)
now = datetime.now(timezone.utc)
await ensure_app_settings_table()
async with async_session() as session:
existing = (
await session.execute(
select(app_settings).where(app_settings.c.name == SETTING_SUMMARY_MODEL)
)
).mappings().one_or_none()
if existing:
await session.execute(
app_settings.update()
.where(app_settings.c.name == SETTING_SUMMARY_MODEL)
.values(value=value, updated_at=now)
)
else:
await session.execute(
app_settings.insert().values(
name=SETTING_SUMMARY_MODEL, value=value, updated_at=now
)
)
await session.commit()
return await get_app_settings()
async def get_app_settings() -> dict:
return {
"summary_model": await get_summary_model(),
"nous_base_url": nous_base_url(),
}
def _fallback_payload() -> dict:
return {
"source": "fallback",
"models": [{"id": mid} for mid in FALLBACK_MODELS],
}
async def _nous_api_key() -> str | None:
"""Keystore first, then env. Any lookup failure is treated as missing."""
try:
stored = await keystore.get_api_key("NOUS_API_KEY")
except Exception:
stored = None
if stored and str(stored).strip():
return str(stored).strip()
env = (os.getenv("NOUS_API_KEY") or "").strip()
return env or None
def _models_user_agent() -> str:
return os.getenv("OSINT_USER_AGENT") or DEFAULT_MODELS_USER_AGENT
def _parse_models_payload(body: object) -> list[dict[str, str]]:
if isinstance(body, dict):
raw = body.get("data", body.get("models", []))
elif isinstance(body, list):
raw = body
else:
raw = []
out: list[dict[str, str]] = []
for item in raw or []:
if isinstance(item, str) and item.strip():
out.append({"id": item.strip()})
elif isinstance(item, dict):
mid = item.get("id") or item.get("name")
if mid:
out.append({"id": str(mid)})
return out
async def _http_get(url: str, *, headers: dict[str, str], timeout: float) -> httpx.Response:
async with httpx.AsyncClient(timeout=timeout, headers=headers) as client:
return await client.get(url)
async def list_models() -> dict:
"""Live ``GET {base}/models`` when a key is present; otherwise curated fallback.
Never raises to the caller for missing key or upstream failure.
"""
global _models_cache
key = await _nous_api_key()
if not key:
return _fallback_payload()
now = time.monotonic()
hit = _models_cache
if hit and now - hit[0] < MODELS_CACHE_TTL_S:
return hit[1]
url = f"{nous_base_url()}/models"
headers = {
"Authorization": f"Bearer {key}",
"User-Agent": _models_user_agent(),
"Accept": "application/json",
}
try:
resp = await _http_get(url, headers=headers, timeout=MODELS_TIMEOUT_S)
resp.raise_for_status()
models = _parse_models_payload(resp.json())
if not models:
return _fallback_payload()
payload = {"source": "live", "models": models}
_models_cache = (now, payload)
return payload
except Exception:
return _fallback_payload()

View file

@ -1,713 +0,0 @@
"""Data source ingestors — fetch from external APIs and push to NATS."""
from __future__ import annotations
import html
import io
import json
import logging
import os
import re
import time
import zipfile
from datetime import datetime, timedelta, timezone
from email.utils import parsedate_to_datetime
import httpx
import feedparser
import nats
from config import NATS_URL, OSINT_USER_AGENT
from upstream_cache import rss_cache
logger = logging.getLogger("osint.sources")
def _parse_rfc822(date_str: object) -> str | None:
"""Parse RFC-822 date string from feedparser entries."""
if not isinstance(date_str, str):
return None
try:
return parsedate_to_datetime(date_str).astimezone(timezone.utc).isoformat()
except (ValueError, TypeError):
return None
NATS_URLS = NATS_URL
_nc = None
async def _jetstream():
"""Reuse one NATS connection across publishes (no connect/close per event)."""
global _nc
if _nc is None or _nc.is_closed:
_nc = await nats.connect(NATS_URLS)
return _nc.jetstream()
async def publish_event(subject: str, event: dict):
"""Publish an event to NATS JetStream."""
js = await _jetstream()
await js.publish(subject, json.dumps(event).encode())
logger.debug("Published event to %s", subject)
def event_dedup_key(msg: dict) -> str | None:
"""Natural key for generic events. URL when present; else None (always insert)."""
url = msg.get("url")
if not isinstance(url, str):
return None
url = url.strip()
return url or None
async def existing_event_urls(urls: list[str]) -> set[str]:
"""URLs already claimed in event_dedup. Empty input -> empty set."""
if not urls:
return set()
from sqlalchemy import select
from database import async_session
from models import event_dedup as event_dedup_table
async with async_session() as session:
result = await session.execute(
select(event_dedup_table.c.url).where(event_dedup_table.c.url.in_(urls))
)
return {row[0] for row in result}
async def _publish_unknown(subject: str, events: list[dict]) -> int:
"""Publish only events whose URL is not already in event_dedup."""
keys = [event_dedup_key(e) for e in events]
known = await existing_event_urls([k for k in keys if k])
published = 0
for event, key in zip(events, keys):
if key and key in known:
continue
await publish_event(subject, event)
published += 1
return published
def _ua_headers() -> dict[str, str]:
return {"User-Agent": OSINT_USER_AGENT}
# ─── RSS Feed Ingestor ──────────────────────────────────────────────────
async def ingest_rss_feed(feed_url: str, source_id: str | None = None):
"""Fetch and parse an RSS feed, publish items to NATS."""
text = rss_cache.get(feed_url)
if text is None:
async with httpx.AsyncClient(timeout=30, headers=_ua_headers()) as client:
resp = await client.get(feed_url)
resp.raise_for_status()
text = resp.text
rss_cache[feed_url] = text
feed = feedparser.parse(text)
count = 0
for entry in feed.entries[:100]: # max 100 per run
event = {
"source_type": "rss",
"title": entry.get("title"),
"body": entry.get("summary") or entry.get("description"),
"url": entry.get("link"),
"source_timestamp": _parse_rfc822(entry.get("published"))
or datetime.now(timezone.utc).isoformat(),
"tags": [t.get("term") for t in entry.get("tags", []) if t.get("term")],
"raw": {
"feed_url": feed_url,
"feed_title": feed.feed.get("title"),
"author": entry.get("author"),
"categories": [c.get("term") for c in entry.get("categories", [])],
},
}
await publish_event("events.rss", event)
count += 1
logger.info("Ingested %d items from RSS feed %s", count, feed_url)
return count
# ─── GDELT 2.0 DOC API ──────────────────────────────────────────────────
GDELT_API = "https://api.gdeltproject.org/api/v2/doc/doc"
GDELT_DEFAULT_QUERY = '(unrest OR protest OR outage OR cyber OR "power outage")'
def gdelt_params(query: str = "", max_articles: int = 50) -> dict[str, str]:
"""DOC 2.0 query string (not the retired gdeltv2 ``search`` param)."""
q = (query or "").strip() or GDELT_DEFAULT_QUERY
return {
"query": q,
"mode": "ArtList",
"format": "json",
"maxrecords": str(int(max_articles)),
"timespan": "1d",
}
# 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:
return datetime.strptime(value[:15], "%Y%m%dT%H%M%S").replace(
tzinfo=timezone.utc
).isoformat()
except ValueError:
pass
return datetime.now(timezone.utc).isoformat()
def parse_gdelt_articles(data: dict) -> list[dict]:
events = []
for article in data.get("articles") or []:
if not isinstance(article, dict):
continue
url = article.get("url")
if not url:
continue
events.append({
"source_type": "gdel-t2",
"title": article.get("title"),
"body": article.get("domain") or article.get("language"),
"url": url,
"location_name": article.get("sourcecountry"),
"source_timestamp": _parse_gdelt_seendate(article.get("seendate")),
"tags": [t for t in (article.get("language"), article.get("sourcecountry")) if t],
"raw": article,
})
return events
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)
async with httpx.AsyncClient(
timeout=60, headers=_ua_headers(), follow_redirects=True,
) as client:
try:
resp = await client.get(GDELT_API, params=params)
except httpx.TransportError as exc:
# gdeltproject.org certs have expired in the wild; HTTP fallback.
# 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)
logger.info("Ingested %d articles from GDELT", len(events))
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"<PAGE_TITLE>(.*?)</PAGE_TITLE>", re.DOTALL)
_PAGE_PUB_TS_RE = re.compile(r"<PAGE_PRECISEPUBTIMESTAMP>(\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:
tone_float = float(tone)
return max(-1.0, min(1.0, tone_float / 4249.0)) # GDELT tone range
except (ValueError, TypeError):
return None
# ─── Earthquake Ingestor (USGS) ─────────────────────────────────────────
USGS_API = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson"
def parse_usgs_feature(feature: dict) -> dict:
"""Map one USGS GeoJSON feature, keeping the stable event id."""
props = feature.get("properties") or {}
geometry = (feature.get("geometry") or {}).get("coordinates") or []
usgs_id = feature.get("id")
url = props.get("url") or (
f"https://earthquake.usgs.gov/earthquakes/eventpage/{usgs_id}" if usgs_id else None
)
raw = dict(props)
raw["usgs_id"] = usgs_id
return {
"source_type": "earthquake",
"title": props.get("title"),
"body": props.get("description"),
"url": url,
"location_lat": geometry[1] if len(geometry) > 1 else None,
"location_lon": geometry[0] if len(geometry) > 0 else None,
"location_name": props.get("place"),
"sentiment_label": "neutral",
"tags": [f"magnitude:{props.get('mag')}"] if props.get("mag") else [],
"source_timestamp": (
datetime.utcfromtimestamp(props.get("time", 0) / 1000)
.replace(tzinfo=timezone.utc)
.isoformat()
),
"raw": raw,
}
async def ingest_earthquakes():
"""Fetch recent earthquakes from USGS."""
async with httpx.AsyncClient(timeout=30, headers=_ua_headers()) as client:
resp = await client.get(USGS_API)
resp.raise_for_status()
data = resp.json()
count = 0
for feature in data.get("features", []):
event = parse_usgs_feature(feature)
await publish_event("events.earthquake", event)
count += 1
logger.info("Ingested %d earthquake events", count)
return count
# ─── NASA EONET v3 ──────────────────────────────────────────────────────
EONET_API = "https://eonet.gsfc.nasa.gov/api/v3/events"
def parse_eonet_events(payload: dict) -> list[dict]:
events = []
for item in payload.get("events") or []:
if not isinstance(item, dict):
continue
eid = item.get("id")
geoms = item.get("geometry") or []
point = None
for g in geoms:
if isinstance(g, dict) and g.get("type") == "Point":
point = g
if point is None:
continue
coords = point.get("coordinates") or []
if len(coords) < 2:
continue
lon, lat = float(coords[0]), float(coords[1])
cats = item.get("categories") or []
tags = []
for c in cats:
if isinstance(c, dict) and c.get("id"):
tags.append(str(c["id"]))
url = item.get("link") or (f"https://eonet.gsfc.nasa.gov/api/v3/events/{eid}" if eid else None)
ts = point.get("date") or datetime.now(timezone.utc).isoformat()
events.append({
"source_type": "disaster",
"title": item.get("title"),
"body": ", ".join(tags) if tags else None,
"url": url,
"location_lat": lat,
"location_lon": lon,
"location_name": item.get("title"),
"tags": tags,
"source_timestamp": ts,
"raw": {**item, "eonet_id": eid},
})
return events
async def ingest_eonet():
"""Volcanoes, storms, floods, drought — gaps USGS/FIRMS don't cover."""
async with httpx.AsyncClient(timeout=30, headers=_ua_headers()) as client:
resp = await client.get(EONET_API, params={"status": "open", "limit": 100})
resp.raise_for_status()
data = resp.json()
events = parse_eonet_events(data if isinstance(data, dict) else {})
published = await _publish_unknown("events.disaster", events)
logger.info("Ingested %d EONET events (%d already known)", published, len(events) - published)
return published
# ─── CISA KEV ───────────────────────────────────────────────────────────
CISA_KEV_API = (
"https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json"
)
def parse_cisa_kev(payload: dict) -> list[dict]:
events = []
for row in payload.get("vulnerabilities") or []:
if not isinstance(row, dict):
continue
cve = row.get("cveID")
if not cve:
continue
title = row.get("vulnerabilityName") or cve
vendor = row.get("vendorProject") or ""
product = row.get("product") or ""
events.append({
"source_type": "disaster",
"title": f"{cve}: {title}",
"body": row.get("shortDescription") or f"{vendor} {product}".strip(),
"url": f"https://nvd.nist.gov/vuln/detail/{cve}",
"location_lat": None,
"location_lon": None,
"location_name": None,
"tags": ["cisa-kev", cve, "ransomware" if row.get("knownRansomwareCampaignUse") == "Known" else None],
"source_timestamp": row.get("dateAdded") or datetime.now(timezone.utc).isoformat(),
"raw": {**row, "cveID": cve},
})
events[-1]["tags"] = [t for t in events[-1]["tags"] if t]
return events
async def ingest_cisa_kev():
"""Exploited-in-the-wild CVEs. No fake map coords — ticker/events only."""
async with httpx.AsyncClient(timeout=30, headers=_ua_headers(), follow_redirects=True) as client:
resp = await client.get(CISA_KEV_API)
resp.raise_for_status()
data = resp.json()
events = parse_cisa_kev(data if isinstance(data, dict) else {})
published = await _publish_unknown("events.disaster", events)
logger.info("Ingested %d CISA KEV rows (%d already known)", published, len(events) - published)
return published
# ─── Social Signals (Twitter/X-like placeholder) ────────────────────────
async def ingest_social_signals(query: str = "", max_items: int = 50):
"""Placeholder for social media signal ingestion.
In production, this would connect to Twitter API, Reddit, NewsAPI, etc.
For now, it publishes a heartbeat to signal the pipeline is active.
"""
event = {
"source_type": "social",
"title": f"Social signal scan: {query}",
"body": f"Scanned for '{query}' — placeholder connector",
"source_timestamp": datetime.now(timezone.utc).isoformat(),
"tags": [query] if query else [],
"raw": {"query": query, "max_items": max_items, "connector": "placeholder"},
}
await publish_event("events.social", event)
logger.info("Social signal scan complete for '%s'", query)
return 1

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

View file

@ -1,60 +0,0 @@
.marker-cluster-small {
background-color: rgba(181, 226, 140, 0.6);
}
.marker-cluster-small div {
background-color: rgba(110, 204, 57, 0.6);
}
.marker-cluster-medium {
background-color: rgba(241, 211, 87, 0.6);
}
.marker-cluster-medium div {
background-color: rgba(240, 194, 12, 0.6);
}
.marker-cluster-large {
background-color: rgba(253, 156, 115, 0.6);
}
.marker-cluster-large div {
background-color: rgba(241, 128, 23, 0.6);
}
/* IE 6-8 fallback colors */
.leaflet-oldie .marker-cluster-small {
background-color: rgb(181, 226, 140);
}
.leaflet-oldie .marker-cluster-small div {
background-color: rgb(110, 204, 57);
}
.leaflet-oldie .marker-cluster-medium {
background-color: rgb(241, 211, 87);
}
.leaflet-oldie .marker-cluster-medium div {
background-color: rgb(240, 194, 12);
}
.leaflet-oldie .marker-cluster-large {
background-color: rgb(253, 156, 115);
}
.leaflet-oldie .marker-cluster-large div {
background-color: rgb(241, 128, 23);
}
.marker-cluster {
background-clip: padding-box;
border-radius: 20px;
}
.marker-cluster div {
width: 30px;
height: 30px;
margin-left: 5px;
margin-top: 5px;
text-align: center;
border-radius: 15px;
font: 12px "Helvetica Neue", Arial, Helvetica, sans-serif;
}
.marker-cluster span {
line-height: 30px;
}

View file

@ -1,14 +0,0 @@
.leaflet-cluster-anim .leaflet-marker-icon, .leaflet-cluster-anim .leaflet-marker-shadow {
-webkit-transition: -webkit-transform 0.3s ease-out, opacity 0.3s ease-in;
-moz-transition: -moz-transform 0.3s ease-out, opacity 0.3s ease-in;
-o-transition: -o-transform 0.3s ease-out, opacity 0.3s ease-in;
transition: transform 0.3s ease-out, opacity 0.3s ease-in;
}
.leaflet-cluster-spider-leg {
/* stroke-dashoffset (duration and function) should match with leaflet-marker-icon transform in order to track it exactly */
-webkit-transition: -webkit-stroke-dashoffset 0.3s ease-out, -webkit-stroke-opacity 0.3s ease-in;
-moz-transition: -moz-stroke-dashoffset 0.3s ease-out, -moz-stroke-opacity 0.3s ease-in;
-o-transition: -o-stroke-dashoffset 0.3s ease-out, -o-stroke-opacity 0.3s ease-in;
transition: stroke-dashoffset 0.3s ease-out, stroke-opacity 0.3s ease-in;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 696 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 618 B

View file

@ -1,661 +0,0 @@
/* required styles */
.leaflet-pane,
.leaflet-tile,
.leaflet-marker-icon,
.leaflet-marker-shadow,
.leaflet-tile-container,
.leaflet-pane > svg,
.leaflet-pane > canvas,
.leaflet-zoom-box,
.leaflet-image-layer,
.leaflet-layer {
position: absolute;
left: 0;
top: 0;
}
.leaflet-container {
overflow: hidden;
}
.leaflet-tile,
.leaflet-marker-icon,
.leaflet-marker-shadow {
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
-webkit-user-drag: none;
}
/* Prevents IE11 from highlighting tiles in blue */
.leaflet-tile::selection {
background: transparent;
}
/* Safari renders non-retina tile on retina better with this, but Chrome is worse */
.leaflet-safari .leaflet-tile {
image-rendering: -webkit-optimize-contrast;
}
/* hack that prevents hw layers "stretching" when loading new tiles */
.leaflet-safari .leaflet-tile-container {
width: 1600px;
height: 1600px;
-webkit-transform-origin: 0 0;
}
.leaflet-marker-icon,
.leaflet-marker-shadow {
display: block;
}
/* .leaflet-container svg: reset svg max-width decleration shipped in Joomla! (joomla.org) 3.x */
/* .leaflet-container img: map is broken in FF if you have max-width: 100% on tiles */
.leaflet-container .leaflet-overlay-pane svg {
max-width: none !important;
max-height: none !important;
}
.leaflet-container .leaflet-marker-pane img,
.leaflet-container .leaflet-shadow-pane img,
.leaflet-container .leaflet-tile-pane img,
.leaflet-container img.leaflet-image-layer,
.leaflet-container .leaflet-tile {
max-width: none !important;
max-height: none !important;
width: auto;
padding: 0;
}
.leaflet-container img.leaflet-tile {
/* See: https://bugs.chromium.org/p/chromium/issues/detail?id=600120 */
mix-blend-mode: plus-lighter;
}
.leaflet-container.leaflet-touch-zoom {
-ms-touch-action: pan-x pan-y;
touch-action: pan-x pan-y;
}
.leaflet-container.leaflet-touch-drag {
-ms-touch-action: pinch-zoom;
/* Fallback for FF which doesn't support pinch-zoom */
touch-action: none;
touch-action: pinch-zoom;
}
.leaflet-container.leaflet-touch-drag.leaflet-touch-zoom {
-ms-touch-action: none;
touch-action: none;
}
.leaflet-container {
-webkit-tap-highlight-color: transparent;
}
.leaflet-container a {
-webkit-tap-highlight-color: rgba(51, 181, 229, 0.4);
}
.leaflet-tile {
filter: inherit;
visibility: hidden;
}
.leaflet-tile-loaded {
visibility: inherit;
}
.leaflet-zoom-box {
width: 0;
height: 0;
-moz-box-sizing: border-box;
box-sizing: border-box;
z-index: 800;
}
/* workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=888319 */
.leaflet-overlay-pane svg {
-moz-user-select: none;
}
.leaflet-pane { z-index: 400; }
.leaflet-tile-pane { z-index: 200; }
.leaflet-overlay-pane { z-index: 400; }
.leaflet-shadow-pane { z-index: 500; }
.leaflet-marker-pane { z-index: 600; }
.leaflet-tooltip-pane { z-index: 650; }
.leaflet-popup-pane { z-index: 700; }
.leaflet-map-pane canvas { z-index: 100; }
.leaflet-map-pane svg { z-index: 200; }
.leaflet-vml-shape {
width: 1px;
height: 1px;
}
.lvml {
behavior: url(#default#VML);
display: inline-block;
position: absolute;
}
/* control positioning */
.leaflet-control {
position: relative;
z-index: 800;
pointer-events: visiblePainted; /* IE 9-10 doesn't have auto */
pointer-events: auto;
}
.leaflet-top,
.leaflet-bottom {
position: absolute;
z-index: 1000;
pointer-events: none;
}
.leaflet-top {
top: 0;
}
.leaflet-right {
right: 0;
}
.leaflet-bottom {
bottom: 0;
}
.leaflet-left {
left: 0;
}
.leaflet-control {
float: left;
clear: both;
}
.leaflet-right .leaflet-control {
float: right;
}
.leaflet-top .leaflet-control {
margin-top: 10px;
}
.leaflet-bottom .leaflet-control {
margin-bottom: 10px;
}
.leaflet-left .leaflet-control {
margin-left: 10px;
}
.leaflet-right .leaflet-control {
margin-right: 10px;
}
/* zoom and fade animations */
.leaflet-fade-anim .leaflet-popup {
opacity: 0;
-webkit-transition: opacity 0.2s linear;
-moz-transition: opacity 0.2s linear;
transition: opacity 0.2s linear;
}
.leaflet-fade-anim .leaflet-map-pane .leaflet-popup {
opacity: 1;
}
.leaflet-zoom-animated {
-webkit-transform-origin: 0 0;
-ms-transform-origin: 0 0;
transform-origin: 0 0;
}
svg.leaflet-zoom-animated {
will-change: transform;
}
.leaflet-zoom-anim .leaflet-zoom-animated {
-webkit-transition: -webkit-transform 0.25s cubic-bezier(0,0,0.25,1);
-moz-transition: -moz-transform 0.25s cubic-bezier(0,0,0.25,1);
transition: transform 0.25s cubic-bezier(0,0,0.25,1);
}
.leaflet-zoom-anim .leaflet-tile,
.leaflet-pan-anim .leaflet-tile {
-webkit-transition: none;
-moz-transition: none;
transition: none;
}
.leaflet-zoom-anim .leaflet-zoom-hide {
visibility: hidden;
}
/* cursors */
.leaflet-interactive {
cursor: pointer;
}
.leaflet-grab {
cursor: -webkit-grab;
cursor: -moz-grab;
cursor: grab;
}
.leaflet-crosshair,
.leaflet-crosshair .leaflet-interactive {
cursor: crosshair;
}
.leaflet-popup-pane,
.leaflet-control {
cursor: auto;
}
.leaflet-dragging .leaflet-grab,
.leaflet-dragging .leaflet-grab .leaflet-interactive,
.leaflet-dragging .leaflet-marker-draggable {
cursor: move;
cursor: -webkit-grabbing;
cursor: -moz-grabbing;
cursor: grabbing;
}
/* marker & overlays interactivity */
.leaflet-marker-icon,
.leaflet-marker-shadow,
.leaflet-image-layer,
.leaflet-pane > svg path,
.leaflet-tile-container {
pointer-events: none;
}
.leaflet-marker-icon.leaflet-interactive,
.leaflet-image-layer.leaflet-interactive,
.leaflet-pane > svg path.leaflet-interactive,
svg.leaflet-image-layer.leaflet-interactive path {
pointer-events: visiblePainted; /* IE 9-10 doesn't have auto */
pointer-events: auto;
}
/* visual tweaks */
.leaflet-container {
background: #ddd;
outline-offset: 1px;
}
.leaflet-container a {
color: #0078A8;
}
.leaflet-zoom-box {
border: 2px dotted #38f;
background: rgba(255,255,255,0.5);
}
/* general typography */
.leaflet-container {
font-family: "Helvetica Neue", Arial, Helvetica, sans-serif;
font-size: 12px;
font-size: 0.75rem;
line-height: 1.5;
}
/* general toolbar styles */
.leaflet-bar {
box-shadow: 0 1px 5px rgba(0,0,0,0.65);
border-radius: 4px;
}
.leaflet-bar a {
background-color: #fff;
border-bottom: 1px solid #ccc;
width: 26px;
height: 26px;
line-height: 26px;
display: block;
text-align: center;
text-decoration: none;
color: black;
}
.leaflet-bar a,
.leaflet-control-layers-toggle {
background-position: 50% 50%;
background-repeat: no-repeat;
display: block;
}
.leaflet-bar a:hover,
.leaflet-bar a:focus {
background-color: #f4f4f4;
}
.leaflet-bar a:first-child {
border-top-left-radius: 4px;
border-top-right-radius: 4px;
}
.leaflet-bar a:last-child {
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
border-bottom: none;
}
.leaflet-bar a.leaflet-disabled {
cursor: default;
background-color: #f4f4f4;
color: #bbb;
}
.leaflet-touch .leaflet-bar a {
width: 30px;
height: 30px;
line-height: 30px;
}
.leaflet-touch .leaflet-bar a:first-child {
border-top-left-radius: 2px;
border-top-right-radius: 2px;
}
.leaflet-touch .leaflet-bar a:last-child {
border-bottom-left-radius: 2px;
border-bottom-right-radius: 2px;
}
/* zoom control */
.leaflet-control-zoom-in,
.leaflet-control-zoom-out {
font: bold 18px 'Lucida Console', Monaco, monospace;
text-indent: 1px;
}
.leaflet-touch .leaflet-control-zoom-in, .leaflet-touch .leaflet-control-zoom-out {
font-size: 22px;
}
/* layers control */
.leaflet-control-layers {
box-shadow: 0 1px 5px rgba(0,0,0,0.4);
background: #fff;
border-radius: 5px;
}
.leaflet-control-layers-toggle {
background-image: url(images/layers.png);
width: 36px;
height: 36px;
}
.leaflet-retina .leaflet-control-layers-toggle {
background-image: url(images/layers-2x.png);
background-size: 26px 26px;
}
.leaflet-touch .leaflet-control-layers-toggle {
width: 44px;
height: 44px;
}
.leaflet-control-layers .leaflet-control-layers-list,
.leaflet-control-layers-expanded .leaflet-control-layers-toggle {
display: none;
}
.leaflet-control-layers-expanded .leaflet-control-layers-list {
display: block;
position: relative;
}
.leaflet-control-layers-expanded {
padding: 6px 10px 6px 6px;
color: #333;
background: #fff;
}
.leaflet-control-layers-scrollbar {
overflow-y: scroll;
overflow-x: hidden;
padding-right: 5px;
}
.leaflet-control-layers-selector {
margin-top: 2px;
position: relative;
top: 1px;
}
.leaflet-control-layers label {
display: block;
font-size: 13px;
font-size: 1.08333em;
}
.leaflet-control-layers-separator {
height: 0;
border-top: 1px solid #ddd;
margin: 5px -10px 5px -6px;
}
/* Default icon URLs */
.leaflet-default-icon-path { /* used only in path-guessing heuristic, see L.Icon.Default */
background-image: url(images/marker-icon.png);
}
/* attribution and scale controls */
.leaflet-container .leaflet-control-attribution {
background: #fff;
background: rgba(255, 255, 255, 0.8);
margin: 0;
}
.leaflet-control-attribution,
.leaflet-control-scale-line {
padding: 0 5px;
color: #333;
line-height: 1.4;
}
.leaflet-control-attribution a {
text-decoration: none;
}
.leaflet-control-attribution a:hover,
.leaflet-control-attribution a:focus {
text-decoration: underline;
}
.leaflet-attribution-flag {
display: inline !important;
vertical-align: baseline !important;
width: 1em;
height: 0.6669em;
}
.leaflet-left .leaflet-control-scale {
margin-left: 5px;
}
.leaflet-bottom .leaflet-control-scale {
margin-bottom: 5px;
}
.leaflet-control-scale-line {
border: 2px solid #777;
border-top: none;
line-height: 1.1;
padding: 2px 5px 1px;
white-space: nowrap;
-moz-box-sizing: border-box;
box-sizing: border-box;
background: rgba(255, 255, 255, 0.8);
text-shadow: 1px 1px #fff;
}
.leaflet-control-scale-line:not(:first-child) {
border-top: 2px solid #777;
border-bottom: none;
margin-top: -2px;
}
.leaflet-control-scale-line:not(:first-child):not(:last-child) {
border-bottom: 2px solid #777;
}
.leaflet-touch .leaflet-control-attribution,
.leaflet-touch .leaflet-control-layers,
.leaflet-touch .leaflet-bar {
box-shadow: none;
}
.leaflet-touch .leaflet-control-layers,
.leaflet-touch .leaflet-bar {
border: 2px solid rgba(0,0,0,0.2);
background-clip: padding-box;
}
/* popup */
.leaflet-popup {
position: absolute;
text-align: center;
margin-bottom: 20px;
}
.leaflet-popup-content-wrapper {
padding: 1px;
text-align: left;
border-radius: 12px;
}
.leaflet-popup-content {
margin: 13px 24px 13px 20px;
line-height: 1.3;
font-size: 13px;
font-size: 1.08333em;
min-height: 1px;
}
.leaflet-popup-content p {
margin: 17px 0;
margin: 1.3em 0;
}
.leaflet-popup-tip-container {
width: 40px;
height: 20px;
position: absolute;
left: 50%;
margin-top: -1px;
margin-left: -20px;
overflow: hidden;
pointer-events: none;
}
.leaflet-popup-tip {
width: 17px;
height: 17px;
padding: 1px;
margin: -10px auto 0;
pointer-events: auto;
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
}
.leaflet-popup-content-wrapper,
.leaflet-popup-tip {
background: white;
color: #333;
box-shadow: 0 3px 14px rgba(0,0,0,0.4);
}
.leaflet-container a.leaflet-popup-close-button {
position: absolute;
top: 0;
right: 0;
border: none;
text-align: center;
width: 24px;
height: 24px;
font: 16px/24px Tahoma, Verdana, sans-serif;
color: #757575;
text-decoration: none;
background: transparent;
}
.leaflet-container a.leaflet-popup-close-button:hover,
.leaflet-container a.leaflet-popup-close-button:focus {
color: #585858;
}
.leaflet-popup-scrolled {
overflow: auto;
}
.leaflet-oldie .leaflet-popup-content-wrapper {
-ms-zoom: 1;
}
.leaflet-oldie .leaflet-popup-tip {
width: 24px;
margin: 0 auto;
-ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678)";
filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678);
}
.leaflet-oldie .leaflet-control-zoom,
.leaflet-oldie .leaflet-control-layers,
.leaflet-oldie .leaflet-popup-content-wrapper,
.leaflet-oldie .leaflet-popup-tip {
border: 1px solid #999;
}
/* div icon */
.leaflet-div-icon {
background: #fff;
border: 1px solid #666;
}
/* Tooltip */
/* Base styles for the element that has a tooltip */
.leaflet-tooltip {
position: absolute;
padding: 6px;
background-color: #fff;
border: 1px solid #fff;
border-radius: 3px;
color: #222;
white-space: nowrap;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
pointer-events: none;
box-shadow: 0 1px 3px rgba(0,0,0,0.4);
}
.leaflet-tooltip.leaflet-interactive {
cursor: pointer;
pointer-events: auto;
}
.leaflet-tooltip-top:before,
.leaflet-tooltip-bottom:before,
.leaflet-tooltip-left:before,
.leaflet-tooltip-right:before {
position: absolute;
pointer-events: none;
border: 6px solid transparent;
background: transparent;
content: "";
}
/* Directions */
.leaflet-tooltip-bottom {
margin-top: 6px;
}
.leaflet-tooltip-top {
margin-top: -6px;
}
.leaflet-tooltip-bottom:before,
.leaflet-tooltip-top:before {
left: 50%;
margin-left: -6px;
}
.leaflet-tooltip-top:before {
bottom: 0;
margin-bottom: -12px;
border-top-color: #fff;
}
.leaflet-tooltip-bottom:before {
top: 0;
margin-top: -12px;
margin-left: -6px;
border-bottom-color: #fff;
}
.leaflet-tooltip-left {
margin-left: -6px;
}
.leaflet-tooltip-right {
margin-left: 6px;
}
.leaflet-tooltip-left:before,
.leaflet-tooltip-right:before {
top: 50%;
margin-top: -6px;
}
.leaflet-tooltip-left:before {
right: 0;
margin-right: -12px;
border-left-color: #fff;
}
.leaflet-tooltip-right:before {
left: 0;
margin-left: -12px;
border-right-color: #fff;
}
/* Printing */
@media print {
/* Prevent printers from removing background-images of controls. */
.leaflet-control {
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
}

View file

@ -1,11 +0,0 @@
/*
(c) 2014, Vladimir Agafonkin
simpleheat, a tiny JavaScript library for drawing heatmaps with Canvas
https://github.com/mourner/simpleheat
*/
!function(){"use strict";function t(i){return this instanceof t?(this._canvas=i="string"==typeof i?document.getElementById(i):i,this._ctx=i.getContext("2d"),this._width=i.width,this._height=i.height,this._max=1,void this.clear()):new t(i)}t.prototype={defaultRadius:25,defaultGradient:{.4:"blue",.6:"cyan",.7:"lime",.8:"yellow",1:"red"},data:function(t,i){return this._data=t,this},max:function(t){return this._max=t,this},add:function(t){return this._data.push(t),this},clear:function(){return this._data=[],this},radius:function(t,i){i=i||15;var a=this._circle=document.createElement("canvas"),s=a.getContext("2d"),e=this._r=t+i;return a.width=a.height=2*e,s.shadowOffsetX=s.shadowOffsetY=200,s.shadowBlur=i,s.shadowColor="black",s.beginPath(),s.arc(e-200,e-200,t,0,2*Math.PI,!0),s.closePath(),s.fill(),this},gradient:function(t){var i=document.createElement("canvas"),a=i.getContext("2d"),s=a.createLinearGradient(0,0,0,256);i.width=1,i.height=256;for(var e in t)s.addColorStop(e,t[e]);return a.fillStyle=s,a.fillRect(0,0,1,256),this._grad=a.getImageData(0,0,1,256).data,this},draw:function(t){this._circle||this.radius(this.defaultRadius),this._grad||this.gradient(this.defaultGradient);var i=this._ctx;i.clearRect(0,0,this._width,this._height);for(var a,s=0,e=this._data.length;e>s;s++)a=this._data[s],i.globalAlpha=Math.max(a[2]/this._max,t||.05),i.drawImage(this._circle,a[0]-this._r,a[1]-this._r);var n=i.getImageData(0,0,this._width,this._height);return this._colorize(n.data,this._grad),i.putImageData(n,0,0),this},_colorize:function(t,i){for(var a,s=3,e=t.length;e>s;s+=4)a=4*t[s],a&&(t[s-3]=i[a],t[s-2]=i[a+1],t[s-1]=i[a+2])}},window.simpleheat=t}(),/*
(c) 2014, Vladimir Agafonkin
Leaflet.heat, a tiny and fast heatmap plugin for Leaflet.
https://github.com/Leaflet/Leaflet.heat
*/
L.HeatLayer=(L.Layer?L.Layer:L.Class).extend({initialize:function(t,i){this._latlngs=t,L.setOptions(this,i)},setLatLngs:function(t){return this._latlngs=t,this.redraw()},addLatLng:function(t){return this._latlngs.push(t),this.redraw()},setOptions:function(t){return L.setOptions(this,t),this._heat&&this._updateOptions(),this.redraw()},redraw:function(){return!this._heat||this._frame||this._map._animating||(this._frame=L.Util.requestAnimFrame(this._redraw,this)),this},onAdd:function(t){this._map=t,this._canvas||this._initCanvas(),t._panes.overlayPane.appendChild(this._canvas),t.on("moveend",this._reset,this),t.options.zoomAnimation&&L.Browser.any3d&&t.on("zoomanim",this._animateZoom,this),this._reset()},onRemove:function(t){t.getPanes().overlayPane.removeChild(this._canvas),t.off("moveend",this._reset,this),t.options.zoomAnimation&&t.off("zoomanim",this._animateZoom,this)},addTo:function(t){return t.addLayer(this),this},_initCanvas:function(){var t=this._canvas=L.DomUtil.create("canvas","leaflet-heatmap-layer leaflet-layer"),i=L.DomUtil.testProp(["transformOrigin","WebkitTransformOrigin","msTransformOrigin"]);t.style[i]="50% 50%";var a=this._map.getSize();t.width=a.x,t.height=a.y;var s=this._map.options.zoomAnimation&&L.Browser.any3d;L.DomUtil.addClass(t,"leaflet-zoom-"+(s?"animated":"hide")),this._heat=simpleheat(t),this._updateOptions()},_updateOptions:function(){this._heat.radius(this.options.radius||this._heat.defaultRadius,this.options.blur),this.options.gradient&&this._heat.gradient(this.options.gradient),this.options.max&&this._heat.max(this.options.max)},_reset:function(){var t=this._map.containerPointToLayerPoint([0,0]);L.DomUtil.setPosition(this._canvas,t);var i=this._map.getSize();this._heat._width!==i.x&&(this._canvas.width=this._heat._width=i.x),this._heat._height!==i.y&&(this._canvas.height=this._heat._height=i.y),this._redraw()},_redraw:function(){var t,i,a,s,e,n,h,o,r,d=[],_=this._heat._r,l=this._map.getSize(),m=new L.Bounds(L.point([-_,-_]),l.add([_,_])),c=void 0===this.options.max?1:this.options.max,u=void 0===this.options.maxZoom?this._map.getMaxZoom():this.options.maxZoom,f=1/Math.pow(2,Math.max(0,Math.min(u-this._map.getZoom(),12))),g=_/2,p=[],v=this._map._getMapPanePos(),w=v.x%g,y=v.y%g;for(t=0,i=this._latlngs.length;i>t;t++)if(a=this._map.latLngToContainerPoint(this._latlngs[t]),m.contains(a)){e=Math.floor((a.x-w)/g)+2,n=Math.floor((a.y-y)/g)+2;var x=void 0!==this._latlngs[t].alt?this._latlngs[t].alt:void 0!==this._latlngs[t][2]?+this._latlngs[t][2]:1;r=x*f,p[n]=p[n]||[],s=p[n][e],s?(s[0]=(s[0]*s[2]+a.x*r)/(s[2]+r),s[1]=(s[1]*s[2]+a.y*r)/(s[2]+r),s[2]+=r):p[n][e]=[a.x,a.y,r]}for(t=0,i=p.length;i>t;t++)if(p[t])for(h=0,o=p[t].length;o>h;h++)s=p[t][h],s&&d.push([Math.round(s[0]),Math.round(s[1]),Math.min(s[2],c)]);this._heat.data(d).draw(this.options.minOpacity),this._frame=null},_animateZoom:function(t){var i=this._map.getZoomScale(t.zoom),a=this._map._getCenterOffset(t.center)._multiplyBy(-i).subtract(this._map._getMapPanePos());L.DomUtil.setTransform?L.DomUtil.setTransform(this._canvas,a,i):this._canvas.style[L.DomUtil.TRANSFORM]=L.DomUtil.getTranslateString(a)+" scale("+i+")"}}),L.heatLayer=function(t,i){return new L.HeatLayer(t,i)};

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -1,244 +0,0 @@
"""Timescale 1-minute track rollups for DVR playback.
Live overlays stay in memory. Historical `?timestamp=` reads the 1-minute
continuous aggregates (or an in-process downsample when the DB is down).
"""
from __future__ import annotations
import json
from datetime import datetime, timedelta, timezone
from typing import Any, Literal
from sqlalchemy import text
from database import async_session
from live_layers import parse_bbox, to_marker
TRACK_BUCKET = "1 minute"
Kind = Literal["vessel", "aircraft"]
_RAW_TABLE = {
"vessel": "vessel_positions",
"aircraft": "aircraft_positions",
}
_CAGG = {
"vessel": "vessel_tracks_1min",
"aircraft": "aircraft_tracks_1min",
}
_ID_COL = {
"vessel": "mmsi",
"aircraft": "hex",
}
# Last persist time per entity so AIS/ADS-B does not write every frame.
_last_write: dict[tuple[str, str], datetime] = {}
_MIN_WRITE_GAP = timedelta(seconds=20)
def minute_bucket(ts: datetime) -> datetime:
if ts.tzinfo is None:
ts = ts.replace(tzinfo=timezone.utc)
return ts.replace(second=0, microsecond=0)
def downsample_tracks(rows: list[dict]) -> list[dict]:
"""Last sample per id per 1-minute bucket (mirrors the CAGG)."""
last: dict[tuple[str, datetime], dict] = {}
for row in rows:
rid = str(row.get("id") or "")
ts = row.get("ts")
if not rid or not isinstance(ts, datetime):
continue
bucket = minute_bucket(ts)
key = (rid, bucket)
prev = last.get(key)
if prev is None or ts >= prev["ts"]:
last[key] = {**row, "id": rid, "bucket": bucket, "ts": ts}
out = []
for (_id, bucket), row in last.items():
out.append({
"id": row["id"],
"bucket": bucket,
"lat": row.get("lat"),
"lon": row.get("lon"),
"heading": row.get("heading"),
"speed": row.get("speed"),
"label": row.get("label"),
})
return out
def positions_at_timestamp(rows: list[dict], ts: datetime) -> list[dict]:
"""Positions whose 1-minute bucket equals floor(ts)."""
want = minute_bucket(ts)
picked = [r for r in downsample_tracks(rows) if r["bucket"] == want]
return [
to_marker(
r["id"], r.get("lat"), r.get("lon"),
heading=r.get("heading"), speed=r.get("speed"),
label=r.get("label") or r["id"],
)
for r in picked
if r.get("lat") is not None and r.get("lon") is not None
]
def parse_timestamp(value: str | datetime | None) -> datetime | None:
if value is None or value == "":
return None
if isinstance(value, datetime):
ts = value
else:
raw = str(value).strip().replace("Z", "+00:00")
ts = datetime.fromisoformat(raw)
if ts.tzinfo is None:
ts = ts.replace(tzinfo=timezone.utc)
return ts
async def record_position(kind: Kind, marker: dict, ts: datetime | None = None) -> bool:
"""Insert one sample into the raw hypertable (rate-limited)."""
vid = str(marker.get("id") or "")
lat, lon = marker.get("lat"), marker.get("lon")
if not vid or lat is None or lon is None:
return False
now = ts or datetime.now(timezone.utc)
key = (kind, vid)
prev = _last_write.get(key)
if prev is not None and now - prev < _MIN_WRITE_GAP:
return False
_last_write[key] = now
table = _RAW_TABLE[kind]
id_col = _ID_COL[kind]
extra = marker.get("extra") or {}
try:
async with async_session() as session:
await session.execute(
text(
f"""
INSERT INTO {table} ({id_col}, ts, lat, lon, heading, speed, label, extra)
VALUES (:id, :ts, :lat, :lon, :heading, :speed, :label, CAST(:extra AS jsonb))
ON CONFLICT ({id_col}, ts) DO NOTHING
"""
),
{
"id": vid,
"ts": now,
"lat": float(lat),
"lon": float(lon),
"heading": marker.get("heading"),
"speed": marker.get("speed"),
"label": marker.get("label") or vid,
"extra": json.dumps(extra),
},
)
await session.commit()
return True
except Exception:
return False
async def fetch_positions_at(
kind: Kind,
ts: datetime,
bbox: str | None = None,
limit: int = 2000,
) -> list[dict]:
"""Read the 1-minute CAGG for the bucket containing ``ts``."""
bucket = minute_bucket(ts)
table = _CAGG[kind]
id_col = _ID_COL[kind]
where = "bucket = :bucket"
params: dict[str, Any] = {"bucket": bucket, "limit": limit}
if bbox:
minlon, minlat, maxlon, maxlat = parse_bbox(bbox)
where += " AND lon BETWEEN :minlon AND :maxlon AND lat BETWEEN :minlat AND :maxlat"
params.update(minlon=minlon, minlat=minlat, maxlon=maxlon, maxlat=maxlat)
sql = f"""
SELECT {id_col} AS id, lat, lon, heading, speed, label, bucket
FROM {table}
WHERE {where}
LIMIT :limit
"""
try:
async with async_session() as session:
rows = (await session.execute(text(sql), params)).mappings().all()
points = [
to_marker(
r["id"], r["lat"], r["lon"],
heading=r["heading"], speed=r["speed"],
label=r["label"] or r["id"],
extra={"bucket": r["bucket"].isoformat() if r["bucket"] else None, "dvr": True},
)
for r in rows
if r["lat"] is not None and r["lon"] is not None
]
return points
except Exception:
return []
async def track_range() -> dict:
"""Earliest/latest buckets across both CAGGs — slider bounds."""
try:
async with async_session() as session:
row = (await session.execute(text(
"""
SELECT min(t) AS tmin, max(t) AS tmax FROM (
SELECT min(bucket) AS t FROM vessel_tracks_1min
UNION ALL SELECT max(bucket) FROM vessel_tracks_1min
UNION ALL SELECT min(bucket) FROM aircraft_tracks_1min
UNION ALL SELECT max(bucket) FROM aircraft_tracks_1min
UNION ALL SELECT min(poll_at) FROM vessels
UNION ALL SELECT max(poll_at) FROM vessels
) s
"""
))).mappings().first()
if not row or row["tmin"] is None:
now = datetime.now(timezone.utc).replace(second=0, microsecond=0)
return {"min": (now - timedelta(hours=6)).isoformat(), "max": now.isoformat()}
return {
"min": row["tmin"].isoformat(),
"max": row["tmax"].isoformat(),
}
except Exception:
now = datetime.now(timezone.utc).replace(second=0, microsecond=0)
return {"min": (now - timedelta(hours=6)).isoformat(), "max": now.isoformat()}
async def recent_markers(kind: Kind, limit: int = 2000) -> list[dict]:
"""Latest raw sample per id — used when in-process last-known is empty."""
table = _RAW_TABLE[kind]
id_col = _ID_COL[kind]
sql = f"""
SELECT DISTINCT ON ({id_col})
{id_col} AS id, lat, lon, heading, speed, label, extra
FROM {table}
WHERE ts > now() - interval '15 minutes'
ORDER BY {id_col}, ts DESC
LIMIT :limit
"""
try:
async with async_session() as session:
rows = (await session.execute(text(sql), {"limit": limit})).mappings().all()
out = []
for r in rows:
extra = r.get("extra") or {}
if isinstance(extra, str):
try:
extra = json.loads(extra)
except (TypeError, ValueError):
extra = {}
m = to_marker(
r["id"], r["lat"], r["lon"],
heading=r["heading"], speed=r["speed"],
label=r["label"] or r["id"],
extra=extra if isinstance(extra, dict) else {},
)
if m.get("lat") is not None and m.get("lon") is not None:
out.append(m)
return out
except Exception:
return []

View file

@ -1,11 +0,0 @@
"""In-process TTL caches for chatty upstreams (FIRMS, RSS). No Redis."""
from __future__ import annotations
from cachetools import TTLCache
# FIRMS NRT updates every ~5–10 min; 5 min / 100 keys is enough for bbox×dataset.
firms_cache: TTLCache = TTLCache(maxsize=100, ttl=300)
# News RSS: 1 minute is enough to absorb dashboard double-clicks / retries.
rss_cache: TTLCache = TTLCache(maxsize=100, ttl=60)

View file

@ -1,671 +0,0 @@
"""VesselAPI REST poller — quota-capped AIS for the Middle East (free tier 150 calls/mo).
VesselAPI and AISStream are two independent, first-class vessel providers —
not a primary/fallback pair. AISStream (WebSocket) owns live US-coast AIS;
VesselAPI (REST) covers the Strait of Hormuz (default box) where AISStream
has no coverage. Missing one key never disables the other. This worker polls
the REST ``GET /v1/location/vessels/bounding-box`` endpoint at most
``VESSELAPI_MAX_CALLS_PER_DAY`` (default 5) *successful 2xx* calls per UTC day
and upserts the results into the shared ``vessel_last_known`` store.
Idle (no crash) when VESSELAPI_API_KEY is unset. Never called from the GET
/api/vessels path — map pans must not hit upstream. One request per poll,
``pagination.limit=50``, never follow ``nextToken``, never send ``filter.sat``.
"""
from __future__ import annotations
import asyncio
import calendar
import json
import logging
import os
from datetime import date, datetime, timezone
import httpx
from sqlalchemy import Column, Date, DateTime, Integer, Table, func, select, text
from config import (
OSINT_USER_AGENT,
VESSELAPI_API_KEY,
VESSELAPI_BBOX,
VESSELAPI_INTERVAL,
VESSELAPI_MAX_CALLS_PER_DAY,
)
from database import async_session, engine, metadata
from live_layers import parse_bbox, to_marker, upsert_vessel, vessel_last_known, vessel_lock
logger = logging.getLogger("osint.vesselapi")
BASE_URL = "https://api.vesselapi.com/v1"
ENDPOINT = f"{BASE_URL}/location/vessels/bounding-box"
MAX_SPAN_DEG = 4.0 # |dLat| + |dLon| — VesselAPI 400s above this.
PAGE_LIMIT = 50 # pagination.limit; never follow nextToken on the free tier.
_client: httpx.AsyncClient | None = None
_client_lock = asyncio.Lock()
# ── Box parsing / span validation ─────────────────────────────────────────
class BboxError(ValueError):
"""A configured VesselAPI box violates the 4° span rule or is malformed."""
def validate_bbox_span(
minlat: float, minlon: float, maxlat: float, maxlon: float,
) -> None:
"""Reject boxes VesselAPI would 400 on (span > 4°, bad order, bad range)."""
if not (-90 <= minlat <= 90 and -90 <= maxlat <= 90
and -180 <= minlon <= 180 and -180 <= maxlon <= 180):
raise BboxError("coordinates out of range")
if minlat >= maxlat or minlon >= maxlon:
raise BboxError("bbox must have min < max on both axes")
dlat = abs(maxlat - minlat)
dlon = abs(maxlon - minlon)
if dlat + dlon > MAX_SPAN_DEG:
raise BboxError(
f"span |dLat|+|dLon| = {dlat + dlon:.2f}° exceeds {MAX_SPAN_DEG}° cap"
)
def parse_boxes(raw: str) -> list[tuple[float, float, float, float]]:
"""Env format: ``minlat,minlon,maxlat,maxlon[; ...]`` (lat/lon order)."""
out: list[tuple[float, float, float, float]] = []
for chunk in (raw or "").split(";"):
parts = [p.strip() for p in chunk.split(",") if p.strip()]
if len(parts) != 4:
continue
try:
minlat = float(parts[0])
minlon = float(parts[1])
maxlat = float(parts[2])
maxlon = float(parts[3])
except ValueError:
continue
out.append((minlat, minlon, maxlat, maxlon))
return out
def parse_boxes_validated(raw: str) -> list[tuple[float, float, float, float]]:
"""Parse boxes, log + skip any that violate the span/order/range rules."""
valid: list[tuple[float, float, float, float]] = []
for box in parse_boxes(raw):
try:
validate_bbox_span(*box)
valid.append(box)
except BboxError as exc:
logger.warning("VesselAPI bbox %r skipped: %s", box, exc)
return valid
# ── Position → marker transform ───────────────────────────────────────────
def _f(value: object) -> float | None:
if value is None or value == "":
return None
try:
return float(value)
except (TypeError, ValueError):
return None
def _s(value: object) -> str | None:
if value is None:
return None
text = str(value).strip()
return text or None
def transform_vesselapi_position(obj: dict | None) -> dict | None:
"""Map one VesselAPI position object to the shared marker contract.
Returns None for glitch rows, missing MMSI, or missing coordinates.
"""
if not obj or not isinstance(obj, dict):
return None
if obj.get("suspected_glitch") is True:
return None
mmsi = obj.get("mmsi")
if mmsi is None:
return None
lat = _f(obj.get("latitude"))
lon = _f(obj.get("longitude"))
if lat is None or lon is None:
return None
mmsi_s = str(mmsi)
name = _s(obj.get("vessel_name") or obj.get("name"))
heading = _f(obj.get("heading"))
if heading is None:
heading = _f(obj.get("cog"))
sog = _f(obj.get("sog"))
extra: dict = {
"src": "vesselapi",
"mmsi": mmsi_s,
"cog": obj.get("cog"),
"sog": obj.get("sog"),
"navstat": obj.get("nav_status"),
}
imo = obj.get("imo")
if imo:
extra["imo"] = imo
dest = _s(obj.get("dest") or obj.get("destination"))
if dest:
extra["dest"] = dest
ts = obj.get("timestamp") or obj.get("processed_timestamp")
if ts:
extra["timestamp"] = ts
return to_marker(
mmsi_s, lat, lon,
heading=heading,
speed=sog,
label=name or mmsi_s,
extra=extra,
)
def transform_vesselapi_payload(payload: dict | None) -> list[dict]:
"""Flatten a bounding-box response ``{vessels: [...]}`` to markers."""
if not payload or not isinstance(payload, dict):
return []
rows = payload.get("vessels") or []
out = []
for row in rows:
marker = transform_vesselapi_position(row)
if marker:
out.append(marker)
return out
def utc_day_start(now: datetime) -> datetime:
"""Floor ``now`` to 00:00:00 UTC."""
if now.tzinfo is None:
now = now.replace(tzinfo=timezone.utc)
now = now.astimezone(timezone.utc)
return now.replace(hour=0, minute=0, second=0, microsecond=0)
def pick_poll_at(poll_times: list[datetime], as_of: datetime) -> datetime | None:
"""Latest poll timestamp at or before ``as_of`` (DVR as-of)."""
if as_of.tzinfo is None:
as_of = as_of.replace(tzinfo=timezone.utc)
else:
as_of = as_of.astimezone(timezone.utc)
eligible: list[datetime] = []
for raw in poll_times:
ts = raw if raw.tzinfo else raw.replace(tzinfo=timezone.utc)
ts = ts.astimezone(timezone.utc)
if ts <= as_of:
eligible.append(ts)
return max(eligible) if eligible else None
def snapshot_as_of(rows: list[dict], as_of: datetime) -> list[dict]:
"""Keep only rows from the latest poll_at ≤ ``as_of``."""
chosen = pick_poll_at(
[r["poll_at"] for r in rows if r.get("poll_at") is not None],
as_of,
)
if chosen is None:
return []
out = []
for row in rows:
ts = row.get("poll_at")
if ts is None:
continue
if ts.tzinfo is None:
ts = ts.replace(tzinfo=timezone.utc)
if ts.astimezone(timezone.utc) == chosen:
out.append(row)
return out
# ── Durable daily quota (Postgres, survives restarts) ─────────────────────
# Mirrors keystore.api_keys: lazy CREATE TABLE IF NOT EXISTS, no alembic fork.
vesselapi_quota = Table(
"vesselapi_quota",
metadata,
Column("day", Date, primary_key=True),
Column("calls", Integer, nullable=False, server_default="0"),
Column("remaining", Integer, nullable=True),
Column("updated_at", DateTime(timezone=True), server_default=func.now(), nullable=False),
)
_CREATE_QUOTA_SQL = text(
"""
CREATE TABLE IF NOT EXISTS vesselapi_quota (
day DATE PRIMARY KEY,
calls INTEGER NOT NULL DEFAULT 0,
remaining INTEGER,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
)
"""
)
_quota_lock = asyncio.Lock()
_quota_ensured = False
async def ensure_quota_table() -> None:
global _quota_ensured
if _quota_ensured:
return
async with _quota_lock:
if _quota_ensured:
return
async with engine.begin() as conn:
await conn.execute(_CREATE_QUOTA_SQL)
_quota_ensured = True
class PgQuotaStore:
"""Postgres-backed daily call counter. Injected for tests."""
async def calls_today(self, day: date) -> int:
await ensure_quota_table()
async with async_session() as session:
row = (await session.execute(
select(vesselapi_quota.c.calls).where(vesselapi_quota.c.day == day)
)).scalar()
return int(row) if row else 0
async def remaining_today(self, day: date) -> int | None:
await ensure_quota_table()
async with async_session() as session:
row = (await session.execute(
select(vesselapi_quota.c.remaining).where(vesselapi_quota.c.day == day)
)).scalar()
return int(row) if row is not None else None
async def bump(self, day: date, remaining: int | None) -> int:
await ensure_quota_table()
now = datetime.now(timezone.utc)
async with async_session() as session:
existing = (await session.execute(
select(vesselapi_quota.c.calls).where(vesselapi_quota.c.day == day)
)).scalar()
if existing is None:
await session.execute(
vesselapi_quota.insert().values(
day=day, calls=1, remaining=remaining, updated_at=now,
)
)
else:
await session.execute(
vesselapi_quota.update()
.where(vesselapi_quota.c.day == day)
.values(
calls=vesselapi_quota.c.calls + 1,
remaining=remaining,
updated_at=now,
)
)
await session.commit()
return (int(existing) if existing else 0) + 1
# ── Daily VesselAPI snapshots (DVR as-of + survive restarts) ──────────────
# Cleared at the UTC day boundary so the table holds today's 5 polls only.
_CREATE_VESSELS_SQL = text(
"""
CREATE TABLE IF NOT EXISTS vessels (
mmsi TEXT NOT NULL,
poll_at TIMESTAMPTZ NOT NULL,
lat DOUBLE PRECISION NOT NULL,
lon DOUBLE PRECISION NOT NULL,
heading DOUBLE PRECISION,
speed DOUBLE PRECISION,
label TEXT,
extra JSONB,
PRIMARY KEY (mmsi, poll_at)
)
"""
)
_CREATE_VESSELS_POLL_IDX = text(
"CREATE INDEX IF NOT EXISTS ix_vessels_poll_at ON vessels (poll_at DESC)"
)
_CREATE_VESSELS_BBOX_IDX = text(
"CREATE INDEX IF NOT EXISTS ix_vessels_bbox ON vessels (lon, lat)"
)
_vessels_lock = asyncio.Lock()
_vessels_ensured = False
async def ensure_vessels_table() -> None:
global _vessels_ensured
if _vessels_ensured:
return
async with _vessels_lock:
if _vessels_ensured:
return
async with engine.begin() as conn:
await conn.execute(_CREATE_VESSELS_SQL)
await conn.execute(_CREATE_VESSELS_POLL_IDX)
await conn.execute(_CREATE_VESSELS_BBOX_IDX)
_vessels_ensured = True
def _marker_from_vessel_row(r) -> dict:
extra = r.get("extra") or {}
if isinstance(extra, str):
try:
extra = json.loads(extra)
except (TypeError, ValueError):
extra = {}
if not isinstance(extra, dict):
extra = {}
extra.setdefault("src", "vesselapi")
poll_at = r.get("poll_at")
if poll_at is not None and hasattr(poll_at, "isoformat"):
extra["poll_at"] = poll_at.isoformat()
marker = to_marker(
str(r["id"]), r["lat"], r["lon"],
heading=r.get("heading"), speed=r.get("speed"),
label=r.get("label") or str(r["id"]),
extra=extra,
)
marker["seen_at"] = extra.get("poll_at") or datetime.now(timezone.utc).isoformat()
return marker
async def persist_vessel_snapshot(markers: list[dict], poll_at: datetime) -> None:
"""Write one VesselAPI poll into ``vessels`` (today's snapshots)."""
await ensure_vessels_table()
if not markers:
return
async with async_session() as session:
for m in markers:
vid = str(m.get("id") or "")
lat, lon = m.get("lat"), m.get("lon")
if not vid or lat is None or lon is None:
continue
extra = dict(m.get("extra") or {})
extra.setdefault("src", "vesselapi")
await session.execute(
text(
"""
INSERT INTO vessels
(mmsi, poll_at, lat, lon, heading, speed, label, extra)
VALUES
(:mmsi, :poll_at, :lat, :lon, :heading, :speed, :label,
CAST(:extra AS jsonb))
ON CONFLICT (mmsi, poll_at) DO UPDATE SET
lat = EXCLUDED.lat,
lon = EXCLUDED.lon,
heading = EXCLUDED.heading,
speed = EXCLUDED.speed,
label = EXCLUDED.label,
extra = EXCLUDED.extra
"""
),
{
"mmsi": vid,
"poll_at": poll_at,
"lat": float(lat),
"lon": float(lon),
"heading": m.get("heading"),
"speed": m.get("speed"),
"label": m.get("label") or vid,
"extra": json.dumps(extra),
},
)
await session.commit()
async def purge_old_vessels(before: datetime | None = None) -> None:
"""Drop snapshots from before the current UTC day (or ``before``)."""
await ensure_vessels_table()
cutoff = before or utc_day_start(datetime.now(timezone.utc))
async with async_session() as session:
await session.execute(
text("DELETE FROM vessels WHERE poll_at < :cutoff"),
{"cutoff": cutoff},
)
await session.commit()
async def fetch_vessels_as_of(
ts: datetime,
bbox: str | None = None,
limit: int = 2000,
) -> list[dict]:
"""Latest VesselAPI poll at or before ``ts`` (DVR as-of, not exact minute)."""
try:
await ensure_vessels_table()
async with async_session() as session:
poll = (await session.execute(
text("SELECT max(poll_at) FROM vessels WHERE poll_at <= :ts"),
{"ts": ts},
)).scalar()
if poll is None:
return []
sql = """
SELECT mmsi AS id, lat, lon, heading, speed, label, extra, poll_at
FROM vessels
WHERE poll_at = :poll
"""
params: dict = {"poll": poll, "limit": limit}
if bbox:
minlon, minlat, maxlon, maxlat = parse_bbox(bbox)
sql += (
" AND lon BETWEEN :minlon AND :maxlon"
" AND lat BETWEEN :minlat AND :maxlat"
)
params.update(
minlon=minlon, minlat=minlat, maxlon=maxlon, maxlat=maxlat,
)
sql += " LIMIT :limit"
rows = (await session.execute(text(sql), params)).mappings().all()
return [_marker_from_vessel_row(r) for r in rows]
except Exception:
logger.exception("VesselAPI snapshot fetch failed")
return []
async def hydrate_last_known() -> int:
"""Seed in-memory last-known from today's latest poll (app boot)."""
try:
rows = await fetch_vessels_as_of(datetime.now(timezone.utc))
except Exception:
logger.exception("VesselAPI hydrate failed")
return 0
if not rows:
return 0
async with vessel_lock:
for m in rows:
vid = str(m.get("id") or "")
if vid:
vessel_last_known[vid] = m
return len(rows)
# ── Budget / scheduling (pure, unit-testable) ─────────────────────────────
def days_left_in_month(now: datetime) -> int:
"""UTC days remaining in the current month, inclusive of today."""
_, last = calendar.monthrange(now.year, now.month)
return last - now.day + 1
def budget_allows(
calls_today: int,
remaining: int | None,
days_left: int,
max_per_day: int,
) -> bool:
"""True if another poll is permitted today.
Local hard cap: fewer than ``max_per_day`` successful calls today.
Monthly floor: if ``X-RateLimit-Remaining`` is known, keep at least
``max_per_day * days_left`` in reserve for the rest of the month.
"""
if calls_today >= max_per_day:
return False
if remaining is not None and remaining <= max_per_day * days_left:
return False
return True
def choose_box(
boxes: list[tuple[float, float, float, float]],
calls_today: int,
max_per_day: int,
) -> int:
"""Index into ``boxes`` for the next poll.
Prefer refreshing the first (primary) box rather than spraying one call
across every region — round-robin only when the remaining daily budget is
enough to cover all boxes.
"""
if len(boxes) <= 1:
return 0
budget_left = max_per_day - calls_today
if budget_left >= len(boxes):
return calls_today % len(boxes)
return 0
# ── HTTP / poll ───────────────────────────────────────────────────────────
async def _resolve_key() -> str:
from keystore import get_api_key
return (
os.getenv("VESSELAPI_API_KEY")
or VESSELAPI_API_KEY
or (await get_api_key("VESSELAPI_API_KEY"))
or ""
).strip()
async def _get_client() -> httpx.AsyncClient:
global _client
if _client is None:
async with _client_lock:
if _client is None:
_client = httpx.AsyncClient(
timeout=httpx.Timeout(15.0, connect=5.0),
follow_redirects=True,
headers={"User-Agent": OSINT_USER_AGENT, "Accept": "application/json"},
limits=httpx.Limits(max_connections=1, max_keepalive_connections=1),
)
return _client
async def close_client() -> None:
global _client
if _client is not None:
await _client.aclose()
_client = None
def _int_header(value: str | None) -> int | None:
if value is None:
return None
try:
return int(value)
except (TypeError, ValueError):
return None
async def poll_once(store, boxes: list[tuple[float, float, float, float]], key: str) -> bool:
"""One quota-checked poll. Returns True if a successful 2xx was made.
Only successful 2xx responses count against the monthly quota; 4xx/5xx/429
are skipped without retry-storming (Retry-After respected by simply
sleeping the interval).
"""
now = datetime.now(timezone.utc)
today = now.date()
calls = await store.calls_today(today)
remaining = await store.remaining_today(today)
days_left = days_left_in_month(now)
if not budget_allows(calls, remaining, days_left, VESSELAPI_MAX_CALLS_PER_DAY):
logger.info(
"VesselAPI quota reached (calls_today=%d, remaining=%s, days_left=%d) — skip poll",
calls, remaining, days_left,
)
return False
idx = choose_box(boxes, calls, VESSELAPI_MAX_CALLS_PER_DAY)
minlat, minlon, maxlat, maxlon = boxes[idx]
client = await _get_client()
params = {
"filter.latBottom": str(minlat),
"filter.latTop": str(maxlat),
"filter.lonLeft": str(minlon),
"filter.lonRight": str(maxlon),
"pagination.limit": str(PAGE_LIMIT),
}
headers = {"Authorization": f"Bearer {key}"}
try:
resp = await client.get(ENDPOINT, params=params, headers=headers)
except httpx.HTTPError as exc:
logger.warning("VesselAPI request failed: %s", exc)
return False
if resp.status_code == 429:
logger.warning(
"VesselAPI rate-limited (Retry-After=%s) — skip poll",
resp.headers.get("Retry-After"),
)
return False
if resp.status_code >= 400:
logger.warning("VesselAPI HTTP %d — not counted against quota", resp.status_code)
return False
# 2xx success — counts against the monthly quota.
remaining = _int_header(resp.headers.get("X-RateLimit-Remaining"))
calls = await store.bump(today, remaining)
try:
data = resp.json()
except ValueError:
logger.warning("VesselAPI 2xx with non-JSON body — counted but ignored")
return True
markers = transform_vesselapi_payload(data)
for m in markers:
await upsert_vessel(m)
try:
await persist_vessel_snapshot(markers, now)
await purge_old_vessels(utc_day_start(now))
except Exception: # noqa: BLE001 — live overlay must not die on persist
logger.exception("VesselAPI snapshot persist failed")
logger.info(
"VesselAPI poll OK: %d vessels (remaining=%s, calls_today=%d)",
len(markers), remaining, calls,
)
return True
# ── Worker loop ───────────────────────────────────────────────────────────
async def run_vesselapi_worker(store: PgQuotaStore | None = None) -> None:
"""Long-lived poll loop. Idle when the key is unset; never crashes the app."""
if store is None:
store = PgQuotaStore()
boxes = parse_boxes_validated(VESSELAPI_BBOX)
if not boxes:
logger.warning(
"VESSELAPI_BBOX has no valid boxes (span ≤ %.1f°) — poller idle", MAX_SPAN_DEG,
)
while True:
try:
if not boxes:
await asyncio.sleep(VESSELAPI_INTERVAL)
continue
key = await _resolve_key()
if not key:
logger.warning(
"VESSELAPI_API_KEY not set — VesselAPI poller idle. "
"Create a free key at https://dashboard.vesselapi.com/"
)
await asyncio.sleep(VESSELAPI_INTERVAL)
continue
await poll_once(store, boxes, key)
except asyncio.CancelledError:
raise
except Exception: # noqa: BLE001 — keep the loop alive across transient failures
logger.exception("VesselAPI poll error")
await asyncio.sleep(VESSELAPI_INTERVAL)

View file

@ -1,115 +0,0 @@
"""In-memory WebSocket pub/sub with viewport filtering.
Zero extra deps. Ingest workers publish AIS/ADS-B points; only clients whose
current map bbox contains the point receive the payload. No Redis/Kafka.
"""
from __future__ import annotations
import asyncio
from typing import Any
from uuid import UUID
BBox = tuple[float, float, float, float] # minlon, minlat, maxlon, maxlat
def _uuid_str(value: object) -> str | None:
try:
return str(UUID(str(value)))
except (ValueError, TypeError, AttributeError):
return None
def point_in_bbox(lon: float, lat: float, bbox: BBox | None) -> bool:
"""True if (lon, lat) sits inside an axis-aligned viewport."""
if bbox is None:
return False
minlon, minlat, maxlon, maxlat = bbox
return minlon <= lon <= maxlon and minlat <= lat <= maxlat
class ConnectionManager:
"""Maps Tailscale/browser clients → viewport bbox + per-client queue."""
def __init__(self) -> None:
self._queues: dict[str, asyncio.Queue] = {}
self._viewports: dict[str, BBox] = {}
self._watched: dict[str, set[str]] = {}
def register(self, client_id: str, maxsize: int = 256) -> asyncio.Queue:
q: asyncio.Queue = asyncio.Queue(maxsize=maxsize)
self._queues[client_id] = q
return q
def unregister(self, client_id: str) -> None:
self._queues.pop(client_id, None)
self._viewports.pop(client_id, None)
self._watched.pop(client_id, None)
def set_watched_geofences(self, client_id: str, ids: list[str]) -> None:
"""Watch these fence UUIDs so geofence_alert delivers off-viewport.
Invalid UUIDs are ignored. Empty list = watch none (viewport-only).
"""
if client_id not in self._queues:
return
watched: set[str] = set()
for raw in ids:
uid = _uuid_str(raw)
if uid is not None:
watched.add(uid)
self._watched[client_id] = watched
def set_viewport(self, client_id: str, bbox: BBox) -> None:
if client_id in self._queues:
self._viewports[client_id] = bbox
def viewport_of(self, client_id: str) -> BBox | None:
return self._viewports.get(client_id)
def viewports(self) -> list[BBox]:
return list(self._viewports.values())
def has_clients(self) -> bool:
return bool(self._queues)
async def publish_point(
self,
kind: str,
payload: dict[str, Any],
*,
lat: float,
lon: float,
) -> int:
"""Enqueue `{type, payload}` for clients whose viewport contains the point.
kind=geofence_alert also delivers when payload.geofence_id is in the
client's watch set (even if the point is off-viewport). Other kinds
stay viewport-only. Drops the oldest queued message if a client's
buffer is full. Returns the number of clients that got a copy.
"""
msg = {"type": kind, "payload": payload}
sent = 0
gid = _uuid_str(payload.get("geofence_id")) if kind == "geofence_alert" else None
for client_id, queue in list(self._queues.items()):
in_view = point_in_bbox(lon, lat, self._viewports.get(client_id))
if kind == "geofence_alert":
watching = gid is not None and gid in self._watched.get(client_id, set())
if not in_view and not watching:
continue
elif not in_view:
continue
if queue.full():
try:
queue.get_nowait()
except asyncio.QueueEmpty:
pass
try:
queue.put_nowait(msg)
except asyncio.QueueFull:
continue
sent += 1
return sent
manager = ConnectionManager()

View file

@ -1,21 +0,0 @@
# osint.rpi.local — Sentinel-1 SAR tile proxy (/titiler/)
#
# GitOps: this file is the source of truth. On the Pi:
# sudo cp deploy/osint-titiler.nginx.conf /etc/nginx/snippets/osint-titiler.conf
# then `include snippets/osint-titiler.conf;` inside the osint.rpi.local server
# block (before `location /`), `nginx -t && systemctl reload nginx`.
#
# The browser hits /titiler/cog/tiles/... (same-origin). We strip the /titiler
# prefix so self-hosted TiTiler (127.0.0.1:8001) sees /cog/tiles/... and proxy
# its response straight back. Tiles are heavy PNGs — disable buffering so a
# slow client doesn't hold a worker open.
location /titiler/ {
proxy_pass http://127.0.0.1:8001/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_buffering off;
proxy_read_timeout 300s;
}

View file

@ -1,23 +0,0 @@
# osint.rpi.local — WebSocket upgrade for /ws/live
#
# GitOps: this file is the source of truth. On the Pi:
# sudo cp deploy/osint-ws.nginx.conf /etc/nginx/snippets/osint-ws.conf
# then `include snippets/osint-ws.conf;` inside the osint.rpi.local server
# block (before `location /`), `nginx -t && systemctl reload nginx`.
#
# Without these headers nginx proxies GET /ws/live as HTTP/1.0 → FastAPI 404
# and the HUD reconnects every few seconds.
location /ws/ {
proxy_pass http://127.0.0.1:8000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
proxy_buffering off;
}

View file

@ -1,289 +0,0 @@
# OSINT Dashboard — container stack (all env-driven, 12-factor).
# Single combined TimescaleDB+PostGIS image is pinned to pg13 because that is
# the only arm64 build Timescale publishes with PostGIS bundled. The app uses
# only standard SQL types, so pg13 is fully sufficient.
#
# Bring up: docker compose up -d
# With NATS: docker compose --profile ingest up -d
# Env: copy .env.example to .env and adjust.
#
# Project name is pinned here (NOT via COMPOSE_PROJECT_NAME in CI) so the
# named volumes stay osint-dashboard_osint-pgdata / _camera-snapshots and
# match the live stack on the Pi.
name: osint-dashboard
services:
db:
# NO build: block here on purpose. The DB image (TimescaleDB+PostGIS) is
# built once via Dockerfile.pg and pinned as localhost/osint-dashboard-pg.
# Dockerfile.pg installs TimescaleDB from packagecloud.io, which some
# networks (and ISP abuse-mitigation blackholes) block, so rebuilding it
# on every CI deploy made the pipeline flaky. Rebuild manually when the
# base image or extensions need bumping:
# docker build -f Dockerfile.pg -t localhost/osint-dashboard-pg:latest .
# FORCE_RECREATE_DB=1 scripts/compose-reup.sh db
image: localhost/osint-dashboard-pg:latest
pull_policy: never
container_name: osint-db
restart: unless-stopped
environment:
POSTGRES_USER: ${DB_USER:-osint}
POSTGRES_PASSWORD: ${DB_PASSWORD:-osint}
POSTGRES_DB: ${DB_NAME:-osint_data}
# Ensure TimescaleDB is preloaded (conf.d drop-in may be ignored by the
# official image's runtime-generated postgresql.conf, so pass it explicitly).
# shared_buffers capped at 2GB for Pi 5 8GB / 4 cores.
command:
[
"-c", "shared_preload_libraries=timescaledb",
"-c", "shared_buffers=2GB",
]
deploy:
resources:
limits:
memory: 3G
ports:
- "127.0.0.1:5432:5432"
volumes:
- osint-pgdata:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${DB_USER:-osint} -d ${DB_NAME:-osint_data}"]
interval: 10s
timeout: 5s
retries: 10
nats:
image: nats:2.10
pull_policy: missing
platform: linux/arm64
container_name: osint-nats
restart: unless-stopped
profiles: ["ingest"]
ports:
- "127.0.0.1:4222:4222"
- "127.0.0.1:8222:8222"
command: ["-js"]
ingester:
build:
context: .
dockerfile: Dockerfile
platforms: ["linux/arm64"]
image: localhost/osint-dashboard:latest
pull_policy: never
container_name: osint-ingester
restart: unless-stopped
profiles: ["ingest"]
depends_on:
nats:
condition: service_started
db:
condition: service_healthy
environment:
DB_USER: ${DB_USER:-osint}
DB_PASSWORD: ${DB_PASSWORD:-osint}
DB_HOST: db
DB_PORT: ${DB_PORT:-5432}
DB_NAME: ${DB_NAME:-osint_data}
NATS_URL: ${NATS_URL:-nats://nats:4222}
RSS_URL: ${RSS_URL:-}
GDELT_QUERY: ${GDELT_QUERY:-}
INGEST_INTERVAL: ${INGEST_INTERVAL:-300}
INGEST_EARTHQUAKES: ${INGEST_EARTHQUAKES:-1}
# ── NASA FIRMS active fires ──
INGEST_FIRES: ${INGEST_FIRES:-1}
FIRMS_MAP_KEY: ${FIRMS_MAP_KEY:-}
FIRMS_DATASET: ${FIRMS_DATASET:-VIIRS_NOAA20_NRT}
FIRMS_DATASETS: ${FIRMS_DATASETS:-VIIRS_NOAA20_NRT,VIIRS_NOAA21_NRT}
FIRMS_BBOX: ${FIRMS_BBOX:--180,-60,180,75}
FIRMS_INTERVAL: ${FIRMS_INTERVAL:-900}
OSINT_USER_AGENT: ${OSINT_USER_AGENT:-osint-dashboard/1.0 (self-hosted; [email protected])}
AISSTREAM_API_KEY: ${AISSTREAM_API_KEY:-}
AISSTREAM_BBOX: ${AISSTREAM_BBOX:-24,-125,50,-66}
AISSTREAM_IN_INGEST: ${AISSTREAM_IN_INGEST:-0}
VESSELAPI_API_KEY: ${VESSELAPI_API_KEY:-}
VESSELAPI_BBOX: ${VESSELAPI_BBOX:-25.5,55.4,27.3,57.2}
VESSELAPI_INTERVAL: ${VESSELAPI_INTERVAL:-17280}
VESSELAPI_MAX_CALLS_PER_DAY: ${VESSELAPI_MAX_CALLS_PER_DAY:-5}
VESSELAPI_IN_INGEST: ${VESSELAPI_IN_INGEST:-0}
command: ["python", "app/run_ingester.py"]
entrypoint: ["python", "app/run_ingester.py"]
app:
build:
context: .
dockerfile: Dockerfile
platforms: ["linux/arm64"]
image: localhost/osint-dashboard:latest
pull_policy: never
container_name: osint-dashboard
restart: unless-stopped
depends_on:
db:
condition: service_healthy
environment:
DB_USER: ${DB_USER:-osint}
DB_PASSWORD: ${DB_PASSWORD:-osint}
DB_HOST: db
DB_PORT: ${DB_PORT:-5432}
DB_NAME: ${DB_NAME:-osint_data}
NATS_URL: ${NATS_URL:-nats://nats:4222}
MINIO_ENDPOINT: ${MINIO_ENDPOINT:-minio:9000}
MINIO_ACCESS_KEY: ${MINIO_ACCESS_KEY:-}
MINIO_SECRET_KEY: ${MINIO_SECRET_KEY:-}
MINIO_SECURE: ${MINIO_SECURE:-false}
# ── NASA FIRMS (for the /api/ingest/fires trigger endpoint) ──
FIRMS_MAP_KEY: ${FIRMS_MAP_KEY:-}
FIRMS_DATASET: ${FIRMS_DATASET:-VIIRS_NOAA20_NRT}
FIRMS_DATASETS: ${FIRMS_DATASETS:-VIIRS_NOAA20_NRT,VIIRS_NOAA21_NRT}
FIRMS_BBOX: ${FIRMS_BBOX:--180,-60,180,75}
OSINT_USER_AGENT: ${OSINT_USER_AGENT:-osint-dashboard/1.0 (self-hosted; [email protected])}
NOMINATIM_URL: ${NOMINATIM_URL:-https://nominatim.openstreetmap.org}
NOMINATIM_MIN_INTERVAL: ${NOMINATIM_MIN_INTERVAL:-1.0}
AISSTREAM_API_KEY: ${AISSTREAM_API_KEY:-}
AISSTREAM_BBOX: ${AISSTREAM_BBOX:-24,-125,50,-66}
AISSTREAM_IN_APP: ${AISSTREAM_IN_APP:-1}
VESSELAPI_API_KEY: ${VESSELAPI_API_KEY:-}
VESSELAPI_BBOX: ${VESSELAPI_BBOX:-25.5,55.4,27.3,57.2}
VESSELAPI_INTERVAL: ${VESSELAPI_INTERVAL:-17280}
VESSELAPI_MAX_CALLS_PER_DAY: ${VESSELAPI_MAX_CALLS_PER_DAY:-5}
VESSELAPI_IN_APP: ${VESSELAPI_IN_APP:-1}
# ── Self-hosted TiTiler (Sentinel-1 SAR tiles) ──
TITILER_PUBLIC_BASE: ${TITILER_PUBLIC_BASE:-/titiler}
TITILER_INTERNAL_URL: ${TITILER_INTERNAL_URL:-http://titiler:8000}
ports:
- "127.0.0.1:8000:8000"
deploy:
resources:
limits:
memory: 2G
healthcheck:
test: ["CMD-SHELL", "python -c \"import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8000/api/health').status==200 else 1)\""]
interval: 30s
timeout: 5s
retries: 5
# ── Self-hosted TiTiler (Sentinel-1 SAR COG → XYZ tiles) ────────────────
# Warps the signed Planetary Computer COG into WebMercator XYZ tiles so the
# browser never loads a multi-GB GeoTIFF. The FastAPI app signs the COG URL
# and returns a /titiler/... template; nginx routes /titiler/ here.
# Listens on 8000 INSIDE the container (the app already owns host 8000);
# published on host loopback 127.0.0.1:8001 only.
titiler:
image: ghcr.io/developmentseed/titiler:latest@sha256:1809958d063543e3ec858259536002b2de78e9f8f09a22a8d9591bdc2b550b14
pull_policy: missing
container_name: osint-titiler
platform: linux/arm64
restart: unless-stopped
environment:
- PORT=8000
- WORKERS_PER_CORE=1
ports:
- "127.0.0.1:8001:8000"
deploy:
resources:
limits:
memory: 1G
camera-service:
build:
context: .
dockerfile: Dockerfile
platforms: ["linux/arm64"]
image: localhost/osint-dashboard:latest
pull_policy: never
container_name: osint-camera-scraper
restart: unless-stopped
profiles: ["ingest"]
depends_on:
nats:
condition: service_started
db:
condition: service_healthy
environment:
DB_USER: ${DB_USER:-osint}
DB_PASSWORD: ${DB_PASSWORD:-osint}
DB_HOST: db
DB_PORT: ${DB_PORT:-5432}
DB_NAME: ${DB_NAME:-osint_data}
NATS_URL: ${NATS_URL:-nats://nats:4222}
CAMERA_SOURCE_URLS: ${CAMERA_SOURCE_URLS:-}
CAMERA_SCRAPE_INTERVAL: ${CAMERA_SCRAPE_INTERVAL:-3600}
CAMERA_REQUEST_DELAY: ${CAMERA_REQUEST_DELAY:-2.0}
NOMINATIM_URL: ${NOMINATIM_URL:-https://nominatim.openstreetmap.org}
NOMINATIM_MIN_INTERVAL: ${NOMINATIM_MIN_INTERVAL:-1.1}
SNAPSHOT_CACHE_DIR: /data/snapshots
SNAPSHOT_TTL_SECONDS: ${SNAPSHOT_TTL_SECONDS:-300}
command: ["python", "app/run_camera_service.py"]
entrypoint: []
volumes:
- camera-snapshots:/data/snapshots
# ── News pipeline: continuous scraper + 15-min summarizer ───────────────
# Both services point at the EXISTING osint-db (tables articles +
# article_summaries, created by idempotent alembic migration 003_news).
# Scheduling replaces the upstream k8s CronJobs with in-compose wall-clock
# loops (run_news_scraper.py / run_news_summarizer.py).
news-scraper:
build:
context: ./news/scraper
dockerfile: Dockerfile
platforms: ["linux/arm64"]
image: localhost/osint-news-scraper:latest
pull_policy: never
container_name: osint-news-scraper
restart: unless-stopped
profiles: ["ingest"]
depends_on:
db:
condition: service_healthy
environment:
DB_USER: ${DB_USER:-osint}
DB_PASSWORD: ${DB_PASSWORD:-osint}
DB_HOST: db
DB_PORT: ${DB_PORT:-5432}
DB_NAME: ${DB_NAME:-osint_data}
LOG_LEVEL: ${NEWS_LOG_LEVEL:-INFO}
NEWS_SCRAPE_INTERVAL_S: ${NEWS_SCRAPE_INTERVAL_S:-10}
NEWS_SCRAPE_RUN_ON_START: ${NEWS_SCRAPE_RUN_ON_START:-1}
# Override the image ENTRYPOINT ["scrapy"] with the scheduler loop.
entrypoint: []
command: ["python", "run_news_scraper.py"]
news-summarizer:
build:
context: ./news/summerizer
dockerfile: Dockerfile
platforms: ["linux/arm64"]
image: localhost/osint-news-summarizer:latest
pull_policy: never
container_name: osint-news-summarizer
restart: unless-stopped
profiles: ["ingest"]
depends_on:
db:
condition: service_healthy
environment:
DB_USER: ${DB_USER:-osint}
DB_PASSWORD: ${DB_PASSWORD:-osint}
DB_HOST: db
DB_PORT: ${DB_PORT:-5432}
DB_NAME: ${DB_NAME:-osint_data}
NOUS_API_KEY: ${NOUS_API_KEY:-}
NOUS_BASE_URL: ${NOUS_BASE_URL:-https://inference-api.nousresearch.com/v1}
SUMMARY_MODEL: ${SUMMARY_MODEL:-}
OSINT_USER_AGENT: ${OSINT_USER_AGENT:-osint-dashboard-news-summarizer}
BATCH_SIZE: ${NEWS_BATCH_SIZE:-50}
SUMMARY_WINDOW_MINUTES: ${SUMMARY_WINDOW_MINUTES:-15}
INCLUDE_FUTURES: ${INCLUDE_FUTURES:-0}
NEWS_SUMMARIZE_INTERVAL_S: ${NEWS_SUMMARIZE_INTERVAL_S:-900}
NEWS_SUMMARIZE_RUN_ON_START: ${NEWS_SUMMARIZE_RUN_ON_START:-1}
NEWS_SUMMARIZE_FORCE: ${NEWS_SUMMARIZE_FORCE:-0}
TZ: ${TZ:-America/New_York}
NEWS_RECAP_HOUR: ${NEWS_RECAP_HOUR:-23}
NEWS_RECAP_MINUTE: ${NEWS_RECAP_MINUTE:-0}
command: ["python", "run_news_summarizer.py"]
volumes:
osint-pgdata:
camera-snapshots:

View file

@ -1,86 +0,0 @@
# Admin authentication
The dashboard is **public read-only**: anyone can open the map and the news
brief. One admin (the operator) additionally gets API-key management, settings
and every state-changing route. There is no user table, no RBAC and no OAuth —
one admin, one signed cookie (`app/auth.py`).
## Surface
| Route | Anonymous | Admin |
| --- | --- | --- |
| `GET /`, `GET /login`, `GET /static/*`, `WS /ws/live` | ✅ | ✅ |
| Read allowlist (`GET /api/news`, `/api/map/*`, feeds, analytics, cameras, `POST /api/search`, …) | ✅ | ✅ |
| `GET/POST/DELETE /api/keys*` | 401 | ✅ |
| `GET/PUT /api/settings`, `GET /api/news/models` | 401 | ✅ |
| Every other `POST/PUT/PATCH/DELETE` (`/api/ingest/*`, `/api/sources`, events, entities, alerts, geofences, `/api/vessels/subscribe`) | 401 | ✅ |
| `GET /api/auth/me` | 200 `{"authenticated": false, "admin": false}` | 200, both `true` |
| `POST /api/auth/login` | — | 200 + `Set-Cookie` |
| `POST /api/auth/logout` | 200 (clears cookie) | 200 |
Enforcement is **deny-by-default on `/api/*`** in `AdminAuthMiddleware`
(`app/auth.py`); the public list is an explicit allowlist (`PUBLIC_GET_EXACT`,
`PUBLIC_GET_PATTERNS`, `PUBLIC_POST_EXACT`). Naming a path there is the only way
to make it public — never a per-route decorator in `app/main.py`.
## Configuration
Three environment variables (cluster: Secret `osint-admin`):
| Variable | Meaning |
| --- | --- |
| `ADMIN_USER` | Admin username. |
| `ADMIN_PASSWORD_HASH` | `pbkdf2_sha256$<iterations>$<salt_b64>$<hash_b64>`. |
| `ADMIN_SESSION_SECRET` | HMAC-SHA256 key for the session token. |
```bash
python app/auth.py hash 'your password' # password hash
python -c 'import secrets; print(secrets.token_urlsafe(48))' # session secret
```
Put the values into a Secret and reference them from the deployment; never
commit them.
### Fail closed
If `ADMIN_PASSWORD_HASH` **or** `ADMIN_SESSION_SECRET` is unset/empty:
* every admin endpoint answers `403 {"detail": "admin auth not configured"}`,
* `/login` renders that message instead of the form,
* `/api/auth/login` also answers 403,
* public pages and the read allowlist still work.
There is no default password and no bypass.
## Session cookie
`osint_session`, HMAC-SHA256 signed base64url JSON payload `{v,sub,iat,exp}`,
`HttpOnly`, `SameSite=Lax`, `Path=/`, 7-day lifetime, `Secure` when the request
arrived over https (`X-Forwarded-Proto`, i.e. behind Cloudflare). Signature and
expiry are checked with `hmac.compare_digest`; a token for another username, or
one signed with a different secret, is rejected.
Set `ADMIN_COOKIE_SECURE=1` (`true`/`yes` also work) whenever the deployment is
TLS-only but the app itself is reached over plain HTTP. In the cluster the
Cloudflare tunnel originates at the Cilium Gateway on plain HTTP and Envoy
normalizes `X-Forwarded-Proto` to `http`, so the header inference never fires
there — the flag is what makes the cookie `Secure` in the cluster. Leave it
unset for local development, where the cookie has to work over `http://localhost`.
## Abuse controls
* **Login rate limit:** 5 failed attempts per client IP (first hop of
`X-Forwarded-For`, else the socket peer) per 15 minutes, then `429`.
In-memory — fine for the single replica.
* **CSRF:** state-changing admin requests that carry `Origin`/`Referer` must
match the request host, else `403`. Header-less clients (curl,
service-to-service) rely on the signed SameSite=Lax cookie.
## HUD
`app/static/index.html` hides admin chrome with `body:not(.is-admin)
[data-admin]` and adds the class only when `GET /api/auth/me` reports
`admin: true`. The menu's Ingest / API Keys / Settings entries, the summarizer
panel and the geofence draw/rename/delete controls are admin-only; anonymous
visitors see a discreet `SIGN IN` link to `/login`. This is UX only — the API
gate is what actually protects the data.

View file

@ -1,145 +0,0 @@
# FIRMS active fire / hotspot heatmap — data source
The OSINT map's fire overlay is fed by **NASA FIRMS** (Fire Information for
Resource Management System). Two zero-cost options exist; this repo implements
option A (ingested vector points served as JSON), and option B (GIBS raster
tiles) is documented below for a no-storage frontend-only alternative.
---
## A. FIRMS area CSV → Postgres/TimescaleDB → `GET /api/fires`
### Data flow
```
NASA FIRMS area CSV ──► app/fire_sources.py ──► NATS events.fire
│
app/ingestor.py (ingest_fire_row)
│
fires hypertable (idempotent PK)
│
GET /api/fires?bbox=&since= (JSON)
```
* `app/fire_sources.py` fetches the VIIRS active-fire CSV for a bounding box,
normalises each row (combining `acq_date` + `acq_time` into a UTC timestamp),
and publishes one message per hotspot to NATS JetStream subject `events.fire`.
* The long-running ingester (`app/run_ingester.py`) polls FIRMS on its own
~15-minute cadence (`FIRMS_INTERVAL`, default 900 s) and shares the existing
NATS consumer. `ingest_event` routes `source_type == "fire"` messages to
`ingest_fire_row`, which writes to the `fires` table.
* **Idempotency:** the `fires` primary key IS the natural key
`(latitude, longitude, acq_time, satellite)`. Inserts use
`ON CONFLICT DO NOTHING`, so a hotspot re-delivered on a later poll is
silently ignored — no duplicates, no upsert churn.
* The `fires` table is a **TimescaleDB hypertable** partitioned on `acq_time`
(1-day chunks), so retention is one `drop_chunks` call away.
### Endpoint
```
GET /api/fires?bbox=<minlon,minlat,maxlon,maxlat>&since=<ISO-8601-UTC>&limit=<N>
```
| Query param | Meaning | Default |
|---|---|---|
| `bbox` | `"minlon,minlat,maxlon,maxlat"` to bound the result (e.g. `-125,24,-66,50`). | all stored detections |
| `since` | only hotspots acquired at/after this UTC instant (e.g. `2026-08-24T12:00:00Z`). | none |
| `limit` | max rows returned. | `2000` (max `10000`) |
Response is a plain JSON array (frontend renders it as the heatmap overlay):
```json
[
{
"latitude": 39.45678,
"longitude": -121.12345,
"brightness": 341.4, // bright_ti4, Kelvin
"confidence": "h", // VIIRS: n (nominal) / l (low) / h (high)
"acq_time": "2026-08-24T18:10:00Z",
"satellite": "N", // N (S-NPP), N20, N21
"instrument": "VIIRS",
"bright_ti5": 310.2, // 12µm brightness, Kelvin
"frp": 12.4, // fire radiative power, MW
"daynight": "D" // D / N
}
]
```
A manual poll can also be triggered with `POST /api/ingest/fires?bbox=...`.
### Configuration (all via env / `.env`)
| Var | Default | Notes |
|---|---|---|
| `FIRMS_MAP_KEY` | *(blank)* | **Required for live data.** Free key: <https://firms.modaps.eosdis.nasa.gov/api/map_key_info/> (1-minute signup). Until set, the fire loop logs a warning and stays idle — it never crashes the ingester. |
| `FIRMS_DATASET` | `VIIRS_SNPP_NRT` | NRT VIIRS S-NPP 375 m active fire detection. |
| `FIRMS_BBOX` | `-180,-60,180,75` | Poll area `"minlon,minlat,maxlon,maxlat"`. Narrow it (e.g. `-125,24,-66,50`) to cut payload and write volume. |
| `FIRMS_INTERVAL` | `900` | Poll cadence in seconds (~15 min; FIRMS NRT refreshes every ~5–10 min). |
| `INGEST_FIRES` | `1` | Set `0` to disable the fire loop entirely. |
| `FIRMS_TIMEOUT` | `60` | Outbound HTTP timeout for the CSV download. |
### Tests
`tests/` — parser/normalisation/mapping unit tests run anywhere; DB-backed
idempotency + API contract tests are marked `integration` and auto-skip without
a reachable TimescaleDB+PostGIS (the repo's `localhost/osint-dashboard-pg`
image or a local `postgis/postgis`):
```bash
DB_HOST=... DB_PORT=... DB_USER=osint DB_PASSWORD=... DB_NAME=osint_data \
pytest tests/ -v
```
`DB_NULL_POOL=1` is set by the test suite (fresh connection per event loop).
### Live verification
Live end-to-end verification (real FIRMS fetch → NATS → Postgres → API) is
**blocked until `FIRMS_MAP_KEY` is set** in `.env`. Everything else — CSV
parsing, idempotent storage, the API contract — is verified against a real
TimescaleDB instance in the test suite.
---
## B. GIBS thermal-anomaly tiles — zero-cost, no key, no storage
If you want a fire layer with **zero backend work** (raster tiles rendered by
the map library directly, no ingest, no DB, no API key), NASA GIBS serves the
same VIIRS S-NPP detections as WMTS tiles:
* Layer: **`VIIRS_SNPP_Thermal_Anomalies_375m_All`** (375 m VIIRS S-NPP thermal
anomalies / active fires). Sibling layers exist for day/night-only views
(`..._Day`, `..._Night`).
* REST tile URL (Web Mercator, EPSG:3857 — what Leaflet/MapLibre use):
```
https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/VIIRS_SNPP_Thermal_Anomalies_375m_All/default/{Time}/GoogleMapsCompatible_Level{Z}/{Y}/{X}.png
```
* `{Time}` is a date like `2026-08-24` (or a time-of-day string); the list of
available times comes from the WMTS capabilities:
`https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/1.0.0/WMTSCapabilities.xml`
(search for the layer, read its `Dimension` → `Value`).
* Leaflet/MapLibre example:
```js
L.tileLayer(
'https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/VIIRS_SNPP_Thermal_Anomalies_375m_All/default/{time}/GoogleMapsCompatible_Level{z}/{y}/{x}.png',
{ attribution: 'NASA GIBS / FIRMS', maxZoom: 9 }
).addTo(map);
```
**Trade-offs vs. option A:**
| | A — FIRMS CSV ingest | B — GIBS WMTS tiles |
|---|---|---|
| Data in our DB | yes (queryable, filterable) | no (pixels only) |
| Per-hotspot attributes (brightness, FRP, confidence) | yes | no (colour-coded only) |
| Time range / `since` filtering server-side | yes | tile `{Time}` per snapshot |
| Backend cost | ingest service + DB rows | none |
| API key | free FIRMS_MAP_KEY | none |
GIBS is the right choice when the map only needs "where are fires right now".
The FIRMS ingest is right when you want to query, aggregate, or persist the
detections (e.g. "fires near X in the last 24 h").

View file

@ -1,613 +0,0 @@
# Free data streams for the OSINT dashboard
Builder brief for backend + frontend. Researched 2026-08-27. Every endpoint below was either live-probed from this machine or taken from the provider’s current docs. Prefer **free, no-key, CORS-open** sources first. Keys are called out explicitly.
This is **not** a camera-discovery change. Existing camera rules still apply: never emit `rtsp://` hrefs; camera pins go through `/api/cameras/{id}/snapshot`; HTTP directory cams use `/stream` MJPEG.
---
## 0. What is already in the repo (do not rebuild)
| Layer | Status | Notes |
|---|---|---|
| NASA FIRMS VIIRS hotspots | Ingested (`app/fire_sources.py` → NATS `events.fire` → `fires` hypertable → `GET /api/fires`) | Needs free `FIRMS_MAP_KEY`. See `docs/firms.md`. |
| NASA GIBS basemaps | Frontend tiles via `app/gibs_map.py` | No key. CORS `*`. |
| GIBS VIIRS thermal tiles | Documented, not wired as overlay | Same GIBS stack; no key. |
| Cameras | Scraper → `cameras` table | Defaults already include ALERTWest JPEGs + Live-Environment-Streams HLS/YouTube GeoJSON. |
| News / RSS / GDELT / USGS quakes | Ingest | Out of scope for this brief. |
**Action for existing fire ingest:** NASA will stop Suomi NPP product delivery on **2026-11-01**. Switch `FIRMS_DATASET` from `VIIRS_SNPP_NRT` to `VIIRS_NOAA20_NRT` and/or `VIIRS_NOAA21_NRT` before then.[20]
---
## 1. Architecture rules (backend + frontend)
Moving objects (aircraft, vessels, trains) and alerts are **vectors**. Radar / satellite / GIBS fire tiles are **rasters**.
| Kind | Where it runs | Persist? | API shape |
|---|---|---|---|
| Radar, GOES, GIBS, OpenRailwayMap tiles | **Browser** `L.tileLayer` (CORS `*` on the recommended ones) | No | Tile URL template |
| Aircraft / trains / last-known ships | **Backend poll** → last-known row → `GET /api/{layer}?bbox=` | Last-known only (Timescale, 1-day chunks, drop after 24–72 h) | JSON array of points |
| AIS live stream | **Backend WebSocket** (aisstream forbids browsers)[5] | Last-known + optional 15-min trail | Same `/api/vessels` |
| NWS / SPC polygons | Backend poll **or** browser (NWS CORS `*`)[17] | Optional 24 h | GeoJSON FeatureCollection |
| Official JPEG/HLS cameras | Existing `cameras` scraper | Yes, same table | Existing `/stream` + HLS |
**Do not** hit third-party APIs from the Leaflet client when: (a) an API key would leak, (b) CORS is closed, (c) the provider rate-limits by IP and many map users would share one Pi egress. Proxy those through FastAPI.
**Pi / home-uplink constraints:** viewport bbox only. Never poll global ADS-B or global AIS. Cap aircraft poll to 5–10 s, trains 15–30 s, FIRMS already 900 s. Do not store 1 Hz AIS history.
Suggested NATS subjects (match `events.fire`): `events.aircraft`, `events.vessel`, `events.train`, `events.alert`.
Suggested last-known tables (natural keys):
```
aircraft(icao24 PK, callsign, lat, lon, alt_baro_m, gs_kt, track_deg, squawk, src, seen_at)
vessels(mmsi PK, name, lat, lon, sog_kt, cog_deg, navstat, dest, src, seen_at)
trains(train_id PK, route, lat, lon, heading, late_min, src, seen_at)
```
---
## 2. Build order (what to ship first)
### Phase A — frontend-only, no new tables (1–2 days)
1. RainViewer radar overlay (global, no key, CORS `*`).[13][14]
2. IEM NEXRAD CONUS overlay as US-quality alternative (no key, CORS `*`).[15]
3. GIBS `VIIRS_SNPP_Thermal_Anomalies_375m_All` fire-pixel overlay (already documented in `docs/firms.md`).
4. NWS active alerts GeoJSON overlay (no key, User-Agent required, CORS `*`).[17]
5. IEM current storm-based warnings GeoJSON.[16]
### Phase B — backend last-known overlays
6. ADSB.lol viewport aircraft (no key today).[3]
7. OpenSky bbox as fallback / research-grade (anonymous works; OAuth recommended).[1]
8. Amtraker trains (no key; **must** send identifying `User-Agent`).[9]
9. WFIGS incident points + current perimeters (no key).[21]
10. Caltrans CWWP2 cameras into existing `cameras` scraper (JPEG + HLS).[27]
### Phase C — free keys, streams
11. AISStream WebSocket (free GitHub-login key; **server-side only**).[5]
12. Optional OpenSky OAuth client for 4,000 credits/day vs 400 anonymous.[1]
13. Optional Transitland key later for multi-agency GTFS-RT (10k REST/month free).[12]
Skip paid: MarineTraffic, ADS-B Exchange, FlightAware, TrafficLand, OpenWeatherMap One Call paid tiers.
---
## 3. Air traffic
### 3.1 ADSB.lol — **recommended primary for the map**
| | |
|---|---|
| Cost / key | Free, no key today. Docs say a feeder key *may* be required in the future; contact them before treating this as a production SLA.[3] |
| License | ODbL 1.0 (same family as OSM; share-alike on the database).[4] |
| CORS | Treat as **backend-only**. Do not assume browser CORS. |
| Live probe 2026-08-27 | `GET https://api.adsb.lol/v2/lat/35.88/lon/-78.79/dist/50` → HTTP 200, 27 aircraft near RDU. |
Useful endpoints:[3]
```
GET /v2/lat/{lat}/lon/{lon}/dist/{radius_nm} # radius cap 250 nm
GET /v2/point/{lat}/{lon}/{radius}
GET /v2/sqk/{squawk} # e.g. 7700/7600/7500
GET /v2/mil
GET /v2/hex/{icao}
GET /v2/callsign/{callsign}
```
Sample fields from live payload: `hex, flight, r, t, lat, lon, alt_baro, gs, track, squawk, emergency, category, seen_pos`.
**Backend:** poll the **map viewport** (center + radius from bbox, clamp ≤ 150 nm) every 5–10 s. Dedup on `hex`. Do not poll `/v2/mil` on a timer unless the user toggles a mil filter.
**Frontend:** circleMarker or rotating icon, tooltip = `flight`/`hex`/`alt`. Cluster above ~200 markers. Color by altitude or `emergency != none`.
### 3.2 OpenSky Network — research-grade fallback
| | |
|---|---|
| Cost / key | Free for non-commercial / research. Anonymous OK. Authenticated uses OAuth2 **client credentials** (not basic auth). Create `client_id` + `client_secret` on the account page.[1][26] |
| Terms | Cite the OpenSky paper + URL for publications. Commercial needs a license. They may block AWS/hyperscaler IPs.[2] |
| Live probe | `GET /api/states/all?lamin=33.8&lomin=-84.5&lamax=36.6&lomax=-75.4` → HTTP 200, **270** state vectors over NC in 0.63 s. |
Root: `https://opensky-network.org/api`[1]
```
GET /states/all?lamin=&lomin=&lamax=&lomax=&extended=1
```
State vector indexes: `0 icao24, 1 callsign, 2 origin_country, 5 lon, 6 lat, 7 baro_alt m, 8 on_ground, 9 velocity m/s, 10 true_track, 14 squawk`.[1]
Credits (independent buckets for `/states/*`, `/tracks/*`, `/flights/*`):[1]
| Tier | Credits / refill |
|---|---|
| Anonymous | 400 / day |
| Standard user (OAuth) | 4,000 / day |
| Active feeder ≥30% uptime | 8,000 / day |
`/states/all` costs **1–4 credits** by bbox area (≤25 sq° = 1 credit; global = 4). Exhaustion → HTTP 429 + `X-Rate-Limit-Retry-After-Seconds`.[1]
Anonymous: live only, 10 s time resolution. Authenticated: up to 1 hour of history, 5 s resolution.[1]
Token:
```
POST https://auth.opensky-network.org/auth/realms/opensky-network/protocol/openid-connect/token
grant_type=client_credentials&client_id=&client_secret=
Authorization: Bearer <access_token> # ~30 min TTL
```
**Backend:** use OpenSky as fallback when ADSB.lol 429s, or for a “research” toggle. Always send a bbox. NC-sized box is ~25 sq° → 1 credit; 10 s poll as anonymous = 8,640 credits/day → **will 429**. Authenticated 4,000/day ≈ one poll every ~22 s if cost=1. Prefer ADSB.lol for the live map; keep OpenSky for sparse/historical.
**Do not** run this from AWS/the Pi if OpenSky starts blocking the IP; the docs warn about hyperscalers.[2]
### 3.3 AviationWeather.gov METARs (context, not tracks)
No key. User-Agent required. **100 req/min**. **No CORS** — backend only.[22]
```
GET https://aviationweather.gov/api/data/metar?ids=KRDU&format=json
```
Live probe: KRDU thunderstorm METAR returned JSON with `lat/lon/temp/rawOb`. Use as airport popup, not as an aircraft layer. Prefer the gzip cache files for bulk.
### 3.4 Skip
- ADS-B Exchange — paid gateway / API key.
- FlightAware / AeroAPI — paid.
- OpenSky Trino historical — overkill for the live map.
---
## 4. Boat / AIS traffic
### 4.1 AISStream — **recommended live ships**
| | |
|---|---|
| Cost / key | Free. Sign in with GitHub, create key at `/account`. Shown once; rotate from Account.[5][6] |
| Transport | `wss://stream.aisstream.io/v0/stream` |
| Browser | **Forbidden.** Connect from the FastAPI/ingest container and proxy a downsampled last-known feed.[5] |
| Limits | 3 connections / account, 3 / IP. Subscribe JSON **within 3 seconds** or the socket closes. Subscription replace ≤ 1/s. No SLA, no replay.[5] |
| Compression | Negotiate `permessage-deflate`. Uncompressed connections get bandwidth caps starting **September 2026**.[5] |
Subscribe (bbox is **\[\[lat, lon\], \[lat, lon\]\]** — not lon/lat):[5]
```json
{
"APIKey": "<AISSTREAM_API_KEY>",
"BoundingBoxes": [[[33.8, -84.5], [36.6, -75.4]]],
"FilterMessageTypes": [
"PositionReport",
"StandardClassBPositionReport",
"ExtendedClassBPositionReport",
"ShipStaticData"
]
}
```
Frames are **binary WebSocket** containing UTF-8 JSON. Decode bytes, then `json.loads`.[5]
Position envelope (docs + site examples): `MessageType`, `MetaData.{MMSI,ShipName,Latitude,Longitude}`, `Message.PositionReport.{Sog,Cog,TrueHeading,NavigationalStatus}`.[5][6]
**Backend:** one long-lived WS in the `ingest` profile. Filter to the dashboard’s configured bbox (default CONUS coasts + Great Lakes, not world). Upsert last-known by MMSI. Expose `GET /api/vessels?bbox=`. Reconnect with jittered backoff; resend full subscription in <3 s. Do not fan the raw stream to browsers.
**Frontend:** circleMarker, color by nav status / SOG, tooltip name+MMSI. Optional 5-minute trail from in-memory ring, not DB.
### 4.2 AISHub — only if you feed a receiver
Free **if you contribute a live AIS UDP feed**. Then JSON/XML/CSV at most **once per minute**.[7][8]
```
https://data.aishub.net/ws.php?username=USER&format=1&output=json&latmin=&latmax=&lonmin=&lonmax=
```
`format=1` = human-readable degrees / knots. Faster than once/minute returns empty.[8]
Not useful on the Pi unless Lance later stands up an AIS dongle. Keep as a footnote.
### 4.3 Skip / later
- MarineTraffic REST — commercial.
- Global Fishing Watch — free **non-commercial** token, fishing-effort tiles / vessel identity, not a general AIS live layer.[24] Optional Phase D for a “fishing effort” overlay.
- AISHub without a feeder — no data.
---
## 5. Train traffic
There is **no free global live train API**. US intercity is solvable; European freight is not, cheaply.
### 5.1 Amtraker — **recommended US passenger trains**
Community API that rehosts Amtrak + Brightline + VIA Rail. Free. **Identifying `User-Agent` required or the request is blocked.**[9] Data license ODC-By 1.0; attribute “Amtraker” on the map (collapsed OSM-style credit is OK).[9][10]
Live probe: `GET https://api.amtraker.com/v3/trains` and `https://api-v3.amtraker.com/v3/trains` both HTTP 200, **~1.3 MB**, **197 train numbers**. Sample: Sunset Limited `#1`, `lat/lon`, `heading`, `stations[]`, `iconColor`.
```
GET https://api.amtraker.com/v3/trains
GET https://api.amtraker.com/v3/trains/:trainId # e.g. 5-9
GET https://api.amtraker.com/v3/stations
GET https://api.amtraker.com/v3/stale # stale=true if Amtrak >15 min old
```
Poll **15–30 s**. Response is `{ "1": [Train, ...], "5": [...], ... }` — flatten to one row per `trainID`. Do not hammer; the author asks not to spam.[10]
**Frontend:** train icon, color from `iconColor` (or compute lateness). Popup: route, number, next station, delay.
### 5.2 Transitland — multi-agency GTFS-RT (optional, key)
Free plan: **10,000 REST queries/month**, 100k vector tiles/month, 1,000 routing/month. Key via Interline signup (`apikey=` query or header; **not** `Authorization`). Attribution required.[11][12]
```
https://transit.land/api/v2/rest/
```
Use later if you want commuter rail / subway vehicle positions (LA Metro, MTA, etc.). 10k/month is only ~13 queries/hour — **cannot** poll every agency every 15 s. Cache GTFS-RT protobufs yourself from the **agency’s own feed URL** (those are usually free, no Transitland meter). Transitland is a directory; the live positions should come from the agency GTFS-RT URL listed in the Atlas.
### 5.3 OpenRailwayMap — infrastructure tiles only
`https://tiles.openrailwaymap.org/{style}/{z}/{x}/{y}.png` — OSM-derived tracks, not live trains.[25] This probe’s HEAD got **HTTP 403** (UA/hotlink?). Treat as optional overlay; do not depend on it. No vehicle data.
### 5.4 Skip
- Official Amtrak Track-A-Train JSON — unofficial reverse-engineering; Amtraker already does this legally enough for a hobby map, with a documented UA policy.
- Deutsche Bahn / Network Rail — free-ish developer portals but EU-centric and key + ToS heavy. Out of scope unless the map goes global-rail.
---
## 6. Open video / camera feeds (official public only)
Do **not** add Insecam-style random IP cams as a new source. The scraper already has a public list; this section is **agency-published** JPEG/HLS.
### 6.1 Already wired
- ALERTWest / ALERTCalifornia: `https://api.cdn.prod.alertwest.com/api/getCameraDataByLoc` — live probe HTTP 200, **6.6 MB** JSON with `data.locs` + `data.cams`. Snapshots at `https://img.cdn.prod.alertwest.com/data/img/{cid}/...` (see `parse_alertwest_json`).
- Live-Environment-Streams GeoJSON (HLS / YouTube / JPEG).
- `public-ip-cams` README list.
### 6.2 Caltrans CWWP2 — **add to CAMERA_SOURCE_URLS**
Official CA DOT CCTV. No key.
```
https://cwwp2.dot.ca.gov/data/d{N}/cctv/cctvStatusD{NN}.json
```
Live probe D4: HTTP 200, **2.4 MB**, **749 cameras**.
Each `data[].cctv`:
- `location.{latitude,longitude,locationName,nearbyPlace,district,route,county,direction}`
- `inService` (`"true"`/`"false"`)
- `imageData.static.currentImageURL` — JPEG, updates ~5 s (`https://cwwp2.dot.ca.gov/data/d4/cctv/image/...jpg`)
- `imageData.streamingVideoURL` — **HLS** `https://wzmedia.dot.ca.gov/D4/....stream/playlist.m3u8`
Districts 1–12 exist with the same schema (D4 verified). Backend: new parser next to `parse_alertwest_json`, skip `inService != true`, store JPEG as `snapshot_url`, HLS as stream URL (dashboard already vendors `hls.min.js`). Frontend: same camera popup; prefer JPEG for map thumbs, HLS in the preview pane. Never RTSP.
Politeness: scrape hourly like other sources (`CAMERA_SCRAPE_INTERVAL=3600`). Do not scrape every JPEG every cycle — store URLs, let the snapshot cache fetch on demand.
### 6.3 IEM webcams — small, Iowa-centric bonus
```
GET https://mesonet.agron.iastate.edu/geojson/webcam.geojson
```
No key, CORS permissive.[23] Live probe: HTTP 200, **3** cameras at probe time (not a national network). Fields: `cid, name, imgurl, utc_valid, state`. Nice extra source, low value vs ALERTWest/Caltrans.
### 6.4 YouTube live (already in Live-Environment-Streams)
Do not call the YouTube Data API unless you want search. Embedding existing stream URLs from the GeoJSON is enough. YouTube Data API **requires a Google key** and quota.
### 6.5 Skip
- Insecam / random “public IP cam” aggregators — ToS / privacy.
- TrafficLand, EarthCam commercial APIs.
- SkylineWebcams — scraping, not an API.
---
## 7. Fire maps (beyond current FIRMS points)
FIRMS CSV = hotspot **points** (already ingested). WFIGS = **incident identity + perimeters**. GIBS = **pixel overlay**. Use all three; they answer different questions.
### 7.1 WFIGS current incident locations — **recommended vector layer**
No key. ArcGIS FeatureServer, GeoJSON.
```
https://services3.arcgis.com/T4QMspbfLg3qTGWY/arcgis/rest/services/WFIGS_Incident_Locations_Current/FeatureServer/0/query
?where=1=1&outFields=IncidentName,IncidentSize,FireDiscoveryDateTime,POOState,PercentContained,IncidentTypeCategory,FireCause
&outSR=4326&f=geojson
```
Live probe: **635** current locations. Sample: `Foster Bridge`, 675 acres, `US-FL`, 100% contained, cause Human. `FireDiscoveryDateTime` is **epoch ms**.
Poll 5–15 min (NIFC says related perimeter service refreshes ~5 min).[21] Backend can proxy `GET /api/fire-incidents` so the keyless URL is cached. Frontend: labeled point, popup acres / contained %.
Some similarly named services (`Current_WildlandFire_Locations`) return **Token Required** — stick to `WFIGS_Incident_Locations_Current`.
### 7.2 WFIGS current perimeters — **recommended polygon overlay**
```
https://services3.arcgis.com/T4QMspbfLg3qTGWY/arcgis/rest/services/WFIGS_Interagency_Perimeters_Current/FeatureServer/0/query
?where=1=1&outFields=poly_IncidentName,poly_GISAcres,attr_IncidentSize,attr_PercentContained,attr_FireDiscoveryDateTime
&outSR=4326&f=geojson
```
Live probe: **236** current perimeters. Historic `WFIGS_Interagency_Perimeters` counted **41,078** — do not fetch that unfiltered. Use Current only, or `resultRecordCount` + bbox `geometry` + `spatialRel=esriSpatialRelIntersects`.
Authoritative US wildland-fire polygons; not every incident has a perimeter. Refresh ~5 min, fall-off rules drop stale small fires.[21]
**Frontend:** `L.geoJSON` fill red/orange by acres. Click for name/acres. This is the layer that makes FIRMS dots make sense.
### 7.3 GIBS thermal tiles (no key, no storage)
Already in `docs/firms.md`. Leaflet:
```
https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/VIIRS_SNPP_Thermal_Anomalies_375m_All/default/{time}/GoogleMapsCompatible_Level{z}/{y}/{x}.png
```
Max zoom ~9. `{time}` = `YYYY-MM-DD`. Same GIBS CORS `*` as existing basemaps. Use as a toggle under FIRMS points.
### 7.4 FIRMS dataset note
Keep the CSV ingest. Add NOAA-20/21 datasets. Ultra-real-time US/Canada is available on those products (seconds-scale for much of US/Canada).[20]
---
## 8. Weather radar + alerts
### 8.1 RainViewer — **recommended global radar overlay**
No key. Personal / educational / small community. Attribution: “Weather data by RainViewer” + link.[13]
Live probe: `GET https://api.rainviewer.com/public/weather-maps.json` → version `2.0`, host `https://tilecache.rainviewer.com`, **13** past frames (~2 h, 10 min steps). Tile HEAD: HTTP 200, CORS `*`, **`x-ratelimit-limit: 500` / 60 s**, burst 300.
Tile URL:[14]
```
{host}{path}/{size}/{z}/{x}/{y}/{color}/{smooth}_{snow}.png
```
Example: `https://tilecache.rainviewer.com/v2/radar/cb581daa2c0f/256/{z}/{x}/{y}/2/1_1.png`
- `{size}` 256 or 512
- `{color}` scheme id (2 is a common default)
- `{smooth}_{snow}` e.g. `1_1`
- **max zoom 7** (coarse vs IEM)
**Frontend:** fetch the JSON every 5 min, set `L.tileLayer` to the latest `past[].path`. Optional animation through `past` frames. No backend.
### 8.2 IEM NEXRAD / MRMS — **recommended CONUS quality radar**
Iowa Environmental Mesonet. No key. Free including commercial, as-is, no SLA.[16] CORS `*` on tiles (live HEAD confirmed).
Current CONUS base reflectivity TMS:[15]
```
https://mesonet.agron.iastate.edu/cache/tile.py/1.0.0/nexrad-n0q/{z}/{x}/{y}.png
```
Cache-Control 5 min. Aliases `mesonet1/2/3.agron.iastate.edu` for parallel browser tile fetches.[15]
Loop (past 5–55 min, step 5): layer `nexrad-n0q-mXXm` e.g. `nexrad-n0q-m05m`.
Also useful:
| Layer | Meaning |
|---|---|
| `nexrad-eet` | Echo tops |
| `q2-hsr` | MRMS seamless hybrid-scan reflectivity |
| `q2-n1p` / `q2-p24h` | MRMS 1 h / 24 h precip |
| `goes_east_conus_ch02` | GOES-East visible |
| `goes_east_conus_ch13` | GOES-East IR |
WMS alternative: `https://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0q.cgi?` — TMS is simpler for Leaflet.
**Frontend:** use IEM as default when the map is over CONUS (higher res than RainViewer z7); RainViewer when zoomed outside the US or as a global fallback.
### 8.3 NWS API — alerts / forecasts (no radar tiles)
`https://api.weather.gov` — US public domain, no fee. **User-Agent required** (app + contact). Rate limit unpublished; 429s clear in ~5 s. CORS `*`.[17]
Live probe: `GET /alerts/active?area=NC` → HTTP 200 GeoJSON, 4 alerts, CORS `*`.
```
GET https://api.weather.gov/alerts/active?area=NC
GET https://api.weather.gov/alerts/active?point={lat},{lon}
GET https://api.weather.gov/points/{lat},{lon} # then follow forecast URLs
```
**Frontend can hit this directly** (CORS open) **or** backend can cache 30 s to protect the Pi if many tabs are open. Prefer backend cache. Draw `features[].geometry` with color by `properties.severity` / `event`.
### 8.4 IEM storm-based warnings GeoJSON
```
GET https://mesonet.agron.iastate.edu/geojson/sbw.geojson
```
Live probe: **46** current polygons. Sample: Severe Thunderstorm Warning, WFO BGM. Good companion to NWS alerts (polygon-accurate).
### 8.5 Open-Meteo — point forecast, not radar
No key for non-commercial **< 10,000 calls/day**. CC BY 4.0 data, attribution required. Commercial needs a plan or self-host.[18][19]
```
GET https://api.open-meteo.com/v1/forecast?latitude=35.88&longitude=-78.79&current=temperature_2m,precipitation,weather_code,wind_speed_10m
```
Live probe: RDU 28.4 °C, weather_code 80 (rain showers). Use for click-to-forecast popups, not a map overlay. Cache by grid cell.
### 8.6 NHC active storms
```
GET https://www.nhc.noaa.gov/CurrentStorms.json
```
Live probe: HTTP 200, `activeStorms[]` — Tropical Storm Dolly (`al042026`, 13.6N 38.7W, 35 kt). No key. Plot as a hurricane marker + optional NHC cone GeoJSON (separate NHC GIS products). Nice extra during Atlantic season.
---
## 9. Keys / env vars to add
Store new secrets in the existing Keys UI (`api_keys` table) **and** `.env` fallback, same planned pattern as FIRMS.
| Var | Required for | How to get | Cost |
|---|---|---|---|
| `FIRMS_MAP_KEY` | Existing fire CSV | https://firms.modaps.eosdis.nasa.gov/api/map_key_info/ | Free |
| `OPENSKY_CLIENT_ID` / `OPENSKY_CLIENT_SECRET` | OpenSky authenticated | OpenSky account → API Client | Free |
| `AISSTREAM_API_KEY` | Live AIS | GitHub login at aisstream.io/account | Free |
| `TRANSITLAND_API_KEY` | Transitland REST (optional) | Interline free plan | Free 10k/mo |
| `GFW_TOKEN` | Fishing-effort overlay (optional) | globalfishingwatch.org/our-apis/tokens | Free, non-commercial |
| *(none)* | ADSB.lol, Amtraker, RainViewer, IEM, NWS, WFIGS, Caltrans, Open-Meteo, NHC | — | Free |
Amtraker: no key, but set `OSINT_USER_AGENT` to something like `osint-dashboard/1.0 ([email protected])` — already have `USER_AGENT` in `camera_config.py`; reuse it on **all** outbound HTTP.
NWS: same User-Agent header is mandatory.[17]
---
## 10. Suggested API surface (backend engineer)
Keep FIRMS `GET /api/fires`. Add:
```
GET /api/aircraft?bbox=minlon,minlat,maxlon,maxlat
GET /api/vessels?bbox=...
GET /api/trains?bbox=...
GET /api/fire-incidents?bbox=... # WFIGS points
GET /api/fire-perimeters?bbox=... # WFIGS polygons (or proxy GeoJSON)
GET /api/alerts?area=NC|&bbox=... # cached NWS + IEM SBW
GET /api/map/radar # { provider, tileUrl, frames[] } for RainViewer metadata
GET /api/map/layers # already have GIBS; extend with radar/fire tile templates
```
All vector endpoints: default `limit=2000`, require bbox except trains (Amtrak is ~200 rows total). Return arrays of `{id, lat, lon, heading, speed, label, extra}` so the frontend can share one marker renderer.
Do **not** proxy RainViewer/IEM/GIBS tiles through the Pi (bandwidth). Return the template; browser fetches tiles.
AISStream stays inside `ingest` profile (needs a long-lived process, like FIRMS). Aircraft/trains can live in `run_ingester.py` loops.
---
## 11. Suggested UI (frontend bot)
Layer toggles on the existing Leaflet map (same pattern as GIBS + fire heatmap):
| Toggle | Default | Source |
|---|---|---|
| Radar | on (CONUS) | IEM `nexrad-n0q` if view intersects US, else RainViewer |
| NWS alerts | on | polygons |
| FIRMS heat | existing | existing |
| WFIGS perimeters | on | polygons |
| WFIGS incidents | off | points |
| Aircraft | on | `/api/aircraft` |
| Vessels | off until AIS key | `/api/vessels` |
| Trains | on | `/api/trains` |
| Cameras | existing | existing |
Viewport-driven: on `moveend` (debounced 300 ms), refetch aircraft/vessels for the new bbox. Do not refetch radar tiles except RainViewer frame JSON every 5 min.
Marker performance: canvas renderer (`L.canvas()`), cluster at zoom < 7, hide labels until zoom ≥ 8.
Camera preview: Caltrans HLS via existing hls.js path; JPEG thumb from `currentImageURL`. Still never emit RTSP.
Attribution bar (required): OpenSky / ADSB.lol ODbL / Amtraker / RainViewer / IEM / NWS / NASA FIRMS-GIBS / NIFC WFIGS / OSM as applicable.
---
## 12. Legal / ethics (non-negotiable)
- RTSP policy unchanged (never emit `rtsp://` hrefs).
- AISStream: server-side only; do not put the key in JS.[5]
- OpenSky: non-commercial unless licensed; cite if you publish.[2]
- ADSB.lol: ODbL share-alike on derived databases.[4]
- Amtraker: ODC-By, visible credit, identifying UA.[9]
- RainViewer: personal/educational; credit + link.[13]
- Open-Meteo: non-commercial 10k/day on the public instance.[18]
- GFW: non-commercial.[24]
- Caltrans / NWS / NIFC / NASA / IEM: US public or explicitly open; still cache politely.
- Do not scrape MarineTraffic / FlightRadar24 / FlightAware map tiles.
---
## 13. Verification log (this research session)
| Endpoint | Result |
|---|---|
| OpenSky `/states/all` NC bbox | 200, 270 aircraft, 0.63 s |
| ADSB.lol `/v2/lat/35.88/lon/-78.79/dist/50` | 200, 27 aircraft |
| RainViewer `weather-maps.json` | 200, 13 past frames |
| RainViewer tile | 200, CORS `*`, 500 req/min header |
| Open-Meteo forecast RDU | 200, 28.4 °C, code 80 |
| NWS `/alerts/active?area=NC` | 200, 4 alerts, CORS `*` |
| IEM `nexrad-n0q` tile | 200, CORS `*`, max-age 300 |
| IEM `sbw.geojson` | 200, 46 polygons |
| IEM `webcam.geojson` | 200, 3 cams |
| WFIGS locations count | 635 |
| WFIGS current perimeters count | 236 |
| ALERTWest `getCameraDataByLoc` | 200, 6.6 MB |
| Caltrans D4 CCTV JSON | 200, 749 cams, JPEG + HLS |
| Amtraker `/v3/trains` | 200, ~197 numbers, 1.3 MB |
| AviationWeather METAR KRDU | 200 JSON |
| NHC `CurrentStorms.json` | 200, TS Dolly |
| OpenRailwayMap tile HEAD | **403** — do not rely on |
---
## 14. Concrete next tickets
**Backend**
1. `FIRMS_DATASET` dual-write NOAA-20/21; document S-NPP sunset.
2. `aircraft` ingest: ADSB.lol viewport poll + `/api/aircraft`.
3. `trains` ingest: Amtraker 30 s poll + User-Agent + `/api/trains`.
4. Camera parser: Caltrans CWWP2 D1–D12 → existing `cameras` rows (`discovery_source=caltrans`).
5. WFIGS proxy endpoints (locations + current perimeters), 5–15 min cache.
6. AISStream worker behind `AISSTREAM_API_KEY` (idle if unset, same as FIRMS).
7. `/api/alerts` 30 s cache of NWS + IEM SBW.
**Frontend**
1. Layer control: radar (IEM/RainViewer), alerts, WFIGS, aircraft, trains, vessels.
2. Shared point-layer component (id, lat, lon, heading, label).
3. RainViewer frame JSON → animated overlay.
4. Caltrans HLS in existing preview pane.
5. Attribution strip.
**Do not start with:** Transitland, GFW, AISHub, OpenSky OAuth (until ADSB.lol is live and still needs a fallback).
## Sources
[1] https://openskynetwork.github.io/opensky-api/rest.html
[2] https://openskynetwork.github.io/opensky-api
[3] https://api.adsb.lol
[4] https://www.adsb.lol/docs/open-data/api
[5] https://aisstream.io/documentation
[6] https://aisstream.io
[7] https://www.aishub.net
[8] https://www.aishub.net/api
[9] https://github.com/piemadd/amtrak
[10] https://amtraker.com/about
[11] https://www.transit.land/documentation
[12] https://www.transit.land/plans-pricing
[13] https://www.rainviewer.com/api.html
[14] https://www.rainviewer.com/api/weather-maps-api.html
[15] https://mesonet.agron.iastate.edu/ogc
[16] https://mesonet.agron.iastate.edu/api
[17] https://www.weather.gov/documentation/services-web-API
[18] https://open-meteo.com
[19] https://open-meteo.com/en/docs
[20] https://firms.modaps.eosdis.nasa.gov/api/area
[21] https://data-nifc.opendata.arcgis.com/datasets/nifc::wfigs-current-interagency-fire-perimeters/about
[22] https://aviationweather.gov/data/api
[23] https://mesonet.agron.iastate.edu/geojson/webcam.py?help
[24] https://globalfishingwatch.org/our-apis/documentation
[25] https://openrailwaymap.org
[26] https://opensky-network.org/about/faq
[27] https://cwwp2.dot.ca.gov/vm/iframemap.htm

View file

@ -1,347 +0,0 @@
# News pipeline — scraper + Nous Portal summarizer
The OSINT dashboard ingests a large curated feed list (`news/scraper/urls.txt`)
continuously and produces an English LLM brief plus flagged ticker/map rows
every 15 minutes. Both services were vendored from the upstream
`~/Projects/newsPipeline` project and re-integrated here against the EXISTING
osint-db — **no second Postgres**. The LLM is **Nous Portal**
(`inference-api.nousresearch.com`) — not Gemini.
## Architecture
```
urls.txt (RSS + homepages)
│
▼
news-scraper (Scrapy, continuous) ──► articles table (osint-db)
│ │
│ ▼
news-summarizer (Nous Portal, every 15m + 23:00 recap) ──► article_summaries + news_items
│
▼
GET /api/news · /api/news/summaries · /api/news/ticker · /api/news/map
GET /api/news/models · GET/PUT /api/settings
```
| Component | Image | Container | Scheduling |
|---|---|---|---|
| Scraper | `localhost/osint-news-scraper` | `osint-news-scraper` | loop, `NEWS_SCRAPE_INTERVAL_S` (default 10s after each crawl) |
| Summarizer | `localhost/osint-news-summarizer` | `osint-news-summarizer` | loop, `NEWS_SUMMARIZE_INTERVAL_S` (default 900s) |
Both services live under the `ingest` compose profile (same as the ingester
and camera-scraper): `docker compose --profile ingest up -d`.
The summarizer is a batch sidecar, **not** a live overlay. Do **not** reuse
`GET /api/alerts` (dashboard entity/keyword alerts). Do **not** stuff news
into `overlay_catalog()` — `/api/map/layers` `overlays` stays live upstream
feeds (`GET /api/news` exact key set is unchanged on purpose).
## Data flow
1. **Scraper** — `news/scraper/run_news_scraper.py` runs
`scrapy crawl articles` back-to-back (default 10s pause). The spider reads
URLs from `urls.txt` (homepages autodiscover RSS; feed URLs are parsed
directly), follows each `<item>` link, extracts the main article body, and
the `PostgresPipeline` writes to `articles` with URL-based dedup
(`ON CONFLICT (url) DO NOTHING`). Items whose parsed publish date is more
than 2 hours in the future are dropped at ingest (`future_dated_dropped`)
and never surface via `/api/news`, which additionally hides any
`articles.timestamp > now()` row until its date arrives.
2. **Summarizer** — `news/summerizer/run_news_summarizer.py` runs
`summarizer.py` every `NEWS_SUMMARIZE_INTERVAL_S` (default 900) over the
last `SUMMARY_WINDOW_MINUTES` (default 15), and again at 23:00
`America/New_York` (`TZ`) over the last 24 hours as a daily recap
(`kind=daily_recap`). Both map-reduce through Nous Portal (`SUMMARY_MODEL`
/ Settings, default `Hermes-4.3-36B`), write the English brief to
`article_summaries` (column `model` is the LLM id; `kind` is
`interval` or `daily_recap`), and flagged ticker/map rows to `news_items`.
Loops are serial (two crawls/summaries never overlap). Interval idempotency:
if `article_summaries` already has a row in the last interval, the summarizer
**skips** (prevents double-pins on `RUN_ON_START` recreate). Set
`NEWS_SUMMARIZE_FORCE=1` to ignore that skip.
The `articles` and `article_summaries` tables are created by the idempotent
alembic migration `003_news` (also created by the scraper's own
`CREATE TABLE IF NOT EXISTS`). `news_items` is alembic `005_news_items` and
`article_scores` is `012_article_scores` (also created by the summarizer's own
`ensure_tables()`). Container startup order doesn't matter.
## Grading and selection
The map phase grades every article 0-100 against the rubric in the map prompt
(90-100 breaking geopolitical/military/security or major disaster, 70-89
significant national/international news, 40-69 notable regional/economic/tech/
health, 10-39 routine crime and local interest, 0-9 noise: sport, celebrity,
entertainment, market tape, promotional and event-calendar listings). The
summarizer parses the first `Score:` line in each `Article <n>:` block, clamps
it to 0-100, and falls back to the `Importance:` label (critical 95, high 78,
medium 50, low 22, none 5) when the line is missing or unparsable — a block is
never dropped and the fallback count is logged per batch. Only blocks scoring
`>= SUMMARY_MIN_SCORE` (default 60) reach the reduce prompt, best first, capped
at `SUMMARY_TOP_N` (default 12). If nothing clears the bar, up to
`SUMMARY_FALLBACK_TOP` blocks (default 3) scoring at least
`SUMMARY_FALLBACK_MIN_SCORE` (default 40) are used; when none does, or when
`SUMMARY_FALLBACK_TOP=0`, the reduce phase receives an empty DATA section and
writes the empty-brief response instead of promoting noise. The reduce prompt
no longer asks for filler: it leads with the highest-scoring stories and never
promotes an item above its score. Every graded article is persisted to
`article_scores` (score, category, selected, model, summary_id) so the operator
can tune the thresholds against real data.
Syndicated wire copy is collapsed **before** the threshold and cap, so
`SUMMARY_TOP_N` counts distinct stories instead of stations: the same headline
carried by seven Hearst domains is one story, not seven. Titles are normalised
first (lowercase, punctuation flattened, a trailing ` - KCCI` / ` | CNN` /
` — AP` source suffix dropped when it is short and digit-free), then two blocks
are the same story when the normalised titles are equal or at least
`SUMMARY_DEDUPE_SIMILARITY` similar (default 0.85; word-set Jaccard or
word-sequence `difflib` ratio). The highest-scoring copy represents the story
(ties → earliest); differing `category` values and titles that disagree on any
number are never merged. Duplicates are still written to `article_scores` with
`selected=false` and `duplicate_of` = the surviving `article_id`, so nothing is
lost for tuning. `SUMMARY_DEDUPE=0` disables dedupe entirely; raising
`SUMMARY_DEDUPE_SIMILARITY` toward 0.95 makes it stricter. Dedupe is pure string
work — no extra LLM call.
## Keys and Settings
- **`NOUS_API_KEY`** — paste in the dashboard **Keys** UI (`api_keys` /
`keystore.KEY_REGISTRY`). Env / `.env` is an **override** (env wins, same
as FIRMS). Never returned by any API; never emitted into `index.html`;
never proxied from the browser.
- **Idle without a key** — if env is unset **and** the keystore row is empty,
the summarizer logs and idles (never crashes). News intel APIs return `[]`.
- **Model** — non-secret. Settings UI model selector `PUT /api/settings`
`{ "summary_model": "…" }` stores `SUMMARY_MODEL` in `app_settings` (1–128
chars). `GET /api/settings` echoes `{summary_model, nous_base_url}`.
`nous_base_url` is read-only. Default `Hermes-4.3-36B`. Live catalog is
best-effort `GET /api/news/models`.
## Endpoints
### GET /api/news — recent articles
Key set **unchanged** (no `lat`/`lon` on articles; geo lives on `/api/news/map`).
| Query param | Meaning | Default |
|---|---|---|
| `domain` | filter by source domain (e.g. `www.reuters.com`) | none |
| `since` | only articles captured at/after this UTC instant (ISO-8601) | none |
| `limit` | max rows | `50` (max `500`) |
| `offset` | pagination offset | `0` |
| `include_content` | include full article body | `false` |
```json
[
{
"id": 1,
"title": "…",
"url": "https://…",
"content": null,
"domain": "www.reuters.com",
"timestamp": "2026-08-24T18:10:00Z"
}
]
```
### GET /api/news/summaries — master LLM briefs
| Query param | Meaning | Default |
|---|---|---|
| `since` | only summaries generated at/after this UTC instant | none |
| `limit` | max rows | `20` (max `100`) |
| `offset` | pagination offset | `0` |
```json
[
{
"id": 1,
"summary_text": "English markdown brief…",
"batch_timestamp": "2026-08-24T18:10:00Z",
"model": "Hermes-4.3-36B",
"kind": "daily_recap"
}
]
```
`model` and `kind` are additive (`interval` | `daily_recap` | `null` for old rows).
`?kind=daily_recap` pins the nightly 24h recap. Empty DB → `[]` (no crash).
Malformed `kind` → `422`.
### GET /api/news/ticker — HUD headlines
Critical/high `news_items` with `kind=ticker` first. If none are flagged,
medium/low ticker rows fill the tape so the dock is not blank. Do **not**
reuse `GET /api/alerts`. Bottom HUD `#nt-track` scrolls these rows, not a
dump of the whole brief.
| Query param | Meaning | Default |
|---|---|---|
| `since` | only items created at/after this UTC instant | none |
| `limit` | max rows | `20` (max `50`) |
```json
[
{
"id": 1,
"headline": "…",
"importance": "critical",
"location_name": "Kyiv",
"url": "https://…",
"created_at": "2026-08-24T18:10:00Z"
}
]
```
### GET /api/news/map — geolocated critical/high pins
Only rows with valid `lat`/`lon`. Optional bbox. **No zoom skip** — world
view is the point. Layer-panel toggle uses this dedicated path (same as
event blips), not `overlay_catalog`.
| Query param | Meaning | Default |
|---|---|---|
| `bbox` | `minlon,minlat,maxlon,maxlat` | all flagged pins |
| `since` | only items created at/after this UTC instant | last 24 hours |
| `limit` | max rows | `200` (max `500`) |
Malformed bbox → `422`.
```json
[
{
"id": 1,
"headline": "…",
"importance": "high",
"location_name": "Kyiv",
"lat": 50.45,
"lon": 30.52,
"location_confidence": "city",
"category": "military/conflict",
"url": "https://…",
"created_at": "2026-08-24T18:10:00Z"
}
]
```
Pins are LLM-estimated and clamped (`lat∈[-90,90]`, `lon∈[-180,180]`). No
Nominatim. No writes into `events`.
### GET /api/news/models — Settings dropdown catalog
Never 502s. `{ "source": "live"|"fallback", "models": [{"id": "…"}] }`.
### GET /api/settings · PUT /api/settings
```json
{ "summary_model": "Hermes-4.3-36B", "nous_base_url": "https://inference-api.nousresearch.com/v1" }
```
PUT body is `{ "summary_model": "<1–128 char id>" }`. `nous_base_url` is
ignored even if sent.
## Reduce JSON contract
Reduce phase (`response_format: json_object`, English only) must be a single
object. Parser (`intel.parse_reduce_json`) strips `<think>…</think>` and
markdown json fences, then brace-slices:
```json
{
"summary_en": "English markdown brief or the no-qualifying-events sentence",
"ticker": [
{"headline": "", "importance": "critical", "url": "", "location_name": ""}
],
"map_items": [
{
"headline": "",
"importance": "critical",
"location_name": "",
"lat": 0,
"lon": 0,
"location_confidence": "city",
"category": "military/conflict",
"url": ""
}
]
}
```
Persist ticker for critical/high first; if none, persist medium/low so the
tape is not empty. Map rows stay critical/high with valid coords; Unknown /
invented places are dropped. Caps: 12 ticker (≤140 chars, no markdown), 20
map. `summary_en` lands in `article_summaries.summary_text`.
## Configuration (all via env / `.env`)
| Var | Default | Notes |
|---|---|---|
| `NOUS_API_KEY` | *(blank)* | **Required for summaries.** Prefer Keys UI; env overrides. Unset in **both** env and `api_keys` = summarizer logs and idles (never crashes); APIs return `[]`. |
| `NOUS_BASE_URL` | `https://inference-api.nousresearch.com/v1` | Read-only in Settings. |
| `SUMMARY_MODEL` | `Hermes-4.3-36B` | Compose default. Operator-facing choice is Settings → `app_settings.SUMMARY_MODEL`. |
| `NEWS_BATCH_SIZE` | `50` | Articles per map-phase batch (compose maps to container `BATCH_SIZE`). |
| `SUMMARY_MIN_SCORE` | `60` | Map-phase score a block must reach to enter the reduce brief. |
| `SUMMARY_TOP_N` | `12` | Max blocks passed to the reduce phase (best score first). |
| `SUMMARY_FALLBACK_TOP` | `3` | Blocks used when nothing clears `SUMMARY_MIN_SCORE`; `0` = empty DATA. |
| `SUMMARY_FALLBACK_MIN_SCORE` | `40` | Score floor for the fallback set; below it the reduce phase gets empty DATA. |
| `SUMMARY_DEDUPE` | `1` | Collapse syndicated wire copies before selection; `0` skips dedupe entirely. |
| `SUMMARY_DEDUPE_SIMILARITY` | `0.85` | Normalised-title similarity at which two blocks count as the same story (1.0 = verbatim only). |
| `SUMMARY_WINDOW_MINUTES` | `15` | How far back the summarizer looks for new articles (window is `(now - N, now]`; future-dated rows are ignored). |
| `NEWS_SCRAPE_INTERVAL_S` | `10` | Pause after each crawl before the next (scraper is otherwise continuous). |
| `NEWS_SUMMARIZE_INTERVAL_S` | `900` | Seconds between analyst runs (default 15 min). |
| `TZ` | `America/New_York` | Timezone for the 23:00 daily recap. |
| `NEWS_RECAP_HOUR` | `23` | Local hour of the daily 24h recap. |
| `NEWS_RECAP_MINUTE` | `0` | Local minute of the daily recap. |
| `NEWS_SCRAPE_RUN_ON_START` | `1` | Run one scrape immediately on container start. |
| `NEWS_SUMMARIZE_RUN_ON_START` | `1` | Run one summarize immediately on container start. |
| `NEWS_SUMMARIZE_FORCE` | `0` | `1` ignores the interval/recap idempotency skip (double-pins on recreate). |
| `INCLUDE_FUTURES` | `0` | Legacy. Ignored — prompts never inject futures/market tape. |
| `NEWS_LOG_LEVEL` | `INFO` | Scrapy log level. |
| `OSINT_USER_AGENT` | `osint-dashboard-news-summarizer` | Sent on every outbound Nous call. |
| `TELEGRAM_TOKEN` / `TELEGRAM_CHAT_ID` | *(blank)* | Reserved for the (out-of-scope) Telegram delivery bot. |
DB_* for both services is mapped to the shared osint-db credentials
(`DB_HOST=db`, same `DB_USER/DB_PASSWORD/DB_NAME` as the rest of the stack).
Nous chat: `POST {NOUS_BASE_URL}/chat/completions` via `news/summerizer/nous_client.py`
(`httpx`, no `openai` SDK). Auth is a Bearer token from `NOUS_API_KEY`.
No Hermes-4 reasoning system prompt. Reduce uses `json_mode=True`.
## Prompts
Both prompts are env-overridable. Defaults recap the articles actually
provided, ranked by breaking important news, and ignore futures / commodity
tape. ticker/map may be empty; `summary_en` must still be a real brief.
`RECAP_PROMPT` (23:00, 24h window) is the daily recap; `SUMMARY_PROMPT` is the
15-min analyst. `INCLUDE_FUTURES` is ignored.
## Tests
```bash
PYTHONPATH=news/summerizer pytest news/summerizer/tests -v
# intel + nous_client tests PASS (no network)
PYTHONPATH=app pytest tests/test_api_news.py \
tests/test_api_settings.py tests/test_api_live_layers.py -v
# DB-marked tests skip without Postgres; live_layers must still PASS
# /api/map/layers overlays key set UNCHANGED
```
## Live verification
After deploy / compose rebuild of `news-summarizer` on the Pi:
1. Keys UI: save `NOUS_API_KEY` → status `****last4`.
2. Settings: pick a model → Save → `GET /api/settings` echoes it.
3. `docker compose --profile ingest logs -f news-summarizer` — next run (or
`NEWS_SUMMARIZE_RUN_ON_START=1` recreate) logs `Processing N articles with <model>`.
4. `curl -s localhost:8000/api/news/summaries?limit=1` — English `summary_text`, `model` set.
5. `curl -s localhost:8000/api/news/ticker` — flagged headlines only.
6. `curl -s localhost:8000/api/news/map` — only rows with lat/lon.
7. HUD: NEWS ticker scrolls flagged items; map overlay pins popup with location.
8. Unset key + empty keystore → summarizer logs idle, APIs return `[]`, no crash.
**Operator action after merge:** paste a Nous Portal API key in API Keys; pick
a model in Settings if the default `Hermes-4.3-36B` is not wanted; rebuild
`osint-news-summarizer` on the Pi (`pi-app-deploy` / compose).

View file

@ -1,347 +0,0 @@
# Free satellite feeds for the OSINT map
Builder inventory (research profile). Probed **2026-08-29** from this machine. Do **not** treat search snippets as live — every row below had a `curl`/GET (tile, GetCapabilities, STAC, or GetMap). 404 tile rows are omitted unless Capabilities/DescribeDomains still prove the layer exists (sparse fire overlays 404 on empty tiles).
**Pi rules:** browser `L.tileLayer` when CORS `*`; do not proxy multi-GB COGs through the Pi; STAC+SAS like existing Sentinel-1 is “backend same as S-1”; no Redis; home uplink is small.
GIBS Web Mercator REST template (no key):[2]
```
https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/{layer}/default/{time}/{TileMatrixSet}/{z}/{y}/{x}.{jpg|png}
```
Omit `{time}` for static layers. Sub-daily GOES/Himawari accept `YYYY-MM-DD` **or** `YYYY-MM-DDTHH:MI:SSZ` (GIBS snaps to nearest).[2] Attribution: NASA asks clients to acknowledge GIBS/ESDIS.[1]
Live GetCapabilities `epsg3857/best` on 2026-08-29: **1315** `Layer` entries, **all** with a `GoogleMapsCompatible_LevelN` matrix, `access-control-allow-origin: *`.[4] GIBS documents **1000+** visualizations; many LANCE layers appear within **3.5 hours** of observation.[3]
Worldview is the interactive catalog of the same tiles.[5] GIBS developer portal: Earthdata GIBS API page (HTTP 403 from this host at probe time; docs site above is the working copy).[27]
---
## Already in the product (do not rediscover)
| id | status |
|---|---|
| `BlueMarble_ShadedRelief_Bathymetry` | GIBS basemap (`app/gibs_map.py`) |
| `VIIRS_SNPP_CorrectedReflectance_TrueColor` | GIBS basemap |
| `MODIS_Terra_CorrectedReflectance_TrueColor` | GIBS basemap |
| `MODIS_Aqua_CorrectedReflectance_TrueColor` | GIBS basemap |
| `VIIRS_SNPP_DayNightBand_ENCC` | GIBS night lights |
| FIRMS VIIRS hotspot CSV | ingest + `FIRMS_MAP_KEY` |
| `VIIRS_SNPP_Thermal_Anomalies_375m_All` | overlay in `app/live_layers.py` (`gibs_thermal`). **Caps now say TMS `GoogleMapsCompatible_Level8`**, not Level9 — the wired URL uses Level9 (will 400). |
| Sentinel-1 GRD | Planetary Computer STAC + SAS + TiTiler `GET /api/map/sentinel1` |
| IEM NEXRAD / RainViewer | weather radar, not satellite |
Repo docs already flag **Suomi NPP product stop 2026-11-01** — swap SNPP true color / DNB / thermal / FIRMS `VIIRS_SNPP_NRT` to NOAA-20/21 before then.
---
## Ranked “add tomorrow” (sections 1–2)
Most new OSINT signal per **zero dollars**, browser tiles only:
1. **VIIRS NOAA-20 + NOAA-21 true color** — SNPP replacement, same dropdown pattern.
2. **VIIRS false-color SWIR** (`BandsM11-I2-I1`, `BandsM3-I3-M11`, MODIS 7-2-1) — burn scars, flood, bare soil.
3. **GIBS GOES-East/West GeoColor + Band13 IR** — 10-minute weather-sat, Hormuz + CONUS.
4. **GIBS Himawari AHI vis + IR** — same for IO/WestPac.
5. **HLS S30/L30** — 30 m Landsat/Sentinel-2 look without TiTiler.
6. **OPERA RTC Sentinel-1 + DIST-ALERT + DSWx** — SAR / disturbance / flood as GIBS tiles (not COGs).
7. **NOAA-20/21 DNB** — night lights after SNPP.
8. **IEM GOES XYZ** — “latest” tiles, no time in the URL, already CORS `*` like NEXRAD.[6]
9. **EUMETView WMS** — Meteosat/MTG for Europe–Africa–IO, CORS `*`.[18]
10. **GFW GLAD-S2 / integrated deforestation alerts** — raster tiles, CORS `*` when `Origin` is sent.[15]
11. **MUR SST + VIIRS/PACE/OLCI chlorophyll** — ocean.
12. **MODIS NDVI 8-day + IMERG rain** — veg / flood context.
13. **SRTM / ASTER GDEM color index** — satellite-derived DEM, static.
14. **NOAA-20/21 thermal anomalies** — FIRMS-shaped overlay after SNPP; empty tiles 404.
---
## 1. Drop-in GIBS WMTS
All rows: **key? no**. **CORS `*`**. **Pi fit: browser `L.tileLayer`**. Same time-domain helper as `gibs_map.py` (`…/1.0.0/{id}/default/{tms}/all/all.xml`).
Format of URL column: layer id + TMS + ext. Date used in probes: `2026-08-27` unless noted.
### 1.1 Optical (true / false / SWIR)
| id | what you see | tile pattern | cadence | max zoom | license | already have? | probe |
|---|---|---|---|---|---|---|---|
| `VIIRS_NOAA20_CorrectedReflectance_TrueColor` | Daily true color, JPSS-1 | `…/{id}/default/{time}/GoogleMapsCompatible_Level9/{z}/{y}/{x}.jpg` | daily | 9 (~250 m) | NASA GIBS ack[1] | **no** (SNPP only) | 200 `*` jpeg |
| `VIIRS_NOAA21_CorrectedReflectance_TrueColor` | Daily true color, JPSS-2 | same Level9 jpg | daily | 9 | NASA GIBS[1] | no | 200 |
| `VIIRS_SNPP_CorrectedReflectance_BandsM11-I2-I1` | False color SWIR (burns, flood) | Level9 jpg | daily | 9 | NASA GIBS[1] | no | 200 |
| `VIIRS_SNPP_CorrectedReflectance_BandsM3-I3-M11` | False color (snow/ice/desert) | Level9 jpg | daily | 9 | NASA GIBS[1] | no | 200 |
| `VIIRS_NOAA20_CorrectedReflectance_BandsM11-I2-I1` | NOAA-20 SWIR false color | Level9 jpg | daily | 9 | NASA GIBS[1] | no | 200 |
| `VIIRS_NOAA21_CorrectedReflectance_BandsM11-I2-I1` | NOAA-21 SWIR false color | Level9 jpg | daily | 9 | NASA GIBS[1] | no | 200 |
| `MODIS_Terra_CorrectedReflectance_Bands721` | Classic 7-2-1 burn/SWIR | Level9 jpg | daily | 9 | NASA GIBS[1] | no | 200 |
| `MODIS_Terra_CorrectedReflectance_Bands367` | 3-6-7 false color | Level9 jpg | daily | 9 | NASA GIBS[1] | no | 200 |
| `MODIS_Aqua_CorrectedReflectance_Bands721` | Aqua 7-2-1 | Level9 jpg | daily | 9 | NASA GIBS[1] | no | 200 |
| `HLS_S30_Nadir_BRDF_Adjusted_Reflectance` | Harmonized Sentinel-2 30 m RGB | Level12 png | ~2–3 d when a granule exists | 12 (~30 m) | NASA GIBS[1] | no | 200 at z=5 NC; 404 on empty granules is normal. Domain from 2015–present |
| `HLS_L30_Nadir_BRDF_Adjusted_Reflectance` | Harmonized Landsat 30 m | Level12 png | 8–16 d | 12 | NASA GIBS[1] | no | in caps; tile 404 on empty scene |
| `Landsat_WELD_CorrectedReflectance_TrueColor_Global_Monthly` | Landsat WELD monthly mosaic | Level12 jpg | monthly, **not NRT** | 12 | NASA GIBS[1] | no | 200 |
| `Landsat_WELD_CorrectedReflectance_TrueColor_Global_Annual` | WELD annual | Level12 jpg | yearly | 12 | NASA GIBS[1] | no | 200 |
### 1.2 Weather satellites (imagery, not NEXRAD)
Sub-daily. Probe with `2026-08-27` **and** `2026-08-27T18:00:00Z` both 200 (nearestValue).[2]
| id | what you see | TMS / ext | cadence | max zoom | already have? | probe |
|---|---|---|---|---|---|---|
| `GOES-East_ABI_GeoColor` | GeoColor full disk (Americas, Atlantic, Hormuz west edge) | Level7 png | ~10 min | 7 | no | 200 |
| `GOES-West_ABI_GeoColor` | GeoColor Pacific / CONUS west | Level7 png | ~10 min | 7 | no | 200 (also 200 over CA with ISO time) |
| `GOES-East_ABI_Band2_Red_Visible_1km` | ABI vis | Level7 png | ~10 min | 7 | no | 200 |
| `GOES-West_ABI_Band2_Red_Visible_1km` | ABI vis | Level7 png | ~10 min | 7 | no | 200 |
| `GOES-East_ABI_Band13_Clean_Infrared` | Clean IR window | Level6 png | ~10 min | 6 | no | 200 |
| `GOES-West_ABI_Band13_Clean_Infrared` | Clean IR | Level6 png | ~10 min | 6 | no | 200 |
| `GOES-East_ABI_FireTemp` | Fire temperature RGB | Level7 png | ~10 min | 7 | no | 200 |
| `GOES-West_ABI_FireTemp` | Fire temperature RGB | Level7 png | ~10 min | 7 | no | 404 on NC tile (wrong disk); use west longitudes |
| `GOES-East_ABI_Dust` | Dust RGB | Level7 png | ~10 min | 7 | no | 200 |
| `GOES-East_ABI_Air_Mass` | Air mass RGB | Level6 png | ~10 min | 6 | no | 200 |
| `GOES-West_ABI_Air_Mass` | Air mass RGB | Level6 png | ~10 min | 6 | no | 200 |
| `Himawari_AHI_Band3_Red_Visible_1km` | Himawari vis (IO / WestPac / Aus) | Level7 png | ~10 min | 7 | no | 200 (ISO time over Japan) |
| `Himawari_AHI_Band13_Clean_Infrared` | Himawari IR | Level6 png | ~10 min | 6 | no | 200 |
| `Himawari_AHI_Air_Mass` | Himawari air mass | Level6 png | ~10 min | 6 | no | 200 |
**Meteosat is not in GIBS.** Use section 2 EUMETView.
### 1.3 SAR / flood / disturbance (GIBS tiles — skip TiTiler)
| id | what you see | TMS | cadence | max zoom | already have? | probe |
|---|---|---|---|---|---|---|
| `OPERA_L2_Radiometric_Terrain_Corrected_SAR_Sentinel-1` | S-1 RTC browse (better than GRD for terrain) | Level12 png | scene-based from 2025-01 | 12 | **no** (you have GRD COGs, not RTC tiles) | 200 at z=5; domain 2025-01-10/… |
| `OPERA_L3_DIST-ALERT-HLS_Color_Index` | Vegetation disturbance / clearing alert | Level12 png | ~2–3 d | 12 | no | 200 |
| `OPERA_L3_DIST-ANN-HLS_Color_Index` | Annual DIST | Level12 png | yearly | 12 | no | in caps |
| `OPERA_L3_Dynamic_Surface_Water_Extent-HLS` | Surface water / flood (HLS, 30 m) | Level12 png | ~2–3 d | 12 | no | 200 at z=5 |
| `OPERA_L3_Dynamic_Surface_Water_Extent-Sentinel-1` | Surface water from S-1 (clouds irrelevant) | Level12 png | S-1 revisit | 12 | no | 200 at z=5 |
| `NISAR_L2_Geocoded_Polarimetric_Covariance` | NISAR early browse | Level13 png | when downlinked | 13 | no | 200 (layer exists; coverage still sparse) |
| `SMAP_L4_Analyzed_Surface_Soil_Moisture` | Soil moisture | Level6 png | daily | 6 | no | 200 |
| `SMAP_L3_Active_Sigma0_VV` | SMAP radar σ0 | Level6 png | 2–3 d | 6 | no | in caps (SMAP radar died 2015 — historical) |
No ICEYE / Capella / Umbra / ALOS PALSAR **daily** layers in this GIBS 3857 dump.[4] ALOS shows up as mosaics on Planetary Computer (section 3).
### 1.4 Thermal / fire / volcano
Sparse PNG overlays: **empty tiles 404**. Capabilities + DescribeDomains still 200. Frontend must tolerate 404 (Leaflet does).
| id | what you see | TMS | cadence | max zoom | already have? | probe |
|---|---|---|---|---|---|---|
| `VIIRS_SNPP_Thermal_Anomalies_375m_All` | 375 m hotspots | **Level8** png (not 9) | daily | 8 | **yes**, but wired as Level9 | Domain 200; many tiles 404 |
| `VIIRS_NOAA20_Thermal_Anomalies_375m_All` | NOAA-20 hotspots | Level8 png | daily | 8 | no | Domain 200 (`2020-01-01/…` through at least 2025-09); tiles 404 if no fire in tile |
| `VIIRS_NOAA21_Thermal_Anomalies_375m_All` | NOAA-21 hotspots | Level8 png | daily | 8 | no | same |
| `VIIRS_*_Thermal_Anomalies_375m_{Day,Night}` | day/night split | Level8 png | daily | 8 | no | in caps |
| `MODIS_{Terra,Aqua,Combined}_Thermal_Anomalies_All` | 1 km MODIS fire | Level7 png | daily | 7 | no | in caps |
| `GOES-East_ABI_FireTemp` | geostationary fire RGB | Level7 png | ~10 min | 7 | no | 200 |
Also keep FIRMS CSV — points beat raster for click/query.
### 1.5 Night lights (beyond current DNB ENCC)
| id | what you see | TMS / ext | cadence | max zoom | already have? | probe |
|---|---|---|---|---|---|---|
| `VIIRS_NOAA20_DayNightBand` | NOAA-20 DNB | Level7 png | daily | 7 | no | 200 |
| `VIIRS_NOAA21_DayNightBand` | NOAA-21 DNB | Level7 png | daily | 7 | no | 200 |
| `VIIRS_NOAA20_DayNightBand_At_Sensor_Radiance` | radiance, not ENCC | Level8 png | daily | 8 | no | 200 |
| `VIIRS_SNPP_DayNightBand_At_Sensor_Radiance` | SNPP radiance | Level8 png | daily | 8 | no | 200 |
| `VIIRS_NOAA20_DayNightBand_AtSensor_M15` | DNB+M15 composite jpg | Level8 jpg | daily | 8 | no | 200 |
| `VIIRS_Night_Lights` | Black-marble-style annual-ish | Level8 png | time-dim | 8 | no | 200 on 2026-08-27 mosaic date |
| `VIIRS_CityLights_2012` | Static 2012 city lights | Level8 jpg | **static** (`has_time=false`) | 8 | no | 200 |
`VIIRS_Black_Marble` and `VIIRS_NOAA20_DayNightBand_ENCC` are in caps; ENCC-NOAA20 returned HTTP 400 on the Level8 template we tried — do not ship until DescribeDomains + a known-good date are wired. SNPP ENCC stays as the current layer.
### 1.6 Ocean
| id | what you see | TMS | cadence | max zoom | probe |
|---|---|---|---|---|---|
| `GHRSST_L4_MUR_Sea_Surface_Temperature` | 1 km MUR SST | Level7 png | daily | 7 | 200 |
| `GHRSST_L4_MUR_Sea_Surface_Temperature_Anomalies` | SST anomaly | Level7 png | daily | 7 | in caps |
| `MODIS_Aqua_L3_SST_MidIR_4km_Night_Daily` | MODIS SST | Level6 png | daily | 6 | 200 |
| `MODIS_Aqua_L2_Chlorophyll_A` | Aqua chl-a | Level7 png | daily | 7 | 200 |
| `VIIRS_SNPP_L2_Chlorophyll_A` | VIIRS chl-a | Level7 png | daily | 7 | 200 |
| `VIIRS_NOAA20_Chlorophyll_a` | NOAA-20 chl-a | Level7 png | daily | 7 | 200 |
| `OCI_PACE_Chlorophyll_a` | PACE OCI chl-a | Level7 png | daily | 7 | 200 |
| `S3A_OLCI_Chlorophyll_a` | Sentinel-3A OLCI chl-a | Level7 png | daily | 7 | 200 |
| `S3B_OLCI_Chlorophyll_a` | Sentinel-3B OLCI | Level7 png | daily | 7 | in caps |
| `MODIS_Terra_Sea_Ice` | sea ice | Level7 png | daily | 7 | 200 |
| `GHRSST_L4_MUR_Sea_Ice_Concentration` | MUR ice | Level7 png | daily | 7 | in caps |
No dedicated “SAR oil slick” GIBS layer in the 3857 dump. Closest: OPERA RTC / DSWx-S1 + existing S-1 GRD TiTiler.
### 1.7 Vegetation / burn / flood / precip / atm
| id | what you see | TMS | cadence | max zoom | probe |
|---|---|---|---|---|---|
| `MODIS_Terra_NDVI_8Day` | NDVI | Level9 png | 8-day | 9 | 200 |
| `MODIS_Terra_L3_NDVI_16Day` | NDVI 16-day | Level9 png | 16-day | 9 | 200 |
| `IMERG_Precipitation_Rate` | GPM IMERG rain | Level6 png | sub-daily | 6 | 200 |
| `MODIS_Terra_Aerosol` | AOD | Level6 png | daily | 6 | 200 |
| `MODIS_Terra_Land_Surface_Temp_Day` | LST | Level7 png | daily | 7 | 200 |
| `VIIRS_SNPP_Land_Surface_Temp_Day` | VIIRS LST | Level7 png | daily | 7 | 200 |
| `AIRS_L3_Carbon_Monoxide_500hPa_Volume_Mixing_Ratio_Daily_Night` | CO (fires, industry) | Level6 png | daily | 6 | 200 |
| `OMI_NO2` / `OMI_Aerosol_Index` | NO2 / smoke index | Level6 png | daily | 6 | OMI AI 200; several OMPS 200 |
| `MODIS_Water_Mask` | static water mask | Level9 png | static | 9 | 200 |
MODIS burned-area monthly (`MCD64` / `MODIS_Combined_L3_Burned_Area_Monthly`) is in caps; our dated tile 400’d — wire only after a DescribeDomains date hits 200.
### 1.8 DEM (satellite-derived, tileable)
| id | what you see | TMS / ext | cadence | max zoom | probe |
|---|---|---|---|---|---|
| `SRTM_Color_Index` | SRTM elevation color | Level12 png | static | 12 | 200 |
| `ASTER_GDEM_Color_Index` | ASTER GDEM color | Level12 png | static | 12 | 200 |
| `ASTER_GDEM_Color_Shaded_Relief` | ASTER hillshade | Level12 jpg | static | 12 | 200 |
| `ASTER_GDEM_Greyscale_Shaded_Relief` | grey hillshade | Level12 jpg | static | 12 | in caps |
| `GEDI_ISS_L3_Canopy_Height_Mean_RH100_201904-202303` | GEDI canopy height | Level7 png | static epoch | 7 | related GEDI biomass 200 |
Blue Marble shaded relief is **already** the basemap — these are extra.
---
## 2. Other XYZ / WMTS / WMS (no key)
Ranked after GIBS for signal/$; still free.
| id | what you see | provider | URL pattern | key? | CORS | cadence | max zoom / res | license / attribution | Pi fit | already have? | probe 2026-08-29 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| `iem_goes_east_conus_ch02` | GOES-East CONUS ABI ch02 vis, **latest** | Iowa State IEM | `https://mesonet.agron.iastate.edu/cache/tile.py/1.0.0/goes_east_conus_ch02/{z}/{x}/{y}.png` | no | `*` | ~5 min cache header | TMS; vis ~1 km | Cite IEM / NOAA GOES[6][7] | **browser** (same stack as NEXRAD) | no | 200 image/png `*` |
| `iem_goes_east_conus_ch13` | GOES-East CONUS IR ch13 | IEM | `…/goes_east_conus_ch13/{z}/{x}/{y}.png` | no | `*` | ~5 min | IR ~2 km | IEM[6] | browser | no | 200 |
| `iem_goes_east_fulldisk_ch02` | GOES-East full disk vis | IEM | `…/goes_east_fulldisk_ch02/{z}/{x}/{y}.png` | no | `*` | ~5 min | full disk | IEM[6] | browser | no | 200 |
| `iem_goes_west_conus_ch02` | GOES-West CONUS vis | IEM | `…/goes_west_conus_ch02/{z}/{x}/{y}.png` | no | `*` | ~5 min | | IEM[6] | browser | no | 200 |
| `iem_goes_vis_1km` | Legacy name → GOES-East vis | IEM | `…/goes-vis-1km/{z}/{x}/{y}.png` | no | `*` | ~5 min | | IEM[6] | browser | no | 200 |
| IEM GOES template | Any bird/sector/channel | IEM | `goes_{east\|west}_{fulldisk\|conus\|mesoscale-1\|mesoscale-2\|alaska\|puertorico}_ch{01–16}`[6] | no | `*` | NRT | 16 ABI bands | IEM[6] | browser | no | template documented; ch02/ch13 probed |
| `eumet_msg_natural` | Meteosat natural color | EUMETSAT EUMETView GeoServer | WMS `https://view.eumetsat.int/geoserver/ows` layer `msg_fes:rgb_natural` EPSG:3857 GetMap | no | `*` | NRT | SEVIRI ~3 km | EUMETSAT viz; cite EUMETSAT[18] | **browser `L.tileLayer.wms`** (not XYZ). Caps 200, 165 layer names | no | GetMap 200 image/png `*` |
| `eumet_msg_ir108` | Meteosat IR 10.8 | EUMETView | WMS `msg_fes:ir108` | no | `*` | NRT | | EUMETSAT | browser WMS | no | name in caps |
| `eumet_msg_fire` | Meteosat fire | EUMETView | WMS `msg_fes:fire` | no | `*` | NRT | | EUMETSAT | browser WMS | no | name in caps |
| `eumet_mtg_ir105` | MTG-I IR | EUMETView | WMS `mtg_fd:ir105_hrfi` | no | `*` | NRT | FCI | EUMETSAT | browser WMS | no | name in caps |
| `eumet_s3_olci_rgb` | S3 OLCI RGB mosaic | EUMETView | WMS `copernicus:daily_sentinel3ab_olci_l1_rgb_fulres` | no | `*` | daily | OLCI | Copernicus/EUMETSAT | browser WMS | no | name in caps |
| `eumet_s3_chl` | S3 chl-a | EUMETView | WMS `copernicus:daily_sentinel3ab_olci_l2_chl_fullres` | no | `*` | daily | | Copernicus | browser WMS | no | name in caps |
| `gfw_glad_s2` | GLAD Sentinel-2 deforestation alerts | GFW tile cache | `https://tiles.globalforestwatch.org/umd_glad_sentinel2_alerts/latest/default/{z}/{x}/{y}.png` | no | `*` **if `Origin` header** (null without it) | ~daily | raster z 0–22 documented[15] | WRI/UMD; cite GFW | **browser** (Leaflet sends Origin) | no | 200 image/png; with Origin → CORS `*` |
| `gfw_integrated` | Integrated deforestation alerts | GFW | `https://tiles.globalforestwatch.org/gfw_integrated_alerts/latest/default/{z}/{x}/{y}.png` | no | `*` + Origin | ~daily | | GFW | browser | no | 200 |
| `gfw_tcl` | UMD tree-cover loss | GFW | `https://tiles.globalforestwatch.org/umd_tree_cover_loss/latest/tcd_30/{z}/{x}/{y}.png` | no | (same host) | annual | | GFW/UMD | browser | no | 200 |
| `star_goes19_fd_geocolor` | GOES-19 full-disk GeoColor **JPEG** (not XYZ) | NOAA NESDIS STAR CDN | `https://cdn.star.nesdis.noaa.gov/GOES19/ABI/FD/GEOCOLOR/latest.jpg` also `…/CONUS/GEOCOLOR/latest.jpg` | no | `*` | minutes | full-disk / CONUS image | NOAA | **not a map layer** — optional lightbox. Do not tile-proxy | no | 200 jpeg `*`[21] |
| `star_goes18_fd_geocolor` | GOES-18 FD GeoColor JPEG | STAR | `https://cdn.star.nesdis.noaa.gov/GOES18/ABI/FD/GEOCOLOR/latest.jpg` | no | `*` | minutes | | NOAA | lightbox only | no | 200 |
IEM JSON `…/GOES/conus/channel02/GOES-16_C02.json` is **stale** (`generated_at` 2025-04-07) but the **tile names still 200**. Prefer GIBS GeoColor when you need a time slider; prefer IEM when you want “whatever is latest” with zero time plumbing.[6][7]
### 2.x Works but **not** browser-direct (no CORS)
| id | what you see | URL | CORS | Pi fit | probe |
|---|---|---|---|---|---|
| RAMMB/CIRA SLIDER GeoColor tiles | GOES-19 / Himawari / JPSS loops, ~10 min | Times: `https://rammb-slider.cira.colostate.edu/data/json/goes-19/full_disk/geocolor/latest_times.json` (`timestamps_int`). Tile: `https://rammb-slider.cira.colostate.edu/data/imagery/{YYYY}/{MM}/{DD}/goes-19---full_disk/geocolor/{ts}/{zz}/{yyy}_{xxx}.png` e.g. `…/2026/08/28/goes-19---full_disk/geocolor/20260828225021/00/000_000.png`. Himawari times JSON also 200. | **none** | **Do not proxy tiles through the Pi.** Bookmark / deep-link SLIDER instead.[19][26] | times 200; tile 200 png; CORS null |
| NICT Himawari-8 Real-time Web | 10-min full disk PNG grid | `https://himawari8.nict.go.jp/img/D531106/latest.json` then `https://himawari8.nict.go.jp/img/D531106/2d/550/{YYYY}/{MM}/{DD}/{HHMMSS}_{x}_{y}.png` | **none** | same — no Pi proxy | latest.json 200; tile 200 png; CORS null[22] |
| OpenAerialMap | Per-scene TMS of open UAV/sat | `https://api.openaerialmap.org/meta` → `properties.tms` | CORS **only** `https://map.openaerialmap.org` | not usable from the dashboard origin without a proxy; opportunistic, not a global basemap[23][25] | meta 200 |
| USGS LandsatLook STAC | Landsat C2 STAC | `https://landsatlook.usgs.gov/stac-server` | CORS locked to `https://landsatlook.usgs.gov/stac-server` | backend-only if ever; prefer Earth Search / PC / GIBS HLS[24] | collections + search 200 |
| NOAA CoastWatch ERDDAP WMS (`jplMURSST41`) | MUR SST WMS | `https://coastwatch.pfeg.noaa.gov/erddap/wms/jplMURSST41/request` | mixed | **flaky**: GetCapabilities 200 earlier, **503** on later GetMap/GetCapabilities. Prefer GIBS MUR | 503 on 2nd pass |
| RainViewer `satellite.infrared` | would be IR sat frames | `https://api.rainviewer.com/public/weather-maps.json` | `*` | **empty list** (`"infrared": []`) at probe time — do not ship. Radar path already in product[20] | JSON 200, satellite IR empty |
---
## 3. STAC / COG (TiTiler, same pattern as Sentinel-1)
Do **not** stream COGs through the Pi for a basemap. Viewport bbox + short datetime window + SAS/public HTTPS + existing TiTiler. Prefer GIBS HLS / OPERA tiles (section 1) when a browse PNG is enough.
| id | what you see | provider | STAC | key? | CORS | cadence | res | license | Pi fit | already have? | probe |
|---|---|---|---|---|---|---|---|---|---|---|---|
| `sentinel-2-l2a` (Earth Search) | S2 L2A COGs, public HTTPS | Element 84 / AWS Open Data | `https://earth-search.aws.element84.com/v1` collections: `sentinel-2-l2a`, `sentinel-2-c1-l2a`, `sentinel-2-l1c`, `sentinel-2-pre-c1-l2a`, `sentinel-1-grd`, `landsat-c2-l2`, `naip`, `cop-dem-glo-30`, `cop-dem-glo-90`[8][9] | no | STAC `*` | S2 ~5 d | 10 m | Copernicus open; AWS public bucket HTTPS (not requester-pays for these COGs)[9] | **backend same as S-1**: search → TCI/visual COG → TiTiler. Live item `S2A_40RCP_20260827_0_L2A` href `https://sentinel-cogs.s3.us-west-2.amazonaws.com/…/TCI.tif` | no | collections + search 200 `*` |
| `sentinel-2-l2a` (Planetary Computer) | same S2 on Azure | Microsoft PC | `https://planetarycomputer.microsoft.com/api/stac/v1/collections/sentinel-2-l2a` | SAS token (unsigned search works) | STAC `*` | ~5 d | 10 m | Copernicus; Azure blob needs SAS like current S-1 | backend same as S-1 | no | collection + search 200 `*` (136 collections listed)[10][11] |
| `sentinel-1-rtc` | S-1 IW RTC γ0 COGs | PC / Catalyst | `/collections/sentinel-1-rtc` | **PC account required to retrieve SAS** for RTC blobs[12] | STAC `*` | IW land | ~10 m pixels | **CC BY 4.0**[12] | backend same as S-1 **plus** PC login for SAS. Prefer GIBS OPERA RTC tiles if browse is enough | no | collection 200; search item `S1D_IW_GRDH_…_rtc` assets `vv,vh,tilejson,rendered_preview` |
| `sentinel-1-grd` (PC) | GRD | PC | `/collections/sentinel-1-grd` | SAS | `*` | 6–12 d | | Copernicus | **already have** | yes | 200 |
| `sentinel-1-grd` (Earth Search) | GRD on AWS | E84 | `/collections/sentinel-1-grd` | requester-pays **s3://** URLs per E84 README[9] | `*` | | | Copernicus | worse than PC for the Pi (AWS creds) | no | collection 200 |
| `landsat-c2-l2` | Landsat 8/9 SR | E84 + PC | both catalogs | no / SAS | `*` | 8–16 d | 30 m | USGS public | backend TiTiler; or just use GIBS HLS | no | both 200 |
| `hls2-s30` / `hls2-l30` | HLS v2 COGs | PC | `/collections/hls2-s30`, `hls2-l30` | SAS | `*` | 2–3 d | 30 m | NASA | prefer GIBS HLS tiles | no | collections 200 |
| `goes-cmi` | GOES Cloud & Moisture Imagery COGs | PC | `/collections/goes-cmi` | SAS | `*` | 5–10 min | ABI | NOAA | **overkill vs GIBS/IEM tiles** | no | collection 200 |
| `modis-14A1-061` / `modis-64A1-061` | MODIS fire / burned area | PC | `/collections/modis-14A1-061`, `modis-64A1-061` | SAS | `*` | daily / monthly | 1 km / 500 m | NASA | prefer GIBS fire tiles + FIRMS | no | 200 |
| `alos-palsar-mosaic` / `alos-fnf-mosaic` | ALOS PALSAR yearly mosaic / forest-nonforest | PC | those collection ids | SAS | `*` | **annual** | 25 m | JAXA (check collection) | backend mosaic, not live SAR | no | 200 |
| `nasadem` / `cop-dem-glo-30` | DEM COGs | PC + E84 | `nasadem`, `cop-dem-glo-30` | public / SAS | `*` | static | 30 m | NASA / Copernicus | prefer GIBS SRTM/ASTER tiles | no | 200 |
| `naip` | USDA NAIP aerial (CONUS) | E84 + PC | `naip` | no | `*` | leaf-on, not NRT | ~0.6 m | USDA | CONUS only; huge. Optional TiTiler | no | 200 |
| `io-lulc-annual-v02` | 10 m land cover | PC | `io-lulc-annual-v02` | SAS | `*` | annual | 10 m | various | overlay, not sat photo | no | 200 |
| CDSE `sentinel-2-l2a` / `sentinel-1-grd` | Copernicus Dataspace STAC | ESA CDSE | `https://stac.dataspace.copernicus.eu/v1/collections/sentinel-2-l2a` (lowercase ids work; `SENTINEL-2` 404) | **free account** for many assets | **CORS none** | same as ESA | | Copernicus | backend only; Earth Search/PC easier on a Pi | no | collection 200, CORS null. List endpoint is paginated (first page was CLMS burned-area COGs)[14] |
PC catalog also has Sentinel-3 OLCI/SLSTR NetCDF, Sentinel-5P, GOES-GLM — NetCDF is a bad TiTiler citizen; use GIBS/EUMETView for those.
---
## 4. Free-account / license-gated (no card this week)
| id | note | why not a dropdown tomorrow |
|---|---|---|
| Microsoft PC SAS for RTC (and some blobs) | “A Planetary Computer account is required to retrieve SAS tokens to read the RTC data.”[12] | Search is open; **read** needs an account. GRD path you already have may not need this. |
| Copernicus Data Space (`stac.dataspace.copernicus.eu`) | STAC search 200 without cookie; **no CORS**; downloads often need a free CDSE login | Use Earth Search/PC unless you want official ESA provenance |
| JAXA P-Tree / Himawari Monitor | Himawari standard data, account | NICT/GIBS already cover browse |
| EUMETSAT Data Store | full MTG/MSG granules | EUMETView WMS is the browse path |
| FIRMS map key | already in product | add `VIIRS_NOAA20_NRT` / `VIIRS_NOAA21_NRT` before SNPP sunset |
| USGS ERS / EarthExplorer | Landsat/ASTER download login | GIBS HLS + Earth Search cover browse |
| Planet Tropical Forest Observatory | paid successor after NICFI | see skip |
---
## 5. Skip / costs money / dead
| id | why |
|---|---|
| **NICFI / Planet tropical mosaics (free)** | Free NICFI phase **ended 1 Apr 2025**. Removed from GFW and Collect Earth Online. Successor is Planet **Tropical Forest Observatory (subscription)** or a future NICFI re-compete.[16][17] PC collections `planet-nicfi-analytic` / `planet-nicfi-visual` still exist but assets are **RFP winners only** + proprietary PLA.[13] |
| Sentinel Hub (paid tiers) | billed processing units |
| Google Earth Engine | billing project |
| Maxar / Planet commercial | $ |
| ICEYE commercial | no free global tile/STAC found this pass |
| Umbra / Capella / Maxar **open data** STAC | catalogs 200 (`maxar-opendata`, `umbra-open-data-catalog`) but **disaster events only**, not a standing layer |
| Esri World Imagery / Clarity | tiles 200 CORS `*` — **ToS not a free basemap we should wrap** |
| Mapbox / Google satellite | key + ToS |
| GEE Dynamic World / NICFI in EE | EE billing |
| `nowcoast.noaa.gov` | HTTP **403** |
| FIRMS WMS (`firms.modaps.eosdis.nasa.gov/wms/…`) | HTTP **404** — use CSV + GIBS |
| RainViewer satellite IR | payload empty[20] |
| CoastWatch ERDDAP | 503 at probe; GIBS MUR replaces SST |
| Proxying RAMMB or NICT tiles | no CORS; would soak the home uplink |
---
## Implementation notes for builders
1. **GIBS dropdown:** reuse `MAP_LAYERS` in `app/gibs_map.py`. New rows are `{id, title, tms, format, has_time, max_zoom}`. Time-domain fetch already exists.
2. **SNPP sunset:** NOAA-20/21 true color, DNB, thermal, FIRMS datasets first. SNPP true color can stay as fallback until 2026-11-01.
3. **Fix thermal TMS:** caps say `GoogleMapsCompatible_Level8` for `VIIRS_*_Thermal_Anomalies_375m_*`. Level9 GetTile is HTTP 400 XML.
4. **GOES time:** either GIBS `{time}` ISO + existing date slider, or IEM “latest” XYZ with no time (simpler, CONUS/FD only).
5. **HLS / OPERA:** empty granules 404 — same as “today’s MODIS isn’t ingested yet”. Clamp latest date via DescribeDomains like current daily mosaics.
6. **Do not add TiTiler S2 as a global basemap.** 10 m COGs will thrash the Pi. GIBS HLS Level12 is the browse path; Earth Search TCI is a “inspect this viewport” action like S-1.
7. **EUMETView:** `L.tileLayer.wms` against `https://view.eumetsat.int/geoserver/ows`, layers `msg_fes:rgb_natural` / `msg_fes:ir108`. Caps CORS `*`.
8. **GFW:** send browser Origin (Leaflet does). No key.
9. **Attribution strings:** NASA GIBS acknowledgment[1]; IEM; EUMETSAT; GFW/UMD; NOAA STAR.
### Probe stats (this run)
- GIBS WMTS caps: 5 796 177 bytes, CORS `*`, 1315 layers.[4]
- Curated GIBS GetTile: **78/90 HTTP 200** first batch; extra GOES/DNB/HLS/OPERA/ocean 200 as tabulated.
- Earth Search collections (complete list): `sentinel-2-pre-c1-l2a`, `cop-dem-glo-30`, `naip`, `cop-dem-glo-90`, `landsat-c2-l2`, `sentinel-2-l2a`, `sentinel-2-l1c`, `sentinel-2-c1-l2a`, `sentinel-1-grd`.[8]
- Planetary Computer: 136 collections; S-1 RTC CC-BY-4.0.[11][12]
Raw probe JSON lives next to this file in the kanban workspace (`gibs_probes.json`, `wave2_probes.json`, `wave3_probes.json`, `gibs_all_layers.json`).
## Sources
[1] https://nasa-gibs.github.io/gibs-api-docs
[2] https://nasa-gibs.github.io/gibs-api-docs/access-basics
[3] https://nasa-gibs.github.io/gibs-api-docs/available-visualizations
[4] https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/1.0.0/WMTSCapabilities.xml
[5] https://worldview.earthdata.nasa.gov
[6] https://mesonet.agron.iastate.edu/ogc
[7] https://mesonet.agron.iastate.edu/GIS/goes.phtml
[8] https://earth-search.aws.element84.com/v1/collections
[9] https://github.com/Element84/earth-search
[10] https://planetarycomputer.microsoft.com/catalog
[11] https://planetarycomputer.microsoft.com/api/stac/v1/collections
[12] https://planetarycomputer.microsoft.com/dataset/sentinel-1-rtc
[13] https://planetarycomputer.microsoft.com/dataset/planet-nicfi-analytic
[14] https://stac.dataspace.copernicus.eu/v1/collections
[15] https://tiles.globalforestwatch.org
[16] https://www.collect.earth/planet-imagery-via-nicfi-is-no-longer-available-on-ceo
[17] https://www.globalforestwatch.org/blog/data-and-tools/planet-imagery-changes-gfw
[18] https://view.eumetsat.int/geoserver/ows?service=WMS&request=GetCapabilities
[19] https://rammb-slider.cira.colostate.edu
[20] https://api.rainviewer.com/public/weather-maps.json
[21] https://cdn.star.nesdis.noaa.gov/GOES19/ABI/FD/GEOCOLOR/latest.jpg
[22] https://himawari8.nict.go.jp
[23] https://api.openaerialmap.org/meta?limit=1
[24] https://landsatlook.usgs.gov/stac-server/collections
[25] https://openaerialmap.org
[26] https://bellingcat.gitbook.io/toolkit/more/all-tools/rammb-slider
[27] https://www.earthdata.nasa.gov/engage/open-data-services-software/earthdata-developer-portal/gibs-api

Binary file not shown.

After

Width:  |  Height:  |  Size: 174 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 368 KiB

BIN
evidence-ticker-crop.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

View file

@ -1,19 +0,0 @@
# Secrets and Config
.env
*.key
*.pem
# Python artifacts
**/__pycache__/
*.py[cod]
*$py.class
.pytest_cache/
# Scrapy runtime output (created inside the container at /app/data)
data/
*.jsonl
.scrapy/
# Git
.git
.gitignore

View file

@ -1,4 +0,0 @@
# Scrapy runtime output (only created when run locally, not in the container)
data/
*.jsonl
.scrapy/

View file

@ -1,44 +0,0 @@
FROM python:3.12-slim AS builder
# Prevent Python from writing .pyc files and enable unbuffered logging
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
WORKDIR /install
# Install system dependencies required for building lxml and other Scrapy deps
RUN apt-get update && apt-get install -y \
gcc \
libxml2-dev \
libxslt-dev \
libffi-dev \
libssl-dev \
&& rm -rf /var/lib/apt/lists/*
# Install dependencies to a temporary location
COPY requirements.txt .
RUN pip install --no-cache-dir --prefix=/install -r requirements.txt
# --- Stage 2: Runtime ---
FROM python:3.12-slim
WORKDIR /app
# Copy the installed python packages from the builder stage
COPY --from=builder /install /usr/local
# Copy the project files
COPY . .
# Security: Run as a non-privileged user
RUN useradd -m scraper
RUN mkdir -p /app/data && chown -R scraper:scraper /app/data
USER scraper
# Set the entrypoint to the scrapy command
ENTRYPOINT ["scrapy"]
# Default command if none is provided
CMD ["crawl", "articles"]

View file

@ -1,56 +0,0 @@
"""Feed helpers shared by the news spider (no Scrapy import)."""
from __future__ import annotations
import datetime
import re
from email.utils import parsedate_to_datetime
from urllib.parse import urlparse
AUDIO_EXT = (".mp3", ".m4a", ".ogg", ".wav", ".aac", ".flac", ".opus")
def is_audio_url(url: str) -> bool:
path = urlparse(url or "").path.lower()
return any(path.endswith(ext) for ext in AUDIO_EXT)
def article_timestamp(pub_date: str | None) -> datetime.datetime:
"""Prefer the feed's pubDate/published; fall back to now (UTC)."""
if pub_date:
try:
return parsedate_to_datetime(pub_date).astimezone(datetime.timezone.utc)
except (TypeError, ValueError, IndexError):
pass
try:
raw = pub_date.replace("Z", "+00:00")
ts = datetime.datetime.fromisoformat(raw)
if ts.tzinfo is None:
ts = ts.replace(tzinfo=datetime.timezone.utc)
return ts
except ValueError:
pass
return datetime.datetime.now(datetime.timezone.utc)
# Whole-title CDATA wrapper only. Keep in sync with app/news_title.py —
# the scraper image and the API image do not share a package.
_CDATA_WRAPPER = re.compile(
r"\A\s*<!\[CDATA\[(.*?)\]\]>\s*\Z",
re.DOTALL,
)
def unwrap_cdata_title(title):
"""Strip a surrounding CDATA wrapper. Anything else is unchanged.
``<![CDATA[Hello]]>`` and ``\\n <![CDATA[Hello]]>`` become
``Hello``. Real HTML (``<b>Hello</b>``) 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()

View file

@ -1,12 +0,0 @@
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
import scrapy
class NewsscraperItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
pass

View file

@ -1,113 +0,0 @@
# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals
# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
class NewsscraperSpiderMiddleware:
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the spider middleware does not modify the
# passed objects.
@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_spider_input(self, response, spider):
# Called for each response that goes through the spider
# middleware and into the spider.
# Should return None or raise an exception.
return None
def process_spider_output(self, response, result, spider):
# Called with the results returned from the Spider, after
# it has processed the response.
# Must return an iterable of Request, or item objects.
for i in result:
yield i
def process_spider_exception(self, response, exception, spider):
# Called when a spider or process_spider_input() method
# (from other spider middleware) raises an exception.
# Should return either None or an iterable of Request or item objects.
pass
async def process_start(self, start):
# Called with an async iterator over the spider start() method or the
# matching method of an earlier spider middleware.
async for item_or_request in start:
yield item_or_request
def spider_opened(self, spider):
spider.logger.info("Spider opened: %s" % spider.name)
class NewsscraperDownloaderMiddleware:
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the downloader middleware does not modify the
# passed objects.
@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_request(self, request, spider):
# Called for each request that goes through the downloader
# middleware.
# Must either:
# - return None: continue processing this request
# - or return a Response object
# - or return a Request object
# - or raise IgnoreRequest: process_exception() methods of
# installed downloader middleware will be called
return None
def process_response(self, request, response, spider):
# Called with the response returned from the downloader.
# Must either;
# - return a Response object
# - return a Request object
# - or raise IgnoreRequest
return response
def process_exception(self, request, exception, spider):
# Called when a download handler or a process_request()
# (from other downloader middleware) raises an exception.
# Must either:
# - return None: continue processing this exception
# - return a Response object: stops process_exception() chain
# - return a Request object: stops process_exception() chain
pass
def spider_opened(self, spider):
spider.logger.info("Spider opened: %s" % spider.name)
class ProxyMiddleware:
def __init__(self, proxy_url):
self.proxy_url = proxy_url
@classmethod
def from_crawler(cls, crawler):
return cls(proxy_url=crawler.settings.get('PROXY_URL'))
def process_request(self, request, spider):
# Only attach the proxy if PROXY_URL was successfully built
if self.proxy_url:
request.meta['proxy'] = self.proxy_url

View file

@ -1,148 +0,0 @@
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import datetime
import logging
import psycopg2
import os
from scrapy.exceptions import DropItem
from newsScraper.feed_util import unwrap_cdata_title
log = logging.getLogger(__name__)
# Feed items dated further ahead than this are event listings (or clock skew
# from the source), not news. Dropping them keeps `ORDER BY timestamp DESC`
# from pinning the top of /api/news for days. See docs/news.md.
FUTURE_TOLERANCE = datetime.timedelta(hours=2)
def _parsed_timestamp(value):
"""Return an aware UTC datetime for an item timestamp, or None.
None means "could not parse" — callers must keep such items, exactly as
before this guard existed (undated items currently get now() upstream).
"""
if isinstance(value, datetime.datetime):
ts = value
elif isinstance(value, str) and value.strip():
try:
ts = datetime.datetime.fromisoformat(value.strip().replace("Z", "+00:00"))
except ValueError:
return None
else:
return None
if ts.tzinfo is None:
ts = ts.replace(tzinfo=datetime.timezone.utc)
return ts.astimezone(datetime.timezone.utc)
def is_future_dated(value, now=None, tolerance=FUTURE_TOLERANCE):
"""True when a parsed publish timestamp is more than `tolerance` ahead."""
ts = _parsed_timestamp(value)
if ts is None:
return False
now = now or datetime.datetime.now(datetime.timezone.utc)
return ts > now + tolerance
class PostgresPipeline:
def __init__(self, db_config):
# 1. Store the config
self.db_config = db_config
# 2. Initialize the set here so it exists when process_item is called
self.seen_urls = set()
# 3. Future-dated drops, reported once per run in close_spider()
self.future_dated_dropped = 0
@classmethod
def from_crawler(cls, crawler):
db_config = {
'host': crawler.settings.get('DB_HOST'),
'database': crawler.settings.get('DB_NAME'),
'user': crawler.settings.get('DB_USER'),
'password': crawler.settings.get('DB_PASSWORD'),
}
return cls(db_config=db_config)
def open_spider(self, spider):
# Connect using environment variables
self.connection = psycopg2.connect(
host=os.getenv('DB_HOST'),
database=os.getenv('DB_NAME'),
user=os.getenv('DB_USER'),
password=os.getenv('DB_PASSWORD'),
port=os.getenv('DB_PORT', '5432')
)
self.cur = self.connection.cursor()
# Create table if it doesn't exist
self.cur.execute("""
CREATE TABLE IF NOT EXISTS articles (
id SERIAL PRIMARY KEY,
title TEXT,
url TEXT UNIQUE,
content TEXT,
domain TEXT,
timestamp TIMESTAMPTZ
)
""")
self.connection.commit()
def process_item(self, item, spider):
url = item['url']
if is_future_dated(item.get('timestamp')):
self.future_dated_dropped += 1
stats = getattr(getattr(spider, 'crawler', None), 'stats', None)
if stats is not None:
stats.inc_value('future_dated_dropped')
raise DropItem(f"Future-dated item: {url}")
if url in self.seen_urls:
raise DropItem(f"Duplicate URL (in-memory): {url}")
self.seen_urls.add(url)
item['title'] = unwrap_cdata_title(item['title'])
try:
self.cur.execute("""
INSERT INTO articles (title, url, content, domain, timestamp)
VALUES (%s, %s, %s, %s, %s)
ON CONFLICT (url) DO NOTHING
""", (
item['title'],
item['url'],
item['text'],
item['domain'],
item['timestamp']
))
if self.cur.rowcount == 0:
raise DropItem(f"Duplicate URL (database): {url}")
self.connection.commit()
return item
except DropItem:
self.connection.rollback()
raise
except Exception as e:
spider.logger.error(f"Error saving to Postgres: {e}")
self.connection.rollback()
raise
def close_spider(self, spider):
if self.future_dated_dropped:
spider.logger.info(
"Dropped %d future-dated item(s) (>%s ahead)",
self.future_dated_dropped, FUTURE_TOLERANCE,
)
self.cur.close()
self.connection.close()
from itemadapter import ItemAdapter
class NewsscraperPipeline:
def process_item(self, item, spider):
return item

View file

@ -1,95 +0,0 @@
import os
from dotenv import load_dotenv
load_dotenv()
PROXY_USER = os.getenv('PROXY_USER', '').strip()
PROXY_PASS = os.getenv('PROXY_PASS', '').strip()
PROXY_ENDPOINT = os.getenv('PROXY_ENDPOINT', '').strip()
def get_proxy_url():
if not PROXY_ENDPOINT:
return None
endpoint = PROXY_ENDPOINT.replace('http://', '').replace('https://','')
if PROXY_USER and PROXY_PASS:
return f"http://{PROXY_USER}:{PROXY_PASS}@{endpoint}"
else:
return f"http://{endpoint}"
PROXY_URL = get_proxy_url()
DOWNLOADER_MIDDLEWARES = {
'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware': 110,
}
BOT_NAME = "newsScraper"
SPIDER_MODULES = ["newsScraper.spiders"]
NEWSPIDER_MODULE = "newsScraper.spiders"
ADDONS = {}
# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = os.getenv('USER_AGENT', "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
DEFAULT_REQUEST_HEADERS = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate, br',
'DNT': '1',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
}
# Obey robots.txt rules
ROBOTSTXT_OBEY = True
# Concurrency and throttling settings
CONCURRENT_REQUESTS = os.getenv('CONCURRENT_REQUESTS', '100').strip()
CONCURRENT_REQUESTS_PER_DOMAIN = 2
DOWNLOAD_DELAY = 3
REACTOR_THREADPOOL_MAXSIZE = 100
LOG_LEVEL = os.getenv('LOG_LEVEL', 'INFO')
RETRY_ENABLED = True
DOWNLOAD_TIMEOUT = 60
AJAXCRAWL_ENABLED = False
AUTO_THROTTLE_ENABLED = True
AUTOTHROTTLE_ENABLED = True
AUTOTHROTTLE_TARGET_CONCURRENCY = 2.0
DNSCACHE_ENABLED = True
DNSCACHE_SIZE = 20000
DNS_TIMEOUT = 20
DNS_RESOLVER = 'scrapy.resolver.CachingThreadedResolver'
# Depth must allow homepage(0) -> discovered feed(1) -> article(2).
DEPTH_LIMIT = os.getenv('DEPTH_LIMIT', 3)
TWISTED_REACTOR = "twisted.internet.asyncioreactor.AsyncioSelectorReactor"
FEEDS = {
'data/hourly_news.jsonl':{
'format': 'jsonlines',
'encoding': 'utf8',
'overwrite': True,
}
}
FEED_EXPORT_ENCODING = "utf-8"
ITEM_PIPELINES = {
'newsScraper.pipelines.PostgresPipeline': 300,
}
# Database Config (These should be in your .env / K8s Secrets)
DB_HOST = os.getenv('DB_HOST', 'postgres-service')
DB_NAME = os.getenv('DB_NAME', 'news_db')
DB_USER = os.getenv('DB_USER', 'admin')
DB_PASSWORD = os.getenv('DB_PASSWORD')
db_config = {
'host': DB_HOST,
'database': DB_NAME,
'user': DB_USER,
'password': DB_PASSWORD,
'port': 5432 # Default postgres port
}

View file

@ -1,4 +0,0 @@
# This package will contain the spiders of your Scrapy project
#
# Please refer to the documentation for information on how to create and manage
# your spiders.

View file

@ -1,120 +0,0 @@
import scrapy
from scrapy.spiders import Spider
from urllib.parse import urljoin, urlparse
import datetime
import re
from newsScraper.feed_util import article_timestamp, is_audio_url
class NewsRSSSpider(Spider):
"""Crawl the curated news sources in urls.txt and extract articles.
urls.txt contains curated news HOMEPAGES and RSS/Atom feeds, so this spider
implements feed autodiscovery: it fetches each start URL, finds the
RSS/Atom feed link (`<link rel="alternate" type="application/rss+xml">`
or a visible /rss|/feed link), follows it, and then follows each feed
item's article link to extract the full text.
Upstream filtered urls.txt for '/rss'/'/feed' lines, which matched ZERO
of the 257 homepage URLs — the scraper silently did nothing. This version
makes the curated homepage list actually work.
"""
name = "articles"
# 0 = start URL (homepage), 1 = discovered feed, 2 = article
# DEPTH_LIMIT must be >= 2 (see settings.py).
def __init__(self, filename='urls.txt', *args, **kwargs):
super(NewsRSSSpider, self).__init__(*args, **kwargs)
with open(filename, 'r') as f:
self.start_urls = [
line.strip() for line in f
if line.strip() and not line.strip().startswith('#')
]
@staticmethod
def _looks_like_feed(response) -> bool:
"""Heuristic: XML body (rss/feed/RDF root) or a feed-looking URL."""
ct = (response.headers.get('Content-Type') or b'').decode('latin1', 'ignore').lower()
url = response.url.lower()
if url.endswith(('.xml', '.rss', '.atom')):
return True
if 'xml' in ct or 'rss' in ct or 'atom' in ct:
return True
try:
root = response.xpath('local-name(/*)').get()
if root and root.lower() in ('rss', 'feed', 'rdf'):
return True
except Exception: # noqa: BLE001 — non-XML responses fail XPath root lookup
pass
return False
def parse(self, response):
"""Handle a start URL: parse it directly if it is a feed, otherwise
autodiscover its RSS/Atom feed link(s)."""
if self._looks_like_feed(response):
yield from self.parse_feed(response)
return
# Feed autodiscovery: <link rel="alternate" type="application/rss+xml">
feed_links = response.xpath(
'//link[@rel="alternate" and '
'(contains(@type, "rss") or contains(@type, "atom") or contains(@type, "xml"))]/@href'
).getall()
if not feed_links:
# Fallback: visible links to /feed or /rss paths on the page.
feed_links = response.xpath(
'//a[contains(@href, "/feed") or contains(@href, "/rss")]/@href'
).getall()
for href in feed_links[:3]: # cap discovery per homepage
yield scrapy.Request(
urljoin(response.url, href),
callback=self.parse_feed,
meta={'source': response.url},
)
def parse_feed(self, response):
"""Parse an RSS (<item>) or Atom (<entry>) feed into article requests."""
for node in response.xpath('//item | //entry'):
title = node.xpath('title/text()').get()
link = (
node.xpath('link/text()').get()
or node.xpath('link/@href').get()
or node.xpath('guid/text()').get()
)
pub_date = (
node.xpath('pubDate/text()').get()
or node.xpath('published/text()').get()
or node.xpath('updated/text()').get()
)
if link:
if is_audio_url(link):
continue
yield scrapy.Request(
link,
callback=self.parse_article,
meta={'title': title, 'date': pub_date},
)
def parse_article(self, response):
"""Extract the main article text from the linked article page."""
title = response.meta.get('title')
# Greedy search for the main text body
article_text = response.xpath(
'//article//p/text() | //main//p/text() | '
'//div[contains(@class, "body")]//p/text() | '
'//div[contains(@class, "content")]//p/text()'
).getall()
pure_text = " ".join(article_text)
pure_text = re.sub(r'\s+', ' ', pure_text).strip()
if len(pure_text) > 300:
yield {
'title': title,
'url': response.url,
'text': pure_text,
'domain': urlparse(response.url).netloc,
'timestamp': article_timestamp(response.meta.get('date')).isoformat()
}

View file

@ -1,44 +0,0 @@
attrs==25.4.0
Automat==25.4.16
brotli==1.2.0
certifi==2026.1.4
cffi==2.0.0
charset-normalizer==3.4.4
constantly==23.10.4
cryptography==46.0.3
cssselect==1.3.0
defusedxml==0.7.1
filelock==3.20.2
hyperlink==21.0.0
idna==3.11
Incremental==24.11.0
itemadapter==0.13.1
itemloaders==1.3.2
jmespath==1.0.1
lxml==6.0.2
packaging==25.0
parsel==1.10.0
Protego==0.5.0
pyasn1==0.6.1
pyasn1_modules==0.4.2
pycparser==2.23
PyDispatcher==2.0.7
pyOpenSSL==25.3.0
queuelib==1.8.0
requests==2.32.5
requests-file==3.0.1
Scrapy==2.14.0
scrapy-user-agents==0.1.1
service-identity==24.2.0
tldextract==5.3.1
Twisted==25.5.0
typing_extensions==4.15.0
ua-parser==1.0.1
ua-parser-builtins==202601
urllib3==2.6.3
user-agents==2.2.0
w3lib==2.3.1
zope.interface==8.1.1
psycopg2-binary==2.9.11
python-dotenv==0.20.0
scrapy-playwright==0.0.45

View file

@ -1,53 +0,0 @@
#!/usr/bin/env python3
"""Scheduler loop for the news scraper — crawl continuously.
As soon as one Scrapy pass finishes, wait NEWS_SCRAPE_INTERVAL_S seconds
and start the next. Two crawls never overlap (the loop is serial).
Env (all optional, 12-factor):
NEWS_SCRAPE_INTERVAL_S seconds between crawls (default 10)
NEWS_SCRAPE_RUN_ON_START "1" to crawl immediately on boot (default 1)
"""
from __future__ import annotations
import datetime
import logging
import os
import subprocess
import sys
import time
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
logger = logging.getLogger("news.scraper")
INTERVAL_S = max(0, int(os.getenv("NEWS_SCRAPE_INTERVAL_S", "10")))
RUN_ON_START = os.getenv("NEWS_SCRAPE_RUN_ON_START", "1").lower() in ("1", "true", "yes")
CRAWL_CMD = ["scrapy", "crawl", "articles"]
def run_crawl() -> None:
logger.info("scrape starting at %s", datetime.datetime.now().isoformat(timespec="seconds"))
try:
proc = subprocess.run(CRAWL_CMD, cwd="/app")
logger.info("scrape finished rc=%s", proc.returncode)
except Exception: # noqa: BLE001 — keep the loop alive across failures
logger.exception("scrape failed")
def main() -> None:
logger.info(
"news scraper loop starting (interval_s=%s, run_on_start=%s)",
INTERVAL_S, RUN_ON_START,
)
if RUN_ON_START:
run_crawl()
while True:
logger.info("next scrape in %ss", INTERVAL_S)
time.sleep(INTERVAL_S)
run_crawl()
if __name__ == "__main__":
sys.exit(main())

View file

@ -1,11 +0,0 @@
# Automatically created by: scrapy startproject
#
# For more information about the [deploy] section see:
# https://scrapyd.readthedocs.io/en/latest/deploy.html
[settings]
default = newsScraper.settings
[deploy]
#url = http://localhost:6800/
project = newsScraper

Some files were not shown because too many files have changed in this diff Show more