forked from longtao.wu/droboticflow
134 lines
4.8 KiB
Python
134 lines
4.8 KiB
Python
from __future__ import annotations
|
|
|
|
import http.cookiejar
|
|
import http.client
|
|
import json
|
|
import time
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
from typing import Any, Callable
|
|
|
|
|
|
ErrorFactory = Callable[[str], Exception]
|
|
|
|
|
|
def is_csrf_protected_method(method: str) -> bool:
|
|
return method.upper() not in {"GET", "HEAD", "OPTIONS"}
|
|
|
|
|
|
class DroboticflowClient:
|
|
def __init__(
|
|
self,
|
|
api_base_url: str,
|
|
*,
|
|
api_token: str = "",
|
|
error_factory: ErrorFactory = RuntimeError,
|
|
cookie_jar: http.cookiejar.CookieJar | None = None,
|
|
opener: urllib.request.OpenerDirector | None = None,
|
|
) -> None:
|
|
self.api_base_url = api_base_url.rstrip("/")
|
|
self.api_token = api_token.strip()
|
|
self.error_factory = error_factory
|
|
self.cookie_jar = cookie_jar or http.cookiejar.CookieJar()
|
|
self.opener = opener or urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.cookie_jar))
|
|
|
|
def csrf_token(self) -> str:
|
|
for cookie in self.cookie_jar:
|
|
if cookie.name == "droboticflow_csrf":
|
|
return urllib.parse.unquote(cookie.value)
|
|
return ""
|
|
|
|
def request_headers(self, method: str, base_headers: dict[str, str] | None = None) -> dict[str, str]:
|
|
headers = dict(base_headers or {})
|
|
if self.api_token:
|
|
headers["Authorization"] = f"Bearer {self.api_token}"
|
|
if is_csrf_protected_method(method):
|
|
token = self.csrf_token()
|
|
if token:
|
|
headers["X-Droboticflow-CSRF-Token"] = token
|
|
return headers
|
|
|
|
def request_json(
|
|
self,
|
|
method: str,
|
|
path: str,
|
|
payload: Any | None = None,
|
|
*,
|
|
expected: tuple[int, ...] = (200, 201, 202, 204),
|
|
timeout: int = 60,
|
|
retries: int = 1,
|
|
retry_delay_seconds: float = 1.0,
|
|
) -> Any:
|
|
method = method.upper()
|
|
body = None
|
|
headers = {"Content-Type": "application/json"}
|
|
if payload is not None:
|
|
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
|
status, raw, _ = self.request_bytes(
|
|
method,
|
|
path,
|
|
body=body,
|
|
headers=headers,
|
|
expected=expected,
|
|
timeout=timeout,
|
|
retries=retries,
|
|
retry_delay_seconds=retry_delay_seconds,
|
|
)
|
|
if status == 204 or not raw:
|
|
return None
|
|
return json.loads(raw.decode("utf-8", errors="replace"))
|
|
|
|
def request_bytes(
|
|
self,
|
|
method: str,
|
|
path: str,
|
|
*,
|
|
body: bytes | None = None,
|
|
headers: dict[str, str] | None = None,
|
|
expected: tuple[int, ...] = (200,),
|
|
timeout: int = 300,
|
|
retries: int = 1,
|
|
retry_delay_seconds: float = 1.0,
|
|
) -> tuple[int, bytes, dict[str, str]]:
|
|
method = method.upper()
|
|
attempts = max(1, retries)
|
|
last_error: BaseException | None = None
|
|
for attempt in range(1, attempts + 1):
|
|
request_headers = self.request_headers(method, headers)
|
|
req = urllib.request.Request(f"{self.api_base_url}{path}", data=body, headers=request_headers, method=method)
|
|
try:
|
|
with self.opener.open(req, timeout=timeout) as resp:
|
|
raw = resp.read()
|
|
status = getattr(resp, "status", resp.getcode())
|
|
if status not in expected:
|
|
message = raw.decode("utf-8", errors="replace")
|
|
raise self.error_factory(f"{method} {path} unexpected {status}: {message}")
|
|
return status, raw, dict(resp.headers.items())
|
|
except urllib.error.HTTPError as err:
|
|
raw = err.read().decode("utf-8", errors="replace")
|
|
raise self.error_factory(f"{method} {path} failed {err.code}: {raw}") from err
|
|
except (urllib.error.URLError, http.client.RemoteDisconnected, TimeoutError) as err:
|
|
last_error = err
|
|
if attempt >= attempts:
|
|
break
|
|
time.sleep(min(retry_delay_seconds * attempt, 3.0))
|
|
if attempts == 1:
|
|
raise self.error_factory(f"{method} {path} failed: {last_error}") from last_error
|
|
raise self.error_factory(f"{method} {path} failed after retries: {last_error}") from last_error
|
|
|
|
def login_if_configured(self, email: str, password: str, *, label: str) -> str:
|
|
if not email:
|
|
return ""
|
|
response = self.request_json(
|
|
"POST",
|
|
"/api/auth/login",
|
|
{"email": email, "password": password},
|
|
expected=(200,),
|
|
)
|
|
identifier = email
|
|
if isinstance(response, dict):
|
|
identifier = str(response.get("email") or response.get("name") or identifier)
|
|
print(f"logged in {label}: {identifier}")
|
|
return identifier
|