91 lines
2.7 KiB
Python
91 lines
2.7 KiB
Python
|
|
import json
|
|
from datetime import datetime, timezone, timedelta
|
|
from core.state import db, ws_registry, _KITTYREC_SYSTEM_PID
|
|
from core.builders import now_iso
|
|
|
|
_HANDLERS = {}
|
|
|
|
|
|
def reply_handler(name):
|
|
def decorator(fn):
|
|
_HANDLERS[name] = fn
|
|
return fn
|
|
return decorator
|
|
|
|
|
|
def send_system_msg(to_pid: int, text: str) -> int:
|
|
msg_id = db.send_message(_KITTYREC_SYSTEM_PID, to_pid, 30, text)
|
|
ws_registry.send(to_pid, {"Id": 2, "Msg": {
|
|
"Id": msg_id, "FromPlayerId": _KITTYREC_SYSTEM_PID,
|
|
"SentTime": now_iso(), "Type": 30, "Data": text,
|
|
"RoomId": None, "PlayerEventId": None,
|
|
}})
|
|
return msg_id
|
|
|
|
|
|
def send_and_await(to_pid: int, text: str, handler_type: str, context: dict = None, expires_in: int = 86400) -> None:
|
|
send_system_msg(to_pid, text)
|
|
_register(to_pid, handler_type, context or {}, expires_in)
|
|
|
|
|
|
def has_pending(pid: int) -> bool:
|
|
return _get_pending(pid) is not None
|
|
|
|
|
|
def dispatch_reply(pid: int, text: str) -> bool:
|
|
row = _get_pending(pid)
|
|
if not row:
|
|
return False
|
|
|
|
handler_type = row["handler_type"]
|
|
context = json.loads(row["context"] or "{}")
|
|
fn = _HANDLERS.get(handler_type)
|
|
|
|
_clear(pid)
|
|
|
|
if fn is None:
|
|
print(f"[SysMsg] No handler registered for type '{handler_type}' (pid={pid})")
|
|
return False
|
|
|
|
def reply(reply_text, next_handler=None, next_context=None, expires_in=86400):
|
|
send_system_msg(pid, reply_text)
|
|
if next_handler:
|
|
_register(pid, next_handler, next_context if next_context is not None else context, expires_in)
|
|
|
|
fn(pid, text, context, reply)
|
|
return True
|
|
|
|
|
|
def _register(pid: int, handler_type: str, context: dict, expires_in: int) -> None:
|
|
conn = db._get_conn()
|
|
if expires_in:
|
|
expires_at = (datetime.now(timezone.utc) + timedelta(seconds=expires_in)).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
else:
|
|
expires_at = None
|
|
conn.execute(
|
|
"INSERT OR REPLACE INTO system_reply_queue (profile_id, handler_type, context, expires_at, created_at) "
|
|
"VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)",
|
|
(pid, handler_type, json.dumps(context), expires_at),
|
|
)
|
|
conn.commit()
|
|
|
|
|
|
def _get_pending(pid: int):
|
|
conn = db._get_conn()
|
|
row = conn.execute("SELECT * FROM system_reply_queue WHERE profile_id=?", (pid,)).fetchone()
|
|
if row is None:
|
|
return None
|
|
if row["expires_at"]:
|
|
now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
if now > row["expires_at"]:
|
|
_clear(pid)
|
|
return None
|
|
return row
|
|
|
|
|
|
def _clear(pid: int) -> None:
|
|
conn = db._get_conn()
|
|
conn.execute("DELETE FROM system_reply_queue WHERE profile_id=?", (pid,))
|
|
conn.commit()
|