New web ui

This commit is contained in:
nyan404 committed 2026-08-17 02:31:18 +03:00
1 parent a360fd9c63
commit caee27c3ea
11 files changed
+248 -16

No files matched your search

+2 -2
View File
@@ -87,8 +87,8 @@ class CoachingSession:
raise ValueError("Некорректный статус самостоятельности")
statuses = (self.kitten_independence,) + tuple(independence for _, _, independence in self.extra_kittens)
nonself_count = sum(status == "несамостоятельно" for status in statuses)
if self.skill == "ЗУ" and len(set(statuses)) > 1:
raise ValueError("Для ЗУ все котята в одном отчёте должны иметь одинаковый статус")
if self.skill == "ЗУ" and any(s != "самостоятельно" for s in statuses):
raise ValueError("Для ЗУ все котята должны быть самостоятельными")
if self.skill == "ЛУ" and nonself_count > 1:
raise ValueError("Для ЛУ допускается только один несамостоятельный котёнок")
+6
View File
@@ -55,6 +55,12 @@ class ImageHostClient:
body = response.read()
content_type = response.headers.get_content_type() or "image/jpeg"
file_name = f"vk-{photo.get('owner_id', 'photo')}-{photo.get('id', 'upload')}.jpg"
return self.upload_bytes(body, file_name, content_type)
def upload_bytes(self, body: bytes, file_name: str, content_type: str = "image/jpeg") -> str | None:
"""Загружает произвольный файл на image-host и возвращает прямую ссылку."""
if not self.api_url or not body:
return None
initiate = self._request_json(
"/api/uploads/initiate",
{
+2 -2
View File
@@ -96,8 +96,8 @@ def _extra_kittens(value: str) -> tuple[tuple[str, int, str], ...]:
def _validate_independence(skill: str, primary: str, extras: tuple[tuple[str, int, str], ...] | list[tuple[str, int, str]]) -> None:
statuses = (primary,) + tuple(independence for _, _, independence in extras)
if skill == "ЗУ" and len(set(statuses)) > 1:
raise ValueError("Для ЗУ все котята в одном отчёте должны иметь одинаковый статус")
if skill == "ЗУ" and any(s != "самостоятельно" for s in statuses):
raise ValueError("Для ЗУ все котята должны быть самостоятельными")
if skill == "ЛУ" and sum(status == "несамостоятельно" for status in statuses) > 1:
raise ValueError("Для ЛУ допускается только один несамостоятельный котёнок")
+105 -3
View File
@@ -1,19 +1,25 @@
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:
@@ -23,6 +29,39 @@ def history_store() -> CalculationStore:
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"
@@ -44,6 +83,27 @@ class Handler(BaseHTTPRequestHandler):
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"):
@@ -67,6 +127,12 @@ class Handler(BaseHTTPRequestHandler):
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:
@@ -83,16 +149,52 @@ class Handler(BaseHTTPRequestHandler):
self.wfile.write(content)
def do_POST(self) -> None: # noqa: N802
if self.path not in ("/api/calculate", "/api/inspect-bulk", "/api/resolve-identity"):
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 self.path == "/api/inspect-bulk":
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: