"""
@router /api/content
@description 内容管理路由模块
@author wjh
@created at 2025-11-25
"""
from fastapi import APIRouter, Query
from fastapi.responses import JSONResponse
import os, re, yaml, hashlib, html
from datetime import datetime, timezone
router = APIRouter()
def _backend_root():
return os.path.dirname(os.path.dirname(__file__))
def _content_dir():
return os.path.join(_backend_root(), "content")
def _find_file(slug: str, lang: str):
p = os.path.join(_content_dir(), f"{slug}.{lang}.md")
if os.path.isfile(p):
return p, lang
for name in os.listdir(_content_dir()) if os.path.isdir(_content_dir()) else []:
if name.startswith(f"{slug}.") and name.endswith(".md"):
return os.path.join(_content_dir(), name), name.split(".")[-2]
return None, lang
def _parse_front_matter(text: str):
if text.startswith("---"):
end = text.find("\n---", 3)
if end != -1:
fm = text[3:end+1].strip()
rest = text[end+4:].lstrip()
try:
meta = yaml.safe_load(fm) or {}
except Exception:
meta = {}
return meta, rest
return {}, text
def _inline(s: str):
s = html.escape(s)
s = re.sub(r"\*\*(.+?)\*\*", r"\1", s)
s = re.sub(r"\*(.+?)\*", r"\1", s)
s = re.sub(r"`([^`]+)`", r"\1", s)
s = re.sub(r"\[([^\]]+)\]\((https?://[^\s)]+)\)", r"\1", s)
return s
def _md_to_html(md: str):
lines = md.splitlines()
out = []
i = 0
in_ul = False
in_code = False
code_buf = []
while i < len(lines):
line = lines[i]
if line.strip().startswith("```"):
if in_code:
out.append("
" + html.escape("\n".join(code_buf)) + "")
code_buf = []
in_code = False
else:
in_code = True
i += 1
continue
if in_code:
code_buf.append(line)
i += 1
continue
if re.match(r"^#{1,6}\s", line):
m = re.match(r"^(#{1,6})\s+(.*)$", line)
level = len(m.group(1))
out.append(f"" + _inline(line) + "
") i += 1 if in_ul: out.append("") return "\n".join(out) @router.get("/{slug}") async def get_content(slug: str, lang: str = Query("zh-CN")): path, actual_lang = _find_file(slug, lang) if not path: data = { "slug": slug, "locale": lang, "title": "", "body_html": "暂无内容
", "version": 0, "updated_at": datetime.now(timezone.utc).isoformat() } return JSONResponse({"success": True, "data": data}) with open(path, "r", encoding="utf-8") as f: text = f.read() meta, body = _parse_front_matter(text) title = str(meta.get("title") or "") if not title: for l in body.splitlines(): if l.startswith("# "): title = l[2:].strip() break html_body = _md_to_html(body) version = int(meta.get("version") or int(os.path.getmtime(path))) updated_at = datetime.fromtimestamp(os.path.getmtime(path), tz=timezone.utc).isoformat() etag = hashlib.sha256((slug + actual_lang + html_body).encode("utf-8")).hexdigest() data = { "slug": slug, "locale": actual_lang, "title": title, "body_html": html_body, "version": version, "updated_at": updated_at } resp = JSONResponse({"success": True, "data": data}) resp.headers["ETag"] = f'W/"{etag}"' return resp