feat(guides): 新增通知图文教程与通用 Webhook Skill
- guides: 新增消息推送教程入口、固定目录、截图放大与技能下载 - docs/notifications: 补齐企微接入、业务适配、预览测试与发布验收图文 - skill: 固化跨平台配置体验,增加注册日报和充值通知示例及界面参考图 - scripts: 统一生成教程、原图标注和可重复验证的技能包 - README: 同步目录、入口和维护命令
This commit is contained in:
@@ -0,0 +1,169 @@
|
||||
#!/usr/bin/env python3
|
||||
"""由同一内容源生成通知教程、保留原图的 SVG 标注和可下载技能包。"""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import html
|
||||
import io
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import struct
|
||||
import zipfile
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DOCS = ROOT / "docs/notifications"
|
||||
PUBLIC = ROOT / "public/guides/notifications"
|
||||
SLUG = "wecom-notification-integration"
|
||||
SKILL = DOCS / "skill" / SLUG
|
||||
|
||||
|
||||
def image_size(raw, image_format):
|
||||
"""读取 PNG/JPEG 文件头尺寸,不重新编码截图。"""
|
||||
if image_format == "png" and raw[:8] == b"\x89PNG\r\n\x1a\n":
|
||||
return struct.unpack(">II", raw[16:24])
|
||||
if image_format == "jpeg" and raw[:2] == b"\xff\xd8":
|
||||
offset = 2
|
||||
while offset + 8 < len(raw):
|
||||
if raw[offset] != 255:
|
||||
break
|
||||
while raw[offset] == 255:
|
||||
offset += 1
|
||||
marker = raw[offset]
|
||||
offset += 1
|
||||
if marker in (0xD8, 0xD9) or 0xD0 <= marker <= 0xD7:
|
||||
continue
|
||||
length = int.from_bytes(raw[offset:offset + 2], "big")
|
||||
if marker in (0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF):
|
||||
height, width = struct.unpack(">HH", raw[offset + 3:offset + 7])
|
||||
return width, height
|
||||
if length < 2:
|
||||
break
|
||||
offset += length
|
||||
raise ValueError("截图不是有效的 PNG/JPEG")
|
||||
|
||||
|
||||
def render_svg(key, raw, shot, title):
|
||||
"""保留原始图片字节,仅以独立矢量图层增加操作指引。"""
|
||||
width, height = shot["width"], shot["height"]
|
||||
image_format = shot["format"]
|
||||
if image_size(raw, image_format) != (width, height):
|
||||
raise ValueError(f"截图格式或尺寸不匹配:{key}")
|
||||
radius = 15 if width < 600 else 20
|
||||
stroke = 2 if width < 600 else 3
|
||||
annotations = []
|
||||
for number, annotation in enumerate(shot["annotations"], 1):
|
||||
rect, badge = annotation["rect"], annotation["badge"]
|
||||
x, y, w, h = (rect[k] for k in ("x", "y", "width", "height"))
|
||||
bx, by = badge["x"], badge["y"]
|
||||
if annotation["number"] != number or not all(math.isfinite(v) for v in (x, y, w, h, bx, by)):
|
||||
raise ValueError(f"标注编号或坐标无效:{key}")
|
||||
if not (w > 0 and h > 0 and x >= 0 and y >= 0 and x + w <= width and y + h <= height):
|
||||
raise ValueError(f"标注框超出截图:{key}")
|
||||
if not (radius <= bx <= width - radius and radius <= by <= height - radius):
|
||||
raise ValueError(f"标注编号超出截图:{key}")
|
||||
tx, ty = max(x, min(x + w, bx)), max(y, min(y + h, by))
|
||||
annotations.append(
|
||||
f'<g><rect x="{x - 3}" y="{y - 3}" width="{w + 6}" height="{h + 6}" rx="6" '
|
||||
f'fill="none" stroke="#ef4444" stroke-width="{stroke}"/>'
|
||||
f'<path d="M {bx} {by} L {tx} {ty}" fill="none" stroke="#ef4444" '
|
||||
f'stroke-width="{stroke}" marker-end="url(#arrow)"/>'
|
||||
f'<circle cx="{bx}" cy="{by}" r="{radius}" fill="#ef4444" stroke="white" stroke-width="2"/>'
|
||||
f'<text x="{bx}" y="{by + 6}" text-anchor="middle" fill="white" '
|
||||
f'font-family="Arial,sans-serif" font-size="{radius + 3}" font-weight="700">{number}</text></g>'
|
||||
)
|
||||
encoded = base64.b64encode(raw).decode("ascii")
|
||||
return (
|
||||
f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" '
|
||||
f'viewBox="0 0 {width} {height}" role="img" aria-labelledby="title desc">'
|
||||
f'<title id="title">{html.escape(title)}</title><desc id="desc">{html.escape(shot["source"])}</desc>'
|
||||
'<defs><marker id="arrow" markerWidth="9" markerHeight="9" refX="8" refY="4.5" '
|
||||
'orient="auto" markerUnits="userSpaceOnUse"><path d="M0,0 L9,4.5 L0,9Z" fill="#ef4444"/></marker></defs>'
|
||||
f'<image width="{width}" height="{height}" href="data:image/{image_format};base64,{encoded}"/>'
|
||||
+ "".join(annotations) + "</svg>\n"
|
||||
).encode("utf8")
|
||||
|
||||
|
||||
def skill_archive():
|
||||
"""固定文件顺序、权限和时间戳,下载包在不同机器也可重复核对。"""
|
||||
output = io.BytesIO()
|
||||
files = sorted(path for path in SKILL.rglob("*") if path.is_file())
|
||||
if not (SKILL / "SKILL.md").is_file():
|
||||
raise ValueError("缺少技能入口")
|
||||
with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_STORED) as archive:
|
||||
for path in files:
|
||||
if path.is_symlink():
|
||||
raise ValueError("技能包不能包含外部文件链接")
|
||||
item = zipfile.ZipInfo(f"{SLUG}/{path.relative_to(SKILL).as_posix()}", (1980, 1, 1, 0, 0, 0))
|
||||
item.create_system = 3
|
||||
item.external_attr = 0o100644 << 16
|
||||
archive.writestr(item, path.read_bytes())
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
def generate(check=False, install=False):
|
||||
"""核对内容、来源、标注与派生文件;安装仅在显式参数下写入个人技能目录。"""
|
||||
guide = json.loads((DOCS / "guide.json").read_text())
|
||||
shots = json.loads((DOCS / "screenshots.json").read_text())
|
||||
outputs = {}
|
||||
used, ids = set(), set()
|
||||
readme = [f'# {guide["title"]}', guide["intro"], f'更新时间:{guide["updated"]}', f'> {guide["notice"]}', "## 目录"]
|
||||
readme.append("\n".join(f'- [{step["title"]}](#{step["id"]})' for step in guide["steps"]))
|
||||
for step in guide["steps"]:
|
||||
if not re.fullmatch(r"[a-z][a-z0-9-]*", step["id"]) or step["id"] in ids:
|
||||
raise ValueError("章节 ID 不合法或重复")
|
||||
ids.add(step["id"])
|
||||
readme.extend([f'<a id="{step["id"]}"></a>', f'## {step["title"]}', step["lead"]])
|
||||
for key in step.get("images", []):
|
||||
shot = shots[key]
|
||||
if not shot.get("source") or len(guide["captions"][key]) != len(shot["annotations"]):
|
||||
raise ValueError(f"缺少截图来源或标注与说明不一致:{key}")
|
||||
extension = "jpg" if shot["format"] == "jpeg" else "png"
|
||||
raw = (DOCS / "screenshots" / f"{key}.{extension}").read_bytes()
|
||||
outputs[PUBLIC / f"{key}.svg"] = render_svg(key, raw, shot, step["title"])
|
||||
used.add(key)
|
||||
readme.extend([f'![{step["title"]}](../../public/guides/notifications/{key}.svg)', f'*{shot["source"]} · 点击图片可放大*'])
|
||||
if guide["captions"][key]:
|
||||
readme.append("\n".join(f"{i}. {text}" for i, text in enumerate(guide["captions"][key], 1)))
|
||||
readme.append("\n".join(f"- {text}" for text in step["bullets"]))
|
||||
if step.get("code"):
|
||||
readme.append(f'```text\n{step["code"]}\n```')
|
||||
if used != set(shots):
|
||||
raise ValueError("存在未引用或遗漏的截图")
|
||||
readme.extend(["## 官方参考", "\n".join(f'- [{ref["label"]}]({ref["url"]})' for ref in guide["references"]), "## 维护教程",
|
||||
"- 内容源:`guide.json`;网页读取相同内容。原图与来源/坐标:`screenshots/`、`screenshots.json`。",
|
||||
"- `python3 scripts/build-notification-guide.py` 生成 README、SVG 标注和 skill ZIP;`--check` 只检查一致性。",
|
||||
"- skill 源码:`skill/wecom-notification-integration/`;显式添加 `--install-skill` 安装或更新本地技能。",
|
||||
"- 网页入口:`/guides/notifications`;skill 下载:`/guides/notifications/wecom-notification-integration.zip`。",
|
||||
"- public 中的静态资源可能独立访问,不能依赖页面路由鉴权保密;发布前检查原图与文字中没有真实密钥、联系人和私密群内容。"])
|
||||
outputs[DOCS / "README.md"] = ("\n\n".join(readme) + "\n").encode("utf8")
|
||||
outputs[PUBLIC / f"{SLUG}.zip"] = skill_archive()
|
||||
for path, content in outputs.items():
|
||||
if check:
|
||||
if not path.is_file() or path.read_bytes() != content:
|
||||
raise ValueError(f"派生文件需要重新生成:{path.relative_to(ROOT)}")
|
||||
else:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(content)
|
||||
if install:
|
||||
target = Path(os.environ.get("CODEX_HOME", str(Path.home() / ".codex"))) / "skills" / SLUG
|
||||
if check:
|
||||
for path in SKILL.rglob("*"):
|
||||
if path.is_file() and (not (target / path.relative_to(SKILL)).is_file() or path.read_bytes() != (target / path.relative_to(SKILL)).read_bytes()):
|
||||
raise ValueError("本地安装技能与项目源不一致")
|
||||
else:
|
||||
shutil.copytree(SKILL, target, dirs_exist_ok=True)
|
||||
print(f'本地技能{"检查通过" if check else "已安装"}:{target}')
|
||||
print(f'{"检查通过" if check else "已生成"}:{len(guide["steps"])} 个章节、{len(shots)} 张截图和技能包')
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--check", action="store_true", help="只检查派生文件一致性")
|
||||
parser.add_argument("--install-skill", action="store_true", help="安装或检查本地技能")
|
||||
args = parser.parse_args()
|
||||
generate(args.check, args.install_skill)
|
||||
Reference in New Issue
Block a user