"""Заявки сообщества: валидация и отдельное хранилище очереди модерации.""" from __future__ import annotations import json import os import sqlite3 from pathlib import Path from typing import Any from urllib.parse import urlparse APPLICATION_TYPES = { "feather_donation": "Пожертвовать перо отряду", "kitten": "Стать бельчонком", "flying_squirrel": "Стать белкой-летягой", "curator": "Стать куратором", } MAX_APPLICATION_NAME_LENGTH = 100 MAX_APPLICATION_ATTACHMENTS = 10 MAX_APPLICATION_FEATHERS = 100 MAX_APPLICATION_TEXT_LENGTH = 500 MAX_APPLICATION_URL_LENGTH = 2_048 MAX_APPLICATION_FEATHER_AMOUNT = 100_000 class ApplicationError(ValueError): """Понятная пользователю ошибка данных заявки.""" def _positive_id(value: Any, label: str) -> int: if isinstance(value, bool): raise ApplicationError(f"{label} должно быть числом") try: result = int(value) except (TypeError, ValueError) as exc: raise ApplicationError(f"{label} должно быть числом") from exc if result <= 0: raise ApplicationError(f"{label} должно быть положительным") return result def _normalise_vk_link(value: Any) -> str: """Accept a real VK HTTPS link without making users type the protocol.""" link = str(value or "").strip() if not link: return "" if len(link) > MAX_APPLICATION_URL_LENGTH: raise ApplicationError("Ссылка VK слишком длинная") parsed = urlparse(link) if not parsed.scheme and parsed.path.split("/", 1)[0].lower() in {"vk.com", "www.vk.com", "vk.ru", "www.vk.ru"}: link = f"https://{link}" parsed = urlparse(link) host = (parsed.hostname or "").lower() if parsed.scheme != "https" or host not in {"vk.com", "www.vk.com", "vk.ru", "www.vk.ru", "m.vk.com", "m.vk.ru"}: raise ApplicationError("Укажите HTTPS-ссылку на страницу VK") return link def _https_link(value: Any, label: str) -> str: link = str(value or "").strip() if len(link) > MAX_APPLICATION_URL_LENGTH: raise ApplicationError(f"{label} слишком длинная") parsed = urlparse(link) if parsed.scheme != "https" or not parsed.hostname: raise ApplicationError(f"{label} должна начинаться с https://") return link def _attachments(value: Any) -> list[dict[str, str]]: if not isinstance(value, list) or len(value) > MAX_APPLICATION_ATTACHMENTS: raise ApplicationError(f"Можно приложить не более {MAX_APPLICATION_ATTACHMENTS} изображений") attachments: list[dict[str, str]] = [] for item in value: if not isinstance(item, dict): raise ApplicationError("Некорректное вложение") url = _https_link(item.get("url"), "Ссылка на вложение") attachment = {"type": "photo", "url": url} name = str(item.get("name", "")).strip() if name: attachment["name"] = name[:MAX_APPLICATION_NAME_LENGTH] attachments.append(attachment) return attachments def validate_application(payload: dict[str, Any]) -> dict[str, Any]: """Возвращает очищенную заявку и проверяет обязательные поля её типа.""" if not isinstance(payload, dict): raise ApplicationError("Ожидалась заявка в формате JSON") application_type = str(payload.get("type", "")).strip() if application_type not in APPLICATION_TYPES: raise ApplicationError("Выберите тип заявки") name = str(payload.get("name", "")).strip() if not name: raise ApplicationError("Укажите имя персонажа") if len(name) > MAX_APPLICATION_NAME_LENGTH: raise ApplicationError(f"Имя персонажа не должно быть длиннее {MAX_APPLICATION_NAME_LENGTH} символов") result: dict[str, Any] = { "type": application_type, "name": name, "character_id": _positive_id(payload.get("character_id"), "ID персонажа"), "attachments": _attachments(payload.get("attachments", [])), "vk_link": _normalise_vk_link(payload.get("vk_link")), } if application_type == "kitten": if not result["attachments"]: raise ApplicationError("Для заявки в бельчата приложите скриншот активности") elif application_type == "flying_squirrel": practiced_before = payload.get("practiced_before") if not isinstance(practiced_before, bool): raise ApplicationError("Укажите, сдавали ли вы практику ранее") result["practiced_before"] = practiced_before result["practice_review_link"] = str(payload.get("practice_review_link", "")).strip() if practiced_before and not result["practice_review_link"]: raise ApplicationError("Приложите ссылку на комментарий с прошлой практики") if result["practice_review_link"]: result["practice_review_link"] = _https_link(result["practice_review_link"], "Ссылка на комментарий") elif application_type == "curator": if not result["attachments"]: raise ApplicationError("Для заявки куратором приложите скриншот ЛУ с дробью") elif application_type == "feather_donation": feathers = [] raw_feathers = payload.get("feathers", []) if not isinstance(raw_feathers, list) or len(raw_feathers) > MAX_APPLICATION_FEATHERS: raise ApplicationError(f"Можно указать не более {MAX_APPLICATION_FEATHERS} строк с перьями") for item in raw_feathers: if not isinstance(item, dict): continue color = str(item.get("color", "")).strip() source = str(item.get("source", "")).strip() if not color or not source: raise ApplicationError("Для каждого пера укажите цвет и источник добычи") if len(color) > MAX_APPLICATION_TEXT_LENGTH or len(source) > MAX_APPLICATION_TEXT_LENGTH: raise ApplicationError(f"Описание пера не должно быть длиннее {MAX_APPLICATION_TEXT_LENGTH} символов") amount = _positive_id(item.get("amount"), "Количество перьев") if amount > MAX_APPLICATION_FEATHER_AMOUNT: raise ApplicationError(f"Количество перьев не должно превышать {MAX_APPLICATION_FEATHER_AMOUNT}") feathers.append({"color": color, "amount": amount, "source": source}) if not feathers: raise ApplicationError("Добавьте хотя бы одно перо") result["feathers"] = feathers return result class ApplicationStore: """Хранилище заявок в PostgreSQL production и SQLite для разработки.""" def __init__(self, database_url: str | None = None, sqlite_path: str | Path | None = None) -> None: self.database_url = database_url or "" self.sqlite_path = Path(sqlite_path) if sqlite_path else None if self.database_url.startswith(("postgres://", "postgresql://")): import psycopg self._psycopg = psycopg self._ensure_postgres_schema() else: self.sqlite_path = self.sqlite_path or Path("data/belki.sqlite3") self.sqlite_path.parent.mkdir(parents=True, exist_ok=True) self._ensure_sqlite_schema() @classmethod def from_environment(cls) -> "ApplicationStore": return cls(os.getenv("BELKI_DATABASE_URL"), os.getenv("BELKI_HISTORY_DB", "data/belki.sqlite3")) def _ensure_sqlite_schema(self) -> None: with sqlite3.connect(self.sqlite_path) as connection: connection.execute("""CREATE TABLE IF NOT EXISTS applications ( id INTEGER PRIMARY KEY AUTOINCREMENT, actor_id INTEGER, reply_peer_id INTEGER, source TEXT NOT NULL, application_json TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending', created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, reviewed_at TEXT )""") try: connection.execute("ALTER TABLE applications ADD COLUMN notified_at TEXT") except sqlite3.OperationalError: pass connection.execute("""CREATE TABLE IF NOT EXISTS application_export_events ( id INTEGER PRIMARY KEY AUTOINCREMENT, application_id INTEGER NOT NULL, event_type TEXT NOT NULL, payload_json TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending', attempts INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, delivered_at TEXT, last_error TEXT )""") def _ensure_postgres_schema(self) -> None: with self._psycopg.connect(self.database_url) as connection: connection.execute("""CREATE TABLE IF NOT EXISTS belki_applications ( id BIGSERIAL PRIMARY KEY, actor_id BIGINT, reply_peer_id BIGINT, source TEXT NOT NULL, application_json JSONB NOT NULL, status TEXT NOT NULL DEFAULT 'pending', created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), reviewed_at TIMESTAMPTZ )""") connection.execute("ALTER TABLE belki_applications ADD COLUMN IF NOT EXISTS notified_at TIMESTAMPTZ") connection.execute("""CREATE TABLE IF NOT EXISTS belki_application_export_events ( id BIGSERIAL PRIMARY KEY, application_id BIGINT NOT NULL, event_type TEXT NOT NULL, payload_json JSONB NOT NULL, status TEXT NOT NULL DEFAULT 'pending', attempts INTEGER NOT NULL DEFAULT 0, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), delivered_at TIMESTAMPTZ, last_error TEXT )""") def create(self, *, application: dict[str, Any], actor_id: int | None, reply_peer_id: int | None, source: str) -> int: if self.database_url.startswith(("postgres://", "postgresql://")): from psycopg.types.json import Jsonb with self._psycopg.connect(self.database_url) as connection: row = connection.execute("""INSERT INTO belki_applications (actor_id, reply_peer_id, source, application_json) VALUES (%s, %s, %s, %s) RETURNING id""", (actor_id, reply_peer_id, source, Jsonb(application))).fetchone() application_id = int(row[0]) self.enqueue_export(application_id, "application_created", { "id": application_id, "source": source, "status": "pending", "application": application, }) return application_id with sqlite3.connect(self.sqlite_path) as connection: cursor = connection.execute("""INSERT INTO applications (actor_id, reply_peer_id, source, application_json) VALUES (?, ?, ?, ?)""", (actor_id, reply_peer_id, source, json.dumps(application, ensure_ascii=False))) application_id = int(cursor.lastrowid) self.enqueue_export(application_id, "application_created", { "id": application_id, "source": source, "status": "pending", "application": application, }) return application_id def list(self, *, status: str | None = None, limit: int = 500) -> list[dict[str, Any]]: if status not in (None, "pending", "accepted"): raise ApplicationError("Неизвестный статус заявки") limit = max(1, min(int(limit), 500)) if self.database_url.startswith(("postgres://", "postgresql://")): query = "SELECT id, actor_id, reply_peer_id, source, application_json, status, created_at, reviewed_at FROM belki_applications" params: tuple[Any, ...] = () if status: query += " WHERE status = %s"; params = (status,) query += " ORDER BY created_at DESC LIMIT %s"; params += (limit,) with self._psycopg.connect(self.database_url) as connection: rows = connection.execute(query, params).fetchall() else: query = "SELECT id, actor_id, reply_peer_id, source, application_json, status, created_at, reviewed_at FROM applications" params: tuple[Any, ...] = () if status: query += " WHERE status = ?"; params = (status,) query += " ORDER BY created_at DESC LIMIT ?"; params += (limit,) with sqlite3.connect(self.sqlite_path) as connection: rows = connection.execute(query, params).fetchall() return [{"id": row[0], "actor_id": row[1], "reply_peer_id": row[2], "source": row[3], "application": row[4] if isinstance(row[4], dict) else json.loads(row[4]), "status": row[5], "created_at": row[6].isoformat() if hasattr(row[6], "isoformat") else row[6], "reviewed_at": row[7].isoformat() if hasattr(row[7], "isoformat") else row[7]} for row in rows] def accept(self, application_id: int) -> dict[str, Any] | None: if application_id <= 0: raise ApplicationError("ID заявки должно быть положительным") if self.database_url.startswith(("postgres://", "postgresql://")): with self._psycopg.connect(self.database_url) as connection: row = connection.execute("""UPDATE belki_applications SET status = 'accepted', reviewed_at = NOW() WHERE id = %s AND status = 'pending' RETURNING id, actor_id, reply_peer_id, source, application_json, status, created_at, reviewed_at""", (application_id,)).fetchone() else: with sqlite3.connect(self.sqlite_path) as connection: cursor = connection.execute("UPDATE applications SET status = 'accepted', reviewed_at = CURRENT_TIMESTAMP WHERE id = ? AND status = 'pending'", (application_id,)) if not cursor.rowcount: return None application = next((item for item in self.list(limit=500) if item["id"] == application_id), None) if application: self.enqueue_export(application_id, "application_accepted", application) return application if row is None: return None application = {"id": row[0], "actor_id": row[1], "reply_peer_id": row[2], "source": row[3], "application": row[4], "status": row[5], "created_at": row[6].isoformat(), "reviewed_at": row[7].isoformat()} self.enqueue_export(application_id, "application_accepted", application) return application def enqueue_export(self, application_id: int, event_type: str, snapshot: dict[str, Any]) -> int: """Сохраняет событие для будущего экспорта до любого сетевого вызова.""" payload = {"schema_version": 1, "event_type": event_type, "application": snapshot} if self.database_url.startswith(("postgres://", "postgresql://")): from psycopg.types.json import Jsonb with self._psycopg.connect(self.database_url) as connection: row = connection.execute("""INSERT INTO belki_application_export_events (application_id, event_type, payload_json) VALUES (%s, %s, %s) RETURNING id""", (application_id, event_type, Jsonb(payload))).fetchone() return int(row[0]) with sqlite3.connect(self.sqlite_path) as connection: cursor = connection.execute("""INSERT INTO application_export_events (application_id, event_type, payload_json) VALUES (?, ?, ?)""", (application_id, event_type, json.dumps(payload, ensure_ascii=False))) return int(cursor.lastrowid) def pending_exports(self, *, limit: int = 100) -> list[dict[str, Any]]: """Возвращает недоставленные события в порядке их создания.""" limit = max(1, min(int(limit), 500)) if self.database_url.startswith(("postgres://", "postgresql://")): with self._psycopg.connect(self.database_url) as connection: rows = connection.execute("""SELECT id, application_id, event_type, payload_json, attempts FROM belki_application_export_events WHERE status = 'pending' ORDER BY id LIMIT %s""", (limit,)).fetchall() else: with sqlite3.connect(self.sqlite_path) as connection: rows = connection.execute("""SELECT id, application_id, event_type, payload_json, attempts FROM application_export_events WHERE status = 'pending' ORDER BY id LIMIT ?""", (limit,)).fetchall() return [{"id": row[0], "application_id": row[1], "event_type": row[2], "payload": row[3] if isinstance(row[3], dict) else json.loads(row[3]), "attempts": row[4]} for row in rows] def mark_exported(self, event_id: int) -> None: if self.database_url.startswith(("postgres://", "postgresql://")): with self._psycopg.connect(self.database_url) as connection: connection.execute("UPDATE belki_application_export_events SET status = 'delivered', delivered_at = NOW(), attempts = attempts + 1, last_error = NULL WHERE id = %s", (event_id,)) else: with sqlite3.connect(self.sqlite_path) as connection: connection.execute("UPDATE application_export_events SET status = 'delivered', delivered_at = CURRENT_TIMESTAMP, attempts = attempts + 1, last_error = NULL WHERE id = ?", (event_id,)) def record_export_failure(self, event_id: int, message: str) -> None: message = message[:1000] if self.database_url.startswith(("postgres://", "postgresql://")): with self._psycopg.connect(self.database_url) as connection: connection.execute("UPDATE belki_application_export_events SET attempts = attempts + 1, last_error = %s WHERE id = %s", (message, event_id)) else: with sqlite3.connect(self.sqlite_path) as connection: connection.execute("UPDATE application_export_events SET attempts = attempts + 1, last_error = ? WHERE id = ?", (message, event_id)) def pending_notifications(self) -> list[dict[str, Any]]: """Возвращает принятые VK-заявки, для которых ещё не отправлено уведомление.""" if self.database_url.startswith(("postgres://", "postgresql://")): with self._psycopg.connect(self.database_url) as connection: rows = connection.execute("""SELECT id, reply_peer_id, application_json FROM belki_applications WHERE status = 'accepted' AND notified_at IS NULL AND reply_peer_id IS NOT NULL""").fetchall() else: with sqlite3.connect(self.sqlite_path) as connection: rows = connection.execute("""SELECT id, reply_peer_id, application_json FROM applications WHERE status = 'accepted' AND notified_at IS NULL AND reply_peer_id IS NOT NULL""").fetchall() return [{"id": row[0], "reply_peer_id": row[1], "application": row[2] if isinstance(row[2], dict) else json.loads(row[2])} for row in rows] def mark_notified(self, application_id: int) -> None: if self.database_url.startswith(("postgres://", "postgresql://")): with self._psycopg.connect(self.database_url) as connection: connection.execute("UPDATE belki_applications SET notified_at = NOW() WHERE id = %s", (application_id,)) else: with sqlite3.connect(self.sqlite_path) as connection: connection.execute("UPDATE applications SET notified_at = CURRENT_TIMESTAMP WHERE id = ?", (application_id,))