from __future__ import annotations import json import base64 import hashlib import mimetypes import os import re import secrets import threading import time from datetime import datetime 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, calculate_payload, inspect_bulk_payload, rename_identity_payload, resolve_identity_payload from .belki.history import CalculationStore from .belki.applications import ApplicationError, ApplicationStore, validate_application from .belki.admin_filters import WEB_TIMEZONE, matches_period, period_bounds from .belki.google_sheets_export import GoogleSheetsExportService from .belki.identity import IdentityDirectory from .belki.image_host import ImageHostError, ImageStoreClient from .belki.xlsx_export import build_xlsx from .sudoku import SudokuError, SudokuStore from .belki.vk_scheduler import VkConversationStore ROOT = Path(__file__).resolve().parents[1] WEB_ROOT = ROOT / "web" _HISTORY_STORE: CalculationStore | None = None _IDENTITY_DIR: IdentityDirectory | None = None _APPLICATION_STORE: ApplicationStore | None = None _SUDOKU_STORE: SudokuStore | None = None _VK_CONVERSATION_STORE: VkConversationStore | None = None _ADMIN_SESSIONS: dict[str, float] = {} _ADMIN_SESSIONS_LOCK = threading.Lock() _ISSUED_WEB_UPLOAD_URLS: dict[str, float] = {} _ISSUED_WEB_UPLOADS_LOCK = threading.Lock() _ADMIN_AUTH_ATTEMPTS: dict[str, list[float]] = {} _ADMIN_AUTH_LOCK = threading.Lock() MAX_JSON_BODY_BYTES = 20 * 1024 * 1024 MAX_UPLOAD_BYTES = 15 * 1024 * 1024 REQUEST_READ_TIMEOUT_SECONDS = 15 MAX_CONCURRENT_REQUESTS = 32 MAX_CONCURRENT_ADMIN_UPDATES = 8 ADMIN_AUTH_WINDOW_SECONDS = 15 * 60 MAX_ADMIN_AUTH_ATTEMPTS = 5 _ADMIN_UPDATE_SLOTS = threading.BoundedSemaphore(MAX_CONCURRENT_ADMIN_UPDATES) WEB_UPLOAD_URL_TTL_SECONDS = 30 * 60 MAX_ISSUED_WEB_UPLOAD_URLS = 1_000 IMAGE_OBJECT_NAME = re.compile(r"^[a-f0-9]{32}\.(?:png|jpg|webp)$") ADMIN_SESSION_TTL_SECONDS = 12 * 60 * 60 MAX_ADMIN_SESSIONS = 100 def detect_raster_image_type(body: bytes) -> str | None: """Returns the MIME type for supported raster image signatures only.""" if body.startswith(b"\x89PNG\r\n\x1a\n"): return "image/png" if body.startswith(b"\xff\xd8\xff"): return "image/jpeg" if len(body) >= 12 and body.startswith(b"RIFF") and body[8:12] == b"WEBP": return "image/webp" return None def safe_upload_name(value: object, content_type: str) -> str: """Drops path-like input and supplies a stable name for the image host.""" name = str(value or "").replace("\\", "/").split("/")[-1].replace("\x00", "").strip() if not name: suffix = {"image/png": "png", "image/jpeg": "jpg", "image/webp": "webp"}[content_type] return f"screenshot.{suffix}" return name[:255] def remember_issued_web_upload(url: str, *, now: float | None = None) -> None: """Register one upload URL for the short upload-and-submit web flow.""" timestamp = time.monotonic() if now is None else now with _ISSUED_WEB_UPLOADS_LOCK: expired = [item for item, expiry in _ISSUED_WEB_UPLOAD_URLS.items() if expiry <= timestamp] for item in expired: del _ISSUED_WEB_UPLOAD_URLS[item] if url not in _ISSUED_WEB_UPLOAD_URLS and len(_ISSUED_WEB_UPLOAD_URLS) >= MAX_ISSUED_WEB_UPLOAD_URLS: oldest = min(_ISSUED_WEB_UPLOAD_URLS, key=_ISSUED_WEB_UPLOAD_URLS.__getitem__) del _ISSUED_WEB_UPLOAD_URLS[oldest] _ISSUED_WEB_UPLOAD_URLS[url] = timestamp + WEB_UPLOAD_URL_TTL_SECONDS def validate_web_attachments(value: object, *, now: float | None = None) -> list[dict]: """Accept only unexpired attachments issued by this process to the web form.""" if not isinstance(value, list) or len(value) > 10: raise ApiError("Можно приложить от 0 до 10 изображений") timestamp = time.monotonic() if now is None else now attachments: list[dict] = [] with _ISSUED_WEB_UPLOADS_LOCK: expired = [item for item, expiry in _ISSUED_WEB_UPLOAD_URLS.items() if expiry <= timestamp] for item in expired: del _ISSUED_WEB_UPLOAD_URLS[item] for item in value: if not isinstance(item, dict) or not isinstance(item.get("url"), str): raise ApiError("Некорректное вложение") if item["url"] not in _ISSUED_WEB_UPLOAD_URLS: raise ApiError("Вложение должно быть загружено через форму Белок") attachments.append(item) return attachments def validate_web_report_attachments(payload: dict) -> list[dict]: """Apply the web rule: screenshots are required only for an inspection.""" attachments = validate_web_attachments(payload.get("attachments", [])) if payload.get("mode") == "inspection" and not attachments: raise ApiError("Для осмотра приложите хотя бы один скриншот") if payload.get("mode") != "inspection" and attachments: raise ApiError("Скриншоты прикладываются только к осмотрам") return attachments def allow_admin_auth_attempt(client_ip: str, *, now: float | None = None) -> bool: """Apply a bounded per-source budget to the password-only admin login.""" timestamp = time.monotonic() if now is None else now with _ADMIN_AUTH_LOCK: attempts = [item for item in _ADMIN_AUTH_ATTEMPTS.get(client_ip, []) if timestamp - item < ADMIN_AUTH_WINDOW_SECONDS] if len(attempts) >= MAX_ADMIN_AUTH_ATTEMPTS: _ADMIN_AUTH_ATTEMPTS[client_ip] = attempts return False attempts.append(timestamp) _ADMIN_AUTH_ATTEMPTS[client_ip] = attempts return True def clear_admin_auth_attempts(client_ip: str) -> None: """Удаляет временные неудачные попытки входа администратора для IP.""" with _ADMIN_AUTH_LOCK: _ADMIN_AUTH_ATTEMPTS.pop(client_ip, None) def remember_admin_session(token: str, *, now: float | None = None) -> None: """Keep a bounded, expiring set of opaque admin session tokens.""" timestamp = time.monotonic() if now is None else now with _ADMIN_SESSIONS_LOCK: expired = [item for item, expiry in _ADMIN_SESSIONS.items() if expiry <= timestamp] for item in expired: del _ADMIN_SESSIONS[item] if token not in _ADMIN_SESSIONS and len(_ADMIN_SESSIONS) >= MAX_ADMIN_SESSIONS: oldest = min(_ADMIN_SESSIONS, key=_ADMIN_SESSIONS.__getitem__) del _ADMIN_SESSIONS[oldest] _ADMIN_SESSIONS[token] = timestamp + ADMIN_SESSION_TTL_SECONDS def admin_session_authorized(token: str, *, now: float | None = None) -> bool: """Проверяет токен сессии и удаляет его после истечения срока действия.""" timestamp = time.monotonic() if now is None else now with _ADMIN_SESSIONS_LOCK: expiry = _ADMIN_SESSIONS.get(token) if expiry is None: return False if expiry <= timestamp: del _ADMIN_SESSIONS[token] return False return True def forget_admin_session(token: str) -> None: """Удаляет токен административной сессии из памяти процесса.""" with _ADMIN_SESSIONS_LOCK: _ADMIN_SESSIONS.pop(token, None) def acquire_admin_update_slot() -> bool: """Reserve a bounded worker slot for a long-lived admin WebSocket.""" return _ADMIN_UPDATE_SLOTS.acquire(blocking=False) def release_admin_update_slot() -> None: """Освобождает глобальный слот фонового обновления заявок.""" _ADMIN_UPDATE_SLOTS.release() def history_store() -> CalculationStore: """Лениво создаёт singleton хранилища истории расчётов.""" global _HISTORY_STORE if _HISTORY_STORE is None: _HISTORY_STORE = CalculationStore.from_environment() return _HISTORY_STORE def sudoku_store() -> SudokuStore: """Return the lazily initialized store for resumable Sudoku games.""" global _SUDOKU_STORE if _SUDOKU_STORE is None: _SUDOKU_STORE = SudokuStore.from_environment() return _SUDOKU_STORE def vk_conversation_store() -> VkConversationStore: global _VK_CONVERSATION_STORE if _VK_CONVERSATION_STORE is None: _VK_CONVERSATION_STORE = VkConversationStore.from_environment() return _VK_CONVERSATION_STORE def public_sudoku_game(game: dict) -> dict: """Keep the answer key on the server while returning a playable game.""" return {key: value for key, value in game.items() if key != "solution"} def identity_dir() -> IdentityDirectory: """Лениво создаёт справочник персонажей из окружения.""" global _IDENTITY_DIR if _IDENTITY_DIR is None: _IDENTITY_DIR = IdentityDirectory.from_environment(persistent=True) return _IDENTITY_DIR def application_store() -> ApplicationStore: """Лениво создаёт singleton хранилища заявок.""" global _APPLICATION_STORE if _APPLICATION_STORE is None: _APPLICATION_STORE = ApplicationStore.from_environment() return _APPLICATION_STORE def sync_application_exports() -> int: """Отправляет накопленные outbox-события в настроенный внешний экспорт.""" """No-op until the explicitly disabled Google export is configured.""" return GoogleSheetsExportService(application_store()).sync_pending() def report_matches_filters(record: dict, query: dict[str, list[str]]) -> bool: """Match the report-only filters that are also represented in the admin URL.""" payload = record.get("input", {}) category = query.get("category", ["all"])[0] actual = "inspection" if payload.get("mode") == "inspection" else "training" if payload.get("mode") == "training" else "lu" if payload.get("skill") == "ЛУ" else "zu" if payload.get("skill") == "ЗУ" else "other" if category != "all" and category != actual: return False cat = query.get("cat", [""])[0] if cat and str(payload.get("escort_id", payload.get("character_id", ""))) != cat: return False kitten = query.get("kitten", [""])[0] if kitten: ids = [payload.get("kitten_id")] ids.extend(item.get("id") if isinstance(item, dict) else item[1] if isinstance(item, (list, tuple)) and len(item) > 1 else None for item in payload.get("extra_kittens", [])) if kitten not in {str(value) for value in ids if value is not None}: return False return True class BelkiHTTPServer(ThreadingHTTPServer): """Threaded server with bounded slow-client and worker resource use.""" def __init__(self, server_address: tuple[str, int], handler_class: type[BaseHTTPRequestHandler]) -> None: """Настраивает многопоточный HTTP-сервер и лимиты обработки.""" super().__init__(server_address, handler_class) self._request_slots = threading.BoundedSemaphore(MAX_CONCURRENT_REQUESTS) def get_request(self): # type: ignore[no-untyped-def] """Получает клиентский сокет и применяет короткий таймаут чтения.""" request, client_address = super().get_request() request.settimeout(REQUEST_READ_TIMEOUT_SECONDS) return request, client_address def process_request(self, request, client_address) -> None: # type: ignore[no-untyped-def] """Передаёт соединение в отдельный поток обработки.""" if not self._request_slots.acquire(blocking=False): request.close() return super().process_request(request, client_address) def process_request_thread(self, request, client_address) -> None: # type: ignore[no-untyped-def] """Обрабатывает соединение и закрывает сокет после завершения.""" try: super().process_request_thread(request, client_address) finally: self._request_slots.release() class Handler(BaseHTTPRequestHandler): server_version = "BelkiCalculator/0.1" protocol_version = "HTTP/1.1" def _json(self, status: int, body: dict) -> None: """Отправляет JSON-ответ с указанным HTTP-статусом.""" 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 _xlsx(self, filename: str, content: bytes) -> None: """Send an authenticated administrative spreadsheet attachment.""" self.send_response(200) self.send_header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") self.send_header("Content-Disposition", f'attachment; filename="{filename}"') self.send_header("Content-Length", str(len(content))) self.end_headers() self.wfile.write(content) def _admin_period(self, query: dict[str, list[str]]): """Parse the common period query and return an API error for invalid dates.""" try: return period_bounds(query.get("period", ["all"])[0], query.get("date_from", [None])[0], query.get("date_to", [None])[0]) except ValueError as exc: self._json(400, {"error": str(exc)}) return None def _session_token(self, name: str) -> str: """Извлекает именованный токен из cookie текущего запроса.""" cookies = self.headers.get("Cookie", "") return next((part.strip().split("=", 1)[1] for part in cookies.split(";") if part.strip().startswith(f"{name}=")), "") def _admin_session_authorized(self) -> bool: """Проверяет авторизацию административной сессии запроса.""" return admin_session_authorized(self._session_token("belki_admin_session")) def _admin_authorized(self) -> bool: """Проверяет административную cookie и срок её действия.""" expected = os.getenv("BELKI_ADMIN_PASSWORD", "") if not expected: self._json(503, {"error": "Админская панель не настроена: задайте BELKI_ADMIN_PASSWORD"}) return False if not self._admin_session_authorized() and not secrets.compare_digest(self.headers.get("X-Admin-Password", ""), expected): self._json(401, {"error": "Неверный пароль"}) return False return True def _json_with_cookie(self, status: int, body: dict, cookie: str) -> None: """Отправляет JSON-ответ и добавляет заголовок Set-Cookie.""" 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 _admin_cookie(self, token: str) -> str: """Формирует безопасный cookie заголовок для административного токена.""" secure = "; Secure" if self.headers.get("X-Forwarded-Proto", "") == "https" else "" return f"belki_admin_session={token}; Path=/; Max-Age={ADMIN_SESSION_TTL_SECONDS}; HttpOnly; SameSite=Lax{secure}" def _serve_admin_updates(self) -> None: """Возвращает административную страницу после проверки доступа.""" if not self._admin_session_authorized(): self._json(401, {"error": "Требуется авторизация"}) return key = self.headers.get("Sec-WebSocket-Key", "") if self.headers.get("Upgrade", "").lower() != "websocket" or not key: self._json(400, {"error": "Требуется подключение WebSocket"}) return if not acquire_admin_update_slot(): self._json(503, {"error": "Слишком много активных подключений админ-панели"}) return accept = base64.b64encode(hashlib.sha1(f"{key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11".encode("ascii")).digest()).decode("ascii") try: self.send_response(101, "Switching Protocols") self.send_header("Upgrade", "websocket") self.send_header("Connection", "Upgrade") self.send_header("Sec-WebSocket-Accept", accept) self.end_headers() self.close_connection = True while True: payload = json.dumps({"type": "refresh"}, ensure_ascii=False).encode("utf-8") size = len(payload) header = bytes([0x81, size]) if size < 126 else bytes([0x81, 126]) + size.to_bytes(2, "big") self.connection.sendall(header + payload) time.sleep(25) except (BrokenPipeError, ConnectionError, OSError): return finally: release_admin_update_slot() def do_GET(self) -> None: # noqa: N802 """Маршрутизирует GET-запросы к API, админке или статическим файлам.""" 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 in ("/applications", "/applications/"): self._file(WEB_ROOT / "applications.html") return if path in ("/sudoku", "/sudoku/"): self._file(WEB_ROOT / "sudoku.html") return if path == "/api/sudoku/games": try: nickname = parse_qs(urlparse(self.path).query).get("nickname", [""])[0] game = sudoku_store().current(nickname) self._json(200, {"game": public_sudoku_game(game) if game else None}) except SudokuError as exc: self._json(400, {"error": str(exc)}) return if path == "/api/admin/session": self._json(200, {"authenticated": self._admin_session_authorized()}) return if path == "/api/admin/updates": self._serve_admin_updates() return if path.startswith("/api/images/"): object_name = path.removeprefix("/api/images/") if not IMAGE_OBJECT_NAME.fullmatch(object_name): self._json(404, {"error": "Не найдено"}) return try: response = ImageStoreClient().get_object(object_name) except ImageHostError: self._json(404, {"error": "Не найдено"}) return try: self.send_response(200) self.send_header("Content-Type", response.headers.get("Content-Type", mimetypes.guess_type(object_name)[0] or "application/octet-stream")) content_length = response.headers.get("Content-Length") if content_length: self.send_header("Content-Length", content_length) self.send_header("Cache-Control", "public, max-age=31536000, immutable") self.end_headers() while chunk := response.read(64 * 1024): self.wfile.write(chunk) except (BrokenPipeError, ConnectionError, OSError): return finally: response.close() response.release_conn() return if path == "/api/admin/calculations": if not self._admin_authorized(): return query = parse_qs(urlparse(self.path).query) bounds = self._admin_period(query) if bounds is None: return 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 records = [item for item in history_store().list_calculations(sort_by=sort_by, descending=descending, limit=limit) if matches_period(item, *bounds) and report_matches_filters(item, query)] self._json(200, {"items": records}) return if path == "/api/admin/calculations.xlsx": if not self._admin_authorized(): return query = parse_qs(urlparse(self.path).query) bounds = self._admin_period(query) if bounds is None: return records = [item for item in history_store().list_calculations(sort_by="escort_id", descending=True, limit=500) if matches_period(item, *bounds) and report_matches_filters(item, query)] rows = [[item["id"], datetime.fromisoformat(str(item["created_at"]).replace("Z", "+00:00")), item["mode"], item["source"], item["actor_id"], item["message"]] for item in records] self._xlsx("belki-reports.xlsx", build_xlsx(sheet_name="Отчёты", headers=["ID", "Создан (UTC+3)", "Тип", "Источник", "Автор", "Отчёт"], rows=rows, display_timezone=WEB_TIMEZONE)) return if path == "/api/admin/applications": if not self._admin_authorized(): return query = parse_qs(urlparse(self.path).query) status = query.get("status", [None])[0] or None bounds = self._admin_period(query) if bounds is None: return self._json(200, {"items": [item for item in application_store().list(status=status) if matches_period(item, *bounds)]}) return if path == "/api/admin/applications.xlsx": if not self._admin_authorized(): return query = parse_qs(urlparse(self.path).query) status = query.get("status", [None])[0] or None bounds = self._admin_period(query) if bounds is None: return records = [item for item in application_store().list(status=status) if matches_period(item, *bounds)] rows = [[item["id"], datetime.fromisoformat(str(item["created_at"]).replace("Z", "+00:00")), item["status"], item["source"], item["application"].get("type", ""), item["application"].get("name", ""), item["application"].get("character_id")] for item in records] self._xlsx("belki-applications.xlsx", build_xlsx(sheet_name="Заявки", headers=["ID", "Создана (UTC+3)", "Статус", "Источник", "Тип", "Имя", "ID персонажа"], rows=rows, display_timezone=WEB_TIMEZONE)) return if path == "/api/admin/vk/conversations": if not self._admin_authorized(): return self._json(200, {"items": vk_conversation_store().list_conversations()}) return if path == "/api/admin/vk/templates": if not self._admin_authorized(): return self._json(200, {"items": vk_conversation_store().list_templates()}) return if path == "/api/admin/vk/schedules": if not self._admin_authorized(): return self._json(200, {"items": vk_conversation_store().list_schedules()}) 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: """Отдаёт существующий статический файл с подходящим MIME-типом.""" 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 _read_json_body(self) -> dict: """Читает JSON-тело запроса с ограничением размера и проверкой объекта.""" """Read a bounded JSON request before passing it to public handlers.""" content_type = self.headers.get("Content-Type", "") if not content_type.lower().startswith("application/json"): raise ApiError("Ожидалось содержимое в формате JSON") try: length = int(self.headers.get("Content-Length", "")) except ValueError as exc: raise ApiError("Некорректный размер запроса") from exc if not 0 <= length <= MAX_JSON_BODY_BYTES: raise ApiError(f"Слишком большой запрос (максимум {MAX_JSON_BODY_BYTES // 1024 // 1024} МБ)") try: payload = json.loads(self.rfile.read(length)) if length else {} except json.JSONDecodeError as exc: raise ApiError("Не удалось прочитать JSON") from exc if not isinstance(payload, dict): raise ApiError("Ожидался JSON-объект") return payload def do_POST(self) -> None: # noqa: N802 """Обрабатывает вход, авторизацию и создание заявок через POST API.""" parsed = urlparse(self.path) is_sudoku_create = parsed.path == "/api/sudoku/games" is_sudoku_regenerate = parsed.path.startswith("/api/sudoku/games/") and parsed.path.endswith("/regenerate") if self.path not in ("/api/admin/auth", "/api/admin/logout", "/api/web/upload", "/api/calculate", "/api/reports", "/api/inspect-bulk", "/api/resolve-identity", "/api/rename-identity", "/api/applications", "/api/admin/vk/templates", "/api/admin/vk/schedules") and not is_sudoku_create and not is_sudoku_regenerate: self._json(404, {"error": "Не найдено"}) return try: payload = self._read_json_body() if is_sudoku_create: self._json(201, {"game": public_sudoku_game(sudoku_store().create(payload.get("nickname"), payload.get("difficulty")))}) elif is_sudoku_regenerate: game_id = parsed.path.removeprefix("/api/sudoku/games/").removesuffix("/regenerate").strip("/") sudoku_store().get(game_id, payload.get("nickname")) self._json(201, {"game": public_sudoku_game(sudoku_store().create(payload.get("nickname"), payload.get("difficulty")))}) elif self.path == "/api/admin/auth": client_ip = self.client_address[0] if not allow_admin_auth_attempt(client_ip): self._json(429, {"error": "Слишком много попыток. Повторите через 15 минут."}) return expected = os.getenv("BELKI_ADMIN_PASSWORD", "") if not expected or not secrets.compare_digest(str(payload.get("password", "")), expected): self._json(401, {"error": "Неверный пароль"}) return clear_admin_auth_attempts(client_ip) token = secrets.token_urlsafe(32) remember_admin_session(token) self._json_with_cookie(200, {"authenticated": True}, self._admin_cookie(token)) elif self.path == "/api/admin/logout": forget_admin_session(self._session_token("belki_admin_session")) self._json_with_cookie(200, {"authenticated": False}, "belki_admin_session=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax") 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) > MAX_UPLOAD_BYTES: raise ApiError("Файл слишком большой (максимум 15 МБ)") content_type = detect_raster_image_type(body) if content_type is None: raise ApiError("Поддерживаются только изображения PNG, JPEG и WebP") declared_type = str(payload.get("type", "")).split(";", 1)[0].strip().lower() if declared_type and declared_type != content_type: raise ApiError("Тип файла не совпадает с содержимым изображения") try: url = ImageStoreClient().upload_bytes( body, safe_upload_name(payload.get("name"), content_type), content_type ) except ImageHostError as exc: raise ApiError(f"Не удалось загрузить изображение: {exc}") from exc if not url: raise ApiError("Хранилище изображений не настроено") remember_issued_web_upload(url) self._json(200, {"url": url, "name": safe_upload_name(payload.get("name"), content_type)}) 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/rename-identity": self._json(200, rename_identity_payload(payload)) elif self.path == "/api/applications": payload["attachments"] = validate_web_report_attachments(payload) application = validate_application(payload) application_id = application_store().create(application=application, actor_id=None, reply_peer_id=None, source="web") sync_application_exports() self._json(201, {"id": application_id, "status": "pending", "message": "Заявка отправлена на рассмотрение."}) elif self.path == "/api/admin/vk/templates": if not self._admin_authorized(): return template_id = vk_conversation_store().create_template(str(payload.get("name", "")), str(payload.get("text", "")), active=bool(payload.get("active", True)), starts_on=payload.get("starts_on"), ends_on=payload.get("ends_on")) self._json(201, {"id": template_id}) elif self.path == "/api/admin/vk/schedules": if not self._admin_authorized(): return schedule_id = vk_conversation_store().create_schedule(template_id=int(payload["template_id"]), peer_id=int(payload["peer_id"]), times=payload.get("times", []), weekdays=payload.get("weekdays"), timezone_name=str(payload.get("timezone", "Europe/Moscow")), active=bool(payload.get("active", False)), starts_on=payload.get("starts_on"), ends_on=payload.get("ends_on")) self._json(201, {"id": schedule_id}) elif self.path == "/api/calculate": payload["attachments"] = validate_web_report_attachments(payload) self._json(200, calculate_payload(payload)) else: payload["attachments"] = validate_web_attachments(payload.get("attachments", [])) self._json(201, calculate_and_store(payload, actor_id=None, source="web")) except (ApiError, ApplicationError, SudokuError) 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_PUT(self) -> None: # noqa: N802 """Save an in-progress Sudoku board for resuming on another device.""" parsed = urlparse(self.path) prefix = "/api/sudoku/games/" if not parsed.path.startswith(prefix) or not parsed.path.removeprefix(prefix): self._json(404, {"error": "Не найдено"}) return try: payload = self._read_json_body() game = sudoku_store().save(parsed.path.removeprefix(prefix), payload.get("nickname"), payload.get("board"), payload.get("elapsedSeconds")) self._json(200, {"game": public_sudoku_game(game)}) except (ApiError, SudokuError) 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) vk_schedule_prefix = "/api/admin/vk/schedules/" if parsed.path.startswith(vk_schedule_prefix): if not self._admin_authorized(): return try: schedule_id = int(parsed.path[len(vk_schedule_prefix):].strip("/")) except ValueError: self._json(400, {"error": "Некорректный ID расписания"}) return if not vk_conversation_store().delete_schedule(schedule_id): self._json(404, {"error": "Расписание не найдено"}) return self._json(200, {"deleted": schedule_id}) return 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 do_PATCH(self) -> None: # noqa: N802 """Меняет статус новой заявки через PATCH API.""" parsed = urlparse(self.path) entered_prefix = "/api/admin/calculations/" if parsed.path.startswith(entered_prefix) and parsed.path.endswith("/entered"): if not self._admin_authorized(): return try: calculation_id = int(parsed.path[len(entered_prefix):-len("/entered")].strip("/")) payload = self._read_json_body() item = history_store().set_entered(calculation_id, bool(payload.get("entered"))) except (ApiError, ValueError) as exc: self._json(400, {"error": str(exc)}) return if item is None: self._json(404, {"error": "Запись не найдена"}) else: self._json(200, {"item": item}) return if parsed.path.startswith("/api/admin/vk/conversations/") or parsed.path.startswith("/api/admin/vk/schedules/"): if not self._admin_authorized(): return try: payload = self._read_json_body() item_id = int(parsed.path.rsplit("/", 1)[1]) store = vk_conversation_store() if "/conversations/" in parsed.path: store._execute("UPDATE vk_conversations SET mailing_enabled=? WHERE peer_id=?", (bool(payload.get("mailing_enabled")), item_id)) item = store.get_conversation(item_id) else: store._execute("UPDATE vk_schedules SET active=? WHERE id=?", (bool(payload.get("active")), item_id)) if bool(payload.get("active")): store._execute("UPDATE vk_conversations SET mailing_enabled=TRUE WHERE peer_id=(SELECT peer_id FROM vk_schedules WHERE id=?)", (item_id,)) else: store._execute("UPDATE vk_conversations SET mailing_enabled=FALSE WHERE peer_id=(SELECT peer_id FROM vk_schedules WHERE id=?) AND NOT EXISTS (SELECT 1 FROM vk_schedules other WHERE other.peer_id=vk_conversations.peer_id AND other.active=TRUE)", (item_id,)) item = next((x for x in store.list_schedules() if x["id"] == item_id), None) if item is None: self._json(404, {"error": "Запись не найдена"}) else: self._json(200, {"item": item}) except (ValueError, ApiError) as exc: self._json(400, {"error": str(exc)}) return prefix = "/api/admin/applications/" if not parsed.path.startswith(prefix): self._json(404, {"error": "Не найдено"}) return if not self._admin_authorized(): return raw_id, separator, action = parsed.path[len(prefix):].strip("/").partition("/") if not separator or action not in {"accept", "reject"}: self._json(404, {"error": "Не найдено"}) return try: application = application_store().review(int(raw_id), status="accepted" if action == "accept" else "rejected") except (ValueError, ApplicationError) as exc: self._json(400, {"error": str(exc)}) return if application is None: self._json(404, {"error": "Заявка не найдена или уже рассмотрена"}) return if application["status"] == "accepted": sync_application_exports() self._json(200, {"item": application}) def log_message(self, format: str, *args: object) -> None: """Пишет стандартные HTTP-логи в настроенный логгер приложения.""" if os.getenv("BELKI_ACCESS_LOG", "0") == "1": super().log_message(format, *args) def serve() -> None: """Запускает HTTP-сервер на адресе и порту из переменных окружения.""" host = os.getenv("BELKI_HOST", "0.0.0.0") port = int(os.getenv("BELKI_PORT", "8080")) BelkiHTTPServer((host, port), Handler).serve_forever() if __name__ == "__main__": serve()