refactor(webgui): extract request and static helpers
This commit is contained in:
1 parent
e03dcaa183
commit
1ef7325ead
3 files changed
+108
-81
No files matched your search
+10
-81
@@ -34,6 +34,8 @@ from gui.web_gui_pkg import (
|
||||
_inc_map,
|
||||
_parse_countdown_seconds,
|
||||
)
|
||||
from gui.web_gui_pkg.request_parsing import read_json, send_json
|
||||
from gui.web_gui_pkg.static_handler import serve_static
|
||||
|
||||
BASE_DIR = path_config.PROJECT_ROOT
|
||||
CONFIG_PATH = path_config.get_config_path()
|
||||
@@ -903,91 +905,18 @@ RUNNER = ProcRunner()
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def _send_json(self, obj, status: int = 200) -> None:
|
||||
data = json.dumps(obj, ensure_ascii=False).encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
send_json(self, obj, status=status)
|
||||
|
||||
def _read_json(self) -> dict:
|
||||
n = int(self.headers.get("Content-Length") or 0)
|
||||
raw = self.rfile.read(n) if n > 0 else b"{}"
|
||||
try:
|
||||
return json.loads(raw.decode("utf-8"))
|
||||
except Exception:
|
||||
return {}
|
||||
return read_json(self)
|
||||
|
||||
def _serve_static(self, rel_path: str) -> None:
|
||||
rel_path = rel_path.lstrip("/")
|
||||
if not rel_path:
|
||||
rel_path = "index.html"
|
||||
safe = os.path.normpath(rel_path).replace("\\", "/")
|
||||
# 安全检查:防止路径遍历攻击
|
||||
if safe.startswith("../") or safe.startswith("..\\") or ".." in safe:
|
||||
self.send_error(HTTPStatus.FORBIDDEN)
|
||||
return
|
||||
full = os.path.join(WEBUI_DIR, safe)
|
||||
# 额外安全检查:确保文件在 WEBUI_DIR 目录内
|
||||
try:
|
||||
full_real = os.path.realpath(full)
|
||||
webui_real = os.path.realpath(WEBUI_DIR)
|
||||
if (
|
||||
not full_real.startswith(webui_real + os.sep)
|
||||
and full_real != webui_real
|
||||
):
|
||||
self.send_error(HTTPStatus.FORBIDDEN)
|
||||
return
|
||||
except Exception:
|
||||
self.send_error(HTTPStatus.FORBIDDEN)
|
||||
return
|
||||
if not os.path.isfile(full):
|
||||
self.send_error(HTTPStatus.NOT_FOUND)
|
||||
return
|
||||
|
||||
ext = os.path.splitext(full)[1].lower()
|
||||
ctype = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
".css": "text/css; charset=utf-8",
|
||||
".js": "application/javascript; charset=utf-8",
|
||||
".png": "image/png",
|
||||
".jpg": "image/jpeg",
|
||||
".jpeg": "image/jpeg",
|
||||
".svg": "image/svg+xml; charset=utf-8",
|
||||
}.get(ext, "application/octet-stream")
|
||||
|
||||
try:
|
||||
with open(full, "rb") as f:
|
||||
data = f.read()
|
||||
# 对于静态资源,使用适当的缓存策略
|
||||
cache_control = (
|
||||
"no-store" if ext in (".html", ".js") else "public, max-age=3600"
|
||||
)
|
||||
self.send_response(HTTPStatus.OK)
|
||||
self.send_header("Content-Type", ctype)
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.send_header("Cache-Control", cache_control)
|
||||
# 添加 ETag 支持(简单实现:基于文件大小和修改时间)
|
||||
try:
|
||||
stat = os.stat(full)
|
||||
etag = f'"{stat.st_size}-{int(stat.st_mtime)}"'
|
||||
self.send_header("ETag", etag)
|
||||
# 检查 If-None-Match 头,支持 304 Not Modified
|
||||
if_none_match = self.headers.get("If-None-Match", "")
|
||||
if if_none_match == etag:
|
||||
self.send_response(HTTPStatus.NOT_MODIFIED)
|
||||
self.end_headers()
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
except FileNotFoundError:
|
||||
self.send_error(HTTPStatus.NOT_FOUND)
|
||||
except Exception as e:
|
||||
_wg_log(f"[WEB_GUI] Error serving static file {rel_path}: {e}", level="ERROR")
|
||||
self.send_error(HTTPStatus.INTERNAL_SERVER_ERROR)
|
||||
serve_static(
|
||||
self,
|
||||
webui_dir=WEBUI_DIR,
|
||||
rel_path=rel_path,
|
||||
log_error=lambda msg: _wg_log(msg, level="ERROR"),
|
||||
)
|
||||
|
||||
def do_GET(self):
|
||||
u = urlparse(self.path)
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import json
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
|
||||
|
||||
def send_json(handler: BaseHTTPRequestHandler, obj, status: int = 200) -> None:
|
||||
data = json.dumps(obj, ensure_ascii=False).encode("utf-8")
|
||||
handler.send_response(status)
|
||||
handler.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
handler.send_header("Cache-Control", "no-store")
|
||||
handler.send_header("Content-Length", str(len(data)))
|
||||
handler.end_headers()
|
||||
handler.wfile.write(data)
|
||||
|
||||
|
||||
def read_json(handler: BaseHTTPRequestHandler) -> dict:
|
||||
n = int(handler.headers.get("Content-Length") or 0)
|
||||
raw = handler.rfile.read(n) if n > 0 else b"{}"
|
||||
try:
|
||||
value = json.loads(raw.decode("utf-8"))
|
||||
except Exception:
|
||||
return {}
|
||||
return value if isinstance(value, dict) else {}
|
||||
@@ -0,0 +1,76 @@
|
||||
import os
|
||||
from http import HTTPStatus
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
from typing import Callable
|
||||
|
||||
|
||||
def serve_static(
|
||||
handler: BaseHTTPRequestHandler,
|
||||
*,
|
||||
webui_dir: str,
|
||||
rel_path: str,
|
||||
log_error: Callable[[str], None],
|
||||
) -> None:
|
||||
rel_path = rel_path.lstrip("/")
|
||||
if not rel_path:
|
||||
rel_path = "index.html"
|
||||
safe = os.path.normpath(rel_path).replace("\\", "/")
|
||||
# 安全检查:防止路径遍历攻击
|
||||
if safe.startswith("../") or safe.startswith("..\\") or ".." in safe:
|
||||
handler.send_error(HTTPStatus.FORBIDDEN)
|
||||
return
|
||||
full = os.path.join(webui_dir, safe)
|
||||
# 额外安全检查:确保文件在 WEBUI_DIR 目录内
|
||||
try:
|
||||
full_real = os.path.realpath(full)
|
||||
webui_real = os.path.realpath(webui_dir)
|
||||
if not full_real.startswith(webui_real + os.sep) and full_real != webui_real:
|
||||
handler.send_error(HTTPStatus.FORBIDDEN)
|
||||
return
|
||||
except Exception:
|
||||
handler.send_error(HTTPStatus.FORBIDDEN)
|
||||
return
|
||||
if not os.path.isfile(full):
|
||||
handler.send_error(HTTPStatus.NOT_FOUND)
|
||||
return
|
||||
|
||||
ext = os.path.splitext(full)[1].lower()
|
||||
ctype = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
".css": "text/css; charset=utf-8",
|
||||
".js": "application/javascript; charset=utf-8",
|
||||
".png": "image/png",
|
||||
".jpg": "image/jpeg",
|
||||
".jpeg": "image/jpeg",
|
||||
".svg": "image/svg+xml; charset=utf-8",
|
||||
}.get(ext, "application/octet-stream")
|
||||
|
||||
try:
|
||||
with open(full, "rb") as f:
|
||||
data = f.read()
|
||||
# 对于静态资源,使用适当的缓存策略
|
||||
cache_control = "no-store" if ext in (".html", ".js") else "public, max-age=3600"
|
||||
handler.send_response(HTTPStatus.OK)
|
||||
handler.send_header("Content-Type", ctype)
|
||||
handler.send_header("Content-Length", str(len(data)))
|
||||
handler.send_header("Cache-Control", cache_control)
|
||||
# 添加 ETag 支持(简单实现:基于文件大小和修改时间)
|
||||
try:
|
||||
stat = os.stat(full)
|
||||
etag = f'"{stat.st_size}-{int(stat.st_mtime)}"'
|
||||
handler.send_header("ETag", etag)
|
||||
# 检查 If-None-Match 头,支持 304 Not Modified
|
||||
if_none_match = handler.headers.get("If-None-Match", "")
|
||||
if if_none_match == etag:
|
||||
handler.send_response(HTTPStatus.NOT_MODIFIED)
|
||||
handler.end_headers()
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
handler.end_headers()
|
||||
handler.wfile.write(data)
|
||||
except FileNotFoundError:
|
||||
handler.send_error(HTTPStatus.NOT_FOUND)
|
||||
except Exception as e:
|
||||
log_error(f"[WEB_GUI] Error serving static file {rel_path}: {e}")
|
||||
handler.send_error(HTTPStatus.INTERNAL_SERVER_ERROR)
|
||||
Reference in new issue
Block a user