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
+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": "Не найдено"})
|
||||
|
||||
Reference in new issue
Block a user