"""Dependency-free Pairmade REST client. The API remains the source of truth.""" import json import os from urllib.error import HTTPError from urllib.parse import quote, urlsplit from urllib.request import Request, build_opener, HTTPRedirectHandler DEFAULT_ORIGIN = "https://yourpairmade.com" ACTION_STATUSES = {"completed", "queued", "awaiting_approval", "denied", "unavailable", "uncertain", "cancelled"} class _NoRedirect(HTTPRedirectHandler): def redirect_request(self, request, fp, code, message, headers, new_url): return None class PairmadeHttpError(Exception): def __init__(self, status_code, body): super().__init__(f"Pairmade request failed with HTTP {status_code}") self.status_code = status_code self.body = body class PairmadeClient: def __init__(self, origin=None, token=None): self.origin = (origin or os.environ.get("PAIRMADE_API_ORIGIN") or DEFAULT_ORIGIN).rstrip("/") url = urlsplit(self.origin) if url.scheme != "https" or not url.hostname or url.username or url.password or url.path not in {"", "/"} or url.query or url.fragment: raise ValueError("Use an HTTPS Pairmade origin.") self._opener = build_opener(_NoRedirect) self.token = token or os.environ.get("YOUR_TOKEN") if not self.token: raise ValueError("Set YOUR_TOKEN in the server environment.") def _request(self, path, method="GET", payload=None, extra_headers=None): headers = {"Authorization": "Bearer " + self.token} if payload is not None: headers["Content-Type"] = "application/json" if extra_headers: headers.update(extra_headers) data = json.dumps(payload).encode() if payload is not None else None request = Request(self.origin + path, data=data, headers=headers, method=method) try: with self._opener.open(request, timeout=30) as response: raw = response.read() except HTTPError as error: raw = error.read() try: body = json.loads(raw.decode()) if raw else None except ValueError: body = raw.decode(errors="replace") raise PairmadeHttpError(error.code, body) from error return json.loads(raw.decode()) if raw else None def capabilities(self): return self._request("/api/v1/capabilities") def run(self, name, input, options=None): options = options or {} operation = next((item for item in self.capabilities()["operations"] if item["name"] == name and item.get("available")), None) if operation is None: raise ValueError("Operation is not available to this connection: " + name) headers = {} if not operation["readOnly"]: key = options.get("idempotencyKey") if not key: raise ValueError("Mutations require idempotencyKey; reuse the same key and input when retrying.") headers["Idempotency-Key"] = key payload = {"input": input} if options.get("scheduleAt"): payload["scheduleAt"] = options["scheduleAt"] return self._request("/api/v1/operations/" + quote(name, safe=""), "POST", payload, headers) def status(self, action_id): return self._request("/api/v1/actions/" + quote(action_id, safe="")) def cancel(self, action_id): return self._request("/api/v1/actions/" + quote(action_id, safe="") + "/cancel", "POST") # Returned action status is preserved; inspect queued, awaiting_approval, and uncertain states explicitly.