onmynod 0.1.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 @@
1
+ dist/
onmynod-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,58 @@
1
+ Metadata-Version: 2.5
2
+ Name: onmynod
3
+ Version: 0.1.0
4
+ Summary: Command line for OnMyNod: upload videos and post them to YouTube, Instagram, Facebook and TikTok
5
+ Requires-Python: >=3.11
6
+ Requires-Dist: httpx>=0.27
7
+ Description-Content-Type: text/markdown
8
+
9
+ # onmynod — command line
10
+
11
+ Upload videos and post them to YouTube, Instagram, Facebook and TikTok from a terminal, a script or an AI agent
12
+ (Claude Code, Codex…). It uses an OnMyNod API key.
13
+
14
+ ## Install
15
+
16
+ From a checkout of this repository:
17
+
18
+ ```bash
19
+ uv tool install ./cli # or: pipx install ./cli
20
+ ```
21
+
22
+ Once the package is published to PyPI: `uv tool install onmynod` (or `pipx install onmynod`).
23
+
24
+ Releasing: bump `version` in `pyproject.toml`, then run Actions → publish-cli on `product`
25
+ (`.github/workflows/publish-cli.yml`, PyPI Trusted Publishing; no token is stored).
26
+
27
+ ## Sign in
28
+
29
+ An admin creates a key in **Settings → API keys**. New keys hold every post they create for approval; an admin
30
+ approves it on the Approvals page before anything is published.
31
+
32
+ ```bash
33
+ onmynod login # paste the key; saved to ~/.config/onmynod/config.json (owner-only)
34
+ onmynod whoami
35
+ ```
36
+
37
+ In CI or for an agent, set `ONMYNOD_API_KEY` instead (and `ONMYNOD_URL` for another server). A saved key is only ever
38
+ sent to the address it was saved for.
39
+
40
+ ## Post
41
+
42
+ ```bash
43
+ onmynod accounts
44
+ onmynod post clip.mp4 --to youtube --to @mybrand --title "Launch" --text "Out now" \
45
+ --option privacy=public --at 2026-12-24T18:00 --dry-run # check first: nothing is created
46
+ onmynod post clip.mp4 --to youtube --title "Launch" --text "Out now" --option privacy=public --wait
47
+ onmynod status POST_ID
48
+ ```
49
+
50
+ `--to` takes an account id, its name, its @handle, or a platform name when that platform has one account. `--at`
51
+ without an offset is this computer's local time. `--option NAME=VALUE` sets a platform option (YouTube `privacy`,
52
+ TikTok `privacy_level`, …) for every account in the post.
53
+
54
+ Other commands: `upload`, `media`, `posts --view approval|open|done`, `reschedule POST WHEN`, `cancel POST`,
55
+ `retry POST TARGET`, `events --post POST`, `logout`. Add `--json` to any command for machine-readable output;
56
+ `--lang tr|es|de|ar` translates the server's messages.
57
+
58
+ Exit codes: `0` done, `1` the server refused or a delivery failed, `2` wrong usage or not signed in.
@@ -0,0 +1,50 @@
1
+ # onmynod — command line
2
+
3
+ Upload videos and post them to YouTube, Instagram, Facebook and TikTok from a terminal, a script or an AI agent
4
+ (Claude Code, Codex…). It uses an OnMyNod API key.
5
+
6
+ ## Install
7
+
8
+ From a checkout of this repository:
9
+
10
+ ```bash
11
+ uv tool install ./cli # or: pipx install ./cli
12
+ ```
13
+
14
+ Once the package is published to PyPI: `uv tool install onmynod` (or `pipx install onmynod`).
15
+
16
+ Releasing: bump `version` in `pyproject.toml`, then run Actions → publish-cli on `product`
17
+ (`.github/workflows/publish-cli.yml`, PyPI Trusted Publishing; no token is stored).
18
+
19
+ ## Sign in
20
+
21
+ An admin creates a key in **Settings → API keys**. New keys hold every post they create for approval; an admin
22
+ approves it on the Approvals page before anything is published.
23
+
24
+ ```bash
25
+ onmynod login # paste the key; saved to ~/.config/onmynod/config.json (owner-only)
26
+ onmynod whoami
27
+ ```
28
+
29
+ In CI or for an agent, set `ONMYNOD_API_KEY` instead (and `ONMYNOD_URL` for another server). A saved key is only ever
30
+ sent to the address it was saved for.
31
+
32
+ ## Post
33
+
34
+ ```bash
35
+ onmynod accounts
36
+ onmynod post clip.mp4 --to youtube --to @mybrand --title "Launch" --text "Out now" \
37
+ --option privacy=public --at 2026-12-24T18:00 --dry-run # check first: nothing is created
38
+ onmynod post clip.mp4 --to youtube --title "Launch" --text "Out now" --option privacy=public --wait
39
+ onmynod status POST_ID
40
+ ```
41
+
42
+ `--to` takes an account id, its name, its @handle, or a platform name when that platform has one account. `--at`
43
+ without an offset is this computer's local time. `--option NAME=VALUE` sets a platform option (YouTube `privacy`,
44
+ TikTok `privacy_level`, …) for every account in the post.
45
+
46
+ Other commands: `upload`, `media`, `posts --view approval|open|done`, `reschedule POST WHEN`, `cancel POST`,
47
+ `retry POST TARGET`, `events --post POST`, `logout`. Add `--json` to any command for machine-readable output;
48
+ `--lang tr|es|de|ar` translates the server's messages.
49
+
50
+ Exit codes: `0` done, `1` the server refused or a delivery failed, `2` wrong usage or not signed in.
@@ -0,0 +1,20 @@
1
+ [project]
2
+ name = "onmynod"
3
+ version = "0.1.0"
4
+ description = "Command line for OnMyNod: upload videos and post them to YouTube, Instagram, Facebook and TikTok"
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ dependencies = ["httpx>=0.27"]
8
+
9
+ [project.scripts]
10
+ onmynod = "onmynod_cli.main:main"
11
+
12
+ [build-system]
13
+ requires = ["hatchling"]
14
+ build-backend = "hatchling.build"
15
+
16
+ [tool.hatch.build.targets.wheel]
17
+ packages = ["src/onmynod_cli"]
18
+
19
+ [tool.ruff]
20
+ line-length = 120
@@ -0,0 +1,2 @@
1
+ """OnMyNod command line."""
2
+ __version__ = "0.1.0"
@@ -0,0 +1,137 @@
1
+ """A small client for the REST API, authenticated with an API key.
2
+
3
+ The key is sent only to the API's own origin. Signed storage URLs returned for uploads (S3, R2) never receive it.
4
+ """
5
+ import time
6
+ from pathlib import Path
7
+ from urllib.parse import urlsplit
8
+
9
+ import httpx
10
+
11
+ from . import __version__
12
+
13
+ CONTENT_TYPES = {
14
+ ".mp4": ("video/mp4", "video"), ".mov": ("video/quicktime", "video"),
15
+ ".jpg": ("image/jpeg", "image"), ".jpeg": ("image/jpeg", "image"), ".png": ("image/png", "image"),
16
+ ".srt": ("application/x-subrip", "captions"), ".vtt": ("text/vtt", "captions"),
17
+ }
18
+ MAX_RETRY_WAIT = 30 # seconds: a rate-limit wait longer than this is reported instead of slept through
19
+
20
+
21
+ class ApiError(Exception):
22
+ def __init__(self, status: int, code: str, message: str, problems: list[str] | None = None):
23
+ super().__init__(message)
24
+ self.status, self.code, self.problems = status, code, problems or []
25
+
26
+
27
+ def _origin(url: str) -> tuple[str, str]:
28
+ parts = urlsplit(url)
29
+ return parts.scheme, parts.netloc
30
+
31
+
32
+ class Client:
33
+ def __init__(self, url: str, key: str, http: httpx.Client | None = None, locale: str | None = None):
34
+ self.url, self.key = url.rstrip("/"), key
35
+ # Sent with every request (not as the HTTP client's defaults): an injected client gets them too
36
+ self.headers = {"User-Agent": f"onmynod-cli/{__version__}", **({"X-Locale": locale} if locale else {})}
37
+ self.http = http or httpx.Client(base_url=self.url, timeout=httpx.Timeout(60, write=None))
38
+ self._me: dict | None = None
39
+
40
+ # ---------- plumbing ----------
41
+ def request(self, method: str, path: str, **kw):
42
+ headers = {**self.headers, **kw.pop("headers", {}), "Authorization": f"Bearer {self.key}"}
43
+ for _ in range(3):
44
+ r = self.http.request(method, path, headers=headers, **kw)
45
+ wait = r.headers.get("retry-after", "")
46
+ if r.status_code == 429 and wait.isdigit() and int(wait) <= MAX_RETRY_WAIT and "content" not in kw:
47
+ time.sleep(int(wait))
48
+ continue
49
+ break
50
+ if r.status_code >= 400:
51
+ try:
52
+ err = r.json().get("error") or {}
53
+ except ValueError:
54
+ err = {}
55
+ raise ApiError(r.status_code, err.get("code", "http_error"), err.get("message") or f"HTTP {r.status_code}",
56
+ err.get("problems"))
57
+ return r.json() if r.content else None
58
+
59
+ def me(self) -> dict:
60
+ if self._me is None:
61
+ self._me = self.request("GET", "/api/v1/key")
62
+ return self._me
63
+
64
+ @property
65
+ def ws(self) -> str:
66
+ return f"/api/v1/workspaces/{self.me()['workspace']['id']}"
67
+
68
+ # ---------- reading ----------
69
+ def accounts(self) -> list[dict]:
70
+ return self.request("GET", f"{self.ws}/accounts")
71
+
72
+ def media(self, type: str = "video", limit: int = 20) -> list[dict]:
73
+ return self.request("GET", f"{self.ws}/media", params={"type": type, "limit": limit})
74
+
75
+ def posts(self, view: str = "all", limit: int = 20, offset: int = 0) -> list[dict]:
76
+ return self.request("GET", f"{self.ws}/posts", params={"view": view, "limit": limit, "offset": offset})
77
+
78
+ def post(self, post_id: str) -> dict:
79
+ return self.request("GET", f"{self.ws}/posts/{post_id}")
80
+
81
+ def events(self, post_id: str | None = None, limit: int = 30) -> list[dict]:
82
+ params = {"limit": limit, **({"post_id": post_id} if post_id else {})}
83
+ return self.request("GET", f"{self.ws}/events", params=params)
84
+
85
+ # ---------- writing ----------
86
+ def upload(self, path: str | Path, progress=None) -> dict:
87
+ """Uploads a file (video, thumbnail image or captions) and returns the ready media record."""
88
+ path = Path(path)
89
+ ctype, kind = CONTENT_TYPES.get(path.suffix.lower(), (None, None))
90
+ if not ctype:
91
+ raise ApiError(0, "bad_type", f"{path.name}: use MP4 or MOV for video, JPG or PNG for a thumbnail, SRT or VTT "
92
+ "for captions.")
93
+ size = path.stat().st_size
94
+ out = self.request("POST", f"{self.ws}/media",
95
+ json={"filename": path.name, "content_type": ctype, "size": size, "type": kind})
96
+ up, media_id = out["upload"], out["media"]["id"]
97
+ url = up["url"] if up["url"].startswith(("http://", "https://")) else self.url + up["url"]
98
+ headers = {**(up.get("headers") or {}), "Content-Length": str(size)} # streamed, not chunked
99
+ own = _origin(url) == _origin(self.url)
100
+ if own: # the app's own upload endpoint
101
+ headers.update({**self.headers, "Authorization": f"Bearer {self.key}"})
102
+ with open(path, "rb") as f:
103
+ body = _Reader(f, size, progress)
104
+ if own:
105
+ r = self.http.request(up["method"], url, content=body, headers=headers)
106
+ else: # a signed storage URL: no key, a fresh client so no default header leaks
107
+ with httpx.Client(timeout=httpx.Timeout(60, write=None)) as plain:
108
+ r = plain.request(up["method"], url, content=body, headers=headers)
109
+ if r.status_code >= 400:
110
+ raise ApiError(r.status_code, "upload_failed", f"The upload failed (HTTP {r.status_code}).")
111
+ return self.request("POST", f"{self.ws}/media/{media_id}/complete")
112
+
113
+ def create_post(self, body: dict) -> dict:
114
+ return self.request("POST", f"{self.ws}/posts", json=body)
115
+
116
+ def reschedule(self, post_id: str, when: str) -> dict:
117
+ return self.request("POST", f"{self.ws}/posts/{post_id}/reschedule", json={"scheduled_at": when})
118
+
119
+ def cancel(self, post_id: str, target_id: str) -> dict:
120
+ return self.request("POST", f"{self.ws}/posts/{post_id}/targets/{target_id}/cancel")
121
+
122
+ def retry(self, post_id: str, target_id: str) -> dict:
123
+ return self.request("POST", f"{self.ws}/posts/{post_id}/targets/{target_id}/retry")
124
+
125
+
126
+ class _Reader:
127
+ """Streams a file in chunks (a large video is never read into memory) and reports progress."""
128
+
129
+ def __init__(self, f, size: int, progress):
130
+ self.f, self.size, self.progress, self.sent = f, size, progress, 0
131
+
132
+ def __iter__(self):
133
+ while chunk := self.f.read(1 << 20):
134
+ self.sent += len(chunk)
135
+ if self.progress:
136
+ self.progress(self.sent, self.size)
137
+ yield chunk
@@ -0,0 +1,50 @@
1
+ """Where the CLI keeps its address and API key.
2
+
3
+ Order: the ONMYNOD_API_KEY / ONMYNOD_URL environment variables, then the config file written by `onmynod login`
4
+ (~/.config/onmynod/config.json, readable only by its owner).
5
+ """
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+
10
+ DEFAULT_URL = "https://app.onmynod.com"
11
+
12
+
13
+ def path() -> Path:
14
+ base = os.environ.get("XDG_CONFIG_HOME") or (Path.home() / ".config")
15
+ return Path(base) / "onmynod" / "config.json"
16
+
17
+
18
+ def load() -> dict:
19
+ try:
20
+ return json.loads(path().read_text())
21
+ except (OSError, ValueError):
22
+ return {}
23
+
24
+
25
+ def save(data: dict) -> Path:
26
+ p = path()
27
+ p.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
28
+ # Created with owner-only permissions from the start: the key is never readable by others, not even briefly
29
+ fd = os.open(p, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
30
+ with os.fdopen(fd, "w") as f:
31
+ json.dump(data, f)
32
+ os.chmod(p, 0o600)
33
+ return p
34
+
35
+
36
+ def remove() -> bool:
37
+ try:
38
+ path().unlink()
39
+ return True
40
+ except FileNotFoundError:
41
+ return False
42
+
43
+
44
+ def resolve(url: str | None = None) -> tuple[str, str]:
45
+ """(address, key) from the options, the environment and the file, in that order."""
46
+ stored = load()
47
+ address = (url or os.environ.get("ONMYNOD_URL") or stored.get("url") or DEFAULT_URL).rstrip("/")
48
+ # The saved key goes only to the address it was saved for: pointing the CLI elsewhere must not send it there
49
+ saved = stored.get("key", "") if stored.get("url", "").rstrip("/") == address else ""
50
+ return address, os.environ.get("ONMYNOD_API_KEY", "").strip() or saved
@@ -0,0 +1,342 @@
1
+ """`onmynod`: upload videos and post them from a terminal, a script or an AI agent.
2
+
3
+ Every command prints readable text, or JSON with --json (for scripts and agents). Exit codes: 0 done, 1 the server
4
+ refused or failed, 2 wrong usage or not signed in.
5
+ """
6
+ import argparse
7
+ import getpass
8
+ import json
9
+ import sys
10
+ import time
11
+ import uuid
12
+ from datetime import UTC, datetime
13
+
14
+ import httpx
15
+
16
+ from . import __version__, config
17
+ from .client import ApiError, Client
18
+
19
+ OPEN = ("waiting_approval", "queued", "publishing")
20
+
21
+
22
+ class Usage(Exception):
23
+ pass
24
+
25
+
26
+ # ---------- output ----------
27
+ def _emit(args, data, text: str) -> None:
28
+ print(json.dumps(data, ensure_ascii=False, indent=2) if args.json else text)
29
+
30
+
31
+ def _when(value: str | None) -> str:
32
+ return (value or "")[:16].replace("T", " ")
33
+
34
+
35
+ def _post_text(p: dict) -> str:
36
+ head = f"{p['id']} {p.get('label') or ''}".rstrip()
37
+ state = {"pending": "waiting for approval", "approved": "approved", "rejected": "rejected",
38
+ "withdrawn": "withdrawn"}.get(p.get("approval", ""), "")
39
+ lines = [head, f" {'scheduled ' + _when(p['scheduled_at']) + ' UTC' if p.get('scheduled_at') else 'post now'}"
40
+ + (f" · {state}" if state else "")]
41
+ for t in p.get("targets", []):
42
+ extra = t.get("url") or t.get("error") or t.get("note") or ""
43
+ lines.append(f" - {t['platform']:<9} {t['account_name'][:30]:<30} {t['status']:<16} {extra}".rstrip()
44
+ + f" [target {t['id']}]")
45
+ return "\n".join(lines)
46
+
47
+
48
+ # ---------- helpers ----------
49
+ def _client(args) -> Client:
50
+ url, key = config.resolve(args.url)
51
+ if not key:
52
+ raise Usage("Not signed in. Run `onmynod login`, or set ONMYNOD_API_KEY.")
53
+ return Client(url, key, locale=args.lang)
54
+
55
+
56
+ def _is_id(value: str) -> bool:
57
+ try:
58
+ uuid.UUID(value)
59
+ return True
60
+ except ValueError:
61
+ return False
62
+
63
+
64
+ def _time(value: str) -> str:
65
+ """ISO 8601. A time without an offset is taken as this computer's local time."""
66
+ try:
67
+ when = datetime.fromisoformat(value.strip().replace(" ", "T"))
68
+ except ValueError:
69
+ raise Usage(f"Not a date and time: {value!r}. Use e.g. 2026-12-24T18:00 or 2026-12-24T18:00+03:00.") from None
70
+ return (when if when.tzinfo else when.astimezone()).isoformat()
71
+
72
+
73
+ def _accounts(c: Client, wanted: list[str]) -> list[str]:
74
+ """Account ids from ids, names, handles or platform names (when that platform has a single account)."""
75
+ rows, out = c.accounts(), []
76
+ for w in wanted:
77
+ if _is_id(w) and any(a["id"] == w for a in rows):
78
+ out.append(w)
79
+ continue
80
+ low = w.lower().lstrip("@")
81
+ found = [a for a in rows if low in (a["name"].lower(), a["handle"].lower().lstrip("@"))] or \
82
+ [a for a in rows if a["platform"] == low]
83
+ if len(found) != 1:
84
+ choices = ", ".join(f"{a['platform']}:{a['name']} ({a['id']})" for a in (found or rows)) or "none connected"
85
+ raise Usage(f"{'Several accounts match' if found else 'No account matches'} {w!r}. Choices: {choices}")
86
+ out.append(found[0]["id"])
87
+ return out
88
+
89
+
90
+ def _options(pairs: list[str]) -> dict:
91
+ out = {}
92
+ for pair in pairs:
93
+ name, sep, raw = pair.partition("=")
94
+ if not sep or not name:
95
+ raise Usage(f"--option needs NAME=VALUE, got {pair!r}")
96
+ try:
97
+ out[name] = json.loads(raw)
98
+ except ValueError:
99
+ out[name] = raw
100
+ return out
101
+
102
+
103
+ def _progress(args):
104
+ if args.json or not sys.stderr.isatty():
105
+ return None
106
+
107
+ def show(sent: int, size: int) -> None:
108
+ sys.stderr.write(f"\rUploading… {sent * 100 // max(size, 1)}%")
109
+ if sent >= size:
110
+ sys.stderr.write("\n")
111
+ return show
112
+
113
+
114
+ # ---------- commands ----------
115
+ def cmd_login(args) -> int:
116
+ url = (args.url or config.load().get("url") or config.DEFAULT_URL).rstrip("/")
117
+ if args.key_stdin:
118
+ key = sys.stdin.readline().strip()
119
+ else:
120
+ print(f"Create a key in {url}/settings#api-keys (admins only), then paste it here.", file=sys.stderr)
121
+ key = getpass.getpass("API key: ").strip()
122
+ if not key.startswith("omn_"):
123
+ raise Usage("That does not look like an API key (it starts with omn_).")
124
+ me = Client(url, key, locale=args.lang).me()
125
+ where = config.save({"url": url, "key": key})
126
+ _emit(args, me, f"Signed in to {me['workspace']['name']} as {me['user']['name']} (key {me['name']}). "
127
+ f"Saved to {where}.")
128
+ return 0
129
+
130
+
131
+ def cmd_logout(args) -> int:
132
+ removed = config.remove()
133
+ _emit(args, {"removed": removed}, "Signed out: the saved key was removed." if removed else "No saved key.")
134
+ return 0
135
+
136
+
137
+ def cmd_whoami(args) -> int:
138
+ me = _client(args).me()
139
+ hold = "posts wait for approval" if me["hold_posts"] else f"approval setting: {me['workspace']['approval_mode']}"
140
+ _emit(args, me, f"{me['workspace']['name']} ({me['workspace']['timezone']}) · key {me['name']} · {hold}")
141
+ return 0
142
+
143
+
144
+ def cmd_accounts(args) -> int:
145
+ rows = _client(args).accounts()
146
+ text = "\n".join(f"{a['id']} {a['platform']:<9} {a['name']}" + (f" (@{a['handle'].lstrip('@')})" if a["handle"] else "")
147
+ + (" [reconnect needed]" if a["needs_reconnect"] else "") for a in rows) or "No connected accounts."
148
+ _emit(args, rows, text)
149
+ return 0
150
+
151
+
152
+ def cmd_media(args) -> int:
153
+ rows = _client(args).media(args.type, args.limit)
154
+ text = "\n".join(f"{m['id']} {m['filename']} {m.get('kind') or m['type']}"
155
+ + (f" {m['duration']}s" if m.get("duration") else "") for m in rows) or "No files."
156
+ _emit(args, rows, text)
157
+ return 0
158
+
159
+
160
+ def cmd_upload(args) -> int:
161
+ m = _client(args).upload(args.file, _progress(args))
162
+ _emit(args, m, f"{m['id']} {m['filename']} is ready"
163
+ + (f" ({m['kind']}, {m['duration']}s, {m['width']}x{m['height']})" if m["type"] == "video" else ""))
164
+ return 0
165
+
166
+
167
+ def cmd_post(args) -> int:
168
+ c = _client(args)
169
+ if _is_id(args.video):
170
+ media_id = args.video
171
+ else:
172
+ media_id = c.upload(args.video, _progress(args))["id"]
173
+ extra = {}
174
+ if args.thumbnail:
175
+ extra["thumbnail_id"] = args.thumbnail if _is_id(args.thumbnail) else c.upload(args.thumbnail)["id"]
176
+ if args.captions:
177
+ extra["captions_id"] = args.captions if _is_id(args.captions) else c.upload(args.captions)["id"]
178
+ options = _options(args.option)
179
+ targets = [{"account_id": a, "title": args.title, "text": args.text, "options": options, **extra}
180
+ for a in _accounts(c, args.to)]
181
+ body = {"media_id": media_id, "targets": targets, "label": args.label, "ai_generated": args.ai_generated,
182
+ "dry_run": args.dry_run, **({"scheduled_at": _time(args.at)} if args.at else {})}
183
+ out = c.create_post(body)
184
+ if args.dry_run:
185
+ lines = ["Dry run: nothing was created.",
186
+ f" {'scheduled ' + _when(out['scheduled_at']) + ' UTC' if out['scheduled_at'] else 'would post now'}"
187
+ + (" · would wait for approval" if out["needs_approval"] else "")]
188
+ lines += [f" - {t['platform']:<9} {t['account_name']}" for t in out["targets"]]
189
+ _emit(args, out, "\n".join(lines))
190
+ return 0
191
+ if args.wait and out["approval"] != "pending":
192
+ out = _wait(c, out["id"], args.timeout)
193
+ _emit(args, out, _post_text(out) + ("\nAn admin has to approve it in the app before it is published."
194
+ if out["approval"] == "pending" else ""))
195
+ return 0 if not any(t["status"] == "failed" for t in out["targets"]) else 1
196
+
197
+
198
+ def _wait(c: Client, post_id: str, timeout: int) -> dict:
199
+ end = time.monotonic() + timeout
200
+ while True:
201
+ p = c.post(post_id)
202
+ if not any(t["status"] in OPEN for t in p["targets"]) or time.monotonic() > end:
203
+ return p
204
+ if p.get("scheduled_at") and datetime.fromisoformat(p["scheduled_at"]) > datetime.now(UTC):
205
+ return p # scheduled for later: nothing to wait for now
206
+ time.sleep(3)
207
+
208
+
209
+ def cmd_posts(args) -> int:
210
+ rows = _client(args).posts(args.view, args.limit)
211
+ _emit(args, rows, "\n\n".join(_post_text(p) for p in rows) or "No posts.")
212
+ return 0
213
+
214
+
215
+ def cmd_status(args) -> int:
216
+ c = _client(args)
217
+ p = _wait(c, args.post, args.timeout) if args.wait else c.post(args.post)
218
+ _emit(args, p, _post_text(p))
219
+ return 0
220
+
221
+
222
+ def cmd_reschedule(args) -> int:
223
+ p = _client(args).reschedule(args.post, _time(args.when))
224
+ _emit(args, p, _post_text(p))
225
+ return 0
226
+
227
+
228
+ def cmd_cancel(args) -> int:
229
+ c = _client(args)
230
+ ids = [args.target] if args.target else [t["id"] for t in c.post(args.post)["targets"] if t["status"] in OPEN]
231
+ if not ids:
232
+ raise Usage("Nothing to cancel: every delivery of this post has finished.")
233
+ p = None
234
+ for tid in ids:
235
+ p = c.cancel(args.post, tid)
236
+ _emit(args, p, _post_text(p))
237
+ return 0
238
+
239
+
240
+ def cmd_retry(args) -> int:
241
+ p = _client(args).retry(args.post, args.target)
242
+ _emit(args, p, _post_text(p))
243
+ return 0
244
+
245
+
246
+ def cmd_events(args) -> int:
247
+ rows = _client(args).events(args.post, args.limit)
248
+ _emit(args, rows, "\n".join(f"{_when(e['created_at'])} {e['level']:<5} {e['message']}" for e in rows) or "No events.")
249
+ return 0
250
+
251
+
252
+ # ---------- arguments ----------
253
+ def parser() -> argparse.ArgumentParser:
254
+ common = argparse.ArgumentParser(add_help=False)
255
+ common.add_argument("--json", action="store_true", help="print JSON (for scripts and agents)")
256
+ common.add_argument("--url", help=f"server address (default: saved, ONMYNOD_URL or {config.DEFAULT_URL})")
257
+ common.add_argument("--lang", choices=["en", "tr", "es", "ar", "de"], help="language of server messages")
258
+ # The common options belong to each command (`onmynod accounts --json`): on the top parser as well, a command's
259
+ # defaults would silently overwrite them
260
+ p = argparse.ArgumentParser(prog="onmynod", description="Upload videos and post them to YouTube, Instagram, "
261
+ "Facebook and TikTok.")
262
+ p.add_argument("--version", action="version", version=f"onmynod {__version__}")
263
+ sub = p.add_subparsers(dest="command", required=True, metavar="COMMAND")
264
+
265
+ def add(name, fn, help, **kw):
266
+ s = sub.add_parser(name, help=help, description=help, parents=[common], **kw)
267
+ s.set_defaults(fn=fn)
268
+ return s
269
+
270
+ s = add("login", cmd_login, "save an API key for this computer")
271
+ s.add_argument("--key-stdin", action="store_true", help="read the key from standard input instead of a prompt")
272
+ add("logout", cmd_logout, "forget the saved API key")
273
+ add("whoami", cmd_whoami, "show the workspace and key in use")
274
+ add("accounts", cmd_accounts, "list connected accounts")
275
+ s = add("media", cmd_media, "list uploaded files")
276
+ s.add_argument("--type", choices=["video", "image", "captions"], default="video")
277
+ s.add_argument("--limit", type=int, default=20)
278
+ s = add("upload", cmd_upload, "upload a video (MP4, MOV), thumbnail (JPG, PNG) or captions (SRT, VTT)")
279
+ s.add_argument("file")
280
+ s = add("post", cmd_post, "post a video (a file path or an uploaded video's id) to one or more accounts")
281
+ s.add_argument("video")
282
+ s.add_argument("--to", action="append", required=True, metavar="ACCOUNT",
283
+ help="account id, name, @handle, or a platform with one account; repeat for several")
284
+ s.add_argument("--title", default="")
285
+ s.add_argument("--text", default="", help="description or caption")
286
+ s.add_argument("--at", help="when to post, e.g. 2026-12-24T18:00 (local time) or with an offset; default: now")
287
+ s.add_argument("--label", default="", help="name shown in the app")
288
+ s.add_argument("--option", action="append", default=[], metavar="NAME=VALUE",
289
+ help="platform option, e.g. privacy=unlisted; repeat for several")
290
+ s.add_argument("--thumbnail", help="image file or uploaded image id")
291
+ s.add_argument("--captions", help="captions file or uploaded captions id")
292
+ s.add_argument("--ai-generated", action="store_true", help="mark the video as AI-generated")
293
+ s.add_argument("--dry-run", action="store_true", help="check everything and show the result without posting")
294
+ s.add_argument("--wait", action="store_true", help="wait until publishing finishes")
295
+ s.add_argument("--timeout", type=int, default=600, help="seconds to wait at most (default 600)")
296
+ s = add("posts", cmd_posts, "list posts")
297
+ s.add_argument("--view", choices=["all", "open", "done", "approval"], default="all")
298
+ s.add_argument("--limit", type=int, default=20)
299
+ s = add("status", cmd_status, "show a post and each delivery's status")
300
+ s.add_argument("post")
301
+ s.add_argument("--wait", action="store_true", help="wait until publishing finishes")
302
+ s.add_argument("--timeout", type=int, default=600)
303
+ s = add("reschedule", cmd_reschedule, "move a post that has not started to another time")
304
+ s.add_argument("post")
305
+ s.add_argument("when")
306
+ s = add("cancel", cmd_cancel, "cancel a post's unfinished deliveries (or one with --target)")
307
+ s.add_argument("post")
308
+ s.add_argument("--target")
309
+ s = add("retry", cmd_retry, "queue a failed or canceled delivery again")
310
+ s.add_argument("post")
311
+ s.add_argument("target")
312
+ s = add("events", cmd_events, "show the activity log")
313
+ s.add_argument("--post")
314
+ s.add_argument("--limit", type=int, default=30)
315
+ return p
316
+
317
+
318
+ def main(argv: list[str] | None = None) -> int:
319
+ args = parser().parse_args(argv)
320
+ try:
321
+ return args.fn(args)
322
+ except Usage as e:
323
+ print(f"onmynod: {e}", file=sys.stderr)
324
+ return 2
325
+ except ApiError as e:
326
+ if args.json:
327
+ print(json.dumps({"error": {"status": e.status, "code": e.code, "message": str(e), "problems": e.problems}},
328
+ ensure_ascii=False), file=sys.stderr)
329
+ else:
330
+ print(f"onmynod: {e}", file=sys.stderr)
331
+ for extra in e.problems[1:]:
332
+ print(f" {extra}", file=sys.stderr)
333
+ return 1
334
+ except (OSError, httpx.HTTPError) as e:
335
+ print(f"onmynod: {e}", file=sys.stderr)
336
+ return 1
337
+ except KeyboardInterrupt:
338
+ return 130
339
+
340
+
341
+ if __name__ == "__main__":
342
+ sys.exit(main())