Metadata-Version: 2.5
Name: godam-sdk
Version: 0.3.0
Summary: Upload videos to GoDAM and get their embed URLs, with only an organization licence key.
Project-URL: Homepage, https://github.com/rtCamp/godam-sdk/tree/main/python
Project-URL: Issues, https://github.com/rtCamp/godam-sdk/issues
Project-URL: Changelog, https://github.com/rtCamp/godam-sdk/blob/main/python/CHANGELOG.md
Author-email: rtCamp <contact@rtcamp.com>
License-Expression: GPL-2.0-or-later
License-File: LICENSE
Keywords: dash,godam,hls,sdk,transcoding,upload,video
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Multimedia :: Video
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx<1,>=0.27
Description-Content-Type: text/markdown

# godam-sdk (Python)

Upload videos to [GoDAM](https://godam.io) and get their embed URLs, using only your organization licence key.

> Proof of concept (0.x). The API may change before 1.0. The `godam` command lives in the JavaScript package: `npx @rtcamp/godam-sdk`.

## Requirements

- Python 3.10 or later.
- A GoDAM organization licence key. Keep it on a server or your own machine: never in a browser or a public repo.

## Install

```bash
pip install godam-sdk
```

## Quick start

```python
import os

from godam import GodamClient

with GodamClient(os.environ["GODAM_API_KEY"], organization=os.environ.get("GODAM_ORGANIZATION")) as godam:
    video = godam.upload("intro.mp4", title="Intro", public=True)
    ready = godam.wait_until_ready(video.id)

print(ready.id, ready.hls_url, ready.thumbnail_url, ready.ai_summary)
```

Set `organization` (the licence's organization name) whenever the licence key's owner may belong to more than one organization: without it an upload can land in another organization.

Into a GoDAM folder by path (missing folders are created), one video or many:

```python
godam.upload("labeljet-210.mp4", title="LabelJet 210", folder="Vidyard/Products/Labelers")
```

Many videos, a few at a time, with captions. A failed video never stops the rest:

```python
from godam import CaptionSpec, UploadItem

items = [
    UploadItem(
        "videos/29-profile.mp4",
        title="Profile and invitations",
        public=True,
        ref="vidyard-id-1",
        captions=(CaptionSpec(language="en", file="captions/29.en.vtt"),),
    ),
    UploadItem("videos/30-server.mp4", title="Create a server", public=True, ref="vidyard-id-2"),
]

with GodamClient(os.environ["GODAM_API_KEY"]) as godam:
    for r in godam.upload_many(items, concurrency=4):
        print(r.item.ref, r.file.id if r.file else None, r.error)
```

## API

| Method | Returns |
|---|---|
| `GodamClient(api_key, *, organization=None, api_url=..., upload_url=..., allow_insecure_urls=False, http_client=None, retries=3, retry_delay=1.0, timeout=60.0, upload_timeout=None, app_info=None, logger=None)` | A client. Raises `MISSING_API_KEY` without a key. Use it with `with`, or call `close()`. Set `organization` (the licence's organization name in GoDAM Central) when the key's owner belongs to several organizations; without it uploads go to the owner's default organization. It travels in an HTTP header, so it must be printable ASCII (`Acme Media` is fine, `Müller Medien` and `日本` are not) or the constructor raises `INVALID_ORGANIZATION`. `timeout` limits each Central request, from sending it to reading the whole answer (default 60 s), `upload_timeout` each file upload (default: no total limit). `app_info` (e.g. `"acme-import/1.0"`) is added to the User-Agent header, so it must be printable ASCII or the constructor raises `INVALID_OPTIONS`. `api_url` and `upload_url` must start with `https://`, because the key and the upload token travel to them; `http://` is accepted for `localhost`, `127.0.0.1` and `[::1]`, or for any host with `allow_insecure_urls=True`, and the constructor raises `INVALID_OPTIONS` otherwise. A redirect is never followed, not even by a `http_client` set to follow them |
| `upload(path, *, title=None, public=None, folder=None, file_name=None, content_type=None, timeout=None, upload_timeout=None, on_created=None, cancel=None)` | The new video (`MediaFile`), usually `Queued`. A `title` that is empty or only spaces counts as not given, so the video keeps the title Central set from the file name. A `title` over 500 characters (after trimming) raises `INVALID_TITLE` before anything is uploaded. A `folder` (a path such as `Vidyard/Products/Labelers`, created if missing) puts the video there instead of in the root; one GoDAM would refuse raises `INVALID_OPTIONS` before anything is uploaded (see [Folders](#folders)). A `content_type` that is not `type/subtype` (letters, digits and the punctuation of an HTTP token; no parameters such as `; codecs=`) raises `INVALID_OPTIONS`. If a step fails after the file was created, the raised `GodamError` has the new video's `video_id`. `on_created(video_id)` is called with that id as soon as the upload service has created the video, before the title is set and the video is read back: record the id there. If it raises, the upload ends with `CALLBACK_FAILED`, which carries the id |
| `get_file(video_id, *, timeout=None, cancel=None)` | The video's current state and URLs |
| `wait_until_ready(video_id, *, interval=5, timeout=900, on_status=None, ai_summary=True, ai_timeout=180, cancel=None)` | The video once `Transcoded`, then with its AI summary (up to `ai_timeout` seconds; `ai_summary=False` skips). A poll that fails for a passing reason (a network error, a timeout, an HTTP 408, 429 or 5xx, e.g. a Central restart) does not end the wait: it polls again until `timeout`, then raises `TIMEOUT` (once `Transcoded`, it returns the last state it read after the AI deadline instead). Other errors, such as an unknown video or a cancel, are raised at once. An `interval`, `timeout` or `ai_timeout` that is not a finite number from 0, an `on_status` that is not callable or an `ai_summary` that is not a bool raises `INVALID_OPTIONS` before the first poll (`upload_many` checks its wait options the same way, and also refuses names it does not know) |
| `add_caption(video_id, *, language, file=None, content=None, label=None, kind="subtitles", is_default=False, format=None, timeout=None, cancel=None)` | Every caption on the video after adding a VTT or SRT track. The video must be transcoded; label defaults to the language; 20 tracks at most |
| `list_captions(video_id, *, timeout=None, cancel=None)` | Every caption track on the video (`Caption`) |
| `upload_many(items, *, concurrency=4, wait=True, on_start=None, on_created=None, on_uploaded=None, on_result=None, cancel=None, **wait_options)` | One `UploadResult(item, file, captions, error, video_id, callback_error)` per `UploadItem`, in order. At most `concurrency` (default 4, a number from 1) in progress; each item uploads, waits, then gets its `captions`; a failed item never stops the rest. `item.ref` is carried through, e.g. a Vidyard ID. An `UploadItem` also takes the options of `upload()` (`folder`, `file_name`, `content_type`, `timeout`, `upload_timeout`, `on_created`, `cancel`): give a `content_type` for a file whose extension the SDK does not know (`.mpg`, `.wmv`, `.ts`), or it fails as `UNKNOWN_FILE_TYPE`; a `CaptionSpec` takes `timeout` and `cancel`. `video_id` is set whenever a video was created, even if a later step failed. `on_start(item)` is called as each item starts. `on_created(item, video_id)` is called the moment the upload service has created a video, before its title is set: save the id there. `on_uploaded(item, file)` is called once the upload has returned, before the wait. A callback of yours that raises never ends the batch (the `on_status` wait option included): the exception is kept on that item's result as `callback_error` and the item carries on, so check `callback_error` after the run. Callbacks are called one at a time, so they need no locking of their own. A bad `concurrency`, or unknown or badly typed wait options, or a `cancel` that is not a `threading.Event`, raise `INVALID_OPTIONS` before the first upload. The own `cancel` of an `UploadItem` or of one of its `CaptionSpec`s that is not one fails that item alone as `INVALID_OPTIONS`, before its upload (so no video is created), like any other bad option of one item. After the first `WRONG_ORGANIZATION`, or the first `UPLOAD_FAILED` with `failure_reason` `storage_limit` or `license`, no new item is started: videos in progress finish, and the items not yet started come back with that error and are not uploaded. Setting `cancel` stops the batch the same way, with `ABORTED`: see below. The same function is `godam.upload_many(client, items, ...)`, which takes any client that has `upload`, `wait_until_ready` and `add_caption` |

`MediaFile` fields: `id`, `title`, `public`, `status`, `failure_reason`, `duration_seconds`, `width`, `height`, `hls_url`, `dash_url`, `mp4_url`, `thumbnail_url`, `ai_summary`, and `raw` (everything GoDAM sent).

## Folders

`folder` puts a video in a GoDAM folder by path. It is an argument of `upload()` and a field of `UploadItem`:

```python
godam.upload("labeljet-210.mp4", title="LabelJet 210", folder="Vidyard/Products/Labelers")
```

GoDAM creates the folders that are missing, under the organization's root. The path is read the way GoDAM reads it: split at `/`, each level trimmed, empty levels dropped (` Vidyard / Products//Labelers/ ` is `Vidyard/Products/Labelers`), and a path with nothing in it (or `None`) counts as not given (no folder is sent). Anything GoDAM would refuse raises `INVALID_OPTIONS` before anything is uploaded (an `UploadItem` with such a folder fails alone, and nothing is sent for it): not a string, over 1000 characters as given, more than 10 levels, a level over 140 characters, a level that is `.` or `..`, or a level with a control character below U+0020, an unpaired surrogate, or one of `\ : * ? " < > |`. The JavaScript SDK applies the same rules. The folder travels to the upload service as the `godam_folder` form field.

**It needs two server changes.** A folder takes effect only once [rtCamp/godam-core#1923](https://github.com/rtCamp/godam-core/pull/1923) (GoDAM Central) and [rtCamp/godam-upload#82](https://github.com/rtCamp/godam-upload/pull/82) (the upload service) are deployed. Until both are, an upload with a folder lands in the organization's root: the upload service ignores a form field it does not know, so nothing fails, and the SDK does not check where the video went.

## Errors

Every failure of a call to GoDAM is a `GodamError` with a `code`, a `message` and, for HTTP errors, `http_status`. Problems with your own input are not wrapped: a file that is missing or unreadable raises `OSError` (`FileNotFoundError` and the like), a caption file that is not UTF-8 raises `UnicodeDecodeError`, and a malformed `api_url` or `upload_url` that gets past the constructor's check can raise `httpx.InvalidURL`. When the failure came after the video was created (the upload worked, a later step did not), `video_id` holds its id; keep it, because uploading the file again would make a duplicate. When the upload itself ended without a clear answer, `video_id` is `None` although a video may exist: see `UPLOAD_OUTCOME_UNKNOWN`.

| `code` | When |
|---|---|
| `MISSING_API_KEY` | No key given to the client |
| `UNKNOWN_FILE_TYPE` | The file's type can't be told from its extension; pass `content_type` |
| `INVALID_TITLE` | The title is over 500 characters (after trimming) or not a string; nothing was uploaded |
| `INVALID_ORGANIZATION` | `organization` has a character that is not printable ASCII (a letter such as `ü`, a line break, a control character), or is not a string (raised by the constructor) |
| `INVALID_OPTIONS` | The client got an `api_url` or `upload_url` that is not https:// (and not a local http:// one, or `allow_insecure_urls` is not set), or an `app_info` that is not printable ASCII, or an upload `content_type` that is not `type/subtype` (an `UploadItem` with one fails alone), or a `retries` (a whole number), `retry_delay`, `timeout` or `upload_timeout` that is not a finite number from 0 (raised by the constructor, or by a call given such a `timeout` or `upload_timeout`); or `upload_many` got a `concurrency` that is not a number from 1, or unknown or badly typed wait options, or a `cancel` that is not a `threading.Event` (that of an item or caption fails only its item, before its upload); or an upload got a `folder` GoDAM would refuse (see [Folders](#folders)). Nothing was uploaded |
| `UPLOAD_TOKEN_FAILED` | Central returned no upload token |
| `UPLOAD_FAILED` | The upload service refused the file. When it says why, `failure_reason` holds the reason: `storage_limit` or `license` today (otherwise `None`). A 400 also counts as a refusal when it carries Central's own text (the `message` of the answer, which then becomes the error's message) or says the upload token was refused (`Invalid user token passed`): the service stores nothing in either case |
| `UPLOAD_OUTCOME_UNKNOWN` | The file upload ended without a clear answer: a 5xx, a timeout or a dropped connection after the file was sent, a cancel after the whole file was sent (the `ABORTED` error is its `__cause__`), or a 400 that is not known to be a refusal: no `failure_reason`, no Central text in `message`, and not a refused upload token (the upload service sends one 400 both for a refusal and for a Central failure that kept the file). A failure before anything was sent, such as a connection that could not be made or a redirect, is not this: it is `NETWORK_ERROR` (or `REQUEST_TIMEOUT` for a connect timeout). The video may or may not exist and `video_id` is `None`: look in the library before uploading the file again. `upload_many` carries on with the other items |
| `CALLBACK_FAILED` | Your `on_created` callback threw while a single `upload()` was running. The video exists, so `video_id` holds its id and `__cause__` your error, but the upload stops there: the title is not set and the video is not read back. (In a batch an error of yours never ends the item: it is kept on the result, see `upload_many`) |
| `NOT_FOUND` | Central's answer held no video. An unknown or deleted ID usually comes back as Central's own `FileNotFound` instead (see the last row) |
| `INVALID_CAPTION` | No language, no file or content (or both), or a caption file that isn't .vtt or .srt |
| `NETWORK_ERROR` | No answer after the retries, the connection dropped while the answer was coming in, the answer could not be decoded (a corrupt compressed body), or the server answered with a redirect (never followed, so the key, the token and the file go nowhere else; it is not retried either). The message names the reason and `__cause__` holds the original `httpx` error |
| `REQUEST_TIMEOUT` | A request, answer included, did not finish within its time limit, could not connect within 10 s, or stayed silent for 300 s, after the retries |
| `ABORTED` | The call's `cancel` was set. A cancel after the whole file of an `upload()` was sent ends as `UPLOAD_OUTCOME_UNKNOWN` instead. In `upload_many` it also marks the items that were not started when the batch's `cancel` was set |
| `WRONG_ORGANIZATION` | The upload went into another organization of the key's owner; set the organization (`organization` on the client). In `upload_many` it also marks the items that were not started |
| `TRANSCODE_FAILED` | GoDAM could not transcode the video (`message` holds the reason) |
| `TIMEOUT` | Still not transcoded after `timeout` seconds, or the polls kept failing (network, 408, 429, 5xx) until then |
| `API_ERROR` | Central answered with an HTTP error and no `error_type`. A licence key Central does not know ends here, with `http_status` 417 |
| Central's `error_type` | Passed through for the calls to Central (everything except the file upload), e.g. `FileNotFound` for an unknown or deleted video ID, or `NoActiveSubscription`. The upload service sends text instead, plus `failure_reason` where it has one |

```python
from godam import GodamError

try:
    godam.upload("intro.mp4")
except GodamError as e:
    if e.code == "UPLOAD_OUTCOME_UNKNOWN":
        ...  # The video may exist: look in the library before uploading intro.mp4 again.
    elif e.code == "API_ERROR" and e.http_status == 417:
        ...  # Central did not accept the licence key.
```

## Timeouts, cancelling and debugging

`timeout` limits each Central request (default 60 s) and `upload_timeout` each file upload (default none), both from sending the request to reading the whole answer, so a body that trickles in is cut off too; `0` means no limit. A large video can take as long as it needs, but a connection that cannot be made within 10 s, or stays silent for 300 s, ends as `REQUEST_TIMEOUT` instead of hanging (the same in both SDKs: Node's fetch gives up on a connection after 10 s, and the Python SDK does too). `upload`, `get_file`, `add_caption` and `list_captions` also take `timeout=` for one call, which limits that call's Central requests only: the file upload inside `upload()` follows `upload_timeout` (the client's, or the `upload_timeout=` passed to that call), so a short `timeout` cannot cut off a video that is being created. A `timeout` or `upload_timeout` that is not a finite number from 0 raises `INVALID_OPTIONS` before anything is sent.

With a total `timeout` (the default is 60 s) or a `cancel`, each request runs on a helper thread that the calling thread waits for, because `httpx` has no total time limit and cannot interrupt a call in flight. A `http_client` of your own whose transport or hooks use thread-locals therefore sees another thread than yours; with `timeout=0` and no `cancel`, a request stays on the calling thread. A request that times out or is cancelled is given up on, not stopped: a file being sent stops at its next chunk, and any other request goes on until its idle limit ends it. That limit is a limit on silence (at most 300 s) that starts again on every byte, so a server that keeps trickling data can hold the helper thread longer.

Every method that calls GoDAM takes `cancel`, a `threading.Event`, for that call: set it from any thread, a signal handler or a timer, and the call stops at once with `ABORTED` and is not retried. It also stops the wait between retries and between the polls of `wait_until_ready`, and a file being sent stops going out and its connection closes. A request already sent is given up on without waiting for its answer, though the server may still finish it. A cancel while the file is still being read leaves no video and is `ABORTED`; a cancel after the whole file has been sent ends the upload as `UPLOAD_OUTCOME_UNKNOWN` instead (the cancel is its `__cause__`), because the service has the file and may still create the video, so look in the library before uploading it again; once the video exists, the error carries its `video_id`.

```python
import signal
import threading

cancel = threading.Event()
signal.signal(signal.SIGINT, lambda *_: cancel.set())  # Ctrl+C cancels instead of killing the run

with GodamClient(os.environ["GODAM_API_KEY"]) as godam:
    results = godam.upload_many(items, cancel=cancel)  # items not yet started come back with ABORTED
```

For `upload_many`, `cancel` cancels the batch: items not yet started are not uploaded (they come back with `ABORTED` and an `on_result` call, but no `on_start`), and items in progress are cancelled at their current call, a video that was already created keeping its `video_id`. It cancels the waits too, so the wait options take no `cancel`. An `UploadItem` or a `CaptionSpec` can carry its own `cancel`, which cancels only that item, at whatever step it is in. Ctrl+C (a `KeyboardInterrupt` in the thread that called `upload_many`) cancels the items in progress the same way, with or without a `cancel` of yours, so it reaches you at once instead of after their waits.

Set `GODAM_LOG=debug` (any letter case, read when the client is created) to print one line per request to stderr (call, status, time, retries), or pass `logger=` a function that receives each line, or attach a handler to the `godam` logger. Bodies and the licence key are never logged. A `logger` that raises never fails a call: its error is ignored.

## Samples

- [`examples/upload.py`](examples/upload.py): one video, waiting until it's ready.
- [`examples/batch_import.py`](examples/batch_import.py): a manifest of many videos with captions, 4 at a time, recording each one's ID and skipping finished ones on a re-run.

## How it works

`upload()` swaps the licence key for an upload token (it does not expire), sends the file to the upload service with that token, then sets title and public. `wait_until_ready()` reads the video every 5 seconds. Requests that fail on the network, time out, or get a 408, 429 or 5xx are retried 3 times with a doubling delay (±25% jitter, at most 30 s, or the server's `Retry-After` when it is whole seconds, at most 60 s); the file upload itself is retried only after a 429 or when the connection could not be made at all (nothing was sent), since a retry after a server error could create a duplicate video, and a failure after the file was sent is reported as `UPLOAD_OUTCOME_UNKNOWN`. These are the same GoDAM calls the JavaScript SDK makes, all live today; when the single-call upload route ships, only `upload()` changes. 0.3.0 stays on this token flow; `folder` is a field of the file upload, see [Folders](#folders). `organization`, `INVALID_ORGANIZATION` and `WRONG_ORGANIZATION` go away when the SDK moves to the licence-key route.

## Development

```bash
uv sync              # creates .venv with the dev tools
uv run pytest        # unit tests, no network
uv run ruff check . && uv run ruff format --check . && uv run mypy
uv build             # sdist and wheel in dist/
```

Releases: bump `version` in `pyproject.toml` and `src/godam/_version.py`, add the entry to `CHANGELOG.md`, then publish a GitHub release tagged `python-v<version>` (e.g. `python-v0.3.0`). The release workflow at the repo root publishes to PyPI with trusted publishing.

## License

GPL-2.0-or-later. See [LICENSE](LICENSE).
