| 1 | """共用文章输入及 Markdown 主题渲染;此模块不登录、不上传,也不处理平台限制。""" |
| 2 | from __future__ import annotations |
| 3 | |
| 4 | import json |
| 5 | import os |
| 6 | import shutil |
| 7 | import subprocess |
| 8 | from html import escape |
| 9 | from pathlib import Path |
| 10 | |
| 11 | from utils.article_content import ArticleDocument |
| 12 | |
| 13 | |
| 14 | ARTICLE_THEMES = { |
| 15 | "plain": "原生:仅转换正文结构,不添加主题样式", |
| 16 | "default": "经典:居中标题与强调色", |
| 17 | "grace": "优雅:圆角引用与柔和装饰", |
| 18 | "simple": "简洁:清晰留白与轻量装饰", |
| 19 | "modern": "现代:暖色、圆角与宽松行距", |
| 20 | } |
| 21 | ARTICLE_MARKDOWN_EXTENSIONS = {".md", ".markdown"} |
| 22 | ARTICLE_HTML_EXTENSIONS = {".html", ".htm"} |
| 23 | ARTICLE_RENDERER_DIR = Path(__file__).with_name("article_renderer") |
| 24 | |
| 25 | |
| 26 | def load_article(content_file: str | Path, theme: str | None = None) -> ArticleDocument: |
| 27 | """从原稿所在目录解析资源;长正文通过标准输入传递,不进入命令行参数。""" |
| 28 | path = Path(content_file).expanduser().resolve() |
| 29 | source = path.read_text(encoding="utf-8-sig") |
| 30 | suffix = path.suffix.lower() |
| 31 | metadata = {} |
| 32 | if suffix in ARTICLE_MARKDOWN_EXTENSIONS: |
| 33 | theme = theme or "default" |
| 34 | if theme not in ARTICLE_THEMES: |
| 35 | raise ValueError(f"主题必须为: {', '.join(ARTICLE_THEMES)}") |
| 36 | node = shutil.which("node") |
| 37 | if not node or not (ARTICLE_RENDERER_DIR / "node_modules/baoyu-md").is_dir(): |
| 38 | raise RuntimeError("Markdown 渲染需要 Node.js 22+ 及依赖;请执行 sau article setup") |
| 39 | completed = subprocess.run( |
| 40 | [node, str(ARTICLE_RENDERER_DIR / "render.mjs")], |
| 41 | input=json.dumps({"content": source, "theme": theme}, ensure_ascii=False), |
| 42 | capture_output=True, text=True, encoding="utf-8", timeout=60, |
| 43 | ) |
| 44 | if completed.returncode: |
| 45 | raise RuntimeError(f"Markdown 渲染失败: {completed.stderr.strip()}") |
| 46 | payload = json.loads(completed.stdout) |
| 47 | source, metadata = payload["html"], payload["metadata"] |
| 48 | elif suffix in ARTICLE_HTML_EXTENSIONS | {".txt"}: |
| 49 | if theme is not None: |
| 50 | raise ValueError("--theme 仅适用于 Markdown;HTML 和 TXT 不重新套用主题") |
| 51 | if suffix == ".txt": |
| 52 | source = "".join(f"<p>{escape(line) if line else '<br>'}</p>" for line in source.splitlines()) |
| 53 | else: |
| 54 | raise ValueError("正文文件支持 .html/.htm、.md/.markdown,以及兼容的 .txt") |
| 55 | document = ArticleDocument(source, path.parent) |
| 56 | document.source_format = "markdown" if suffix in ARTICLE_MARKDOWN_EXTENSIONS else ("text" if suffix == ".txt" else "html") |
| 57 | document.theme = theme |
| 58 | document.metadata = metadata |
| 59 | return document |
| 60 | |
| 61 | |
| 62 | def render_article_file(content_file: str | Path, output: str | Path, |
| 63 | theme: str | None = None, overwrite: bool = False) -> dict: |
| 64 | """保存可独立预览的 HTML;输出路径改变时仍能找到原稿中的本地图片。""" |
| 65 | source = Path(content_file).expanduser().resolve() |
| 66 | target = Path(output).expanduser().resolve() |
| 67 | if target == source: |
| 68 | raise ValueError("输出文件不能覆盖输入原稿") |
| 69 | if target.suffix.lower() not in ARTICLE_HTML_EXTENSIONS: |
| 70 | raise ValueError("--output 必须为 .html 或 .htm 文件") |
| 71 | if target.exists() and not overwrite: |
| 72 | raise FileExistsError(f"输出文件已存在;使用 --overwrite 明确覆盖: {target}") |
| 73 | document = load_article(source, theme) |
| 74 | title = escape(document.metadata.get("title", source.stem)) |
| 75 | html = ('<!doctype html><html><head><meta charset="utf-8">' |
| 76 | '<meta name="viewport" content="width=device-width, initial-scale=1">' |
| 77 | f'<title>{title}</title></head><body>{document.content_html}</body></html>') |
| 78 | target.parent.mkdir(parents=True, exist_ok=True) |
| 79 | target.write_text(html, encoding="utf-8") |
| 80 | return {"output": str(target), "format": document.source_format, |
| 81 | "theme": document.theme, "image_count": len(document.images)} |
| 82 | |
| 83 | |
| 84 | def setup_article_renderer() -> None: |
| 85 | """按锁文件安装本地渲染依赖;发表和渲染过程中不下载程序。""" |
| 86 | node = shutil.which("node") |
| 87 | npm = shutil.which("npm.cmd" if os.name == "nt" else "npm") |
| 88 | if not node or not npm: |
| 89 | raise RuntimeError("请先安装 Node.js 22+(含 npm),再执行 sau article setup") |
| 90 | version = subprocess.check_output([node, "--version"], text=True).strip() |
| 91 | if int(version.lstrip("v").split(".")[0]) < 22: |
| 92 | raise RuntimeError(f"文章渲染需要 Node.js 22+,当前为 {version}") |
| 93 | subprocess.run([npm, "ci", "--ignore-scripts", "--no-audit", "--no-fund"], |
| 94 | cwd=ARTICLE_RENDERER_DIR, check=True, timeout=180) |
| 95 |