post-upload 1.2.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.
post_upload/client.py ADDED
@@ -0,0 +1,1147 @@
1
+ """Post-Upload API client."""
2
+
3
+ import io
4
+ import json as _json
5
+ import math
6
+ import mimetypes
7
+ import os
8
+ import shutil
9
+ import tempfile
10
+ import time
11
+ from contextlib import ExitStack
12
+ from typing import (
13
+ IO, Any, BinaryIO, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Union,
14
+ )
15
+ from urllib.parse import quote
16
+
17
+ import requests
18
+
19
+ from ._version import __version__
20
+ from .types import (
21
+ CompletedUploadSession, SkippedPlatform, UploadResponse, UploadSession, UploadSessionStatus,
22
+ )
23
+
24
+ DEFAULT_BASE_URL = "https://api.post-upload.com"
25
+ USER_AGENT = f"post-upload-python/{__version__}"
26
+ MAX_PHOTOS = 10
27
+
28
+ #: Environment variables read (in order) when no ``api_key`` is passed.
29
+ API_KEY_ENV_VARS = ("POST_UPLOAD_API_KEY", "INDREELFORGE_API_KEY")
30
+
31
+ #: Local videos larger than this (bytes) are sent with the chunked upload
32
+ #: endpoints automatically. Requests reach the API through Cloudflare, which
33
+ #: caps a single request body at 100 MB.
34
+ CHUNKED_THRESHOLD = 95 * 1024 * 1024
35
+
36
+ #: Largest video the API accepts (via chunked upload or ``video_url``).
37
+ MAX_VIDEO_BYTES = 500 * 1024 * 1024
38
+
39
+ #: Statuses on which a chunk upload is retried (plus network errors / timeouts).
40
+ RETRYABLE_STATUSES = frozenset({0, 408, 425, 429, 500, 502, 503, 504})
41
+
42
+ #: Every platform key known to this SDK version.
43
+ PLATFORMS = (
44
+ "instagram", "youtube", "tiktok", "facebook", "x", "linkedin", "threads", "pinterest",
45
+ "reddit", "bluesky", "google_business", "discord", "telegram", "slack", "mastodon", "wordpress",
46
+ "devto", "hashnode", "lemmy", "nostr", "whop", "listmonk",
47
+ )
48
+
49
+ #: Platforms connected with :meth:`PostUpload.connect_with_credentials`, and their required fields.
50
+ CREDENTIAL_PLATFORMS: Dict[str, Tuple[str, ...]] = {
51
+ "discord": ("webhook_url",),
52
+ "telegram": ("bot_token", "chat_id"),
53
+ "slack": ("webhook_url",),
54
+ "mastodon": ("instance_url", "access_token"),
55
+ "wordpress": ("site_url", "username", "app_password"),
56
+ "devto": ("api_key",),
57
+ "hashnode": ("access_token", "publication_id"),
58
+ "lemmy": ("instance_url", "username", "password", "community"),
59
+ "nostr": ("nsec",),
60
+ "whop": ("api_key",),
61
+ "listmonk": ("base_url", "api_user", "api_token", "list_ids"),
62
+ }
63
+
64
+ #: Optional credential fields per platform (see :data:`CREDENTIAL_PLATFORMS`).
65
+ #: Whop needs exactly one of ``experience_id`` (forum) or ``channel_id`` (chat).
66
+ CREDENTIAL_OPTIONAL_FIELDS: Dict[str, Tuple[str, ...]] = {
67
+ "devto": ("base_url",),
68
+ "lemmy": ("totp",),
69
+ "nostr": ("relays", "blossom_server"),
70
+ "whop": ("experience_id", "channel_id"),
71
+ }
72
+
73
+ ProgressCallback = Callable[[int, int], None]
74
+ VideoSource = Union[str, "os.PathLike[str]", bytes, bytearray, memoryview, IO[bytes]]
75
+
76
+ Field = Tuple[str, Tuple[Optional[str], Any]]
77
+
78
+
79
+ class PostUploadError(Exception):
80
+ """Error from the Post-Upload API (or a network failure / timeout).
81
+
82
+ Attributes:
83
+ status_code: HTTP status code (0 = network error, 408 = client-side timeout).
84
+ code: Machine-readable error code from the API (``error_code`` / ``code``),
85
+ or ``NETWORK_ERROR`` / ``TIMEOUT``; ``None`` when not provided.
86
+ body: Parsed JSON response body (dict) or raw text, if any.
87
+ headers: Response headers (``None`` for network errors).
88
+ """
89
+
90
+ def __init__(
91
+ self,
92
+ message: str,
93
+ status_code: int = 0,
94
+ code: Optional[str] = None,
95
+ body: Any = None,
96
+ headers: Optional[Mapping[str, str]] = None,
97
+ ):
98
+ super().__init__(message)
99
+ self.message = message
100
+ self.status_code = status_code
101
+ self.code = code
102
+ self.body = body
103
+ self.headers = headers
104
+
105
+ @property
106
+ def status(self) -> int:
107
+ """Alias of :attr:`status_code`."""
108
+ return self.status_code
109
+
110
+ def __repr__(self) -> str:
111
+ return (
112
+ f"{type(self).__name__}(message={self.message!r}, status_code={self.status_code!r}, "
113
+ f"code={self.code!r})"
114
+ )
115
+
116
+
117
+ #: Deprecated aliases (the SDK was called IndReelForge / InReelForge before
118
+ #: 1.2.0). They are the same class, so ``except IndReelForgeError`` keeps working.
119
+ IndReelForgeError = PostUploadError
120
+ InReelForgeError = PostUploadError
121
+
122
+
123
+ def _form_value(value: Any) -> Optional[List[str]]:
124
+ """Convert a Python value to one or more multipart field values."""
125
+ if value is None:
126
+ return None
127
+ if isinstance(value, bool):
128
+ return ["true" if value else "false"]
129
+ if isinstance(value, (list, tuple)):
130
+ out: List[str] = []
131
+ for v in value:
132
+ if v is None:
133
+ continue
134
+ out.append(("true" if v else "false") if isinstance(v, bool) else str(v))
135
+ return out
136
+ if isinstance(value, dict):
137
+ return [_json.dumps(value)]
138
+ return [str(value)]
139
+
140
+
141
+ def get_skipped_platforms(response: Any) -> List[SkippedPlatform]:
142
+ """
143
+ Platforms an upload skipped because the file is too large for them.
144
+
145
+ They are stored as ``failed`` with ``FILE_TOO_LARGE_FOR_PLATFORM``, never
146
+ sent, and use none of the platform's quota; the other platforms publish.
147
+ Returns ``[]`` when nothing was skipped.
148
+
149
+ Example:
150
+ >>> res = client.upload_video("my-brand", ["youtube", "bluesky"], video_path="big.mp4")
151
+ >>> for s in get_skipped_platforms(res):
152
+ ... print(s["platform"], s.get("message"))
153
+ """
154
+ if not isinstance(response, dict):
155
+ return []
156
+ data = response.get("data")
157
+ skipped = data.get("skipped_platforms") if isinstance(data, dict) else None
158
+ if skipped is None:
159
+ skipped = response.get("skipped_platforms")
160
+ return list(skipped) if isinstance(skipped, list) else []
161
+
162
+
163
+ def _seg(value: Any) -> str:
164
+ return quote(str(value), safe="")
165
+
166
+
167
+ def _require(value: Any, name: str) -> None:
168
+ if value is None or value == "":
169
+ raise ValueError(f"{name} is required")
170
+
171
+
172
+ class PostUpload:
173
+ """
174
+ Official Python client for the Post-Upload API.
175
+
176
+ Publish videos, photos, text and documents to 22 platforms: Instagram,
177
+ YouTube, TikTok, Facebook, X (Twitter), LinkedIn, Threads, Pinterest,
178
+ Reddit, Bluesky, Google Business Profile, Discord, Telegram, Slack,
179
+ Mastodon, WordPress, Dev.to, Hashnode, Lemmy, Nostr, Whop and Listmonk.
180
+
181
+ Args:
182
+ api_key: Your Post-Upload API key. When omitted it is read from the
183
+ ``POST_UPLOAD_API_KEY`` environment variable (or the older
184
+ ``INDREELFORGE_API_KEY``).
185
+ base_url: API base URL (default: https://api.post-upload.com).
186
+ timeout: Request timeout in seconds (default: 120).
187
+ session: Optional ``requests.Session`` to use.
188
+ headers: Optional extra headers sent with every request.
189
+ chunked_threshold: Local videos larger than this many bytes are sent
190
+ with the chunked upload endpoints (default :data:`CHUNKED_THRESHOLD`,
191
+ 95 MiB).
192
+ max_retries: How often a failed chunk is retried on 429 / 5xx /
193
+ network errors (default 5).
194
+
195
+ The client can be used as a context manager to close its HTTP session::
196
+
197
+ with PostUpload(api_key="...") as client:
198
+ client.get_me()
199
+
200
+ Example:
201
+ >>> client = PostUpload(api_key="your-api-key")
202
+ >>> result = client.upload_video(
203
+ ... user="my-profile",
204
+ ... platforms=["instagram", "tiktok"],
205
+ ... video_path="./video.mp4",
206
+ ... title="My video",
207
+ ... )
208
+ """
209
+
210
+ def __init__(
211
+ self,
212
+ api_key: Optional[str] = None,
213
+ base_url: str = DEFAULT_BASE_URL,
214
+ timeout: Union[int, float] = 120,
215
+ session: Optional[requests.Session] = None,
216
+ headers: Optional[Mapping[str, str]] = None,
217
+ *,
218
+ chunked_threshold: Optional[int] = None,
219
+ max_retries: int = 5,
220
+ ):
221
+ if not api_key:
222
+ for var in API_KEY_ENV_VARS:
223
+ api_key = os.environ.get(var)
224
+ if api_key:
225
+ break
226
+ if not api_key:
227
+ raise ValueError("api_key is required (or set POST_UPLOAD_API_KEY)")
228
+ self.api_key = api_key
229
+ self.base_url = (base_url or DEFAULT_BASE_URL).rstrip("/")
230
+ self.timeout = timeout
231
+ self.chunked_threshold = chunked_threshold
232
+ self.max_retries = max(0, int(max_retries))
233
+ self._session = session or requests.Session()
234
+ # Always send an explicit User-Agent: the API sits behind Cloudflare,
235
+ # which blocks generic library agents such as "Python-urllib".
236
+ self._session.headers.update(
237
+ {
238
+ "User-Agent": USER_AGENT,
239
+ "Accept": "application/json",
240
+ }
241
+ )
242
+ if headers:
243
+ self._session.headers.update(dict(headers))
244
+ self._session.headers["Authorization"] = f"Apikey {self.api_key}"
245
+
246
+ # ── Lifecycle ──
247
+
248
+ def close(self) -> None:
249
+ """Close the underlying HTTP session."""
250
+ self._session.close()
251
+
252
+ def __enter__(self) -> "PostUpload":
253
+ return self
254
+
255
+ def __exit__(self, *exc: Any) -> None:
256
+ self.close()
257
+
258
+ # ── Core request ──
259
+
260
+ def _request(
261
+ self,
262
+ method: str,
263
+ path: str,
264
+ json: Optional[Any] = None,
265
+ data: Optional[Any] = None,
266
+ files: Optional[Any] = None,
267
+ params: Optional[Mapping[str, Any]] = None,
268
+ headers: Optional[Mapping[str, str]] = None,
269
+ ) -> Any:
270
+ """Make an API request and return the decoded JSON body."""
271
+ url = f"{self.base_url}{path}"
272
+ if params:
273
+ params = {k: v for k, v in params.items() if v is not None and v != ""}
274
+ try:
275
+ resp = self._session.request(
276
+ method,
277
+ url,
278
+ json=json,
279
+ data=data,
280
+ files=files,
281
+ params=params or None,
282
+ headers=dict(headers) if headers else None,
283
+ timeout=self.timeout,
284
+ )
285
+ except requests.exceptions.Timeout:
286
+ raise PostUploadError("Request timed out", 408, "TIMEOUT") from None
287
+ except requests.exceptions.ConnectionError as e:
288
+ raise PostUploadError(f"Connection failed: {e}", 0, "NETWORK_ERROR") from None
289
+
290
+ text = resp.text or ""
291
+ body: Any = {}
292
+ if text.strip():
293
+ try:
294
+ body = resp.json()
295
+ except ValueError:
296
+ body = text
297
+
298
+ if not resp.ok:
299
+ obj = body if isinstance(body, dict) else None
300
+ message = None
301
+ if obj:
302
+ message = obj.get("error_description") or obj.get("error") or obj.get("message")
303
+ if not message:
304
+ message = text.strip()[:300] if isinstance(body, str) and text.strip() else f"HTTP {resp.status_code}"
305
+ code = (obj.get("error_code") or obj.get("code")) if obj else None
306
+ raise PostUploadError(
307
+ str(message),
308
+ resp.status_code,
309
+ str(code) if code is not None else None,
310
+ body if text.strip() else None,
311
+ dict(resp.headers),
312
+ )
313
+
314
+ return body
315
+
316
+ @staticmethod
317
+ def _idem(idempotency_key: Optional[str]) -> Optional[Dict[str, str]]:
318
+ return {"Idempotency-Key": idempotency_key} if idempotency_key else None
319
+
320
+ @staticmethod
321
+ def _fields(pairs: Sequence[Tuple[str, Any]]) -> List[Field]:
322
+ """Multipart text fields (``(name, (None, value))``) from (name, value) pairs."""
323
+ out: List[Field] = []
324
+ for name, value in pairs:
325
+ values = _form_value(value)
326
+ if values is None:
327
+ continue
328
+ for v in values:
329
+ out.append((name, (None, v)))
330
+ return out
331
+
332
+ def _build_form_fields(
333
+ self,
334
+ user: str,
335
+ platforms: Optional[Sequence[str]],
336
+ title: Optional[str] = None,
337
+ first_comment: Optional[str] = None,
338
+ schedule: Optional[str] = None,
339
+ timezone: Optional[str] = None,
340
+ description: Optional[str] = None,
341
+ add_to_queue: Optional[bool] = None,
342
+ async_upload: Optional[bool] = None,
343
+ request_id: Optional[str] = None,
344
+ platform_options: Optional[Mapping[str, Any]] = None,
345
+ extra: Optional[Mapping[str, Any]] = None,
346
+ ) -> List[Field]:
347
+ _require(user, "user")
348
+ pairs: List[Tuple[str, Any]] = [("user", user)]
349
+ for p in platforms or []:
350
+ pairs.append(("platform[]", p))
351
+ pairs += [
352
+ ("title", title or None),
353
+ ("description", description or None),
354
+ ("first_comment", first_comment or None),
355
+ ("schedule", schedule or None),
356
+ ("timezone", timezone or None),
357
+ ("add_to_queue", add_to_queue),
358
+ ("async_upload", async_upload),
359
+ ("request_id", request_id or None),
360
+ ]
361
+ for source in (platform_options, extra):
362
+ for key, value in (source or {}).items():
363
+ pairs.append((key, value))
364
+ return self._fields(pairs)
365
+
366
+ def _build_form_data(
367
+ self,
368
+ user: str,
369
+ platforms: List[str],
370
+ title: Optional[str] = None,
371
+ first_comment: Optional[str] = None,
372
+ schedule: Optional[str] = None,
373
+ timezone: Optional[str] = None,
374
+ **kwargs: Any,
375
+ ) -> Dict[str, Any]:
376
+ """Deprecated 1.0 helper kept for compatibility; returns a plain form dict."""
377
+ data: Dict[str, Any] = {"user": user, "platform[]": platforms}
378
+ if title:
379
+ data["title"] = title
380
+ if first_comment:
381
+ data["first_comment"] = first_comment
382
+ if schedule:
383
+ data["schedule"] = schedule
384
+ if timezone:
385
+ data["timezone"] = timezone
386
+ for key, value in kwargs.items():
387
+ data[key] = value
388
+ return data
389
+
390
+ # ── Upload ──
391
+
392
+ def upload_video(
393
+ self,
394
+ user: str,
395
+ platforms: List[str],
396
+ video_path: Optional[Union[str, "os.PathLike[str]"]] = None,
397
+ title: Optional[str] = None,
398
+ first_comment: Optional[str] = None,
399
+ schedule: Optional[str] = None,
400
+ timezone: Optional[str] = None,
401
+ *,
402
+ video_url: Optional[str] = None,
403
+ video_file: Optional[Union[bytes, bytearray, memoryview, IO[bytes]]] = None,
404
+ staged_file_id: Optional[str] = None,
405
+ filename: Optional[str] = None,
406
+ mime_type: Optional[str] = None,
407
+ chunked: Optional[bool] = None,
408
+ on_progress: Optional[ProgressCallback] = None,
409
+ description: Optional[str] = None,
410
+ add_to_queue: Optional[bool] = None,
411
+ async_upload: Optional[bool] = None,
412
+ request_id: Optional[str] = None,
413
+ idempotency_key: Optional[str] = None,
414
+ platform_options: Optional[Mapping[str, Any]] = None,
415
+ **kwargs: Any,
416
+ ) -> UploadResponse:
417
+ """
418
+ Upload a video to one or more platforms.
419
+
420
+ Give the video in exactly one way: ``video_path`` (local file),
421
+ ``video_file`` (bytes or a binary file object / stream), ``video_url``
422
+ (public URL the server downloads, up to 500 MB) or ``staged_file_id``
423
+ (a file already sent with :meth:`upload_large_file`).
424
+
425
+ Local files larger than :data:`CHUNKED_THRESHOLD` (95 MiB) are sent with
426
+ the chunked upload endpoints automatically (up to 500 MB), then posted
427
+ by ``staged_file_id``. Pass ``chunked=True`` to always do that, or
428
+ ``chunked=False`` to always send one multipart request.
429
+
430
+ Args:
431
+ user: Profile name (managed user).
432
+ platforms: Platforms, e.g. ``["instagram", "tiktok", "youtube"]``.
433
+ video_path: Path to a local video file.
434
+ title: Post title / caption.
435
+ first_comment: First comment text.
436
+ schedule: ISO-8601 datetime to publish later.
437
+ timezone: IANA timezone used with ``schedule``.
438
+ video_url: Public http(s) URL of the video; the server downloads it.
439
+ video_file: Video bytes or a binary file object (read part by part
440
+ for a chunked upload; a non-seekable stream is spooled to a
441
+ temporary file first).
442
+ staged_file_id: ID returned by :meth:`complete_upload_session` /
443
+ :meth:`upload_large_file` (usable once).
444
+ filename: File name sent for ``video_file`` (default: the file
445
+ object's name, else ``video.mp4``).
446
+ mime_type: MIME type for a chunked upload (default: from the name).
447
+ chunked: ``True`` / ``False`` to force or disable the chunked
448
+ upload; ``None`` (default) decides by size.
449
+ on_progress: ``on_progress(sent_bytes, total_bytes)``, called after
450
+ each part of a chunked upload.
451
+ description: Long description.
452
+ add_to_queue: Put the post in the profile's next free queue slot.
453
+ async_upload: ``False`` = wait (up to ~50 s) for the publish result;
454
+ the response then has ``sync: True`` and per-platform results.
455
+ request_id: Your own correlation id (see :meth:`get_request_status`).
456
+ idempotency_key: Sent as the ``Idempotency-Key`` header.
457
+ platform_options: Platform-specific fields (e.g. ``{"privacy_level": "PUBLIC_TO_EVERYONE"}``).
458
+ **kwargs: Platform-specific fields (same as ``platform_options``).
459
+
460
+ Returns:
461
+ Upload response with ``data.upload_id`` and per-platform statuses.
462
+ Platforms the file is too large for are skipped (the others still
463
+ publish) and listed in ``data.skipped_platforms``; see
464
+ :func:`get_skipped_platforms`.
465
+ """
466
+ sources = [
467
+ x for x in (video_path, video_file, video_url, staged_file_id)
468
+ if x is not None and not (isinstance(x, str) and x == "")
469
+ ]
470
+ if not sources:
471
+ raise ValueError(
472
+ "upload_video requires video_path, video_file, video_url or staged_file_id"
473
+ )
474
+ if len(sources) > 1:
475
+ raise ValueError(
476
+ "upload_video takes only one of video_path, video_file, video_url or staged_file_id"
477
+ )
478
+ if video_path is not None and not os.path.isfile(video_path):
479
+ raise FileNotFoundError(f"Video file not found: {video_path}")
480
+
481
+ fields = self._build_form_fields(
482
+ user, platforms, title, first_comment, schedule, timezone, description,
483
+ add_to_queue, async_upload, request_id, platform_options, kwargs,
484
+ )
485
+ with ExitStack() as stack:
486
+ if video_path is not None or video_file is not None:
487
+ source: VideoSource = video_path if video_path is not None else video_file # type: ignore[assignment]
488
+ fh, name, size = self._open_source(stack, source, filename)
489
+ if chunked or (chunked is None and size > self._threshold()):
490
+ staged_file_id = self._chunked_upload(fh, name, size, mime_type, on_progress)
491
+ else:
492
+ fields.append(("video", (name, fh)))
493
+ if staged_file_id:
494
+ fields.append(("staged_file_id", (None, str(staged_file_id))))
495
+ elif video_url:
496
+ fields.append(("video", (None, str(video_url))))
497
+ return self._request(
498
+ "POST", "/api/upload", files=fields, headers=self._idem(idempotency_key)
499
+ )
500
+
501
+ # ── Chunked upload (videos up to 500 MB) ──
502
+
503
+ def _threshold(self) -> int:
504
+ return CHUNKED_THRESHOLD if self.chunked_threshold is None else int(self.chunked_threshold)
505
+
506
+ @staticmethod
507
+ def _open_source(
508
+ stack: ExitStack, source: VideoSource, filename: Optional[str]
509
+ ) -> Tuple[BinaryIO, str, int]:
510
+ """Return a seekable binary file positioned at the start, its name and size."""
511
+ if isinstance(source, (str, os.PathLike)):
512
+ path = os.fspath(source)
513
+ if not os.path.isfile(path):
514
+ raise FileNotFoundError(f"Video file not found: {path}")
515
+ fh = stack.enter_context(open(path, "rb"))
516
+ return fh, filename or os.path.basename(path), os.path.getsize(path)
517
+ if isinstance(source, (bytes, bytearray, memoryview)):
518
+ data = bytes(source)
519
+ return io.BytesIO(data), filename or "video.mp4", len(data)
520
+ if not hasattr(source, "read"):
521
+ raise TypeError("video must be a path, bytes or a binary file object")
522
+ name = filename or os.path.basename(str(getattr(source, "name", "") or "")) or "video.mp4"
523
+ try:
524
+ seekable = bool(source.seekable()) if hasattr(source, "seekable") else False
525
+ except Exception: # pragma: no cover - exotic streams
526
+ seekable = False
527
+ if seekable and source.tell() == 0:
528
+ size = source.seek(0, os.SEEK_END)
529
+ source.seek(0)
530
+ return source, name, size # type: ignore[return-value]
531
+ # Non-seekable stream (or one not at offset 0): spool it to a temporary
532
+ # file (in memory up to the threshold, then on disk) so its size is
533
+ # known and every part can be re-read for a retry.
534
+ spool = stack.enter_context(tempfile.SpooledTemporaryFile(max_size=CHUNKED_THRESHOLD))
535
+ shutil.copyfileobj(source, spool, 1024 * 1024)
536
+ size = spool.tell()
537
+ spool.seek(0)
538
+ return spool, name, size # type: ignore[return-value]
539
+
540
+ def create_upload_session(
541
+ self, filename: str, size: int, mime_type: Optional[str] = None
542
+ ) -> UploadSession:
543
+ """
544
+ Start a chunked upload (``POST /api/upload/chunked/init``).
545
+
546
+ Args:
547
+ filename: Video file name, e.g. ``"episode.mp4"`` (MP4, MOV, AVI, WebM, MKV).
548
+ size: Total size in bytes (at most 500 MB).
549
+ mime_type: e.g. ``"video/mp4"`` (default: guessed from ``filename``).
550
+
551
+ Returns:
552
+ ``upload_session_id``, ``chunk_size``, ``total_chunks`` and ``expires_at``.
553
+ """
554
+ _require(filename, "filename")
555
+ if not isinstance(size, int) or isinstance(size, bool) or size <= 0:
556
+ raise ValueError("size must be a positive number of bytes")
557
+ mime = mime_type or mimetypes.guess_type(filename)[0] or "video/mp4"
558
+ return self._request(
559
+ "POST",
560
+ "/api/upload/chunked/init",
561
+ json={"filename": filename, "size": size, "mime_type": mime},
562
+ )
563
+
564
+ def upload_part(
565
+ self,
566
+ session_id: str,
567
+ index: int,
568
+ data: Union[bytes, bytearray, memoryview],
569
+ *,
570
+ retries: Optional[int] = None,
571
+ ) -> Dict[str, Any]:
572
+ """
573
+ Send one part (``PUT /api/upload/chunked/{id}/{index}``).
574
+
575
+ Every part must be exactly the session's ``chunk_size`` bytes except the
576
+ last. Retried with exponential backoff on 429, 5xx and network errors
577
+ (honouring ``Retry-After``); re-sending an index replaces it.
578
+
579
+ Args:
580
+ session_id: ``upload_session_id`` from :meth:`create_upload_session`.
581
+ index: 0-based part number.
582
+ data: The part's bytes.
583
+ retries: Override the client's ``max_retries`` for this part.
584
+ """
585
+ _require(session_id, "session_id")
586
+ if not isinstance(index, int) or isinstance(index, bool) or index < 0:
587
+ raise ValueError("index must be a non-negative integer")
588
+ body = bytes(data)
589
+ attempts = (self.max_retries if retries is None else max(0, int(retries))) + 1
590
+ for attempt in range(attempts):
591
+ try:
592
+ return self._request(
593
+ "PUT",
594
+ f"/api/upload/chunked/{_seg(session_id)}/{index}",
595
+ data=body,
596
+ headers={"Content-Type": "application/octet-stream"},
597
+ )
598
+ except PostUploadError as e:
599
+ if e.status_code not in RETRYABLE_STATUSES or attempt == attempts - 1:
600
+ raise
601
+ self._sleep(self._retry_delay(e, attempt))
602
+ raise AssertionError("unreachable") # pragma: no cover
603
+
604
+ def complete_upload_session(self, session_id: str) -> CompletedUploadSession:
605
+ """
606
+ Assemble and check the file (``POST /api/upload/chunked/{id}/complete``).
607
+
608
+ Returns:
609
+ ``staged_file_id`` (pass it to :meth:`upload_video`; usable once).
610
+ """
611
+ _require(session_id, "session_id")
612
+ return self._request("POST", f"/api/upload/chunked/{_seg(session_id)}/complete")
613
+
614
+ def get_upload_session(self, session_id: str) -> UploadSessionStatus:
615
+ """Parts received so far (``GET /api/upload/chunked/{id}``), to resume an upload."""
616
+ _require(session_id, "session_id")
617
+ return self._request("GET", f"/api/upload/chunked/{_seg(session_id)}")
618
+
619
+ def abort_upload_session(self, session_id: str) -> Dict[str, Any]:
620
+ """Cancel a chunked upload and delete its parts (``DELETE /api/upload/chunked/{id}``)."""
621
+ _require(session_id, "session_id")
622
+ return self._request("DELETE", f"/api/upload/chunked/{_seg(session_id)}")
623
+
624
+ def upload_large_file(
625
+ self,
626
+ video: VideoSource,
627
+ *,
628
+ filename: Optional[str] = None,
629
+ mime_type: Optional[str] = None,
630
+ on_progress: Optional[ProgressCallback] = None,
631
+ ) -> str:
632
+ """
633
+ Send a video with the chunked upload endpoints and return its ``staged_file_id``.
634
+
635
+ Runs init, every part (sequentially, with retries) and complete. If
636
+ anything fails after the session was created, the session is cancelled
637
+ (best effort) and the error is raised.
638
+
639
+ Args:
640
+ video: Path, bytes or binary file object.
641
+ filename: File name (default: from the path / file object, else ``video.mp4``).
642
+ mime_type: MIME type (default: guessed from the name).
643
+ on_progress: ``on_progress(sent_bytes, total_bytes)`` after each part.
644
+
645
+ Example:
646
+ >>> staged = client.upload_large_file("./episode.mp4")
647
+ >>> client.upload_video("my-brand", ["youtube"], staged_file_id=staged, title="Episode 1")
648
+ """
649
+ with ExitStack() as stack:
650
+ fh, name, size = self._open_source(stack, video, filename)
651
+ return self._chunked_upload(fh, name, size, mime_type, on_progress)
652
+
653
+ def _chunked_upload(
654
+ self,
655
+ fh: BinaryIO,
656
+ name: str,
657
+ size: int,
658
+ mime_type: Optional[str],
659
+ on_progress: Optional[ProgressCallback],
660
+ ) -> str:
661
+ if size <= 0:
662
+ raise ValueError("The video file is empty")
663
+ if size > MAX_VIDEO_BYTES:
664
+ raise ValueError(
665
+ f"The video is {size} bytes; the API accepts at most {MAX_VIDEO_BYTES} bytes (500 MB)"
666
+ )
667
+ session = self.create_upload_session(name, size, mime_type)
668
+ session_id = session.get("upload_session_id") if isinstance(session, dict) else None
669
+ if not session_id:
670
+ raise PostUploadError("Chunked upload init returned no upload_session_id", 0, None, session)
671
+ try:
672
+ chunk_size = int(session.get("chunk_size") or 0)
673
+ if chunk_size <= 0:
674
+ raise PostUploadError("Chunked upload init returned no chunk_size", 0, None, session)
675
+ total = int(session.get("total_chunks") or math.ceil(size / chunk_size))
676
+ sent = 0
677
+ for index in range(total):
678
+ offset = index * chunk_size
679
+ length = min(chunk_size, size - offset)
680
+ fh.seek(offset)
681
+ part = fh.read(length)
682
+ if len(part) != length:
683
+ raise IOError(
684
+ f"Could not read part {index}: expected {length} bytes, got {len(part)}"
685
+ )
686
+ self.upload_part(session_id, index, part)
687
+ sent += length
688
+ if on_progress:
689
+ on_progress(sent, size)
690
+ done = self.complete_upload_session(session_id)
691
+ staged = done.get("staged_file_id") if isinstance(done, dict) else None
692
+ if not staged:
693
+ raise PostUploadError(
694
+ "Chunked upload complete returned no staged_file_id", 0, None, done
695
+ )
696
+ return str(staged)
697
+ except BaseException:
698
+ try:
699
+ self.abort_upload_session(session_id)
700
+ except Exception:
701
+ pass
702
+ raise
703
+
704
+ @staticmethod
705
+ def _retry_delay(error: PostUploadError, attempt: int) -> float:
706
+ retry_after = None
707
+ for key, value in (error.headers or {}).items():
708
+ if key.lower() == "retry-after":
709
+ retry_after = value
710
+ break
711
+ if retry_after is not None:
712
+ try:
713
+ return min(max(float(retry_after), 0.0), 60.0)
714
+ except (TypeError, ValueError):
715
+ pass
716
+ return min(1.0 * (2 ** attempt), 30.0)
717
+
718
+ @staticmethod
719
+ def _sleep(seconds: float) -> None:
720
+ time.sleep(seconds)
721
+
722
+ def upload_photos(
723
+ self,
724
+ user: str,
725
+ platforms: List[str],
726
+ photo_paths: Optional[List[str]] = None,
727
+ title: Optional[str] = None,
728
+ first_comment: Optional[str] = None,
729
+ schedule: Optional[str] = None,
730
+ timezone: Optional[str] = None,
731
+ *,
732
+ photo_urls: Optional[List[str]] = None,
733
+ description: Optional[str] = None,
734
+ add_to_queue: Optional[bool] = None,
735
+ async_upload: Optional[bool] = None,
736
+ request_id: Optional[str] = None,
737
+ idempotency_key: Optional[str] = None,
738
+ platform_options: Optional[Mapping[str, Any]] = None,
739
+ **kwargs: Any,
740
+ ) -> Dict[str, Any]:
741
+ """
742
+ Upload photos (single image or carousel) to one or more platforms.
743
+
744
+ Args:
745
+ user: Profile name.
746
+ platforms: List of platforms.
747
+ photo_paths: Paths to local photo files.
748
+ photo_urls: Public http(s) photo URLs. At most 10 photos in total.
749
+ title: Post title / caption.
750
+
751
+ Other arguments are the same as :meth:`upload_video`.
752
+ """
753
+ paths = list(photo_paths or [])
754
+ urls = list(photo_urls or [])
755
+ if not paths and not urls:
756
+ raise ValueError("upload_photos requires photo_paths or photo_urls")
757
+ if len(paths) + len(urls) > MAX_PHOTOS:
758
+ raise ValueError(f"upload_photos accepts at most {MAX_PHOTOS} photos")
759
+ for p in paths:
760
+ if not os.path.isfile(p):
761
+ raise FileNotFoundError(f"Photo file not found: {p}")
762
+
763
+ fields = self._build_form_fields(
764
+ user, platforms, title, first_comment, schedule, timezone, description,
765
+ add_to_queue, async_upload, request_id, platform_options, kwargs,
766
+ )
767
+ with ExitStack() as stack:
768
+ for p in paths:
769
+ fh = stack.enter_context(open(p, "rb"))
770
+ fields.append(("photos[]", (os.path.basename(p), fh)))
771
+ for u in urls:
772
+ fields.append(("photo_urls[]", (None, str(u))))
773
+ return self._request(
774
+ "POST", "/api/upload_photos", files=fields, headers=self._idem(idempotency_key)
775
+ )
776
+
777
+ def upload_text(
778
+ self,
779
+ user: str,
780
+ platforms: List[str],
781
+ title: Optional[str] = None,
782
+ first_comment: Optional[str] = None,
783
+ schedule: Optional[str] = None,
784
+ timezone: Optional[str] = None,
785
+ *,
786
+ text: Optional[str] = None,
787
+ description: Optional[str] = None,
788
+ add_to_queue: Optional[bool] = None,
789
+ async_upload: Optional[bool] = None,
790
+ request_id: Optional[str] = None,
791
+ idempotency_key: Optional[str] = None,
792
+ platform_options: Optional[Mapping[str, Any]] = None,
793
+ **kwargs: Any,
794
+ ) -> Dict[str, Any]:
795
+ """
796
+ Publish a text-only post.
797
+
798
+ Args:
799
+ user: Profile name.
800
+ platforms: List of platforms.
801
+ title: Text content (kept for 1.0 compatibility; same as ``text``).
802
+ text: Text content. Either ``text`` or ``title`` is required.
803
+
804
+ Other arguments are the same as :meth:`upload_video`.
805
+ """
806
+ content = text if text is not None else title
807
+ if not content:
808
+ raise ValueError("upload_text requires text (or title)")
809
+ fields = self._build_form_fields(
810
+ user, platforms, None, first_comment, schedule, timezone, description,
811
+ add_to_queue, async_upload, request_id, platform_options, kwargs,
812
+ )
813
+ fields.append(("text", (None, content)))
814
+ return self._request(
815
+ "POST", "/api/upload_text", files=fields, headers=self._idem(idempotency_key)
816
+ )
817
+
818
+ def upload_document(
819
+ self,
820
+ user: str,
821
+ document_path: str,
822
+ title: Optional[str] = None,
823
+ *,
824
+ description: Optional[str] = None,
825
+ first_comment: Optional[str] = None,
826
+ visibility: Optional[str] = None,
827
+ target_linkedin_page_id: Optional[str] = None,
828
+ schedule: Optional[str] = None,
829
+ timezone: Optional[str] = None,
830
+ request_id: Optional[str] = None,
831
+ idempotency_key: Optional[str] = None,
832
+ platform_options: Optional[Mapping[str, Any]] = None,
833
+ **kwargs: Any,
834
+ ) -> Dict[str, Any]:
835
+ """
836
+ Publish a LinkedIn document post (PDF, PPT, PPTX, DOC, DOCX; max 100 MB).
837
+
838
+ Args:
839
+ user: Profile name.
840
+ document_path: Path to the document file.
841
+ title: Post title (defaults to the file name on the server).
842
+ visibility: LinkedIn visibility, e.g. ``"PUBLIC"``.
843
+ target_linkedin_page_id: Post as a LinkedIn company page.
844
+ """
845
+ _require(user, "user")
846
+ _require(document_path, "document_path")
847
+ if not os.path.isfile(document_path):
848
+ raise FileNotFoundError(f"Document file not found: {document_path}")
849
+ pairs: List[Tuple[str, Any]] = [
850
+ ("user", user),
851
+ ("title", title or None),
852
+ ("description", description or None),
853
+ ("first_comment", first_comment or None),
854
+ ("visibility", visibility or None),
855
+ ("target_linkedin_page_id", target_linkedin_page_id or None),
856
+ ("schedule", schedule or None),
857
+ ("timezone", timezone or None),
858
+ ("request_id", request_id or None),
859
+ ]
860
+ for source in (platform_options, kwargs):
861
+ pairs.extend((source or {}).items())
862
+ fields = self._fields(pairs)
863
+ with ExitStack() as stack:
864
+ fh = stack.enter_context(open(document_path, "rb"))
865
+ fields.append(("document", (os.path.basename(document_path), fh)))
866
+ return self._request(
867
+ "POST", "/api/upload_document", files=fields, headers=self._idem(idempotency_key)
868
+ )
869
+
870
+ # ── Account / uploads ──
871
+
872
+ def get_me(self) -> Dict[str, Any]:
873
+ """Current account: plan, monthly usage and API key id."""
874
+ return self._request("GET", "/api/me")
875
+
876
+ def get_upload_status(self, upload_id: str) -> Dict[str, Any]:
877
+ """Status of one upload (per-platform results, post ids, errors)."""
878
+ _require(upload_id, "upload_id")
879
+ return self._request("GET", f"/api/upload/{_seg(upload_id)}/status")
880
+
881
+ def get_request_status(self, request_id: str) -> Dict[str, Any]:
882
+ """Look an upload up by your own ``request_id`` (or by upload id)."""
883
+ _require(request_id, "request_id")
884
+ return self._request("GET", "/api/uploadposts/status", params={"request_id": request_id})
885
+
886
+ def list_uploads(
887
+ self,
888
+ limit: Optional[int] = None,
889
+ page: Optional[int] = None,
890
+ status: Optional[str] = None,
891
+ ) -> Dict[str, Any]:
892
+ """Paginated upload history (``limit`` 1-100, ``page`` 1-based, optional ``status`` filter)."""
893
+ return self._request(
894
+ "GET", "/api/uploads", params={"limit": limit, "page": page, "status": status}
895
+ )
896
+
897
+ def get_upload(self, upload_id: str) -> Dict[str, Any]:
898
+ """A single upload record."""
899
+ _require(upload_id, "upload_id")
900
+ return self._request("GET", f"/api/uploads/{_seg(upload_id)}")
901
+
902
+ def delete_upload(self, upload_id: str) -> Dict[str, Any]:
903
+ """Delete an upload record and its stored media (not allowed while processing)."""
904
+ _require(upload_id, "upload_id")
905
+ return self._request("DELETE", f"/api/uploads/{_seg(upload_id)}")
906
+
907
+ def retry_upload(self, upload_id: str) -> Dict[str, Any]:
908
+ """Retry a failed upload."""
909
+ _require(upload_id, "upload_id")
910
+ return self._request("POST", f"/api/uploads/{_seg(upload_id)}/retry")
911
+
912
+ def get_platform_limits(self) -> Dict[str, Any]:
913
+ """Per-platform daily posting limits and current usage."""
914
+ return self._request("GET", "/api/platform-limits")
915
+
916
+ # ── Profiles ──
917
+
918
+ def get_profiles(self) -> Dict[str, Any]:
919
+ """List all managed profiles."""
920
+ return self._request("GET", "/api/profiles")
921
+
922
+ def create_profile(self, name: str) -> Dict[str, Any]:
923
+ """Create a new managed profile."""
924
+ _require(name, "name")
925
+ return self._request("POST", "/api/profiles", json={"name": name})
926
+
927
+ def delete_profile(self, name: str) -> Dict[str, Any]:
928
+ """Delete a managed profile."""
929
+ _require(name, "name")
930
+ return self._request("DELETE", f"/api/profiles/{_seg(name)}")
931
+
932
+ def connect_with_credentials(
933
+ self,
934
+ profile: str,
935
+ platform: str,
936
+ credentials: Optional[Mapping[str, str]] = None,
937
+ **fields: str,
938
+ ) -> Dict[str, Any]:
939
+ """
940
+ Connect a platform that uses credentials instead of OAuth.
941
+
942
+ Pass the platform's fields as a dict, as keyword arguments, or both
943
+ (keyword arguments win)::
944
+
945
+ client.connect_with_credentials("my-brand", "telegram", bot_token="123:AA...", chat_id="@mychannel")
946
+ client.connect_with_credentials("my-brand", "mastodon", {"instance_url": "https://mastodon.social",
947
+ "access_token": "..."})
948
+
949
+ Fields per platform (``?`` = optional; see ``CREDENTIAL_PLATFORMS`` and
950
+ ``CREDENTIAL_OPTIONAL_FIELDS``):
951
+ discord: webhook_url | telegram: bot_token, chat_id | slack: webhook_url |
952
+ mastodon: instance_url, access_token | wordpress: site_url, username, app_password |
953
+ devto: api_key, base_url? | hashnode: access_token, publication_id |
954
+ lemmy: instance_url, username, password, community, totp? |
955
+ nostr: nsec, relays?, blossom_server? |
956
+ whop: api_key + one of experience_id (forum) / channel_id (chat) |
957
+ listmonk: base_url, api_user, api_token, list_ids
958
+
959
+ The server verifies the credentials live before saving them; connecting
960
+ again replaces them.
961
+
962
+ Returns:
963
+ ``{"success": True, "message": ..., "platform_username": ...}``
964
+
965
+ Raises:
966
+ PostUploadError: 400 with ``code`` ``MISSING_FIELD``, ``FIELD_TOO_LONG``
967
+ or ``INVALID_CREDENTIALS`` (``e.body["details"]["field"]`` names the
968
+ field), 404 if the profile does not exist, 502 if the platform
969
+ could not be reached.
970
+ """
971
+ _require(profile, "profile")
972
+ _require(platform, "platform")
973
+ body: Dict[str, Any] = dict(credentials or {})
974
+ body.update(fields)
975
+ if not body:
976
+ raise ValueError("credentials are required")
977
+ return self._request(
978
+ "POST",
979
+ f"/api/profiles/{_seg(profile)}/connect/{_seg(platform)}/credentials",
980
+ json=body,
981
+ )
982
+
983
+ # ── Scheduling ──
984
+
985
+ def get_scheduled_posts(self) -> Dict[str, Any]:
986
+ """All scheduled (not yet published) posts: ``{"scheduled_posts": [...]}``."""
987
+ return self._request("GET", "/api/schedule")
988
+
989
+ def update_scheduled_post(
990
+ self,
991
+ job_id: str,
992
+ scheduled_date: Optional[str] = None,
993
+ timezone: Optional[str] = None,
994
+ title: Optional[str] = None,
995
+ caption: Optional[str] = None,
996
+ ) -> Dict[str, Any]:
997
+ """Reschedule or edit a scheduled post."""
998
+ _require(job_id, "job_id")
999
+ body = {
1000
+ k: v
1001
+ for k, v in {
1002
+ "scheduled_date": scheduled_date,
1003
+ "timezone": timezone,
1004
+ "title": title,
1005
+ "caption": caption,
1006
+ }.items()
1007
+ if v is not None
1008
+ }
1009
+ return self._request("PATCH", f"/api/schedule/{_seg(job_id)}", json=body)
1010
+
1011
+ def cancel_scheduled_post(self, job_id: str) -> Dict[str, Any]:
1012
+ """Cancel a scheduled post."""
1013
+ _require(job_id, "job_id")
1014
+ return self._request("DELETE", f"/api/schedule/{_seg(job_id)}")
1015
+
1016
+ # ── Queue ──
1017
+
1018
+ def get_queue_settings(self, profile: str) -> Dict[str, Any]:
1019
+ """Queue settings (time slots, days, timezone) for a profile."""
1020
+ _require(profile, "profile")
1021
+ return self._request("GET", "/api/queue/settings", params={"profile": profile})
1022
+
1023
+ def update_queue_settings(
1024
+ self,
1025
+ profile: str,
1026
+ slots: Optional[List[Any]] = None,
1027
+ days_of_week: Optional[List[int]] = None,
1028
+ timezone: Optional[str] = None,
1029
+ max_posts_per_slot: Optional[int] = None,
1030
+ ) -> Dict[str, Any]:
1031
+ """Create or update a profile's queue (``slots`` like ``["09:00", "17:30"]``, days 0=Sunday)."""
1032
+ _require(profile, "profile")
1033
+ body: Dict[str, Any] = {"profile_username": profile}
1034
+ if slots is not None:
1035
+ body["slots"] = slots
1036
+ if days_of_week is not None:
1037
+ body["days_of_week"] = days_of_week
1038
+ if timezone is not None:
1039
+ body["timezone"] = timezone
1040
+ if max_posts_per_slot is not None:
1041
+ body["max_posts_per_slot"] = max_posts_per_slot
1042
+ return self._request("POST", "/api/queue/settings", json=body)
1043
+
1044
+ def get_queue_preview(self, profile: str, count: Optional[int] = None) -> Dict[str, Any]:
1045
+ """Upcoming queue slots for a profile."""
1046
+ _require(profile, "profile")
1047
+ return self._request("GET", "/api/queue/preview", params={"profile": profile, "count": count})
1048
+
1049
+ def get_next_queue_slot(self, profile: str) -> Dict[str, Any]:
1050
+ """The next free queue slot for a profile."""
1051
+ _require(profile, "profile")
1052
+ return self._request("GET", "/api/queue/next-slot", params={"profile": profile})
1053
+
1054
+ # ── Platform helpers ──
1055
+
1056
+ def get_facebook_pages(self, profile: str) -> Dict[str, Any]:
1057
+ """Facebook pages for the profile (use the id as ``facebook_page_id``)."""
1058
+ _require(profile, "profile")
1059
+ return self._request("GET", "/api/platforms/facebook/pages", params={"profile": profile})
1060
+
1061
+ def get_linkedin_pages(self, profile: str) -> Dict[str, Any]:
1062
+ """LinkedIn company pages (use the id as ``target_linkedin_page_id``)."""
1063
+ _require(profile, "profile")
1064
+ return self._request("GET", "/api/platforms/linkedin/pages", params={"profile": profile})
1065
+
1066
+ def get_pinterest_boards(self, profile: str) -> Dict[str, Any]:
1067
+ """Pinterest boards (use the id as ``pinterest_board_id``)."""
1068
+ _require(profile, "profile")
1069
+ return self._request("GET", "/api/platforms/pinterest/boards", params={"profile": profile})
1070
+
1071
+ def get_google_business_locations(self, profile: str) -> Dict[str, Any]:
1072
+ """Google Business Profile locations (use the id as ``gbp_location_id``)."""
1073
+ _require(profile, "profile")
1074
+ return self._request(
1075
+ "GET", "/api/platforms/google-business/locations", params={"profile": profile}
1076
+ )
1077
+
1078
+ # ── Analytics ──
1079
+
1080
+ def get_analytics(self, range: str = "30d") -> Dict[str, Any]:
1081
+ """Account analytics overview (``range`` such as ``"7d"``, ``"30d"``, ``"90d"``)."""
1082
+ return self._request("GET", "/api/analytics/overview", params={"range": range})
1083
+
1084
+ def get_live_analytics(
1085
+ self, profile: str, platforms: Optional[Sequence[str]] = None
1086
+ ) -> Dict[str, Any]:
1087
+ """Live follower / engagement stats pulled from the platforms for a profile."""
1088
+ _require(profile, "profile")
1089
+ return self._request(
1090
+ "GET",
1091
+ f"/api/analytics/live/{_seg(profile)}",
1092
+ params={"platforms": ",".join(platforms) if platforms else None},
1093
+ )
1094
+
1095
+ def get_post_analytics(self, upload_id: str, platform: Optional[str] = None) -> Dict[str, Any]:
1096
+ """Per-post analytics for an upload (optionally for one platform)."""
1097
+ _require(upload_id, "upload_id")
1098
+ return self._request(
1099
+ "GET", f"/api/analytics/post/{_seg(upload_id)}", params={"platform": platform}
1100
+ )
1101
+
1102
+ def get_total_impressions(
1103
+ self,
1104
+ profile: str,
1105
+ platform: Optional[str] = None,
1106
+ period: Optional[str] = None,
1107
+ start_date: Optional[str] = None,
1108
+ end_date: Optional[str] = None,
1109
+ ) -> Dict[str, Any]:
1110
+ """Total impressions for a profile."""
1111
+ _require(profile, "profile")
1112
+ return self._request(
1113
+ "GET",
1114
+ f"/api/analytics/total-impressions/{_seg(profile)}",
1115
+ params={
1116
+ "platform": platform,
1117
+ "period": period,
1118
+ "start_date": start_date,
1119
+ "end_date": end_date,
1120
+ },
1121
+ )
1122
+
1123
+ # ── FFmpeg ──
1124
+
1125
+ def get_ffmpeg_usage(self) -> Dict[str, Any]:
1126
+ """FFmpeg processing minutes used / remaining this month."""
1127
+ return self._request("GET", "/api/ffmpeg/usage")
1128
+
1129
+ def list_ffmpeg_jobs(self) -> Dict[str, Any]:
1130
+ """Recent FFmpeg jobs (latest 50): ``{"jobs": [...]}``."""
1131
+ return self._request("GET", "/api/ffmpeg/jobs")
1132
+
1133
+ def get_ffmpeg_job(self, job_id: str) -> Dict[str, Any]:
1134
+ """A single FFmpeg job."""
1135
+ _require(job_id, "job_id")
1136
+ return self._request("GET", f"/api/ffmpeg/jobs/{_seg(job_id)}")
1137
+
1138
+ # ── Plans ──
1139
+
1140
+ def get_plans(self) -> Dict[str, Any]:
1141
+ """List available subscription plans."""
1142
+ return self._request("GET", "/api/plans")
1143
+
1144
+
1145
+ #: Deprecated aliases (the SDK was called IndReelForge / InReelForge before 1.2.0).
1146
+ IndReelForge = PostUpload
1147
+ InReelForge = PostUpload