feat: schedule VK conversation messages
This commit is contained in:
1 parent
f7c5eb994e
commit
4590070bbc
9 files changed
+314
-2
No files matched your search
@@ -22,6 +22,7 @@
|
||||
- Do not add unnecessary local build artifacts or temporary files to the repository.
|
||||
|
||||
## Notes
|
||||
- VK scheduler lives in `app/belki/vk_scheduler.py`; use `BELKI_DATABASE_URL` in production and `BELKI_HISTORY_DB` for local SQLite checks. Keep mailing disabled until an administrator explicitly enables a conversation and schedule.
|
||||
- The build job waits for the DinD daemon and runs `docker info` before building.
|
||||
- Never commit `.env` or `.gitlab.variables.env`; the latter contains the GitLab Variable handoff and a namespace-scoped kubeconfig.
|
||||
|
||||
|
||||
@@ -71,3 +71,6 @@ Production Belki images and Kubernetes workloads require `linux/amd64`. CI sets
|
||||
`/sudoku` is a separate public route, backed by `app/sudoku.py` and `web/sudoku.html`. A supplied nickname (case-insensitive) is intentionally only a resume key, not authentication; never present it as private storage. Games persist in `sudoku_games` through `BELKI_DATABASE_URL` in production or `SUDOKU_DB` locally. The public API must never return the saved solution, and it must keep original clues immutable. The generator is the explicitly requested `dokusan==0.1.0`; it is GPL-3.0-only, Alpha, and last released in 2023, so retain the `NOTICE`/README license disclosure and revalidate it before future runtime upgrades.
|
||||
|
||||
The final gateway Dockerfile must copy `nginx.conf` into the release image, not rely exclusively on the immutable gateway base. This keeps `/sudoku` and other route changes from producing a successful deployment with an old Nginx configuration and a public 404.
|
||||
# 2026-09-06: VK conversation scheduler
|
||||
|
||||
`app/belki/vk_scheduler.py` хранит реестр бесед, шаблоны, расписания и историю попыток в общей БД (`BELKI_DATABASE_URL` или `BELKI_HISTORY_DB`). `BelkiBot` регистрирует `chat_invite_user`/`chat_invite_user_by_link`, помечает `chat_kick_user`/`chat_leave_user` как недоступные и запускает idempotent scheduler в отдельном daemon-потоке. Админские endpoints `/api/admin/vk/conversations`, `/templates`, `/schedules` защищены существующей сессией; сообщения по умолчанию выключены.
|
||||
@@ -21,6 +21,7 @@ from .image_host import ImageHostClient
|
||||
from .identity import Identity, IdentityDirectory
|
||||
from .applications import APPLICATION_TYPES, ApplicationError, ApplicationStore, validate_application
|
||||
from .google_sheets_export import GoogleSheetsExportService
|
||||
from .vk_scheduler import VkConversationStore, VkScheduler
|
||||
|
||||
"""
|
||||
Обработка VK-бота:
|
||||
@@ -853,6 +854,8 @@ class BelkiBot:
|
||||
self.application_store = ApplicationStore.from_environment()
|
||||
self.application_dialog = ApplicationDialog(identities, self.application_store)
|
||||
self.application_exporter = GoogleSheetsExportService(self.application_store)
|
||||
self.conversation_store = VkConversationStore.from_environment()
|
||||
self.scheduler = VkScheduler(self.conversation_store, self.client.send)
|
||||
|
||||
def response_for_text(self, text: str) -> str:
|
||||
"""Обработка текстового сообщения и возврат ответа."""
|
||||
@@ -874,6 +877,14 @@ class BelkiBot:
|
||||
return
|
||||
message = event.get("object", {}).get("message", event.get("object", {}))
|
||||
peer_id = message.get("peer_id")
|
||||
action = (message.get("action") or {}).get("type")
|
||||
if peer_id and int(peer_id) >= 2_000_000_000:
|
||||
chat_id = int(peer_id) - 2_000_000_000
|
||||
if action in {"chat_invite_user", "chat_invite_user_by_link"}:
|
||||
self.conversation_store.upsert_conversation(peer_id=int(peer_id), chat_id=chat_id,
|
||||
title=(message.get("chat_settings") or {}).get("title"), invited_by=message.get("from_id"))
|
||||
elif action in {"chat_kick_user", "chat_leave_user"}:
|
||||
self.conversation_store.mark_removed(int(peer_id), action)
|
||||
sender_id = message.get("from_id", message.get("sender_id", peer_id))
|
||||
text = self._button_text(message) or message.get("text", "")
|
||||
if peer_id is not None:
|
||||
@@ -963,6 +974,7 @@ class BelkiBot:
|
||||
self.application_exporter.sync_pending()
|
||||
time.sleep(15)
|
||||
threading.Thread(target=notification_loop, name="belki-application-notifier", daemon=True).start()
|
||||
threading.Thread(target=self.scheduler.run_forever, name="belki-vk-scheduler", daemon=True).start()
|
||||
for event in self.events():
|
||||
self.handle_event(event)
|
||||
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
"""VK conversation registry and idempotent message scheduler."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from zoneinfo import ZoneInfo
|
||||
from typing import Any, Callable
|
||||
|
||||
MOSCOW = "Europe/Moscow"
|
||||
|
||||
|
||||
def conversation_peer_id(chat_id: int) -> int:
|
||||
"""Convert VK chat id (1-based) to the conversation peer id."""
|
||||
value = int(chat_id)
|
||||
if value <= 0:
|
||||
raise ValueError("chat_id должен быть положительным")
|
||||
return 2_000_000_000 + value
|
||||
|
||||
|
||||
def parse_schedule(*, times: list[str], weekdays: list[int] | None = None,
|
||||
timezone_name: str = MOSCOW) -> tuple[list[str], list[int], str]:
|
||||
"""Validate fixed HH:MM times and ISO weekdays (1=Mon..7=Sun)."""
|
||||
try:
|
||||
ZoneInfo(timezone_name)
|
||||
except Exception as exc:
|
||||
raise ValueError("Неизвестный часовой пояс") from exc
|
||||
clean_times = sorted(set(str(value).strip() for value in times))
|
||||
if not clean_times:
|
||||
raise ValueError("Укажите хотя бы одно время")
|
||||
for value in clean_times:
|
||||
if len(value) != 5 or value[2] != ":":
|
||||
raise ValueError("Время должно быть в формате HH:MM")
|
||||
hour, minute = value.split(":")
|
||||
if not (hour.isdigit() and minute.isdigit() and 0 <= int(hour) <= 23 and 0 <= int(minute) <= 59):
|
||||
raise ValueError("Время должно быть в формате HH:MM")
|
||||
days = sorted(set(int(day) for day in (weekdays or [1, 2, 3, 4, 5, 6, 7])))
|
||||
if not days or any(day < 1 or day > 7 for day in days):
|
||||
raise ValueError("Дни недели должны быть от 1 до 7")
|
||||
return clean_times, days, timezone_name
|
||||
|
||||
|
||||
class VkConversationStore:
|
||||
"""Persistence for conversations, templates, schedules and delivery history."""
|
||||
|
||||
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 or os.getenv("BELKI_HISTORY_DB", "data/belki.sqlite3"))
|
||||
self._postgres = self.database_url.startswith(("postgres://", "postgresql://"))
|
||||
if self._postgres:
|
||||
import psycopg
|
||||
self._psycopg = psycopg
|
||||
self._ensure_schema()
|
||||
else:
|
||||
self.sqlite_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self._ensure_schema()
|
||||
|
||||
@classmethod
|
||||
def from_environment(cls) -> "VkConversationStore":
|
||||
return cls(os.getenv("BELKI_DATABASE_URL"), os.getenv("BELKI_HISTORY_DB", "data/belki.sqlite3"))
|
||||
|
||||
def _ensure_schema(self) -> None:
|
||||
statements = [
|
||||
"""CREATE TABLE IF NOT EXISTS vk_conversations (
|
||||
peer_id BIGINT PRIMARY KEY, chat_id BIGINT NOT NULL, title TEXT,
|
||||
status TEXT NOT NULL DEFAULT 'active', mailing_enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
added_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, invited_by BIGINT,
|
||||
removed_at TEXT, removal_reason TEXT, last_success_at TEXT, last_error TEXT)""",
|
||||
"""CREATE TABLE IF NOT EXISTS vk_message_templates (
|
||||
id INTEGER PRIMARY KEY, name TEXT NOT NULL, text TEXT NOT NULL,
|
||||
active BOOLEAN NOT NULL DEFAULT TRUE, created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
starts_on TEXT, ends_on TEXT)""",
|
||||
"""CREATE TABLE IF NOT EXISTS vk_schedules (
|
||||
id INTEGER PRIMARY KEY, template_id INTEGER NOT NULL, peer_id BIGINT NOT NULL,
|
||||
times_json TEXT NOT NULL, weekdays_json TEXT NOT NULL, timezone TEXT NOT NULL DEFAULT 'Europe/Moscow',
|
||||
active BOOLEAN NOT NULL DEFAULT FALSE, starts_on TEXT, ends_on TEXT,
|
||||
FOREIGN KEY(template_id) REFERENCES vk_message_templates(id),
|
||||
FOREIGN KEY(peer_id) REFERENCES vk_conversations(peer_id))""",
|
||||
"""CREATE TABLE IF NOT EXISTS vk_delivery_attempts (
|
||||
id INTEGER PRIMARY KEY, schedule_id INTEGER NOT NULL, planned_for TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'pending', attempted_at TEXT, attempts INTEGER NOT NULL DEFAULT 0,
|
||||
vk_result TEXT, error TEXT, UNIQUE(schedule_id, planned_for))""",
|
||||
]
|
||||
if self._postgres:
|
||||
with self._psycopg.connect(self.database_url) as conn:
|
||||
for statement in statements:
|
||||
conn.execute(statement.replace("INTEGER PRIMARY KEY", "BIGSERIAL PRIMARY KEY"))
|
||||
else:
|
||||
with sqlite3.connect(self.sqlite_path) as conn:
|
||||
for statement in statements:
|
||||
conn.execute(statement)
|
||||
|
||||
def _execute(self, sql: str, params: tuple[Any, ...] = (), *, fetch: bool = False) -> list[tuple] | None:
|
||||
if self._postgres:
|
||||
with self._psycopg.connect(self.database_url) as conn:
|
||||
cur = conn.execute(sql.replace("?", "%s"), params)
|
||||
return cur.fetchall() if fetch else None
|
||||
with sqlite3.connect(self.sqlite_path) as conn:
|
||||
cur = conn.execute(sql, params)
|
||||
return cur.fetchall() if fetch else None
|
||||
|
||||
def upsert_conversation(self, *, peer_id: int, chat_id: int, title: str | None = None, invited_by: int | None = None) -> dict:
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
if self._postgres:
|
||||
self._execute("""INSERT INTO vk_conversations(peer_id,chat_id,title,status,mailing_enabled,added_at,invited_by)
|
||||
VALUES(?,?,?, 'active',FALSE,?,?) ON CONFLICT(peer_id) DO UPDATE SET title=COALESCE(EXCLUDED.title,vk_conversations.title), status='active', removed_at=NULL, removal_reason=NULL, invited_by=COALESCE(EXCLUDED.invited_by,vk_conversations.invited_by)""", (peer_id, chat_id, title, now, invited_by))
|
||||
else:
|
||||
self._execute("""INSERT INTO vk_conversations(peer_id,chat_id,title,status,mailing_enabled,added_at,invited_by) VALUES(?,?,?,'active',0,?,?)
|
||||
ON CONFLICT(peer_id) DO UPDATE SET title=COALESCE(excluded.title,title), status='active', removed_at=NULL, removal_reason=NULL, invited_by=COALESCE(excluded.invited_by,invited_by)""", (peer_id, chat_id, title, now, invited_by))
|
||||
return self.get_conversation(peer_id) or {}
|
||||
|
||||
def mark_removed(self, peer_id: int, reason: str) -> None:
|
||||
self._execute("UPDATE vk_conversations SET status='bot_removed', mailing_enabled=FALSE, removed_at=?, removal_reason=? WHERE peer_id=?", (datetime.now(timezone.utc).isoformat(), reason[:500], peer_id))
|
||||
|
||||
def get_conversation(self, peer_id: int) -> dict | None:
|
||||
rows = self._execute("SELECT peer_id,chat_id,title,status,mailing_enabled,added_at,invited_by,removed_at,removal_reason,last_success_at,last_error FROM vk_conversations WHERE peer_id=?", (peer_id,), fetch=True) or []
|
||||
return self._conversation_row(rows[0]) if rows else None
|
||||
|
||||
def list_conversations(self) -> list[dict]:
|
||||
rows = self._execute("SELECT peer_id,chat_id,title,status,mailing_enabled,added_at,invited_by,removed_at,removal_reason,last_success_at,last_error FROM vk_conversations ORDER BY added_at DESC", fetch=True) or []
|
||||
return [self._conversation_row(row) for row in rows]
|
||||
|
||||
@staticmethod
|
||||
def _conversation_row(row: tuple) -> dict:
|
||||
keys = ("peer_id", "chat_id", "title", "status", "mailing_enabled", "added_at", "invited_by", "removed_at", "removal_reason", "last_success_at", "last_error")
|
||||
return dict(zip(keys, row))
|
||||
|
||||
def create_template(self, name: str, text: str, *, active: bool = True, starts_on: str | None = None, ends_on: str | None = None) -> int:
|
||||
if not text.strip() or len(text) > 4096: raise ValueError("Текст шаблона должен быть от 1 до 4096 символов")
|
||||
rows = self._execute("INSERT INTO vk_message_templates(name,text,active,starts_on,ends_on) VALUES(?,?,?,?,?) RETURNING id", (name.strip() or "Без названия", text.strip(), active, starts_on, ends_on), fetch=True)
|
||||
return int(rows[0][0]) if rows else 0
|
||||
|
||||
def list_templates(self) -> list[dict]:
|
||||
rows = self._execute("SELECT id,name,text,active,starts_on,ends_on,created_at FROM vk_message_templates ORDER BY id DESC", fetch=True) or []
|
||||
return [dict(zip(("id","name","text","active","starts_on","ends_on","created_at"), row)) for row in rows]
|
||||
|
||||
def create_schedule(self, *, template_id: int, peer_id: int, times: list[str], weekdays: list[int] | None = None, timezone_name: str = MOSCOW, active: bool = False, starts_on: str | None = None, ends_on: str | None = None) -> int:
|
||||
clean_times, days, zone = parse_schedule(times=times, weekdays=weekdays, timezone_name=timezone_name)
|
||||
rows = self._execute("INSERT INTO vk_schedules(template_id,peer_id,times_json,weekdays_json,timezone,active,starts_on,ends_on) VALUES(?,?,?,?,?,?,?,?) RETURNING id", (template_id, peer_id, json.dumps(clean_times), json.dumps(days), zone, active, starts_on, ends_on), fetch=True)
|
||||
return int(rows[0][0]) if rows else 0
|
||||
|
||||
def list_schedules(self) -> list[dict]:
|
||||
rows = self._execute("SELECT id,template_id,peer_id,times_json,weekdays_json,timezone,active,starts_on,ends_on FROM vk_schedules ORDER BY id DESC", fetch=True) or []
|
||||
keys = ("id","template_id","peer_id","times","weekdays","timezone","active","starts_on","ends_on")
|
||||
return [{**dict(zip(keys, row[:3] + (json.loads(row[3]), json.loads(row[4])) + row[5:]))} for row in rows]
|
||||
|
||||
def claim_delivery(self, schedule_id: int, planned_for: str) -> bool:
|
||||
try:
|
||||
self._execute("INSERT INTO vk_delivery_attempts(schedule_id,planned_for) VALUES(?,?)", (schedule_id, planned_for))
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def finish_delivery(self, schedule_id: int, planned_for: str, *, success: bool, result: Any = None, error: str | None = None) -> None:
|
||||
self._execute("UPDATE vk_delivery_attempts SET status=?,attempted_at=?,attempts=attempts+1,vk_result=?,error=? WHERE schedule_id=? AND planned_for=?", ("sent" if success else "failed", datetime.now(timezone.utc).isoformat(), json.dumps(result, ensure_ascii=False) if result is not None else None, error[:1000] if error else None, schedule_id, planned_for))
|
||||
if success:
|
||||
self._execute("UPDATE vk_conversations SET last_success_at=?,last_error=NULL WHERE peer_id=(SELECT peer_id FROM vk_schedules WHERE id=?)", (datetime.now(timezone.utc).isoformat(), schedule_id))
|
||||
else:
|
||||
self._execute("UPDATE vk_conversations SET last_error=? WHERE peer_id=(SELECT peer_id FROM vk_schedules WHERE id=?)", (error[:1000] if error else "Ошибка VK", schedule_id))
|
||||
|
||||
|
||||
class VkScheduler:
|
||||
def __init__(self, store: VkConversationStore, send: Callable[[int, str], Any], *, interval: float = 20.0) -> None:
|
||||
self.store, self.send, self.interval = store, send, interval
|
||||
|
||||
@staticmethod
|
||||
def planned_slot(schedule: dict, now: datetime | None = None) -> datetime | None:
|
||||
zone = ZoneInfo(schedule.get("timezone", MOSCOW)); local = (now or datetime.now(timezone.utc)).astimezone(zone).replace(second=0, microsecond=0)
|
||||
if local.isoweekday() not in schedule.get("weekdays", [1,2,3,4,5,6,7]): return None
|
||||
candidates = [local.replace(hour=int(t[:2]), minute=int(t[3:])) for t in schedule.get("times", [])]
|
||||
past = [candidate for candidate in candidates if candidate <= local]
|
||||
return max(past) if past else None
|
||||
|
||||
def run_once(self, now: datetime | None = None) -> int:
|
||||
sent = 0
|
||||
for schedule in self.store.list_schedules():
|
||||
if not schedule.get("active"): continue
|
||||
slot = self.planned_slot(schedule, now)
|
||||
if slot is None or (schedule.get("starts_on") and slot.date().isoformat() < schedule["starts_on"]) or (schedule.get("ends_on") and slot.date().isoformat() > schedule["ends_on"]): continue
|
||||
planned_for = slot.astimezone(timezone.utc).isoformat()
|
||||
if not self.store.claim_delivery(schedule["id"], planned_for): continue
|
||||
template = next((item for item in self.store.list_templates() if item["id"] == schedule["template_id"] and item.get("active")), None)
|
||||
conversation = self.store.get_conversation(schedule["peer_id"])
|
||||
if not template or not conversation or conversation.get("status") != "active" or not conversation.get("mailing_enabled"):
|
||||
self.store.finish_delivery(schedule["id"], planned_for, success=False, error="Рассылка отключена или беседа недоступна")
|
||||
continue
|
||||
try:
|
||||
result = None
|
||||
for attempt in range(3):
|
||||
try:
|
||||
result = self.send(int(schedule["peer_id"]), template["text"])
|
||||
break
|
||||
except (OSError, TimeoutError) as exc:
|
||||
if attempt == 2:
|
||||
raise
|
||||
time.sleep(0.25 * (2 ** attempt))
|
||||
self.store.finish_delivery(schedule["id"], planned_for, success=True, result=result); sent += 1
|
||||
except Exception as exc:
|
||||
self.store.finish_delivery(schedule["id"], planned_for, success=False, error=str(exc))
|
||||
return sent
|
||||
|
||||
def run_forever(self) -> None:
|
||||
while True:
|
||||
try: self.run_once()
|
||||
except Exception: pass
|
||||
time.sleep(self.interval)
|
||||
+46
-1
@@ -22,6 +22,7 @@ from .belki.identity import IdentityDirectory
|
||||
from .belki.image_host import ImageHostClient, ImageHostError
|
||||
from .belki.xlsx_export import build_xlsx
|
||||
from .sudoku import SudokuError, SudokuStore
|
||||
from .belki.vk_scheduler import VkConversationStore
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
@@ -30,6 +31,7 @@ _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] = {}
|
||||
@@ -189,6 +191,13 @@ def sudoku_store() -> SudokuStore:
|
||||
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"}
|
||||
@@ -441,6 +450,18 @@ class Handler(BaseHTTPRequestHandler):
|
||||
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:
|
||||
@@ -483,7 +504,7 @@ class Handler(BaseHTTPRequestHandler):
|
||||
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/applications") and not is_sudoku_create and not is_sudoku_regenerate:
|
||||
"/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:
|
||||
@@ -546,6 +567,14 @@ class Handler(BaseHTTPRequestHandler):
|
||||
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))
|
||||
@@ -599,6 +628,22 @@ class Handler(BaseHTTPRequestHandler):
|
||||
def do_PATCH(self) -> None: # noqa: N802
|
||||
"""Меняет статус новой заявки через PATCH API."""
|
||||
parsed = urlparse(self.path)
|
||||
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))
|
||||
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": "Не найдено"})
|
||||
|
||||
@@ -136,3 +136,4 @@ flowchart LR
|
||||
## Ограничения развёртывания
|
||||
|
||||
Исходники ограничивают размер и параллелизм запросов, но TLS и сетевой rate limit должны обеспечиваться на внешнем прокси. Перед следующим production rollout необходимо убедиться, что админский путь недоступен по plaintext HTTP и что `belki-web` не публикуется в обход этого прокси.
|
||||
- VK scheduler: `BelkiBot.handle_event` -> `VkConversationStore` (реестр) -> `VkScheduler` (timezone, claim `schedule_id+planned_for`, VK `messages.send`); админка `/admin` -> `/api/admin/vk/*`.
|
||||
@@ -120,3 +120,4 @@
|
||||
# Обновление 2026-08-16: несколько котят
|
||||
|
||||
Калькулятор прокачки принимает `extra_kittens` из веб-формы, API и VK-команды. Общая выплата сопровождающему не суммирует полную ставку на каждого котёнка: первый подопечный использует базовый коэффициент, второй — множитель 1,5, каждый следующий — дополнительный множитель 1,15. Сайт добавляет строки дополнительных котят динамически; VK поддерживает сегмент `доп. котята: Имя [ID], Имя2 [ID]`.
|
||||
- 2026-09-06: добавлен `app/belki/vk_scheduler.py` — реестр VK-бесед, шаблоны, ежедневные/недельные расписания и уникальные delivery-attempts; scheduler запускается daemon-потоком `belki-bot`, админские API доступны под `/api/admin/vk/*`.
|
||||
@@ -0,0 +1,31 @@
|
||||
import tempfile
|
||||
import unittest
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from app.belki.vk_scheduler import VkConversationStore, VkScheduler, conversation_peer_id, parse_schedule
|
||||
|
||||
|
||||
class VkSchedulerTests(unittest.TestCase):
|
||||
def test_peer_and_schedule_validation(self):
|
||||
self.assertEqual(conversation_peer_id(3), 2000000003)
|
||||
self.assertEqual(parse_schedule(times=["09:00", "09:00"], weekdays=[1]), (["09:00"], [1], "Europe/Moscow"))
|
||||
with self.assertRaises(ValueError): parse_schedule(times=["25:00"])
|
||||
|
||||
def test_delivery_claim_is_idempotent(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
store = VkConversationStore(sqlite_path=Path(directory) / "vk.sqlite3")
|
||||
store.upsert_conversation(peer_id=2000000003, chat_id=3)
|
||||
store._execute("UPDATE vk_conversations SET mailing_enabled=1 WHERE peer_id=?", (2000000003,))
|
||||
template_id = store.create_template("Тест", "Сообщение")
|
||||
store.create_schedule(template_id=template_id, peer_id=2000000003, times=["12:00"], weekdays=[1], active=True)
|
||||
calls = []
|
||||
scheduler = VkScheduler(store, lambda peer, text: calls.append((peer, text)) or {"message_id": 1})
|
||||
now = datetime(2026, 9, 7, 12, 1, tzinfo=timezone.utc)
|
||||
self.assertEqual(scheduler.run_once(now), 1)
|
||||
self.assertEqual(scheduler.run_once(now), 0)
|
||||
self.assertEqual(calls, [(2000000003, "Сообщение")])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+10
-1
@@ -91,6 +91,7 @@
|
||||
<nav class="tabs" aria-label="Раздел админской панели">
|
||||
<button class="admin-tab tab" type="button" data-admin-view="reports" aria-selected="true">Отчёты</button>
|
||||
<button class="admin-tab tab" type="button" data-admin-view="applications" aria-selected="false">Заявки</button>
|
||||
<button class="admin-tab tab" type="button" data-admin-view="vk" aria-selected="false">Беседы VK</button>
|
||||
</nav>
|
||||
<section id="reportsView" class="admin-section">
|
||||
<header class="topbar">
|
||||
@@ -115,6 +116,11 @@
|
||||
<button id="load" type="button">Обновить</button>
|
||||
<a id="reportsExport" class="export-link" href="/api/admin/calculations.xlsx">Скачать XLSX</a>
|
||||
</section>
|
||||
<section id="vkView" class="admin-section hidden" aria-labelledby="vkTitle">
|
||||
<header class="topbar"><div><h2 id="vkTitle">Беседы VK</h2><p class="intro">Реестр бесед и расписания сообщений. Время указано в часовом поясе расписания.</p></div><div class="record-count" id="vkCount">Не загружено</div></header>
|
||||
<section class="controls"><button id="loadVk" type="button">Обновить</button><label class="control-group">Текст шаблона<input id="vkTemplateText" maxlength="4096" placeholder="Сообщение для рассылки"></label><button id="saveVkTemplate" type="button">Создать шаблон</button></section>
|
||||
<p class="error" id="vkError" role="alert"></p><div class="table-wrap"><table><thead><tr><th>Беседа</th><th>Статус</th><th>Рассылка</th><th>Добавлена</th><th>Последняя отправка</th><th>Ошибка</th></tr></thead><tbody id="vkRows"><tr><td class="empty" colspan="6">Загрузка…</td></tr></tbody></table></div>
|
||||
</section>
|
||||
<p class="error" id="error" role="alert"></p>
|
||||
<div class="table-wrap"><table><thead><tr><th>Кот</th><th>Котята</th><th>Фото</th><th>Дата (UTC+3)</th><th>Сообщение</th><th>Автор</th><th>ID</th><th></th></tr></thead><tbody id="rows"><tr><td class="empty" colspan="8">Загрузка истории…</td></tr></tbody></table></div>
|
||||
</section>
|
||||
@@ -150,6 +156,8 @@
|
||||
const galleryCounter = document.querySelector('#galleryCounter');
|
||||
let items = [], galleryPhotos = [], galleryIndex = 0, activeCategory = 'all';
|
||||
let applications = [], activeApplicationStatus = 'pending', selectedApplicationId = null, activeAdminView = 'reports', updatesSocket = null, updatesRetry = null;
|
||||
async function loadVk() { const errorNode=document.querySelector('#vkError'); errorNode.textContent=''; try { const response=await fetch('/api/admin/vk/conversations'); const data=await response.json(); if(!response.ok) throw new Error(data.error||'Не удалось загрузить беседы'); const rowsNode=document.querySelector('#vkRows'); rowsNode.replaceChildren(); document.querySelector('#vkCount').textContent=`${(data.items||[]).length} бесед`; (data.items||[]).forEach(item=>{const row=document.createElement('tr'); const name=document.createElement('td'); name.textContent=`${item.title||'Без названия'} · ${item.peer_id} / chat ${item.chat_id}`; const status=document.createElement('td'); status.textContent=item.status||'—'; const toggle=document.createElement('button'); toggle.type='button'; toggle.textContent=item.mailing_enabled?'Выключить':'Включить'; toggle.onclick=async()=>{toggle.disabled=true; await fetch(`/api/admin/vk/conversations/${item.peer_id}`,{method:'PATCH',headers:{'Content-Type':'application/json'},body:JSON.stringify({mailing_enabled:!item.mailing_enabled})}); loadVk();}; const mailing=document.createElement('td'); mailing.append(toggle); const added=document.createElement('td'); added.textContent=displayDate(item.added_at); const success=document.createElement('td'); success.textContent=displayDate(item.last_success_at); const lastError=document.createElement('td'); lastError.textContent=item.last_error||item.removal_reason||'—'; row.append(name,status,mailing,added,success,lastError); rowsNode.append(row); }); } catch(err) { errorNode.textContent=err.message; } }
|
||||
async function createVkTemplate() { const textValue=document.querySelector('#vkTemplateText').value.trim(); if(!textValue)return; const response=await fetch('/api/admin/vk/templates',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({name:'Шаблон VK',text:textValue,active:true})}); if(!response.ok){const data=await response.json();document.querySelector('#vkError').textContent=data.error||'Не удалось создать шаблон';return;} document.querySelector('#vkTemplateText').value=''; }
|
||||
|
||||
// Extracts the primary person identity from a stored report payload.
|
||||
function personData(input) { return {name: input.escort_name || input.character_name || '', id: input.escort_id || input.character_id || ''}; }
|
||||
@@ -208,10 +216,11 @@
|
||||
// Closes the photo gallery dialog.
|
||||
function closeGallery() { if (galleryDialog.close) galleryDialog.close(); else galleryDialog.removeAttribute('open'); }
|
||||
// Switches between report and application admin views.
|
||||
function selectAdminView(view) { activeAdminView = view; document.querySelector('#reportsView').classList.toggle('hidden', view !== 'reports'); document.querySelector('#applicationsView').classList.toggle('hidden', view !== 'applications'); document.querySelectorAll('.admin-tab').forEach(tab => tab.setAttribute('aria-selected', String(tab.dataset.adminView === view))); }
|
||||
function selectAdminView(view) { activeAdminView = view; document.querySelector('#reportsView').classList.toggle('hidden', view !== 'reports'); document.querySelector('#applicationsView').classList.toggle('hidden', view !== 'applications'); document.querySelector('#vkView').classList.toggle('hidden', view !== 'vk'); document.querySelectorAll('.admin-tab').forEach(tab => tab.setAttribute('aria-selected', String(tab.dataset.adminView === view))); if(view==='vk')loadVk(); }
|
||||
authForm.addEventListener('submit', authenticate); loadButton.addEventListener('click', load); sort.addEventListener('change', render); direction.addEventListener('change', render); catFilter.addEventListener('change', load); kittenFilter.addEventListener('change', load); [reportPeriod, reportDateFrom, reportDateTo].forEach(control => control.addEventListener('change', load)); document.querySelectorAll('[data-category]').forEach(tab => tab.addEventListener('click', () => { activeCategory = tab.dataset.category; document.querySelectorAll('[data-category]').forEach(item => item.setAttribute('aria-selected', String(item === tab))); load(); })); document.querySelector('#closeGallery').addEventListener('click', closeGallery); document.querySelector('#prevPhoto').addEventListener('click', () => { galleryIndex = (galleryIndex - 1 + galleryPhotos.length) % galleryPhotos.length; updateGallery(); }); document.querySelector('#nextPhoto').addEventListener('click', () => { galleryIndex = (galleryIndex + 1) % galleryPhotos.length; updateGallery(); }); document.addEventListener('keydown', event => { if (!galleryDialog.open) return; if (event.key === 'Escape') closeGallery(); if (event.key === 'ArrowLeft') document.querySelector('#prevPhoto').click(); if (event.key === 'ArrowRight') document.querySelector('#nextPhoto').click(); });
|
||||
document.querySelector('#loadApplications').addEventListener('click', loadApplications); [applicationPeriod, applicationDateFrom, applicationDateTo].forEach(control => control.addEventListener('change', loadApplications)); document.querySelectorAll('.application-tab').forEach(tab => tab.addEventListener('click', () => { activeApplicationStatus = tab.dataset.status; document.querySelectorAll('.application-tab').forEach(item => item.setAttribute('aria-selected', String(item === tab))); loadApplications(); }));
|
||||
document.querySelectorAll('.admin-tab').forEach(tab => tab.addEventListener('click', () => selectAdminView(tab.dataset.adminView)));
|
||||
document.querySelector('#loadVk').addEventListener('click', loadVk); document.querySelector('#saveVkTemplate').addEventListener('click', createVkTemplate);
|
||||
restoreAdminSession();
|
||||
</script>
|
||||
</body>
|
||||
|
||||
Reference in new issue
Block a user