73 lines
3.3 KiB
Python
73 lines
3.3 KiB
Python
"""把 ``index.html`` 发出去之前,先把公开配置注进 ``</head>`` 之前。
|
||
|
||
前端认 ``window.__APP_CONFIG__``(``frontend/src/stores/app.ts:initFromInjectedConfig``):
|
||
接得住就没有"先转一圈问 ``/settings/public``、再决定画哪一屏"那一次往返——登录页要问它
|
||
才知道该画免登那一屏还是账号密码表单,免登落地失败那一屏也要画「回到统一门户」那颗按钮。
|
||
开发模式下 vite 的 ``inject-public-settings`` 插件做同一件事,生产这一份就补在这里
|
||
(以前只有那句"与生产一致"的注释,没有对应的实现)。
|
||
|
||
三条口径:
|
||
|
||
* 配置直接取 :func:`app.public_config.payload`,与接口共用一份,不另写;
|
||
* 站点名这些是管理员自己填的,尖括号一律转义——``</script>`` 能改写脚本的边界;
|
||
* 注入只是"锦上添花":库还没起来、配置问不出、文件读不到,一律回 ``None``,
|
||
让调用方按原样把文件发出去,页面宁可多问一次也不该打不开。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import hashlib
|
||
import json
|
||
import logging
|
||
from pathlib import Path
|
||
|
||
from . import public_config
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
#: 前端那一口约定的变量名,也是"这一份已经注过了"的记号
|
||
MARKER = "window.__APP_CONFIG__"
|
||
|
||
#: 只留最近这一版:index.html 一次部署换一次,留多了是白占内存
|
||
_cache: dict[str, str] = {}
|
||
|
||
|
||
def _script(payload: dict) -> str:
|
||
"""配置 -> 一段脚本。尖括号与行分隔符转义掉,别让管理员填的站点名改写脚本边界。"""
|
||
raw = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
|
||
raw = raw.replace("<", "\\u003c").replace(">", "\\u003e")
|
||
# 这两位在 JSON 里是合法字符,在 JavaScript 的字符串字面量里却是行终止符
|
||
raw = raw.replace(chr(0x2028), "\\u2028").replace(chr(0x2029), "\\u2029")
|
||
return f"<script>{MARKER}={raw};</script>"
|
||
|
||
|
||
def shell_html(path: Path) -> str | None:
|
||
"""注入好的 ``index.html`` 全文;任何一步问不出来就回 ``None``,调用方原样发文件。"""
|
||
try:
|
||
stat = path.stat()
|
||
payload = public_config.payload()
|
||
except Exception: # noqa: BLE001 - 库还没起来是常事,不该因此拦着发页面
|
||
logger.warning("首屏配置取不到,index.html 按原样发出", exc_info=True)
|
||
return None
|
||
# 缓存键 = 文件指纹 + 配置指纹:换版本、改站点名、动免登开关,都会当场绕开这一份
|
||
digest = hashlib.sha256(
|
||
json.dumps(payload, sort_keys=True, ensure_ascii=False, default=str).encode("utf-8")
|
||
).hexdigest()
|
||
key = f"{stat.st_mtime_ns}:{stat.st_size}:{digest}"
|
||
if _cache.get("key") == key and _cache.get("html"):
|
||
return _cache["html"]
|
||
try:
|
||
html = path.read_text(encoding="utf-8")
|
||
except OSError:
|
||
logger.warning("读不到 %s,交给调用方按原样发", path, exc_info=True)
|
||
return None
|
||
if "</head>" not in html:
|
||
return None
|
||
# 已经注过一份(比如有人把注好的产物又拷了回来)就别叠第二份
|
||
if MARKER in html:
|
||
return html
|
||
injected = html.replace("</head>", f"{_script(payload)}\n </head>", 1)
|
||
_cache.clear()
|
||
_cache.update({"key": key, "html": injected})
|
||
return injected
|