Upload files to "core"
This commit is contained in:
59
core/password_crypto.py
Normal file
59
core/password_crypto.py
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
import os
|
||||||
|
import socket
|
||||||
|
import hashlib
|
||||||
|
import base64
|
||||||
|
from cryptography.fernet import Fernet
|
||||||
|
|
||||||
|
_SECRET_KEY_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), ".secret_key")
|
||||||
|
_fernet = None
|
||||||
|
|
||||||
|
|
||||||
|
def _get_fernet():
|
||||||
|
global _fernet
|
||||||
|
if _fernet is not None:
|
||||||
|
return _fernet
|
||||||
|
with open(_SECRET_KEY_PATH, "rb") as f:
|
||||||
|
secret = f.read().strip()
|
||||||
|
hostname = socket.gethostname().encode()
|
||||||
|
salt = hashlib.sha256(hostname + b":kittyrec-pw-enc").digest()
|
||||||
|
derived = hashlib.pbkdf2_hmac("sha256", secret, salt, 480_000)
|
||||||
|
fernet_key = base64.urlsafe_b64encode(derived[:32])
|
||||||
|
_fernet = Fernet(fernet_key)
|
||||||
|
return _fernet
|
||||||
|
|
||||||
|
|
||||||
|
def encrypt_password(plaintext: str) -> str:
|
||||||
|
token = _get_fernet().encrypt(plaintext.encode("utf-8"))
|
||||||
|
return "enc:" + token.decode("ascii")
|
||||||
|
|
||||||
|
|
||||||
|
def decrypt_password(stored: str) -> str | None:
|
||||||
|
if not stored or not stored.startswith("enc:"):
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
token = stored[4:].encode("ascii")
|
||||||
|
return _get_fernet().decrypt(token).decode("utf-8")
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def check_password(stored: str, candidate: str) -> bool:
|
||||||
|
if not stored:
|
||||||
|
return False
|
||||||
|
if stored.startswith("enc:"):
|
||||||
|
plaintext = decrypt_password(stored)
|
||||||
|
return plaintext is not None and plaintext == candidate
|
||||||
|
if stored.startswith(("pbkdf2:", "scrypt:", "argon2:")):
|
||||||
|
from werkzeug.security import check_password_hash
|
||||||
|
return check_password_hash(stored, candidate)
|
||||||
|
return stored == candidate
|
||||||
|
|
||||||
|
|
||||||
|
def has_password(stored: str) -> bool:
|
||||||
|
if not stored:
|
||||||
|
return False
|
||||||
|
if stored.startswith("enc:"):
|
||||||
|
return True
|
||||||
|
if stored.startswith(("pbkdf2:", "scrypt:", "argon2:")):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
66
core/profanity.py
Normal file
66
core/profanity.py
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
import re
|
||||||
|
import unicodedata
|
||||||
|
from better_profanity import profanity as _bp
|
||||||
|
|
||||||
|
_bp.load_censor_words()
|
||||||
|
|
||||||
|
_EXTRA_WORDS = [
|
||||||
|
'kys', 'kms', 'jewishdoc', 'fck', 'fk',
|
||||||
|
]
|
||||||
|
_bp.add_censor_words(_EXTRA_WORDS)
|
||||||
|
|
||||||
|
_HATE_WORDS = {'kys', 'kms'}
|
||||||
|
|
||||||
|
_HATE_PATTERNS = [
|
||||||
|
r"n[i1!|][gq9][gq9][e3]r",
|
||||||
|
r"n[i1!|][gq9][gq9][ae3]",
|
||||||
|
r"n[i1!|][gq9][gq9][ae3][sz]",
|
||||||
|
r"f[a4][gq9][gq9][o0]t",
|
||||||
|
r"f[a4][gq9][gq9][o0]t[sz]",
|
||||||
|
r"f[a4][gq9]",
|
||||||
|
r"ch[i1][nk][gq][sz]?",
|
||||||
|
r"g[o0][o0]k[sz]?",
|
||||||
|
r"sp[i1][cks][sz]?",
|
||||||
|
r"w[e3]tb[a4][cks][gq][sz]?",
|
||||||
|
r"k[i1][ck][e3][sz]?",
|
||||||
|
r"j[e3]w[sz]?\b",
|
||||||
|
r"h[e3][e3]b[sz]?",
|
||||||
|
r"cr[a4][cks][gq][e3]r[sz]?",
|
||||||
|
r"j[i1][gq][a4]b[o0][o0]",
|
||||||
|
r"t[o0]w[e3]lh[e3][a4]d",
|
||||||
|
r"r[e3]t[a4]rd",
|
||||||
|
r"tr[a4]nn[yi1][e3]?[sz]?",
|
||||||
|
r"[sz]h[e3]m[a4][l1][e3]",
|
||||||
|
]
|
||||||
|
_HATE_RE = re.compile(
|
||||||
|
"|".join(r"(?<!\w)(?:" + p + r")(?!\w)" for p in _HATE_PATTERNS),
|
||||||
|
re.IGNORECASE,
|
||||||
|
)
|
||||||
|
|
||||||
|
def _normalize(text: str) -> str:
|
||||||
|
normalized = unicodedata.normalize('NFKD', text)
|
||||||
|
ascii_only = normalized.encode('ascii', 'ignore').decode('ascii')
|
||||||
|
return ascii_only
|
||||||
|
|
||||||
|
def _squish(s: str) -> str:
|
||||||
|
s = re.sub(r'[^a-zA-Z0-9]', '', s)
|
||||||
|
s = re.sub(r'(.)\1{2,}', r'\1', s)
|
||||||
|
return s
|
||||||
|
|
||||||
|
def is_clean(text: str) -> bool:
|
||||||
|
for variant in (text, _normalize(text)):
|
||||||
|
if _bp.contains_profanity(variant):
|
||||||
|
return False
|
||||||
|
squished = _squish(variant)
|
||||||
|
if squished and _bp.contains_profanity(squished):
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
def is_hate_speech(text: str) -> bool:
|
||||||
|
lower = text.lower()
|
||||||
|
for word in _HATE_WORDS:
|
||||||
|
if re.search(r'(?<!\w)' + re.escape(word) + r'(?!\w)', lower):
|
||||||
|
return True
|
||||||
|
if _HATE_RE.search(text):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
351
core/state.py
Normal file
351
core/state.py
Normal file
@@ -0,0 +1,351 @@
|
|||||||
|
|
||||||
|
import json
|
||||||
|
import threading
|
||||||
|
|
||||||
|
from .database import Database
|
||||||
|
from .constants import KNOWN_ACTIVITIES, DORM_ROOM_GUID
|
||||||
|
from .config import server as _server_cfg
|
||||||
|
|
||||||
|
APP_VERSION = _server_cfg.get("app_version", "20180810")
|
||||||
|
|
||||||
|
db = Database()
|
||||||
|
|
||||||
|
maintenance_mode: bool = False
|
||||||
|
maintenance_lock = threading.Lock()
|
||||||
|
maintenance_exempt: set[int] = set()
|
||||||
|
|
||||||
|
server_region: str = "us"
|
||||||
|
|
||||||
|
class GameSession:
|
||||||
|
_counter = 1
|
||||||
|
_counter_lock = threading.Lock()
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _new_id(cls) -> int:
|
||||||
|
with cls._counter_lock:
|
||||||
|
sid = cls._counter
|
||||||
|
cls._counter += 1
|
||||||
|
return sid
|
||||||
|
|
||||||
|
def __init__(self, activity_level_id: str, name: str, activity_key: str = "room",
|
||||||
|
private: bool = False, sandbox: bool = False, creator_pid: int | None = 1):
|
||||||
|
self.session_id = GameSession._new_id()
|
||||||
|
self.activity_level_id = activity_level_id
|
||||||
|
self.name = name
|
||||||
|
self.activity_key = activity_key
|
||||||
|
self.private = private
|
||||||
|
self.sandbox = sandbox
|
||||||
|
self.creator_player_id = creator_pid
|
||||||
|
self.max_capacity = 20
|
||||||
|
self.game_in_progress = False
|
||||||
|
self.players: set[int] = set()
|
||||||
|
self.photon_room_id = f"{activity_key}_{self.session_id}"
|
||||||
|
self.rec_room_id: int | None = None
|
||||||
|
self.special_gamemode: int = 0
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_full(self) -> bool:
|
||||||
|
return len(self.players) >= self.max_capacity
|
||||||
|
|
||||||
|
def to_dict(self) -> dict:
|
||||||
|
asset_url = ""
|
||||||
|
scene_name = ""
|
||||||
|
room = None
|
||||||
|
if self.rec_room_id:
|
||||||
|
try:
|
||||||
|
room = db.get_room(self.rec_room_id)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
if not room and self.activity_level_id:
|
||||||
|
try:
|
||||||
|
room = db.get_room_by_activity(self.activity_level_id)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
if room:
|
||||||
|
asset_url = room.get("UnityAssetBundleUrl", "")
|
||||||
|
scene_name = room.get("UnitySceneName", "")
|
||||||
|
return {
|
||||||
|
"SpecialGamemode": self.special_gamemode,
|
||||||
|
"GameSessionId": self.session_id,
|
||||||
|
"RegionId": server_region,
|
||||||
|
"RoomId": self.photon_room_id,
|
||||||
|
"EventId": None,
|
||||||
|
"RecRoomId": self.rec_room_id,
|
||||||
|
"CreatorPlayerId": self.creator_player_id if self.rec_room_id else None,
|
||||||
|
"Name": self.name,
|
||||||
|
"ActivityLevelId": self.activity_level_id,
|
||||||
|
"Private": self.private and self.activity_level_id != DORM_ROOM_GUID,
|
||||||
|
"Sandbox": self.sandbox,
|
||||||
|
"SupportsScreens": True,
|
||||||
|
"SupportsVR": True,
|
||||||
|
"GameInProgress": self.game_in_progress,
|
||||||
|
"MaxCapacity": self.max_capacity,
|
||||||
|
"IsFull": self.is_full,
|
||||||
|
"UnityAssetBundleUrl": asset_url,
|
||||||
|
"UnitySceneName": scene_name,
|
||||||
|
}
|
||||||
|
|
||||||
|
def to_v1_dict(self) -> dict:
|
||||||
|
return {
|
||||||
|
"Id": self.photon_room_id,
|
||||||
|
"AppVersion": APP_VERSION,
|
||||||
|
"Activity": self.activity_key,
|
||||||
|
"Private": self.private,
|
||||||
|
"AvailableSpace": max(0, self.max_capacity - len(self.players)),
|
||||||
|
"GameInProgress": self.game_in_progress,
|
||||||
|
"PlayerIds": list(self.players),
|
||||||
|
}
|
||||||
|
|
||||||
|
class SessionManager:
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self._sessions: dict[int, GameSession] = {}
|
||||||
|
self._player_session: dict[int, int] = {}
|
||||||
|
self._lock = threading.Lock()
|
||||||
|
|
||||||
|
def get_player_session(self, player_id: int) -> GameSession | None:
|
||||||
|
with self._lock:
|
||||||
|
sid = self._player_session.get(player_id)
|
||||||
|
return self._sessions.get(sid) if sid is not None else None
|
||||||
|
|
||||||
|
def get_session(self, session_id: int) -> GameSession | None:
|
||||||
|
with self._lock:
|
||||||
|
return self._sessions.get(session_id)
|
||||||
|
|
||||||
|
def join_room(self, player_id: int, activity_level_id: str, name: str,
|
||||||
|
activity_key: str = "room", private: bool = False,
|
||||||
|
sandbox: bool = False, rec_room_id: int | None = None,
|
||||||
|
creator_pid: int | None = None) -> GameSession:
|
||||||
|
with self._lock:
|
||||||
|
self._leave_locked(player_id)
|
||||||
|
is_dorm = (activity_level_id == DORM_ROOM_GUID)
|
||||||
|
if private or sandbox or is_dorm:
|
||||||
|
s = GameSession(activity_level_id, name, activity_key,
|
||||||
|
private=private or is_dorm, sandbox=sandbox, creator_pid=creator_pid or player_id)
|
||||||
|
else:
|
||||||
|
best: GameSession | None = None
|
||||||
|
for existing in self._sessions.values():
|
||||||
|
if (existing.activity_level_id == activity_level_id
|
||||||
|
and existing.rec_room_id == rec_room_id
|
||||||
|
and not existing.private
|
||||||
|
and not existing.is_full):
|
||||||
|
if best is None or len(existing.players) > len(best.players):
|
||||||
|
best = existing
|
||||||
|
s = best or GameSession(activity_level_id, name, activity_key,
|
||||||
|
private=False, sandbox=False, creator_pid=creator_pid or player_id)
|
||||||
|
s.rec_room_id = rec_room_id
|
||||||
|
if s.special_gamemode == 0:
|
||||||
|
try:
|
||||||
|
if rec_room_id:
|
||||||
|
s.special_gamemode = db.get_special_gamemode_for_room(rec_room_id)
|
||||||
|
else:
|
||||||
|
s.special_gamemode = db.get_gamemode_default(activity_level_id)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
s.players.add(player_id)
|
||||||
|
self._sessions[s.session_id] = s
|
||||||
|
self._player_session[player_id] = s.session_id
|
||||||
|
return s
|
||||||
|
|
||||||
|
def leave_session(self, player_id: int) -> None:
|
||||||
|
with self._lock:
|
||||||
|
self._leave_locked(player_id)
|
||||||
|
|
||||||
|
def _leave_locked(self, player_id: int) -> None:
|
||||||
|
sid = self._player_session.pop(player_id, None)
|
||||||
|
if sid is not None and sid in self._sessions:
|
||||||
|
s = self._sessions[sid]
|
||||||
|
s.players.discard(player_id)
|
||||||
|
if not s.players:
|
||||||
|
del self._sessions[sid]
|
||||||
|
|
||||||
|
def join_session_of(self, joining_pid: int, target_pid: int, party_size: int = 1) -> GameSession | None:
|
||||||
|
with self._lock:
|
||||||
|
target_sid = self._player_session.get(target_pid)
|
||||||
|
if target_sid is None:
|
||||||
|
return None
|
||||||
|
target_session = self._sessions.get(target_sid)
|
||||||
|
if target_session is None:
|
||||||
|
return None
|
||||||
|
available = target_session.max_capacity - len(target_session.players)
|
||||||
|
if available < max(1, party_size):
|
||||||
|
return None
|
||||||
|
self._leave_locked(joining_pid)
|
||||||
|
target_session.players.add(joining_pid)
|
||||||
|
self._player_session[joining_pid] = target_sid
|
||||||
|
return target_session
|
||||||
|
|
||||||
|
def join_session_by_id(self, joining_pid: int, session_id: int) -> GameSession | None:
|
||||||
|
with self._lock:
|
||||||
|
target = self._sessions.get(session_id)
|
||||||
|
if target is None or target.is_full:
|
||||||
|
return None
|
||||||
|
self._leave_locked(joining_pid)
|
||||||
|
target.players.add(joining_pid)
|
||||||
|
self._player_session[joining_pid] = session_id
|
||||||
|
return target
|
||||||
|
|
||||||
|
def modify_session(self, session_id: int, **kwargs) -> GameSession | None:
|
||||||
|
with self._lock:
|
||||||
|
s = self._sessions.get(session_id)
|
||||||
|
if s is None:
|
||||||
|
return None
|
||||||
|
for key, val in kwargs.items():
|
||||||
|
if key == "name":
|
||||||
|
s.name = val
|
||||||
|
elif key == "activity_level_id":
|
||||||
|
s.activity_level_id = val
|
||||||
|
name, akey, _ = KNOWN_ACTIVITIES.get(val, ("Custom Room", "custom", False))
|
||||||
|
s.activity_key = akey
|
||||||
|
s.name = name
|
||||||
|
elif key == "max_capacity":
|
||||||
|
s.max_capacity = max(1, min(40, int(val)))
|
||||||
|
elif key == "game_in_progress":
|
||||||
|
s.game_in_progress = bool(val)
|
||||||
|
elif key == "private":
|
||||||
|
s.private = bool(val)
|
||||||
|
elif key == "special_gamemode":
|
||||||
|
s.special_gamemode = int(val)
|
||||||
|
return s
|
||||||
|
|
||||||
|
def all_public_sessions(self) -> list[GameSession]:
|
||||||
|
with self._lock:
|
||||||
|
return [s for s in self._sessions.values() if not s.private and s.players]
|
||||||
|
|
||||||
|
def all_sessions(self) -> list[GameSession]:
|
||||||
|
with self._lock:
|
||||||
|
return [s for s in self._sessions.values() if s.players]
|
||||||
|
|
||||||
|
class ConnectionRegistry:
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self._conns: dict[int, object] = {}
|
||||||
|
self._screen_mode: dict[int, bool] = {}
|
||||||
|
self._lock = threading.Lock()
|
||||||
|
|
||||||
|
def register(self, player_id: int, ws) -> None:
|
||||||
|
with self._lock:
|
||||||
|
old_ws = self._conns.get(player_id)
|
||||||
|
self._conns[player_id] = ws
|
||||||
|
self._screen_mode.pop(player_id, None)
|
||||||
|
if old_ws is not None and old_ws is not ws:
|
||||||
|
try:
|
||||||
|
old_ws.close()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def set_screen_mode(self, player_id: int, in_screen_mode: bool) -> None:
|
||||||
|
with self._lock:
|
||||||
|
self._screen_mode[player_id] = in_screen_mode
|
||||||
|
|
||||||
|
def is_screen_mode(self, player_id: int) -> bool:
|
||||||
|
with self._lock:
|
||||||
|
return self._screen_mode.get(player_id, False)
|
||||||
|
|
||||||
|
def unregister(self, player_id: int, ws=None) -> bool:
|
||||||
|
with self._lock:
|
||||||
|
if ws is None or self._conns.get(player_id) is ws:
|
||||||
|
self._conns.pop(player_id, None)
|
||||||
|
self._screen_mode.pop(player_id, None)
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
def close_and_unregister(self, player_id: int) -> bool:
|
||||||
|
with self._lock:
|
||||||
|
ws = self._conns.pop(player_id, None)
|
||||||
|
if ws is None:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
ws.close()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return True
|
||||||
|
|
||||||
|
def spam_and_close(self, player_id: int, msg: dict, count: int = 10) -> bool:
|
||||||
|
import time as _time
|
||||||
|
with self._lock:
|
||||||
|
ws = self._conns.pop(player_id, None)
|
||||||
|
if ws is None:
|
||||||
|
return False
|
||||||
|
payload = json.dumps(msg)
|
||||||
|
for _ in range(count):
|
||||||
|
try:
|
||||||
|
ws.send(payload)
|
||||||
|
_time.sleep(0.05)
|
||||||
|
except Exception:
|
||||||
|
break
|
||||||
|
try:
|
||||||
|
ws.close()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return True
|
||||||
|
|
||||||
|
_EXCLUDE_PIDS = {23}
|
||||||
|
|
||||||
|
def is_connected(self, player_id: int) -> bool:
|
||||||
|
with self._lock:
|
||||||
|
return player_id in self._conns
|
||||||
|
|
||||||
|
def connected_ids(self) -> list[int]:
|
||||||
|
with self._lock:
|
||||||
|
return [pid for pid in self._conns if pid not in self._EXCLUDE_PIDS]
|
||||||
|
|
||||||
|
def player_count(self) -> int:
|
||||||
|
with self._lock:
|
||||||
|
return sum(1 for pid in self._conns if pid not in self._EXCLUDE_PIDS)
|
||||||
|
|
||||||
|
def send(self, player_id: int, msg: dict) -> bool:
|
||||||
|
with self._lock:
|
||||||
|
ws = self._conns.get(player_id)
|
||||||
|
if ws is None:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
ws.send(json.dumps(msg))
|
||||||
|
return True
|
||||||
|
except Exception:
|
||||||
|
with self._lock:
|
||||||
|
self._conns.pop(player_id, None)
|
||||||
|
return False
|
||||||
|
|
||||||
|
def broadcast(self, msg: dict, exclude_pid: int | None = None) -> None:
|
||||||
|
with self._lock:
|
||||||
|
targets = list(self._conns.items())
|
||||||
|
for pid, ws in targets:
|
||||||
|
if pid == exclude_pid:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
ws.send(json.dumps(msg))
|
||||||
|
except Exception:
|
||||||
|
with self._lock:
|
||||||
|
self._conns.pop(pid, None)
|
||||||
|
|
||||||
|
session_mgr = SessionManager()
|
||||||
|
ws_registry = ConnectionRegistry()
|
||||||
|
|
||||||
|
_KITTYREC_SYSTEM_PID = 23
|
||||||
|
|
||||||
|
|
||||||
|
class _NullWs:
|
||||||
|
def send(self, _data):
|
||||||
|
pass
|
||||||
|
def close(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
_system_null_ws = _NullWs()
|
||||||
|
|
||||||
|
|
||||||
|
def _system_account_thread():
|
||||||
|
import time
|
||||||
|
ws_registry.register(_KITTYREC_SYSTEM_PID, _system_null_ws)
|
||||||
|
print(f"[System] KittyRec account (pid={_KITTYREC_SYSTEM_PID}) is now online")
|
||||||
|
while True:
|
||||||
|
time.sleep(5)
|
||||||
|
with ws_registry._lock:
|
||||||
|
if ws_registry._conns.get(_KITTYREC_SYSTEM_PID) is not _system_null_ws:
|
||||||
|
ws_registry._conns[_KITTYREC_SYSTEM_PID] = _system_null_ws
|
||||||
|
|
||||||
|
|
||||||
|
def bring_system_account_online():
|
||||||
|
t = threading.Thread(target=_system_account_thread, daemon=True, name="kittyrec-system")
|
||||||
|
t.start()
|
||||||
90
core/system_messages.py
Normal file
90
core/system_messages.py
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
|
||||||
|
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()
|
||||||
81
core/ws_helpers.py
Normal file
81
core/ws_helpers.py
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
|
||||||
|
from .state import ws_registry, db
|
||||||
|
|
||||||
|
|
||||||
|
def push_presence(player_id: int, session=None, online: bool = True) -> None:
|
||||||
|
ws_registry.broadcast({
|
||||||
|
"Id": 12,
|
||||||
|
"Msg": {
|
||||||
|
"PlayerId": player_id,
|
||||||
|
"IsOnline": online,
|
||||||
|
"InScreenMode": ws_registry.is_screen_mode(player_id),
|
||||||
|
"GameSession": session.to_dict() if session else None,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
def push_gift(player_id: int, gift: dict) -> bool:
|
||||||
|
sent = ws_registry.send(player_id, {"Id": 30, "Msg": gift})
|
||||||
|
print(f"[Push] Gift id={gift.get('Id')} → pid={player_id} sent={sent}")
|
||||||
|
if sent and gift.get("Id"):
|
||||||
|
db.mark_gift_pushed(gift["Id"])
|
||||||
|
return sent
|
||||||
|
|
||||||
|
def push_store_balance(player_id: int, new_balance: int, currency_type: int, amount: int) -> None:
|
||||||
|
ws_registry.send(player_id, {
|
||||||
|
"Id": 60,
|
||||||
|
"Msg": {
|
||||||
|
"Balance": new_balance,
|
||||||
|
"CurrencyType": currency_type,
|
||||||
|
"BalanceUpdates": [{
|
||||||
|
"UpdateResponse": 0,
|
||||||
|
"Data": {
|
||||||
|
"BalanceAddType": 5,
|
||||||
|
"BaseAward": amount,
|
||||||
|
"BalanceInGiftBox": True,
|
||||||
|
},
|
||||||
|
}],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
def push_kick(player_id: int, session_id: int = 0, reason: int = -1, message: str = "Kicked by admin") -> None:
|
||||||
|
ws_registry.send(player_id, {
|
||||||
|
"Id": 22,
|
||||||
|
"Msg": {
|
||||||
|
"ReportCategory": reason,
|
||||||
|
"Duration": 0,
|
||||||
|
"GameSessionId": session_id,
|
||||||
|
"Message": message,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
def push_profile_update(player_id: int) -> None:
|
||||||
|
from .builders import make_profile_from_db
|
||||||
|
profile_row = db.get_profile(player_id)
|
||||||
|
if profile_row is None:
|
||||||
|
return
|
||||||
|
ws_registry.broadcast({
|
||||||
|
"Id": 11,
|
||||||
|
"Msg": make_profile_from_db(profile_row),
|
||||||
|
})
|
||||||
|
|
||||||
|
def push_room_update(player_id: int, room_dict: dict) -> None:
|
||||||
|
ws_registry.send(player_id, {"Id": 14, "Msg": room_dict})
|
||||||
|
|
||||||
|
def push_session_update(player_id: int, session) -> None:
|
||||||
|
ws_registry.send(player_id, {"Id": 13, "Msg": session.to_dict()})
|
||||||
|
|
||||||
|
def _consumable_row_to_msg(row: dict) -> dict:
|
||||||
|
return {
|
||||||
|
"Id": row["id"],
|
||||||
|
"ConsumableItemDesc": row["consumable_item_desc"],
|
||||||
|
"CreatedAt": row["created_at"].replace(" ", "T") + "Z" if "T" not in row["created_at"] else row["created_at"],
|
||||||
|
"Count": row["count"],
|
||||||
|
"UnlockedLevel": row["unlocked_level"],
|
||||||
|
"IsActive": bool(row["is_active"]),
|
||||||
|
}
|
||||||
|
|
||||||
|
def push_consumable_added(player_id: int, consumable_row: dict) -> None:
|
||||||
|
ws_registry.send(player_id, {"Id": 70, "Msg": _consumable_row_to_msg(consumable_row)})
|
||||||
|
|
||||||
|
def push_consumable_removed(player_id: int, consumable_row: dict) -> None:
|
||||||
|
ws_registry.send(player_id, {"Id": 71, "Msg": _consumable_row_to_msg(consumable_row)})
|
||||||
Reference in New Issue
Block a user