fiftyeight 1.0.0__tar.gz

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.
@@ -0,0 +1,25 @@
1
+ # Secrets
2
+ .env
3
+ .env.*
4
+ !.env.example
5
+
6
+ # Python
7
+ __pycache__/
8
+ *.pyc
9
+ .venv/
10
+ .pytest_cache/
11
+ .ruff_cache/
12
+ *.db
13
+
14
+ # Node
15
+ node_modules/
16
+ .next/
17
+ .vercel/
18
+ out/
19
+
20
+ # OS
21
+ .DS_Store
22
+
23
+ # Local demo stack data
24
+ apps/api/demo/.data/
25
+ infra/hosted/storage.env
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Fifty Eight
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.
@@ -0,0 +1,181 @@
1
+ Metadata-Version: 2.5
2
+ Name: fiftyeight
3
+ Version: 1.0.0
4
+ Summary: Command line for Fifty Eight: hire your AI team, publish and schedule short videos, approve and measure them
5
+ Project-URL: Homepage, https://fiftyeight.app
6
+ Project-URL: Documentation, https://fiftyeight.app/docs/cli
7
+ Author: Fifty Eight
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: ai,api,cli,fifty eight,instagram,short video,social media,tiktok,youtube
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: End Users/Desktop
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Internet
22
+ Classifier: Topic :: Multimedia :: Video
23
+ Classifier: Topic :: Utilities
24
+ Requires-Python: >=3.11
25
+ Requires-Dist: httpx>=0.28.1
26
+ Requires-Dist: typer>=0.15.0
27
+ Description-Content-Type: text/markdown
28
+
29
+ # fiftyeight: the Fifty Eight command line
30
+
31
+ Fifty Eight is your AI team for short videos. You hire the agents you need (Strategist, Editor, Community manager, UGC
32
+ Creator, Team leader; the Publisher, the Analyst and the Optimizer come with every account) and they plan, make, post
33
+ and measure your videos on Instagram, TikTok and YouTube.
34
+
35
+ `fiftyeight` lets you run that team from a terminal or a script: see and change your team, publish and schedule posts,
36
+ approve what your team prepared, top up your video balance, set up webhooks and read your results. Every command is
37
+ one or two calls to the public REST API, with the same rules as the app. The API, MCP and this command line are
38
+ included in every account. Full docs: https://fiftyeight.app/docs/cli
39
+
40
+ ## Install
41
+
42
+ Needs Python 3.11 or newer.
43
+
44
+ ```sh
45
+ pipx install fiftyeight # or: uv tool install fiftyeight
46
+ fiftyeight --version
47
+ ```
48
+
49
+ ## Sign in
50
+
51
+ An owner or admin creates the workspace's API key in **Settings › Developers** and picks what it may do:
52
+
53
+ | Scope | What the key may do |
54
+ |---|---|
55
+ | `read` | Read everything: posts, accounts, team, results, prices, balance. |
56
+ | `write` | Drafts, automations, brands, knowledge, uploads, questions to agents, webhooks. Never publishes or spends. |
57
+ | `publish` | Post, schedule, change or cancel posts; approve videos and posts waiting for you. |
58
+ | `billing` | Confirm anything that costs money (owner only). |
59
+ | `brief` | Change the brand brief. |
60
+ | `ads` | The Ads manager and boosts (a boost also needs `billing`). |
61
+
62
+ A new key gets `read` only unless you tick more. A workspace has one key: rotate it to get a new secret.
63
+
64
+ ```sh
65
+ fiftyeight auth login # asks for the key, checks it, saves it
66
+ fiftyeight auth status
67
+ ```
68
+
69
+ The key is saved in `~/.config/fiftyeight/config.json`, readable only by you. For CI or scripts, set
70
+ `FIFTYEIGHT_API_KEY` instead. `FIFTYEIGHT_API_URL` (or `--api-url`) points the command line at another API.
71
+
72
+ ## Your team
73
+
74
+ ```sh
75
+ fiftyeight prices # every price
76
+ fiftyeight prices --agent team_leader --accounts 2 # what a team costs a month
77
+ fiftyeight team show # who is hired, paused, their freedom, the monthly bill
78
+ fiftyeight team preview --hire editor # the bill with a change (nothing changes)
79
+ fiftyeight team hire strategist # shows the price, then asks "Confirm? [y/N]"
80
+ fiftyeight team hire creator --top-up 20 # the UGC Creator starts with a video top-up
81
+ fiftyeight team pause community
82
+ fiftyeight team resume community
83
+ fiftyeight team let-go editor # works until the end of the month you paid
84
+ fiftyeight team freedom editor do_and_tell # ask_first, do_and_tell or on_its_own
85
+ fiftyeight team leader on --budget 50 --videos 8 --seconds 30
86
+ fiftyeight team leader setup --videos 12
87
+ fiftyeight team leader off
88
+ ```
89
+
90
+ ### Anything that costs money: preview, then confirm
91
+
92
+ Hiring, letting go, pausing, resuming, the Team leader, top-ups, AI avatar videos and ad boosts all work the same way:
93
+
94
+ 1. The command asks for a preview. Nothing is charged. You see each line, what is charged today and your new
95
+ monthly bill.
96
+ 2. It asks `Confirm? [y/N]`. Only a yes confirms (paid up front: the agent starts once paid).
97
+
98
+ `--yes` confirms without asking (for scripts), `--dry-run` shows the preview and stops. Confirming needs a key with the
99
+ `billing` scope, and each key has a daily spending limit (an owner sets it in Settings › Developers). A preview is
100
+ valid 10 minutes and confirms once. For scripts, the raw calls are there too:
101
+
102
+ ```sh
103
+ fiftyeight spend preview hire --agent editor # prints the token
104
+ fiftyeight spend confirm TOKEN
105
+ fiftyeight spend preview boost --approval APPROVAL_ID
106
+ ```
107
+
108
+ ## Videos, balance and approvals
109
+
110
+ ```sh
111
+ fiftyeight balance # what is left on the video balance
112
+ fiftyeight balance top-up 25 # $25, preview then confirm
113
+ fiftyeight videos draft "Our new winter menu" --seconds 30 # an AI avatar video ($0.17 a second)
114
+ fiftyeight approvals list # what waits for you
115
+ fiftyeight approvals approve APPROVAL_ID # needs the publish scope
116
+ ```
117
+
118
+ AI avatar videos: Avatars powered by HeyGen.
119
+
120
+ ## Publishing
121
+
122
+ ```sh
123
+ fiftyeight accounts list
124
+ fiftyeight accounts set ACCOUNT_ID --timezone Europe/Paris
125
+
126
+ # A local video to two accounts tomorrow at 18:00, Paris time
127
+ fiftyeight posts create -f launch.mp4 -a ACCOUNT_1 -a ACCOUNT_2 \
128
+ --caption-file caption.txt --schedule 2026-12-01T18:00 --timezone Europe/Paris
129
+ fiftyeight posts list --status scheduled
130
+ fiftyeight posts cancel POST_ID
131
+ fiftyeight timing # the best times your Optimizer learned
132
+ ```
133
+
134
+ ## The brand brief, automations and your team's answers
135
+
136
+ ```sh
137
+ fiftyeight brief # every part and whether it is confirmed
138
+ fiftyeight brief set tone voice="Warm and short" # needs the brief scope
139
+ fiftyeight automations list
140
+ fiftyeight automations create --help
141
+ fiftyeight agent ask "What should we post next week?" # the team chat (with the Strategist)
142
+ fiftyeight agent to analyst "How did last week go?"
143
+ fiftyeight activity summary
144
+ ```
145
+
146
+ ## Webhooks
147
+
148
+ Fifty Eight calls your https URL when something happens (post published or failed, video ready, something needs
149
+ you, an agent hired, let go or paused, balance low, ad boosts, brief updated).
150
+
151
+ ```sh
152
+ fiftyeight webhooks events
153
+ fiftyeight webhooks add https://example.com/58 -e post.published -e post.failed # prints the secret once
154
+ fiftyeight webhooks deliveries WEBHOOK_ID
155
+ fiftyeight webhooks resend DELIVERY_ID
156
+ fiftyeight webhooks test WEBHOOK_ID
157
+ ```
158
+
159
+ Each call is signed: check `Fifty-Eight-Signature: t=<time>,v1=<hex>`, where `v1` is the HMAC-SHA256 of
160
+ `"<time>.<raw body>"` with your secret, and refuse calls older than 5 minutes.
161
+
162
+ ## Limits and errors
163
+
164
+ - Each key may make 120 calls a minute (30 that change something, 10 previews or confirms). Over that, the command
165
+ says how many seconds to wait.
166
+ - When your team's AI budget is used, the command says so: don't retry, it comes back on its own.
167
+ - A key without the right scope gets a plain message naming the scope to add.
168
+
169
+ Add `--json` right after `fiftyeight` (e.g. `fiftyeight --json team show`) for machine-readable output. Errors print the
170
+ API's message and exit with status 1 (2 for a usage mistake).
171
+
172
+ ## Develop
173
+
174
+ ```sh
175
+ cd apps/cli
176
+ uv sync
177
+ uv run pytest
178
+ uv run ruff check . && uv run ruff format --check .
179
+ ```
180
+
181
+ Release (maintainers): `rm -rf dist && uv build && uv publish --token <PyPI token>`.
@@ -0,0 +1,153 @@
1
+ # fiftyeight: the Fifty Eight command line
2
+
3
+ Fifty Eight is your AI team for short videos. You hire the agents you need (Strategist, Editor, Community manager, UGC
4
+ Creator, Team leader; the Publisher, the Analyst and the Optimizer come with every account) and they plan, make, post
5
+ and measure your videos on Instagram, TikTok and YouTube.
6
+
7
+ `fiftyeight` lets you run that team from a terminal or a script: see and change your team, publish and schedule posts,
8
+ approve what your team prepared, top up your video balance, set up webhooks and read your results. Every command is
9
+ one or two calls to the public REST API, with the same rules as the app. The API, MCP and this command line are
10
+ included in every account. Full docs: https://fiftyeight.app/docs/cli
11
+
12
+ ## Install
13
+
14
+ Needs Python 3.11 or newer.
15
+
16
+ ```sh
17
+ pipx install fiftyeight # or: uv tool install fiftyeight
18
+ fiftyeight --version
19
+ ```
20
+
21
+ ## Sign in
22
+
23
+ An owner or admin creates the workspace's API key in **Settings › Developers** and picks what it may do:
24
+
25
+ | Scope | What the key may do |
26
+ |---|---|
27
+ | `read` | Read everything: posts, accounts, team, results, prices, balance. |
28
+ | `write` | Drafts, automations, brands, knowledge, uploads, questions to agents, webhooks. Never publishes or spends. |
29
+ | `publish` | Post, schedule, change or cancel posts; approve videos and posts waiting for you. |
30
+ | `billing` | Confirm anything that costs money (owner only). |
31
+ | `brief` | Change the brand brief. |
32
+ | `ads` | The Ads manager and boosts (a boost also needs `billing`). |
33
+
34
+ A new key gets `read` only unless you tick more. A workspace has one key: rotate it to get a new secret.
35
+
36
+ ```sh
37
+ fiftyeight auth login # asks for the key, checks it, saves it
38
+ fiftyeight auth status
39
+ ```
40
+
41
+ The key is saved in `~/.config/fiftyeight/config.json`, readable only by you. For CI or scripts, set
42
+ `FIFTYEIGHT_API_KEY` instead. `FIFTYEIGHT_API_URL` (or `--api-url`) points the command line at another API.
43
+
44
+ ## Your team
45
+
46
+ ```sh
47
+ fiftyeight prices # every price
48
+ fiftyeight prices --agent team_leader --accounts 2 # what a team costs a month
49
+ fiftyeight team show # who is hired, paused, their freedom, the monthly bill
50
+ fiftyeight team preview --hire editor # the bill with a change (nothing changes)
51
+ fiftyeight team hire strategist # shows the price, then asks "Confirm? [y/N]"
52
+ fiftyeight team hire creator --top-up 20 # the UGC Creator starts with a video top-up
53
+ fiftyeight team pause community
54
+ fiftyeight team resume community
55
+ fiftyeight team let-go editor # works until the end of the month you paid
56
+ fiftyeight team freedom editor do_and_tell # ask_first, do_and_tell or on_its_own
57
+ fiftyeight team leader on --budget 50 --videos 8 --seconds 30
58
+ fiftyeight team leader setup --videos 12
59
+ fiftyeight team leader off
60
+ ```
61
+
62
+ ### Anything that costs money: preview, then confirm
63
+
64
+ Hiring, letting go, pausing, resuming, the Team leader, top-ups, AI avatar videos and ad boosts all work the same way:
65
+
66
+ 1. The command asks for a preview. Nothing is charged. You see each line, what is charged today and your new
67
+ monthly bill.
68
+ 2. It asks `Confirm? [y/N]`. Only a yes confirms (paid up front: the agent starts once paid).
69
+
70
+ `--yes` confirms without asking (for scripts), `--dry-run` shows the preview and stops. Confirming needs a key with the
71
+ `billing` scope, and each key has a daily spending limit (an owner sets it in Settings › Developers). A preview is
72
+ valid 10 minutes and confirms once. For scripts, the raw calls are there too:
73
+
74
+ ```sh
75
+ fiftyeight spend preview hire --agent editor # prints the token
76
+ fiftyeight spend confirm TOKEN
77
+ fiftyeight spend preview boost --approval APPROVAL_ID
78
+ ```
79
+
80
+ ## Videos, balance and approvals
81
+
82
+ ```sh
83
+ fiftyeight balance # what is left on the video balance
84
+ fiftyeight balance top-up 25 # $25, preview then confirm
85
+ fiftyeight videos draft "Our new winter menu" --seconds 30 # an AI avatar video ($0.17 a second)
86
+ fiftyeight approvals list # what waits for you
87
+ fiftyeight approvals approve APPROVAL_ID # needs the publish scope
88
+ ```
89
+
90
+ AI avatar videos: Avatars powered by HeyGen.
91
+
92
+ ## Publishing
93
+
94
+ ```sh
95
+ fiftyeight accounts list
96
+ fiftyeight accounts set ACCOUNT_ID --timezone Europe/Paris
97
+
98
+ # A local video to two accounts tomorrow at 18:00, Paris time
99
+ fiftyeight posts create -f launch.mp4 -a ACCOUNT_1 -a ACCOUNT_2 \
100
+ --caption-file caption.txt --schedule 2026-12-01T18:00 --timezone Europe/Paris
101
+ fiftyeight posts list --status scheduled
102
+ fiftyeight posts cancel POST_ID
103
+ fiftyeight timing # the best times your Optimizer learned
104
+ ```
105
+
106
+ ## The brand brief, automations and your team's answers
107
+
108
+ ```sh
109
+ fiftyeight brief # every part and whether it is confirmed
110
+ fiftyeight brief set tone voice="Warm and short" # needs the brief scope
111
+ fiftyeight automations list
112
+ fiftyeight automations create --help
113
+ fiftyeight agent ask "What should we post next week?" # the team chat (with the Strategist)
114
+ fiftyeight agent to analyst "How did last week go?"
115
+ fiftyeight activity summary
116
+ ```
117
+
118
+ ## Webhooks
119
+
120
+ Fifty Eight calls your https URL when something happens (post published or failed, video ready, something needs
121
+ you, an agent hired, let go or paused, balance low, ad boosts, brief updated).
122
+
123
+ ```sh
124
+ fiftyeight webhooks events
125
+ fiftyeight webhooks add https://example.com/58 -e post.published -e post.failed # prints the secret once
126
+ fiftyeight webhooks deliveries WEBHOOK_ID
127
+ fiftyeight webhooks resend DELIVERY_ID
128
+ fiftyeight webhooks test WEBHOOK_ID
129
+ ```
130
+
131
+ Each call is signed: check `Fifty-Eight-Signature: t=<time>,v1=<hex>`, where `v1` is the HMAC-SHA256 of
132
+ `"<time>.<raw body>"` with your secret, and refuse calls older than 5 minutes.
133
+
134
+ ## Limits and errors
135
+
136
+ - Each key may make 120 calls a minute (30 that change something, 10 previews or confirms). Over that, the command
137
+ says how many seconds to wait.
138
+ - When your team's AI budget is used, the command says so: don't retry, it comes back on its own.
139
+ - A key without the right scope gets a plain message naming the scope to add.
140
+
141
+ Add `--json` right after `fiftyeight` (e.g. `fiftyeight --json team show`) for machine-readable output. Errors print the
142
+ API's message and exit with status 1 (2 for a usage mistake).
143
+
144
+ ## Develop
145
+
146
+ ```sh
147
+ cd apps/cli
148
+ uv sync
149
+ uv run pytest
150
+ uv run ruff check . && uv run ruff format --check .
151
+ ```
152
+
153
+ Release (maintainers): `rm -rf dist && uv build && uv publish --token <PyPI token>`.
@@ -0,0 +1,64 @@
1
+ [project]
2
+ name = "fiftyeight"
3
+ dynamic = ["version"]
4
+ description = "Command line for Fifty Eight: hire your AI team, publish and schedule short videos, approve and measure them"
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ authors = [{ name = "Fifty Eight" }]
10
+ keywords = ["fifty eight", "social media", "short video", "instagram", "tiktok", "youtube", "ai", "cli", "api"]
11
+ classifiers = [
12
+ "Development Status :: 5 - Production/Stable",
13
+ "Environment :: Console",
14
+ "Intended Audience :: Developers",
15
+ "Intended Audience :: End Users/Desktop",
16
+ "Operating System :: OS Independent",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3 :: Only",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Topic :: Internet",
23
+ "Topic :: Multimedia :: Video",
24
+ "Topic :: Utilities",
25
+ ]
26
+ dependencies = [
27
+ "httpx>=0.28.1",
28
+ "typer>=0.15.0",
29
+ ]
30
+
31
+ [project.urls]
32
+ Homepage = "https://fiftyeight.app"
33
+ Documentation = "https://fiftyeight.app/docs/cli"
34
+
35
+ [project.scripts]
36
+ fiftyeight = "fiftyeight_cli.main:app"
37
+
38
+ [build-system]
39
+ requires = ["hatchling>=1.27"]
40
+ build-backend = "hatchling.build"
41
+
42
+ [tool.hatch.version]
43
+ path = "src/fiftyeight_cli/__init__.py"
44
+
45
+ [tool.hatch.build.targets.sdist]
46
+ include = ["src/fiftyeight_cli", "tests", "README.md", "LICENSE", "pyproject.toml"]
47
+
48
+ [tool.hatch.build.targets.wheel]
49
+ packages = ["src/fiftyeight_cli"]
50
+
51
+ [dependency-groups]
52
+ dev = [
53
+ "pytest>=9.2.0",
54
+ "respx>=0.23.1",
55
+ "ruff>=0.17.4",
56
+ ]
57
+
58
+ [tool.ruff]
59
+ line-length = 120
60
+ target-version = "py311"
61
+
62
+ [tool.ruff.lint]
63
+ select = ["E", "F", "I", "B", "UP", "SIM"]
64
+ ignore = ["B008"] # typer.Option defaults
@@ -0,0 +1 @@
1
+ __version__ = "1.0.0"
@@ -0,0 +1,119 @@
1
+ """Thin HTTP client for the Fifty Eight REST API (https://.../v1)."""
2
+
3
+ import mimetypes
4
+ import os
5
+
6
+ import httpx
7
+
8
+ from fiftyeight_cli import __version__
9
+
10
+
11
+ class ApiError(Exception):
12
+ """An API answer >= 400. `code` is the API's machine code when it sends one (scope_required, rate_limited,
13
+ spend_cap, already_used, price_changed, invalid_token, ai_budget_day...), `retry_after` the seconds to wait
14
+ (429)."""
15
+
16
+ def __init__(self, status: int, message: str, code: str | None = None, retry_after: int | None = None,
17
+ scope: str | None = None): # fmt: skip
18
+ super().__init__(message)
19
+ self.status = status
20
+ self.message = message
21
+ self.code = code
22
+ self.retry_after = retry_after
23
+ self.scope = scope
24
+
25
+
26
+ def _body(resp: httpx.Response) -> dict:
27
+ try:
28
+ body = resp.json()
29
+ except ValueError:
30
+ return {}
31
+ return body if isinstance(body, dict) else {}
32
+
33
+
34
+ def _retry_after(resp: httpx.Response) -> int | None:
35
+ try:
36
+ return max(0, int(float(resp.headers.get("Retry-After", ""))))
37
+ except ValueError:
38
+ return None
39
+
40
+
41
+ def _detail(resp: httpx.Response) -> str:
42
+ try:
43
+ body = resp.json()
44
+ except ValueError:
45
+ return resp.text.strip()[:300] or resp.reason_phrase
46
+ detail = body.get("detail") if isinstance(body, dict) else None
47
+ if isinstance(detail, list): # FastAPI validation errors
48
+ return "; ".join(
49
+ f"{'.'.join(str(x) for x in d.get('loc', [])[1:]) or 'body'}: {d.get('msg', '')}" for d in detail
50
+ )
51
+ return str(detail or body)
52
+
53
+
54
+ class Client:
55
+ def __init__(self, base_url: str, api_key: str, timeout: float = 60.0):
56
+ self.base_url = base_url.rstrip("/")
57
+ self.http = httpx.Client(
58
+ base_url=self.base_url,
59
+ timeout=timeout,
60
+ headers={"Authorization": f"Bearer {api_key}", "User-Agent": f"fiftyeight-cli/{__version__}"},
61
+ )
62
+
63
+ def request(self, method: str, path: str, *, json=None, params=None, headers=None):
64
+ try:
65
+ resp = self.http.request(method, path, json=json, params=params, headers=headers)
66
+ except httpx.HTTPError as exc:
67
+ raise ApiError(0, f"Could not reach {self.base_url}: {exc}") from exc
68
+ if resp.status_code >= 400:
69
+ body = _body(resp)
70
+ code = body.get("code") if isinstance(body.get("code"), str) else None
71
+ scope = body.get("scope") if isinstance(body.get("scope"), str) else None
72
+ raise ApiError(resp.status_code, _detail(resp), code, _retry_after(resp), scope)
73
+ return resp.json() if resp.content else None
74
+
75
+ def get(self, path: str, **kw):
76
+ return self.request("GET", path, **kw)
77
+
78
+ def post(self, path: str, **kw):
79
+ return self.request("POST", path, **kw)
80
+
81
+ def patch(self, path: str, **kw):
82
+ return self.request("PATCH", path, **kw)
83
+
84
+ def put(self, path: str, **kw):
85
+ return self.request("PUT", path, **kw)
86
+
87
+ def delete(self, path: str, **kw):
88
+ return self.request("DELETE", path, **kw)
89
+
90
+ def put_file(self, upload_url: str, file_path: str, content_type: str) -> None:
91
+ """PUT a local file to an upload URL given by the API."""
92
+ with open(file_path, "rb") as f:
93
+ try:
94
+ resp = httpx.put(upload_url, content=f, headers={"Content-Type": content_type}, timeout=None)
95
+ except httpx.HTTPError as exc:
96
+ raise ApiError(0, f"Upload failed: {exc}") from exc
97
+ if resp.status_code >= 400:
98
+ raise ApiError(resp.status_code, f"Upload failed: {resp.text.strip()[:300] or resp.reason_phrase}")
99
+
100
+ def upload(self, file_path: str) -> dict:
101
+ """Two steps: ask for an upload URL, then PUT the bytes there. Returns {media_id, public_url}."""
102
+ if not os.path.isfile(file_path):
103
+ raise ApiError(0, f"No such file: {file_path}")
104
+ content_type = mimetypes.guess_type(file_path)[0] or ""
105
+ if not content_type.startswith(("video/", "image/")):
106
+ raise ApiError(0, f"{file_path} is not a video or image (unknown type {content_type or '?'})")
107
+ size = os.path.getsize(file_path)
108
+ slot = self.post(
109
+ "/v1/media/uploads",
110
+ json={"filename": os.path.basename(file_path), "content_type": content_type, "size_bytes": size},
111
+ )
112
+ with open(file_path, "rb") as f:
113
+ try:
114
+ resp = httpx.put(slot["upload_url"], content=f, headers={"Content-Type": content_type}, timeout=None)
115
+ except httpx.HTTPError as exc:
116
+ raise ApiError(0, f"Upload failed: {exc}") from exc
117
+ if resp.status_code >= 400:
118
+ raise ApiError(resp.status_code, f"Upload failed: {resp.text.strip()[:300] or resp.reason_phrase}")
119
+ return {"media_id": slot["media_id"], "public_url": slot["public_url"]}
@@ -0,0 +1,50 @@
1
+ """Where the CLI finds its API key and API URL.
2
+
3
+ Order: command-line option, then environment (FIFTYEIGHT_API_KEY, FIFTYEIGHT_API_URL), then the config file written
4
+ by `fiftyeight auth login` (~/.config/fiftyeight/config.json, readable only by you).
5
+ """
6
+
7
+ import json
8
+ import os
9
+ from pathlib import Path
10
+
11
+ DEFAULT_API_URL = "https://api.fiftyeight.app"
12
+
13
+
14
+ def config_dir() -> Path:
15
+ if os.environ.get("FIFTYEIGHT_CONFIG_DIR"):
16
+ return Path(os.environ["FIFTYEIGHT_CONFIG_DIR"])
17
+ base = os.environ.get("XDG_CONFIG_HOME") or os.path.join(Path.home(), ".config")
18
+ return Path(base) / "fiftyeight"
19
+
20
+
21
+ def config_path() -> Path:
22
+ return config_dir() / "config.json"
23
+
24
+
25
+ def load() -> dict:
26
+ try:
27
+ return json.loads(config_path().read_text())
28
+ except (FileNotFoundError, json.JSONDecodeError):
29
+ return {}
30
+
31
+
32
+ def save(data: dict) -> Path:
33
+ path = config_path()
34
+ path.parent.mkdir(parents=True, exist_ok=True)
35
+ os.chmod(path.parent, 0o700)
36
+ # Create with 0600 from the start, so the key is never readable by others, even briefly.
37
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
38
+ with os.fdopen(fd, "w") as f:
39
+ json.dump(data, f, indent=2)
40
+ os.chmod(path, 0o600)
41
+ return path
42
+
43
+
44
+ def api_key(override: str | None = None) -> str | None:
45
+ return override or os.environ.get("FIFTYEIGHT_API_KEY") or load().get("api_key")
46
+
47
+
48
+ def api_url(override: str | None = None) -> str:
49
+ url = override or os.environ.get("FIFTYEIGHT_API_URL") or load().get("api_url") or DEFAULT_API_URL
50
+ return url.rstrip("/")