#!/usr/bin/env python3 """Assemble 电子书小红书包 — 同步壳层后强制 hackrobot 正文,再扁平打包。""" from __future__ import annotations import shutil import sys from pathlib import Path from subprocess import check_call ROOT = Path(__file__).resolve().parents[1] MINI = ROOT.parent SRC = ROOT / "tool" OUT = ROOT / "release-book" PACK_CANDIDATES = ( MINI / "weapp" / "scripts" / "pack-hackrobot-book.py", MINI / "scripts" / "pack-hackrobot-book.py", ) def main() -> int: sync = ROOT / "scripts" / "sync_data.py" if sync.is_file(): try: check_call([sys.executable, str(sync)]) except Exception as e: print(f"WARN sync_data failed, continue with local book seed: {e}", file=sys.stderr) # export 会写回旧册;必须再用 hackrobot 覆盖 book-data + portal.book pack = next((p for p in PACK_CANDIDATES if p.is_file()), None) if pack: check_call([sys.executable, str(pack)]) else: print(f"WARN missing pack-hackrobot-book.py under {PACK_CANDIDATES}", file=sys.stderr) if OUT.exists(): shutil.rmtree(OUT, ignore_errors=True) OUT.mkdir(parents=True) parts = [] for name in ("book/book-data.js", "book/markdown.js", "book/xhs-bridge.js", "book-app.js"): p = SRC / name if not p.is_file(): print(f"missing {name}", file=sys.stderr) return 1 text = p.read_text(encoding="utf-8") if name == "book-app.js": marker = "(function ()" idx = text.find(marker) if idx < 0: idx = text.find("function getBook") if idx > 0 and "var BOOK_DATA" in text[:idx]: text = "/* book-app runtime */\n" + text[idx:] parts.append(text) html_src = SRC / "book.html" css_src = SRC / "book-styles.css" if not html_src.is_file() or not css_src.is_file(): print("missing book.html / book-styles.css", file=sys.stderr) return 1 shutil.copy2(html_src, OUT / "index.html") shutil.copy2(css_src, OUT / "styles.css") (OUT / "app.js").write_text( "/* bundled xhs ebook — hackrobot offline BOOK_DATA */\n" + "\n".join(parts) + "\n", encoding="utf-8", ) book_imgs = SRC / "book" / "images" if book_imgs.is_dir(): shutil.copytree(book_imgs, OUT / "images") nested = [p for p in OUT.rglob("index.html") if p != OUT / "index.html"] if nested: print("FATAL nested index.html", nested, file=sys.stderr) return 1 app_js = (OUT / "app.js").read_text(encoding="utf-8", errors="ignore") if "低成本工作室" not in app_js or "数字游民:自动化杠杆副业" not in app_js: print("FATAL release-book missing hackrobot chapters", file=sys.stderr) return 1 if "rewardAuthor" not in app_js or "free_chapters" not in app_js: print("FATAL release-book missing tip/trial unlock hooks", file=sys.stderr) return 1 css = (OUT / "styles.css").read_text(encoding="utf-8", errors="ignore") html = (OUT / "index.html").read_text(encoding="utf-8", errors="ignore") if ".paywall" not in css or 'id="btn-reward"' not in html: print("FATAL release-book missing paywall UI", file=sys.stderr) return 1 print(f"assembled {OUT}") for p in sorted(OUT.iterdir()): if p.is_file(): print(f" {p.name}\t{p.stat().st_size}") return 0 if __name__ == "__main__": raise SystemExit(main())