slike 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- config.example.toml +15 -0
- slike-0.1.0.dist-info/METADATA +292 -0
- slike-0.1.0.dist-info/RECORD +8 -0
- slike-0.1.0.dist-info/WHEEL +4 -0
- slike-0.1.0.dist-info/entry_points.txt +2 -0
- slike-0.1.0.dist-info/licenses/LICENSE +22 -0
- slike.py +606 -0
- slikeupload.py +295 -0
config.example.toml
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# Slike SDK configuration
|
|
2
|
+
# Copy this file to ~/.slike/config.toml and fill in your token.
|
|
3
|
+
#
|
|
4
|
+
# Priority (highest wins):
|
|
5
|
+
# 1. CLI flags (--token, --env, …)
|
|
6
|
+
# 2. Environment variables: SLIKE_TOKEN, SLIKE_ENVIRONMENT
|
|
7
|
+
# 3. This config file
|
|
8
|
+
|
|
9
|
+
# Auth token (required)
|
|
10
|
+
token = ""
|
|
11
|
+
|
|
12
|
+
# Environment: "dev" or "prod"
|
|
13
|
+
# dev → uses dev API URL + token-dev cookie
|
|
14
|
+
# prod → uses prod API URL + token cookie
|
|
15
|
+
environment = "prod"
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: slike
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python SDK for publishing media on Slike platform
|
|
5
|
+
Project-URL: Homepage, https://code.sli.ke/python/slike-media-package
|
|
6
|
+
Project-URL: Documentation, https://code.sli.ke/python/slike-media-package#readme
|
|
7
|
+
Project-URL: Repository, https://code.sli.ke/python/slike-media-package
|
|
8
|
+
Project-URL: Issues, https://code.sli.ke/python/slike-media-package/issues
|
|
9
|
+
Author: Arpit Kumar
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: api,media,publishing,sdk,slike
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.7
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
24
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
25
|
+
Requires-Python: >=3.7
|
|
26
|
+
Requires-Dist: requests>=2.25.0
|
|
27
|
+
Requires-Dist: tomli>=1.2; python_version < '3.11'
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
|
|
30
|
+
# slike
|
|
31
|
+
|
|
32
|
+
Python SDK and CLI for the [Slike](https://sli.ke) platform.
|
|
33
|
+
|
|
34
|
+
Supports **chunked file upload** (4 MiB chunks), **editor-video registration**, **publish-by-URL** (Google Drive, YouTube, direct links), and two auth flows: **direct Slike token** or **Denmark JWT** (exchanged at `/login`).
|
|
35
|
+
|
|
36
|
+
Requires Python 3.7+.
|
|
37
|
+
|
|
38
|
+
---
|
|
39
|
+
|
|
40
|
+
## Install
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pip3 install slike
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
## Python SDK
|
|
49
|
+
|
|
50
|
+
The SDK is a client class. Construct with credentials, call `initialize()` once to validate them, then call methods.
|
|
51
|
+
|
|
52
|
+
### Quick start (direct Slike token)
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
from slike import SlikeMedia
|
|
56
|
+
|
|
57
|
+
client = SlikeMedia(token="your-slike-token", environment="prod")
|
|
58
|
+
client.initialize() # validates the token via user.me; raises SlikeAPIError on failure
|
|
59
|
+
|
|
60
|
+
# Upload a local file
|
|
61
|
+
result = client.register_media(
|
|
62
|
+
file_path="/path/to/video.mp4",
|
|
63
|
+
title="My Video",
|
|
64
|
+
description="Description",
|
|
65
|
+
on_progress=lambda done, total: print(f"{done}/{total} chunks"),
|
|
66
|
+
)
|
|
67
|
+
print(result["id"])
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
### Quick start (Denmark JWT)
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
from slike import SlikeMedia
|
|
74
|
+
|
|
75
|
+
client = SlikeMedia(
|
|
76
|
+
denmark_token="<jwt>", # exchanged for a Slike session token at /login
|
|
77
|
+
service="slike", # optional, default: "slike"
|
|
78
|
+
environment="prod",
|
|
79
|
+
)
|
|
80
|
+
client.initialize() # exchanges the JWT; raises SlikeAPIError on failure
|
|
81
|
+
|
|
82
|
+
print(client.token) # the resolved Slike session token
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
You must provide exactly one of `token` or `denmark_token`.
|
|
86
|
+
|
|
87
|
+
### Methods
|
|
88
|
+
|
|
89
|
+
#### `register_media`
|
|
90
|
+
|
|
91
|
+
Register media on Slike. Provide exactly one of `file_path` (chunked file upload) or `editor_settings` (editor-generated video — no bytes uploaded; the asset server renders from the spec).
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
# File mode
|
|
95
|
+
client.register_media(
|
|
96
|
+
file_path="/path/to/video.mp4",
|
|
97
|
+
title="My Video",
|
|
98
|
+
description="Description",
|
|
99
|
+
asset_type="video", # optional, default: "video"
|
|
100
|
+
tags=["news", "sports"], # optional
|
|
101
|
+
preset_config={"meta": "", "social": ""}, # optional
|
|
102
|
+
on_progress=lambda done, total: print(f"{done}/{total} chunks"),
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
# Editor mode
|
|
106
|
+
client.register_media(
|
|
107
|
+
title="My Editor Video",
|
|
108
|
+
description="Description",
|
|
109
|
+
editor_settings={
|
|
110
|
+
"clips": [...],
|
|
111
|
+
"background_music": {...},
|
|
112
|
+
"source_width": 1080,
|
|
113
|
+
"source_height": 1920,
|
|
114
|
+
},
|
|
115
|
+
)
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
#### `publish_media`
|
|
119
|
+
|
|
120
|
+
Publish media by URL (Google Drive, YouTube, direct link).
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
client.publish_media(
|
|
124
|
+
url="https://drive.google.com/file/d/FILE_ID/view",
|
|
125
|
+
title="My Video",
|
|
126
|
+
description="Description",
|
|
127
|
+
type="gdrive", # gdrive | youtube | url
|
|
128
|
+
asset_type="video", # optional
|
|
129
|
+
tags=["news", "sports"], # optional
|
|
130
|
+
auto_publish=True, # optional, default: True
|
|
131
|
+
)
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
### Error handling
|
|
135
|
+
|
|
136
|
+
```python
|
|
137
|
+
from slike import SlikeMedia, SlikeAPIError
|
|
138
|
+
|
|
139
|
+
try:
|
|
140
|
+
client = SlikeMedia(token="...", environment="prod")
|
|
141
|
+
client.initialize()
|
|
142
|
+
result = client.register_media(file_path="video.mp4", title="T", description="D")
|
|
143
|
+
except ValueError as e:
|
|
144
|
+
print(f"Bad input: {e}")
|
|
145
|
+
except SlikeAPIError as e:
|
|
146
|
+
print(f"API / auth error: {e}")
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
---
|
|
150
|
+
|
|
151
|
+
## Configuration (CLI only)
|
|
152
|
+
|
|
153
|
+
The CLI accepts the token + environment inline, falls back to env vars and a config file. The Python SDK takes them as constructor arguments — no file reads.
|
|
154
|
+
|
|
155
|
+
### Priority (highest wins)
|
|
156
|
+
|
|
157
|
+
1. CLI flags (`--token`, `--denmark-token`, `--env`, `--config`)
|
|
158
|
+
2. Environment variables (`SLIKE_TOKEN`, `SLIKE_ENVIRONMENT`, `SLIKE_CONFIG`)
|
|
159
|
+
3. `./config.toml` (current directory), then `~/.slike/config.toml`
|
|
160
|
+
|
|
161
|
+
### Config file format
|
|
162
|
+
|
|
163
|
+
```toml
|
|
164
|
+
token = "your-token-here"
|
|
165
|
+
environment = "prod" # "dev" or "prod"
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
### Environment variables
|
|
169
|
+
|
|
170
|
+
| Variable | Description |
|
|
171
|
+
|---------------------|-----------------------------------------|
|
|
172
|
+
| `SLIKE_TOKEN` | Slike auth token |
|
|
173
|
+
| `SLIKE_ENVIRONMENT` | `dev` or `prod` |
|
|
174
|
+
| `SLIKE_CONFIG` | Path to a specific config file |
|
|
175
|
+
|
|
176
|
+
---
|
|
177
|
+
|
|
178
|
+
## CLI
|
|
179
|
+
|
|
180
|
+
```bash
|
|
181
|
+
# Upload a local file
|
|
182
|
+
slike-upload video.mp4 --title "My Video" --desc "Description"
|
|
183
|
+
|
|
184
|
+
# Publish by URL (Google Drive)
|
|
185
|
+
slike-upload --url https://drive.google.com/file/d/FILE_ID/view \
|
|
186
|
+
--type gdrive --title "My Video" --desc "Description"
|
|
187
|
+
|
|
188
|
+
# Use a Denmark JWT instead of a Slike token
|
|
189
|
+
slike-upload video.mp4 --title "T" --desc "D" --denmark-token <jwt>
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
### Publish by URL
|
|
193
|
+
|
|
194
|
+
```
|
|
195
|
+
slike-upload --url <URL> --type <gdrive|youtube|url>
|
|
196
|
+
--title "Title" --desc "Description"
|
|
197
|
+
[--asset-type video|shorts]
|
|
198
|
+
[--tags tag1,tag2]
|
|
199
|
+
[--no-publish]
|
|
200
|
+
[--token <token> | --denmark-token <jwt> [--service <name>]]
|
|
201
|
+
[--env dev|prod] [--config <path>]
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
| Flag | Required | Description |
|
|
205
|
+
|-------------------|----------|----------------------------------------------------------|
|
|
206
|
+
| `--url` | yes | Media URL to ingest |
|
|
207
|
+
| `--type` | no | `gdrive`, `youtube`, or `url` (default: `url`) |
|
|
208
|
+
| `--title` | yes | Media title |
|
|
209
|
+
| `--desc` | yes | Media description |
|
|
210
|
+
| `--asset-type` | no | Asset type, e.g. `video`, `shorts` (default: `video`) |
|
|
211
|
+
| `--tags` | no | Comma-separated tags |
|
|
212
|
+
| `--no-publish` | no | Save as draft, skip auto-publish |
|
|
213
|
+
| `--token` | no | Slike auth token |
|
|
214
|
+
| `--denmark-token` | no | Denmark JWT (exchanged for a Slike session token) |
|
|
215
|
+
| `--service` | no | Service name for Denmark auth (default: `slike`) |
|
|
216
|
+
| `--env` | no | `dev` or `prod` (overrides config) |
|
|
217
|
+
| `--config` | no | Path to config file |
|
|
218
|
+
|
|
219
|
+
### Upload a local file
|
|
220
|
+
|
|
221
|
+
```
|
|
222
|
+
slike-upload <file>
|
|
223
|
+
--title "Title" --desc "Description"
|
|
224
|
+
[--asset-type video|shorts]
|
|
225
|
+
[--tags tag1,tag2]
|
|
226
|
+
[--payload '<JSON>']
|
|
227
|
+
[--token <token> | --denmark-token <jwt>]
|
|
228
|
+
[--env dev|prod] [--config <path>]
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
#### Using `--payload` JSON
|
|
232
|
+
|
|
233
|
+
Pass all metadata as a single JSON string instead of individual flags. CLI flags take precedence when both are given.
|
|
234
|
+
|
|
235
|
+
| Field | Type | Default | Notes |
|
|
236
|
+
|-----------------|--------------|---------------|------------------------------------|
|
|
237
|
+
| `title` | string | required | |
|
|
238
|
+
| `desc` | string | required | |
|
|
239
|
+
| `asset_type` | string | `"video"` | e.g. `"video"`, `"shorts"` |
|
|
240
|
+
| `tags` | list[string] | `null` | e.g. `["news", "sports"]` |
|
|
241
|
+
| `preset_config` | object | `null` | `{"meta": "...", "social": "..."}` |
|
|
242
|
+
| `downloads` | object | `null` | `{"url": "https://..."}` |
|
|
243
|
+
| `islive` | int | `0` | `0` or `1` |
|
|
244
|
+
| `type` | int | `0` | Media type integer |
|
|
245
|
+
| `source` | string | `"uploadsdk"` | Upload source identifier |
|
|
246
|
+
|
|
247
|
+
---
|
|
248
|
+
|
|
249
|
+
## Environments
|
|
250
|
+
|
|
251
|
+
| Environment | RPC endpoint | Upload endpoint | Auth endpoint |
|
|
252
|
+
|-------------|------------------------------|-----------------------------------|-------------------------------------|
|
|
253
|
+
| `prod` | `https://b2b.sli.ke/rpc` | `https://asset.sli.ke/upload` | `https://accounts.sli.ke/login` |
|
|
254
|
+
| `dev` | `https://app-dev.sli.ke/rpc` | `https://asset-dev.sli.ke/upload` | `https://accounts-dev.sli.ke/login` |
|
|
255
|
+
|
|
256
|
+
---
|
|
257
|
+
|
|
258
|
+
## How it works
|
|
259
|
+
|
|
260
|
+
**Auth (`initialize()`)**:
|
|
261
|
+
- With `token`: calls `user.me` RPC to verify the token is valid.
|
|
262
|
+
- With `denmark_token`: POSTs `{type: 4, jwt: <jwt>, service}` to `/login` and reads `data.token` from the response.
|
|
263
|
+
|
|
264
|
+
**Chunked file upload (`register_media(file_path=...)`)**:
|
|
265
|
+
1. `media.register` RPC → returns `media_id` + short-lived upload JWT
|
|
266
|
+
2. File is split into **4 MiB chunks**, each POSTed as `multipart/form-data` with the JWT in the `token` header
|
|
267
|
+
3. The asset server assembles and processes the file. Failed chunks retry up to **3 times** with exponential backoff.
|
|
268
|
+
|
|
269
|
+
**Editor video (`register_media(editor_settings=...)`)**:
|
|
270
|
+
- `media.register` RPC with `type: "videoeditor"` and the editor spec. No bytes are uploaded — the asset server renders from the spec.
|
|
271
|
+
|
|
272
|
+
---
|
|
273
|
+
|
|
274
|
+
## Development
|
|
275
|
+
|
|
276
|
+
```bash
|
|
277
|
+
git clone <repo>
|
|
278
|
+
cd slike-media-package
|
|
279
|
+
python3 -m pip install -e .
|
|
280
|
+
|
|
281
|
+
# Run tests
|
|
282
|
+
python3 -m unittest test_slike -v
|
|
283
|
+
|
|
284
|
+
# Build wheel
|
|
285
|
+
pip install hatch && hatch build
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
---
|
|
289
|
+
|
|
290
|
+
## License
|
|
291
|
+
|
|
292
|
+
MIT
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
config.example.toml,sha256=taI6ywRC3EVDPKaq8o1gHFVAivpgReDFmS7dCJKwmtM,424
|
|
2
|
+
slike.py,sha256=uBgFUQ-dXpypZAlxCc-mEbPOCYKvDUDMLzYT-YsTgwo,21501
|
|
3
|
+
slikeupload.py,sha256=pPwrIHHAgseZNjWW59GIJT9tooo2nRwnBSvifnRSLFA,9691
|
|
4
|
+
slike-0.1.0.dist-info/METADATA,sha256=54nCiAWpuBIVDlH45hmYtBAFwubYMQkldxFMtwIsRXw,10315
|
|
5
|
+
slike-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
6
|
+
slike-0.1.0.dist-info/entry_points.txt,sha256=l9nOQLkAgzFxOKuO_zKctNiEKTaGJpiwdbk2tm0MiwI,44
|
|
7
|
+
slike-0.1.0.dist-info/licenses/LICENSE,sha256=HFQLYFYu0Av6U3UgWeNT16A-zdF3Vs3XE9a6J9q0xJ0,1069
|
|
8
|
+
slike-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Arpit Kumar
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
slike.py
ADDED
|
@@ -0,0 +1,606 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Slike Media SDK
|
|
3
|
+
A Python client for the Slike platform — supports direct Slike tokens or
|
|
4
|
+
Denmark JWT tokens (exchanged at /login for a Slike session token).
|
|
5
|
+
|
|
6
|
+
Usage:
|
|
7
|
+
from slike import SlikeMedia
|
|
8
|
+
|
|
9
|
+
client = SlikeMedia(token="...", environment="prod")
|
|
10
|
+
client.initialize() # validates token (raises on failure)
|
|
11
|
+
|
|
12
|
+
client.publish_media(url="...", title="T", description="D", type="gdrive")
|
|
13
|
+
client.register_media(file_path="x.mp4", title="T", description="D")
|
|
14
|
+
client.register_media(editor_settings={...}, title="T", description="D")
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
__version__ = "0.1.0"
|
|
18
|
+
__all__ = [
|
|
19
|
+
"SlikeMedia",
|
|
20
|
+
"SlikeAPIError",
|
|
21
|
+
"SlikeConfig",
|
|
22
|
+
"load_config",
|
|
23
|
+
"PRODUCTION_URL",
|
|
24
|
+
"DEVELOPMENT_URL",
|
|
25
|
+
"PRODUCTION_UPLOAD_URL",
|
|
26
|
+
"DEVELOPMENT_UPLOAD_URL",
|
|
27
|
+
"PRODUCTION_AUTH_URL",
|
|
28
|
+
"DEVELOPMENT_AUTH_URL",
|
|
29
|
+
"DENMARK_LOGIN_TYPE",
|
|
30
|
+
"DEFAULT_AUTH_SERVICE",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
import json
|
|
34
|
+
import logging
|
|
35
|
+
import os
|
|
36
|
+
import sys
|
|
37
|
+
import argparse
|
|
38
|
+
import uuid
|
|
39
|
+
import requests
|
|
40
|
+
from typing import Dict, Optional, Any, List
|
|
41
|
+
from dataclasses import dataclass
|
|
42
|
+
|
|
43
|
+
try:
|
|
44
|
+
import tomllib # Python 3.11+
|
|
45
|
+
except ImportError:
|
|
46
|
+
try:
|
|
47
|
+
import tomli as tomllib # type: ignore[no-redef]
|
|
48
|
+
except ImportError:
|
|
49
|
+
tomllib = None # type: ignore[assignment]
|
|
50
|
+
|
|
51
|
+
logger = logging.getLogger(__name__)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
# ---------------------------------------------------------------------------
|
|
55
|
+
# Constants
|
|
56
|
+
# ---------------------------------------------------------------------------
|
|
57
|
+
|
|
58
|
+
PRODUCTION_URL = "https://b2b.sli.ke/rpc"
|
|
59
|
+
DEVELOPMENT_URL = "https://app-dev.sli.ke/rpc"
|
|
60
|
+
|
|
61
|
+
PRODUCTION_UPLOAD_URL = "https://asset.sli.ke/upload"
|
|
62
|
+
DEVELOPMENT_UPLOAD_URL = "https://asset-dev.sli.ke/upload"
|
|
63
|
+
|
|
64
|
+
PRODUCTION_AUTH_URL = "https://accounts.sli.ke/login"
|
|
65
|
+
DEVELOPMENT_AUTH_URL = "https://accounts-dev.sli.ke/login"
|
|
66
|
+
|
|
67
|
+
# Chunk size: 4 MiB — mirrors Resumable.js default
|
|
68
|
+
CHUNK_SIZE = 4 * 1024 * 1024
|
|
69
|
+
|
|
70
|
+
# Denmark auth (mirrors the JS SDK)
|
|
71
|
+
DENMARK_LOGIN_TYPE = 4
|
|
72
|
+
DEFAULT_AUTH_SERVICE = "slike"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
_session = requests.Session()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class SlikeAPIError(Exception):
|
|
79
|
+
"""Custom exception for Slike API errors."""
|
|
80
|
+
pass
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
# ---------------------------------------------------------------------------
|
|
84
|
+
# Config (used by the CLI)
|
|
85
|
+
# ---------------------------------------------------------------------------
|
|
86
|
+
|
|
87
|
+
@dataclass
|
|
88
|
+
class SlikeConfig:
|
|
89
|
+
token: str = ""
|
|
90
|
+
environment: str = "prod"
|
|
91
|
+
file: str = ""
|
|
92
|
+
title: str = ""
|
|
93
|
+
desc: str = ""
|
|
94
|
+
asset_type: str = ""
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def load_config(config_path: Optional[str] = None) -> SlikeConfig:
|
|
98
|
+
"""
|
|
99
|
+
Load config from (in priority order):
|
|
100
|
+
1. Explicit path argument
|
|
101
|
+
2. SLIKE_CONFIG env var
|
|
102
|
+
3. ./config.toml (cwd) or ~/.slike/config.toml
|
|
103
|
+
|
|
104
|
+
Environment variable overrides (always win over file):
|
|
105
|
+
SLIKE_TOKEN, SLIKE_ENVIRONMENT
|
|
106
|
+
"""
|
|
107
|
+
cfg = SlikeConfig()
|
|
108
|
+
|
|
109
|
+
path = (
|
|
110
|
+
config_path
|
|
111
|
+
or os.environ.get("SLIKE_CONFIG")
|
|
112
|
+
or (os.path.join(os.getcwd(), "config.toml") if os.path.isfile(os.path.join(os.getcwd(), "config.toml")) else None)
|
|
113
|
+
or os.path.expanduser("~/.slike/config.toml")
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
if os.path.isfile(path):
|
|
117
|
+
logger.debug("Loaded config from %s", path)
|
|
118
|
+
if tomllib is not None:
|
|
119
|
+
with open(path, "rb") as f:
|
|
120
|
+
data = tomllib.load(f)
|
|
121
|
+
else:
|
|
122
|
+
data = {}
|
|
123
|
+
with open(path) as f:
|
|
124
|
+
for raw in f:
|
|
125
|
+
line = raw.strip()
|
|
126
|
+
if not line or line.startswith("#") or "=" not in line:
|
|
127
|
+
continue
|
|
128
|
+
key, _, value = line.partition("=")
|
|
129
|
+
data[key.strip().lower()] = value.strip().strip('"').strip("'")
|
|
130
|
+
cfg.token = data.get("token", "")
|
|
131
|
+
cfg.environment = data.get("environment", "prod")
|
|
132
|
+
cfg.file = data.get("file", "")
|
|
133
|
+
cfg.title = data.get("title", "")
|
|
134
|
+
cfg.desc = data.get("desc", "")
|
|
135
|
+
cfg.asset_type = data.get("asset_type", "")
|
|
136
|
+
|
|
137
|
+
if os.environ.get("SLIKE_TOKEN"):
|
|
138
|
+
cfg.token = os.environ["SLIKE_TOKEN"]
|
|
139
|
+
if os.environ.get("SLIKE_ENVIRONMENT"):
|
|
140
|
+
cfg.environment = os.environ["SLIKE_ENVIRONMENT"]
|
|
141
|
+
|
|
142
|
+
return cfg
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
# ---------------------------------------------------------------------------
|
|
146
|
+
# Internal helpers
|
|
147
|
+
# ---------------------------------------------------------------------------
|
|
148
|
+
|
|
149
|
+
def _normalize_env(environment: Optional[str]) -> str:
|
|
150
|
+
if not environment:
|
|
151
|
+
return "prod"
|
|
152
|
+
env = environment.lower()
|
|
153
|
+
if env in ("dev", "prod"):
|
|
154
|
+
return env
|
|
155
|
+
raise ValueError(f"Invalid environment: '{environment}'. Must be 'dev' or 'prod'")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _get_api_url(environment: str) -> str:
|
|
159
|
+
return DEVELOPMENT_URL if environment == "dev" else PRODUCTION_URL
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _get_auth_url(environment: str) -> str:
|
|
163
|
+
return DEVELOPMENT_AUTH_URL if environment == "dev" else PRODUCTION_AUTH_URL
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _build_headers() -> Dict[str, str]:
|
|
167
|
+
return {"Content-Type": "application/json"}
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _build_cookies(token: str, environment: str) -> Dict[str, str]:
|
|
171
|
+
"""Auth cookie name differs between envs (server reads token from cookie)."""
|
|
172
|
+
return {"token-dev": token} if environment == "dev" else {"token": token}
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _make_request(api_url: str, payload: Dict[str, Any], headers: Dict[str, str],
|
|
176
|
+
cookies: Optional[Dict[str, str]] = None) -> Dict[str, Any]:
|
|
177
|
+
try:
|
|
178
|
+
logger.debug("POST %s method=%s", api_url, payload.get("method"))
|
|
179
|
+
response = _session.post(api_url, json=payload, headers=headers,
|
|
180
|
+
cookies=cookies or {}, verify=True, timeout=30)
|
|
181
|
+
result = _parse_response(response)
|
|
182
|
+
_check_for_errors(response, result)
|
|
183
|
+
return result
|
|
184
|
+
except SlikeAPIError:
|
|
185
|
+
raise
|
|
186
|
+
except requests.exceptions.RequestException as e:
|
|
187
|
+
raise SlikeAPIError(f"Request to Slike failed: {str(e)}")
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _parse_response(response: requests.Response) -> Dict[str, Any]:
|
|
191
|
+
try:
|
|
192
|
+
return response.json()
|
|
193
|
+
except ValueError:
|
|
194
|
+
raise SlikeAPIError(f"Invalid JSON response: {response.text}")
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _check_for_errors(response: requests.Response, result: Dict[str, Any]) -> None:
|
|
198
|
+
if response.status_code >= 400:
|
|
199
|
+
msg = _extract_error_message(result.get("error") if isinstance(result, dict) else None,
|
|
200
|
+
response.text)
|
|
201
|
+
raise SlikeAPIError(f"HTTP {response.status_code}: {msg}")
|
|
202
|
+
|
|
203
|
+
if isinstance(result, dict) and "error" in result:
|
|
204
|
+
error_obj = result.get("error")
|
|
205
|
+
if not error_obj:
|
|
206
|
+
return
|
|
207
|
+
if isinstance(error_obj, dict):
|
|
208
|
+
error_msg = error_obj.get("message", "Unknown JSON-RPC error")
|
|
209
|
+
error_code = error_obj.get("code", "N/A")
|
|
210
|
+
error_data = error_obj.get("data", "")
|
|
211
|
+
full_error = f"{error_msg} (code: {error_code})"
|
|
212
|
+
if error_data:
|
|
213
|
+
full_error += f" - {error_data}"
|
|
214
|
+
else:
|
|
215
|
+
full_error = str(error_obj)
|
|
216
|
+
raise SlikeAPIError(f"JSON-RPC error: {full_error}")
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _extract_error_message(error_obj: Any, default: str) -> str:
|
|
220
|
+
if isinstance(error_obj, dict):
|
|
221
|
+
return error_obj.get("message", default)
|
|
222
|
+
return str(error_obj) if error_obj else default
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _validate_required_params(url: str, title: str, description: str, token: str) -> None:
|
|
226
|
+
if not url or not isinstance(url, str):
|
|
227
|
+
raise ValueError("url parameter is required and must be a non-empty string")
|
|
228
|
+
if not title or not isinstance(title, str):
|
|
229
|
+
raise ValueError("title parameter is required and must be a non-empty string")
|
|
230
|
+
if not description or not isinstance(description, str):
|
|
231
|
+
raise ValueError("description parameter is required and must be a non-empty string")
|
|
232
|
+
if not token:
|
|
233
|
+
raise ValueError("token is required")
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _build_publish_payload(
|
|
237
|
+
url: str, title: str, description: str, type: str,
|
|
238
|
+
tags: Optional[List[str]], preset_meta: Optional[str],
|
|
239
|
+
asset_type: Optional[str], auto_publish: bool,
|
|
240
|
+
) -> Dict[str, Any]:
|
|
241
|
+
params: Dict[str, Any] = {
|
|
242
|
+
"title": title, "desc": description, "url": url,
|
|
243
|
+
"type": type, "auto_publish": auto_publish,
|
|
244
|
+
}
|
|
245
|
+
if tags:
|
|
246
|
+
if not isinstance(tags, list):
|
|
247
|
+
raise ValueError("tags parameter must be a list of strings")
|
|
248
|
+
params["tags"] = tags
|
|
249
|
+
if preset_meta:
|
|
250
|
+
params["preset_meta"] = preset_meta
|
|
251
|
+
if asset_type:
|
|
252
|
+
params["asset_type"] = asset_type
|
|
253
|
+
return {
|
|
254
|
+
"jsonrpc": "2.0",
|
|
255
|
+
"id": uuid.uuid4().int & 0x7FFFFFFF,
|
|
256
|
+
"method": "media.publish",
|
|
257
|
+
"params": params,
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
# ---------------------------------------------------------------------------
|
|
262
|
+
# Auth
|
|
263
|
+
# ---------------------------------------------------------------------------
|
|
264
|
+
|
|
265
|
+
def _validate_slike_token(environment: str, token: str) -> None:
|
|
266
|
+
"""Call user.me to verify the token is valid. Raises SlikeAPIError on failure."""
|
|
267
|
+
payload = {
|
|
268
|
+
"jsonrpc": "2.0",
|
|
269
|
+
"id": uuid.uuid4().int & 0x7FFFFFFF,
|
|
270
|
+
"method": "user.me",
|
|
271
|
+
"params": {},
|
|
272
|
+
}
|
|
273
|
+
_make_request(
|
|
274
|
+
_get_api_url(environment),
|
|
275
|
+
payload,
|
|
276
|
+
_build_headers(),
|
|
277
|
+
_build_cookies(token, environment),
|
|
278
|
+
)
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def _authenticate_with_denmark(environment: str, denmark_token: str, service: str) -> str:
|
|
282
|
+
"""Exchange a Denmark JWT for a Slike session token via the /login endpoint."""
|
|
283
|
+
auth_url = _get_auth_url(environment)
|
|
284
|
+
body = {
|
|
285
|
+
"type": DENMARK_LOGIN_TYPE,
|
|
286
|
+
"jwt": denmark_token,
|
|
287
|
+
"service": service,
|
|
288
|
+
}
|
|
289
|
+
try:
|
|
290
|
+
response = _session.post(auth_url, json=body, headers=_build_headers(), timeout=30)
|
|
291
|
+
except requests.exceptions.RequestException as e:
|
|
292
|
+
raise SlikeAPIError(f"Auth network error: {str(e)}")
|
|
293
|
+
|
|
294
|
+
try:
|
|
295
|
+
data = response.json()
|
|
296
|
+
except ValueError:
|
|
297
|
+
raise SlikeAPIError(f"Auth returned non-JSON response: {response.text}")
|
|
298
|
+
|
|
299
|
+
if not response.ok:
|
|
300
|
+
msg = (
|
|
301
|
+
(data.get("message") if isinstance(data, dict) else None)
|
|
302
|
+
or (data.get("msg") if isinstance(data, dict) else None)
|
|
303
|
+
or response.reason
|
|
304
|
+
or "unknown"
|
|
305
|
+
)
|
|
306
|
+
raise SlikeAPIError(f"Auth failed: HTTP {response.status_code}: {msg}")
|
|
307
|
+
|
|
308
|
+
payload = data.get("data") if isinstance(data, dict) else None
|
|
309
|
+
token = payload.get("token") if isinstance(payload, dict) else None
|
|
310
|
+
if not isinstance(token, str) or not token:
|
|
311
|
+
raise SlikeAPIError("Auth failed: response missing 'data.token'")
|
|
312
|
+
return token
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
# ---------------------------------------------------------------------------
|
|
316
|
+
# Client
|
|
317
|
+
# ---------------------------------------------------------------------------
|
|
318
|
+
|
|
319
|
+
class SlikeMedia:
|
|
320
|
+
"""
|
|
321
|
+
Slike Media SDK client.
|
|
322
|
+
|
|
323
|
+
Initialize with either a direct Slike `token` or a `denmark_token` (JWT,
|
|
324
|
+
which gets exchanged at /login for a Slike session token), plus the
|
|
325
|
+
`environment`. Call `initialize()` once before invoking any method —
|
|
326
|
+
it validates the token (or performs the Denmark exchange) and raises
|
|
327
|
+
`SlikeAPIError` on failure.
|
|
328
|
+
"""
|
|
329
|
+
|
|
330
|
+
VERSION = __version__
|
|
331
|
+
|
|
332
|
+
def __init__(
|
|
333
|
+
self,
|
|
334
|
+
*,
|
|
335
|
+
token: Optional[str] = None,
|
|
336
|
+
denmark_token: Optional[str] = None,
|
|
337
|
+
service: Optional[str] = None,
|
|
338
|
+
environment: Optional[str] = None,
|
|
339
|
+
):
|
|
340
|
+
if not token and not denmark_token:
|
|
341
|
+
raise TypeError("SlikeMedia: token or denmark_token is required")
|
|
342
|
+
self.environment = _normalize_env(environment)
|
|
343
|
+
self._input_token = (token or "").strip() or None
|
|
344
|
+
self._denmark_token = (denmark_token or "").strip() or None
|
|
345
|
+
if token and not self._input_token:
|
|
346
|
+
raise TypeError("SlikeMedia: token cannot be empty")
|
|
347
|
+
if denmark_token and not self._denmark_token:
|
|
348
|
+
raise TypeError("SlikeMedia: denmark_token cannot be empty")
|
|
349
|
+
self._service = service or DEFAULT_AUTH_SERVICE
|
|
350
|
+
self._token: Optional[str] = None
|
|
351
|
+
self._initialized = False
|
|
352
|
+
|
|
353
|
+
# ------------------------------------------------------------------
|
|
354
|
+
# Lifecycle
|
|
355
|
+
# ------------------------------------------------------------------
|
|
356
|
+
|
|
357
|
+
def initialize(self) -> None:
|
|
358
|
+
"""Validate the token (or exchange the Denmark JWT). Raises on failure."""
|
|
359
|
+
if self._initialized:
|
|
360
|
+
return
|
|
361
|
+
if self._input_token:
|
|
362
|
+
_validate_slike_token(self.environment, self._input_token)
|
|
363
|
+
self._token = self._input_token
|
|
364
|
+
else:
|
|
365
|
+
assert self._denmark_token
|
|
366
|
+
self._token = _authenticate_with_denmark(
|
|
367
|
+
self.environment, self._denmark_token, self._service
|
|
368
|
+
)
|
|
369
|
+
self._initialized = True
|
|
370
|
+
|
|
371
|
+
@property
|
|
372
|
+
def initialized(self) -> bool:
|
|
373
|
+
return self._initialized
|
|
374
|
+
|
|
375
|
+
@property
|
|
376
|
+
def token(self) -> Optional[str]:
|
|
377
|
+
"""The active Slike session token (None until `initialize()` succeeds)."""
|
|
378
|
+
return self._token
|
|
379
|
+
|
|
380
|
+
def _require_token(self) -> str:
|
|
381
|
+
if not self._initialized or not self._token:
|
|
382
|
+
raise SlikeAPIError(
|
|
383
|
+
"SlikeMedia is not initialized. Call initialize() before using SDK methods."
|
|
384
|
+
)
|
|
385
|
+
return self._token
|
|
386
|
+
|
|
387
|
+
# ------------------------------------------------------------------
|
|
388
|
+
# Methods
|
|
389
|
+
# ------------------------------------------------------------------
|
|
390
|
+
|
|
391
|
+
def publish_media(
|
|
392
|
+
self,
|
|
393
|
+
*,
|
|
394
|
+
url: str,
|
|
395
|
+
title: str,
|
|
396
|
+
description: str,
|
|
397
|
+
type: str = "url",
|
|
398
|
+
asset_type: Optional[str] = None,
|
|
399
|
+
tags: Optional[List[str]] = None,
|
|
400
|
+
preset_meta: Optional[str] = None,
|
|
401
|
+
auto_publish: bool = True,
|
|
402
|
+
) -> Dict[str, Any]:
|
|
403
|
+
"""Publish media by URL (Google Drive, YouTube, direct link)."""
|
|
404
|
+
token = self._require_token()
|
|
405
|
+
_validate_required_params(url, title, description, token)
|
|
406
|
+
payload = _build_publish_payload(
|
|
407
|
+
url, title, description, type, tags, preset_meta, asset_type, auto_publish,
|
|
408
|
+
)
|
|
409
|
+
return _make_request(
|
|
410
|
+
_get_api_url(self.environment),
|
|
411
|
+
payload,
|
|
412
|
+
_build_headers(),
|
|
413
|
+
_build_cookies(token, self.environment),
|
|
414
|
+
)
|
|
415
|
+
|
|
416
|
+
def register_media(
|
|
417
|
+
self,
|
|
418
|
+
*,
|
|
419
|
+
title: str,
|
|
420
|
+
description: str,
|
|
421
|
+
file_path: Optional[str] = None,
|
|
422
|
+
editor_settings: Optional[Dict[str, Any]] = None,
|
|
423
|
+
asset_type: str = "video",
|
|
424
|
+
tags: Optional[List[str]] = None,
|
|
425
|
+
preset_config: Optional[Dict] = None,
|
|
426
|
+
downloads: Optional[Dict] = None,
|
|
427
|
+
islive: int = 0,
|
|
428
|
+
media_type: Any = None,
|
|
429
|
+
source: Optional[str] = None,
|
|
430
|
+
fid: Optional[str] = None,
|
|
431
|
+
on_progress: Optional[Any] = None,
|
|
432
|
+
) -> Dict[str, Any]:
|
|
433
|
+
"""
|
|
434
|
+
Register media on Slike. Provide exactly one of:
|
|
435
|
+
- `file_path` → register + chunked upload of a local file
|
|
436
|
+
- `editor_settings` → register an editor-generated video (no bytes)
|
|
437
|
+
"""
|
|
438
|
+
token = self._require_token()
|
|
439
|
+
from slikeupload import _do_register_media
|
|
440
|
+
return _do_register_media(
|
|
441
|
+
token=token,
|
|
442
|
+
environment=self.environment,
|
|
443
|
+
title=title,
|
|
444
|
+
description=description,
|
|
445
|
+
file_path=file_path,
|
|
446
|
+
editor_settings=editor_settings,
|
|
447
|
+
asset_type=asset_type,
|
|
448
|
+
tags=tags,
|
|
449
|
+
preset_config=preset_config,
|
|
450
|
+
downloads=downloads,
|
|
451
|
+
islive=islive,
|
|
452
|
+
media_type=media_type,
|
|
453
|
+
source=source,
|
|
454
|
+
fid=fid,
|
|
455
|
+
on_progress=on_progress,
|
|
456
|
+
)
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
# ---------------------------------------------------------------------------
|
|
460
|
+
# CLI
|
|
461
|
+
# ---------------------------------------------------------------------------
|
|
462
|
+
|
|
463
|
+
def _cli_progress(done: int, total: int) -> None:
|
|
464
|
+
pct = int(done / total * 100)
|
|
465
|
+
bar = "#" * (pct // 2)
|
|
466
|
+
print(f"\r [{bar:<50}] {done}/{total} chunks ({pct}%)", end="", flush=True)
|
|
467
|
+
if done == total:
|
|
468
|
+
print()
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def main() -> None:
|
|
472
|
+
"""slike-upload — CLI for uploading media to Slike."""
|
|
473
|
+
parser = argparse.ArgumentParser(
|
|
474
|
+
prog="slike-upload",
|
|
475
|
+
description="Upload a media file to the Slike platform.",
|
|
476
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
477
|
+
epilog="""
|
|
478
|
+
Examples:
|
|
479
|
+
# Upload using config file
|
|
480
|
+
slike-upload video.mp4 --title "My Video" --desc "A description"
|
|
481
|
+
|
|
482
|
+
# Override environment on the fly
|
|
483
|
+
slike-upload video.mp4 --title "Test" --desc "Test" --env dev
|
|
484
|
+
|
|
485
|
+
# Pass token directly (skips config file)
|
|
486
|
+
slike-upload video.mp4 --title "My Video" --desc "Desc" --token abc123
|
|
487
|
+
|
|
488
|
+
# Use a Denmark JWT instead of a Slike token
|
|
489
|
+
slike-upload video.mp4 --title "T" --desc "D" --denmark-token <jwt>
|
|
490
|
+
|
|
491
|
+
# Publish by URL (no file upload)
|
|
492
|
+
slike-upload --url https://drive.google.com/file/d/... --type gdrive \\
|
|
493
|
+
--title "My Video" --desc "Desc"
|
|
494
|
+
""",
|
|
495
|
+
)
|
|
496
|
+
|
|
497
|
+
parser.add_argument("file", nargs="?", help="Local file path to upload")
|
|
498
|
+
parser.add_argument("--url", help="Remote media URL (for publish-by-URL mode)")
|
|
499
|
+
parser.add_argument("--type", default="url", dest="media_type",
|
|
500
|
+
help="Media type for URL mode: gdrive, youtube, url (default: url)")
|
|
501
|
+
|
|
502
|
+
parser.add_argument("--title", default=None, help="Media title")
|
|
503
|
+
parser.add_argument("--desc", default=None, help="Media description")
|
|
504
|
+
parser.add_argument("--asset-type", default=None, help="Asset type, e.g. video, shorts")
|
|
505
|
+
parser.add_argument("--tags", default=None, help="Comma-separated tags")
|
|
506
|
+
parser.add_argument("--no-publish", action="store_true",
|
|
507
|
+
help="Do not auto-publish after URL publish")
|
|
508
|
+
parser.add_argument("--payload", default=None,
|
|
509
|
+
help='JSON metadata for file upload '
|
|
510
|
+
'(title, desc, asset_type, tags, preset_config, '
|
|
511
|
+
'downloads, islive, type, source). '
|
|
512
|
+
'CLI flags take precedence over payload values.')
|
|
513
|
+
|
|
514
|
+
parser.add_argument("--token", default=None, help="Slike auth token (overrides config)")
|
|
515
|
+
parser.add_argument("--denmark-token", default=None, dest="denmark_token",
|
|
516
|
+
help="Denmark JWT (exchanged for a Slike session token)")
|
|
517
|
+
parser.add_argument("--service", default=None,
|
|
518
|
+
help=f"Service name for Denmark auth (default: {DEFAULT_AUTH_SERVICE})")
|
|
519
|
+
parser.add_argument("--env", default=None, dest="environment",
|
|
520
|
+
help="Environment: dev or prod (overrides config)")
|
|
521
|
+
parser.add_argument("--config", default=None, help="Path to config file")
|
|
522
|
+
|
|
523
|
+
args = parser.parse_args()
|
|
524
|
+
|
|
525
|
+
cfg = load_config(args.config)
|
|
526
|
+
token = args.token or (cfg.token if not args.denmark_token else None)
|
|
527
|
+
env = args.environment or cfg.environment
|
|
528
|
+
|
|
529
|
+
if not token and not args.denmark_token:
|
|
530
|
+
print("Error: auth required. Set --token or --denmark-token, "
|
|
531
|
+
"SLIKE_TOKEN, or token in config.toml")
|
|
532
|
+
sys.exit(1)
|
|
533
|
+
|
|
534
|
+
payload_data: Dict[str, Any] = {}
|
|
535
|
+
if args.payload:
|
|
536
|
+
try:
|
|
537
|
+
payload_data = json.loads(args.payload)
|
|
538
|
+
except json.JSONDecodeError as e:
|
|
539
|
+
print(f"Error: --payload is not valid JSON: {e}")
|
|
540
|
+
sys.exit(1)
|
|
541
|
+
|
|
542
|
+
title = args.title or payload_data.get("title", "")
|
|
543
|
+
desc = args.desc or payload_data.get("desc", "")
|
|
544
|
+
asset_type = args.asset_type or payload_data.get("asset_type", "video")
|
|
545
|
+
tags = ([t.strip() for t in args.tags.split(",")] if args.tags
|
|
546
|
+
else payload_data.get("tags"))
|
|
547
|
+
preset_config = payload_data.get("preset_config")
|
|
548
|
+
downloads = payload_data.get("downloads")
|
|
549
|
+
islive = payload_data.get("islive", 0)
|
|
550
|
+
media_type = payload_data.get("type", 0)
|
|
551
|
+
source = payload_data.get("source", "uploadsdk")
|
|
552
|
+
|
|
553
|
+
client = SlikeMedia(
|
|
554
|
+
token=token,
|
|
555
|
+
denmark_token=args.denmark_token,
|
|
556
|
+
service=args.service,
|
|
557
|
+
environment=env,
|
|
558
|
+
)
|
|
559
|
+
try:
|
|
560
|
+
client.initialize()
|
|
561
|
+
except SlikeAPIError as e:
|
|
562
|
+
print(f"Error: failed to initialize SlikeMedia: {e}")
|
|
563
|
+
sys.exit(1)
|
|
564
|
+
|
|
565
|
+
if args.url:
|
|
566
|
+
if not title or not desc:
|
|
567
|
+
print("Error: --title and --desc are required for URL publish mode")
|
|
568
|
+
sys.exit(1)
|
|
569
|
+
print(f"Publishing via URL ({env})…")
|
|
570
|
+
result = client.publish_media(
|
|
571
|
+
url=args.url, title=title, description=desc,
|
|
572
|
+
type=args.media_type, asset_type=asset_type, tags=tags,
|
|
573
|
+
auto_publish=not args.no_publish,
|
|
574
|
+
)
|
|
575
|
+
r = result.get("result") or result
|
|
576
|
+
print(f"Done. Media ID: {r.get('id', '?')}")
|
|
577
|
+
return
|
|
578
|
+
|
|
579
|
+
if not args.file:
|
|
580
|
+
parser.error("Provide a file path or --url")
|
|
581
|
+
if not title or not desc:
|
|
582
|
+
print("Error: title and desc are required (via --title/--desc or --payload)")
|
|
583
|
+
sys.exit(1)
|
|
584
|
+
if not os.path.isfile(args.file):
|
|
585
|
+
print(f"Error: file not found: {args.file}")
|
|
586
|
+
sys.exit(1)
|
|
587
|
+
|
|
588
|
+
print(f"Uploading {os.path.basename(args.file)} ({env})…")
|
|
589
|
+
result = client.register_media(
|
|
590
|
+
file_path=args.file,
|
|
591
|
+
title=title,
|
|
592
|
+
description=desc,
|
|
593
|
+
asset_type=asset_type,
|
|
594
|
+
tags=tags,
|
|
595
|
+
preset_config=preset_config,
|
|
596
|
+
downloads=downloads,
|
|
597
|
+
islive=islive,
|
|
598
|
+
media_type=media_type,
|
|
599
|
+
source=source,
|
|
600
|
+
on_progress=_cli_progress,
|
|
601
|
+
)
|
|
602
|
+
print(f"Done. Media ID: {result.get('id', '?')}")
|
|
603
|
+
|
|
604
|
+
|
|
605
|
+
if __name__ == "__main__":
|
|
606
|
+
main()
|
slikeupload.py
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Internal: chunked file upload + media.register payload assembly.
|
|
3
|
+
|
|
4
|
+
Used by `SlikeMedia.register_media`. Not part of the public API.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import math
|
|
8
|
+
import mimetypes
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
import time
|
|
12
|
+
import uuid
|
|
13
|
+
from typing import Any, Dict, List, Optional
|
|
14
|
+
|
|
15
|
+
import requests
|
|
16
|
+
|
|
17
|
+
from slike import (
|
|
18
|
+
CHUNK_SIZE,
|
|
19
|
+
DEVELOPMENT_UPLOAD_URL,
|
|
20
|
+
PRODUCTION_UPLOAD_URL,
|
|
21
|
+
SlikeAPIError,
|
|
22
|
+
_build_cookies,
|
|
23
|
+
_build_headers,
|
|
24
|
+
_get_api_url,
|
|
25
|
+
_make_request,
|
|
26
|
+
_session,
|
|
27
|
+
logger,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
__all__: List[str] = []
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# ---------------------------------------------------------------------------
|
|
34
|
+
# URL + payload builders
|
|
35
|
+
# ---------------------------------------------------------------------------
|
|
36
|
+
|
|
37
|
+
def _get_upload_url(environment: str) -> str:
|
|
38
|
+
return DEVELOPMENT_UPLOAD_URL if environment == "dev" else PRODUCTION_UPLOAD_URL
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _build_register_payload(
|
|
42
|
+
title: str,
|
|
43
|
+
description: str,
|
|
44
|
+
asset_type: str,
|
|
45
|
+
tags: Optional[List[str]],
|
|
46
|
+
preset_config: Optional[Dict],
|
|
47
|
+
downloads: Optional[Dict],
|
|
48
|
+
islive: int,
|
|
49
|
+
source: Optional[str],
|
|
50
|
+
media_type: Any,
|
|
51
|
+
fid: Optional[str],
|
|
52
|
+
file_path: Optional[str],
|
|
53
|
+
editor_settings: Optional[Dict[str, Any]],
|
|
54
|
+
) -> Dict[str, Any]:
|
|
55
|
+
if file_path:
|
|
56
|
+
filename = os.path.basename(file_path)
|
|
57
|
+
file_size = os.path.getsize(file_path)
|
|
58
|
+
params: Dict[str, Any] = {
|
|
59
|
+
"fid": fid or f"{file_size}{filename}",
|
|
60
|
+
"title": title,
|
|
61
|
+
"desc": description,
|
|
62
|
+
"source": source or "uploadsdk",
|
|
63
|
+
"name": "media",
|
|
64
|
+
"type": 0 if media_type is None else media_type,
|
|
65
|
+
"islive": islive,
|
|
66
|
+
"asset_type": asset_type,
|
|
67
|
+
}
|
|
68
|
+
else:
|
|
69
|
+
params = {
|
|
70
|
+
"name": "media",
|
|
71
|
+
"type": "videoeditor" if media_type is None else media_type,
|
|
72
|
+
"source": source or "videoeditor",
|
|
73
|
+
"islive": islive,
|
|
74
|
+
"title": title,
|
|
75
|
+
"desc": description,
|
|
76
|
+
"fid": fid or str(int(time.time() * 1000)),
|
|
77
|
+
"asset_type": asset_type,
|
|
78
|
+
"editor_settings": editor_settings,
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
if tags:
|
|
82
|
+
if not isinstance(tags, list):
|
|
83
|
+
raise ValueError("tags parameter must be a list of strings")
|
|
84
|
+
params["tags"] = tags
|
|
85
|
+
if preset_config:
|
|
86
|
+
params["preset_config"] = preset_config
|
|
87
|
+
if downloads:
|
|
88
|
+
params["downloads"] = downloads
|
|
89
|
+
|
|
90
|
+
return {
|
|
91
|
+
"jsonrpc": "2.0",
|
|
92
|
+
"id": uuid.uuid4().int & 0x7FFFFFFF,
|
|
93
|
+
"method": "media.register",
|
|
94
|
+
"params": params,
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
# ---------------------------------------------------------------------------
|
|
99
|
+
# Chunk upload
|
|
100
|
+
# ---------------------------------------------------------------------------
|
|
101
|
+
|
|
102
|
+
def _build_resumable_identifier(filename: str, file_size: int) -> str:
|
|
103
|
+
"""Build a deterministic Resumable.js uniqueIdentifier, matching the frontend logic."""
|
|
104
|
+
sanitized = re.sub(r"[.\s]", "", filename)
|
|
105
|
+
return f"{file_size}-{sanitized}"
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _detect_mime_type(file_path: str) -> str:
|
|
109
|
+
mime, _ = mimetypes.guess_type(file_path)
|
|
110
|
+
return mime or "application/octet-stream"
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _upload_chunk(
|
|
114
|
+
upload_url: str,
|
|
115
|
+
media_id: str,
|
|
116
|
+
upload_jwt: str,
|
|
117
|
+
chunk_data: bytes,
|
|
118
|
+
chunk_number: int,
|
|
119
|
+
total_chunks: int,
|
|
120
|
+
file_size: int,
|
|
121
|
+
filename: str,
|
|
122
|
+
mime_type: str,
|
|
123
|
+
identifier: str,
|
|
124
|
+
) -> None:
|
|
125
|
+
"""Upload a single chunk using Resumable.js-compatible multipart form-data."""
|
|
126
|
+
files = [
|
|
127
|
+
("resumableChunkNumber", (None, str(chunk_number))),
|
|
128
|
+
("resumableChunkSize", (None, str(CHUNK_SIZE))),
|
|
129
|
+
("resumableCurrentChunkSize", (None, str(len(chunk_data)))),
|
|
130
|
+
("resumableTotalSize", (None, str(file_size))),
|
|
131
|
+
("resumableType", (None, mime_type)),
|
|
132
|
+
("resumableIdentifier", (None, identifier)),
|
|
133
|
+
("resumableFilename", (None, filename)),
|
|
134
|
+
("resumableRelativePath", (None, filename)),
|
|
135
|
+
("resumableTotalChunks", (None, str(total_chunks))),
|
|
136
|
+
("method", (None, "asset.file")),
|
|
137
|
+
("entity", (None, media_id)),
|
|
138
|
+
("key", (None, "media")),
|
|
139
|
+
("file", (filename, chunk_data, mime_type)),
|
|
140
|
+
]
|
|
141
|
+
try:
|
|
142
|
+
response = _session.post(
|
|
143
|
+
upload_url,
|
|
144
|
+
files=files,
|
|
145
|
+
headers={"token": upload_jwt},
|
|
146
|
+
verify=True,
|
|
147
|
+
timeout=120,
|
|
148
|
+
)
|
|
149
|
+
if response.status_code >= 400:
|
|
150
|
+
raise SlikeAPIError(
|
|
151
|
+
f"Chunk {chunk_number}/{total_chunks} upload failed: "
|
|
152
|
+
f"HTTP {response.status_code} — {response.text}"
|
|
153
|
+
)
|
|
154
|
+
except SlikeAPIError:
|
|
155
|
+
raise
|
|
156
|
+
except requests.exceptions.RequestException as e:
|
|
157
|
+
raise SlikeAPIError(f"Chunk {chunk_number}/{total_chunks} upload failed: {str(e)}")
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
_RETRY_ATTEMPTS = 3
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _upload_chunk_with_retry(
|
|
164
|
+
upload_url: str,
|
|
165
|
+
media_id: str,
|
|
166
|
+
upload_jwt: str,
|
|
167
|
+
chunk_data: bytes,
|
|
168
|
+
chunk_number: int,
|
|
169
|
+
total_chunks: int,
|
|
170
|
+
file_size: int,
|
|
171
|
+
filename: str,
|
|
172
|
+
mime_type: str,
|
|
173
|
+
identifier: str,
|
|
174
|
+
) -> None:
|
|
175
|
+
"""Retry wrapper around _upload_chunk with exponential backoff."""
|
|
176
|
+
last_exc: Optional[Exception] = None
|
|
177
|
+
for attempt in range(1, _RETRY_ATTEMPTS + 1):
|
|
178
|
+
try:
|
|
179
|
+
_upload_chunk(
|
|
180
|
+
upload_url, media_id, upload_jwt,
|
|
181
|
+
chunk_data, chunk_number, total_chunks,
|
|
182
|
+
file_size, filename, mime_type, identifier,
|
|
183
|
+
)
|
|
184
|
+
return
|
|
185
|
+
except SlikeAPIError as exc:
|
|
186
|
+
last_exc = exc
|
|
187
|
+
if attempt < _RETRY_ATTEMPTS:
|
|
188
|
+
wait = 2 ** (attempt - 1)
|
|
189
|
+
logger.warning(
|
|
190
|
+
"Chunk %d/%d failed (attempt %d/%d), retrying in %ds: %s",
|
|
191
|
+
chunk_number, total_chunks, attempt, _RETRY_ATTEMPTS, wait, exc,
|
|
192
|
+
)
|
|
193
|
+
time.sleep(wait)
|
|
194
|
+
raise SlikeAPIError(
|
|
195
|
+
f"Chunk {chunk_number}/{total_chunks} failed after {_RETRY_ATTEMPTS} attempts: {last_exc}"
|
|
196
|
+
) from last_exc
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _upload_file_chunks(
|
|
200
|
+
upload_url: str,
|
|
201
|
+
media_id: str,
|
|
202
|
+
upload_jwt: str,
|
|
203
|
+
file_path: str,
|
|
204
|
+
on_progress: Optional[Any],
|
|
205
|
+
) -> None:
|
|
206
|
+
"""Read file and upload it in CHUNK_SIZE pieces sequentially."""
|
|
207
|
+
file_size = os.path.getsize(file_path)
|
|
208
|
+
filename = os.path.basename(file_path)
|
|
209
|
+
mime_type = _detect_mime_type(file_path)
|
|
210
|
+
total_chunks = math.ceil(file_size / CHUNK_SIZE)
|
|
211
|
+
identifier = _build_resumable_identifier(filename, file_size)
|
|
212
|
+
|
|
213
|
+
with open(file_path, "rb") as fh:
|
|
214
|
+
for chunk_number in range(1, total_chunks + 1):
|
|
215
|
+
chunk_data = fh.read(CHUNK_SIZE)
|
|
216
|
+
if not chunk_data:
|
|
217
|
+
break
|
|
218
|
+
logger.debug("Uploading chunk %d/%d", chunk_number, total_chunks)
|
|
219
|
+
_upload_chunk_with_retry(
|
|
220
|
+
upload_url, media_id, upload_jwt,
|
|
221
|
+
chunk_data, chunk_number, total_chunks,
|
|
222
|
+
file_size, filename, mime_type, identifier,
|
|
223
|
+
)
|
|
224
|
+
if callable(on_progress):
|
|
225
|
+
on_progress(chunk_number, total_chunks)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
# ---------------------------------------------------------------------------
|
|
229
|
+
# Internal entry point — called from SlikeMedia.register_media
|
|
230
|
+
# ---------------------------------------------------------------------------
|
|
231
|
+
|
|
232
|
+
def _do_register_media(
|
|
233
|
+
*,
|
|
234
|
+
token: str,
|
|
235
|
+
environment: str,
|
|
236
|
+
title: str,
|
|
237
|
+
description: str,
|
|
238
|
+
file_path: Optional[str] = None,
|
|
239
|
+
editor_settings: Optional[Dict[str, Any]] = None,
|
|
240
|
+
asset_type: str = "video",
|
|
241
|
+
tags: Optional[List[str]] = None,
|
|
242
|
+
preset_config: Optional[Dict] = None,
|
|
243
|
+
downloads: Optional[Dict] = None,
|
|
244
|
+
islive: int = 0,
|
|
245
|
+
media_type: Any = None,
|
|
246
|
+
source: Optional[str] = None,
|
|
247
|
+
fid: Optional[str] = None,
|
|
248
|
+
on_progress: Optional[Any] = None,
|
|
249
|
+
) -> Dict[str, Any]:
|
|
250
|
+
if not title or not isinstance(title, str):
|
|
251
|
+
raise ValueError("title parameter is required and must be a non-empty string")
|
|
252
|
+
if not description or not isinstance(description, str):
|
|
253
|
+
raise ValueError("description parameter is required and must be a non-empty string")
|
|
254
|
+
if bool(file_path) == bool(editor_settings):
|
|
255
|
+
raise ValueError("Provide exactly one of file_path or editor_settings")
|
|
256
|
+
|
|
257
|
+
if file_path:
|
|
258
|
+
if not isinstance(file_path, str):
|
|
259
|
+
raise ValueError("file_path must be a string")
|
|
260
|
+
if not os.path.isfile(file_path):
|
|
261
|
+
raise ValueError(f"file_path does not exist or is not a file: '{file_path}'")
|
|
262
|
+
else:
|
|
263
|
+
if not isinstance(editor_settings, dict) or not editor_settings:
|
|
264
|
+
raise ValueError("editor_settings must be a non-empty dict")
|
|
265
|
+
|
|
266
|
+
payload = _build_register_payload(
|
|
267
|
+
title=title,
|
|
268
|
+
description=description,
|
|
269
|
+
asset_type=asset_type,
|
|
270
|
+
tags=tags,
|
|
271
|
+
preset_config=preset_config,
|
|
272
|
+
downloads=downloads,
|
|
273
|
+
islive=islive,
|
|
274
|
+
source=source,
|
|
275
|
+
media_type=media_type,
|
|
276
|
+
fid=fid,
|
|
277
|
+
file_path=file_path,
|
|
278
|
+
editor_settings=editor_settings,
|
|
279
|
+
)
|
|
280
|
+
api_url = _get_api_url(environment)
|
|
281
|
+
headers = _build_headers()
|
|
282
|
+
cookies = _build_cookies(token, environment)
|
|
283
|
+
result = _make_request(api_url, payload, headers, cookies)
|
|
284
|
+
|
|
285
|
+
result_data = result.get("result") or {}
|
|
286
|
+
media_id = result_data.get("id")
|
|
287
|
+
upload_jwt = result_data.get("jwt")
|
|
288
|
+
if not media_id or not upload_jwt:
|
|
289
|
+
raise SlikeAPIError("media.register did not return expected 'id' and 'jwt' fields")
|
|
290
|
+
|
|
291
|
+
if file_path:
|
|
292
|
+
upload_url = _get_upload_url(environment)
|
|
293
|
+
_upload_file_chunks(upload_url, media_id, upload_jwt, file_path, on_progress)
|
|
294
|
+
|
|
295
|
+
return result_data
|