Upload files to "core"
This commit is contained in:
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()
|
||||
Reference in New Issue
Block a user