#!/usr/bin/env python3 """Export VIP formal content seed JSON from miniprogram H5 data TS files.""" from __future__ import annotations import json import re from datetime import datetime, timezone from pathlib import Path REPO = Path(__file__).resolve().parents[3] H5 = REPO / "apps" / "miniprogram" / "h5" / "src" / "data" OUT = REPO / "apps" / "api" / "services" / "ebook_svc" / "data" / "vip_library_seed.json" def _extract_json_assign(text: str, name: str): m = re.search(rf"(?:export\s+)?const {name}\s*(?::[^=]+)?=\s*", text) if not m: raise SystemExit(f"missing {name}") i = m.end() while i < len(text) and text[i].isspace(): i += 1 if text[i] not in "{[": raise SystemExit(f"{name}: expected object/array") open_ch, close_ch = ("{", "}") if text[i] == "{" else ("[", "]") depth = 0 in_str = False esc = False j = i while j < len(text): ch = text[j] if in_str: if esc: esc = False elif ch == "\\": esc = True elif ch == '"': in_str = False else: if ch == '"': in_str = True elif ch == open_ch: depth += 1 elif ch == close_ch: depth -= 1 if depth == 0: raw = text[i : j + 1] # TS → JSON: trailing commas, quotes, bare keys raw = re.sub(r",\s*([}\]])", r"\1", raw) raw = re.sub(r"(?m)^\s*'([^']+)'\s*:", r'"\1":', raw) raw = re.sub(r"([{\[,]\s*)([A-Za-z_][A-Za-z0-9_]*)\s*:", r'\1"\2":', raw) raw = re.sub(r":\s*'([^']*)'", r': "\1"', raw) return json.loads(raw) j += 1 raise SystemExit(f"{name}: unclosed") def main() -> int: ebooks = _extract_json_assign((H5 / "vipEbooks.ts").read_text(encoding="utf-8"), "VIP_EBOOKS") course_txt = (H5 / "vipCourse.ts").read_text(encoding="utf-8") videos = _extract_json_assign(course_txt, "V") fallback = ( "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" ) # RAW uses unquoted keys — parse lesson rows via regex row_re = re.compile( r"\{\s*name:\s*'([^']*)'\s*,\s*duration:\s*'([^']*)'\s*,\s*key:\s*'([^']*)'\s*\}" ) mod_re = re.compile( r"\{\s*emoji:\s*'([^']*)'\s*,\s*title:\s*'([^']*)'\s*,\s*lessons:\s*\[(.*?)\]\s*,?\s*\}", re.S, ) # slice RAW block mi0 = course_txt.find("const RAW =") mi1 = course_txt.find("] as const", mi0) raw_block = course_txt[mi0:mi1] course_mods = [] for mi, mm in enumerate(mod_re.finditer(raw_block)): lessons_list = [] for li, lm in enumerate(row_re.finditer(mm.group(3))): key = lm.group(3) lessons_list.append( { "key": key, "moduleIndex": mi, "lessonIndex": li, "name": lm.group(1), "duration": lm.group(2), "videoUrl": str(videos.get(key) or fallback), } ) course_mods.append( {"emoji": mm.group(1), "title": mm.group(2), "lessons": lessons_list} ) if not course_mods: raise SystemExit("failed to parse RAW modules") lessons = _extract_json_assign( (H5 / "vipLessonContent.ts").read_text(encoding="utf-8"), "VIP_LESSON_CONTENT" ) lib = { "version": 1, "updatedAt": datetime.now(timezone.utc).isoformat(), "ebooks": ebooks, "course": {"id": "cloudphone", "title": "云手机实战课", "modules": course_mods}, "lessons": lessons, } OUT.parent.mkdir(parents=True, exist_ok=True) OUT.write_text(json.dumps(lib, ensure_ascii=False, separators=(",", ":")), encoding="utf-8") print( "wrote", OUT, "ebooks", list(ebooks.keys()), "modules", len(course_mods), "lessons", len(lessons), "kb", OUT.stat().st_size // 1024, ) return 0 if __name__ == "__main__": raise SystemExit(main())