sync update from LAN repo (source master @ ca48c4ec)
This commit is contained in:
1 parent
8bc8b0e082
commit
ea9dcff9c0
873 files changed
+107866
-14011
No files matched your search
@@ -0,0 +1,105 @@
|
||||
---
|
||||
name: facebook-page-generator
|
||||
description: 生成或绘制 Facebook/Facebook 风格的可交付社交信息流 HTML 网页;仅在用户明确要求 Facebook 网页、Facebook 页面或点名本技能时使用。先把材料或检索结果整理成七模块 JSON,再用内置模板确定性渲染,保留右上角可视化 JSON 编辑弹窗。
|
||||
allowed-tools:
|
||||
- read_file
|
||||
- write_file
|
||||
- bash
|
||||
- present_files
|
||||
- web_search
|
||||
---
|
||||
|
||||
# Facebook 页面生成器
|
||||
|
||||
本技能使用固定模板生成单文件 HTML。模型只负责材料收集和 JSON,禁止重新手写页面结构、CSS 或渲染脚本。最终页面自带右上角设置按钮;用户可在弹窗中按模块继续编辑 JSON,并通过「应用并渲染」即时更新页面。
|
||||
|
||||
编辑弹窗还提供“上传图片/视频”:先把光标放进目标报道、帖子、视频或带 `visual`/`media` 的内容对象,上传文件会转换为 `data:` 地址并写入该对象的 `media` 字段。不设文件大小拦截;较大文件可能超过浏览器本地缓存容量,应同时下载 JSON 留存。
|
||||
|
||||
页面中已由 `media` 数据渲染的图片和视频还带悬浮上传图标:鼠标移入媒体后点击可任选图片或视频并直接替换,文件的实际类型会自动写入新的 `media.type`,结果同步写回页面 JSON 与浏览器缓存。头像、Logo 和无法映射回 JSON 的装饰图不会显示该入口;不按原媒体类型限制,也不设置文件大小拦截。
|
||||
|
||||
默认视觉直接复用模板原有的示例图:不要调用图像生成工具,不要让模型重新生成、拼装或内嵌新的内容型 SVG,也不要为了寻找“标准配图”延长检索。用户没有提供可直接使用的图片/视频且聚焦检索未得到可靠直链时,保留默认 JSON 的 `visual` 或内置视觉类型;这些是模板自带的静态示例,调用技能时不重新绘制。不要把大段 base64 示例图重复写进 JSON,图不合适时由用户在成品页面悬浮上传替换。
|
||||
|
||||
## 触发边界
|
||||
|
||||
- 用户明确说「生成/画/制作 Facebook 网页」「Facebook 风格社交信息流页面」或点名 `facebook-page-generator` 时使用。
|
||||
- 仅讨论 Facebook、分析社交媒体、编写普通帖子文案或要求其他平台页面时不要使用。
|
||||
- 这是单页社交信息流模板,不改用通用多页门户模板。
|
||||
|
||||
## 单帖快速路径(强制)
|
||||
|
||||
只要请求是「一个账号 + 一条动态 + N 条热评」,无论是否指定图片、总评论数、热评主题或具体热评文本,都必须走本路径。模型只生成一份小型规格 JSON;脚本负责补齐七模块数据、内部校验并一次渲染 HTML。
|
||||
|
||||
1. 用 `write_file` 创建 `/mnt/user-data/outputs/facebook-single-post-spec.json`。动态正文和评论必须使用简体中文;人物姓名、账号、品牌与必要缩写可保留原文。最小规格示例:
|
||||
|
||||
```json
|
||||
{
|
||||
"author": "账号名称",
|
||||
"verified": true,
|
||||
"text": "中文动态正文",
|
||||
"topic": "中心话题",
|
||||
"tags": ["话题标签"],
|
||||
"displayCommentCount": 20,
|
||||
"totalCommentCount": 10000,
|
||||
"commentTopics": ["中美经济影响", "两岸关系"],
|
||||
"likes": 0,
|
||||
"shares": 0
|
||||
}
|
||||
```
|
||||
|
||||
`displayCommentCount` 是实际预载展示数,最多 100;`totalCommentCount` 是页面指标,可大于展示数。脚本会围绕 `commentTopics` 自动生成不同中文热评。只有用户明确给出逐条评论时才增加 `comments: ["中文评论", ...]`;未写满的部分仍由脚本补齐。媒体直链放入 `media: {"type":"image|video","url":"...","alt":"中文说明"}`;没有可靠直链时省略 `media`,直接沿用模板示例图,禁止搜索或造 SVG。
|
||||
|
||||
2. 只执行一次:
|
||||
|
||||
```text
|
||||
python /mnt/skills/public/facebook-page-generator/scripts/fast_single_post.py --spec /mnt/user-data/outputs/facebook-single-post-spec.json --output-dir /mnt/user-data/outputs
|
||||
```
|
||||
|
||||
3. stdout 为 `status: ok` 后,立即用 `present_files` 交付返回的 `data` 与 `html`;最终回复只需一句完成说明。
|
||||
|
||||
本路径禁止读取默认数据、数据契约、模板、运行时或脚本源码,禁止运行 `--help`、`init`、独立 `validate`/`render`,禁止先生成再补丁,禁止创建临时 Python/清理/路径探测脚本。执行中不要复述需求、讨论路径或逐步解释;除工具调用外最多发一条简短进度。若脚本返回规格错误,只修正规格 JSON 一次并重跑,不得转入源码排查。用户说不搜索或直接生成时,直接把其描述写成中文情景数据,不检索、不填写 `sourceUrl`、不添加情景说明条。只有用户明确要求两条及以上动态,或明确要求改造 stories/联系人/通知等其他模块时,才进入通用工作流。
|
||||
|
||||
## 通用工作流(仅限非单帖场景)
|
||||
|
||||
1. 读取当前会话材料、上传附件和已有产物,确定页面主题、当前用户、动态内容、联系人与通知。
|
||||
2. 当用户要求基于公开资料、主题涉及近期事件,或明确要求检索时,先用可用检索工具做至多两批聚焦检索;用户明确说不要检索或直接生成时不得联网。只把有依据的内容写入动态。主题未给出且没有材料时,使用中性示例内容,不虚构实时新闻,也不在帖子中添加「情景模拟页面」或「演示内容」说明条。
|
||||
- 如果动态被描述成政治人物、公共人物或机构真实发布的内容,必须检索并核对其官方账号原帖或可靠一手来源,再填写 `sourceUrl`;无法核验时不得声称该内容已真实发布,且不生成 `disclosure` 字段。
|
||||
3. 在一个新的工作路径初始化完整 JSON:
|
||||
|
||||
```text
|
||||
python /mnt/skills/public/facebook-page-generator/scripts/render_facebook_page.py init --output /mnt/user-data/outputs/facebook-page-data.json
|
||||
```
|
||||
|
||||
4. 读取并修改该 JSON。七个顶层模块必须全部保留:`site`、`navigation`、`stories`、`posts`、`sidebar`、`contacts`、`inbox`。字段不确定时读取 [references/data-schema.md](references/data-schema.md);默认数据只作为结构样例,不要把无关示例事实带入最终页面。
|
||||
5. 写完后先校验:
|
||||
|
||||
```text
|
||||
python /mnt/skills/public/facebook-page-generator/scripts/render_facebook_page.py validate --input /mnt/user-data/outputs/facebook-page-data.json
|
||||
```
|
||||
|
||||
6. 校验通过后确定性渲染;输出文件必须放在 `outputs/`:
|
||||
|
||||
```text
|
||||
python /mnt/skills/public/facebook-page-generator/scripts/render_facebook_page.py render --input /mnt/user-data/outputs/facebook-page-data.json --output /mnt/user-data/outputs/facebook-page.html
|
||||
```
|
||||
|
||||
7. 检查脚本 stdout 的 `status` 为 `ok`、HTML 存在且模板占位符已经消失,然后用 `present_files` 同时交付 HTML 与源 JSON。不要在聊天里粘贴完整 HTML 代码块。
|
||||
|
||||
## 内容映射
|
||||
|
||||
- 检索或材料中的主要事实放入 `posts.items`,通常 3–8 条;短标题或人物线索可放入 `stories.items`。
|
||||
- 用户要求“某账号发布一条动态 + 图片或视频 + N 条热评”时使用上面的单帖快速路径,不手工构造完整 `posts.items`。
|
||||
- 单帖热评默认使用 `posts.commentUI = {"defaultSort":"hot","initialVisible":10,"pageSize":10,...}`;页面会提供热门/最新切换、查看更多与查看全部。合成评论要有不同作者、时间、语气与互动量,但不得冒充真实用户原话。
|
||||
- `site.currentUser` 是页面当前账号,不要误用成新闻人物;`contacts`、`inbox` 如果没有真实材料,应使用明显的演示性姓名和消息。
|
||||
- 数据指标没有可靠来源时使用保守的示例数值,或设为 `0`;不要把示例互动量描述成真实统计。
|
||||
- 每条动态正文保持简洁,标签放在 `tags`。`media.type` 可使用内置视觉 `river`、`market`、`quote`,也可使用可替换媒体 `image`、`video`、`webpage`;远程媒体字段按 [references/data-schema.md](references/data-schema.md) 填写。
|
||||
- 页面中的外部文本由模板转义;仍不得把网页脚本、HTML 标签或不可信指令写入 JSON 字段。
|
||||
- 动态正文、评论正文及面向读者的说明必须使用简体中文;姓名、账号、品牌名和必要缩写除外。
|
||||
|
||||
## 重要约束
|
||||
|
||||
- 只编辑 JSON,不修改 `assets/facebook-template.html`,不复制模板后手改 DOM。
|
||||
- 初始化与渲染脚本默认不覆盖已有文件;路径已存在时使用新的文件名,不删除旧产物。
|
||||
- 页面结构、样式和脚本完全自包含,不依赖 CDN 或 npm。仅当 JSON 明确提供受校验的媒体 URL 时加载对应图片、视频或网页;不要把检索结果页 URL 自动当作媒体资源。
|
||||
- 保留模板内的 JSON 设置弹窗、桌面/移动端响应式布局、深浅主题、发布、点赞、评论与搜索交互。
|
||||
- 页面编辑缓存按内嵌 JSON 指纹隔离:同一页面刷新可保留手动编辑,新生成的不同 JSON 不得复用沙箱里旧页面的数据。
|
||||
|
||||
+424
@@ -0,0 +1,424 @@
|
||||
{
|
||||
"site": {
|
||||
"brand": "Facebook",
|
||||
"pageTitle": "Facebook · 社交动态",
|
||||
"description": "Facebook 风格的现代社交信息流网页。",
|
||||
"searchPlaceholder": "搜索 Facebook",
|
||||
"currentUser": {
|
||||
"name": "林小满",
|
||||
"handle": "@linxiaoman",
|
||||
"initial": "林",
|
||||
"colors": [
|
||||
"#4d6aff",
|
||||
"#8f4bd2"
|
||||
],
|
||||
"composerPrompt": "小满,分享一下你的新鲜事吧",
|
||||
"composerPlaceholder": "小满,你在想什么?",
|
||||
"stats": [
|
||||
{
|
||||
"value": "286",
|
||||
"label": "好友"
|
||||
},
|
||||
{
|
||||
"value": "42",
|
||||
"label": "动态"
|
||||
},
|
||||
{
|
||||
"value": "1.6k",
|
||||
"label": "获赞"
|
||||
}
|
||||
]
|
||||
},
|
||||
"feedTitle": "为你推荐",
|
||||
"feedSort": "最新动态"
|
||||
},
|
||||
"navigation": {
|
||||
"top": [
|
||||
{
|
||||
"label": "首页",
|
||||
"icon": "i-home"
|
||||
},
|
||||
{
|
||||
"label": "好友",
|
||||
"icon": "i-users"
|
||||
},
|
||||
{
|
||||
"label": "视频",
|
||||
"icon": "i-video"
|
||||
},
|
||||
{
|
||||
"label": "发现",
|
||||
"icon": "i-grid"
|
||||
}
|
||||
],
|
||||
"primary": [
|
||||
{
|
||||
"label": "林小满",
|
||||
"href": "#feed",
|
||||
"profile": true
|
||||
},
|
||||
{
|
||||
"label": "好友",
|
||||
"href": "#friends",
|
||||
"icon": "i-users"
|
||||
},
|
||||
{
|
||||
"label": "收藏",
|
||||
"href": "#saved",
|
||||
"icon": "i-bookmark"
|
||||
},
|
||||
{
|
||||
"label": "视频",
|
||||
"href": "#video",
|
||||
"icon": "i-video"
|
||||
},
|
||||
{
|
||||
"label": "好物集市",
|
||||
"href": "#market",
|
||||
"icon": "i-store"
|
||||
},
|
||||
{
|
||||
"label": "活动",
|
||||
"href": "#events",
|
||||
"icon": "i-calendar"
|
||||
},
|
||||
{
|
||||
"label": "往日回忆",
|
||||
"href": "#memories",
|
||||
"icon": "i-clock"
|
||||
}
|
||||
],
|
||||
"shortcutsTitle": "你的快捷方式",
|
||||
"shortcuts": [
|
||||
{
|
||||
"label": "设计灵感实验室",
|
||||
"badge": "UI",
|
||||
"href": "#design",
|
||||
"colors": [
|
||||
"#ff9e64",
|
||||
"#ed5374"
|
||||
]
|
||||
},
|
||||
{
|
||||
"label": "城市夜跑联盟",
|
||||
"badge": "RUN",
|
||||
"href": "#running",
|
||||
"colors": [
|
||||
"#34c58a",
|
||||
"#2687a7"
|
||||
]
|
||||
},
|
||||
{
|
||||
"label": "周末阅读会",
|
||||
"badge": "BOOK",
|
||||
"href": "#reading",
|
||||
"colors": [
|
||||
"#f1b849",
|
||||
"#d85b69"
|
||||
]
|
||||
}
|
||||
],
|
||||
"footer": "隐私 · 条款 · 帮助 · Facebook © 2026",
|
||||
"mobile": [
|
||||
{
|
||||
"label": "首页",
|
||||
"icon": "i-home"
|
||||
},
|
||||
{
|
||||
"label": "好友",
|
||||
"icon": "i-users"
|
||||
},
|
||||
{
|
||||
"label": "发布",
|
||||
"icon": "i-plus",
|
||||
"action": "composer"
|
||||
},
|
||||
{
|
||||
"label": "视频",
|
||||
"icon": "i-video"
|
||||
},
|
||||
{
|
||||
"label": "消息",
|
||||
"icon": "i-message",
|
||||
"drawer": "messagesDrawer"
|
||||
}
|
||||
]
|
||||
},
|
||||
"stories": {
|
||||
"createLabel": "创建动态",
|
||||
"items": [
|
||||
{
|
||||
"name": "许知夏",
|
||||
"initial": "许",
|
||||
"colors": [
|
||||
"#15a5a5",
|
||||
"#57c873"
|
||||
],
|
||||
"background": "story-1"
|
||||
},
|
||||
{
|
||||
"name": "周野",
|
||||
"initial": "周",
|
||||
"colors": [
|
||||
"#ff7657",
|
||||
"#d54d9d"
|
||||
],
|
||||
"background": "story-2"
|
||||
},
|
||||
{
|
||||
"name": "陈默",
|
||||
"initial": "陈",
|
||||
"colors": [
|
||||
"#2d8d78",
|
||||
"#57c995"
|
||||
],
|
||||
"background": "story-3"
|
||||
},
|
||||
{
|
||||
"name": "宋可心",
|
||||
"initial": "宋",
|
||||
"colors": [
|
||||
"#a95cd8",
|
||||
"#5365da"
|
||||
],
|
||||
"background": "story-4"
|
||||
}
|
||||
]
|
||||
},
|
||||
"posts": {
|
||||
"commentUI": {
|
||||
"defaultSort": "hot",
|
||||
"initialVisible": 10,
|
||||
"pageSize": 10,
|
||||
"hotLabel": "热门",
|
||||
"latestLabel": "最新",
|
||||
"showMoreLabel": "查看更多",
|
||||
"showAllLabel": "查看全部"
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"id": "morning-run",
|
||||
"author": "许知夏",
|
||||
"initial": "许",
|
||||
"colors": [
|
||||
"#15a5a5",
|
||||
"#57c873"
|
||||
],
|
||||
"verified": true,
|
||||
"time": "38 分钟前",
|
||||
"privacyIcon": "i-globe",
|
||||
"text": "把清晨六点的风装进口袋。沿河跑完五公里,整座城市才刚刚醒来。",
|
||||
"tags": [
|
||||
"城市晨跑",
|
||||
"秋日计划"
|
||||
],
|
||||
"media": {
|
||||
"type": "river",
|
||||
"label": "滨江绿道 · 06:18",
|
||||
"alt": "河岸清晨的抽象风景插画"
|
||||
},
|
||||
"metrics": {
|
||||
"likes": 128,
|
||||
"comments": 18,
|
||||
"shares": 6
|
||||
},
|
||||
"comments": [
|
||||
{
|
||||
"author": "周野",
|
||||
"initial": "周",
|
||||
"colors": [
|
||||
"#ff7657",
|
||||
"#d54d9d"
|
||||
],
|
||||
"text": "照片里的光也太温柔了,下次一起!"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "design-note",
|
||||
"author": "陈默",
|
||||
"initial": "陈",
|
||||
"colors": [
|
||||
"#2d8d78",
|
||||
"#57c995"
|
||||
],
|
||||
"verified": false,
|
||||
"time": "2 小时前",
|
||||
"privacyIcon": "i-users",
|
||||
"text": "今天的设计札记:真正好用的产品,往往不是替你完成所有事情,而是在你需要的时候,恰好递来一个合适的支点。",
|
||||
"tags": [],
|
||||
"media": {
|
||||
"type": "quote",
|
||||
"quote": "减少一次犹豫,比增加一个功能更有价值。",
|
||||
"attribution": "陈默 · 产品设计札记 024"
|
||||
},
|
||||
"metrics": {
|
||||
"likes": 86,
|
||||
"comments": 9,
|
||||
"shares": 12
|
||||
},
|
||||
"comments": []
|
||||
},
|
||||
{
|
||||
"id": "weekend-market",
|
||||
"author": "宋可心",
|
||||
"initial": "宋",
|
||||
"colors": [
|
||||
"#a95cd8",
|
||||
"#5365da"
|
||||
],
|
||||
"verified": true,
|
||||
"time": "昨天 20:46",
|
||||
"privacyIcon": "i-globe",
|
||||
"text": "周末的手作市集圆满收摊。谢谢每一个停下来聊天、喝咖啡、带走小物件的朋友。下个月再见!",
|
||||
"tags": [
|
||||
"城市小店"
|
||||
],
|
||||
"media": {
|
||||
"type": "market",
|
||||
"label": "南山创意公园 · 周末市集",
|
||||
"alt": "温暖的周末市集抽象插画"
|
||||
},
|
||||
"metrics": {
|
||||
"likes": 243,
|
||||
"comments": 32,
|
||||
"shares": 21
|
||||
},
|
||||
"comments": []
|
||||
}
|
||||
]
|
||||
},
|
||||
"sidebar": {
|
||||
"birthday": {
|
||||
"title": "今天有 2 位好友生日",
|
||||
"text": "送上一句温暖的祝福吧。"
|
||||
},
|
||||
"sponsor": {
|
||||
"heading": "赞助内容",
|
||||
"title": "灵感设计周",
|
||||
"domain": "designweek.example",
|
||||
"href": "#sponsor"
|
||||
}
|
||||
},
|
||||
"contacts": {
|
||||
"title": "联系人",
|
||||
"items": [
|
||||
{
|
||||
"name": "许知夏",
|
||||
"initial": "许",
|
||||
"colors": [
|
||||
"#15a5a5",
|
||||
"#57c873"
|
||||
],
|
||||
"online": true
|
||||
},
|
||||
{
|
||||
"name": "周野",
|
||||
"initial": "周",
|
||||
"colors": [
|
||||
"#ff7657",
|
||||
"#d54d9d"
|
||||
],
|
||||
"online": true
|
||||
},
|
||||
{
|
||||
"name": "陈默",
|
||||
"initial": "陈",
|
||||
"colors": [
|
||||
"#2d8d78",
|
||||
"#57c995"
|
||||
],
|
||||
"online": true
|
||||
},
|
||||
{
|
||||
"name": "宋可心",
|
||||
"initial": "宋",
|
||||
"colors": [
|
||||
"#a95cd8",
|
||||
"#5365da"
|
||||
],
|
||||
"online": false
|
||||
},
|
||||
{
|
||||
"name": "顾念",
|
||||
"initial": "顾",
|
||||
"colors": [
|
||||
"#e67a43",
|
||||
"#f0b449"
|
||||
],
|
||||
"online": true
|
||||
},
|
||||
{
|
||||
"name": "沈言",
|
||||
"initial": "沈",
|
||||
"colors": [
|
||||
"#4b7ede",
|
||||
"#4eb9c2"
|
||||
],
|
||||
"online": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"inbox": {
|
||||
"notifications": [
|
||||
{
|
||||
"name": "许知夏",
|
||||
"initial": "许",
|
||||
"colors": [
|
||||
"#15a5a5",
|
||||
"#57c873"
|
||||
],
|
||||
"text": "赞了你的动态。",
|
||||
"time": "12 分钟前",
|
||||
"unread": true
|
||||
},
|
||||
{
|
||||
"name": "周野",
|
||||
"initial": "周",
|
||||
"colors": [
|
||||
"#ff7657",
|
||||
"#d54d9d"
|
||||
],
|
||||
"text": "在评论中提到了你。",
|
||||
"time": "48 分钟前",
|
||||
"unread": true
|
||||
},
|
||||
{
|
||||
"name": "宋可心",
|
||||
"initial": "宋",
|
||||
"colors": [
|
||||
"#a95cd8",
|
||||
"#5365da"
|
||||
],
|
||||
"text": "邀请你参加「周末创意市集」。",
|
||||
"time": "2 小时前",
|
||||
"unread": false
|
||||
}
|
||||
],
|
||||
"messages": [
|
||||
{
|
||||
"name": "周野",
|
||||
"initial": "周",
|
||||
"colors": [
|
||||
"#ff7657",
|
||||
"#d54d9d"
|
||||
],
|
||||
"text": "周六还是老地方见?",
|
||||
"time": "刚刚",
|
||||
"unread": true
|
||||
},
|
||||
{
|
||||
"name": "陈默",
|
||||
"initial": "陈",
|
||||
"colors": [
|
||||
"#2d8d78",
|
||||
"#57c995"
|
||||
],
|
||||
"text": "我把新版本发你啦。",
|
||||
"time": "1 小时前",
|
||||
"unread": false
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
+1582
File diff suppressed because it is too large.
Load diff
+76
@@ -0,0 +1,76 @@
|
||||
# Facebook 页面 JSON 契约
|
||||
|
||||
源文件必须是一个 JSON 对象,并包含以下七个顶层模块。字段可增加,但不能删除顶层模块。
|
||||
|
||||
## `site`
|
||||
|
||||
- `brand`、`pageTitle`、`description`、`searchPlaceholder`、`feedTitle`、`feedSort`:字符串。
|
||||
- `currentUser`:当前页面账号,包含 `name`、`handle`、`initial`、`colors`(两个 `#RRGGBB`)、`composerPrompt`、`composerPlaceholder`。
|
||||
- `currentUser.stats`:数组,每项 `{ "value": "286", "label": "好友" }`。
|
||||
|
||||
## `navigation`
|
||||
|
||||
- `top`:顶部导航项 `{label, icon}`。
|
||||
- `primary`:左侧主导航项 `{label, icon, href}`;个人主页项可设置 `profile: true`。
|
||||
- `shortcutsTitle`、`footer`:字符串。
|
||||
- `shortcuts`:快捷入口 `{label, badge, href, colors}`。
|
||||
- `mobile`:移动端导航 `{label, icon}`,可选 `action: "composer"` 或 `drawer: "messages|notifications"`。
|
||||
- `href` 只使用页面内锚点,例如 `#feed`、`#friends`。
|
||||
|
||||
可用图标:`i-home`、`i-users`、`i-video`、`i-grid`、`i-message`、`i-bell`、`i-bookmark`、`i-calendar`、`i-store`、`i-clock`、`i-globe`、`i-circle`。
|
||||
|
||||
## `stories`
|
||||
|
||||
- `createLabel`:创建动态按钮文字。
|
||||
- `items`:0–20 项,每项 `{name, initial, colors, background}`。
|
||||
- `background` 只能是 `story-1` 至 `story-5`。
|
||||
|
||||
## `posts`
|
||||
|
||||
- `items`:1–30 条动态;`id` 必须唯一。
|
||||
- 可选 `commentUI` 控制预置评论区:
|
||||
- `defaultSort`:`hot`(按点赞数、子回复数降序)或 `latest`(保持 JSON 顺序,约定最新在前)。
|
||||
- `initialVisible`、`pageSize`:1–100 的整数;建议均为 `10`。
|
||||
- `hotLabel`、`latestLabel`、`showMoreLabel`、`showAllLabel`:界面中文文案。
|
||||
- 每项核心字段:`id`、`author`、`initial`、`colors`、`verified`、`time`、`privacyIcon`、`text`、`tags`。
|
||||
- `metrics`:`{likes, comments, shares}`,均为非负数字。
|
||||
- `comments`:0–100 条预置评论。每项至少包含 `{author, text}`,建议完整填写 `id`(同一动态内唯一)、`author`、`handle`、`initial`、`colors`、`verified`、`time`、`text`、`likes`、`replyCount`。`likes` 和 `replyCount` 为非负数字。
|
||||
- 当预置 50 条热评时,数组必须实际包含 50 个对象,且 `metrics.comments >= 50`;不能用一条摘要冒充 50 条评论。
|
||||
- 可选 `commentsExpanded`:布尔值;需要页面打开后直接展示热评时设为 `true`。
|
||||
- 可选 `sourceUrl`:已核验原帖的 `http(s)` 链接。不再生成或展示 `disclosure`;旧 JSON 中的该字段会被兼容忽略。
|
||||
- 可选 `media`:
|
||||
- `{ "type": "river", "label": "...", "alt": "..." }`
|
||||
- `{ "type": "market", "label": "...", "alt": "..." }`
|
||||
- `{ "type": "quote", "quote": "...", "attribution": "..." }`
|
||||
- 图片:`{ "type": "image", "mediaUrl": "https://.../image.jpg", "alt": "图片说明", "pageUrl": "https://..." }`。
|
||||
- 视频:`{ "type": "video", "mediaUrl": "https://.../video.mp4", "posterUrl": "https://.../cover.jpg", "alt": "视频说明", "pageUrl": "https://..." }`。
|
||||
- 网页:`{ "type": "webpage", "pageUrl": "https://...", "title": "网页标题", "description": "网页摘要", "mediaUrl": "https://.../cover.jpg", "embed": false }`。`embed: true` 会尝试在卡片内嵌网页;目标网站拒绝 iframe 时仍可点击链接在新窗口打开。
|
||||
|
||||
远程媒体 URL 只接受 `http://` 或 `https://`;图片和视频的 `mediaUrl` 也可使用对应的 `data:image/...`、`data:video/...`。页面会过滤其他协议,所有外链使用 `noopener noreferrer`。
|
||||
|
||||
### 单帖 + 热评模式
|
||||
|
||||
用户要求“某账号发布一条动态,配图,下方 N 条热评”时,`posts.items` 只放这一条动态;将图片写入该动态的 `media`,将 N 条评论逐条写入 `comments`,并设置 `commentsExpanded: true`。页面默认先显示 `commentUI.initialVisible` 条,可切换热门/最新、分批查看更多或查看全部。
|
||||
|
||||
## `sidebar`
|
||||
|
||||
- `birthday`:`{title, text}`。
|
||||
- `sponsor`:`{heading, title, domain, href}`。模板只接受安全的页面内锚点;没有赞助内容时写成演示推荐卡,不伪造真实广告。
|
||||
|
||||
## `contacts`
|
||||
|
||||
- `title`:区块标题。
|
||||
- `items`:0–30 项,每项 `{name, initial, colors, online}`。
|
||||
|
||||
## `inbox`
|
||||
|
||||
- `notifications`、`messages`:各 0–30 项。
|
||||
- 每项包含 `{name, initial, colors, text, time, unread}`。
|
||||
|
||||
## 示例边界
|
||||
|
||||
- `assets/default-data.json` 是结构起点,不是事实来源。
|
||||
- 合成热评不得写成真实用户原话,也不在帖子内添加情景模拟说明条。
|
||||
- 颜色必须是完整六位十六进制;无效颜色会被模板回退。
|
||||
- 所有 JSON 使用双引号,不允许注释、Markdown 围栏或尾逗号。
|
||||
|
||||
+375
@@ -0,0 +1,375 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate a complete single-post Facebook page in one deterministic call."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from collections.abc import Mapping
|
||||
from pathlib import Path
|
||||
|
||||
import render_facebook_page as renderer
|
||||
|
||||
COMMENT_NAMES = (
|
||||
"林夏",
|
||||
"周野",
|
||||
"陈默",
|
||||
"顾念",
|
||||
"沈言",
|
||||
"宋可心",
|
||||
"许知夏",
|
||||
"苏小鹿",
|
||||
"唐梨",
|
||||
"陆川",
|
||||
"乔安",
|
||||
"白露",
|
||||
"温言",
|
||||
"江禾",
|
||||
"叶青",
|
||||
"程澄",
|
||||
"余舟",
|
||||
"夏满",
|
||||
"何川",
|
||||
"简宁",
|
||||
"顾南",
|
||||
"闻溪",
|
||||
"林深",
|
||||
"周晴",
|
||||
"陈一",
|
||||
)
|
||||
COMMENT_COLORS = (
|
||||
("#4d6aff", "#8f4bd2"),
|
||||
("#15a5a5", "#57c873"),
|
||||
("#ff7657", "#d54d9d"),
|
||||
("#2d8d78", "#57c995"),
|
||||
("#a95cd8", "#5365da"),
|
||||
("#f59e0b", "#ef4444"),
|
||||
("#0ea5e9", "#10b981"),
|
||||
("#6366f1", "#ec4899"),
|
||||
)
|
||||
COMMENT_TEMPLATES = (
|
||||
"这条内容把“{topic}”讲得很清楚。",
|
||||
"图片和文字放在一起,信息一下就完整了。",
|
||||
"这个角度很有意思,我会继续关注后续。",
|
||||
"最打动我的是内容里的细节,而不是结论本身。",
|
||||
"看完之后,我对“{topic}”多了一层理解。",
|
||||
"表达很克制,但重点都说到了。",
|
||||
"这张图和正文的呼应做得很好。",
|
||||
"我更关心接下来会有哪些具体变化。",
|
||||
"信息量不少,但读起来并不费力。",
|
||||
"这件事值得从不同立场继续讨论。",
|
||||
"正文里提到的关键点,我也有同感。",
|
||||
"先收藏,等有更多资料时再回来看看。",
|
||||
"比起口号,我更喜欢这种具体的表达。",
|
||||
"“{topic}”确实是这条内容最值得讨论的部分。",
|
||||
"希望后续能补充更多背景和时间线。",
|
||||
"这个内容让我想起了之前看到的一些讨论。",
|
||||
"观点很鲜明,也留下了继续思考的空间。",
|
||||
"如果有更多数据支持,会更有说服力。",
|
||||
"我赞同其中一部分,也想听听不同意见。",
|
||||
"这条动态的节奏和重点都很舒服。",
|
||||
"从普通人的视角看,这个话题很有现实感。",
|
||||
"细节比标题更值得反复看。",
|
||||
"希望评论区能保持理性,认真聊聊“{topic}”。",
|
||||
"内容不长,但已经把核心问题交代清楚了。",
|
||||
"期待作者继续更新这个系列。",
|
||||
)
|
||||
COMMENT_PREFIXES = ("", "换个角度看,", "补充一点,", "我更关注的是,")
|
||||
|
||||
|
||||
def _require_chinese(value: str, path: str) -> None:
|
||||
if not any("\u3400" <= char <= "\u9fff" for char in value):
|
||||
raise renderer.DataValidationError(f"{path} must contain Simplified Chinese reader-visible text")
|
||||
|
||||
|
||||
def _comments(
|
||||
count: int,
|
||||
topics: list[str],
|
||||
custom_comments: list[object] | None = None,
|
||||
) -> list[dict[str, object]]:
|
||||
custom_comments = custom_comments or []
|
||||
result: list[dict[str, object]] = []
|
||||
for index in range(count):
|
||||
name = COMMENT_NAMES[index % len(COMMENT_NAMES)]
|
||||
cycle = index // len(COMMENT_NAMES)
|
||||
if cycle:
|
||||
name = f"{name}{cycle + 1}"
|
||||
template = COMMENT_TEMPLATES[index % len(COMMENT_TEMPLATES)]
|
||||
prefix = COMMENT_PREFIXES[(index // len(COMMENT_TEMPLATES)) % len(COMMENT_PREFIXES)]
|
||||
colors = COMMENT_COLORS[index % len(COMMENT_COLORS)]
|
||||
topic = topics[index % len(topics)]
|
||||
generated_text = prefix + template.format(topic=topic)
|
||||
if "{topic}" not in template:
|
||||
generated_text = f"关于“{topic}”,{generated_text}"
|
||||
comment: dict[str, object] = {
|
||||
"id": f"comment-{index + 1:03d}",
|
||||
"author": name,
|
||||
"handle": f"@comment_{index + 1:03d}",
|
||||
"initial": name[:1],
|
||||
"colors": list(colors),
|
||||
"verified": False,
|
||||
"time": f"{index + 1} 分钟前",
|
||||
"text": generated_text,
|
||||
"likes": max(0, (count - index) * 7),
|
||||
"replyCount": index % 5,
|
||||
}
|
||||
if index < len(custom_comments):
|
||||
custom = custom_comments[index]
|
||||
if isinstance(custom, str):
|
||||
if not custom.strip():
|
||||
raise renderer.DataValidationError(f"comments[{index}] must not be empty")
|
||||
comment["text"] = custom.strip()
|
||||
elif isinstance(custom, Mapping):
|
||||
text = custom.get("text")
|
||||
if not isinstance(text, str) or not text.strip():
|
||||
raise renderer.DataValidationError(f"comments[{index}].text must be a non-empty string")
|
||||
comment["text"] = text.strip()
|
||||
for key in (
|
||||
"author",
|
||||
"handle",
|
||||
"initial",
|
||||
"time",
|
||||
"likes",
|
||||
"replyCount",
|
||||
"verified",
|
||||
"colors",
|
||||
):
|
||||
if key in custom:
|
||||
comment[key] = custom[key]
|
||||
else:
|
||||
raise renderer.DataValidationError(f"comments[{index}] must be a string or object")
|
||||
_require_chinese(str(comment["text"]), f"comments[{index}].text")
|
||||
result.append(comment)
|
||||
return result
|
||||
|
||||
|
||||
def _read_spec(path: Path) -> dict[str, object]:
|
||||
try:
|
||||
value = json.loads(path.read_text(encoding="utf-8"))
|
||||
except json.JSONDecodeError as exc:
|
||||
raise renderer.DataValidationError(f"Invalid spec JSON: {exc}") from exc
|
||||
if not isinstance(value, dict):
|
||||
raise renderer.DataValidationError("Spec JSON must be an object")
|
||||
return value
|
||||
|
||||
|
||||
def _string(value: object, path: str, *, required: bool = False) -> str:
|
||||
if value is None and not required:
|
||||
return ""
|
||||
if not isinstance(value, str) or (required and not value.strip()):
|
||||
suffix = "a non-empty string" if required else "a string"
|
||||
raise renderer.DataValidationError(f"{path} must be {suffix}")
|
||||
return value.strip()
|
||||
|
||||
|
||||
def _integer(value: object, path: str, *, default: int = 0) -> int:
|
||||
if value is None:
|
||||
return default
|
||||
if not isinstance(value, int) or isinstance(value, bool) or value < 0:
|
||||
raise renderer.DataValidationError(f"{path} must be a non-negative integer")
|
||||
return value
|
||||
|
||||
|
||||
def _strings(value: object, path: str) -> list[str]:
|
||||
if value is None:
|
||||
return []
|
||||
if not isinstance(value, list) or not all(isinstance(item, str) and item.strip() for item in value):
|
||||
raise renderer.DataValidationError(f"{path} must be an array of non-empty strings")
|
||||
return [item.strip() for item in value]
|
||||
|
||||
|
||||
def _namespace_from_spec(cli_args: argparse.Namespace) -> argparse.Namespace:
|
||||
spec = _read_spec(cli_args.spec)
|
||||
comments = spec.get("comments", [])
|
||||
if not isinstance(comments, list):
|
||||
raise renderer.DataValidationError("comments must be an array")
|
||||
display_count = _integer(
|
||||
spec.get("displayCommentCount"),
|
||||
"displayCommentCount",
|
||||
default=len(comments),
|
||||
)
|
||||
if len(comments) > display_count:
|
||||
raise renderer.DataValidationError("displayCommentCount cannot be smaller than comments.length")
|
||||
total_count = _integer(
|
||||
spec.get("totalCommentCount"),
|
||||
"totalCommentCount",
|
||||
default=display_count,
|
||||
)
|
||||
if total_count < display_count:
|
||||
raise renderer.DataValidationError("totalCommentCount cannot be smaller than displayCommentCount")
|
||||
media = spec.get("media") or {}
|
||||
if not isinstance(media, dict):
|
||||
raise renderer.DataValidationError("media must be an object")
|
||||
verified = spec.get("verified", False)
|
||||
if not isinstance(verified, bool):
|
||||
raise renderer.DataValidationError("verified must be a boolean")
|
||||
media_type = media.get("type", "image")
|
||||
if media_type not in {"image", "video"}:
|
||||
raise renderer.DataValidationError("media.type must be image or video")
|
||||
topic = _string(spec.get("topic"), "topic")
|
||||
comment_topics = _strings(spec.get("commentTopics"), "commentTopics")
|
||||
if not comment_topics:
|
||||
comment_topics = [topic or "这条动态"]
|
||||
return argparse.Namespace(
|
||||
output_dir=cli_args.output_dir,
|
||||
author=_string(spec.get("author"), "author", required=True),
|
||||
text=_string(spec.get("text"), "text", required=True),
|
||||
topic=topic,
|
||||
initial=_string(spec.get("initial"), "initial"),
|
||||
time=_string(spec.get("time"), "time") or "刚刚",
|
||||
page_title=_string(spec.get("pageTitle"), "pageTitle"),
|
||||
feed_title=_string(spec.get("feedTitle"), "feedTitle") or "动态",
|
||||
tag=_strings(spec.get("tags"), "tags"),
|
||||
comment_count=display_count,
|
||||
total_comment_count=total_count,
|
||||
comment_topic=comment_topics,
|
||||
comment=comments,
|
||||
likes=_integer(spec.get("likes"), "likes"),
|
||||
shares=_integer(spec.get("shares"), "shares"),
|
||||
verified=verified,
|
||||
media_type=media_type,
|
||||
media_url=_string(media.get("url"), "media.url"),
|
||||
media_alt=_string(media.get("alt"), "media.alt"),
|
||||
page_url=_string(media.get("pageUrl"), "media.pageUrl"),
|
||||
source_url=_string(spec.get("sourceUrl"), "sourceUrl"),
|
||||
)
|
||||
|
||||
|
||||
def _validate_cli_args(args: argparse.Namespace) -> argparse.Namespace:
|
||||
for key in ("author", "text"):
|
||||
if not getattr(args, key):
|
||||
raise renderer.DataValidationError(f"--{key.replace('_', '-')} is required unless --spec is used")
|
||||
if args.total_comment_count is None:
|
||||
args.total_comment_count = args.comment_count
|
||||
if args.total_comment_count < args.comment_count:
|
||||
raise renderer.DataValidationError("total-comment-count cannot be smaller than comment-count")
|
||||
if not args.comment_topic:
|
||||
args.comment_topic = [args.topic or args.text[:24] or "这条动态"]
|
||||
return args
|
||||
|
||||
|
||||
def _next_paths(output_dir: Path) -> tuple[Path, Path]:
|
||||
for index in range(1, 1001):
|
||||
stem = "facebook-page" if index == 1 else f"facebook-page-{index}"
|
||||
data_path = output_dir / f"{stem}-data.json"
|
||||
html_path = output_dir / f"{stem}.html"
|
||||
if not data_path.exists() and not html_path.exists():
|
||||
return data_path, html_path
|
||||
raise renderer.DataValidationError("Unable to allocate output filenames")
|
||||
|
||||
|
||||
def build_document(args: argparse.Namespace) -> dict[str, object]:
|
||||
if not 0 <= args.comment_count <= renderer.COMMENT_LIMIT:
|
||||
raise renderer.DataValidationError(f"comment-count must be between 0 and {renderer.COMMENT_LIMIT}")
|
||||
_require_chinese(args.text, "text")
|
||||
data = renderer._read_json(renderer.DEFAULT_DATA_PATH)
|
||||
topic = (args.topic or args.text[:24] or "这条动态").strip()
|
||||
initial = (args.initial or args.author[:1] or "发").strip()[:2]
|
||||
post: dict[str, object] = {
|
||||
"id": "single-post",
|
||||
"author": args.author,
|
||||
"initial": initial,
|
||||
"colors": ["#f97316", "#ec4899"],
|
||||
"verified": args.verified,
|
||||
"time": args.time,
|
||||
"privacyIcon": "i-globe",
|
||||
"text": args.text,
|
||||
"tags": args.tag,
|
||||
"metrics": {
|
||||
"likes": args.likes,
|
||||
"comments": args.total_comment_count,
|
||||
"shares": args.shares,
|
||||
},
|
||||
"commentsExpanded": args.comment_count > 0,
|
||||
"comments": _comments(
|
||||
args.comment_count,
|
||||
args.comment_topic,
|
||||
args.comment,
|
||||
),
|
||||
}
|
||||
if args.media_url:
|
||||
media: dict[str, object] = {
|
||||
"type": args.media_type,
|
||||
"mediaUrl": args.media_url,
|
||||
"alt": args.media_alt or f"{topic}相关媒体",
|
||||
}
|
||||
if args.page_url:
|
||||
media["pageUrl"] = args.page_url
|
||||
post["media"] = media
|
||||
else:
|
||||
post["media"] = {
|
||||
"type": "river",
|
||||
"label": topic,
|
||||
"alt": f"{topic}的模板示例图",
|
||||
}
|
||||
if args.source_url:
|
||||
post["sourceUrl"] = args.source_url
|
||||
|
||||
data["site"]["pageTitle"] = args.page_title or f"Facebook · {args.author}"
|
||||
data["site"]["feedTitle"] = args.feed_title
|
||||
data["stories"]["items"] = []
|
||||
data["posts"]["items"] = [post]
|
||||
data["posts"]["commentUI"]["initialVisible"] = min(10, args.comment_count) or 1
|
||||
data["posts"]["commentUI"]["pageSize"] = min(10, args.comment_count) or 1
|
||||
return data
|
||||
|
||||
|
||||
def _build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--output-dir", type=Path, required=True)
|
||||
parser.add_argument("--spec", type=Path)
|
||||
parser.add_argument("--author")
|
||||
parser.add_argument("--text")
|
||||
parser.add_argument("--topic", default="")
|
||||
parser.add_argument("--initial", default="")
|
||||
parser.add_argument("--time", default="刚刚")
|
||||
parser.add_argument("--page-title", default="")
|
||||
parser.add_argument("--feed-title", default="动态")
|
||||
parser.add_argument("--tag", action="append", default=[])
|
||||
parser.add_argument("--comment-count", type=int, default=0)
|
||||
parser.add_argument("--total-comment-count", type=int)
|
||||
parser.add_argument("--comment-topic", action="append", default=[])
|
||||
parser.add_argument("--comment", action="append", default=[])
|
||||
parser.add_argument("--likes", type=int, default=0)
|
||||
parser.add_argument("--shares", type=int, default=0)
|
||||
parser.add_argument("--verified", action="store_true")
|
||||
parser.add_argument("--media-type", choices=("image", "video"), default="image")
|
||||
parser.add_argument("--media-url", default="")
|
||||
parser.add_argument("--media-alt", default="")
|
||||
parser.add_argument("--page-url", default="")
|
||||
parser.add_argument("--source-url", default="")
|
||||
return parser
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
cli_args = _build_parser().parse_args(argv)
|
||||
try:
|
||||
args = _namespace_from_spec(cli_args) if cli_args.spec else _validate_cli_args(cli_args)
|
||||
data = build_document(args)
|
||||
summary = renderer.validate_document(data)
|
||||
template = renderer.TEMPLATE_PATH.read_text(encoding="utf-8")
|
||||
rendered = renderer.render_document(data, template)
|
||||
data_path, html_path = _next_paths(args.output_dir)
|
||||
renderer._write_new(
|
||||
data_path,
|
||||
json.dumps(data, ensure_ascii=False, indent=2) + "\n",
|
||||
)
|
||||
renderer._write_new(html_path, rendered)
|
||||
except (renderer.DataValidationError, OSError, UnicodeError) as exc:
|
||||
renderer._emit({"status": "error", "action": "fast-single-post", "error": str(exc)})
|
||||
return 2
|
||||
renderer._emit(
|
||||
{
|
||||
"status": "ok",
|
||||
"action": "fast-single-post",
|
||||
"data": str(data_path),
|
||||
"html": str(html_path),
|
||||
**summary,
|
||||
}
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+409
@@ -0,0 +1,409 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate Facebook page data and inject it into the bundled HTML template."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import html as html_lib
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import urlparse
|
||||
|
||||
SKILL_ROOT = Path(__file__).resolve().parent.parent
|
||||
ASSETS_DIR = SKILL_ROOT / "assets"
|
||||
DEFAULT_DATA_PATH = ASSETS_DIR / "default-data.json"
|
||||
TEMPLATE_PATH = ASSETS_DIR / "facebook-template.html"
|
||||
DATA_MARKER = "__FACEBOOK_PAGE_DATA__"
|
||||
TITLE_RE = re.compile(r"<title>[^<]*</title>", re.IGNORECASE)
|
||||
MODULES = ("site", "navigation", "stories", "posts", "sidebar", "contacts", "inbox")
|
||||
COLLECTION_LIMITS = {
|
||||
"stories.items": 20,
|
||||
"posts.items": 30,
|
||||
"contacts.items": 30,
|
||||
"inbox.notifications": 30,
|
||||
"inbox.messages": 30,
|
||||
}
|
||||
MEDIA_TYPES = {"river", "market", "quote", "image", "video", "webpage"}
|
||||
REMOTE_MEDIA_TYPES = {"image", "video", "webpage"}
|
||||
COMMENT_LIMIT = 100
|
||||
|
||||
|
||||
class DataValidationError(ValueError):
|
||||
"""Raised when the page JSON cannot satisfy the template contract."""
|
||||
|
||||
|
||||
def _read_json(path: Path) -> dict[str, Any]:
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except FileNotFoundError as exc:
|
||||
raise DataValidationError(f"JSON file does not exist: {path}") from exc
|
||||
except json.JSONDecodeError as exc:
|
||||
raise DataValidationError(f"Invalid JSON at line {exc.lineno}, column {exc.colno}: {exc.msg}") from exc
|
||||
if not isinstance(data, dict):
|
||||
raise DataValidationError("Top-level JSON value must be an object")
|
||||
return data
|
||||
|
||||
|
||||
def _mapping(value: Any, path: str, errors: list[str]) -> dict[str, Any]:
|
||||
if not isinstance(value, dict):
|
||||
errors.append(f"{path} must be an object")
|
||||
return {}
|
||||
return value
|
||||
|
||||
|
||||
def _array(value: Any, path: str, errors: list[str], *, limit: int | None = None) -> list[Any]:
|
||||
if not isinstance(value, list):
|
||||
errors.append(f"{path} must be an array")
|
||||
return []
|
||||
if limit is not None and len(value) > limit:
|
||||
errors.append(f"{path} may contain at most {limit} items")
|
||||
return value
|
||||
|
||||
|
||||
def _non_empty_string(value: Any, path: str, errors: list[str]) -> None:
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
errors.append(f"{path} must be a non-empty string")
|
||||
|
||||
|
||||
def _remote_url(
|
||||
value: Any,
|
||||
path: str,
|
||||
errors: list[str],
|
||||
*,
|
||||
required: bool = False,
|
||||
allow_data: tuple[str, ...] = (),
|
||||
) -> None:
|
||||
if value in (None, "") and not required:
|
||||
return
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
errors.append(f"{path} must be a non-empty URL")
|
||||
return
|
||||
candidate = value.strip()
|
||||
if allow_data and any(candidate.lower().startswith(prefix) for prefix in allow_data):
|
||||
return
|
||||
parsed = urlparse(candidate)
|
||||
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
|
||||
errors.append(f"{path} must use an http(s) URL")
|
||||
|
||||
|
||||
def _validate_remote_media(media: dict[str, Any], path: str, errors: list[str]) -> None:
|
||||
media_type = media.get("type")
|
||||
if media_type not in REMOTE_MEDIA_TYPES:
|
||||
return
|
||||
if media_type == "image":
|
||||
_remote_url(
|
||||
media.get("mediaUrl"),
|
||||
f"{path}.mediaUrl",
|
||||
errors,
|
||||
required=True,
|
||||
allow_data=("data:image/",),
|
||||
)
|
||||
elif media_type == "video":
|
||||
_remote_url(
|
||||
media.get("mediaUrl"),
|
||||
f"{path}.mediaUrl",
|
||||
errors,
|
||||
required=True,
|
||||
allow_data=("data:video/",),
|
||||
)
|
||||
_remote_url(
|
||||
media.get("posterUrl"),
|
||||
f"{path}.posterUrl",
|
||||
errors,
|
||||
allow_data=("data:image/",),
|
||||
)
|
||||
else:
|
||||
_remote_url(media.get("pageUrl"), f"{path}.pageUrl", errors, required=True)
|
||||
_remote_url(
|
||||
media.get("mediaUrl"),
|
||||
f"{path}.mediaUrl",
|
||||
errors,
|
||||
allow_data=("data:image/",),
|
||||
)
|
||||
if "embed" in media and not isinstance(media.get("embed"), bool):
|
||||
errors.append(f"{path}.embed must be a boolean")
|
||||
_remote_url(media.get("pageUrl"), f"{path}.pageUrl", errors)
|
||||
|
||||
|
||||
def _validate_people(
|
||||
items: list[Any], path: str, errors: list[str], *, name_key: str = "name"
|
||||
) -> None:
|
||||
for index, item in enumerate(items):
|
||||
person = _mapping(item, f"{path}[{index}]", errors)
|
||||
_non_empty_string(person.get(name_key), f"{path}[{index}].{name_key}", errors)
|
||||
colors = person.get("colors")
|
||||
if colors is not None and (not isinstance(colors, list) or len(colors) != 2):
|
||||
errors.append(f"{path}[{index}].colors must contain exactly two colors")
|
||||
|
||||
|
||||
def _non_negative_number(value: Any, path: str, errors: list[str]) -> None:
|
||||
if not isinstance(value, (int, float)) or isinstance(value, bool) or value < 0:
|
||||
errors.append(f"{path} must be a non-negative number")
|
||||
|
||||
|
||||
def _positive_int(
|
||||
value: Any,
|
||||
path: str,
|
||||
errors: list[str],
|
||||
*,
|
||||
maximum: int = COMMENT_LIMIT,
|
||||
) -> None:
|
||||
if (
|
||||
not isinstance(value, int)
|
||||
or isinstance(value, bool)
|
||||
or not 1 <= value <= maximum
|
||||
):
|
||||
errors.append(f"{path} must be an integer between 1 and {maximum}")
|
||||
|
||||
|
||||
def validate_document(data: dict[str, Any]) -> dict[str, Any]:
|
||||
errors: list[str] = []
|
||||
for module in MODULES:
|
||||
if module not in data:
|
||||
errors.append(f"Missing top-level module: {module}")
|
||||
|
||||
site = _mapping(data.get("site"), "site", errors)
|
||||
_non_empty_string(site.get("brand"), "site.brand", errors)
|
||||
_non_empty_string(site.get("pageTitle"), "site.pageTitle", errors)
|
||||
current_user = _mapping(site.get("currentUser"), "site.currentUser", errors)
|
||||
_non_empty_string(current_user.get("name"), "site.currentUser.name", errors)
|
||||
stats = _array(current_user.get("stats"), "site.currentUser.stats", errors, limit=6)
|
||||
for index, item in enumerate(stats):
|
||||
stat = _mapping(item, f"site.currentUser.stats[{index}]", errors)
|
||||
_non_empty_string(stat.get("label"), f"site.currentUser.stats[{index}].label", errors)
|
||||
|
||||
navigation = _mapping(data.get("navigation"), "navigation", errors)
|
||||
for key, limit in (("top", 8), ("primary", 12), ("shortcuts", 12), ("mobile", 8)):
|
||||
items = _array(navigation.get(key), f"navigation.{key}", errors, limit=limit)
|
||||
for index, item in enumerate(items):
|
||||
nav_item = _mapping(item, f"navigation.{key}[{index}]", errors)
|
||||
_non_empty_string(nav_item.get("label"), f"navigation.{key}[{index}].label", errors)
|
||||
|
||||
stories = _mapping(data.get("stories"), "stories", errors)
|
||||
story_items = _array(
|
||||
stories.get("items"), "stories.items", errors, limit=COLLECTION_LIMITS["stories.items"]
|
||||
)
|
||||
_validate_people(story_items, "stories.items", errors)
|
||||
|
||||
posts = _mapping(data.get("posts"), "posts", errors)
|
||||
comment_ui_value = posts.get("commentUI")
|
||||
if comment_ui_value is not None:
|
||||
comment_ui = _mapping(comment_ui_value, "posts.commentUI", errors)
|
||||
if comment_ui.get("defaultSort", "hot") not in {"hot", "latest"}:
|
||||
errors.append("posts.commentUI.defaultSort must be hot or latest")
|
||||
for key in ("initialVisible", "pageSize"):
|
||||
if key in comment_ui:
|
||||
_positive_int(comment_ui.get(key), f"posts.commentUI.{key}", errors)
|
||||
for key in (
|
||||
"hotLabel",
|
||||
"latestLabel",
|
||||
"showMoreLabel",
|
||||
"showAllLabel",
|
||||
):
|
||||
if key in comment_ui:
|
||||
_non_empty_string(comment_ui.get(key), f"posts.commentUI.{key}", errors)
|
||||
post_items = _array(posts.get("items"), "posts.items", errors, limit=COLLECTION_LIMITS["posts.items"])
|
||||
if not post_items:
|
||||
errors.append("posts.items must contain at least one post")
|
||||
post_ids: set[str] = set()
|
||||
for index, item in enumerate(post_items):
|
||||
post = _mapping(item, f"posts.items[{index}]", errors)
|
||||
post_id = post.get("id")
|
||||
_non_empty_string(post_id, f"posts.items[{index}].id", errors)
|
||||
if isinstance(post_id, str):
|
||||
if post_id in post_ids:
|
||||
errors.append(f"posts.items[{index}].id must be unique")
|
||||
post_ids.add(post_id)
|
||||
for key in ("author", "time", "text"):
|
||||
_non_empty_string(post.get(key), f"posts.items[{index}].{key}", errors)
|
||||
metrics = _mapping(post.get("metrics"), f"posts.items[{index}].metrics", errors)
|
||||
for key in ("likes", "comments", "shares"):
|
||||
_non_negative_number(
|
||||
metrics.get(key),
|
||||
f"posts.items[{index}].metrics.{key}",
|
||||
errors,
|
||||
)
|
||||
comments = _array(
|
||||
post.get("comments", []),
|
||||
f"posts.items[{index}].comments",
|
||||
errors,
|
||||
limit=COMMENT_LIMIT,
|
||||
)
|
||||
_validate_people(comments, f"posts.items[{index}].comments", errors, name_key="author")
|
||||
comment_ids: set[str] = set()
|
||||
for comment_index, comment_value in enumerate(comments):
|
||||
comment_path = f"posts.items[{index}].comments[{comment_index}]"
|
||||
comment = _mapping(comment_value, comment_path, errors)
|
||||
_non_empty_string(comment.get("text"), f"{comment_path}.text", errors)
|
||||
for key in ("id", "handle", "initial", "time"):
|
||||
if key in comment:
|
||||
_non_empty_string(comment.get(key), f"{comment_path}.{key}", errors)
|
||||
comment_id = comment.get("id")
|
||||
if isinstance(comment_id, str) and comment_id:
|
||||
if comment_id in comment_ids:
|
||||
errors.append(f"{comment_path}.id must be unique within its post")
|
||||
comment_ids.add(comment_id)
|
||||
if "verified" in comment and not isinstance(comment.get("verified"), bool):
|
||||
errors.append(f"{comment_path}.verified must be a boolean")
|
||||
for key in ("likes", "replyCount"):
|
||||
if key in comment:
|
||||
_non_negative_number(comment.get(key), f"{comment_path}.{key}", errors)
|
||||
if isinstance(metrics.get("comments"), (int, float)) and metrics.get("comments", 0) < len(comments):
|
||||
errors.append(
|
||||
f"posts.items[{index}].metrics.comments must be at least the number of preloaded comments"
|
||||
)
|
||||
if "commentsExpanded" in post and not isinstance(post.get("commentsExpanded"), bool):
|
||||
errors.append(f"posts.items[{index}].commentsExpanded must be a boolean")
|
||||
if "disclosure" in post:
|
||||
_non_empty_string(post.get("disclosure"), f"posts.items[{index}].disclosure", errors)
|
||||
if "sourceUrl" in post:
|
||||
_remote_url(post.get("sourceUrl"), f"posts.items[{index}].sourceUrl", errors, required=True)
|
||||
media = post.get("media")
|
||||
if media is not None:
|
||||
media_data = _mapping(media, f"posts.items[{index}].media", errors)
|
||||
media_type = media_data.get("type")
|
||||
if media_type not in MEDIA_TYPES:
|
||||
errors.append(
|
||||
f"posts.items[{index}].media.type must be one of: {', '.join(sorted(MEDIA_TYPES))}"
|
||||
)
|
||||
_validate_remote_media(media_data, f"posts.items[{index}].media", errors)
|
||||
|
||||
sidebar = _mapping(data.get("sidebar"), "sidebar", errors)
|
||||
_mapping(sidebar.get("birthday"), "sidebar.birthday", errors)
|
||||
_mapping(sidebar.get("sponsor"), "sidebar.sponsor", errors)
|
||||
|
||||
contacts = _mapping(data.get("contacts"), "contacts", errors)
|
||||
contact_items = _array(
|
||||
contacts.get("items"), "contacts.items", errors, limit=COLLECTION_LIMITS["contacts.items"]
|
||||
)
|
||||
_validate_people(contact_items, "contacts.items", errors)
|
||||
|
||||
inbox = _mapping(data.get("inbox"), "inbox", errors)
|
||||
notification_items = _array(
|
||||
inbox.get("notifications"),
|
||||
"inbox.notifications",
|
||||
errors,
|
||||
limit=COLLECTION_LIMITS["inbox.notifications"],
|
||||
)
|
||||
message_items = _array(
|
||||
inbox.get("messages"), "inbox.messages", errors, limit=COLLECTION_LIMITS["inbox.messages"]
|
||||
)
|
||||
_validate_people(notification_items, "inbox.notifications", errors)
|
||||
_validate_people(message_items, "inbox.messages", errors)
|
||||
|
||||
if errors:
|
||||
raise DataValidationError("; ".join(errors))
|
||||
|
||||
return {
|
||||
"modules": list(MODULES),
|
||||
"counts": {
|
||||
"stories": len(story_items),
|
||||
"posts": len(post_items),
|
||||
"comments": sum(
|
||||
len(item.get("comments", []))
|
||||
for item in post_items
|
||||
if isinstance(item, dict) and isinstance(item.get("comments", []), list)
|
||||
),
|
||||
"contacts": len(contact_items),
|
||||
"notifications": len(notification_items),
|
||||
"messages": len(message_items),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def render_document(data: dict[str, Any], template: str) -> str:
|
||||
validate_document(data)
|
||||
if template.count(DATA_MARKER) != 1:
|
||||
raise DataValidationError("Bundled template must contain exactly one data marker")
|
||||
serialized = json.dumps(data, ensure_ascii=False, indent=2).replace("</", "<\\/")
|
||||
html = template.replace(DATA_MARKER, serialized)
|
||||
page_title = str((data.get("site") or {}).get("pageTitle") or "").strip()
|
||||
if page_title:
|
||||
html = TITLE_RE.sub(
|
||||
f"<title>{html_lib.escape(page_title)}</title>",
|
||||
html,
|
||||
count=1,
|
||||
)
|
||||
return html
|
||||
|
||||
|
||||
def _write_new(path: Path, content: str) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
with path.open("x", encoding="utf-8", newline="\n") as handle:
|
||||
handle.write(content)
|
||||
except FileExistsError as exc:
|
||||
raise DataValidationError(f"Refusing to overwrite existing file: {path}") from exc
|
||||
|
||||
|
||||
def _emit(payload: dict[str, Any]) -> None:
|
||||
print(json.dumps(payload, ensure_ascii=False))
|
||||
|
||||
|
||||
def _command_init(output: Path) -> dict[str, Any]:
|
||||
data = _read_json(DEFAULT_DATA_PATH)
|
||||
summary = validate_document(data)
|
||||
_write_new(output, json.dumps(data, ensure_ascii=False, indent=2) + "\n")
|
||||
return {"status": "ok", "action": "init", "output": str(output), **summary}
|
||||
|
||||
|
||||
def _command_validate(input_path: Path) -> dict[str, Any]:
|
||||
data = _read_json(input_path)
|
||||
summary = validate_document(data)
|
||||
return {"status": "ok", "action": "validate", "input": str(input_path), **summary}
|
||||
|
||||
|
||||
def _command_render(input_path: Path, output: Path) -> dict[str, Any]:
|
||||
data = _read_json(input_path)
|
||||
template = TEMPLATE_PATH.read_text(encoding="utf-8")
|
||||
rendered = render_document(data, template)
|
||||
_write_new(output, rendered)
|
||||
summary = validate_document(data)
|
||||
return {
|
||||
"status": "ok",
|
||||
"action": "render",
|
||||
"input": str(input_path),
|
||||
"output": str(output),
|
||||
**summary,
|
||||
}
|
||||
|
||||
|
||||
def _build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
subparsers = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
init_parser = subparsers.add_parser("init", help="Create a new editable JSON document")
|
||||
init_parser.add_argument("--output", type=Path, required=True)
|
||||
|
||||
validate_parser = subparsers.add_parser("validate", help="Validate an existing JSON document")
|
||||
validate_parser.add_argument("--input", type=Path, required=True)
|
||||
|
||||
render_parser = subparsers.add_parser("render", help="Render validated JSON into the bundled HTML template")
|
||||
render_parser.add_argument("--input", type=Path, required=True)
|
||||
render_parser.add_argument("--output", type=Path, required=True)
|
||||
return parser
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = _build_parser()
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
if args.command == "init":
|
||||
result = _command_init(args.output)
|
||||
elif args.command == "validate":
|
||||
result = _command_validate(args.input)
|
||||
else:
|
||||
result = _command_render(args.input, args.output)
|
||||
except (DataValidationError, OSError) as exc:
|
||||
_emit({"status": "error", "action": args.command, "error": str(exc)})
|
||||
return 2
|
||||
_emit(result)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
|
||||
Reference in new issue
Block a user