@sokeai/cli 1.0.116 → 1.0.117
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.
- package/package.json +1 -1
- package/skills/multi/demo-init/CHANGELOG.md +1241 -0
- package/skills/multi/demo-init/README.md +137 -0
- package/skills/multi/demo-init/SKILL.legacy.md +307 -0
- package/skills/multi/demo-init/assets/placeholder.pptx +0 -0
- package/skills/multi/demo-init/references/anti-patterns.md +83 -0
- package/skills/multi/demo-init/references/asset-design.md +230 -0
- package/skills/multi/demo-init/references/asset-spec.md +94 -0
- package/skills/multi/demo-init/references/blueprint-schema.md +174 -0
- package/skills/multi/demo-init/references/cli-onboarding.md +207 -0
- package/skills/multi/demo-init/references/cli-shared.md +183 -0
- package/skills/multi/demo-init/references/contracts.md +34 -0
- package/skills/multi/demo-init/references/course-setup.md +265 -0
- package/skills/multi/demo-init/references/demo-defaults.md +132 -0
- package/skills/multi/demo-init/references/demo-verify.md +355 -0
- package/skills/multi/demo-init/references/exam-setup.md +245 -0
- package/skills/multi/demo-init/references/gates-matrix.md +38 -0
- package/skills/multi/demo-init/references/map-setup.md +283 -0
- package/skills/multi/demo-init/references/plan-parse.md +185 -0
- package/skills/multi/demo-init/references/platform-access.md +55 -0
- package/skills/multi/demo-init/references/platform-commands.md +510 -0
- package/skills/multi/demo-init/references/point-setup.md +308 -0
- package/skills/multi/demo-init/references/portal-modules.md +130 -0
- package/skills/multi/demo-init/references/portal-setup.md +342 -0
- package/skills/multi/demo-init/references/project-setup.md +173 -0
- package/skills/multi/demo-init/references/run-protocol.md +208 -0
- package/skills/multi/demo-init/references/taxonomy-setup.md +101 -0
- package/skills/multi/demo-init/scripts/assign_backfill.py +281 -0
- package/skills/multi/demo-init/scripts/blueprint_lint.py +693 -0
- package/skills/multi/demo-init/scripts/blueprint_write.py +390 -0
- package/skills/multi/demo-init/scripts/category_bind.py +303 -0
- package/skills/multi/demo-init/scripts/category_create.py +748 -0
- package/skills/multi/demo-init/scripts/category_reassign.py +405 -0
- package/skills/multi/demo-init/scripts/category_verify.py +373 -0
- package/skills/multi/demo-init/scripts/cli_kit.py +597 -0
- package/skills/multi/demo-init/scripts/cli_probe.py +205 -0
- package/skills/multi/demo-init/scripts/course_build.py +857 -0
- package/skills/multi/demo-init/scripts/course_cover_repair.py +243 -0
- package/skills/multi/demo-init/scripts/doc_lint.py +619 -0
- package/skills/multi/demo-init/scripts/dup_cleanup.py +299 -0
- package/skills/multi/demo-init/scripts/dup_scan.py +368 -0
- package/skills/multi/demo-init/scripts/exam_build.py +551 -0
- package/skills/multi/demo-init/scripts/extract_docx.py +370 -0
- package/skills/multi/demo-init/scripts/gen_assets.py +1366 -0
- package/skills/multi/demo-init/scripts/guard.py +1272 -0
- package/skills/multi/demo-init/scripts/map_rebuild.py +391 -0
- package/skills/multi/demo-init/scripts/oss_image_upload.py +367 -0
- package/skills/multi/demo-init/scripts/portal_build.py +450 -0
- package/skills/multi/demo-init/scripts/portal_home_apply.py +255 -0
- package/skills/multi/demo-init/scripts/portal_home_layout.py +398 -0
- package/skills/multi/demo-init/scripts/project_build.py +309 -0
- package/skills/multi/demo-init/scripts/rebuild_taxonomy_map.py +100 -0
- package/skills/multi/demo-init/scripts/scope_plan.py +387 -0
- package/skills/multi/demo-init/scripts/selftest_all.py +211 -0
- package/skills/multi/demo-init/scripts/stock_probe.py +452 -0
- package/skills/multi/demo-init/scripts/taxonomy_build.py +512 -0
- package/skills/multi/demo-init-4.1.0.zip +0 -0
- package/skills/multi/demo-init-4.1.1.zip +0 -0
- package/skills/multi/demo-init-4.1.2.zip +0 -0
- package/skills/multi/demo-init-4.1.3.zip +0 -0
- package/skills/multi/ziQIJJpL +0 -0
- package/skills/multi/ziRsINis +0 -0
- package/skills/multi/ziUjKWRm +0 -0
- package/skills/multi/zipFWfuj +0 -0
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""封面/图片正确上传通道:upload-token → OSS PostObject 直传(content-type 正确)→ 图片库登记 → 课程封面绑定。
|
|
4
|
+
|
|
5
|
+
背景(2026-10-20 定案):
|
|
6
|
+
soke-cli `photo-gallery +create` 直传 OSS 时未设置 Content-Type,OSS 落
|
|
7
|
+
application/octet-stream。列表页 <img> 能嗅探渲染所以正常,但课程编辑页
|
|
8
|
+
「封面图」组件对 content-type 校验/预览失败 → 显示空白。
|
|
9
|
+
|
|
10
|
+
本脚本改走 open-dev 的 ai-training 封面签名通道(强制校验 content_type ∈
|
|
11
|
+
jpg/jpeg/png/webp,≤5MB),file part 显式带 `Content-Type: image/png`,
|
|
12
|
+
OSS 即落 image/png;再调 `photoGallery/create` 登记(object 自定义可对上),
|
|
13
|
+
可选一步绑定到课程封面(全载荷 + imgObj 全 0)。
|
|
14
|
+
|
|
15
|
+
用法:
|
|
16
|
+
python3 oss_image_upload.py --file <本地图片> --title <用途键>
|
|
17
|
+
python3 oss_image_upload.py --file <本地图片> --title <用途键> --course-id <uuid> --bind
|
|
18
|
+
python3 oss_image_upload.py --file <本地图片> --title <用途键> --dry-run
|
|
19
|
+
|
|
20
|
+
输出(stdout 末行为 JSON):photo_uuid / photo_uri / content_type / bound_course。
|
|
21
|
+
退出码:0=成功;1=失败。
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import argparse
|
|
27
|
+
import hashlib
|
|
28
|
+
import json
|
|
29
|
+
import os
|
|
30
|
+
import shutil
|
|
31
|
+
import subprocess
|
|
32
|
+
import sys
|
|
33
|
+
import tempfile
|
|
34
|
+
import time
|
|
35
|
+
import urllib.request
|
|
36
|
+
|
|
37
|
+
DEFAULT_CLI_CANDIDATES = [
|
|
38
|
+
os.environ.get("SOKE_CLI", ""),
|
|
39
|
+
os.path.expanduser("~/.workbuddy/binaries/node/cli-connector-packages/bin/soke-cli"),
|
|
40
|
+
"/usr/local/bin/soke-cli",
|
|
41
|
+
"/opt/homebrew/bin/soke-cli",
|
|
42
|
+
os.path.expanduser("~/.npm-global/bin/soke-cli"),
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
SUPPORTED = {"image/png": {"png"}, "image/jpeg": {"jpg", "jpeg"}, "image/webp": {"webp"}}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def resolve_cli() -> str:
|
|
49
|
+
for cand in DEFAULT_CLI_CANDIDATES:
|
|
50
|
+
if cand and os.path.isfile(cand) and os.access(cand, os.X_OK):
|
|
51
|
+
return cand
|
|
52
|
+
found = shutil.which("soke-cli")
|
|
53
|
+
if found:
|
|
54
|
+
return found
|
|
55
|
+
raise SystemExit("未找到 soke-cli,请先安装:npm i -g @sokeai/cli")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def parse_json(raw: str) -> dict:
|
|
59
|
+
idx = raw.find("{")
|
|
60
|
+
if idx < 0:
|
|
61
|
+
raise ValueError(f"响应不是 JSON:{raw[:200]}")
|
|
62
|
+
obj, _ = json.JSONDecoder().raw_decode(raw[idx:])
|
|
63
|
+
return obj if isinstance(obj, dict) else {}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def cli_api(cli: str, method: str, path: str, data: dict | None = None) -> dict:
|
|
67
|
+
cmd = [cli, "api", method, path]
|
|
68
|
+
if data is not None:
|
|
69
|
+
cmd += ["--data", json.dumps(data, ensure_ascii=False)]
|
|
70
|
+
r = subprocess.run(cmd, capture_output=True, text=True)
|
|
71
|
+
out = r.stdout or ""
|
|
72
|
+
try:
|
|
73
|
+
return parse_json(out)
|
|
74
|
+
except ValueError:
|
|
75
|
+
raise SystemExit(f"api {method} {path} 失败:{(r.stderr or out)[:300]}")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def sniff_content_type(path: str) -> str:
|
|
79
|
+
ext = os.path.splitext(path)[1].lower().lstrip(".")
|
|
80
|
+
for ct, exts in SUPPORTED.items():
|
|
81
|
+
if ext in exts:
|
|
82
|
+
return ct
|
|
83
|
+
raise SystemExit(f"不支持的图片格式 .{ext}(仅 jpg/jpeg/png/webp)")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def request_upload_token(cli: str, path: str, size: int, sha256: str, content_type: str) -> dict:
|
|
87
|
+
resp = cli_api(cli, "POST", "/skills/ai-training/scenario-covers/upload-token", {
|
|
88
|
+
"filename": os.path.basename(path),
|
|
89
|
+
"content_type": content_type,
|
|
90
|
+
"sha256": sha256,
|
|
91
|
+
"file_size": size,
|
|
92
|
+
})
|
|
93
|
+
data = resp.get("data") or {}
|
|
94
|
+
for k in ("upload_url", "upload_fields", "cdn_url", "object_key"):
|
|
95
|
+
if not data.get(k):
|
|
96
|
+
raise SystemExit(f"upload-token 响应缺少 {k}:{json.dumps(resp, ensure_ascii=False)[:300]}")
|
|
97
|
+
return data
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def post_to_oss(token: dict, file_path: str, content_type: str) -> None:
|
|
101
|
+
"""OSS PostObject:表单字段在前,file 必须最后且 part 带 image/* Content-Type。"""
|
|
102
|
+
boundary = "----SokeCoverBoundary7f3a9c"
|
|
103
|
+
fields = token["upload_fields"]
|
|
104
|
+
with open(file_path, "rb") as f:
|
|
105
|
+
payload = f.read()
|
|
106
|
+
|
|
107
|
+
body = bytearray()
|
|
108
|
+
for k, v in fields.items():
|
|
109
|
+
body += (f"--{boundary}\r\nContent-Disposition: form-data; name=\"{k}\"\r\n\r\n{v}\r\n").encode()
|
|
110
|
+
body += (
|
|
111
|
+
f"--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; "
|
|
112
|
+
f"filename=\"{os.path.basename(file_path)}\"\r\n"
|
|
113
|
+
f"Content-Type: {content_type}\r\n\r\n"
|
|
114
|
+
).encode()
|
|
115
|
+
body += payload
|
|
116
|
+
body += f"\r\n--{boundary}--\r\n".encode()
|
|
117
|
+
|
|
118
|
+
req = urllib.request.Request(
|
|
119
|
+
token["upload_url"],
|
|
120
|
+
data=bytes(body),
|
|
121
|
+
headers={"Content-Type": f"multipart/form-data; boundary={boundary}"},
|
|
122
|
+
method="POST",
|
|
123
|
+
)
|
|
124
|
+
with urllib.request.urlopen(req, timeout=120) as resp:
|
|
125
|
+
if resp.status not in (200, 201, 204):
|
|
126
|
+
raise SystemExit(f"OSS 直传失败:HTTP {resp.status}")
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def verify_cdn(url: str, content_type: str) -> None:
|
|
130
|
+
req = urllib.request.Request(url, method="HEAD")
|
|
131
|
+
with urllib.request.urlopen(req, timeout=15) as resp:
|
|
132
|
+
ct = (resp.headers.get("Content-Type") or "").split(";")[0].strip()
|
|
133
|
+
if ct != content_type:
|
|
134
|
+
raise SystemExit(f"CDN content-type 不符:期望 {content_type},实际 {ct}")
|
|
135
|
+
print(f"✅ CDN 校验通过:content-type={ct} HTTP 200", file=sys.stderr)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def register_photo_gallery(cli: str, token: dict, title: str, file_path: str, content_type: str) -> str:
|
|
139
|
+
size = os.path.getsize(file_path)
|
|
140
|
+
ext = os.path.splitext(file_path)[1].lower().lstrip(".")
|
|
141
|
+
if ext == "jpeg":
|
|
142
|
+
ext = "jpg"
|
|
143
|
+
resp = cli_api(cli, "POST", "/skills/photoGallery/create", {
|
|
144
|
+
"title": title,
|
|
145
|
+
"category_id": "empty",
|
|
146
|
+
"filename": os.path.basename(file_path),
|
|
147
|
+
"ext": ext,
|
|
148
|
+
"filesize": str(size),
|
|
149
|
+
"object": token["object_key"],
|
|
150
|
+
"source": "self",
|
|
151
|
+
"storage": "aliyun",
|
|
152
|
+
"target_type": "photoGallery",
|
|
153
|
+
})
|
|
154
|
+
uuid = (resp.get("data") or {}).get("uuid") or ""
|
|
155
|
+
if not uuid:
|
|
156
|
+
raise SystemExit(f"图片库登记失败:{json.dumps(resp, ensure_ascii=False)[:300]}")
|
|
157
|
+
return uuid
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def fetch_photo_uri(cli: str, photo_uuid: str) -> str:
|
|
161
|
+
"""回读图片库标准 photoUri(newsokecdn 域名,与 +create/+list 一致)。"""
|
|
162
|
+
resp = cli_api(cli, "GET", f"/skills/photoGallery/detail/{photo_uuid}")
|
|
163
|
+
uri = (resp.get("data") or {}).get("photoUri") or ""
|
|
164
|
+
return uri
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def bind_course_cover(cli: str, course_id: str, image_url: str, title: str) -> dict:
|
|
168
|
+
detail = cli_api(cli, "GET", f"/skills/course/detail/{course_id}")
|
|
169
|
+
cur = detail.get("data") or {}
|
|
170
|
+
category_id = cur.get("category_id") or ""
|
|
171
|
+
payload = {
|
|
172
|
+
"action": "update",
|
|
173
|
+
"uuid": course_id,
|
|
174
|
+
"title": cur.get("title") or title,
|
|
175
|
+
"description": cur.get("description") or "",
|
|
176
|
+
"img_picked": 0,
|
|
177
|
+
"imgObj": {"image": image_url, "w": 0, "h": 0, "x": 0, "y": 0},
|
|
178
|
+
}
|
|
179
|
+
if category_id:
|
|
180
|
+
payload["category_id"] = category_id
|
|
181
|
+
payload["categories"] = [category_id]
|
|
182
|
+
payload["category_path"] = [category_id]
|
|
183
|
+
resp = cli_api(cli, "PUT", f"/skills/course/update/{course_id}", payload)
|
|
184
|
+
if str(resp.get("code")) != "200":
|
|
185
|
+
raise SystemExit(f"封面绑定失败:{json.dumps(resp, ensure_ascii=False)[:300]}")
|
|
186
|
+
|
|
187
|
+
# ⛔ api PUT 会把 publish_time 重置为 1970(课程掉出「已发布」),必须补发布
|
|
188
|
+
subprocess.run([cli, "course", "+publish", "--course-id", course_id, "--format", "json"],
|
|
189
|
+
capture_output=True, text=True)
|
|
190
|
+
time.sleep(1.5)
|
|
191
|
+
|
|
192
|
+
after = cli_api(cli, "GET", f"/skills/course/detail/{course_id}").get("data") or {}
|
|
193
|
+
img_url = after.get("img_url") or ""
|
|
194
|
+
publish_time = after.get("publish_time") or ""
|
|
195
|
+
img_picked = after.get("img_picked", None)
|
|
196
|
+
# img_picked 语义:0=自定义封面(picture.image 生效),1/2/3=平台默认封面模板。
|
|
197
|
+
# 编辑页回显判据是 img_picked == 0;None 表示 open-dev 白名单未放行(偏差 #89),此时不判失败。
|
|
198
|
+
ok = bind_ok(after, image_url)
|
|
199
|
+
print(("✅ 封面绑定成功(已补发布)" if ok else f"⚠️ 绑定后校验异常:img_url={img_url} publish_time={publish_time} img_picked={img_picked}"), file=sys.stderr)
|
|
200
|
+
if img_picked is None:
|
|
201
|
+
print("ℹ️ img_picked 未返回(open-dev CourseFilter 白名单待部署,偏差 #89)——按 0 写入,前端可显示", file=sys.stderr)
|
|
202
|
+
return {"img_url": img_url, "publish_time": publish_time, "img_picked": img_picked, "ok": ok}
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def bind_ok(after: dict, image_url: str) -> bool:
|
|
206
|
+
"""绑定回读判据(纯函数,供 --self-test 复用)。
|
|
207
|
+
|
|
208
|
+
三条同时成立才算成功:
|
|
209
|
+
1. `img_url == 目标地址`(前端渲染字段,`picture` 非空不算)
|
|
210
|
+
2. `publish_time` 未被打回 1970(api PUT 会重置发布态,必须补 publish)
|
|
211
|
+
3. `img_picked ∈ {0, "0", None}`——0=自定义封面;None=open-dev 白名单未放行(偏差 #89),不判失败
|
|
212
|
+
"""
|
|
213
|
+
img_url = after.get("img_url") or ""
|
|
214
|
+
published = not str(after.get("publish_time") or "").startswith("1970")
|
|
215
|
+
return img_url == image_url and published and after.get("img_picked", None) in (0, "0", None)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def crop_to(path: str, size: str) -> str:
|
|
219
|
+
"""按 WxH 中心裁剪(对应后台「裁切和上传图片」那一步:裁剪后作为新图上传,不写裁剪参数)。"""
|
|
220
|
+
try:
|
|
221
|
+
from PIL import Image
|
|
222
|
+
except ImportError:
|
|
223
|
+
raise SystemExit("--crop 需要 Pillow:pip install pillow")
|
|
224
|
+
w, h = (int(x) for x in size.lower().split("x"))
|
|
225
|
+
im = Image.open(path).convert("RGB")
|
|
226
|
+
src_ratio, dst_ratio = im.width / im.height, w / h
|
|
227
|
+
if src_ratio > dst_ratio: # 太宽 → 裁两边
|
|
228
|
+
new_w = int(im.height * dst_ratio)
|
|
229
|
+
box = ((im.width - new_w) // 2, 0, (im.width + new_w) // 2, im.height)
|
|
230
|
+
else: # 太高 → 裁上下
|
|
231
|
+
new_h = int(im.width / dst_ratio)
|
|
232
|
+
box = (0, (im.height - new_h) // 2, im.width, (im.height + new_h) // 2)
|
|
233
|
+
out = os.path.join(tempfile.gettempdir(), f"soke-cover-{w}x{h}-{os.getpid()}.png")
|
|
234
|
+
im.crop(box).resize((w, h), Image.LANCZOS).save(out, "PNG", optimize=True)
|
|
235
|
+
print(f"✂️ 已中心裁剪 {im.width}×{im.height} → {w}×{h}:{out}", file=sys.stderr)
|
|
236
|
+
return out
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def self_test() -> int:
|
|
240
|
+
"""离线桩测试:入库通道里最容易错的三段纯逻辑。
|
|
241
|
+
|
|
242
|
+
真实事故(偏差 #84 / #87):`photo-gallery +create` 直传 OSS 未设 Content-Type →
|
|
243
|
+
落 octet-stream,列表页能显示但编辑页空白。所以 content-type 必须在 file part 上显式给。
|
|
244
|
+
"""
|
|
245
|
+
cases = []
|
|
246
|
+
|
|
247
|
+
def ck(cond, label):
|
|
248
|
+
cases.append((bool(cond), label))
|
|
249
|
+
|
|
250
|
+
# 1. 扩展名 → content-type(必须是 image/*,不许 octet-stream)
|
|
251
|
+
ck(sniff_content_type("a.png") == "image/png", "sniff png")
|
|
252
|
+
ck(sniff_content_type("a.PNG") == "image/png", "sniff 大写扩展名")
|
|
253
|
+
ck(sniff_content_type("a.jpg") == "image/jpeg", "sniff jpg")
|
|
254
|
+
ck(sniff_content_type("a.jpeg") == "image/jpeg", "sniff jpeg")
|
|
255
|
+
ck(sniff_content_type("a.webp") == "image/webp", "sniff webp")
|
|
256
|
+
try:
|
|
257
|
+
sniff_content_type("a.gif")
|
|
258
|
+
ck(False, "sniff 拒 gif")
|
|
259
|
+
except SystemExit:
|
|
260
|
+
ck(True, "sniff 拒 gif")
|
|
261
|
+
|
|
262
|
+
# 2. CLI 响应解析(日志前缀 + 花括号字段)
|
|
263
|
+
raw = '[soke-cli] 检查更新\n{"code":200,"data":{"upload_fields":{"x":"a{b}"}}}'
|
|
264
|
+
ck(parse_json(raw)["data"]["upload_fields"]["x"] == "a{b}", "parse_json 保留花括号")
|
|
265
|
+
|
|
266
|
+
# 3. 中心裁剪到平台规格(16:9 960×540,不写裁剪参数)
|
|
267
|
+
try:
|
|
268
|
+
from PIL import Image
|
|
269
|
+
except ImportError:
|
|
270
|
+
print(" SKIP 中心裁剪(未装 Pillow)")
|
|
271
|
+
Image = None
|
|
272
|
+
if Image is not None:
|
|
273
|
+
with tempfile.TemporaryDirectory(prefix="oss-") as tmp:
|
|
274
|
+
wide = os.path.join(tmp, "wide.png")
|
|
275
|
+
Image.new("RGB", (1600, 600), (10, 120, 200)).save(wide)
|
|
276
|
+
out = crop_to(wide, "960x540")
|
|
277
|
+
with Image.open(out) as im:
|
|
278
|
+
ck(im.size == (960, 540), "crop_to 输出 960×540")
|
|
279
|
+
tall = os.path.join(tmp, "tall.png")
|
|
280
|
+
Image.new("RGB", (600, 1200), (10, 120, 200)).save(tall)
|
|
281
|
+
out2 = crop_to(tall, "960x540")
|
|
282
|
+
with Image.open(out2) as im:
|
|
283
|
+
ck(im.size == (960, 540), "crop_to 竖图也出 960×540")
|
|
284
|
+
for p in {out, out2}: # 同一 pid 会生成同名文件,去重后删
|
|
285
|
+
if os.path.exists(p):
|
|
286
|
+
os.remove(p)
|
|
287
|
+
|
|
288
|
+
# 4. 绑定回读判据:img_picked 必须是 0(None=白名单未放行,不判失败)
|
|
289
|
+
ck(bind_ok({"img_url": "https://cdn/x.png", "publish_time": "2026-10-22 10:00:00",
|
|
290
|
+
"img_picked": 0}, "https://cdn/x.png"), "bind_ok img_picked=0")
|
|
291
|
+
ck(bind_ok({"img_url": "https://cdn/x.png", "publish_time": "2026-10-22 10:00:00",
|
|
292
|
+
"img_picked": None}, "https://cdn/x.png"), "bind_ok img_picked 缺失不判失败")
|
|
293
|
+
ck(not bind_ok({"img_url": "https://cdn/x.png", "publish_time": "1970-01-01 00:00:00",
|
|
294
|
+
"img_picked": 0}, "https://cdn/x.png"), "bind_ok 抓发布态被打回")
|
|
295
|
+
ck(not bind_ok({"img_url": "https://cdn/other.png", "publish_time": "2026-10-22 10:00:00",
|
|
296
|
+
"img_picked": 0}, "https://cdn/x.png"), "bind_ok 抓封面地址不符")
|
|
297
|
+
|
|
298
|
+
failed = [label for ok_, label in cases if not ok_]
|
|
299
|
+
for ok_, label in cases:
|
|
300
|
+
print(" %s %s" % ("PASS" if ok_ else "FAIL", label))
|
|
301
|
+
print(json.dumps({"ok": not failed, "assertions": len(cases)}, ensure_ascii=False))
|
|
302
|
+
return 0 if not failed else 1
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def main() -> int:
|
|
306
|
+
if "--self-test" in sys.argv[1:]:
|
|
307
|
+
return self_test()
|
|
308
|
+
ap = argparse.ArgumentParser(description="封面图正确上传通道(content-type 修复版)")
|
|
309
|
+
ap.add_argument("--file", required=True, help="本地图片路径(jpg/jpeg/png/webp)")
|
|
310
|
+
ap.add_argument("--title", required=True, help="用途键,同时作为图片库标题")
|
|
311
|
+
ap.add_argument("--category-id", default="empty")
|
|
312
|
+
ap.add_argument("--course-id", help="可选:同时绑定到该课程封面")
|
|
313
|
+
ap.add_argument("--bind", action="store_true", help="与 --course-id 连用,执行封面绑定")
|
|
314
|
+
ap.add_argument("--category-name", default="", help="课程分类名(course-id 未提供时按名解析可留空)")
|
|
315
|
+
ap.add_argument("--crop", default="", help="可选:先按 WxH 中心裁剪再上传(对应后台「裁切和上传」步)")
|
|
316
|
+
ap.add_argument("--dry-run", action="store_true", help="只打印将执行的步骤")
|
|
317
|
+
args = ap.parse_args()
|
|
318
|
+
|
|
319
|
+
path = os.path.abspath(args.file)
|
|
320
|
+
if not os.path.isfile(path):
|
|
321
|
+
raise SystemExit(f"文件不存在:{path}")
|
|
322
|
+
if args.crop:
|
|
323
|
+
path = crop_to(path, args.crop)
|
|
324
|
+
size = os.path.getsize(path)
|
|
325
|
+
if size <= 0 or size > 5 * 1024 * 1024:
|
|
326
|
+
raise SystemExit(f"文件大小 {size} 超限(>0 且 ≤5MB)")
|
|
327
|
+
content_type = sniff_content_type(path)
|
|
328
|
+
sha256 = hashlib.sha256(open(path, "rb").read()).hexdigest()
|
|
329
|
+
|
|
330
|
+
print(f"file={path} size={size} content_type={content_type}", file=sys.stderr)
|
|
331
|
+
if args.dry_run:
|
|
332
|
+
print("dry-run:upload-token → OSS PostObject(file part Content-Type) → photoGallery/create"
|
|
333
|
+
+ (" → course update 全载荷" if args.course_id and args.bind else ""), file=sys.stderr)
|
|
334
|
+
return 0
|
|
335
|
+
|
|
336
|
+
cli = resolve_cli()
|
|
337
|
+
token = request_upload_token(cli, path, size, sha256, content_type)
|
|
338
|
+
print(f"object_key={token['object_key']}", file=sys.stderr)
|
|
339
|
+
|
|
340
|
+
post_to_oss(token, path, content_type)
|
|
341
|
+
verify_cdn(token["cdn_url"], content_type)
|
|
342
|
+
|
|
343
|
+
photo_uuid = register_photo_gallery(cli, token, args.title, path, content_type)
|
|
344
|
+
print(f"✅ 图片库登记成功 uuid={photo_uuid}", file=sys.stderr)
|
|
345
|
+
|
|
346
|
+
# 与图片库记录对齐:用回读的 photoUri(newsokecdn),而不是 token 的 cdn_url(editorcdn)
|
|
347
|
+
photo_uri = fetch_photo_uri(cli, photo_uuid) or token["cdn_url"]
|
|
348
|
+
if photo_uri != token["cdn_url"]:
|
|
349
|
+
verify_cdn(photo_uri, content_type)
|
|
350
|
+
|
|
351
|
+
result = {
|
|
352
|
+
"ok": True,
|
|
353
|
+
"photo_uuid": photo_uuid,
|
|
354
|
+
"photo_uri": photo_uri,
|
|
355
|
+
"object_key": token["object_key"],
|
|
356
|
+
"content_type": content_type,
|
|
357
|
+
"title": args.title,
|
|
358
|
+
}
|
|
359
|
+
if args.course_id and args.bind:
|
|
360
|
+
result["bound_course"] = bind_course_cover(cli, args.course_id, photo_uri, args.title)
|
|
361
|
+
|
|
362
|
+
print(json.dumps(result, ensure_ascii=False))
|
|
363
|
+
return 0
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
if __name__ == "__main__":
|
|
367
|
+
sys.exit(main())
|