64 lines
2.3 KiB
Python
64 lines
2.3 KiB
Python
"""Shared HTTP client for ask-form plugin actions calling the hub bridge."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import sys
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
from typing import Any
|
|
|
|
|
|
def read_payload() -> dict[str, Any]:
|
|
raw = sys.stdin.read().strip()
|
|
if not raw:
|
|
return {}
|
|
data = json.loads(raw)
|
|
return data if isinstance(data, dict) else {}
|
|
|
|
|
|
def emit(data: dict[str, Any]) -> None:
|
|
print(json.dumps(data, ensure_ascii=False))
|
|
|
|
|
|
def fail(status: int, message: str, kind: str = "askform") -> None:
|
|
emit({"_error": {"status": status, "kind": kind, "message": message}})
|
|
sys.exit(0)
|
|
|
|
|
|
def hub_call(method: str, rel_path: str, body: dict[str, Any] | None = None,
|
|
query: dict[str, Any] | None = None, timeout: float = 15.0) -> dict[str, Any]:
|
|
base = (os.environ.get("AIA_TOOLS_URL") or "").rstrip("/")
|
|
token = os.environ.get("AIA_TOOLS_TOKEN") or ""
|
|
pid = os.environ.get("AIA_PLUGIN_ID") or "ask-form"
|
|
if not base or not token:
|
|
fail(500, "missing AIA_TOOLS_URL or AIA_TOOLS_TOKEN")
|
|
qs = ""
|
|
if query:
|
|
pairs = [(k, str(v)) for k, v in query.items() if v is not None and v != ""]
|
|
if pairs:
|
|
qs = "?" + urllib.parse.urlencode(pairs)
|
|
url = f"{base}/plugins/{pid}/hub/askform/{rel_path.lstrip('/')}{qs}"
|
|
data = json.dumps(body).encode("utf-8") if body is not None else None
|
|
req = urllib.request.Request(
|
|
url, data=data, method=method,
|
|
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
|
|
)
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
return json.loads(r.read().decode("utf-8") or "{}")
|
|
except urllib.error.HTTPError as e:
|
|
raw = e.read().decode("utf-8", "replace")
|
|
try:
|
|
err = json.loads(raw).get("error") or {}
|
|
msg = err.get("message") if isinstance(err, dict) else raw
|
|
kind = err.get("kind") if isinstance(err, dict) else "askform"
|
|
except ValueError:
|
|
msg, kind = raw or f"HTTP {e.code}", "askform"
|
|
fail(e.code, str(msg), str(kind or "askform"))
|
|
except (urllib.error.URLError, OSError, ValueError) as e:
|
|
fail(502, f"hub askform bridge error: {e}")
|
|
return {}
|