273 lines
11 KiB
Python
273 lines
11 KiB
Python
|
||
import json
|
||
import threading
|
||
|
||
from core.state import db, session_mgr, ws_registry
|
||
from core.ws_helpers import push_presence, push_gift
|
||
from core.builders import activity_info
|
||
from core.ban_service import cascade_kick_linked, kick_player
|
||
from core.constants import DORM_ROOM_GUID
|
||
from core.config import server as _server_cfg, base_url as _base_url
|
||
|
||
SERVER_BUILD = _server_cfg.get("build", "")
|
||
|
||
_next_session_id = 1
|
||
_session_lock = threading.Lock()
|
||
|
||
|
||
def _is_ip_banned(ip: str) -> bool:
|
||
return db.is_ip_banned(ip)
|
||
|
||
def register_ws(sock) -> None:
|
||
|
||
@sock.route("/api/notification/v2")
|
||
def notification_ws(ws):
|
||
global _next_session_id
|
||
|
||
from core.auth import get_current_profile_id
|
||
from flask import request as ws_req
|
||
pid = get_current_profile_id()
|
||
if pid is None:
|
||
print("[WS] Rejected unauthenticated WebSocket connection")
|
||
ws.close()
|
||
return
|
||
|
||
ip = (ws_req.headers.get("X-Forwarded-For", "") or ws_req.remote_addr or "").split(",")[0].strip()
|
||
if ip and ip not in ("127.0.0.1", "::1"):
|
||
db.record_ip_login(pid, ip)
|
||
|
||
if db.is_banned(pid):
|
||
print(f"[WS] Banned player {pid} tried to connect — closing")
|
||
cascade_kick_linked(pid)
|
||
try:
|
||
ws.send(json.dumps({"Id": 20, "Msg": {}}))
|
||
except Exception:
|
||
pass
|
||
ws.close()
|
||
return
|
||
|
||
import core.state as _st
|
||
with _st.maintenance_lock:
|
||
maint = _st.maintenance_mode
|
||
if maint:
|
||
if pid not in _st.maintenance_exempt:
|
||
print(f"[WS] Player {pid} rejected during maintenance")
|
||
ws.close()
|
||
return
|
||
|
||
if _is_ip_banned(ip):
|
||
print(f"[WS] IP-banned address {ip} tried to connect (pid={pid}) — closing")
|
||
if not db.is_banned(pid):
|
||
db.ban_player(pid, reason="Banned by IP association", duration_hours=0, admin_name="AntiCheat")
|
||
print(f"[AntiCheat] IP cascade ban: player {pid} at banned IP {ip}")
|
||
cascade_kick_linked(pid)
|
||
try:
|
||
ws.send(json.dumps({"Id": 20, "Msg": {}}))
|
||
except Exception:
|
||
pass
|
||
ws.close()
|
||
return
|
||
|
||
try:
|
||
handshake_raw = ws.receive()
|
||
if handshake_raw is None:
|
||
print(f"[WS] Player {pid}: connection closed before handshake")
|
||
return
|
||
handshake = json.loads(handshake_raw)
|
||
print(f"[WS] Player {pid} connected (keys: {list(handshake.keys())})")
|
||
except Exception as e:
|
||
print(f"[WS] Bad handshake from player {pid}: {e}")
|
||
return
|
||
|
||
with _session_lock:
|
||
ws_session_id = _next_session_id
|
||
_next_session_id += 1
|
||
ws.send(json.dumps({"SessionId": ws_session_id}))
|
||
|
||
ws_registry.register(pid, ws)
|
||
from core.daemons import record_session_start
|
||
record_session_start(pid)
|
||
|
||
for pending in db.get_pending_gifts(pid):
|
||
try:
|
||
push_gift(pid, pending)
|
||
except Exception:
|
||
pass
|
||
|
||
from core.daemons import record_heartbeat
|
||
record_heartbeat(pid)
|
||
|
||
settings = db.get_settings(pid)
|
||
if any(s["Key"] == "screen_mode_user" and s["Value"] == "1" for s in settings):
|
||
ws_registry.set_screen_mode(pid, True)
|
||
|
||
try:
|
||
from core.discord import mark_first_login, send_public
|
||
if mark_first_login(pid):
|
||
p = db.get_profile(pid)
|
||
uname = p["Username"] if p else str(pid)
|
||
dname = (p or {}).get("DisplayName", uname)
|
||
img = (p or {}).get("ProfileImageName", "")
|
||
send_public(
|
||
title="First Login!",
|
||
color=0x3498DB,
|
||
fields=[{"name": "Player", "value": uname, "inline": True},
|
||
{"name": "ID", "value": str(pid), "inline": True}],
|
||
description=f"**{dname}** just logged in for the very first time!",
|
||
thumbnail_url=f"{_base_url}/alt/{img}" if img else None,
|
||
throttle_key=f"firstlogin_{pid}",
|
||
throttle_secs=0,
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
session = session_mgr.get_player_session(pid)
|
||
if session is None:
|
||
name, key, sandbox = activity_info(DORM_ROOM_GUID)
|
||
session = session_mgr.join_room(pid, DORM_ROOM_GUID, name, key,
|
||
private=True, sandbox=sandbox)
|
||
|
||
push_presence(pid, session)
|
||
|
||
for other_pid in ws_registry.connected_ids():
|
||
if other_pid == pid:
|
||
continue
|
||
other_session = session_mgr.get_player_session(other_pid)
|
||
try:
|
||
ws.send(json.dumps({
|
||
"Id": 12,
|
||
"Msg": {
|
||
"PlayerId": other_pid,
|
||
"IsOnline": True,
|
||
"InScreenMode": ws_registry.is_screen_mode(other_pid),
|
||
"GameSession": other_session.to_dict() if other_session else None,
|
||
},
|
||
}))
|
||
except Exception:
|
||
pass
|
||
|
||
from core.state import _KITTYREC_SYSTEM_PID
|
||
try:
|
||
ws.send(json.dumps({
|
||
"Id": 12,
|
||
"Msg": {
|
||
"PlayerId": _KITTYREC_SYSTEM_PID,
|
||
"IsOnline": True,
|
||
"InScreenMode": True,
|
||
"GameSession": None,
|
||
},
|
||
}))
|
||
except Exception:
|
||
pass
|
||
|
||
print(f"[WS] Player {pid} → '{session.name}' "
|
||
f"(sid={session.session_id}, {len(session.players)} in room, "
|
||
f"{ws_registry.player_count()} online)")
|
||
|
||
from tracking.password_tracking import has_real_password
|
||
if not has_real_password(pid):
|
||
def _send_pw_msg(_pid=pid):
|
||
import time, string, random
|
||
from core.state import _KITTYREC_SYSTEM_PID
|
||
from datetime import datetime, timezone
|
||
time.sleep(10)
|
||
if not ws_registry.is_connected(_pid):
|
||
return
|
||
if has_real_password(_pid):
|
||
return
|
||
temp_pw = "".join(random.choices(string.ascii_letters + string.digits, k=8))
|
||
_c = db._get_conn()
|
||
_c.execute(
|
||
"UPDATE profiles SET password = ? WHERE id = ? AND registration_status != 2",
|
||
(temp_pw, _pid),
|
||
)
|
||
_c.commit()
|
||
profile = db.get_profile(_pid)
|
||
uname = profile["Username"] if profile else f"Player {_pid}"
|
||
msg_text = (
|
||
f"Welcome to KittyRec!\n"
|
||
f"Username: {uname}\n"
|
||
f"Temp password: {temp_pw}\n"
|
||
f"STOP SHARING YOUR SCREEN!\n"
|
||
f"Reply to this message with a new password (8+ chars) to register!"
|
||
)
|
||
msg_type = 30
|
||
db.delete_messages_of_type(_pid, _KITTYREC_SYSTEM_PID, msg_type)
|
||
msg_id = db.send_message(_KITTYREC_SYSTEM_PID, _pid, msg_type, msg_text)
|
||
sent = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||
ws_registry.send(_pid, {"Id": 2, "Msg": {
|
||
"Id": msg_id, "FromPlayerId": _KITTYREC_SYSTEM_PID,
|
||
"SentTime": sent, "Type": msg_type, "Data": msg_text,
|
||
"RoomId": None, "PlayerEventId": None,
|
||
}})
|
||
print(f"[System] Sent temp password to pid={_pid} user={uname}")
|
||
threading.Thread(target=_send_pw_msg, daemon=True, name=f"temp-pw-{pid}").start()
|
||
|
||
try:
|
||
while True:
|
||
msg = ws.receive()
|
||
if msg is None:
|
||
break
|
||
try:
|
||
data = json.loads(msg)
|
||
api = data.get("api", "")
|
||
|
||
if api == "heartbeat2":
|
||
record_heartbeat(pid)
|
||
cur = session_mgr.get_player_session(pid) or session
|
||
param = data.get("param") or {}
|
||
client_gm = param.get("SpecialGamemode")
|
||
if client_gm is not None and cur:
|
||
try:
|
||
session_mgr.modify_session(cur.session_id, special_gamemode=int(client_gm))
|
||
except Exception:
|
||
pass
|
||
ws.send(json.dumps({
|
||
"Id": 4,
|
||
"Msg": {
|
||
"PlayerId": pid,
|
||
"IsOnline": True,
|
||
"InScreenMode": ws_registry.is_screen_mode(pid),
|
||
"GameSession": cur.to_dict(),
|
||
},
|
||
}))
|
||
|
||
elif api == "playerSubscriptions/v1/update":
|
||
param = data.get("param", {}) or {}
|
||
sub_ids = param.get("PlayerIds", param.get("playerIds", []))[:200]
|
||
for sub_pid in sub_ids:
|
||
sub_session = session_mgr.get_player_session(sub_pid)
|
||
ws.send(json.dumps({
|
||
"Id": 12,
|
||
"Msg": {
|
||
"PlayerId": sub_pid,
|
||
"IsOnline": ws_registry.is_connected(sub_pid),
|
||
"InScreenMode": ws_registry.is_screen_mode(sub_pid),
|
||
"GameSession": sub_session.to_dict() if sub_session else None,
|
||
},
|
||
}))
|
||
|
||
else:
|
||
print(f"[WS] Player {pid}: unhandled api={api!r} data={data}")
|
||
|
||
except json.JSONDecodeError:
|
||
pass
|
||
|
||
except Exception as e:
|
||
print(f"[WS] Player {pid} error: {e}")
|
||
|
||
finally:
|
||
removed = ws_registry.unregister(pid, ws)
|
||
if removed:
|
||
from core.daemons import flush_session_time
|
||
flush_session_time(pid)
|
||
session_mgr.leave_session(pid)
|
||
push_presence(pid, None, online=False)
|
||
from routes.sessions import session_gift_reset
|
||
session_gift_reset(pid)
|
||
print(f"[WS] Player {pid} disconnected – "
|
||
f"{ws_registry.player_count()} remaining")
|
||
else:
|
||
print(f"[WS] Player {pid} old socket closed "
|
||
f"(new connection already registered – ignoring cleanup)")
|