"""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