Files
cwshed-clone/app/main.py
T

109 lines
4.2 KiB
Python

from __future__ import annotations
import json
import mimetypes
import os
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, unquote, urlparse
from .belki.api import ApiError, calculate_and_store, inspect_bulk_payload, resolve_identity_payload
from .belki.history import CalculationStore
ROOT = Path(__file__).resolve().parents[1]
WEB_ROOT = ROOT / "web"
_HISTORY_STORE: CalculationStore | None = None
def history_store() -> CalculationStore:
global _HISTORY_STORE
if _HISTORY_STORE is None:
_HISTORY_STORE = CalculationStore.from_environment()
return _HISTORY_STORE
class Handler(BaseHTTPRequestHandler):
server_version = "BelkiCalculator/0.1"
def _json(self, status: int, body: dict) -> None:
encoded = json.dumps(body, ensure_ascii=False).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(encoded)))
self.end_headers()
self.wfile.write(encoded)
def do_GET(self) -> None: # noqa: N802
path = urlparse(self.path).path
if path in ("/health", "/api/health"):
self._json(200, {"status": "ok"})
return
if path in ("/", "/calculator.html"):
self._file(WEB_ROOT / "calculator.html")
return
if path == "/admin":
self._file(WEB_ROOT / "admin.html")
return
if path == "/api/admin/calculations":
expected = os.getenv("BELKI_ADMIN_PASSWORD", "")
if not expected:
self._json(503, {"error": "Админская панель не настроена: задайте BELKI_ADMIN_PASSWORD"})
return
if self.headers.get("X-Admin-Password", "") != expected:
self._json(401, {"error": "Неверный пароль"})
return
query = parse_qs(urlparse(self.path).query)
sort_by = query.get("sort", ["kitten_id"])[0]
descending = query.get("direction", ["desc"])[0] != "asc"
self._json(200, {"items": history_store().list_calculations(sort_by=sort_by, descending=descending)})
return
requested = unquote(path).lstrip("/")
candidate = (WEB_ROOT / requested).resolve()
if candidate.is_file() and WEB_ROOT.resolve() in candidate.parents:
self._file(candidate)
return
self._json(404, {"error": "Не найдено"})
def _file(self, path: Path) -> None:
content = path.read_bytes()
self.send_response(200)
self.send_header("Content-Type", mimetypes.guess_type(path.name)[0] or "application/octet-stream")
self.send_header("Content-Length", str(len(content)))
self.end_headers()
self.wfile.write(content)
def do_POST(self) -> None: # noqa: N802
if self.path not in ("/api/calculate", "/api/inspect-bulk", "/api/resolve-identity"):
self._json(404, {"error": "Не найдено"})
return
try:
length = int(self.headers.get("Content-Length", "0"))
payload = json.loads(self.rfile.read(length))
if self.path == "/api/inspect-bulk":
self._json(200, inspect_bulk_payload(payload))
elif self.path == "/api/resolve-identity":
self._json(200, resolve_identity_payload(payload))
else:
self._json(200, calculate_and_store(payload, actor_id=None, source="web"))
except ApiError as exc:
self._json(400, {"error": str(exc)})
except (ValueError, json.JSONDecodeError) as exc:
self._json(400, {"error": str(exc)})
except Exception:
self._json(500, {"error": "Внутренняя ошибка калькулятора"})
def log_message(self, format: str, *args: object) -> None:
if os.getenv("BELKI_ACCESS_LOG", "0") == "1":
super().log_message(format, *args)
def serve() -> None:
host = os.getenv("BELKI_HOST", "0.0.0.0")
port = int(os.getenv("BELKI_PORT", "8080"))
ThreadingHTTPServer((host, port), Handler).serve_forever()
if __name__ == "__main__":
serve()