240 lines
11 KiB
Python
240 lines
11 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
import base64
|
|
import mimetypes
|
|
import os
|
|
import secrets
|
|
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
|
|
from .belki.identity import IdentityDirectory
|
|
from .belki.image_host import ImageHostClient
|
|
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
WEB_ROOT = ROOT / "web"
|
|
_HISTORY_STORE: CalculationStore | None = None
|
|
_IDENTITY_DIR: IdentityDirectory | None = None
|
|
_WEB_SESSIONS: set[str] = set()
|
|
|
|
|
|
def history_store() -> CalculationStore:
|
|
global _HISTORY_STORE
|
|
if _HISTORY_STORE is None:
|
|
_HISTORY_STORE = CalculationStore.from_environment()
|
|
return _HISTORY_STORE
|
|
|
|
|
|
def identity_dir() -> IdentityDirectory:
|
|
global _IDENTITY_DIR
|
|
if _IDENTITY_DIR is None:
|
|
_IDENTITY_DIR = IdentityDirectory.from_environment(persistent=True)
|
|
return _IDENTITY_DIR
|
|
|
|
|
|
_WEB_PROFILE_KEY = "web_user"
|
|
|
|
|
|
def save_profile(payload):
|
|
name = str(payload.get("name", "")).strip()
|
|
raw_id = payload.get("character_id")
|
|
try:
|
|
character_id = int(raw_id) if raw_id not in (None, "") else None
|
|
except (TypeError, ValueError):
|
|
raise ApiError("ID персонажа должно быть числом")
|
|
if not name or character_id is None:
|
|
raise ApiError("Нужно указать и имя, и ID персонажа")
|
|
identity = identity_dir().remember(name=name, character_id=character_id)
|
|
actor_id = int(_WEB_PROFILE_KEY.encode().hex(), 16) if isinstance(_WEB_PROFILE_KEY, str) else 0
|
|
identity_dir().remember_profile(actor_id=actor_id, name=name, character_id=character_id)
|
|
return {"status": "saved", "name": identity.name, "character_id": identity.character_id}
|
|
|
|
|
|
def get_profile():
|
|
actor_id = int(_WEB_PROFILE_KEY.encode().hex(), 16) if isinstance(_WEB_PROFILE_KEY, str) else 0
|
|
profile = identity_dir().profile(actor_id=actor_id)
|
|
if profile:
|
|
return {"status": "found", "name": profile.name, "character_id": profile.character_id}
|
|
return {"status": "not_found"}
|
|
|
|
|
|
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 _admin_authorized(self) -> bool:
|
|
expected = os.getenv("BELKI_ADMIN_PASSWORD", "")
|
|
if not expected:
|
|
self._json(503, {"error": "Админская панель не настроена: задайте BELKI_ADMIN_PASSWORD"})
|
|
return False
|
|
if self.headers.get("X-Admin-Password", "") != expected:
|
|
self._json(401, {"error": "Неверный пароль"})
|
|
return False
|
|
return True
|
|
|
|
def _web_authorized(self) -> bool:
|
|
expected = os.getenv("BELKI_WEB_PASSWORD", "")
|
|
if not expected:
|
|
self._json(503, {"error": "Веб-доступ не настроен: задайте BELKI_WEB_PASSWORD"})
|
|
return False
|
|
cookies = self.headers.get("Cookie", "")
|
|
token = next((part.strip().split("=", 1)[1] for part in cookies.split(";") if part.strip().startswith("belki_session=")), "")
|
|
if token not in _WEB_SESSIONS:
|
|
self._json(401, {"error": "Требуется авторизация"})
|
|
return False
|
|
return True
|
|
|
|
def _json_with_cookie(self, status: int, body: dict, cookie: str) -> 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("Set-Cookie", cookie)
|
|
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 ("/", "/belki", "/belki/", "/calculator.html"):
|
|
self._file(WEB_ROOT / "calculator.html")
|
|
return
|
|
if path == "/admin":
|
|
self._file(WEB_ROOT / "admin.html")
|
|
return
|
|
if path == "/api/admin/calculations":
|
|
if not self._admin_authorized():
|
|
return
|
|
query = parse_qs(urlparse(self.path).query)
|
|
sort_by = query.get("sort", ["escort_id"])[0]
|
|
descending = query.get("direction", ["desc"])[0] != "asc"
|
|
try:
|
|
limit = int(query.get("limit", ["100"])[0])
|
|
except ValueError:
|
|
limit = 100
|
|
self._json(200, {"items": history_store().list_calculations(sort_by=sort_by, descending=descending, limit=limit)})
|
|
return
|
|
if path == "/api/web/session":
|
|
expected = os.getenv("BELKI_WEB_PASSWORD", "")
|
|
cookies = self.headers.get("Cookie", "")
|
|
token = next((part.strip().split("=", 1)[1] for part in cookies.split(";") if part.strip().startswith("belki_session=")), "")
|
|
self._json(200, {"authenticated": bool(expected and token in _WEB_SESSIONS)})
|
|
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/web/auth", "/api/web/logout", "/api/web/upload", "/api/calculate", "/api/inspect-bulk", "/api/resolve-identity",
|
|
"/api/save-profile", "/api/get-profile"):
|
|
self._json(404, {"error": "Не найдено"})
|
|
return
|
|
try:
|
|
length = int(self.headers.get("Content-Length", "0"))
|
|
payload = json.loads(self.rfile.read(length)) if length else {}
|
|
if self.path == "/api/web/auth":
|
|
expected = os.getenv("BELKI_WEB_PASSWORD", "")
|
|
if not expected or not secrets.compare_digest(str(payload.get("password", "")), expected):
|
|
self._json(401, {"error": "Неверный пароль"})
|
|
return
|
|
token = secrets.token_urlsafe(32)
|
|
_WEB_SESSIONS.add(token)
|
|
self._json_with_cookie(200, {"authenticated": True}, f"belki_session={token}; Path=/; HttpOnly; SameSite=Lax")
|
|
elif self.path == "/api/web/logout":
|
|
cookies = self.headers.get("Cookie", "")
|
|
token = next((part.strip().split("=", 1)[1] for part in cookies.split(";") if part.strip().startswith("belki_session=")), "")
|
|
_WEB_SESSIONS.discard(token)
|
|
self._json_with_cookie(200, {"authenticated": False}, "belki_session=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax")
|
|
elif not self._web_authorized():
|
|
return
|
|
elif self.path == "/api/web/upload":
|
|
raw = str(payload.get("data", ""))
|
|
if "," in raw:
|
|
raw = raw.split(",", 1)[1]
|
|
try:
|
|
body = base64.b64decode(raw, validate=True)
|
|
except (ValueError, TypeError) as exc:
|
|
raise ApiError("Не удалось прочитать изображение") from exc
|
|
if len(body) > 15 * 1024 * 1024:
|
|
raise ApiError("Файл слишком большой (максимум 15 МБ)")
|
|
url = ImageHostClient(api_url=os.getenv("BELKI_IMAGE_HOST_API_URL", "https://img.nyan404.ru")).upload_bytes(
|
|
body, str(payload.get("name", "screenshot.jpg")), str(payload.get("type", "image/jpeg"))
|
|
)
|
|
if not url:
|
|
raise ApiError("Хранилище изображений не настроено")
|
|
self._json(200, {"url": url, "name": payload.get("name", "screenshot.jpg")})
|
|
elif 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))
|
|
elif self.path == "/api/save-profile":
|
|
self._json(200, save_profile(payload))
|
|
elif self.path == "/api/get-profile":
|
|
self._json(200, get_profile())
|
|
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 do_DELETE(self) -> None: # noqa: N802
|
|
parsed = urlparse(self.path)
|
|
prefix = "/api/admin/calculations/"
|
|
if not parsed.path.startswith(prefix):
|
|
self._json(404, {"error": "Не найдено"})
|
|
return
|
|
if not self._admin_authorized():
|
|
return
|
|
raw_id = parsed.path[len(prefix):]
|
|
try:
|
|
calculation_id = int(raw_id)
|
|
deleted = history_store().delete_calculation(calculation_id)
|
|
except ValueError as exc:
|
|
self._json(400, {"error": str(exc)})
|
|
return
|
|
if not deleted:
|
|
self._json(404, {"error": "Запись не найдена"})
|
|
return
|
|
self._json(200, {"deleted": calculation_id})
|
|
|
|
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()
|