server.py 9.3 KB
import os, json, sys, runpy, subprocess, io, webbrowser, mimetypes
from fastapi import FastAPI, Request
from fastapi.responses import Response, PlainTextResponse, FileResponse, HTMLResponse
import uvicorn

PORT = 9999
ROOT = os.path.dirname(os.path.abspath(__file__))

app = FastAPI()

INDEX_HTML_FALLBACK = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Magic-Vision-Spec 文档导航</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: #f8fafc; color: #1e293b; line-height: 1.6; min-height: 100vh; }
.container { max-width: 800px; margin: 0 auto; padding: 40px 24px; }
h1 { text-align: center; font-size: 1.75rem; margin-bottom: 32px; color: #1e293b; }
h1 small { display: block; font-size: 0.9rem; font-weight: 400; color: #64748b; margin-top: 6px; }
.link { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 16px 20px; text-decoration: none; color: #1e293b; font-size: 0.95rem; transition: background 0.15s; background: #fff; border: 1px solid #e2e8f0; border-radius: 8px; margin-bottom: 12px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
.link:hover { background: #dbeafe; color: #2563eb; }
.link .card-header { border: none; background: none; padding: 0; }
.link-icon { font-size: 1rem; flex-shrink: 0; }
.link-desc { font-size: 0.82rem; color: #94a3b8; white-space: nowrap; }
.footer { text-align: center; padding: 32px; color: #94a3b8; font-size: 0.8rem; }
</style>
</head>
<body>
<div class="container">
  <h1>Magic-Vision-Spec<small>全流程开发规约可视化文档</small></h1>
  <a class="link" href="1-tech-implementation-plan/overview.html"><span class="card-header">🏗️ 1. 技术方案设计</span></a>
  <a class="link" href="2-detailed-design/planning-canvas.html"><span class="card-header">📦 2. 模块详细设计</span></a>
  <a class="link" href="3-operation-flow/overview.html"><span class="card-header">🧪 3. 测试操作文档</span></a>
  <a class="link" href="4-database-schema/overview.html"><span class="card-header">🗄️ 4. 数据库表结构</span></a>
  <a class="link" href="5-api-spec/overview.html"><span class="card-header">🔌 5. API 接口文档</span></a>
  <a class="link" href="sp-0-req-analysis/overview.html"><span class="card-header">📋 sp-0. 需求分析</span></a>
</div>
<footer class="footer">Magic-Vision-Spec</footer>
</body>
</html>"""

# ─── 工具函数 ──────────────────────────────────────────────────

def kill_port(port):
    """强制关闭占用指定端口的进程"""
    try:
        result = subprocess.run(
            ["netstat", "-ano"], capture_output=True, text=True, creationflags=subprocess.CREATE_NO_WINDOW
        )
        for line in result.stdout.splitlines():
            if f":{port}" in line and "LISTENING" in line:
                parts = line.strip().split()
                pid = parts[-1]
                try:
                    subprocess.run(["taskkill", "/F", "/PID", pid], capture_output=True, creationflags=subprocess.CREATE_NO_WINDOW)
                    print(f"  已关闭占用端口 {port} 的进程 (PID {pid})")
                except:
                    pass
    except:
        pass


def render_all():
    """自动执行所有 build.py / render.py / _build_index.py"""
    print("=" * 50)
    print("正在自动渲染所有文档页面...")
    print("=" * 50)

    # 1-tech-implementation-plan 使用 build.py
    print("  >> 1-vision (技术方案)...", end=" ", flush=True)
    try:
        data_dir = os.path.join(ROOT, "1-tech-implementation-plan", "data")
        output_dir = os.path.join(ROOT, "1-tech-implementation-plan")
        # 合并所有数据文件
        merged = json.load(open(os.path.join(data_dir, "common.json"), encoding="utf-8"))
        merged.update(json.load(open(os.path.join(data_dir, "overview.json"), encoding="utf-8")))
        schemes = []
        for fp in sorted(os.listdir(data_dir)):
            if fp.startswith("T-") and fp.endswith(".json"):
                with open(os.path.join(data_dir, fp), encoding="utf-8") as f:
                    schemes.append(json.load(f))
        merged["schemes"] = schemes
        # 加载并执行 build.py 的构建函数
        old_path = list(sys.path)
        old_cwd = os.getcwd()
        try:
            sys.path.insert(0, os.path.join(ROOT, "1-tech-implementation-plan"))
            sys.path.insert(0, ROOT)
            os.chdir(os.path.join(ROOT, "1-tech-implementation-plan"))
            import importlib.util
            spec = importlib.util.spec_from_file_location(
                "build_mod", os.path.join(ROOT, "1-tech-implementation-plan", "build.py")
            )
            mod = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(mod)
            mod.build_tech_design(merged, output_dir)
            print("[OK]")
        finally:
            sys.path = old_path
            os.chdir(old_cwd)
    except Exception as e:
        print(f"[ERROR] {e}")

    render_scripts = [
        ("sp-0-vision (需求分析)", os.path.join(ROOT, "sp-0-req-analysis", "render.py")),
        ("2-vision (模块设计)", os.path.join(ROOT, "2-detailed-design", "render.py")),
        ("3-vision (操作文档)", os.path.join(ROOT, "3-operation-flow",  "render.py")),
        ("4-vision (数据库表)", os.path.join(ROOT, "4-database-schema", "render.py")),
        ("5-vision (API 接口)", os.path.join(ROOT, "5-api-spec",        "render.py")),
    ]

    for name, script_path in render_scripts:
        print(f"  >> {name}...", end=" ", flush=True)
        script_dir = os.path.dirname(script_path)
        old_cwd = os.getcwd()
        try:
            os.chdir(script_dir)
            if ROOT not in sys.path:
                sys.path.insert(0, ROOT)
            runpy.run_path(script_path, run_name="__main__")
            print("[OK]")
        except Exception as e:
            print(f"[ERROR] {e}")
        finally:
            os.chdir(old_cwd)

    print(f"  >> index.html...", end=" ", flush=True)
    try:
        runpy.run_path(os.path.join(ROOT, "_build_index.py"), run_name="__main__")
        print("[OK]")
    except Exception as e:
        print(f"[ERROR] {e}")

    print("=" * 50)
    print("所有文档渲染完成")
    print("=" * 50)


# ─── API 端点(优先于静态文件) ──────────────────────────────

@app.get("/get-state")
async def get_state():
    target = os.path.join(ROOT, "2-detailed-design", "planning-state.json")
    if os.path.exists(target):
        with open(target, "r", encoding="utf-8") as f:
            return Response(content=f.read(), media_type="application/json; charset=utf-8")
    return Response(status_code=404, content="Not Found")


@app.post("/save-state")
async def save_state(request: Request):
    try:
        data = await request.json()
        target = os.path.join(ROOT, "2-detailed-design", "planning-state.json")
        with open(target, "w", encoding="utf-8") as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        return {"ok": True}
    except Exception as e:
        return Response(status_code=500, content=json.dumps({"ok": False, "error": str(e)}))


@app.post("/rerender")
async def rerender():
    buf = io.StringIO()
    old_stdout = sys.stdout
    sys.stdout = buf
    try:
        render_all()
    finally:
        sys.stdout = old_stdout
    return PlainTextResponse(buf.getvalue() + "\n渲染完成!")


# ─── 静态文件服务 ──────────────────────────────────────────────

@app.get("/{full_path:path}")
async def serve_static(full_path: str):
    # 解析路径,防止目录遍历
    full_path = full_path.lstrip("/")
    if not full_path:
        full_path = "index.html"

    file_path = os.path.normpath(os.path.join(ROOT, full_path))
    # 安全检查:必须在 ROOT 目录下
    if not file_path.startswith(os.path.normpath(ROOT)):
        return Response(status_code=403)

    if os.path.isfile(file_path):
        media_type, _ = mimetypes.guess_type(file_path)
        if media_type is None:
            media_type = "application/octet-stream"
        with open(file_path, "rb") as f:
            return Response(content=f.read(), media_type=media_type)

    # 如果是目录,尝试 index.html
    if os.path.isdir(file_path):
        index_path = os.path.join(file_path, "index.html")
        if os.path.isfile(index_path):
            with open(index_path, "rb") as f:
                return Response(content=f.read(), media_type="text/html; charset=utf-8")

    # 根路径回退
    if full_path == "index.html":
        return HTMLResponse(content=INDEX_HTML_FALLBACK)

    return Response(status_code=404)


# ─── 启动 ──────────────────────────────────────────────────────

if __name__ == "__main__":
    render_all()
    kill_port(PORT)

    print(f"Magic-Vision 已启动: http://127.0.0.1:{PORT}")
    webbrowser.open(f"http://127.0.0.1:{PORT}")

    uvicorn.run(app, host="127.0.0.1", port=PORT, log_level="warning")