cholaka 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cholaka/__init__.py +128 -0
- cholaka/_client.py +176 -0
- cholaka/_errors.py +115 -0
- cholaka/_models.py +215 -0
- cholaka/_resources.py +393 -0
- cholaka/_version.py +1 -0
- cholaka/py.typed +0 -0
- cholaka-0.1.0.dist-info/METADATA +221 -0
- cholaka-0.1.0.dist-info/RECORD +10 -0
- cholaka-0.1.0.dist-info/WHEEL +4 -0
cholaka/__init__.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""Python SDK for the Cholaka posting and scheduling API.
|
|
2
|
+
|
|
3
|
+
from datetime import datetime, timedelta, timezone
|
|
4
|
+
from cholaka import Cholaka
|
|
5
|
+
|
|
6
|
+
client = Cholaka() # reads CHOLAKA_API_KEY
|
|
7
|
+
page = client.accounts.list(platform="fb_page")[0]
|
|
8
|
+
photo = client.media.upload("launch.jpg")
|
|
9
|
+
post = client.posts.create(
|
|
10
|
+
"We launch tomorrow!",
|
|
11
|
+
account_ids=[page.id],
|
|
12
|
+
media=[photo],
|
|
13
|
+
scheduled_at=datetime.now(timezone.utc) + timedelta(hours=2),
|
|
14
|
+
)
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from typing import Optional
|
|
20
|
+
|
|
21
|
+
import httpx
|
|
22
|
+
|
|
23
|
+
from ._client import DEFAULT_BASE_URL, DEFAULT_MAX_RETRIES, DEFAULT_TIMEOUT, SyncAPIClient
|
|
24
|
+
from ._errors import (
|
|
25
|
+
APIConnectionError,
|
|
26
|
+
APIError,
|
|
27
|
+
AuthenticationError,
|
|
28
|
+
BadRequestError,
|
|
29
|
+
CholakaError,
|
|
30
|
+
ConflictError,
|
|
31
|
+
InternalServerError,
|
|
32
|
+
NotFoundError,
|
|
33
|
+
PermissionDeniedError,
|
|
34
|
+
PublishTimeoutError,
|
|
35
|
+
RateLimitError,
|
|
36
|
+
UnprocessableEntityError,
|
|
37
|
+
)
|
|
38
|
+
from ._models import (
|
|
39
|
+
FINAL_STATUSES,
|
|
40
|
+
Account,
|
|
41
|
+
MediaAsset,
|
|
42
|
+
Page,
|
|
43
|
+
Post,
|
|
44
|
+
PostStatus,
|
|
45
|
+
PostTarget,
|
|
46
|
+
PublishingLimit,
|
|
47
|
+
)
|
|
48
|
+
from ._resources import AccountsResource, MediaResource, PostsResource
|
|
49
|
+
from ._version import __version__
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class Cholaka:
|
|
53
|
+
"""Client for the Cholaka API.
|
|
54
|
+
|
|
55
|
+
:param api_key: An API token (``cho_...``) with the ``posts:read`` and/or
|
|
56
|
+
``posts:write`` scopes. Defaults to the ``CHOLAKA_API_KEY`` env var.
|
|
57
|
+
:param base_url: API root. Defaults to ``CHOLAKA_BASE_URL``, then
|
|
58
|
+
``https://api.cholaka.ai/api/v1``. ``https://host`` alone also works.
|
|
59
|
+
:param timeout: Seconds per HTTP request. Video uploads can be slow, so
|
|
60
|
+
the default is generous.
|
|
61
|
+
:param max_retries: How many times to retry rate-limited, unreachable or
|
|
62
|
+
temporarily unavailable requests.
|
|
63
|
+
:param http_client: Bring your own ``httpx.Client`` (proxies, custom TLS).
|
|
64
|
+
You remain responsible for closing it.
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
def __init__(
|
|
68
|
+
self,
|
|
69
|
+
api_key: Optional[str] = None,
|
|
70
|
+
*,
|
|
71
|
+
base_url: Optional[str] = None,
|
|
72
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
73
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
74
|
+
http_client: Optional[httpx.Client] = None,
|
|
75
|
+
) -> None:
|
|
76
|
+
self._client = SyncAPIClient(
|
|
77
|
+
api_key, base_url, timeout, max_retries, http_client
|
|
78
|
+
)
|
|
79
|
+
self.posts = PostsResource(self._client)
|
|
80
|
+
self.media = MediaResource(self._client)
|
|
81
|
+
self.accounts = AccountsResource(self._client)
|
|
82
|
+
|
|
83
|
+
@property
|
|
84
|
+
def base_url(self) -> str:
|
|
85
|
+
return self._client.base_url
|
|
86
|
+
|
|
87
|
+
def close(self) -> None:
|
|
88
|
+
"""Close the underlying HTTP connections."""
|
|
89
|
+
self._client.close()
|
|
90
|
+
|
|
91
|
+
def __enter__(self) -> "Cholaka":
|
|
92
|
+
return self
|
|
93
|
+
|
|
94
|
+
def __exit__(self, *exc: object) -> None:
|
|
95
|
+
self.close()
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
__all__ = [
|
|
99
|
+
"Cholaka",
|
|
100
|
+
"DEFAULT_BASE_URL",
|
|
101
|
+
"__version__",
|
|
102
|
+
# models
|
|
103
|
+
"Account",
|
|
104
|
+
"MediaAsset",
|
|
105
|
+
"Page",
|
|
106
|
+
"Post",
|
|
107
|
+
"PostStatus",
|
|
108
|
+
"PostTarget",
|
|
109
|
+
"PublishingLimit",
|
|
110
|
+
"FINAL_STATUSES",
|
|
111
|
+
# resources
|
|
112
|
+
"AccountsResource",
|
|
113
|
+
"MediaResource",
|
|
114
|
+
"PostsResource",
|
|
115
|
+
# errors
|
|
116
|
+
"CholakaError",
|
|
117
|
+
"APIConnectionError",
|
|
118
|
+
"APIError",
|
|
119
|
+
"BadRequestError",
|
|
120
|
+
"AuthenticationError",
|
|
121
|
+
"PermissionDeniedError",
|
|
122
|
+
"NotFoundError",
|
|
123
|
+
"ConflictError",
|
|
124
|
+
"UnprocessableEntityError",
|
|
125
|
+
"RateLimitError",
|
|
126
|
+
"InternalServerError",
|
|
127
|
+
"PublishTimeoutError",
|
|
128
|
+
]
|
cholaka/_client.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import random
|
|
5
|
+
import re
|
|
6
|
+
import time
|
|
7
|
+
from typing import Any, Callable, Dict, Mapping, Optional
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
|
|
11
|
+
from ._errors import APIConnectionError, CholakaError, error_for_status
|
|
12
|
+
from ._version import __version__
|
|
13
|
+
|
|
14
|
+
DEFAULT_BASE_URL = "https://api.cholaka.ai/api/v1"
|
|
15
|
+
DEFAULT_TIMEOUT = 60.0
|
|
16
|
+
DEFAULT_MAX_RETRIES = 2
|
|
17
|
+
|
|
18
|
+
#: Never sleep longer than this for a single retry, even if asked to.
|
|
19
|
+
MAX_RETRY_DELAY = 60.0
|
|
20
|
+
|
|
21
|
+
_RETRYABLE_STATUSES = frozenset({502, 503, 504})
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def normalize_base_url(url: str) -> str:
|
|
25
|
+
"""Accept ``https://host``, ``https://host/api`` or ``https://host/api/v1``."""
|
|
26
|
+
url = url.rstrip("/")
|
|
27
|
+
if re.search(r"/api/v\d+$", url):
|
|
28
|
+
return url
|
|
29
|
+
if url.endswith("/api"):
|
|
30
|
+
return url + "/v1"
|
|
31
|
+
return url + "/api/v1"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class SyncAPIClient:
|
|
35
|
+
"""Shared HTTP plumbing: auth, envelopes, errors and retries."""
|
|
36
|
+
|
|
37
|
+
def __init__(
|
|
38
|
+
self,
|
|
39
|
+
api_key: Optional[str],
|
|
40
|
+
base_url: Optional[str],
|
|
41
|
+
timeout: float,
|
|
42
|
+
max_retries: int,
|
|
43
|
+
http_client: Optional[httpx.Client],
|
|
44
|
+
) -> None:
|
|
45
|
+
key = api_key or os.environ.get("CHOLAKA_API_KEY")
|
|
46
|
+
if not key:
|
|
47
|
+
raise CholakaError(
|
|
48
|
+
"No API key. Pass api_key=... or set CHOLAKA_API_KEY. "
|
|
49
|
+
"Create one under Settings > Integrations."
|
|
50
|
+
)
|
|
51
|
+
if not key.startswith("cho_"):
|
|
52
|
+
raise CholakaError("API keys start with 'cho_'.")
|
|
53
|
+
self.api_key = key
|
|
54
|
+
self.base_url = normalize_base_url(
|
|
55
|
+
base_url or os.environ.get("CHOLAKA_BASE_URL") or DEFAULT_BASE_URL
|
|
56
|
+
)
|
|
57
|
+
self.max_retries = max(0, int(max_retries))
|
|
58
|
+
self._owns_http = http_client is None
|
|
59
|
+
self._http = http_client or httpx.Client(timeout=timeout)
|
|
60
|
+
self._headers = {
|
|
61
|
+
"Authorization": f"Bearer {key}",
|
|
62
|
+
"Accept": "application/json",
|
|
63
|
+
"User-Agent": f"cholaka-python/{__version__}",
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
def close(self) -> None:
|
|
67
|
+
if self._owns_http:
|
|
68
|
+
self._http.close()
|
|
69
|
+
|
|
70
|
+
def request(
|
|
71
|
+
self,
|
|
72
|
+
method: str,
|
|
73
|
+
path: str,
|
|
74
|
+
*,
|
|
75
|
+
params: Optional[Mapping[str, Any]] = None,
|
|
76
|
+
json: Any = None,
|
|
77
|
+
files: Optional[Callable[[], Dict[str, Any]]] = None,
|
|
78
|
+
idempotency_key: Optional[str] = None,
|
|
79
|
+
retry_safe: Optional[bool] = None,
|
|
80
|
+
) -> Any:
|
|
81
|
+
"""Send a request and return the unwrapped ``data`` of the response.
|
|
82
|
+
|
|
83
|
+
``files`` is a factory so a retry re-reads the upload from the start.
|
|
84
|
+
|
|
85
|
+
Retries:
|
|
86
|
+
* 429 is always retried after ``Retry-After``: the server refuses
|
|
87
|
+
those before doing any work.
|
|
88
|
+
* A connection that could not be opened is always retried.
|
|
89
|
+
* 502/503/504 and broken connections are retried only when the
|
|
90
|
+
request is safe to repeat (reads, deletes, or a POST carrying an
|
|
91
|
+
Idempotency-Key).
|
|
92
|
+
"""
|
|
93
|
+
if retry_safe is None:
|
|
94
|
+
retry_safe = method in ("GET", "HEAD", "DELETE") or bool(
|
|
95
|
+
idempotency_key
|
|
96
|
+
)
|
|
97
|
+
headers = dict(self._headers)
|
|
98
|
+
if idempotency_key:
|
|
99
|
+
headers["Idempotency-Key"] = idempotency_key
|
|
100
|
+
url = self.base_url + path
|
|
101
|
+
clean_params = (
|
|
102
|
+
{k: v for k, v in params.items() if v is not None} if params else None
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
attempt = 0
|
|
106
|
+
while True:
|
|
107
|
+
try:
|
|
108
|
+
response = self._http.request(
|
|
109
|
+
method,
|
|
110
|
+
url,
|
|
111
|
+
params=clean_params,
|
|
112
|
+
json=json,
|
|
113
|
+
files=files() if files else None,
|
|
114
|
+
headers=headers,
|
|
115
|
+
)
|
|
116
|
+
except (httpx.ConnectError, httpx.ConnectTimeout) as exc:
|
|
117
|
+
if attempt < self.max_retries:
|
|
118
|
+
self._sleep(self._backoff(attempt))
|
|
119
|
+
attempt += 1
|
|
120
|
+
continue
|
|
121
|
+
raise APIConnectionError(f"Could not connect to {url}: {exc}") from exc
|
|
122
|
+
except httpx.TransportError as exc:
|
|
123
|
+
if retry_safe and attempt < self.max_retries:
|
|
124
|
+
self._sleep(self._backoff(attempt))
|
|
125
|
+
attempt += 1
|
|
126
|
+
continue
|
|
127
|
+
raise APIConnectionError(f"Request to {url} failed: {exc}") from exc
|
|
128
|
+
|
|
129
|
+
status = response.status_code
|
|
130
|
+
if attempt < self.max_retries:
|
|
131
|
+
if status == 429:
|
|
132
|
+
delay = self._retry_after(response)
|
|
133
|
+
if delay is not None and delay <= MAX_RETRY_DELAY:
|
|
134
|
+
self._sleep(delay)
|
|
135
|
+
attempt += 1
|
|
136
|
+
continue
|
|
137
|
+
elif status in _RETRYABLE_STATUSES and retry_safe:
|
|
138
|
+
self._sleep(self._backoff(attempt))
|
|
139
|
+
attempt += 1
|
|
140
|
+
continue
|
|
141
|
+
|
|
142
|
+
return self._parse(response)
|
|
143
|
+
|
|
144
|
+
def _parse(self, response: httpx.Response) -> Any:
|
|
145
|
+
if response.status_code == 204 or not response.content:
|
|
146
|
+
if response.is_success:
|
|
147
|
+
return None
|
|
148
|
+
body: Any = None
|
|
149
|
+
else:
|
|
150
|
+
try:
|
|
151
|
+
body = response.json()
|
|
152
|
+
except ValueError:
|
|
153
|
+
body = response.text
|
|
154
|
+
if not response.is_success:
|
|
155
|
+
raise error_for_status(response.status_code, body, response.headers)
|
|
156
|
+
if isinstance(body, dict) and "data" in body:
|
|
157
|
+
return body["data"]
|
|
158
|
+
return body
|
|
159
|
+
|
|
160
|
+
@staticmethod
|
|
161
|
+
def _retry_after(response: httpx.Response) -> Optional[float]:
|
|
162
|
+
value = response.headers.get("retry-after")
|
|
163
|
+
if value is None:
|
|
164
|
+
return 1.0
|
|
165
|
+
try:
|
|
166
|
+
return max(0.0, float(value))
|
|
167
|
+
except ValueError:
|
|
168
|
+
return None
|
|
169
|
+
|
|
170
|
+
@staticmethod
|
|
171
|
+
def _backoff(attempt: int) -> float:
|
|
172
|
+
return min(8.0, 0.5 * (2**attempt)) * (0.75 + random.random() / 2)
|
|
173
|
+
|
|
174
|
+
# Indirection so tests can skip real sleeps.
|
|
175
|
+
def _sleep(self, seconds: float) -> None:
|
|
176
|
+
time.sleep(seconds)
|
cholaka/_errors.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, List, Mapping, Optional
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class CholakaError(Exception):
|
|
7
|
+
"""Base class for every error raised by this SDK."""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class APIConnectionError(CholakaError):
|
|
11
|
+
"""The API could not be reached, or the connection failed mid-request."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class PublishTimeoutError(CholakaError, TimeoutError):
|
|
15
|
+
"""``posts.wait_for_publish`` gave up before the post finished publishing."""
|
|
16
|
+
|
|
17
|
+
def __init__(self, message: str, post: Any) -> None:
|
|
18
|
+
super().__init__(message)
|
|
19
|
+
#: The post as last seen, so you can inspect its status and targets.
|
|
20
|
+
self.post = post
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class APIError(CholakaError):
|
|
24
|
+
"""The API answered with an error status.
|
|
25
|
+
|
|
26
|
+
``message`` is the server's explanation. Validation failures carry one
|
|
27
|
+
entry per problem in ``messages``.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
def __init__(
|
|
31
|
+
self,
|
|
32
|
+
status_code: int,
|
|
33
|
+
messages: List[str],
|
|
34
|
+
body: Any = None,
|
|
35
|
+
headers: Optional[Mapping[str, str]] = None,
|
|
36
|
+
) -> None:
|
|
37
|
+
self.status_code = status_code
|
|
38
|
+
self.messages = messages or [f"HTTP {status_code}"]
|
|
39
|
+
self.message = "; ".join(self.messages)
|
|
40
|
+
self.body = body
|
|
41
|
+
self.headers = {k.lower(): v for k, v in (headers or {}).items()}
|
|
42
|
+
super().__init__(f"{status_code}: {self.message}")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class BadRequestError(APIError):
|
|
46
|
+
"""400: the request was invalid, for example a scheduled time in the past."""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class AuthenticationError(APIError):
|
|
50
|
+
"""401: the API token is missing, unknown, revoked or expired."""
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class PermissionDeniedError(APIError):
|
|
54
|
+
"""403: the token lacks the scope, or its owner lacks the role, for this call."""
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class NotFoundError(APIError):
|
|
58
|
+
"""404: the post, media asset or account does not exist in your organization."""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class ConflictError(APIError):
|
|
62
|
+
"""409: the post's current status does not allow this change."""
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class UnprocessableEntityError(APIError):
|
|
66
|
+
"""422: for example an Idempotency-Key reused with a different request."""
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class RateLimitError(APIError):
|
|
70
|
+
"""429: the token's per-minute request budget is used up."""
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def retry_after(self) -> Optional[float]:
|
|
74
|
+
"""Seconds to wait before retrying, from the ``Retry-After`` header."""
|
|
75
|
+
value = self.headers.get("retry-after")
|
|
76
|
+
try:
|
|
77
|
+
return float(value) if value is not None else None
|
|
78
|
+
except ValueError:
|
|
79
|
+
return None
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class InternalServerError(APIError):
|
|
83
|
+
"""5xx: something went wrong on the Cholaka side."""
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
_BY_STATUS = {
|
|
87
|
+
400: BadRequestError,
|
|
88
|
+
401: AuthenticationError,
|
|
89
|
+
403: PermissionDeniedError,
|
|
90
|
+
404: NotFoundError,
|
|
91
|
+
409: ConflictError,
|
|
92
|
+
422: UnprocessableEntityError,
|
|
93
|
+
429: RateLimitError,
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def error_for_status(
|
|
98
|
+
status_code: int, body: Any, headers: Mapping[str, str]
|
|
99
|
+
) -> APIError:
|
|
100
|
+
"""Build the most specific error for a response."""
|
|
101
|
+
messages: List[str] = []
|
|
102
|
+
if isinstance(body, dict):
|
|
103
|
+
payload = body.get("error", body)
|
|
104
|
+
raw = payload.get("message") if isinstance(payload, dict) else None
|
|
105
|
+
if isinstance(raw, list):
|
|
106
|
+
messages = [str(m) for m in raw]
|
|
107
|
+
elif raw is not None:
|
|
108
|
+
messages = [str(raw)]
|
|
109
|
+
elif isinstance(body, str) and body.strip():
|
|
110
|
+
messages = [body.strip()[:500]]
|
|
111
|
+
|
|
112
|
+
cls = _BY_STATUS.get(status_code)
|
|
113
|
+
if cls is None:
|
|
114
|
+
cls = InternalServerError if status_code >= 500 else APIError
|
|
115
|
+
return cls(status_code, messages, body=body, headers=headers)
|
cholaka/_models.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from datetime import datetime, timezone
|
|
5
|
+
from typing import Any, Dict, Generic, List, Optional, TypeVar
|
|
6
|
+
|
|
7
|
+
T = TypeVar("T")
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class PostStatus:
|
|
11
|
+
"""Values of :attr:`Post.status`."""
|
|
12
|
+
|
|
13
|
+
DRAFT = "draft"
|
|
14
|
+
SCHEDULED = "scheduled"
|
|
15
|
+
PENDING_APPROVAL = "pending_approval"
|
|
16
|
+
PUBLISHING = "publishing"
|
|
17
|
+
PUBLISHED = "published"
|
|
18
|
+
FAILED = "failed"
|
|
19
|
+
REJECTED = "rejected"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
#: Statuses after which a post will not change unless you act on it.
|
|
23
|
+
FINAL_STATUSES = frozenset(
|
|
24
|
+
{PostStatus.PUBLISHED, PostStatus.FAILED, PostStatus.REJECTED}
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def parse_datetime(value: Any) -> Optional[datetime]:
|
|
29
|
+
"""Parse an ISO 8601 timestamp from the API into an aware datetime."""
|
|
30
|
+
if not value:
|
|
31
|
+
return None
|
|
32
|
+
if isinstance(value, datetime):
|
|
33
|
+
return value
|
|
34
|
+
text = str(value)
|
|
35
|
+
if text.endswith("Z"):
|
|
36
|
+
text = text[:-1] + "+00:00"
|
|
37
|
+
parsed = datetime.fromisoformat(text)
|
|
38
|
+
if parsed.tzinfo is None:
|
|
39
|
+
parsed = parsed.replace(tzinfo=timezone.utc)
|
|
40
|
+
return parsed
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class Account:
|
|
45
|
+
"""A connected social account you can publish to."""
|
|
46
|
+
|
|
47
|
+
id: str
|
|
48
|
+
platform: str
|
|
49
|
+
"""``fb_page``, ``ig_business``, and so on."""
|
|
50
|
+
name: str
|
|
51
|
+
username: Optional[str]
|
|
52
|
+
status: str
|
|
53
|
+
avatar_url: Optional[str]
|
|
54
|
+
tags: List[str]
|
|
55
|
+
created_at: Optional[datetime]
|
|
56
|
+
raw: Dict[str, Any] = field(repr=False, compare=False)
|
|
57
|
+
|
|
58
|
+
@classmethod
|
|
59
|
+
def from_api(cls, data: Dict[str, Any]) -> "Account":
|
|
60
|
+
return cls(
|
|
61
|
+
id=data["id"],
|
|
62
|
+
platform=data.get("platform", ""),
|
|
63
|
+
name=data.get("name", ""),
|
|
64
|
+
username=data.get("username"),
|
|
65
|
+
status=data.get("status", ""),
|
|
66
|
+
avatar_url=data.get("avatarUrl"),
|
|
67
|
+
tags=list(data.get("tags") or []),
|
|
68
|
+
created_at=parse_datetime(data.get("createdAt")),
|
|
69
|
+
raw=data,
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass(frozen=True)
|
|
74
|
+
class MediaAsset:
|
|
75
|
+
"""An uploaded image or video. Attach it to a post by ``id``."""
|
|
76
|
+
|
|
77
|
+
id: str
|
|
78
|
+
type: str
|
|
79
|
+
"""``image`` or ``video``."""
|
|
80
|
+
mime_type: str
|
|
81
|
+
size: int
|
|
82
|
+
width: Optional[int]
|
|
83
|
+
height: Optional[int]
|
|
84
|
+
url: str
|
|
85
|
+
created_at: Optional[datetime]
|
|
86
|
+
raw: Dict[str, Any] = field(repr=False, compare=False)
|
|
87
|
+
|
|
88
|
+
@classmethod
|
|
89
|
+
def from_api(cls, data: Dict[str, Any]) -> "MediaAsset":
|
|
90
|
+
return cls(
|
|
91
|
+
id=data["id"],
|
|
92
|
+
type=data.get("type", ""),
|
|
93
|
+
mime_type=data.get("mimeType", ""),
|
|
94
|
+
size=int(data.get("size") or 0),
|
|
95
|
+
width=data.get("width"),
|
|
96
|
+
height=data.get("height"),
|
|
97
|
+
url=data.get("url", ""),
|
|
98
|
+
created_at=parse_datetime(data.get("createdAt")),
|
|
99
|
+
raw=data,
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@dataclass(frozen=True)
|
|
104
|
+
class PostTarget:
|
|
105
|
+
"""One account a post goes to, with that copy's own publishing state."""
|
|
106
|
+
|
|
107
|
+
id: str
|
|
108
|
+
account_id: str
|
|
109
|
+
status: str
|
|
110
|
+
"""``pending``, ``publishing``, ``published`` or ``failed``."""
|
|
111
|
+
error: Optional[str]
|
|
112
|
+
external_post_id: Optional[str]
|
|
113
|
+
permalink_url: Optional[str]
|
|
114
|
+
published_at: Optional[datetime]
|
|
115
|
+
account_name: Optional[str]
|
|
116
|
+
platform: Optional[str]
|
|
117
|
+
raw: Dict[str, Any] = field(repr=False, compare=False)
|
|
118
|
+
|
|
119
|
+
@classmethod
|
|
120
|
+
def from_api(cls, data: Dict[str, Any]) -> "PostTarget":
|
|
121
|
+
account = data.get("account") or {}
|
|
122
|
+
return cls(
|
|
123
|
+
id=data["id"],
|
|
124
|
+
account_id=data.get("socialAccountId", ""),
|
|
125
|
+
status=data.get("status", ""),
|
|
126
|
+
error=data.get("error"),
|
|
127
|
+
external_post_id=data.get("externalPostId"),
|
|
128
|
+
permalink_url=data.get("permalinkUrl"),
|
|
129
|
+
published_at=parse_datetime(data.get("publishedAt")),
|
|
130
|
+
account_name=account.get("name"),
|
|
131
|
+
platform=account.get("platform"),
|
|
132
|
+
raw=data,
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@dataclass(frozen=True)
|
|
137
|
+
class Post:
|
|
138
|
+
"""A post and the accounts it targets."""
|
|
139
|
+
|
|
140
|
+
id: str
|
|
141
|
+
status: str
|
|
142
|
+
"""One of the :class:`PostStatus` values."""
|
|
143
|
+
content: str
|
|
144
|
+
scheduled_at: Optional[datetime]
|
|
145
|
+
published_at: Optional[datetime]
|
|
146
|
+
error: Optional[str]
|
|
147
|
+
rejection_reason: Optional[str]
|
|
148
|
+
media: List[Dict[str, Any]]
|
|
149
|
+
options: Dict[str, Any]
|
|
150
|
+
targets: List[PostTarget]
|
|
151
|
+
author_id: Optional[str]
|
|
152
|
+
created_at: Optional[datetime]
|
|
153
|
+
updated_at: Optional[datetime]
|
|
154
|
+
raw: Dict[str, Any] = field(repr=False, compare=False)
|
|
155
|
+
|
|
156
|
+
@property
|
|
157
|
+
def is_final(self) -> bool:
|
|
158
|
+
"""True once the post is published, failed or rejected."""
|
|
159
|
+
return self.status in FINAL_STATUSES
|
|
160
|
+
|
|
161
|
+
@classmethod
|
|
162
|
+
def from_api(cls, data: Dict[str, Any]) -> "Post":
|
|
163
|
+
return cls(
|
|
164
|
+
id=data["id"],
|
|
165
|
+
status=data.get("status", ""),
|
|
166
|
+
content=data.get("content", ""),
|
|
167
|
+
scheduled_at=parse_datetime(data.get("scheduledAt")),
|
|
168
|
+
published_at=parse_datetime(data.get("publishedAt")),
|
|
169
|
+
error=data.get("error"),
|
|
170
|
+
rejection_reason=data.get("rejectionReason"),
|
|
171
|
+
media=list(data.get("media") or []),
|
|
172
|
+
options=dict(data.get("options") or {}),
|
|
173
|
+
targets=[PostTarget.from_api(t) for t in data.get("targets") or []],
|
|
174
|
+
author_id=data.get("authorId"),
|
|
175
|
+
created_at=parse_datetime(data.get("createdAt")),
|
|
176
|
+
updated_at=parse_datetime(data.get("updatedAt")),
|
|
177
|
+
raw=data,
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
@dataclass(frozen=True)
|
|
182
|
+
class PublishingLimit:
|
|
183
|
+
"""An Instagram account's rolling 24-hour publishing quota."""
|
|
184
|
+
|
|
185
|
+
account_id: str
|
|
186
|
+
account_name: str
|
|
187
|
+
used: int
|
|
188
|
+
total: int
|
|
189
|
+
remaining: int
|
|
190
|
+
duration_seconds: int
|
|
191
|
+
|
|
192
|
+
@classmethod
|
|
193
|
+
def from_api(cls, data: Dict[str, Any]) -> "PublishingLimit":
|
|
194
|
+
return cls(
|
|
195
|
+
account_id=data.get("accountId", ""),
|
|
196
|
+
account_name=data.get("accountName", ""),
|
|
197
|
+
used=int(data.get("used") or 0),
|
|
198
|
+
total=int(data.get("total") or 0),
|
|
199
|
+
remaining=int(data.get("remaining") or 0),
|
|
200
|
+
duration_seconds=int(data.get("durationSeconds") or 0),
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
@dataclass(frozen=True)
|
|
205
|
+
class Page(Generic[T]):
|
|
206
|
+
"""One page of results. Pass ``next_cursor`` back to get the next page."""
|
|
207
|
+
|
|
208
|
+
items: List[T]
|
|
209
|
+
next_cursor: Optional[str]
|
|
210
|
+
|
|
211
|
+
def __iter__(self): # type: ignore[no-untyped-def]
|
|
212
|
+
return iter(self.items)
|
|
213
|
+
|
|
214
|
+
def __len__(self) -> int:
|
|
215
|
+
return len(self.items)
|
cholaka/_resources.py
ADDED
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import mimetypes
|
|
4
|
+
import os
|
|
5
|
+
import time
|
|
6
|
+
import uuid
|
|
7
|
+
from datetime import datetime
|
|
8
|
+
from typing import (
|
|
9
|
+
IO,
|
|
10
|
+
TYPE_CHECKING,
|
|
11
|
+
Any,
|
|
12
|
+
Callable,
|
|
13
|
+
Dict,
|
|
14
|
+
Iterator,
|
|
15
|
+
List,
|
|
16
|
+
Optional,
|
|
17
|
+
Sequence,
|
|
18
|
+
Union,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
from ._errors import CholakaError, PublishTimeoutError
|
|
22
|
+
from ._models import (
|
|
23
|
+
Account,
|
|
24
|
+
MediaAsset,
|
|
25
|
+
Page,
|
|
26
|
+
Post,
|
|
27
|
+
PostStatus,
|
|
28
|
+
PublishingLimit,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
if TYPE_CHECKING:
|
|
32
|
+
from ._client import SyncAPIClient
|
|
33
|
+
|
|
34
|
+
DateLike = Union[datetime, str]
|
|
35
|
+
MediaRef = Union[str, MediaAsset]
|
|
36
|
+
FileInput = Union[str, "os.PathLike[str]", bytes, IO[bytes]]
|
|
37
|
+
|
|
38
|
+
# Types the API accepts. mimetypes misses some of these on older Pythons.
|
|
39
|
+
_CONTENT_TYPES = {
|
|
40
|
+
".jpg": "image/jpeg",
|
|
41
|
+
".jpeg": "image/jpeg",
|
|
42
|
+
".png": "image/png",
|
|
43
|
+
".webp": "image/webp",
|
|
44
|
+
".mp4": "video/mp4",
|
|
45
|
+
".mov": "video/quicktime",
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _iso(value: DateLike, name: str) -> str:
|
|
50
|
+
"""Render a datetime for the API, refusing naive ones."""
|
|
51
|
+
if isinstance(value, str):
|
|
52
|
+
return value
|
|
53
|
+
if value.tzinfo is None or value.tzinfo.utcoffset(value) is None:
|
|
54
|
+
raise ValueError(
|
|
55
|
+
f"{name} must be timezone-aware, e.g. "
|
|
56
|
+
"datetime(2030, 1, 1, 9, 0, tzinfo=timezone.utc) or "
|
|
57
|
+
"datetime.now().astimezone() + timedelta(hours=1)"
|
|
58
|
+
)
|
|
59
|
+
return value.isoformat()
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _media_ids(media: Optional[Sequence[MediaRef]]) -> Optional[List[str]]:
|
|
63
|
+
if media is None:
|
|
64
|
+
return None
|
|
65
|
+
return [m.id if isinstance(m, MediaAsset) else str(m) for m in media]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _id(value: Union[str, Post, Account, MediaAsset]) -> str:
|
|
69
|
+
return value if isinstance(value, str) else value.id
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class PostsResource:
|
|
73
|
+
"""Create, schedule, publish and manage posts."""
|
|
74
|
+
|
|
75
|
+
def __init__(self, client: "SyncAPIClient") -> None:
|
|
76
|
+
self._client = client
|
|
77
|
+
|
|
78
|
+
def create(
|
|
79
|
+
self,
|
|
80
|
+
content: str,
|
|
81
|
+
*,
|
|
82
|
+
account_ids: Optional[Sequence[str]] = None,
|
|
83
|
+
media: Optional[Sequence[MediaRef]] = None,
|
|
84
|
+
media_meta: Optional[Sequence[Dict[str, Any]]] = None,
|
|
85
|
+
options: Optional[Dict[str, Any]] = None,
|
|
86
|
+
scheduled_at: Optional[DateLike] = None,
|
|
87
|
+
publish_now: bool = False,
|
|
88
|
+
idempotency_key: Optional[str] = None,
|
|
89
|
+
) -> Post:
|
|
90
|
+
"""Create a post.
|
|
91
|
+
|
|
92
|
+
With ``scheduled_at`` the post is queued for that time; with
|
|
93
|
+
``publish_now=True`` it starts publishing immediately; with neither it
|
|
94
|
+
is saved as a draft. If your organization requires approval for the
|
|
95
|
+
token's owner, a scheduled or published post lands in
|
|
96
|
+
``pending_approval`` instead.
|
|
97
|
+
|
|
98
|
+
An ``Idempotency-Key`` is generated for you, so a retried request
|
|
99
|
+
never creates the post twice. Pass your own key to make retries across
|
|
100
|
+
process restarts safe as well.
|
|
101
|
+
|
|
102
|
+
:param account_ids: Ids from :meth:`AccountsResource.list`.
|
|
103
|
+
:param media: Uploaded :class:`MediaAsset` objects or their ids, in
|
|
104
|
+
display order (up to 10 for an Instagram carousel).
|
|
105
|
+
:param media_meta: Per-asset extras such as alt text and user tags,
|
|
106
|
+
each ``{"assetId": ..., "altText": ..., "userTags": [...]}``.
|
|
107
|
+
:param options: Platform options, e.g. ``{"igStory": True}`` or
|
|
108
|
+
``{"fbLink": "https://..."}``. See the API reference.
|
|
109
|
+
:param scheduled_at: A timezone-aware datetime or an ISO 8601 string.
|
|
110
|
+
"""
|
|
111
|
+
if publish_now and scheduled_at is not None:
|
|
112
|
+
raise ValueError("Pass either scheduled_at or publish_now, not both")
|
|
113
|
+
body: Dict[str, Any] = {"content": content}
|
|
114
|
+
if account_ids is not None:
|
|
115
|
+
body["targetIds"] = list(account_ids)
|
|
116
|
+
ids = _media_ids(media)
|
|
117
|
+
if ids is not None:
|
|
118
|
+
body["mediaIds"] = ids
|
|
119
|
+
if media_meta is not None:
|
|
120
|
+
body["mediaMeta"] = list(media_meta)
|
|
121
|
+
if options is not None:
|
|
122
|
+
body["options"] = options
|
|
123
|
+
if scheduled_at is not None:
|
|
124
|
+
body["scheduledAt"] = _iso(scheduled_at, "scheduled_at")
|
|
125
|
+
if publish_now:
|
|
126
|
+
body["publishNow"] = True
|
|
127
|
+
data = self._client.request(
|
|
128
|
+
"POST",
|
|
129
|
+
"/posts",
|
|
130
|
+
json=body,
|
|
131
|
+
idempotency_key=idempotency_key or str(uuid.uuid4()),
|
|
132
|
+
)
|
|
133
|
+
return Post.from_api(data)
|
|
134
|
+
|
|
135
|
+
def get(self, post_id: Union[str, Post]) -> Post:
|
|
136
|
+
"""Fetch one post with the publishing state of each target."""
|
|
137
|
+
return Post.from_api(self._client.request("GET", f"/posts/{_id(post_id)}"))
|
|
138
|
+
|
|
139
|
+
def list(
|
|
140
|
+
self,
|
|
141
|
+
*,
|
|
142
|
+
status: Optional[str] = None,
|
|
143
|
+
account_id: Optional[str] = None,
|
|
144
|
+
date_from: Optional[DateLike] = None,
|
|
145
|
+
date_to: Optional[DateLike] = None,
|
|
146
|
+
limit: Optional[int] = None,
|
|
147
|
+
cursor: Optional[str] = None,
|
|
148
|
+
) -> Page[Post]:
|
|
149
|
+
"""List posts, newest first.
|
|
150
|
+
|
|
151
|
+
:param status: Only posts with this :class:`PostStatus`.
|
|
152
|
+
:param account_id: Only posts that target this account.
|
|
153
|
+
:param date_from: Scheduled or published at or after this time.
|
|
154
|
+
:param date_to: Scheduled or published at or before this time.
|
|
155
|
+
:param limit: Page size, at most 100 (default 50).
|
|
156
|
+
:param cursor: ``next_cursor`` from the previous page.
|
|
157
|
+
"""
|
|
158
|
+
params = {
|
|
159
|
+
"status": status,
|
|
160
|
+
"accountId": account_id,
|
|
161
|
+
"from": _iso(date_from, "date_from") if date_from else None,
|
|
162
|
+
"to": _iso(date_to, "date_to") if date_to else None,
|
|
163
|
+
"limit": str(limit) if limit is not None else None,
|
|
164
|
+
"cursor": cursor,
|
|
165
|
+
}
|
|
166
|
+
data = self._client.request("GET", "/posts", params=params)
|
|
167
|
+
return Page(
|
|
168
|
+
items=[Post.from_api(p) for p in data.get("items", [])],
|
|
169
|
+
next_cursor=data.get("nextCursor"),
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
def iter(self, **filters: Any) -> Iterator[Post]:
|
|
173
|
+
"""Like :meth:`list`, but follows every page for you."""
|
|
174
|
+
filters.pop("cursor", None)
|
|
175
|
+
cursor: Optional[str] = None
|
|
176
|
+
while True:
|
|
177
|
+
page = self.list(cursor=cursor, **filters)
|
|
178
|
+
yield from page.items
|
|
179
|
+
if not page.next_cursor:
|
|
180
|
+
return
|
|
181
|
+
cursor = page.next_cursor
|
|
182
|
+
|
|
183
|
+
def update(
|
|
184
|
+
self,
|
|
185
|
+
post_id: Union[str, Post],
|
|
186
|
+
*,
|
|
187
|
+
content: Optional[str] = None,
|
|
188
|
+
account_ids: Optional[Sequence[str]] = None,
|
|
189
|
+
media: Optional[Sequence[MediaRef]] = None,
|
|
190
|
+
media_meta: Optional[Sequence[Dict[str, Any]]] = None,
|
|
191
|
+
options: Optional[Dict[str, Any]] = None,
|
|
192
|
+
scheduled_at: Optional[DateLike] = None,
|
|
193
|
+
) -> Post:
|
|
194
|
+
"""Change a draft, scheduled or failed post. Omitted fields stay as
|
|
195
|
+
they are. Setting ``scheduled_at`` (re)schedules it.
|
|
196
|
+
|
|
197
|
+
Only ``content`` can change once a post is published; the new text is
|
|
198
|
+
pushed to each platform.
|
|
199
|
+
"""
|
|
200
|
+
body: Dict[str, Any] = {}
|
|
201
|
+
if content is not None:
|
|
202
|
+
body["content"] = content
|
|
203
|
+
if account_ids is not None:
|
|
204
|
+
body["targetIds"] = list(account_ids)
|
|
205
|
+
ids = _media_ids(media)
|
|
206
|
+
if ids is not None:
|
|
207
|
+
body["mediaIds"] = ids
|
|
208
|
+
if media_meta is not None:
|
|
209
|
+
body["mediaMeta"] = list(media_meta)
|
|
210
|
+
if options is not None:
|
|
211
|
+
body["options"] = options
|
|
212
|
+
if scheduled_at is not None:
|
|
213
|
+
body["scheduledAt"] = _iso(scheduled_at, "scheduled_at")
|
|
214
|
+
return self._patch(post_id, body)
|
|
215
|
+
|
|
216
|
+
def schedule(self, post_id: Union[str, Post], at: DateLike) -> Post:
|
|
217
|
+
"""Schedule (or reschedule) an existing post for ``at``."""
|
|
218
|
+
return self._patch(post_id, {"scheduledAt": _iso(at, "at")})
|
|
219
|
+
|
|
220
|
+
def unschedule(self, post_id: Union[str, Post]) -> Post:
|
|
221
|
+
"""Take a scheduled post off the queue and turn it back into a draft."""
|
|
222
|
+
return self._patch(post_id, {"unschedule": True})
|
|
223
|
+
|
|
224
|
+
def publish(self, post_id: Union[str, Post]) -> Post:
|
|
225
|
+
"""Publish an existing draft or scheduled post right away."""
|
|
226
|
+
return self._patch(post_id, {"publishNow": True})
|
|
227
|
+
|
|
228
|
+
def retry(self, post_id: Union[str, Post]) -> Post:
|
|
229
|
+
"""Try publishing a failed post again."""
|
|
230
|
+
data = self._client.request("POST", f"/posts/{_id(post_id)}/retry")
|
|
231
|
+
return Post.from_api(data)
|
|
232
|
+
|
|
233
|
+
def duplicate(
|
|
234
|
+
self, post_id: Union[str, Post], *, idempotency_key: Optional[str] = None
|
|
235
|
+
) -> Post:
|
|
236
|
+
"""Copy a post into a new draft."""
|
|
237
|
+
data = self._client.request(
|
|
238
|
+
"POST",
|
|
239
|
+
f"/posts/{_id(post_id)}/duplicate",
|
|
240
|
+
idempotency_key=idempotency_key or str(uuid.uuid4()),
|
|
241
|
+
)
|
|
242
|
+
return Post.from_api(data)
|
|
243
|
+
|
|
244
|
+
def delete(self, post_id: Union[str, Post]) -> None:
|
|
245
|
+
"""Delete a post. A scheduled post is taken off the queue first."""
|
|
246
|
+
self._client.request("DELETE", f"/posts/{_id(post_id)}")
|
|
247
|
+
|
|
248
|
+
def wait_for_publish(
|
|
249
|
+
self,
|
|
250
|
+
post_id: Union[str, Post],
|
|
251
|
+
*,
|
|
252
|
+
timeout: float = 300.0,
|
|
253
|
+
poll_interval: float = 5.0,
|
|
254
|
+
) -> Post:
|
|
255
|
+
"""Poll until the post is published, failed or rejected, and return it.
|
|
256
|
+
|
|
257
|
+
Check ``post.status`` (and each ``post.targets[i].error``) afterwards:
|
|
258
|
+
a failed publish is returned, not raised.
|
|
259
|
+
|
|
260
|
+
:raises PublishTimeoutError: still not finished after ``timeout``
|
|
261
|
+
seconds. The error's ``post`` attribute holds the last state seen.
|
|
262
|
+
:raises CholakaError: the post is a draft, which never publishes on
|
|
263
|
+
its own.
|
|
264
|
+
"""
|
|
265
|
+
deadline = time.monotonic() + timeout
|
|
266
|
+
while True:
|
|
267
|
+
post = self.get(post_id)
|
|
268
|
+
if post.is_final:
|
|
269
|
+
return post
|
|
270
|
+
if post.status == PostStatus.DRAFT:
|
|
271
|
+
raise CholakaError(
|
|
272
|
+
f"Post {post.id} is a draft and will not publish by itself. "
|
|
273
|
+
"Call posts.publish() or posts.schedule() first."
|
|
274
|
+
)
|
|
275
|
+
remaining = deadline - time.monotonic()
|
|
276
|
+
if remaining <= 0:
|
|
277
|
+
raise PublishTimeoutError(
|
|
278
|
+
f"Post {post.id} is still '{post.status}' after {timeout:.0f}s",
|
|
279
|
+
post,
|
|
280
|
+
)
|
|
281
|
+
self._client._sleep(min(poll_interval, remaining))
|
|
282
|
+
|
|
283
|
+
def _patch(self, post_id: Union[str, Post], body: Dict[str, Any]) -> Post:
|
|
284
|
+
data = self._client.request("PATCH", f"/posts/{_id(post_id)}", json=body)
|
|
285
|
+
return Post.from_api(data)
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
class MediaResource:
|
|
289
|
+
"""Upload images and videos to attach to posts."""
|
|
290
|
+
|
|
291
|
+
def __init__(self, client: "SyncAPIClient") -> None:
|
|
292
|
+
self._client = client
|
|
293
|
+
|
|
294
|
+
def upload(
|
|
295
|
+
self,
|
|
296
|
+
file: FileInput,
|
|
297
|
+
*,
|
|
298
|
+
filename: Optional[str] = None,
|
|
299
|
+
content_type: Optional[str] = None,
|
|
300
|
+
) -> MediaAsset:
|
|
301
|
+
"""Upload one file and return the stored asset.
|
|
302
|
+
|
|
303
|
+
Accepts JPEG, PNG and WebP images (up to 8 MB; converted to JPEG) and
|
|
304
|
+
MP4 or MOV videos (up to 100 MB).
|
|
305
|
+
|
|
306
|
+
:param file: A path, raw bytes, or a binary file object.
|
|
307
|
+
:param filename: Required for bytes; used to infer ``content_type``.
|
|
308
|
+
:param content_type: Override the detected MIME type.
|
|
309
|
+
"""
|
|
310
|
+
factory = _file_factory(file, filename, content_type)
|
|
311
|
+
data = self._client.request(
|
|
312
|
+
"POST", "/posts/media/upload", files=factory, retry_safe=False
|
|
313
|
+
)
|
|
314
|
+
return MediaAsset.from_api(data)
|
|
315
|
+
|
|
316
|
+
def delete(self, media_id: Union[str, MediaAsset]) -> None:
|
|
317
|
+
"""Delete an uploaded asset."""
|
|
318
|
+
self._client.request("DELETE", f"/posts/media/{_id(media_id)}")
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
class AccountsResource:
|
|
322
|
+
"""The connected social accounts you can publish to."""
|
|
323
|
+
|
|
324
|
+
def __init__(self, client: "SyncAPIClient") -> None:
|
|
325
|
+
self._client = client
|
|
326
|
+
|
|
327
|
+
def list(self, *, platform: Optional[str] = None) -> List[Account]:
|
|
328
|
+
"""List connected accounts, optionally only one ``platform``
|
|
329
|
+
(``fb_page``, ``ig_business``, ...)."""
|
|
330
|
+
data = self._client.request("GET", "/social-accounts")
|
|
331
|
+
accounts = [Account.from_api(a) for a in data or []]
|
|
332
|
+
if platform:
|
|
333
|
+
accounts = [a for a in accounts if a.platform == platform]
|
|
334
|
+
return accounts
|
|
335
|
+
|
|
336
|
+
def publishing_limit(self, account_id: Union[str, Account]) -> PublishingLimit:
|
|
337
|
+
"""An Instagram account's remaining 24-hour publishing quota, read
|
|
338
|
+
live from Meta."""
|
|
339
|
+
data = self._client.request(
|
|
340
|
+
"GET", f"/posts/publishing-limit/{_id(account_id)}"
|
|
341
|
+
)
|
|
342
|
+
return PublishingLimit.from_api(data)
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _file_factory(
|
|
346
|
+
file: FileInput, filename: Optional[str], content_type: Optional[str]
|
|
347
|
+
) -> Callable[[], Dict[str, Any]]:
|
|
348
|
+
"""Build a callable producing the multipart ``files`` mapping, so a retry
|
|
349
|
+
can resend the upload from the beginning."""
|
|
350
|
+
if isinstance(file, (str, os.PathLike)):
|
|
351
|
+
path = os.fspath(file)
|
|
352
|
+
name = filename or os.path.basename(path)
|
|
353
|
+
ctype = content_type or _guess_type(name)
|
|
354
|
+
|
|
355
|
+
def from_path() -> Dict[str, Any]:
|
|
356
|
+
with open(path, "rb") as fh:
|
|
357
|
+
return {"file": (name, fh.read(), ctype)}
|
|
358
|
+
|
|
359
|
+
return from_path
|
|
360
|
+
|
|
361
|
+
if isinstance(file, (bytes, bytearray)):
|
|
362
|
+
if not filename and not content_type:
|
|
363
|
+
raise ValueError("Pass filename= (or content_type=) when uploading bytes")
|
|
364
|
+
name = filename or "upload"
|
|
365
|
+
ctype = content_type or _guess_type(name)
|
|
366
|
+
payload = bytes(file)
|
|
367
|
+
return lambda: {"file": (name, payload, ctype)}
|
|
368
|
+
|
|
369
|
+
name = filename or os.path.basename(str(getattr(file, "name", ""))) or "upload"
|
|
370
|
+
ctype = content_type or _guess_type(name)
|
|
371
|
+
if file.seekable():
|
|
372
|
+
start = file.tell()
|
|
373
|
+
|
|
374
|
+
def from_stream() -> Dict[str, Any]:
|
|
375
|
+
file.seek(start)
|
|
376
|
+
return {"file": (name, file.read(), ctype)}
|
|
377
|
+
|
|
378
|
+
return from_stream
|
|
379
|
+
payload = file.read()
|
|
380
|
+
return lambda: {"file": (name, payload, ctype)}
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def _guess_type(name: str) -> str:
|
|
384
|
+
ext = os.path.splitext(name)[1].lower()
|
|
385
|
+
if ext in _CONTENT_TYPES:
|
|
386
|
+
return _CONTENT_TYPES[ext]
|
|
387
|
+
guessed, _ = mimetypes.guess_type(name)
|
|
388
|
+
if not guessed:
|
|
389
|
+
raise ValueError(
|
|
390
|
+
f"Cannot tell the file type of {name!r}. Pass content_type=, e.g. "
|
|
391
|
+
"'image/jpeg' or 'video/mp4'."
|
|
392
|
+
)
|
|
393
|
+
return guessed
|
cholaka/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
cholaka/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: cholaka
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python SDK for the Cholaka posting and scheduling API
|
|
5
|
+
Keywords: cholaka,facebook,instagram,scheduling,social media
|
|
6
|
+
Classifier: Programming Language :: Python :: 3
|
|
7
|
+
Classifier: Typing :: Typed
|
|
8
|
+
Requires-Python: >=3.9
|
|
9
|
+
Requires-Dist: httpx<1,>=0.24
|
|
10
|
+
Provides-Extra: dev
|
|
11
|
+
Requires-Dist: pytest>=7; extra == 'dev'
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
|
|
14
|
+
# Cholaka Python SDK
|
|
15
|
+
|
|
16
|
+
Create, schedule and publish posts to your Cholaka organization's connected
|
|
17
|
+
Facebook Pages and Instagram accounts from Python.
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
pip install cholaka
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Requires Python 3.9+.
|
|
24
|
+
|
|
25
|
+
## Get an API token
|
|
26
|
+
|
|
27
|
+
In Cholaka, an organization admin opens **Settings → Integrations → New token**
|
|
28
|
+
and grants:
|
|
29
|
+
|
|
30
|
+
- `posts:read` to list accounts and read posts
|
|
31
|
+
- `posts:write` to upload media and create, change or delete posts
|
|
32
|
+
|
|
33
|
+
The token (`cho_…`) is shown once. Store it as a secret, for example in the
|
|
34
|
+
`CHOLAKA_API_KEY` environment variable.
|
|
35
|
+
|
|
36
|
+
## Quick start
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
from datetime import datetime, timedelta, timezone
|
|
40
|
+
from cholaka import Cholaka
|
|
41
|
+
|
|
42
|
+
client = Cholaka() # reads CHOLAKA_API_KEY
|
|
43
|
+
|
|
44
|
+
# 1. Pick the accounts to post to.
|
|
45
|
+
for account in client.accounts.list():
|
|
46
|
+
print(account.id, account.platform, account.name)
|
|
47
|
+
|
|
48
|
+
page = client.accounts.list(platform="fb_page")[0]
|
|
49
|
+
|
|
50
|
+
# 2. Upload media (optional).
|
|
51
|
+
photo = client.media.upload("launch.jpg")
|
|
52
|
+
|
|
53
|
+
# 3. Schedule the post.
|
|
54
|
+
post = client.posts.create(
|
|
55
|
+
"We launch tomorrow!",
|
|
56
|
+
account_ids=[page.id],
|
|
57
|
+
media=[photo],
|
|
58
|
+
scheduled_at=datetime.now(timezone.utc) + timedelta(hours=2),
|
|
59
|
+
)
|
|
60
|
+
print(post.id, post.status) # "scheduled", or "pending_approval"
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Publish straight away and wait for the result:
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
post = client.posts.create("Live now", account_ids=[page.id], publish_now=True)
|
|
67
|
+
post = client.posts.wait_for_publish(post, timeout=300)
|
|
68
|
+
|
|
69
|
+
if post.status == "published":
|
|
70
|
+
for target in post.targets:
|
|
71
|
+
print(target.account_name, target.permalink_url)
|
|
72
|
+
else:
|
|
73
|
+
for target in post.targets:
|
|
74
|
+
print(target.account_name, target.status, target.error)
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## Configuration
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
client = Cholaka(
|
|
81
|
+
api_key="cho_...", # default: CHOLAKA_API_KEY
|
|
82
|
+
base_url="https://api.cholaka.ai", # default: CHOLAKA_BASE_URL, then this
|
|
83
|
+
timeout=60.0, # seconds per request
|
|
84
|
+
max_retries=2,
|
|
85
|
+
)
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
`base_url` may be the host alone or end in `/api/v1`. Use `with Cholaka() as
|
|
89
|
+
client:` (or `client.close()`) to release connections. To use proxies or
|
|
90
|
+
custom TLS, pass your own `httpx.Client` as `http_client=`.
|
|
91
|
+
|
|
92
|
+
## Posts
|
|
93
|
+
|
|
94
|
+
| Call | What it does |
|
|
95
|
+
| --- | --- |
|
|
96
|
+
| `posts.create(content, account_ids=, media=, scheduled_at=, publish_now=, options=, media_meta=)` | Create a draft (neither time nor `publish_now`), a scheduled post, or publish now |
|
|
97
|
+
| `posts.get(id)` | One post with per-account status, error and permalink |
|
|
98
|
+
| `posts.list(status=, account_id=, date_from=, date_to=, limit=, cursor=)` | One page, newest first. `page.next_cursor` gets the next |
|
|
99
|
+
| `posts.iter(**filters)` | Every matching post across all pages |
|
|
100
|
+
| `posts.update(id, content=, account_ids=, media=, options=, scheduled_at=)` | Change a draft, scheduled or failed post. On a published post only `content` can change |
|
|
101
|
+
| `posts.schedule(id, at)` | Schedule or reschedule |
|
|
102
|
+
| `posts.unschedule(id)` | Back to draft |
|
|
103
|
+
| `posts.publish(id)` | Publish now |
|
|
104
|
+
| `posts.retry(id)` | Retry a failed post |
|
|
105
|
+
| `posts.duplicate(id)` | Copy into a new draft |
|
|
106
|
+
| `posts.delete(id)` | Delete (cancels a scheduled publish) |
|
|
107
|
+
| `posts.wait_for_publish(id, timeout=, poll_interval=)` | Poll until published, failed or rejected |
|
|
108
|
+
|
|
109
|
+
Any argument that takes an id also accepts the object itself (`Post`,
|
|
110
|
+
`Account`, `MediaAsset`).
|
|
111
|
+
|
|
112
|
+
**Times** must be timezone-aware `datetime`s or ISO 8601 strings. A naive
|
|
113
|
+
`datetime` raises `ValueError` rather than guessing the timezone. For local
|
|
114
|
+
time, use `datetime.now().astimezone()`.
|
|
115
|
+
|
|
116
|
+
**Statuses** (`cholaka.PostStatus`): `draft`, `scheduled`,
|
|
117
|
+
`pending_approval`, `publishing`, `published`, `failed`, `rejected`. If your
|
|
118
|
+
organization requires approval for the token's owner, scheduled and
|
|
119
|
+
publish-now posts wait in `pending_approval` until an admin approves them in
|
|
120
|
+
the app.
|
|
121
|
+
|
|
122
|
+
**Platform options** go in `options`, using the API's field names. For example:
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
client.posts.create("Story time", account_ids=[ig.id], media=[photo],
|
|
126
|
+
options={"igStory": True}, publish_now=True)
|
|
127
|
+
client.posts.create("Read this", account_ids=[page.id],
|
|
128
|
+
options={"fbLink": "https://example.com/post"})
|
|
129
|
+
client.posts.create("Reel", account_ids=[ig.id], media=[video],
|
|
130
|
+
options={"igShareToFeed": True, "igThumbOffsetMs": 1500})
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
Alt text and people tags go in `media_meta`:
|
|
134
|
+
|
|
135
|
+
```python
|
|
136
|
+
client.posts.create("Team day", account_ids=[ig.id], media=[photo],
|
|
137
|
+
media_meta=[{"assetId": photo.id, "altText": "Our team on the roof",
|
|
138
|
+
"userTags": [{"username": "cholaka", "x": 0.5, "y": 0.4}]}])
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
The full list of options is in the API reference at
|
|
142
|
+
`https://<your-api-host>/api/public-docs`.
|
|
143
|
+
|
|
144
|
+
## Media
|
|
145
|
+
|
|
146
|
+
```python
|
|
147
|
+
asset = client.media.upload("photo.png") # path
|
|
148
|
+
asset = client.media.upload(open("clip.mp4", "rb")) # file object
|
|
149
|
+
asset = client.media.upload(data, filename="banner.jpg") # bytes
|
|
150
|
+
client.media.delete(asset)
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
Supported: JPEG, PNG and WebP images up to 8 MB (stored as JPEG), and MP4 or
|
|
154
|
+
MOV video up to 100 MB.
|
|
155
|
+
|
|
156
|
+
## Accounts
|
|
157
|
+
|
|
158
|
+
```python
|
|
159
|
+
client.accounts.list() # all connected accounts
|
|
160
|
+
client.accounts.list(platform="ig_business") # one platform
|
|
161
|
+
client.accounts.publishing_limit(ig) # Instagram's 24h quota
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
## Errors
|
|
165
|
+
|
|
166
|
+
Every error is a `cholaka.CholakaError`. Errors returned by the API are
|
|
167
|
+
`APIError`s with `status_code`, `message` and `messages` (one per validation
|
|
168
|
+
problem):
|
|
169
|
+
|
|
170
|
+
| Exception | Status | Typical cause |
|
|
171
|
+
| --- | --- | --- |
|
|
172
|
+
| `BadRequestError` | 400 | Invalid input, scheduled time in the past |
|
|
173
|
+
| `AuthenticationError` | 401 | Token missing, revoked or expired |
|
|
174
|
+
| `PermissionDeniedError` | 403 | Token lacks the scope, or the owner lacks the role |
|
|
175
|
+
| `NotFoundError` | 404 | Unknown post, media or account |
|
|
176
|
+
| `ConflictError` | 409 | The post's status doesn't allow the change |
|
|
177
|
+
| `UnprocessableEntityError` | 422 | Idempotency key reused with different data |
|
|
178
|
+
| `RateLimitError` | 429 | Too many requests (`.retry_after` seconds) |
|
|
179
|
+
| `InternalServerError` | 5xx | Server problem |
|
|
180
|
+
| `APIConnectionError` | – | Network failure |
|
|
181
|
+
| `PublishTimeoutError` | – | `wait_for_publish` timed out (`.post` has the last state) |
|
|
182
|
+
|
|
183
|
+
```python
|
|
184
|
+
from cholaka import BadRequestError
|
|
185
|
+
|
|
186
|
+
try:
|
|
187
|
+
client.posts.create("Hi", account_ids=[page.id], scheduled_at="2020-01-01T00:00:00Z")
|
|
188
|
+
except BadRequestError as e:
|
|
189
|
+
print(e.messages) # ['Scheduled time is in the past']
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
## Retries, rate limits and duplicates
|
|
193
|
+
|
|
194
|
+
Each token may make 120 requests per minute by default. The SDK retries
|
|
195
|
+
automatically, up to `max_retries` times:
|
|
196
|
+
|
|
197
|
+
- **429 Too Many Requests**: waits for `Retry-After`, then retries any call.
|
|
198
|
+
The server refuses these before doing any work.
|
|
199
|
+
- **Connection refused**: retries any call.
|
|
200
|
+
- **502/503/504 and dropped connections**: retries reads, deletes and creates.
|
|
201
|
+
It does not retry updates, so a publish is never repeated without you
|
|
202
|
+
knowing.
|
|
203
|
+
|
|
204
|
+
`posts.create` and `posts.duplicate` send an `Idempotency-Key`, so a retried
|
|
205
|
+
request never creates the post twice. To stay safe across process restarts,
|
|
206
|
+
pass your own stable key, for example from your database row:
|
|
207
|
+
|
|
208
|
+
```python
|
|
209
|
+
client.posts.create("Weekly digest", account_ids=[page.id],
|
|
210
|
+
scheduled_at=when, idempotency_key=f"digest-{week_id}")
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
The same key with different content raises `UnprocessableEntityError`.
|
|
214
|
+
|
|
215
|
+
## Development
|
|
216
|
+
|
|
217
|
+
```bash
|
|
218
|
+
python -m venv .venv && . .venv/bin/activate
|
|
219
|
+
pip install -e ".[dev]"
|
|
220
|
+
pytest
|
|
221
|
+
```
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
cholaka/__init__.py,sha256=m_b4N8LL27kNDJWY8X25FrtNx_6C_mZSqR3ACZey_gw,3405
|
|
2
|
+
cholaka/_client.py,sha256=nQ3SCli-8TH4PMdEZT_wYIjkPONAj3-cuCEtDAYJX44,6041
|
|
3
|
+
cholaka/_errors.py,sha256=h6zc21n7zGWfc_5q7m16xzvE6H3O8GmrkDlGMoq1wew,3497
|
|
4
|
+
cholaka/_models.py,sha256=KTpZtFvTvcLTQyPupcM9zg5uEwEYZ2N1K1ScYizmtro,6401
|
|
5
|
+
cholaka/_resources.py,sha256=TojKcxsliM1aElHg_evgvybY5Y0IRJZv1tASFC__GGU,14251
|
|
6
|
+
cholaka/_version.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
|
|
7
|
+
cholaka/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
cholaka-0.1.0.dist-info/METADATA,sha256=yAYCmUqIzDWP8IRSRq795ZpgqZPNgC5a-0IeUHP1RUs,7895
|
|
9
|
+
cholaka-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
10
|
+
cholaka-0.1.0.dist-info/RECORD,,
|