- Postiz URL is now required (no built-in host); a key can never be sent to a default instance - /api/postiz/scheduled normalizes scheduled_date and widens the default window - Disabled channels are refused for posting; frontend excludes them from connected platforms - 4xx instead of 500 on missing clip URL / bad schedule date; Postiz error bodies truncated - Add tests/test_postiz.py (24 tests); fix remaining cloud-removal test drift - CLI defaults to localhost:8000; n8n workflows fixed against the real routes - Remove dead media-token auth code, stale copy (download_url/402) and doc drift
156 lines
6 KiB
Python
156 lines
6 KiB
Python
"""Thin synchronous client for the self-hosted Postiz public API.
|
|
|
|
One place that knows the Postiz base path and auth convention so ``app.py`` can
|
|
stay about request handling. Every function is blocking; call them through
|
|
``asyncio.to_thread`` from async handlers (video uploads are tens of seconds).
|
|
|
|
Auth is the RAW API key in the ``Authorization`` header -- NO ``Bearer`` prefix
|
|
(see /tmp/opencode/cleanup/postiz-api.md). There is deliberately no built-in
|
|
host: the base URL comes from the caller or the ``POSTIZ_URL`` env var, and a
|
|
request without one is refused instead of silently shipping the caller's key to
|
|
an instance we picked. The API path prefix ``/api/public/v1`` is appended
|
|
automatically when the caller passes a bare host.
|
|
"""
|
|
|
|
import os
|
|
from typing import Any, Dict, List, Optional
|
|
|
|
import httpx
|
|
|
|
|
|
_API_PREFIX = "/api/public/v1"
|
|
|
|
# Postiz sniffs the MIME of /upload payloads: video must be video/mp4. We send
|
|
# the honest content type for the file extension rather than a blanket octet.
|
|
_MIME_BY_EXT = {
|
|
".mp4": "video/mp4",
|
|
".mov": "video/quicktime",
|
|
".webm": "video/webm",
|
|
".jpg": "image/jpeg",
|
|
".jpeg": "image/jpeg",
|
|
".png": "image/png",
|
|
".webp": "image/webp",
|
|
".gif": "image/gif",
|
|
}
|
|
|
|
|
|
class PostizError(Exception):
|
|
"""A non-2xx response (or missing config) from Postiz.
|
|
|
|
Carries the upstream status and body so the FastAPI layer can translate it
|
|
into the same status/detail it would have surfaced before.
|
|
"""
|
|
|
|
def __init__(self, status_code: int, detail: str):
|
|
super().__init__(detail)
|
|
self.status_code = status_code
|
|
self.detail = detail
|
|
|
|
|
|
def _resolve_base(base: Optional[str]) -> str:
|
|
base = (base or os.environ.get("POSTIZ_URL") or "").strip().rstrip("/")
|
|
if not base:
|
|
raise PostizError(400, "Missing Postiz URL")
|
|
if base.endswith(_API_PREFIX):
|
|
return base
|
|
return base + _API_PREFIX
|
|
|
|
|
|
def _resolve_key(key: Optional[str]) -> str:
|
|
key = (key or os.environ.get("POSTIZ_API_KEY") or "").strip()
|
|
if not key:
|
|
raise PostizError(400, "Missing Postiz API key")
|
|
return key
|
|
|
|
|
|
def _headers(key: Optional[str]) -> Dict[str, str]:
|
|
# Raw key, no "Bearer".
|
|
return {"Authorization": _resolve_key(key)}
|
|
|
|
|
|
def _mime_for(path: str) -> str:
|
|
return _MIME_BY_EXT.get(os.path.splitext(path)[1].lower(),
|
|
"application/octet-stream")
|
|
|
|
|
|
def _handle(resp: httpx.Response) -> Any:
|
|
if resp.status_code not in (200, 201, 202):
|
|
# Truncate the upstream body: it can be an HTML error page or a stack
|
|
# trace, and PostizError.detail rides straight into our API response.
|
|
body = (resp.text or "")[:500]
|
|
raise PostizError(resp.status_code, f"Postiz API Error: {body}")
|
|
if resp.status_code == 204 or not resp.content:
|
|
return None
|
|
try:
|
|
return resp.json()
|
|
except ValueError:
|
|
return None
|
|
|
|
|
|
def list_integrations(base: Optional[str] = None, key: Optional[str] = None,
|
|
timeout: float = 30.0) -> List[Dict[str, Any]]:
|
|
"""Connected channels: ``[{id, name, identifier, picture, disabled, profile}]``."""
|
|
with httpx.Client(timeout=timeout) as client:
|
|
resp = client.get(f"{_resolve_base(base)}/integrations", headers=_headers(key))
|
|
data = _handle(resp)
|
|
return data if isinstance(data, list) else (data or {}).get("integrations", []) or []
|
|
|
|
|
|
def upload_media(base: Optional[str], key: Optional[str], path: str,
|
|
timeout: float = 600.0) -> Dict[str, Any]:
|
|
"""Upload a local file (multipart field ``file``) and return ``{id, path}``."""
|
|
filename = os.path.basename(path)
|
|
with open(path, "rb") as handle:
|
|
files = {"file": (filename, handle, _mime_for(path))}
|
|
with httpx.Client(timeout=timeout) as client:
|
|
resp = client.post(f"{_resolve_base(base)}/upload",
|
|
headers=_headers(key), files=files)
|
|
return _handle(resp) or {}
|
|
|
|
|
|
def create_post(base: Optional[str], key: Optional[str], payload: Dict[str, Any],
|
|
timeout: float = 90.0) -> Any:
|
|
"""Create draft/scheduled/immediate posts. Returns the Postiz response list."""
|
|
with httpx.Client(timeout=timeout) as client:
|
|
resp = client.post(f"{_resolve_base(base)}/posts",
|
|
headers=_headers(key), json=payload)
|
|
return _handle(resp)
|
|
|
|
|
|
def list_posts(base: Optional[str], key: Optional[str], start: str, end: str,
|
|
timeout: float = 60.0) -> List[Dict[str, Any]]:
|
|
"""Posts in a date window. Both ``startDate`` and ``endDate`` are required."""
|
|
params = {"startDate": start, "endDate": end}
|
|
with httpx.Client(timeout=timeout) as client:
|
|
resp = client.get(f"{_resolve_base(base)}/posts",
|
|
headers=_headers(key), params=params)
|
|
data = _handle(resp)
|
|
if isinstance(data, list):
|
|
return data
|
|
return (data or {}).get("posts", []) or []
|
|
|
|
|
|
def delete_post(base: Optional[str], key: Optional[str], post_id: str,
|
|
timeout: float = 30.0) -> Any:
|
|
with httpx.Client(timeout=timeout) as client:
|
|
resp = client.delete(f"{_resolve_base(base)}/posts/{post_id}",
|
|
headers=_headers(key))
|
|
return _handle(resp)
|
|
|
|
|
|
def analytics(base: Optional[str], key: Optional[str], integration: str,
|
|
days: int = 30, timeout: float = 60.0) -> Dict[str, Any]:
|
|
"""Per-channel analytics over the last ``days`` days."""
|
|
with httpx.Client(timeout=timeout) as client:
|
|
resp = client.get(f"{_resolve_base(base)}/analytics/{integration}",
|
|
headers=_headers(key), params={"date": days})
|
|
return _handle(resp) or {}
|
|
|
|
|
|
def analytics_post(base: Optional[str], key: Optional[str], post_id: str,
|
|
days: int = 30, timeout: float = 60.0) -> Dict[str, Any]:
|
|
"""Analytics for a single published post."""
|
|
with httpx.Client(timeout=timeout) as client:
|
|
resp = client.get(f"{_resolve_base(base)}/analytics/post/{post_id}",
|
|
headers=_headers(key), params={"date": days})
|
|
return _handle(resp) or {}
|