AI video skill for Claude Code & Codex — cinematic, editable product promos with Remotion: 124 shot recipe cards, 150 motion previews, beat sync, sound design, Motion Workbench & JianYing (CapCut CN) export.
TypeScript agent-skillsai-agentsai-videoclaude-codeclaude-code-skillsclaude-skillscodexmotion-designmotion-graphicsproduct-videopromo-videoremotionvideo-generationvideo-production
feat(publish): optional social publishing of the finished film via Upload-Post (#93)
Juan Carlos Cavero Graciae9d9b902e894
diff --git a/README.md b/README.mdindex 2dfecb5..0a71677 100644--- a/README.md+++ b/README.md@@ -181,6 +181,7 @@ With these three flags, frame renders from the bundled template work.| Components and assets | 2.5D page camera, captions, flash cuts, digit rolls, SFX, and capture scripts || Production methodology | Capture, visual direction, storyboarding, sound design, beat sync, and final QA || JianYing project export | Load the film into JianYing (CapCut CN) for further editing — per-shot speed, captions, and audio all editable (verified on macOS 11.2) |+| Social publishing (optional) | When you ask for it, publish the finished film to TikTok, Instagram, YouTube, LinkedIn, X and more via the Upload-Post API. Caption and platforms are confirmed first, with a dry-run before posting ([guide](references/publish-upload-post.md)) || Motion workbench | Browser timeline editor opened after delivery: split the film into tracks, edit exposed shot properties, retime, drag in any of the 216 demo motions, export via Remotion |The toolkit primarily targets web and desktop product promos, while individual@@ -200,11 +201,13 @@ video-shotcraft/│ ├── music-beat-sync.md # BGM analysis and beat-sync methodology│ ├── sound-design.md # Sound-design guidance and examples│ ├── jianying-export.md # JianYing (CapCut CN) project-export guide+│ ├── publish-upload-post.md # Optional social publishing (Upload-Post API)│ └── workbench.md # Motion workbench: manifest contract + editability rules├── demos/ # Remotion reference implementations (same categories)├── gallery/ # Static motion-preview Gallery├── template/ # Runnable complete video template├── jianying-export/ # JianYing draft installers (mac tested / win untested)+├── publish/ # Optional social publisher (stdlib-only Python) + offline tests├── workbench/ # Post-delivery motion workbench (Vite + Remotion Player)└── assets/├── lib/ # Reusable Remotion componentsdiff --git a/README_CN.md b/README_CN.mdindex a00c802..8a78c47 100644--- a/README_CN.md+++ b/README_CN.md@@ -161,6 +161,7 @@ agent 会替换成目标产品的截图、文案和品牌信息,复现同等| 组件与素材 | 2.5D 页面相机、字幕、闪切、数字滚动、音效和素材采集脚本 || 制作方法论 | 从素材采集、风格定调和分镜,到声音设计、节奏卡点与最终验收 || 剪映工程导出 | 成片可装进剪映继续编辑:镜头变速/字幕/音轨全开放(Mac 11.2 实测) |+| 社交平台发布(可选) | 用户要求时,通过 Upload-Post API 把成片发到 TikTok / Instagram / YouTube / LinkedIn / X 等;先确认文案与平台、dry-run 后再发([说明](references/publish-upload-post.md)) || 动效工作台 | 交付后自动打开的浏览器时间线编辑器:成片拆多轨、改镜头开放属性、变速重排、拖入 216 个 demo 动效、Remotion 导出 |当前主要面向 Web 与桌面产品宣传片,但镜头卡也可以单独用于功能演示、@@ -179,11 +180,13 @@ video-shotcraft/│ ├── music-beat-sync.md # BGM 节奏分析与卡点方法│ ├── sound-design.md # 声音设计方法与判例│ ├── jianying-export.md # 剪映工程导出方法+│ ├── publish-upload-post.md # 社交平台发布(可选,Upload-Post API)│ └── workbench.md # 动效工作台:成片接入契约 + 可编辑性规则├── demos/ # 镜头卡的 Remotion 参考实现(同类别目录)├── gallery/ # 在线样片画廊的静态站点├── template/ # 可直接运行的完整成片模板├── jianying-export/ # 剪映草稿安装模块(Mac 实测 / Windows 未验证)+├── publish/ # 社交平台发布脚本(纯标准库 Python)+ 离线单测├── workbench/ # 交付后的动效工作台(Vite + Remotion Player)└── assets/├── lib/ # 可复制使用的 Remotion 组件diff --git a/README_JA.md b/README_JA.mdindex ed9accc..305b1db 100644--- a/README_JA.md+++ b/README_JA.md@@ -172,6 +172,7 @@ Use video-shotcraft to make a promo for my product with the Ink Press template.| コンポーネントとアセット | 2.5D ページカメラ、キャプション、フラッシュカット、数字ロール、SFX、キャプチャスクリプト || 制作手法 | キャプチャ、ビジュアルディレクション、ストーリーボード、サウンドデザイン、ビート同期、最終 QA || 剪映プロジェクト書き出し | 完成映像を剪映(CapCut 中国版)で継続編集——ショット変速・字幕・音声トラックを編集可(macOS 11.2 実機検証済み) |+| SNS 投稿(任意) | 依頼があれば、Upload-Post API で完成映像を TikTok・Instagram・YouTube・LinkedIn・X などへ投稿。キャプションと投稿先を確認し、dry-run の後に投稿([ガイド](references/publish-upload-post.md)) || モーションワークベンチ | 納品後に開くブラウザのタイムラインエディタ:映像をトラックに分解、公開されたショット属性の編集、再タイミング、216 個の demo モーションのドラッグ投入、Remotion 書き出し |このツールキットは主に Web およびデスクトップ製品のプロモーションを対象としていますが、@@ -191,11 +192,13 @@ video-shotcraft/│ ├── music-beat-sync.md # BGM analysis and beat-sync methodology│ ├── sound-design.md # Sound-design guidance and examples│ ├── jianying-export.md # JianYing (CapCut CN) project-export guide+│ ├── publish-upload-post.md # Optional social publishing (Upload-Post API)│ └── workbench.md # Motion workbench: manifest contract + editability rules├── demos/ # Remotion reference implementations for shot cards├── gallery/ # Static motion-preview Gallery├── template/ # Runnable complete video template├── jianying-export/ # JianYing draft installers (mac tested / win untested)+├── publish/ # Optional social publisher (stdlib-only Python) + offline tests├── workbench/ # Post-delivery motion workbench (Vite + Remotion Player)└── assets/├── lib/ # Reusable Remotion componentsdiff --git a/SKILL.md b/SKILL.mdindex ad83db0..6e48d49 100644--- a/SKILL.md+++ b/SKILL.md@@ -204,6 +204,11 @@ node workbench/scripts/open.mjs <成片工程目录> # 链接工程 → 起 de字幕内容/字号/颜色、给分镜头变速或重排、调整或替换音频。用户需要或直接点名导出时,读 `references/jianying-export.md` 执行。+**用户主动要求把成片发到社交平台时**(TikTok / Instagram / YouTube / LinkedIn / X 等),+读 `references/publish-upload-post.md` 执行:先确认文案和平台清单,dry-run 通过后再发布。+发布命令只跑一次;结果为 `unknown`、超时或报错时**绝不重跑**,只用 `--status <requestId>` 查询。+这不是第 4 条推荐,用户没提就不要说。+## 何时读哪个文件| 时机 | 读 |@@ -220,6 +225,7 @@ node workbench/scripts/open.mjs <成片工程目录> # 链接工程 → 起 de| 逐镜头实现时写 `src/workbench.ts` 清单 / 镜头 props+schema | workbench.md §2–3(范例 `template/src/workbench.ts`) || 成片交付后(打开动效工作台) | workbench.md(`node workbench/scripts/open.mjs <工程>`;工作台自身文档 `workbench/README.md`) || 成片交付后(剪映工程导出) | jianying-export.md + `jianying-export/` 平台模块 |+| 用户要求发布到社交平台 | publish-upload-post.md + `publish/upload_post.py` |## 资产使用方式@@ -258,6 +264,10 @@ node workbench/scripts/open.mjs <成片工程目录> # 链接工程 → 起 de`smoke_test.py`(新环境先跑的最小冒烟测试)。流程、时间线提取与建轨方法见 `references/jianying-export.md`;需 venv + `pip installpyJianYingDraft`。+- `publish/upload_post.py` 社交平台发布(Upload-Post API,纯标准库):+ 用户要求时把成片发到 TikTok / Instagram / YouTube / LinkedIn / X 等,流程见+ `references/publish-upload-post.md`;需 `UPLOAD_POST_API_KEY` ++ `UPLOAD_POST_USER`。离线单测 `python3 -m unittest publish/test_upload_post.py`。- `gallery/` 静态画廊:优先直接给用户在线版https://vincentwei1021.github.io/video-shotcraft/library.html ;本地跑则先 `gallery/fetch-media.sh` 拉样片(mp4 不在 git 里),再diff --git a/publish/test_upload_post.py b/publish/test_upload_post.pynew file mode 100644index 0000000..798f5ca--- /dev/null+++ b/publish/test_upload_post.py@@ -0,0 +1,284 @@+"""upload_post.py 离线单测(不联网,不需要 key)。++ python3 -m unittest publish/test_upload_post.py -v+"""+import copy+import http.client+import io+import json+import sys+import tempfile+import unittest+import urllib.error+from pathlib import Path+from unittest import mock++sys.path.insert(0, str(Path(__file__).parent))+import upload_post as up # noqa: E402+++def run_cli(argv, *, post=None, gets=()):+ """跑一次 main(),返回 (退出码, JSON 输出, post mock, get mock)。"""+ out = io.StringIO()+ err = io.StringIO()+ # gets: 依次返回的 GET 响应列表;最后一个会一直重复(模拟持续同一状态)+ gets = list(gets)++ def fake_request(method, path, api_key, **kw):+ if method == "POST":+ if isinstance(post, BaseException):+ raise post+ return post+ resp = gets.pop(0) if len(gets) > 1 else gets[0]+ if isinstance(resp, Exception):+ raise resp+ return copy.deepcopy(resp) # main() 会改返回的 dict,不能污染共享样例++ with mock.patch.object(sys, "argv", ["upload_post.py", *argv]), \+ mock.patch.dict("os.environ", {"UPLOAD_POST_API_KEY": "k"}), \+ mock.patch.object(up, "_request", side_effect=fake_request) as req, \+ mock.patch.object(up.time, "sleep"), \+ mock.patch("sys.stdout", out), mock.patch("sys.stderr", err):+ try:+ up.main()+ except SystemExit as e:+ code = e.code+ except BaseException: # 模拟进程中途死掉:保留 stderr 供断言+ run_cli.last_stderr = err.getvalue()+ raise+ run_cli.last_stderr = err.getvalue()+ line = out.getvalue().strip().splitlines()+ return code, json.loads(line[-1]) if line else None, req+++class UploadPostTest(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.video = Path(self.tmp.name) / "promo.mp4"+ self.video.write_bytes(b"\x00" * 64)+ self.base = ["--video", str(self.video), "--title", "t", "--user", "u", "--json-out"]++ def tearDown(self):+ self.tmp.cleanup()++ def test_network_error_polls_same_id_without_resending(self):+ code, js, req = run_cli(+ self.base + ["--platforms", "tiktok"],+ post=urllib.error.URLError("reset"),+ gets=[(200, {"status": "completed", "results": [+ {"platform": "tiktok", "success": True, "post_url": "https://tiktok.com/@a/video/1"}]})],+ )+ self.assertEqual(code, 0)+ self.assertTrue(js["success"])+ posts = [c for c in req.call_args_list if c.args[0] == "POST"]+ self.assertEqual(len(posts), 1)+ sent_id = posts[0].kwargs["headers"]["Idempotency-Key"]+ poll = [c for c in req.call_args_list if c.args[0] == "GET"][0]+ self.assertEqual(poll.kwargs["params"], {"request_id": sent_id})++ def test_mixed_results_fail_and_are_normalized(self):+ code, js, _ = run_cli(+ self.base + ["--platforms", "tiktok,x,linkedin"],+ post=(200, {"request_id": "r"}),+ gets=[(200, {"status": "completed", "results": [+ {"platform": "tiktok", "success": True, "post_url": "https://t/1"},+ {"platform": "x", "success": False, "error_message": "boom"},+ {"platform": "linkedin", "success": False, "skipped": True}]})],+ )+ self.assertEqual(code, 1)+ got = {r["platform"]: (r["status"], r["error"]) for r in js["results"]}+ self.assertEqual(got, {"tiktok": ("completed", None), "x": ("failed", "boom"),+ "linkedin": ("skipped", None)})++ def test_all_skipped_is_not_success(self):+ code, js, _ = run_cli(+ self.base + ["--platforms", "linkedin"], post=(200, {}),+ gets=[(200, {"status": "completed", "results": [{"platform": "linkedin", "skipped": True}]})],+ )+ self.assertEqual(code, 1)+ self.assertFalse(js["success"])++ def test_private_youtube_gets_watch_url_and_note_kept_elsewhere(self):+ res = up.summarize_results({"results": [+ {"platform": "youtube", "success": True, "platform_post_id": "abc",+ "post_url": "Post uploaded as Private. No public URL available."},+ {"platform": "tiktok", "success": True, "platform_post_id": "v1", "post_url": None}]})+ self.assertEqual(res[0]["url"], "https://www.youtube.com/watch?v=abc")+ self.assertIsNone(res[1]["url"])+ self.assertEqual(res[1]["postId"], "v1")++ def test_timeout_reports_still_running(self):+ code, js, _ = run_cli(+ self.base + ["--platforms", "tiktok", "--wait-timeout", "0"], post=(200, {}),+ gets=[(200, {"status": "processing", "results": []})],+ )+ self.assertEqual(code, 0)+ self.assertTrue(js["timedOut"])++ def test_401_is_auth_error(self):+ code, js, _ = run_cli(self.base + ["--platforms", "tiktok"], post=(401, {"message": "Invalid API key"}))+ self.assertEqual((code, js["errorType"]), (1, "auth"))++ def test_validation_happens_before_any_request(self):+ for extra, needle in (+ (["--platforms", "mastodon"], "Unsupported"),+ (["--platforms", "pinterest"], "pinterest-board"),+ (["--platforms", "x", "--schedule", "2020-01-01T00:00:00Z"], "future"),+ ):+ code, js, req = run_cli(self.base + extra)+ self.assertEqual(code, 1)+ self.assertIn(needle, js["error"])+ req.assert_not_called()++ def test_form_fields(self):+ args = mock.Mock(user="u", title="t", platforms=["youtube", "tiktok", "pinterest"],+ schedule=None, timezone=None, first_comment=None, ai_generated=True,+ youtube_privacy="private", tags="a, b", tiktok_privacy="SELF_ONLY",+ tiktok_draft=True, instagram_story=False, facebook_page_id=None,+ linkedin_page_id=None, pinterest_board="B")+ form = up.build_form(args, "", "rid")+ for kv in [("platform[]", "youtube"), ("tags[]", "a"), ("tags[]", "b"),+ ("is_ai_generated", "true"), ("privacy_level", "SELF_ONLY"),+ ("post_mode", "MEDIA_UPLOAD"), ("pinterest_board_id", "B"),+ ("privacyStatus", "private"), ("request_id", "rid"), ("async_upload", "true")]:+ self.assertIn(kv, form)++ def test_multipart_encoding(self):+ body, ctype = up.encode_multipart([("platform[]", "x"), ("title", "标题")],+ [("video", "a.mp4", b"DATA", "video/mp4")])+ boundary = ctype.split("boundary=")[1]+ self.assertTrue(body.endswith(f"--{boundary}--\r\n".encode()))+ self.assertIn('name="title"\r\n\r\n标题'.encode(), body)+ self.assertIn(b'filename="a.mp4"\r\nContent-Type: video/mp4\r\n\r\nDATA', body)+++COMPLETED = (200, {"status": "completed", "results": [+ {"platform": "tiktok", "success": True, "post_url": "https://tiktok.com/@a/video/1"}]})+++class AmbiguousSubmitTest(unittest.TestCase):+ """提交结果不确定时绝不重发,只按同一 request_id 查询。"""++ setUp = UploadPostTest.setUp+ tearDown = UploadPostTest.tearDown++ def _posts_and_ids(self, req):+ posts = [c for c in req.call_args_list if c.args[0] == "POST"]+ gets = [c for c in req.call_args_list if c.args[0] == "GET"]+ return posts, posts[0].kwargs["headers"]["Idempotency-Key"], gets++ def test_503_then_status_completed_is_success_without_resend(self):+ code, js, req = run_cli(self.base + ["--platforms", "tiktok"],+ post=(503, {"message": "Service Unavailable"}), gets=[COMPLETED])+ posts, sent_id, gets = self._posts_and_ids(req)+ self.assertEqual((code, js["success"], len(posts)), (0, True, 1))+ self.assertTrue(all(g.kwargs["params"] == {"request_id": sent_id} for g in gets))++ def test_503_then_not_found_is_unknown_with_request_id(self):+ for status in (500, 502, 503):+ code, js, req = run_cli(self.base + ["--platforms", "tiktok"],+ post=(status, {}), gets=[(404, {"status": "not_found"})])+ posts, sent_id, _ = self._posts_and_ids(req)+ self.assertEqual(code, 2)+ self.assertEqual(js["status"], "unknown")+ self.assertFalse(js["success"])+ self.assertTrue(js["doNotRerun"])+ self.assertEqual(js["requestId"], sent_id)+ self.assertIn(f"--status {sent_id}", js["statusCommand"])+ self.assertEqual(len(posts), 1)++ def test_503_then_status_errors_is_unknown(self):+ code, js, req = run_cli(self.base + ["--platforms", "tiktok"],+ post=(503, {}), gets=[(500, {"message": "boom"})])+ self.assertEqual((code, js["status"]), (2, "unknown"))+ self.assertEqual(len(self._posts_and_ids(req)[0]), 1)++ def test_empty_2xx_is_treated_as_accepted(self):+ code, js, req = run_cli(self.base + ["--platforms", "tiktok"],+ post=(200, {"_invalid": True, "message": ""}), gets=[COMPLETED])+ self.assertEqual((code, js["success"]), (0, True))+ self.assertEqual(len(self._posts_and_ids(req)[0]), 1)++ def test_transport_error_then_not_found_is_unknown(self):+ code, js, _ = run_cli(self.base + ["--platforms", "tiktok"],+ post=urllib.error.URLError("reset"), gets=[(404, {})])+ self.assertEqual((code, js["status"]), (2, "unknown"))++ def test_4xx_before_acceptance_is_definitive_and_not_polled(self):+ for status, etype in ((400, "validation"), (401, "auth"), (403, "forbidden"), (422, "validation")):+ code, js, req = run_cli(self.base + ["--platforms", "tiktok"], post=(status, {"message": "no"}),+ gets=[COMPLETED])+ self.assertEqual((code, js["errorType"]), (1, etype))+ self.assertEqual([c for c in req.call_args_list if c.args[0] == "GET"], [])++ def test_accepted_but_never_found_is_unknown_not_failure(self):+ code, js, _ = run_cli(self.base + ["--platforms", "tiktok"],+ post=(200, {"request_id": "r"}), gets=[(404, {})])+ self.assertEqual((code, js["status"]), (2, "unknown"))++ def test_status_poll_errors_after_acceptance_are_unknown_not_failure(self):+ code, js, _ = run_cli(self.base + ["--platforms", "tiktok"],+ post=(200, {"request_id": "r"}), gets=[(502, {"message": "bad gateway"})])+ self.assertEqual((code, js["status"]), (2, "unknown"))+++class ReviewRegressionTest(unittest.TestCase):+ """PR #93 review: truncated responses and the scheduled status command."""++ setUp = UploadPostTest.setUp+ tearDown = UploadPostTest.tearDown++ def _sent_id(self, req):+ posts = [c for c in req.call_args_list if c.args[0] == "POST"]+ self.assertEqual(len(posts), 1)+ return posts[0].kwargs["headers"]["Idempotency-Key"]++ def test_incomplete_read_on_submit_is_ambiguous_and_actionable(self):+ code, js, req = run_cli(self.base + ["--platforms", "tiktok"],+ post=http.client.IncompleteRead(b"partial"), gets=[(404, {})])+ sent_id = self._sent_id(req)+ self.assertEqual((code, js["status"], js["requestId"]), (2, "unknown", sent_id))+ self.assertTrue(js["doNotRerun"])+ self.assertIn(f"--status {sent_id}", js["statusCommand"])++ def test_incomplete_read_then_found_keeps_the_same_id(self):+ code, js, req = run_cli(self.base + ["--platforms", "tiktok"],+ post=http.client.IncompleteRead(b""), gets=[COMPLETED])+ sent_id = self._sent_id(req)+ self.assertEqual((code, js["success"], js["requestId"]), (0, True, sent_id))+ gets = [c for c in req.call_args_list if c.args[0] == "GET"]+ self.assertTrue(gets and all(g.kwargs["params"] == {"request_id": sent_id} for g in gets))++ def test_other_http_client_errors_are_ambiguous(self):+ for exc in (http.client.RemoteDisconnected("closed"), ConnectionResetError("reset")):+ code, js, req = run_cli(self.base + ["--platforms", "tiktok"], post=exc, gets=[(404, {})])+ self.assertEqual((code, js["status"]), (2, "unknown"))+ self._sent_id(req)++ def test_request_id_is_logged_before_sending(self):+ # 进程在发送途中死掉:stderr 里必须已经有可用的恢复命令+ with self.assertRaises(KeyboardInterrupt):+ run_cli(self.base + ["--platforms", "tiktok"], post=KeyboardInterrupt())+ logged = run_cli.last_stderr+ match = __import__("re").search(r"--status ([0-9a-f-]{36})", logged)+ self.assertIsNotNone(match, logged)+ self.assertIn(f"request_id {match.group(1)}", logged)++ def test_scheduled_status_command_uses_job_id_and_queries_it(self):+ job_id = "a" * 32+ code, js, _ = run_cli(+ self.base + ["--platforms", "x", "--schedule", "2099-01-01T09:00:00Z"],+ post=(202, {"success": True, "job_id": job_id, "request_id": "r"}))+ self.assertEqual((code, js["status"], js["jobId"]), (0, "scheduled", job_id))+ self.assertTrue(js["statusCommand"].endswith(f"--status {job_id}"))+ # 按输出的命令查询:第一次请求必须是 job_id+ status_args = js["statusCommand"].split("upload_post.py ", 1)[1].split()+ code, js2, req = run_cli(status_args + ["--json-out"],+ gets=[(200, {"status": "pending", "job_id": job_id, "results": []})])+ first_get = [c for c in req.call_args_list if c.args[0] == "GET"][0]+ self.assertEqual(first_get.kwargs["params"], {"job_id": job_id})+ self.assertEqual(js2["jobId"], job_id)+++if __name__ == "__main__":+ unittest.main()diff --git a/publish/upload_post.py b/publish/upload_post.pynew file mode 100644index 0000000..26e9bb8--- /dev/null+++ b/publish/upload_post.py@@ -0,0 +1,558 @@+#!/usr/bin/env python3+"""成片一键发布到社交平台(Upload-Post API)。++把交付的 MP4 一次发到 TikTok、Instagram(Reels/Stories)、YouTube、LinkedIn、+Facebook、X、Threads、Pinterest、Bluesky。只在用户明确要求发布、并确认过文案与+平台后执行,流程见 references/publish-upload-post.md。++仅用 Python 标准库,无需 venv / pip。需要两个环境变量:+ UPLOAD_POST_API_KEY Upload-Post 后台创建的 API key+ UPLOAD_POST_USER 连接了社交账号的 profile 名(也可用 --user)++用法:+ # 只校验,不发布(同时检查 key、profile、哪些平台未连接)+ python3 publish/upload_post.py --video out/promo.mp4 --title "..." \\+ --platforms tiktok,instagram,youtube --dry-run++ # 发布并等待每个平台的结果+ python3 publish/upload_post.py --video out/promo.mp4 --title "..." \\+ --platforms tiktok,instagram,youtube++ # 定时发布(按指定时区)+ python3 publish/upload_post.py --video out/promo.mp4 --title "..." \\+ --platforms linkedin,x --schedule 2026-10-01T09:00:00 --timezone Asia/Shanghai++ # 查询之前的发布+ python3 publish/upload_post.py --status <request_id 或 job_id>++行为要点:+ * 视频只上传一次,Upload-Post 分发到各平台,按平台返回链接或错误。+ * 异步上传:API 收到文件即返回 request_id,脚本轮询状态直到全部平台结束+ (或 --wait-timeout 超时;超时不取消,稍后用 --status 查)。+ * 防重复发布:request_id 由脚本生成并作为 Idempotency-Key 发送。只有+ 400/401/403/422 算明确拒绝;5xx、超时、断网、2xx 却无有效 JSON 都算"不确定",+ 不重发文件,改用同一个 id 查询;仍无法确认时输出 status=unknown(退出码 2)、+ request_id 和 --status 命令。unknown 之后绝不能重跑发布命令,只能 --status。+ * profile 未连接的平台返回 skipped,不影响其他平台。+ * YouTube 默认 private;TikTok 默认沿用账号自身隐私设置。+"""+from __future__ import annotations++import argparse+import http.client+import json+import mimetypes+import os+import re+import socket+import sys+import time+import urllib.error+import urllib.parse+import urllib.request+import uuid+from datetime import datetime, timezone+from pathlib import Path++API_BASE = "https://api.upload-post.com"++VIDEO_PLATFORMS = (+ "tiktok", "instagram", "youtube", "linkedin", "facebook",+ "x", "threads", "pinterest", "bluesky",+)+PLATFORM_ALIASES = {"twitter": "x", "reels": "instagram", "shorts": "youtube"}+YOUTUBE_PRIVACY = ("private", "unlisted", "public")+TIKTOK_PRIVACY = (+ "PUBLIC_TO_EVERYONE", "MUTUAL_FOLLOW_FRIENDS", "FOLLOWER_OF_CREATOR", "SELF_ONLY",+)+FINAL_STATUSES = {"completed", "failed", "not_found"}+POLL_INTERVAL_SECS = 10+DEFAULT_WAIT_SECS = 600+UPLOAD_TIMEOUT = 900+API_TIMEOUT = 60+TITLE_MAX = {"youtube": 100, "tiktok": 2200}++# 网络层错误:上传可能已送达,也可能没有,不重发,改查同一 request_id+# http.client.HTTPException 覆盖读响应体时的截断(IncompleteRead)、对端断开+# (RemoteDisconnected)等;ConnectionError 覆盖 ConnectionResetError。+NETWORK_ERRORS = (urllib.error.URLError, socket.timeout, ConnectionError, TimeoutError,+ http.client.HTTPException)+# 只有这些是"服务端受理前明确拒绝":可以直接判失败。其余(5xx、网关错误、+# 超时、2xx 却无有效 JSON)都算"不确定",文件可能已被受理,绝不能重发。+DEFINITIVE_REJECTIONS = {400, 401, 403, 422}+PROBE_ATTEMPTS = 6 # 不确定时按同一 request_id 探查的次数(×POLL_INTERVAL_SECS)+NOT_FOUND_GRACE_POLLS = 6 # 已受理后 status 仍 not_found 的容忍次数(记录可能稍晚写入)+MAX_POLL_ERRORS = 6 # 轮询期间连续出错的容忍次数+++class AmbiguousSubmit(Exception):+ """提交结果不确定:服务端可能已受理。只能按同一 request_id 查询,不能重发。"""+++class ApiError(Exception):+ def __init__(self, message: str, error_type: str = "http", status: int | None = None):+ super().__init__(message)+ self.error_type = error_type+ self.status = status+++def log(msg: str) -> None:+ """日志走 stderr;stdout 只留给 --json-out。"""+ print(msg, file=sys.stderr)+++# ---------------------------------------------------------------- HTTP+def classify_status(status: int) -> str:+ if status == 401:+ return "auth"+ if status in (400, 422):+ return "validation"+ if status == 429:+ return "quota"+ if status == 403:+ return "forbidden"+ return "http"+++def _request(method: str, path: str, api_key: str, *, params: dict | None = None,+ body: bytes | None = None, headers: dict | None = None,+ timeout: int = API_TIMEOUT) -> tuple[int, dict]:+ url = f"{API_BASE}{path}"+ if params:+ url += "?" + urllib.parse.urlencode(params)+ # Upload-Post 的 API key 用 "Apikey" 方案,不是 "Bearer"+ hdrs = {"Authorization": f"Apikey {api_key}", **(headers or {})}+ req = urllib.request.Request(url, data=body, headers=hdrs, method=method)+ try:+ with urllib.request.urlopen(req, timeout=timeout) as resp:+ status, raw = resp.status, resp.read()+ except urllib.error.HTTPError as e:+ status, raw = e.code, e.read()+ try:+ data = json.loads(raw)+ except ValueError: # 空响应或非 JSON+ return status, {"_invalid": True, "message": raw[:300].decode("utf-8", "replace")}+ return status, data if isinstance(data, dict) else {"data": data}+++def _check(status: int, data: dict) -> dict:+ if status < 400:+ return data+ msg = data.get("message") or data.get("error") or str(data)+ raise ApiError(f"HTTP {status}: {msg}", classify_status(status), status)+++def api_get(api_key: str, path: str, params: dict | None = None) -> dict:+ try:+ return _check(*_request("GET", path, api_key, params=params))+ except NETWORK_ERRORS as e:+ raise ApiError(f"Network error: {e}", "http")+++def check_account(api_key: str, user: str) -> dict:+ """校验 key 并列出 profile 已连接的平台。"""+ me = api_get(api_key, "/api/uploadposts/me")+ profile = api_get(api_key, f"/api/uploadposts/users/{urllib.parse.quote(user)}")+ accounts = (profile.get("profile") or profile).get("social_accounts") or {}+ connected = sorted(PLATFORM_ALIASES.get(p, p) for p, acc in accounts.items() if acc)+ return {"plan": me.get("plan"), "connected": connected}+++def get_status(api_key: str, *, request_id: str | None = None, job_id: str | None = None) -> dict:+ params = {"request_id": request_id} if request_id else {"job_id": job_id}+ try:+ status, data = _request("GET", "/api/uploadposts/status", api_key, params=params)+ except NETWORK_ERRORS as e:+ raise ApiError(f"Network error: {e}", "http")+ if status == 404:+ return {"status": "not_found", **params}+ if status < 400 and data.get("_invalid"):+ raise ApiError(f"HTTP {status}: empty or non-JSON status response", "http", status)+ return _check(status, data)+++def encode_multipart(fields: list[tuple[str, str]], files: list[tuple[str, str, bytes, str]]):+ """标准库版 multipart/form-data。files: (字段名, 文件名, 内容, MIME)。"""+ boundary = f"----shotcraft{uuid.uuid4().hex}"+ out = bytearray()+ for name, value in fields:+ out += (f"--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n"+ f"{value}\r\n").encode("utf-8")+ for name, filename, content, mime in files:+ out += (f"--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"; "+ f"filename=\"{filename}\"\r\nContent-Type: {mime}\r\n\r\n").encode("utf-8")+ out += content + b"\r\n"+ out += f"--{boundary}--\r\n".encode()+ return bytes(out), f"multipart/form-data; boundary={boundary}"+++# ---------------------------------------------------------------- 请求构造+def parse_platforms(raw: str | None) -> list[str]:+ platforms: list[str] = []+ for p in (raw or "").split(","):+ p = PLATFORM_ALIASES.get(p.strip().lower(), p.strip().lower())+ if p and p not in platforms:+ platforms.append(p)+ return platforms+++def build_form(args, description: str, request_id: str) -> list[tuple[str, str]]:+ """表单字段(视频文件除外)。platform[] / tags[] 可重复,所以用列表。"""+ form = [("user", args.user), ("title", args.title),+ ("request_id", request_id), ("async_upload", "true")]+ form += [("platform[]", p) for p in args.platforms]+ if description:+ form.append(("description", description))+ if args.schedule:+ form.append(("scheduled_date", args.schedule))+ if args.timezone:+ form.append(("timezone", args.timezone))+ if args.first_comment:+ form.append(("first_comment", args.first_comment))+ if args.ai_generated:+ # 跨平台别名:TikTok AIGC 标签、Instagram "AI info"、YouTube 合成内容声明、X made_with_ai+ form.append(("is_ai_generated", "true"))+ if "youtube" in args.platforms:+ form.append(("privacyStatus", args.youtube_privacy))+ form += [("tags[]", t.strip()) for t in (args.tags or "").split(",") if t.strip()]+ if "tiktok" in args.platforms:+ if args.tiktok_privacy:+ form.append(("privacy_level", args.tiktok_privacy))+ if args.tiktok_draft:+ form.append(("post_mode", "MEDIA_UPLOAD"))+ if "instagram" in args.platforms and args.instagram_story:+ form.append(("media_type", "STORIES"))+ if "facebook" in args.platforms and args.facebook_page_id:+ form.append(("facebook_page_id", args.facebook_page_id))+ if "linkedin" in args.platforms and args.linkedin_page_id:+ form.append(("target_linkedin_page_id", args.linkedin_page_id))+ if "pinterest" in args.platforms:+ form.append(("pinterest_board_id", args.pinterest_board))+ return form+++def submit_upload(api_key: str, video: str, form: list, thumbnail: str | None, request_id: str) -> dict:+ files = [("video", Path(video).name, Path(video).read_bytes(), "video/mp4")]+ if thumbnail:+ mime = mimetypes.guess_type(thumbnail)[0] or "image/png"+ files.append(("thumbnail", Path(thumbnail).name, Path(thumbnail).read_bytes(), mime))+ body, content_type = encode_multipart(form, files)+ try:+ status, data = _request(+ "POST", "/api/upload", api_key, body=body, timeout=UPLOAD_TIMEOUT,+ headers={"Content-Type": content_type, "Idempotency-Key": request_id},+ )+ except NETWORK_ERRORS as e:+ raise AmbiguousSubmit(f"network error: {e}")+ if status in DEFINITIVE_REJECTIONS:+ _check(status, data) # 抛出 ApiError:受理前明确拒绝,可放心判失败+ if status >= 400:+ raise AmbiguousSubmit(f"HTTP {status}: {data.get('message') or data.get('error') or ''}".strip())+ if data.get("_invalid"):+ raise AmbiguousSubmit(f"HTTP {status} with an empty or non-JSON body")+ return data+++def probe_submission(api_key: str, request_id: str) -> dict | None:+ """不确定提交后按同一 request_id 查询:服务端有记录就返回状态,否则 None。"""+ for attempt in range(PROBE_ATTEMPTS):+ try:+ status = get_status(api_key, request_id=request_id)+ if status.get("status") != "not_found":+ return status+ except ApiError:+ pass+ if attempt < PROBE_ATTEMPTS - 1:+ time.sleep(POLL_INTERVAL_SECS)+ return None+++def wait_for_result(api_key: str, request_id: str, wait_secs: int) -> dict:+ deadline = time.monotonic() + wait_secs+ last = None+ not_found = errors = 0+ while True:+ try:+ status = get_status(api_key, request_id=request_id)+ errors = 0+ except ApiError as e:+ # 已提交后查询出错:不能判失败(上传可能正在进行)+ errors += 1+ if errors >= MAX_POLL_ERRORS or time.monotonic() >= deadline:+ return {"status": "unknown", "request_id": request_id, "reason": str(e)}+ time.sleep(POLL_INTERVAL_SECS)+ continue+ state = status.get("status")+ if state == "not_found":+ # 我们确实发出了上传:not_found 只说明记录还没写入或无法确认,不是失败+ not_found += 1+ if not_found >= NOT_FOUND_GRACE_POLLS or time.monotonic() >= deadline:+ return {"status": "unknown", "request_id": request_id,+ "reason": "the server has no record of this request_id yet"}+ time.sleep(POLL_INTERVAL_SECS)+ continue+ progress = f"{status.get('completed', 0)}/{status.get('total', '?')}"+ if (state, progress) != last:+ log(f" 状态 status: {state} ({progress})")+ last = (state, progress)+ if state in FINAL_STATUSES:+ return status+ if time.monotonic() >= deadline:+ status["timedOut"] = True+ return status+ time.sleep(POLL_INTERVAL_SECS)+++def summarize_results(status: dict) -> list[dict]:+ """把各平台结果统一成 [{platform, status, url, postId, note, error, inbox}]。"""+ raw = status.get("results") or []+ if isinstance(raw, dict):+ raw = [{"platform": p, **r} for p, r in raw.items()]+ out = []+ for r in raw:+ if r.get("skipped"):+ state = "skipped"+ elif r.get("status"):+ state = r["status"]+ else:+ state = "completed" if r.get("success") else "failed"+ platform = r.get("platform")+ post_id = r.get("platform_post_id") or r.get("video_id")+ raw_url = r.get("post_url") or r.get("url")+ url = raw_url if raw_url and str(raw_url).startswith("http") else None+ if not url and platform == "youtube" and post_id:+ url = f"https://www.youtube.com/watch?v={post_id}" # private 视频本人也能打开+ out.append({+ "platform": platform,+ "status": state,+ "url": url,+ "postId": post_id,+ "note": raw_url if raw_url and not url else None, # 如 "Post uploaded as Private..."+ "error": (r.get("error_message") or r.get("error")) if state != "completed" else None,+ "inbox": bool(r.get("fallback_to_inbox")),+ })+ return out+++# ---------------------------------------------------------------- 校验与输出+def parse_schedule(value: str, tz: str | None) -> str:+ raw = value.strip()+ dt = datetime.fromisoformat(raw[:-1] + "+00:00" if raw.endswith("Z") else raw)+ if tz: # 带 --timezone 时保持本地时间,由 API 按该时区解释+ return dt.replace(tzinfo=None).strftime("%Y-%m-%dT%H:%M:%S")+ if dt.tzinfo is None:+ dt = dt.replace(tzinfo=timezone.utc)+ dt = dt.astimezone(timezone.utc)+ if dt <= datetime.now(timezone.utc):+ raise ValueError("in the past")+ return dt.strftime("%Y-%m-%dT%H:%M:%SZ")+++def validate_args(args) -> str | None:+ """任何网络请求之前校验,参数错误不会浪费一次上传。"""+ if not args.video:+ return "Missing --video."+ vpath = Path(args.video)+ if not vpath.exists():+ return f"Video file not found: {args.video}"+ if vpath.stat().st_size == 0:+ return f"Video file is empty: {args.video}"+ if not args.title or not args.title.strip():+ return "Missing --title (the caption)."+ if not args.user:+ return "Missing --user. Set UPLOAD_POST_USER or pass --user."+ args.platforms = parse_platforms(args.platforms)+ if not args.platforms:+ return f"Missing --platforms. Choose from: {', '.join(VIDEO_PLATFORMS)}"+ unknown = [p for p in args.platforms if p not in VIDEO_PLATFORMS]+ if unknown:+ return f"Unsupported platform(s): {', '.join(unknown)}. Choose from: {', '.join(VIDEO_PLATFORMS)}"+ if "pinterest" in args.platforms and not args.pinterest_board:+ return "Pinterest needs --pinterest-board BOARD_ID."+ for platform, limit in TITLE_MAX.items():+ if platform in args.platforms and len(args.title) > limit:+ return f"--title is {len(args.title)} chars; {platform} allows {limit}."+ if args.schedule:+ try:+ args.schedule = parse_schedule(args.schedule, args.timezone)+ except ValueError:+ return f"--schedule must be a future ISO8601 timestamp: {args.schedule}"+ if args.thumbnail and not Path(args.thumbnail).exists():+ return f"--thumbnail not found: {args.thumbnail}"+ return None+++def emit(payload: dict, json_out: bool) -> None:+ if json_out:+ print(json.dumps(payload, ensure_ascii=False))+++def fail(msg: str, error_type: str, json_out: bool, **extra):+ log(f"!! {msg}")+ emit({"success": False, "error": msg, "errorType": error_type, **extra}, json_out)+ sys.exit(1)+++def report_unknown(request_id: str, reason: str, json_out: bool, **extra) -> int:+ """结果无法确认:给出 request_id 与查询命令,明确要求不要重跑发布。"""+ cmd = f"python3 publish/upload_post.py --status {request_id}"+ log(f"?? Outcome UNKNOWN ({reason}). The video may already be publishing.")+ log(f"?? DO NOT re-run the publish command: that can post it twice. Check with: {cmd}")+ emit({"success": False, "status": "unknown", "requestId": request_id, "reason": reason,+ "statusCommand": cmd, "doNotRerun": True, **extra}, json_out)+ return 2+++def report(status: dict, results: list[dict], json_out: bool, **extra) -> int:+ for r in results:+ if r["status"] == "completed":+ where = ("sent to TikTok inbox: publish it from the app" if r["inbox"]+ else r["url"] or r["note"] or f"published (post id {r['postId']})")+ log(f"OK {r['platform']}: {where}")+ elif r["status"] == "skipped":+ log(f"-- {r['platform']}: skipped (no account connected to this profile)")+ elif r["status"] in ("failed", "retryable"):+ log(f"!! {r['platform']}: {r['status']}: {r['error']}")+ else:+ log(f" {r['platform']}: {r['status']}")+ state = status.get("status")+ published = [r for r in results if r["status"] == "completed"]+ failed = [r for r in results if r["status"] in ("failed", "retryable")]+ ok = state != "not_found" and not failed and (bool(published) or state not in FINAL_STATUSES)+ if status.get("timedOut"):+ log(f"?? still running; check later: python3 publish/upload_post.py --status {status.get('request_id')}")+ emit({"success": ok, "status": state, "requestId": status.get("request_id"),+ "jobId": status.get("job_id"), "results": results,+ "timedOut": bool(status.get("timedOut")), **extra}, json_out)+ return 0 if ok else 1+++# ---------------------------------------------------------------- CLI+def build_parser() -> argparse.ArgumentParser:+ p = argparse.ArgumentParser(+ description="Publish a finished video to TikTok, Instagram, YouTube, LinkedIn, Facebook, X, "+ "Threads, Pinterest and Bluesky via the Upload-Post API. "+ "See references/publish-upload-post.md.")+ p.add_argument("--video", help="MP4 to publish")+ p.add_argument("--title", help="Caption/title used on every platform (YouTube max 100 chars)")+ g = p.add_mutually_exclusive_group()+ g.add_argument("--description", help="Longer text for YouTube, LinkedIn, Facebook, Pinterest")+ g.add_argument("--description-file", help="Read the description from a file")+ p.add_argument("--platforms", help=f"Comma-separated: {', '.join(VIDEO_PLATFORMS)} (aliases: twitter, reels, shorts)")+ p.add_argument("--user", default=os.getenv("UPLOAD_POST_USER"), help="Upload-Post profile (default $UPLOAD_POST_USER)")+ p.add_argument("--schedule", help="Publish later, ISO8601 (≤365 days ahead)")+ p.add_argument("--timezone", help="IANA zone for --schedule, e.g. Asia/Shanghai (default UTC)")+ p.add_argument("--first-comment", help="Posted as the first comment/reply once live")+ p.add_argument("--ai-generated", action="store_true", help="Disclose AI-generated content (TikTok/Instagram/YouTube/X labels)")+ p.add_argument("--thumbnail", help="Custom thumbnail (YouTube, LinkedIn)")+ p.add_argument("--youtube-privacy", choices=YOUTUBE_PRIVACY, default="private")+ p.add_argument("--tags", help="Comma-separated YouTube tags")+ p.add_argument("--tiktok-privacy", choices=TIKTOK_PRIVACY, help="Default: the account's own")+ p.add_argument("--tiktok-draft", action="store_true", help="Send to TikTok drafts instead of posting")+ p.add_argument("--instagram-story", action="store_true", help="Stories instead of Reels")+ p.add_argument("--facebook-page-id")+ p.add_argument("--linkedin-page-id", help="Post as a LinkedIn company page")+ p.add_argument("--pinterest-board", help="Board ID (required for Pinterest)")+ p.add_argument("--status", metavar="ID", help="Look up an earlier upload (request_id or job_id) and exit")+ p.add_argument("--no-wait", action="store_true", help="Return right after submitting")+ p.add_argument("--wait-timeout", type=int, default=DEFAULT_WAIT_SECS)+ p.add_argument("--dry-run", action="store_true", help="Validate + check the account, no upload")+ p.add_argument("--json-out", action="store_true", help="One machine-readable JSON line on stdout")+ return p+++def main() -> None:+ args = build_parser().parse_args()+ api_key = os.getenv("UPLOAD_POST_API_KEY")+ if not api_key and not args.dry_run:+ fail("UPLOAD_POST_API_KEY is not set: see references/publish-upload-post.md.", "auth", args.json_out)++ if args.status:+ # job_id 是 32 位十六进制;先查更可能的类型,另一种作兜底+ kinds = ["job_id", "request_id"] if re.fullmatch(r"[0-9a-f]{32}", args.status) else ["request_id", "job_id"]+ try:+ for kind in kinds:+ status = get_status(api_key, **{kind: args.status})+ if status.get("status") != "not_found":+ break+ except ApiError as e:+ fail(str(e), e.error_type, args.json_out)+ if status.get("status") == "not_found":+ log(f"!! No upload found with id {args.status}.")+ elif not status.get("job_id"):+ status.setdefault("request_id", args.status)+ sys.exit(report(status, summarize_results(status), args.json_out))++ err = validate_args(args)+ if err:+ fail(err, "validation", args.json_out)+ description = (Path(args.description_file).read_text(encoding="utf-8")+ if args.description_file else args.description or "")+ request_id = str(uuid.uuid4())+ form = build_form(args, description, request_id)++ if args.dry_run:+ log("Dry run: form fields (no upload):")+ log(json.dumps(form, indent=2, ensure_ascii=False))+ auth_ok, auth_msg, connected, missing = False, None, [], []+ if not api_key:+ auth_msg = "UPLOAD_POST_API_KEY is not set"+ else:+ try:+ account = check_account(api_key, args.user)+ auth_ok, connected = True, account["connected"]+ missing = [p for p in args.platforms if p not in connected]+ log(f"OK key valid (plan: {account['plan']}); profile '{args.user}' found.")+ except ApiError as e:+ auth_msg = str(e)+ if auth_msg:+ log(f"?? auth not ready: {auth_msg}")+ if missing:+ log(f"?? not connected on '{args.user}': {', '.join(missing)}: these would be skipped.")+ emit({"success": True, "dryRun": True, "authOk": auth_ok, "authError": auth_msg,+ "user": args.user, "platforms": args.platforms,+ "connectedPlatforms": connected, "missingPlatforms": missing}, args.json_out)+ sys.exit(0)++ # 发送前先记下恢复用的 id:进程中途退出时,用它查询而不是重跑发布+ log(f"-> request_id {request_id}. If this run is interrupted, do NOT re-run it; check with: "+ f"python3 publish/upload_post.py --status {request_id}")+ log(f"-> Uploading '{Path(args.video).name}' to {', '.join(args.platforms)} as '{args.user}'...")+ try:+ submitted = submit_upload(api_key, args.video, form, args.thumbnail, request_id)+ except ApiError as e: # 400/401/403/422:受理前明确拒绝+ fail(str(e), e.error_type, args.json_out, requestId=request_id)+ except AmbiguousSubmit as e:+ log(f"?? upload response unclear ({e}); checking request {request_id} instead of re-sending...")+ found = probe_submission(api_key, request_id)+ if found is None:+ sys.exit(report_unknown(request_id, str(e), args.json_out, platforms=args.platforms))+ log("OK the server has this upload; continuing.")+ submitted = {"request_id": request_id, "job_id": found.get("job_id")}++ if args.schedule:+ job_id = submitted.get("job_id")+ # 定时发布按文档用 job_id 查询;API 没返回 job_id 时才退回 request_id+ cmd = f"python3 publish/upload_post.py --status {job_id or request_id}"+ log(f"OK scheduled for {args.schedule} {args.timezone or 'UTC'} (job {job_id}).")+ log(f" check later: {cmd}")+ emit({"success": True, "status": "scheduled", "jobId": job_id, "requestId": request_id,+ "statusCommand": cmd, "scheduledDate": args.schedule, "timezone": args.timezone,+ "platforms": args.platforms}, args.json_out)+ sys.exit(0)++ if args.no_wait:+ log(f"OK submitted; check progress: python3 publish/upload_post.py --status {request_id}")+ emit({"success": True, "status": "submitted", "requestId": request_id,+ "platforms": args.platforms}, args.json_out)+ sys.exit(0)++ status = wait_for_result(api_key, request_id, args.wait_timeout)+ if status.get("status") == "unknown":+ sys.exit(report_unknown(request_id, status["reason"], args.json_out, platforms=args.platforms))+ status.setdefault("request_id", request_id)+ sys.exit(report(status, summarize_results(status), args.json_out, platforms=args.platforms))+++if __name__ == "__main__":+ main()diff --git a/references/publish-upload-post.md b/references/publish-upload-post.mdnew file mode 100644index 0000000..1b9cef2--- /dev/null+++ b/references/publish-upload-post.md@@ -0,0 +1,111 @@+# 发布到社交平台:成片 → TikTok / Instagram / YouTube / LinkedIn / X …++把交付的 MP4 一次发到 TikTok、Instagram(Reels 或 Stories)、YouTube(含 Shorts)、+LinkedIn、Facebook、X、Threads、Pinterest、Bluesky,可立即发布或定时发布。+脚本 `publish/upload_post.py`,通过 [Upload-Post](https://upload-post.com) API 完成,+只用 Python 标准库(无需 venv / pip)。++**触发时机**:只在用户**主动要求**把成片发到社交平台时执行(例如"帮我发到+TikTok 和 YouTube")。它不是交付收尾 1-2-3 之外的第 4 条推荐,不要主动推销。+发布是公开且难以撤回的操作,**必须先让用户确认文案和平台清单**,再真正发布。++> **说明**:Upload-Post 是第三方托管服务。免费版每月 10 次上传,覆盖上面除+> TikTok 以外的全部平台(TikTok 需付费版)。只有用户配置了自己的 API key 时+> 本流程才会联网。++## 1. 一次性准备(用户操作)++1. 在 https://upload-post.com 注册,创建一个 profile,把要发的社交账号连到这个 profile。+2. 在后台创建 API key。+3. 设置环境变量(或写进用户自己的 shell 配置):++```bash+export UPLOAD_POST_API_KEY=...+export UPLOAD_POST_USER=<profile 名>+```++缺这两个变量时,告诉用户以上三步,停下等待,不要尝试发布。++## 2. 选文件与准备文案++- **文件**:用交付的成片。配了 BGM 的片子有两版(带 BGM / 无 BGM),默认发+ **带 BGM 版**;用户另有要求按用户的来。+- **画幅**:TikTok、Reels、Shorts 要竖屏 9:16。成片是横屏 16:9 时如实告诉用户+ (这些平台会加黑边或裁切),建议改发 YouTube / LinkedIn / X / Facebook,或另渲+ 一版竖屏。+- **文案 `--title`**:在 TikTok / Instagram / X / Threads 上就是正文,按社交文案写+ (钩子一句 + 2–4 个话题标签),不要写成 YouTube 标题。含 YouTube 时 ≤100 字符。+ 交付收尾第 1 条里用户若同意 @ 作者,把那句放进文案。+- **长描述 `--description`**:YouTube / LinkedIn / Facebook / Pinterest 用。+- **AI 声明 `--ai-generated`**:询问用户是否标注 AI 生成内容。成片由 Agent 以代码+ 渲染,一般不属于"逼真的合成影像",默认不标;用了 AI 生成画面或 AI 配音时建议标。++把「文案 + 描述 + 平台清单 + 定时(如有)+ 各平台隐私设置」整理给用户,+**得到明确确认后**再进入下一步。++## 3. 先 dry-run(不发布)++```bash+python3 publish/upload_post.py --video out/promo.mp4 --title "<文案>" \+ --description "<长描述>" --platforms tiktok,instagram,youtube --dry-run --json-out+```++检查输出:`authOk` 为 `true`;`missingPlatforms` 非空说明这些平台没连到 profile,+会被跳过,告诉用户去后台连接,或从清单里去掉。++## 4. 发布++去掉 `--dry-run` 重跑。脚本等待各平台结果(默认最多 10 分钟),逐平台输出链接或错误。++- **每条发布命令只跑一次。** 无论超时、断网、报错还是 `status: "unknown"`,都**不要+ 重跑发布命令**,重跑会生成新的 request_id,同一视频会被发两次。只能查询:+ `python3 publish/upload_post.py --status <requestId> --json-out`+- 脚本如何区分:只有 **400 / 401 / 403 / 422**(服务端受理前明确拒绝)才判失败,此时+ 没有任何东西被发出去,修正参数后可以再发。5xx、网关错误、超时、断网、2xx 却无有效+ JSON 都属于"不确定",视频可能已被受理。脚本会自动用同一个 request_id 查询:查到就+ 照常继续;仍无法确认则输出 `status: "unknown"`(退出码 2)、`requestId` 和+ `statusCommand`,并带 `doNotRerun: true`。+- 脚本在**发送之前**就把 `request_id` 和对应的 `--status` 命令打到 stderr。进程中途+ 被中断时,用这条命令查询,不要重跑发布。+- 定时发布(`--schedule 2026-10-01T09:00:00 --timezone Asia/Shanghai`)立即返回+ `jobId` + `requestId` 和 `statusCommand`。定时任务按 **`jobId`** 查询:+ `python3 publish/upload_post.py --status <jobId> --json-out`(输出里的 `statusCommand`+ 就是这条命令)。++## 5. 向用户汇报++每个平台一行:链接、或原因。++| 平台结果 | 含义 |+|---|---|+| `completed` + `url` | 已发布。私密发布没有公开链接:YouTube 仍给出本人可看的链接,其他平台给 `postId` + `note` |+| `skipped` | profile 没连这个平台,没有发 |+| `failed` / `retryable` | `error` 是平台给的原因(如账号授权过期,去后台重新连接);`retryable` 会由服务端自动重试 |+| TikTok `inbox: true` | TikTok 把视频放进了草稿箱,需要用户在 TikTok App 里点发布 |+| 整体 `status: "unknown"` | 无法确认是否已受理。原样告诉用户 `requestId`,稍后用 `statusCommand` 查询;**不要重跑发布命令** |++## 6. 参数速查++| 参数 | 说明 |+|---|---|+| `--video` / `--title` | 成片路径 / 各平台共用文案 |+| `--description` / `--description-file` | 长描述 |+| `--platforms` | `tiktok,instagram,youtube,linkedin,facebook,x,threads,pinterest,bluesky`(别名 `twitter` `reels` `shorts`) |+| `--user` | profile 名,默认 `$UPLOAD_POST_USER` |+| `--schedule` + `--timezone` | 定时发布(≤365 天),IANA 时区,默认 UTC |+| `--first-comment` | 发布后自动发第一条评论 |+| `--ai-generated` | AI 生成内容声明(TikTok / Instagram / YouTube / X) |+| `--thumbnail` | 自定义封面(YouTube、LinkedIn) |+| `--youtube-privacy` | `private`(默认)/ `unlisted` / `public` |+| `--tags` | YouTube 标签,逗号分隔 |+| `--tiktok-privacy` / `--tiktok-draft` | TikTok 隐私(默认沿用账号设置)/ 只存草稿 |+| `--instagram-story` | 发 Stories 而非 Reels |+| `--facebook-page-id` / `--linkedin-page-id` | 指定 Facebook 主页 / 以 LinkedIn 公司页发布 |+| `--pinterest-board` | Pinterest 必填 |+| `--status ID` | 查询之前的发布:即时发布用 request_id,定时发布用 job_id |+| `--dry-run` / `--json-out` | 只校验不发布 / 输出一行 JSON |++错误类型(`errorType`):`auth`(key 缺失或错误)、`validation`(参数错误,或所选平台都没连接)、+`forbidden`(套餐不支持,如免费版发 TikTok)、`quota`(频率或套餐上限)、`http`(网络 / 服务端)。++离线单测:`python3 -m unittest publish/test_upload_post.py -v`