Metadata-Version: 2.5
Name: slike
Version: 0.3.1
Summary: Python SDK for publishing media on Slike platform
Project-URL: Homepage, https://code.sli.ke/python/slike-media-package
Project-URL: Documentation, https://code.sli.ke/python/slike-media-package#readme
Project-URL: Repository, https://code.sli.ke/python/slike-media-package
Project-URL: Issues, https://code.sli.ke/python/slike-media-package/issues
Author: Arpit Kumar
License-Expression: MIT
License-File: LICENSE
Keywords: api,media,publishing,sdk,slike
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.7
Requires-Dist: requests>=2.25.0
Requires-Dist: tomli>=1.2; python_version < '3.11'
Description-Content-Type: text/markdown

# slike

Python and TypeScript/JavaScript SDK for the [Slike](https://sli.ke) platform.

Supports **file upload** (chunked, resumable), **editor-video registration**, **publish-by-URL** (YouTube, Google Drive, direct links), **premieres**, **media listing** (search, filters, paging), **media status checks**, **metadata retrieval**, **agency listing**, **media update**, **upload cancellation**, **CMS user creation**, and **team-by-host lookup**. Sign in with a **Slike token** or a **Denmark JWT**.

- Python requires **3.7+**
- TypeScript/JS requires **Node 18+** (or modern browser with Fetch API)

---

## Feature availability

What each SDK supports, and the method to call. ✅ = available, — = not available.

| Feature | JS | Python |
|---|---|---|
| Slike token login | ✅ `new SlikeMedia({ token })` + `initialize()` | ✅ `SlikeMedia(token=…)` + `initialize()` |
| Denmark JWT login | ✅ `new SlikeMedia({ denmarkToken })` + `initialize()` | ✅ `SlikeMedia(denmark_token=…)` + `initialize()` |
| List media (search, filters, paging) | ✅ `listMedia` | ✅ `list_media` |
| Media status | ✅ `getStatus` | ✅ `get_status` |
| Update media | ✅ `updateMedia` | ✅ `update_media` |
| Cancel upload by media ID | ✅ `cancelUpload` | ✅ `cancel_upload` |
| Cancel the running upload | ✅ `handle.cancel()` / `AbortSignal` | ✅ `cancel()` |
| Publish by URL | ✅ `publishMedia` | ✅ `publish_media` |
| Upload a file (wait until done) | ✅ `uploadMedia` | ✅ `register_media(file_path=…)` |
| Upload a file in the background | ✅ `uploadMediaBackground` | ✅ `register_media(file_path=…, on_upload_complete=…)` |
| Register and upload as separate steps | ✅ `registerMedia` + `uploadChunks` | — |
| Create media from video editor settings | — | ✅ `register_media(editor_settings=…)` |
| Form metadata (teams, languages, categories) | ✅ `getRequiredMetadata` | ✅ `get_required_metadata` |
| Agency list / search | ✅ `getAgencyList` | ✅ `get_agency_list` |
| Premiere (scheduled live event, like CMS Create → Premiere) | ✅ `createPremiere` | ✅ `create_premiere` |
| Current user's profile | ✅ `getCurrentUser` | — |
| Create CMS user | ✅ `createUser` | ✅ `create_user` |
| Teams by host | ✅ `getTeamsByHost` | ✅ `get_teams_by_host` |
| Command-line tool (upload, publish, status, list, update, cancel, premiere) | — | ✅ `slike-upload` |

JS methods are camelCase and take an options object; Python methods are snake_case and take keyword arguments. Results have the same fields (`isReady` in JS is `is_ready` in Python).

---

## Install

**Python** ([pypi.org/project/slike](https://pypi.org/project/slike/))
```bash
pip3 install slike
```

**JavaScript / TypeScript** (browser, from the Slike CDN; not published on npm)
```html
<script src="https://app.sli.ke/slike-upload-sdk.js"></script>      <!-- production -->
<script src="https://app-dev.sli.ke/slike-upload-sdk.js"></script>  <!-- development -->
```

---

## Python SDK

### Quick start

```python
from slike import SlikeMedia

client = SlikeMedia(token="your-slike-token", environment="prod")
client.initialize()   # validates token; raises SlikeAPIError on failure

# Upload a local file (blocking)
result = client.register_media(
    file_path="/path/to/video.mp4",
    title="My Video",
    description="Description",
    on_progress=lambda done, total: print(f"{done}/{total} chunks"),
)
print("Media ID:", result["id"])
```

### Denmark JWT auth

```python
client = SlikeMedia(
    denmark_token="<jwt>",
    service="slike",        # optional, default: "slike"
    environment="prod",
)
client.initialize()         # exchanges JWT for a Slike session token
print(client.token)         # resolved Slike session token
```

Provide exactly one of `token` or `denmark_token`.

---

### Methods

#### `initialize()`

Validates credentials. Must be called once before any other method.

```python
client.initialize()
```

---

#### `register_media`

Register media on Slike. Provide exactly one of `file_path` (chunked upload) or `editor_settings` (editor-generated video — no bytes uploaded).

**Blocking file upload** (waits for all chunks to finish):

```python
result = client.register_media(
    file_path="/path/to/video.mp4",
    title="My Video",
    description="Description",
    asset_type="video",                          # optional, default: "video"
    tags=["news", "sports"],                     # optional
    preset_config={"meta": "", "social": ""},    # optional
    team="team-id",                              # optional, team ID from get_required_metadata
    business="biz-id",                           # optional, business ID paired with team
    agency="agency-id",                          # optional, agency ID from get_agency_list
    on_progress=lambda done, total: print(f"{done}/{total} chunks"),
)
print("Media ID:", result["id"])
```

Pass `team` and its paired `business` together — both come from the same team object returned by `get_required_metadata`:

```python
meta = client.get_required_metadata()
selected_team = meta["default_team"]["team"]   # or whichever team the user picks

result = client.register_media(
    file_path="/path/to/video.mp4",
    title="My Video",
    description="Description",
    team=selected_team["value"],
    business=selected_team["business"],
)
```

**Non-blocking file upload** (upload runs in a background thread; callback fires the moment chunks finish):

```python
def on_done(res, err):
    if err:
        print("Upload failed:", err)
    else:
        print("Upload complete! ID:", res["id"])

result = client.register_media(
    file_path="/path/to/video.mp4",
    title="My Video",
    description="Description",
    on_upload_complete=on_done,   # fires immediately when chunks finish
)
# result["id"] is available right away — no need to wait
print("Registered, ID:", result["id"])
```

**Editor video** (no file — server renders from spec):

```python
client.register_media(
    title="My Editor Video",
    description="Description",
    tags=["news", "sports"],
    editor_settings={
        "source_width": 1080,
        "source_height": 1920,
        "clips": [...],
        "background_music": {...},
    },
)
```

---

#### `get_status`

Get basic media details and processing readiness by media ID.

```python
status = client.get_status("media_id_here")

print(status["media_id"])  # media ID
print(status["title"])     # media title
print(status["desc"])      # media description
print(status["tags"])      # list of tags
print(status["status"])    # raw status code
print(status["state"])     # raw state code
print(status["is_ready"])  # True when status==5 and state==10
print(status["msg"])       # "Media is ready." or "Media is not ready yet."
```

Media is ready when `is_ready` is `True` (`status == 5` and `state == 10`).

---

#### `cancel`

Cancel **all** in-progress background uploads on this client (local abort only).

```python
import threading

result = client.register_media(
    file_path="/path/to/video.mp4",
    title="My Video",
    description="Description",
    on_upload_complete=lambda res, err: print("cancelled" if isinstance(err, CancelError) else err or res["id"]),
)

# Cancel from a UI button handler or another thread:
threading.Timer(5.0, client.cancel).start()
```

`cancel()` is a no-op if nothing is in progress. All background uploads on the client are stopped; retry backoff sleeps are woken immediately.

---

#### `get_required_metadata`

Fetch all dropdown options for building a media-update form. Returns static constants at the top level, per-team filtered languages and categories, and a flat agency list.

```python
meta = client.get_required_metadata()

# Static constants (from SDK)
print(meta["content_types"])    # [{"value": "package", "label": "Package"}, ...]
print(meta["production_types"]) # [{"value": "In House Originals", "label": "In House Originals"}, ...]
print(meta["content_ratings"])  # [{"value": "1", "label": "Made for Kids"}, ...]
print(meta["media_states"])     # [{"value": 0, "label": "Draft"}, ...]

# Agencies (flat list sorted by recent activity)
for agency in meta["agencies"]:
    print(agency["id"], agency["name"])

# Default team (pre-select on load); None if no teams exist
print(meta["default_team"]["team"])       # {"value": "team-id-1", "label": "Team 1", "is_default": True, "business": "biz-id"}
print(meta["default_team"]["languages"])  # [{"value": "Language 1", "label": "Language 1"}, ...]
print(meta["default_team"]["categories"]) # [{"value": "Category 1", "label": "Category 1", "subcategories": [...]}, ...]

# All teams (populate team switcher)
for entry in meta["teams"]:
    print(entry["team"])        # {"value": ..., "label": ..., "is_default": ..., "business": ...}
    print(entry["languages"])   # languages allowed for this team
    print(entry["categories"])  # categories allowed for this team
```

---

#### `get_agency_list`

List active agencies, optionally filtered by name. Returns up to 50 results sorted by recent activity.

```python
# All active agencies
result = client.get_agency_list()
print(result["count"])   # total count
for a in result["list"]:
    print(a["id"], a["name"])

# Search by name
result = client.get_agency_list(name="toi")
```

| Parameter | Type | Description |
|---|---|---|
| `name` | `str` | Optional name filter |

---

#### `list_media`

List your media with paging, filters and search. Newest first by default.

```python
import datetime

result = client.list_media(page=1, size=20)
print(result["count"], result["has_more"])
for m in result["list"]:
    print(m["id"], m["title"], m["is_ready"])

# Filter + search (any filter also accepts a list, e.g. status=[1, 5])
result = client.list_media(
    search="cricket",
    status=5,
    asset_type="video",
    team="team-id",
    created_from=datetime.datetime(2026, 10, 1),   # datetime or epoch milliseconds
    include=["ctbydata", "teamdata"],              # join related data
)

# Anything else: a raw CMS query, deep-merged over the arguments above
result = client.list_media(status=5, query={"must": {"lang": "english"}, "must_not": {"islive": 1}})
```

| Parameter | Type | Default | Description |
|---|---|---|---|
| `page` / `size` | `int` | `1` / `20` | Paging; `size` is capped at 500 |
| `from_` | `int` | — | Explicit offset; overrides `page` |
| `search` | `str` | — | Search by media ID, title, tags or description (same fields and ranking as the CMS search; an exact ID match ranks first) |
| `status`, `state`, `media_status`, `is_live`, `is_short` | `int` or `list[int]` | — | `must` filters (`islive`, `is_short` on the wire) |
| `asset_type`, `team`, `business`, `agency`, `lang`, `category`, `source` | `str` or `list[str]` | — | `must` filters |
| `created_from` / `created_to` | `datetime` or `int` (epoch ms) | — | Created-at range |
| `sort` | `dict` | `{"ct": "desc"}` | e.g. `{"mt": "asc"}` |
| `include` | `list[str]` | — | Related data (`foreign_keys`): `ctbydata`, `teamdata`, `agencydata`, … |
| `fields` | `list[str]` | — | Only return these fields |
| `include_archived` | `bool` | `False` | Include archived media |
| `query` | `dict` | — | Raw CMS query, deep-merged last |

Returns `{"list", "count", "page", "size", "has_more"}`; each item is the CMS media dict plus `is_ready`.
The CMS ignores filter keys it doesn't allow, and results are scoped to the teams your token can access.

---

#### `update_media`

Update metadata fields on an existing media item. All fields except `id` are optional — only provided fields are sent.

```python
result = client.update_media(
    id="media-id-here",
    title="Updated Title",
    desc="Updated description",
    tags=["news", "sports"],
    lang="English",
    category="News",
    subcategory="Politics",
    ctype="story",
    production_type="In House Originals",
    mfk=2,                  # content rating: 1=Kids, 2=General, 3=18+
    media_state=1,           # 0=Draft, 1=Active
    expiry="2026-12-31",
    youtube_id="dQw4w9WgXcQ",
    parentid="parent-id",
)
print(result)  # dict with updated media fields
```

| Parameter | Type | Description |
|---|---|---|
| `id` | `str` | **Required.** Media ID to update |
| `title` | `str` | **Required.** Media title |
| `title_url` | `str` | URL-friendly title slug |
| `desc` | `str` | Description |
| `tags` | `list[str]` | Tags |
| `agency_credits` | `list[str]` | Agency credits |
| `ctype` | `str` | Content type (see `CONTENT_TYPES`) |
| `production_type` | `str` | Production type (see `PRODUCTION_TYPES`) |
| `lang` | `str` | Language name |
| `category` | `str` | Category name |
| `subcategory` | `str` | Sub-category name |
| `mfk` | `int` | Content rating: `1`=Kids, `2`=General, `3`=18+ |
| `images` | `dict` | Image metadata |
| `expiry` | `str` | Expiry date string |
| `youtube_id` | `str` | YouTube video ID |
| `parentid` | `str` | Parent media ID |
| `media_state` | `int` | `0`=Draft, `1`=Active |

---

#### `cancel_upload`

Cancel a specific upload and mark the media as cancelled in Slike. Use this when the user explicitly cancels from the UI.

```python
result = client.register_media(
    file_path="/path/to/video.mp4",
    title="My Video",
    description="Description",
    on_upload_complete=lambda res, err: print(err or "done"),
)

media_id = result["id"]

# When user clicks Cancel in the UI:
client.cancel_upload(media_id)
```

This stops the upload on this client and marks the media as cancelled in Slike.

---

#### `publish_media`

Publish media by URL (YouTube, Google Drive, direct link).

```python
client.publish_media(
    url="https://drive.google.com/file/d/FILE_ID/view",
    title="My Video",
    description="Description",
    type="gdrive",              # optional: inferred from the URL's host when omitted
    asset_type="video",         # optional, default: "video"
    tags=["news", "sports"],    # optional
    auto_publish=True,          # optional, default: True
)
```

`type` is one of `youtube`, `gdrive` or `httpdownload`; omit it (or pass `url`) to detect it.
When omitted it is taken from the URL's host (YouTube, Google Drive, otherwise `httpdownload`).
Google Drive files must be shared with "Anyone with the link".
Since 0.3.1 `asset_type` is always sent and defaults to `"video"`.

---

#### `create_premiere`

Creates a **premiere**: an existing video scheduled to play as a live event. It works the
same way as **Create → Premiere** in the CMS:

1. It checks the source video. Embedded media, clips and simulives can't be used.
2. It creates the premiere as a new media that copies the source video's title and details, with your
   start time, playback mode and loop count.

No poster is uploaded; add one in the CMS if you need it.

| Playback mode | Meaning (as shown in the CMS) |
|---|---|
| `live` (default) | **Live Only**: scheduled live broadcast, no replay after end |
| `livevod` | **Live + Replay**: goes live as scheduled, then auto-replays for late viewers |
| `vod` | **Video Only**: plays as a normal on-demand video; the loop count is not used |

```python
import datetime

premiere = client.create_premiere(
    source_media_id="1xnhyvsgzl",
    start_time=datetime.datetime(2027, 1, 1, 18, 30),   # or epoch milliseconds
    playback_mode="live",                                 # "live" | "livevod" | "vod"
    loop_count=1,                                         # not used for "vod"
)
print(premiere["id"])
```

Returns `id`, `source_media_id`, `start_time`, `playback_mode` and `loop_count`.

#### `create_user`

Create a CMS user. Send only `name`, `email` and `team` (a list of team ids);
everything else is filled in with the user defaults. Requires a token with admin access to those teams.

```python
result = client.create_user(
    name="Test User",
    email="test.user@example.com",
    team=["nd78ug9zoo", "ndbxuuzzko"],
)
```

Returns a concise confirmation:

```python
{
    "id": "ws41sgoouo",
    "name": "Test User",
    "email": "test.user@example.com",
    "msg": "User created successfully (id ws41sgoouo).",   # or "User access updated (id …)."
}
```

**Existing email:** if a user with this email already exists, their team access
is **replaced** with `team` (not merged) and `msg` says `User access updated`.
Sending the same teams again raises `SlikeAPIError` (`user already exists with
same permissions`).

---

#### `get_teams_by_host`

List the teams attached to a host. Multiple teams can share a host, so the result is always a list.

```python
teams = client.get_teams_by_host(hostid="153")
for t in teams:
    print(t["id"], t["name"], t["hostid"])
```

| Parameter | Type | Description |
|---|---|---|
| `hostid` | `str` | Host id to look up (required) |

Returns a list of `{ "id", "name", "hostid" }`:

```python
[
    {"id": "nd78ug9zoo", "name": "Team A", "hostid": "153"},
    {"id": "ndbxuuzzko", "name": "Team B", "hostid": "153"},
]
```

See [Use case 5](#5-create-a-cms-user-host--teams--user) for the full host → teams → user flow.

---

### Error handling

```python
from slike import SlikeMedia, SlikeAPIError, CancelError

try:
    client = SlikeMedia(token="...", environment="prod")
    client.initialize()
    result = client.register_media(file_path="video.mp4", title="T", description="D")
except ValueError as e:
    print(f"Bad input: {e}")
except CancelError:
    print("Upload was cancelled")
except SlikeAPIError as e:
    print(f"API error: {e} (code: {e.code})")
    if e.conflicts:
        for c in e.conflicts:
            print(f"  conflict: field={c['field']} id={c['id']} value={c['value']}")
```

#### Duplicate file (unique constraint)

When a file with the same `fid` (derived from filename + size) is already registered on the server, `register_media` raises `SlikeAPIError` with `conflicts` populated:

```python
except SlikeAPIError as e:
    if e.conflicts:
        # File already exists — e.conflicts[0]["id"] is the existing media ID
        existing_id = e.conflicts[0]["id"]
        print(f"Already uploaded as media ID: {existing_id}")
    else:
        print(f"API error: {e} (code: {e.code})")
```

`SlikeAPIError` fields:

| Field | Type | Description |
|---|---|---|
| `message` | `str` | Human-readable error message |
| `code` | `int \| None` | HTTP or RPC error code (e.g. `400`) |
| `conflicts` | `list[dict] \| None` | Conflict entries when a unique constraint is violated |

Each conflict entry has `field`, `id`, and `value` keys.

---

## TypeScript / JavaScript SDK

### Quick start

```typescript
import { SlikeMedia } from 'slike';

const client = new SlikeMedia({ token: 'your-slike-token', environment: 'prod' });
await client.initialize();

// Upload a file (blocking — waits for all chunks)
const result = await client.uploadMedia({
  file,           // File object
  title: 'My Video',
  description: 'Description',
  onProgress: (done, total) => console.log(`${done}/${total} chunks`),
});
console.log('Media ID:', result.id);
```

### Denmark JWT auth

```typescript
const client = new SlikeMedia({
  denmarkToken: '<jwt>',
  service: 'slike',       // optional
  environment: 'prod',
});
await client.initialize();
console.log(client.token);
```

---

### Methods

#### `initialize()`

```typescript
await client.initialize();
```

#### `uploadMedia(opts)` — blocking upload

Registers and uploads all chunks. Returns when complete.

```typescript
const result = await client.uploadMedia({
  file,
  title: 'My Video',
  description: 'Description',
  tags: ['news', 'sports'],
  team: 'team-id',        // optional — from getRequiredMetadata
  business: 'biz-id',     // optional — paired with team
  agency: 'agency-id',    // optional — from getAgencyList
  onProgress: (done, total) => console.log(`${done}/${total}`),
  signal: abortController.signal,   // optional AbortSignal
});
```

Pass `team` and `business` together — both come from the same team object:

```typescript
const meta = await client.getRequiredMetadata();
const selectedTeam = meta.defaultTeam?.team;  // or whichever team the user picks

const result = await client.uploadMedia({
  file,
  title: 'My Video',
  description: 'Description',
  team: selectedTeam?.value,
  business: selectedTeam?.business,
});
```

#### `uploadMediaBackground(opts)` — non-blocking upload

Returns an `UploadHandle` immediately. `onUploadComplete` fires the moment chunks finish — caller does not need to wait.

```typescript
const handle = await client.uploadMediaBackground({
  file,
  title: 'My Video',
  description: 'Description',
  onProgress: (done, total) => console.log(`${done}/${total}`),
  onUploadComplete: (result, error) => {
    if (error) console.error('Upload failed:', error);
    else console.log('Upload complete! ID:', result.id);
  },
});

console.log('Media ID (available now):', handle.mediaId);

// Cancel from UI — stops chunks locally AND marks media cancelled on Slike server:
cancelButton.onclick = () => handle.cancel();

// Or await completion:
const result = await handle.completion;
```

`UploadHandle`:

| Property | Type | Description |
|---|---|---|
| `mediaId` | `string` | Media ID (available immediately) |
| `cancel()` | `() => void` | Abort chunks + notify Slike server |
| `completion` | `Promise<RegisterMediaResult>` | Resolves when upload finishes |

#### `getStatus(mediaId, signal?)`

Get basic media details and processing readiness.

```typescript
const status = await client.getStatus('media_id_here');

console.log(status.mediaId);  // media ID
console.log(status.title);    // media title
console.log(status.desc);     // media description
console.log(status.tags);     // string[] | undefined
console.log(status.status);   // raw status code
console.log(status.isReady);  // true when status===5 and state===10
console.log(status.msg);      // "Media is ready." or "Media is not ready yet."
```

#### `getRequiredMetadata(signal?)`

Fetch all dropdown options for building a media-update form. Returns static constants at the top level, per-team filtered languages and categories, and a flat agency list.

```typescript
const meta = await client.getRequiredMetadata();

// Static constants (from SDK)
console.log(meta.contentTypes);    // [{ value: 'package', label: 'Package' }, ...]
console.log(meta.productionTypes); // [{ value: 'In House Originals', label: 'In House Originals' }, ...]
console.log(meta.contentRatings);  // [{ value: '1', label: 'Made for Kids' }, ...]
console.log(meta.mediaStates);     // [{ value: 0, label: 'Draft' }, ...]

// Agencies (flat list sorted by recent activity)
console.log(meta.agencies);        // [{ id: 'agency-id', name: 'Agency Name' }, ...]

// Default team (pre-select on load)
console.log(meta.defaultTeam.team);       // { value: 'team-id-1', label: 'Team 1', is_default: true, business: 'biz-id' }
console.log(meta.defaultTeam.languages);  // [{ value: 'language-1', label: 'Language 1' }, ...]
console.log(meta.defaultTeam.categories); // [{ value: 'category-1', label: 'Category 1', subcategories: [...] }, ...]

// All teams (populate team switcher)
meta.teams.forEach(({ team, languages, categories }) => {
  console.log(team);       // { value, label, is_default, business }
  console.log(languages);  // languages allowed for this team
  console.log(categories); // categories allowed for this team
});
```

You can also import the static constants directly:

```typescript
import { CONTENT_TYPES, PRODUCTION_TYPES, CONTENT_RATINGS, MEDIA_STATES } from 'slike';
```

**Example response:**

```json
{
  "contentTypes":    [{ "value": "content-type-1", "label": "Content Type 1" }],
  "productionTypes": [{ "value": "production-type-1", "label": "Production Type 1" }],
  "contentRatings":  [{ "value": "1", "label": "Rating 1" }],
  "mediaStates":     [{ "value": 0, "label": "State 1" }],
  "agencies":        [{ "id": "agency-id-1", "name": "Agency Name" }],
  "defaultTeam": {
    "team":       { "value": "team-id-1", "label": "Team 1", "is_default": true, "business": "biz-id-1" },
    "languages":  [{ "value": "language-1", "label": "Language 1" }],
    "categories": [{ "value": "category-1", "label": "Category 1", "subcategories": [{ "value": "sub-category-1", "label": "Sub Category 1" }] }]
  },
  "teams": [
    {
      "team":       { "value": "team-id-1", "label": "Team 1", "is_default": true, "business": "biz-id-1" },
      "languages":  [{ "value": "language-1", "label": "Language 1" }],
      "categories": [{ "value": "category-1", "label": "Category 1", "subcategories": [] }]
    },
    {
      "team":       { "value": "team-id-2", "label": "Team 2", "is_default": false, "business": "biz-id-1" },
      "languages":  [{ "value": "language-1", "label": "Language 1" }],
      "categories": [{ "value": "category-1", "label": "Category 1", "subcategories": [{ "value": "sub-category-1", "label": "Sub Category 1" }] }]
    }
  ]
}
```

#### `getAgencyList(opts?, signal?)`

List active agencies, optionally filtered by name. Returns up to 50 results sorted by recent activity.

```typescript
// All active agencies
const result = await client.getAgencyList();
console.log(result.count);         // total count
console.log(result.list);          // [{ id: 'agency-id', name: 'Agency Name' }, ...]

// Search by name
const byName = await client.getAgencyList({ name: 'toi' });
```

`AgencySearchOptions`:

| Field | Type | Description |
|---|---|---|
| `name` | `string` | Optional name filter |

`AgencyListResult`: `{ list: AgencyOption[]; count: number }`
`AgencyOption`: `{ id: string; name: string }`

#### `listMedia(opts?, signal?)`

List your media with paging, filters and search. See [js/README.md](js/README.md#listmedia--list-media) for every option.

```typescript
const res = await client.listMedia({ page: 1, size: 20, search: 'cricket', status: 5, createdFrom: new Date('2026-10-01') });
console.log(res.count, res.hasMore);
res.list.forEach(m => console.log(m.id, m.title, m.isReady));

// Raw CMS query, deep-merged over the options
await client.listMedia({ query: { must: { lang: 'english' }, must_not: { islive: 1 } } });
```

`ListMediaResult`: `{ list: MediaListItem[]; count: number; page: number; size: number; hasMore: boolean }`

#### `updateMedia(opts, signal?)`

Update metadata fields on an existing media item. All fields except `id` are optional.

```typescript
const result = await client.updateMedia({
  id: 'media-id-here',
  title: 'Updated Title',
  desc: 'Updated description',
  tags: ['news', 'sports'],
  lang: 'English',
  category: 'News',
  subcategory: 'Politics',
  ctype: 'story',
  productionType: 'In House Originals',
  mfk: 2,               // content rating: 1=Kids, 2=General, 3=18+
  media_state: 1,        // 0=Draft, 1=Active
  expiry: '2026-12-31',
  youtube_id: 'dQw4w9WgXcQ',
  parentid: 'parent-id',
});
```

`UpdateMediaOptions`:

| Field | Type | Description |
|---|---|---|
| `id` | `string` | **Required.** Media ID to update |
| `title` | `string` | **Required.** Media title |
| `title_url` | `string` | URL-friendly title slug |
| `desc` | `string` | Description |
| `tags` | `string[]` | Tags |
| `agency_credits` | `string[]` | Agency credits |
| `ctype` | `string` | Content type (see `CONTENT_TYPES`) |
| `productionType` | `string` | Production type (see `PRODUCTION_TYPES`) |
| `lang` | `string` | Language name |
| `category` | `string` | Category name |
| `subcategory` | `string` | Sub-category name |
| `mfk` | `number` | Content rating: `1`=Kids, `2`=General, `3`=18+ |
| `images` | `object` | Image metadata |
| `expiry` | `string` | Expiry date string |
| `youtube_id` | `string` | YouTube video ID |
| `parentid` | `string` | Parent media ID |
| `media_state` | `0 \| 1` | `0`=Draft, `1`=Active |

#### `cancelUpload(mediaId, signal?)`

Mark a specific media as cancelled in Slike. Use when the user explicitly cancels from the UI.

```typescript
await client.cancelUpload('media_id_here');
```

> Note: `UploadHandle.cancel()` already calls this automatically. Use `cancelUpload()` directly only when you have a `mediaId` without a handle (e.g. cancelling a previously registered upload on page reload).

#### `publishMedia(opts)`

```typescript
await client.publishMedia({
  url: 'https://drive.google.com/file/d/FILE_ID/view',
  title: 'My Video',
  description: 'Description',
  type: 'gdrive',           // 'gdrive' | 'youtube' | 'url'
  tags: ['news', 'sports'],
  autoPublish: true,
});
```

---

#### `createPremiere(opts, signal?)`

Creates a **premiere**: an existing video scheduled to play as a live event. It works the
same way as **Create → Premiere** in the CMS:

1. It checks the source video. Embedded media, clips and simulives can't be used.
2. It creates the premiere as a new media that copies the source video's title and details, with your
   start time, playback mode and loop count.

No poster is uploaded; add one in the CMS if you need it.

| Playback mode | Meaning (as shown in the CMS) |
|---|---|
| `live` (default) | **Live Only**: scheduled live broadcast, no replay after end |
| `livevod` | **Live + Replay**: goes live as scheduled, then auto-replays for late viewers |
| `vod` | **Video Only**: plays as a normal on-demand video; the loop count is not used |

```ts
const premiere = await slike.createPremiere({
  sourceMediaId: '1xnhyvsgzl',
  startTime: new Date('2027-01-01T18:30:00'),   // or epoch milliseconds
  playbackMode: 'live',                         // 'live' | 'livevod' | 'vod'
  loopCount: 1,                                 // not used for 'vod'
});
console.log(premiere.id);
```

Returns `{ id, sourceMediaId, startTime, playbackMode, loopCount }`.

#### `getCurrentUser({ refresh }?, signal?)`

Returns the connected user's profile (`id`, `name`, `email`, `team_name`, `user_role`, …).
The profile loaded by `initialize()` is reused; pass `{ refresh: true }` to fetch it again.

#### `createUser(opts, signal?)`

Create a CMS user. Provide only `name`, `email` and `team` (an array of team ids);
everything else is filled in with the user defaults. Requires a token with admin access to those teams.

```typescript
const result = await client.createUser({
  name: 'Test User',
  email: 'test.user@example.com',
  team: ['nd78ug9zoo', 'ndbxuuzzko'],
});
```

Returns a concise confirmation:

```typescript
{
  id: 'ws41sgoouo',
  name: 'Test User',
  email: 'test.user@example.com',
  msg: 'User created successfully (id ws41sgoouo).',   // or 'User access updated (id …).'
}
```

**Existing email:** if a user with this email already exists, their team access
is **replaced** with `team` (not merged) and `msg` says `User access updated`.
Sending the same teams again throws `SlikeAPIError` (`user already exists with
same permissions`).

---

#### `getTeamsByHost(hostid, signal?)`

List the teams attached to a host. Multiple teams can share a host, so the result is always an array.

```typescript
const teams = await client.getTeamsByHost('153');
// [{ id: 'nd78ug9zoo', name: 'Team A', hostid: '153' }, ...]
```

| Parameter | Type | Description |
|---|---|---|
| `hostid` | `string` | Host id to look up (required) |
| `signal` | `AbortSignal` | Optional abort signal |

Returns `HostTeam[]` — a list of `{ id, name, hostid }`.

---

### Error handling (TypeScript)

```typescript
import { SlikeMedia, SlikeAPIError, CancelError } from 'slike';

try {
  await client.uploadMedia({ file, title: 'T', description: 'D' });
} catch (err) {
  if (err instanceof CancelError) {
    console.log('Upload cancelled');
  } else if (err instanceof SlikeAPIError) {
    console.error('API error:', err.message, 'code:', err.code);
    if (err.conflicts) {
      for (const c of err.conflicts) {
        console.log(`conflict: field=${c.field} id=${c.id} value=${c.value}`);
      }
    }
  }
}
```

#### Duplicate file (unique constraint)

When a file with the same `fid` is already registered, `registerMedia` throws `SlikeAPIError` with the message _"This file has already been uploaded…"_ and `conflicts` populated:

```typescript
import { SlikeAPIError, type ConflictEntry } from 'slike';

try {
  await client.registerMedia({ file, title: 'T', description: 'D' });
} catch (err) {
  if (err instanceof SlikeAPIError && err.conflicts) {
    // File already exists — err.conflicts[0].id is the existing media ID
    const existing = err.conflicts[0];
    console.log(`Already uploaded as media ID: ${existing.id}`);
  }
}
```

`SlikeAPIError` fields:

| Field | Type | Description |
|---|---|---|
| `message` | `string` | Human-readable error message |
| `code` | `number \| undefined` | HTTP or RPC error code (e.g. `400`) |
| `conflicts` | `ConflictEntry[] \| undefined` | Conflict entries when a unique constraint is violated |

`ConflictEntry` fields: `field`, `id`, `value`.

---

## Use Cases

### 1. Upload a file and check status after

```python
# Python
client.initialize()
result = client.register_media(file_path="video.mp4", title="T", description="D")

status = client.get_status(result["id"])
print(status["msg"])   # "Media is not ready yet." (processing takes time)
```

```typescript
// TypeScript
await client.initialize();
const result = await client.uploadMedia({ file, title: 'T', description: 'D' });

const status = await client.getStatus(result.id);
console.log(status.msg);   // "Media is not ready yet."
```

---

### 2. Background upload with completion callback + cancel from UI

```python
# Python
result = client.register_media(
    file_path="video.mp4",
    title="My Video",
    description="Description",
    on_upload_complete=lambda res, err: (
        print("failed:", err) if err else print("ready to process, ID:", res["id"])
    ),
)

# Store media_id for potential cancel
media_id = result["id"]

# When user clicks Cancel:
client.cancel_upload(media_id)
```

```typescript
// TypeScript
const handle = await client.uploadMediaBackground({
  file,
  title: 'My Video',
  description: 'Description',
  onUploadComplete: (result, error) => {
    if (error) console.error('failed:', error);
    else console.log('chunks done, media processing started:', result.id);
  },
});

// Wire to UI cancel button — aborts chunks AND marks cancelled on server:
cancelBtn.onclick = () => handle.cancel();
```

---

### 3. Check if media is ready before serving

```python
# Python
status = client.get_status(media_id)
if status["is_ready"]:
    print("Serve URL from your CDN using media_id:", status["media_id"])
else:
    print(status["msg"])
```

```typescript
// TypeScript
const status = await client.getStatus(mediaId);
if (status.isReady) {
  serveMedia(status.mediaId);
} else {
  showMessage(status.msg);
}
```

---

### 4. Cancel a previously registered upload (e.g. on page reload)

```typescript
// If you stored the mediaId in localStorage before the page unloaded:
const mediaId = localStorage.getItem('pendingMediaId');
if (mediaId) {
  await client.cancelUpload(mediaId);
  localStorage.removeItem('pendingMediaId');
}
```

---

### 5. Create a CMS user (host → teams → user)

Look up the host's teams, let the operator pick one or more, then create the user.
Calling it again with an existing email **replaces** that user's team access.

```python
teams = client.get_teams_by_host(hostid="83")
chosen = [t["id"] for t in teams if t["name"] in ("Test 2", "Test 3")]

try:
    result = client.create_user(name="Test User", email="test.user@example.com", team=chosen)
    print(result["msg"])   # "User created successfully (id …)." or "User access updated (id …)."
except SlikeAPIError as e:
    print(e)               # e.g. "... user already exists with same permissions: ..."
```

```typescript
const teams = await client.getTeamsByHost('83');
const chosen = teams.filter(t => ['Test 2', 'Test 3'].includes(t.name)).map(t => t.id);

try {
  const { msg } = await client.createUser({ name: 'Test User', email: 'test.user@example.com', team: chosen });
  console.log(msg);
} catch (err) {
  if (err instanceof SlikeAPIError) console.error(err.message);
}
```

Rules when creating a user:

- `team` must contain at least one id, and you must have `admin_console` access for the
  teams — teams you can't administer are dropped; if none remain the call is rejected.
- The email domain must be an allowed domain (globally, or listed in the first team's
  allowed domains), otherwise `invalid email id`.
- Sending exactly the teams the user already has is rejected
  (`user already exists with same permissions`).

---

## Configuration (CLI / Python only)

### Priority (highest wins)

1. CLI flags (`--token`, `--denmark-token`, `--env`, `--config`)
2. Environment variables (`SLIKE_TOKEN`, `SLIKE_ENVIRONMENT`, `SLIKE_CONFIG`)
3. `./config.toml` → `~/.slike/config.toml`

### Config file

```toml
token       = "your-token-here"
environment = "prod"              # "dev" or "prod"
```

### Environment variables

| Variable            | Description                    |
|---------------------|-------------------------------|
| `SLIKE_TOKEN`       | Slike auth token              |
| `SLIKE_ENVIRONMENT` | `dev` or `prod`               |
| `SLIKE_CONFIG`      | Path to a specific config file |

---

## CLI

```bash
# Upload a local file
slike-upload video.mp4 --title "My Video" --desc "Description"

# Publish by URL (Google Drive)
slike-upload --url https://drive.google.com/file/d/FILE_ID/view \
             --type gdrive --title "My Video" --desc "Description"

# Denmark JWT auth
slike-upload video.mp4 --title "T" --desc "D" --denmark-token <jwt>
```

Install it globally with [pipx](https://pipx.pypa.io): `brew install pipx && pipx ensurepath && pipx install slike`.

| Flag              | Description                                              |
|-------------------|----------------------------------------------------------|
| `--url`           | Media URL to ingest (publish mode)                       |
| `--type`          | `gdrive`, `youtube`, or `url` (default: `url`)           |
| `--title`         | Media title                                              |
| `--desc`          | Media description                                        |
| `--asset-type`    | e.g. `video`, `shorts` (default: `video`)                |
| `--tags`          | Comma-separated tags                                     |
| `--no-publish`    | Save as draft, skip auto-publish                         |
| `--token`         | Slike auth token                                         |
| `--denmark-token` | Denmark JWT (exchanged for a Slike session token)        |
| `--service`       | Service name for Denmark auth (default: `slike`)         |
| `--env`           | `dev` or `prod`                                          |
| `--config`        | Path to config file                                      |
| `--payload`       | JSON with `title`, `desc`, `asset_type`, `tags`, `preset_config`, `downloads`, `islive`, `type`, `source`; flags win. `type` must be a string (default `"media"`) |

### Other commands

```bash
# Processing status of one media item
slike-upload status <media_id>

# List media (newest first): search, filters, paging
slike-upload list --search cricket --status 5 --asset-type video --size 20
slike-upload list --from-date 2026-10-01 --to-date 2026-10-13 --page 2
slike-upload list --query '{"must": {"lang": "english"}}' --json

# Update metadata (--title is required by the server)
slike-upload update <media_id> --title "New title" --tags news,sports --media-state 1

# Cancel an upload and mark the media cancelled
slike-upload cancel <media_id> --title "My Video"

# Premiere: like CMS Create → Premiere (start in local time)
slike-upload premiere <media_id> --start "2027-01-01 18:30" --mode live --loop 1
```

| Command | Main options |
|---|---|
| `status <media_id>` | `--json` for the raw result |
| `list` | `--search`, `--status`, `--state`, `--asset-type`, `--team` (comma-separated for several values), `--from-date` / `--to-date` (YYYY-MM-DD), `--page`, `--size` (max 500), `--include`, `--query` (raw JSON), `--json` |
| `update <media_id>` | `--title` (required), `--desc`, `--tags`, `--lang`, `--category`, `--subcategory`, `--ctype`, `--production-type`, `--mfk` (1–3), `--media-state` (0/1), `--expiry`, `--youtube-id`, `--parentid` |
| `cancel <media_id>` | `--title` (required) |
| `premiere <media_id>` | `--start` (required), `--mode` `live` (default) / `livevod` / `vod`, `--loop` (default 1) |

Every command accepts the same auth options as uploads (`--token`, `--denmark-token`, `--service`, `--env`, `--config`). Put options after the command name: `slike-upload list --token … --env dev`.
Run `slike-upload <command> --help` for details. On error a command prints `Error: …` and exits with code 1.

---

## Environments

Pass `environment="dev"` (Python) or `environment: 'dev'` (JavaScript) while testing, and `"prod"` for live use.
The default is `prod`.

---

## Demo

Try every feature in the browser, with code samples for JavaScript, Python and the CLI:
[app.sli.ke/sdk-demo/](https://app.sli.ke/sdk-demo/) (production) ·
[app-dev.sli.ke/sdk-demo/](https://app-dev.sli.ke/sdk-demo/) (development).

---

## License

MIT
