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
+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