space / main.py
Skydata001's picture
Upload main.py
8a768b9 verified
Raw History Blame Contribute Delete
98.4 kB
# Soldier Life 2D - Game Backend Server # FastAPI + WebSocket: auth (username/password, Argon2id), rooms (max 50), # interest management, chat throttling, admin tools, protected diagnostics logs. import os, re, json, time, math, random, secrets, string, sqlite3, threading, asyncio, unicodedata from collections import deque, defaultdict from datetime import datetime, timezone import httpx import uvicorn from argon2 import PasswordHasher from argon2.exceptions import VerifyMismatchError, VerificationError from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect, HTTPException, BackgroundTasks, Header from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from pydantic import BaseModel, Field # ============================ Configuration ============================ PORT = int(os.environ.get("PORT", "7860")) SUPABASE_URL = os.environ.get("SUPABASE_URL", "").rstrip("/") SUPABASE_KEY = os.environ.get("SUPABASE_SERVICE_ROLE_KEY", "") ADMIN_USERNAME = os.environ.get("ADMIN_USERNAME", "") ADMIN_PASSWORD = os.environ.get("ADMIN_PASSWORD", "") SESSION_SECRET = os.environ.get("SESSION_SECRET", "") or secrets.token_hex(32) # App ID الخاص بـ Photon — يُضبط كمتغير بيئة سري على الخادم فقط، ولا يُكتب في ملفات الواجهة. # إن تُرك فارغًا يبقى وضع WebSocket هو الفعّال افتراضيًا ويعمل كل شيء كما قبل. PHOTON_APPID = os.environ.get("PHOTON_APPID", "").strip() ALLOWED_ORIGINS = [x.strip() for x in os.environ.get("ALLOWED_ORIGINS", "*").split(",") if x.strip()] SQLITE_PATH = os.environ.get("SQLITE_PATH", "./soldierlife.db") USE_SUPABASE = bool(SUPABASE_URL and SUPABASE_KEY) MAX_PER_ROOM = 50 WORLD_W = 4800 WORLD_H = 4800 VIEW_RANGE = 1700.0 GRID_CELL = 512 SESSION_TTL = 12 * 3600 MAX_MSG_BYTES = 2048 MOVE_MIN_INTERVAL = 0.04 MOVE_MAX_DIST = 26.0 SHOT_MIN_INTERVAL = 0.08 WS_MSG_PER_SEC = 40 BOOT_TS = time.time() ph = PasswordHasher() # ============================ Logging (ring buffer) ============================ LOGS = deque(maxlen=5000) EVENTS = deque(maxlen=800) def now_iso(): return datetime.now(timezone.utc).isoformat(timespec="seconds") def log(level, source, event, detail="", rid=None): entry = {"ts": now_iso(), "level": level, "source": source, "event": event, "detail": str(detail)[:400], "rid": rid} LOGS.append(entry) try: print(json.dumps(entry, ensure_ascii=False), flush=True) except Exception: pass def event(kind, text): e = {"ts": now_iso(), "kind": kind, "text": str(text)[:220]} EVENTS.append(e) try: print(json.dumps({"ts": e["ts"], "level": "INFO", "source": "events", "event": kind, "detail": e["text"]}, ensure_ascii=False), flush=True) except Exception: pass # ============================ Database layer ============================ # Production: Supabase (PostgREST via service-role key, never sent to clients). # Fallback (local dev/testing only): SQLite when Supabase env vars are absent. DEFAULT_CHAR = {"skin": 1, "eyeType": 0, "eyeColor": 0, "hairStyle": 1, "hairColor": 0} DEFAULT_GUNS = {"owned": [], "equipped": None} SCHEMA_VERSION = "2" # أسماء مستويات الإدارة ADMIN_RANKS = {0: "player", 1: "helper", 2: "moderator", 3: "admin", 4: "senior_admin", 5: "owner"} ADMIN_RANK = int(os.environ.get("ADMIN_RANK", "5")) ADMIN_COLORS = {1: "#7ec8ff", 2: "#4a86ff", 3: "#ff7777", 4: "#ff4444", 5: "#ff2222"} # صلاحيات الإدارة — Allowlist صارمة: أي إجراء غير موجود هنا = ممنوع افتراضيًا. # Owner الوحيد هو حساب env (pid<0 أو arank>=4) — يتجاوز كل الفحوص ولا يُنشأ عبر API. PERMS = { "kick": 2, "ban": 2, "unban": 2, "jail": 2, "bring": 2, "unmute": 2, "mute": 1, "tpto": 1, "staff": 1, "overview": 1, "banned": 2, "events": 2, "users": 2, "money": 3, "setrank": 3, "logs": 3, "self_inv": 2, "self_nc": 2, "setid": 4, "setarank": 4, } def has_perm(s, action): if s["pid"] < 0 or s.get("arank", 0) >= 4: return True need = PERMS.get(action) if need is None: return False return s.get("arank", 0) >= need def require_perm(request, action): s = require_admin(request) if not has_perm(s, action): log("WARN", "admin", "perm_denied", "%s tried '%s'" % (s["username"], action), rid=client_ip(request)) raise HTTPException(status_code=403, detail="رتبتك لا تسمح بهذا الإجراء") return s def refresh_sessions(pid, arank): """مزامنة رتبة الإدارة مع كل جلسات اللاعب النشطة دون كسر الجلسة أو الهوية.""" for tok, sess in SESSIONS.items(): if sess["pid"] == pid: sess["arank"] = arank sess["role"] = "admin" if arank > 0 else "player" def db_get_arank(pid): try: if USE_SUPABASE: r = httpx.get(SUPABASE_URL + "/rest/v1/players?id=eq." + str(pid) + "&select=admin_rank&limit=1", headers=sb_headers(), timeout=15) return (r.json()[0].get("admin_rank") or 0) if r.status_code < 400 and r.json() else 0 with _lk: cur = _db.execute("SELECT admin_rank FROM players WHERE id=?", (pid,)) row = cur.fetchone() return (row[0] or 0) if row else 0 except Exception: return 0 # ------------------------------------------------------------------ # Schema: هجرات idempotent - الخادم ينشئ/يحدّث كل شيء عند كل إقلاع # مستقبلاً: أضف أمر ALTER/CREATE جديد هنا فقط ويعمل تلقائيًا في كل مكان # ------------------------------------------------------------------ PG_UPGRADES = [ # ترقية جدول قديم (نسخة 1) إن وُجد "alter table public.players add column if not exists is_admin boolean not null default false", "alter table public.players add column if not exists admin_rank int not null default 0", "alter table public.players add column if not exists level int not null default 1", "alter table public.players add column if not exists xp int not null default 0", "alter table public.players add column if not exists money int not null default 0", "alter table public.players add column if not exists ip text", "alter table public.players add column if not exists device text", "alter table public.players add column if not exists cookies jsonb not null default '{}'::jsonb", "alter table public.players add column if not exists inventory jsonb not null default '[]'::jsonb", "alter table public.players add column if not exists guns jsonb not null default '{\"owned\":[],\"equipped\":null}'::jsonb", "alter table public.players add column if not exists stats jsonb not null default '{}'::jsonb", "alter table public.players add column if not exists banned_until timestamptz", "alter table public.players add column if not exists ban_reason text", "alter table public.players add column if not exists last_login_at timestamptz", """do $$ begin if exists (select 1 from information_schema.columns where table_schema='public' and table_name='players' and column_name='role') then update public.players set is_admin = true where role = 'admin' and is_admin = false; end if; end $$""", "alter table public.players add column if not exists public_id bigint", "create unique index if not exists players_public_id_uidx on public.players (public_id)", ] PG_MIGRATIONS = [ """create table if not exists public.players ( id bigint generated always as identity primary key, username text not null, username_norm text not null, password_hash text not null, is_admin boolean not null default false, admin_rank int not null default 0, rank_id int not null default 1, level int not null default 1, xp int not null default 0, money int not null default 0, ip text, device text, cookies jsonb not null default '{}'::jsonb, character_data jsonb not null default '{}'::jsonb, inventory jsonb not null default '[]'::jsonb, guns jsonb not null default '{"owned":[],"equipped":null}'::jsonb, stats jsonb not null default '{}'::jsonb, banned_until timestamptz, ban_reason text, last_login_at timestamptz, created_at timestamptz not null default now(), updated_at timestamptz not null default now())""", "create unique index if not exists players_username_norm_uidx on public.players (username_norm)", "create index if not exists players_is_admin_idx on public.players (is_admin)", "create index if not exists players_admin_rank_idx on public.players (admin_rank)", "create index if not exists players_rank_idx on public.players (rank_id)", "create index if not exists players_level_idx on public.players (level)", "create index if not exists players_created_idx on public.players (created_at desc)", "create index if not exists players_ip_idx on public.players (ip)", "create index if not exists players_login_idx on public.players (last_login_at desc)", "create index if not exists players_inventory_gin on public.players using gin (inventory)", "create index if not exists players_guns_gin on public.players using gin (guns)", "create index if not exists players_stats_gin on public.players using gin (stats)", """create table if not exists public.audit_log ( id bigint generated always as identity primary key, admin_id bigint not null, admin_name text not null, action text not null, target_id bigint, target_name text, detail text, created_at timestamptz not null default now())""", "create index if not exists audit_created_idx on public.audit_log (created_at desc)", "create index if not exists audit_admin_idx on public.audit_log (admin_id)", """create table if not exists public.chat_log ( id bigint generated always as identity primary key, player_id bigint not null, player_name text not null, msg text not null, room text not null default 'global', created_at timestamptz not null default now())""", "create index if not exists chat_created_idx on public.chat_log (created_at desc)", "create index if not exists chat_player_idx on public.chat_log (player_id)", """create table if not exists public.daily_missions ( player_id bigint not null, day text not null, tasks jsonb not null default '{}'::jsonb, updated_at timestamptz not null default now(), primary key (player_id, day))""", ] SQLITE_MIGRATIONS = [ """create table if not exists players ( id integer primary key autoincrement, username text not null, username_norm text not null, password_hash text not null, is_admin integer not null default 0, admin_rank integer not null default 0, rank_id integer not null default 1, level integer not null default 1, xp integer not null default 0, money integer not null default 0, ip text, device text, cookies text not null default '{}', character_data text not null default '{}', inventory text not null default '[]', guns text not null default '{"owned":[],"equipped":null}', stats text not null default '{}', banned_until text, ban_reason text, last_login_at text, created_at text, updated_at text)""", "create unique index if not exists players_username_norm_uidx on players (username_norm)", "create index if not exists players_is_admin_idx on players (is_admin)", "create index if not exists players_admin_rank_idx on players (admin_rank)", "create index if not exists players_rank_idx on players (rank_id)", "create index if not exists players_created_idx on players (created_at)", "create index if not exists players_ip_idx on players (ip)", """create table if not exists audit_log ( id integer primary key autoincrement, admin_id integer not null, admin_name text not null, action text not null, target_id integer, target_name text, detail text, created_at text)""", "create index if not exists audit_created_idx on audit_log (created_at)", """create table if not exists chat_log ( id integer primary key autoincrement, player_id integer not null, player_name text not null, msg text not null, room text not null default 'global', created_at text)""", "create index if not exists chat_created_idx on chat_log (created_at)", "create index if not exists chat_player_idx on chat_log (player_id)", "alter table players add column public_id integer", "create unique index if not exists players_public_id_uidx on players (public_id)", """create table if not exists daily_missions ( player_id integer not null, day text not null, tasks text not null default '{}', updated_at text, primary key (player_id, day))""", ] def run_migrations(): global DB_READY if USE_SUPABASE: try: for stmt in PG_MIGRATIONS + PG_UPGRADES: r = httpx.post(SUPABASE_URL + "/rest/v1/rpc/exec_ddl", headers=sb_headers(), json={"sql": stmt}, timeout=25) if r.status_code == 404: log("ERROR", "db", "rpc_missing", "الصق محتوى server/schema.sql في Supabase SQL Editor ثم أعد المحاولة (الخادم يعيد المحاولة تلقائيًا)") return False if r.status_code >= 400: log("ERROR", "db", "migrate_failed", stmt[:70] + " :: " + r.text[:160]) probe = httpx.get(SUPABASE_URL + "/rest/v1/players?select=id&limit=1", headers=sb_headers(), timeout=15) if probe.status_code >= 400: log("ERROR", "db", "probe_failed", probe.text[:160]) return False DB_READY = True log("INFO", "db", "migrated", "supabase schema v%s ready" % SCHEMA_VERSION) return True except Exception as e: log("ERROR", "db", "migrate_error", str(e)[:200]) return False try: with _lk: for stmt in SQLITE_MIGRATIONS: try: _db.execute(stmt) except Exception as e2: log("WARN", "db", "sqlite_migrate", str(e2)[:120]) _db.commit() DB_READY = True log("INFO", "db", "migrated", "sqlite schema v%s ready" % SCHEMA_VERSION) return True except Exception as e: log("ERROR", "db", "migrate_error", str(e)[:200]) return False if not USE_SUPABASE: os.makedirs(os.path.dirname(SQLITE_PATH) or ".", exist_ok=True) _lk = threading.Lock() _db = sqlite3.connect(SQLITE_PATH, check_same_thread=False) def sb_headers(): return {"apikey": SUPABASE_KEY, "Authorization": "Bearer " + SUPABASE_KEY, "Content-Type": "application/json", "Prefer": "return=representation"} def _j(obj): return json.dumps(obj, ensure_ascii=False) def public_id_ok(v): s = str(v) if len(s) != 7 or not s.isdigit(): return False if len(set(s)) == 1: return False if s == s[::-1]: return False if all(int(s[i+1]) - int(s[i]) == 1 for i in range(6)): return False if all(int(s[i]) - int(s[i+1]) == 1 for i in range(6)): return False if all(s[i] == s[i+1] for i in range(0, 6, 2)): return False return True def db_pub_exists(pub): try: if USE_SUPABASE: r = httpx.get(SUPABASE_URL + "/rest/v1/players?public_id=eq." + str(pub) + "&select=id&limit=1", headers=sb_headers(), timeout=15) return bool(r.status_code < 400 and r.json()) with _lk: cur = _db.execute("SELECT id FROM players WHERE public_id=?", (pub,)) return cur.fetchone() is not None except Exception: return False def gen_public_id(): for _ in range(300): v = random.randint(1000000, 9999999) if public_id_ok(v) and not db_pub_exists(v): return v return random.randint(1000000, 9999999) def db_get_pub(pid): try: if USE_SUPABASE: r = httpx.get(SUPABASE_URL + "/rest/v1/players?id=eq." + str(pid) + "&select=public_id&limit=1", headers=sb_headers(), timeout=15) return (r.json()[0].get("public_id") or 0) if r.status_code < 400 and r.json() else 0 with _lk: cur = _db.execute("SELECT public_id FROM players WHERE id=?", (pid,)) row = cur.fetchone() return row[0] if row and row[0] else 0 except Exception: return 0 def db_set_pub(pid, pub): ts = now_iso() try: if USE_SUPABASE: r = httpx.patch(SUPABASE_URL + "/rest/v1/players?id=eq." + str(pid), headers=sb_headers(), timeout=15, json={"public_id": pub, "updated_at": ts}) return r.status_code < 400 with _lk: _db.execute("UPDATE players SET public_id=?, updated_at=? WHERE id=?", (pub, ts, pid)) _db.commit() return True except Exception as e: log("WARN", "db", "set_pub_failed", str(e)[:140]) return False def db_set_arank(pid, arank): ts = now_iso() try: if USE_SUPABASE: r = httpx.patch(SUPABASE_URL + "/rest/v1/players?id=eq." + str(pid), headers=sb_headers(), timeout=15, json={"is_admin": arank > 0, "admin_rank": arank, "updated_at": ts}) return r.status_code < 400 with _lk: _db.execute("UPDATE players SET is_admin=?, admin_rank=?, updated_at=? WHERE id=?", (1 if arank > 0 else 0, arank, ts, pid)) _db.commit() return True except Exception as e: log("WARN", "db", "set_arank_failed", str(e)[:140]) return False def db_add_xp(pid, delta): try: if USE_SUPABASE: r = httpx.get(SUPABASE_URL + "/rest/v1/players?id=eq." + str(pid) + "&select=xp", headers=sb_headers(), timeout=15) cur = (r.json()[0].get("xp") or 0) if r.status_code < 400 and r.json() else 0 r2 = httpx.patch(SUPABASE_URL + "/rest/v1/players?id=eq." + str(pid), headers=sb_headers(), timeout=15, json={ "xp": max(0, cur + delta), "updated_at": now_iso()}) return r2.status_code < 400 with _lk: _db.execute("UPDATE players SET xp=max(0, xp+?), updated_at=? WHERE id=?", (delta, now_iso(), pid)) _db.commit() return True except Exception as e: log("WARN", "db", "xp_failed", str(e)[:140]) return False def db_create_player(username, norm, pw_hash, ip, device): ts = now_iso() device_id = secrets.token_urlsafe(16) cookies = {"device_id": device_id} pub = gen_public_id() if USE_SUPABASE: r = httpx.post(SUPABASE_URL + "/rest/v1/players", headers=sb_headers(), timeout=15, json={ "username": username, "username_norm": norm, "password_hash": pw_hash, "is_admin": False, "admin_rank": 0, "public_id": pub, "character_data": _j(DEFAULT_CHAR), "rank_id": 1, "inventory": "[]", "guns": _j(DEFAULT_GUNS), "ip": ip, "device": (device or "")[:120], "cookies": _j(cookies), "created_at": ts, "updated_at": ts}) if r.status_code >= 400: raise RuntimeError("db_create_failed:" + str(r.status_code)) return r.json()[0]["id"], device_id, pub with _lk: cur = _db.execute( "INSERT INTO players (username,username_norm,password_hash,is_admin,admin_rank,public_id," "character_data,rank_id,inventory,guns,ip,device,cookies,created_at,updated_at)" " VALUES (?,?,?,0,0,?,?,1,'[]',?,?,?,?,?,?)", (username, norm, pw_hash, pub, _j(DEFAULT_CHAR), _j(DEFAULT_GUNS), ip, (device or "")[:120], _j(cookies), ts, ts)) _db.commit() return cur.lastrowid, device_id, pub def db_find_by_norm(norm): if USE_SUPABASE: r = httpx.get(SUPABASE_URL + "/rest/v1/players?username_norm=eq." + norm + "&select=*", headers=sb_headers(), timeout=15) if r.status_code >= 400: return None rows = r.json() return rows[0] if rows else None with _lk: cur = _db.execute("SELECT * FROM players WHERE username_norm=?", (norm,)) row = cur.fetchone() if not row: return None cols = [c[0] for c in cur.description] return dict(zip(cols, row)) def _row_is_admin(row): v = row.get("is_admin") if v is None: return row.get("role") == "admin" return bool(v) def db_touch_login(pid, ip, device, device_id): ts = now_iso() try: cookies = {} if USE_SUPABASE: r = httpx.get(SUPABASE_URL + "/rest/v1/players?id=eq." + str(pid) + "&select=cookies", headers=sb_headers(), timeout=15) if r.status_code < 400 and r.json(): try: cookies = json.loads(r.json()[0].get("cookies") or "{}") except Exception: cookies = {} if device_id: cookies["device_id"] = device_id r2 = httpx.patch(SUPABASE_URL + "/rest/v1/players?id=eq." + str(pid), headers=sb_headers(), timeout=15, json={ "ip": ip, "device": (device or "")[:120], "cookies": _j(cookies), "last_login_at": ts}) return r2.status_code < 400 with _lk: cur = _db.execute("SELECT cookies FROM players WHERE id=?", (pid,)) r0 = cur.fetchone() if r0: try: cookies = json.loads(r0[0] or "{}") except Exception: cookies = {} if device_id: cookies["device_id"] = device_id _db.execute("UPDATE players SET ip=?, device=?, cookies=?, last_login_at=?, updated_at=? WHERE id=?", (ip, (device or "")[:120], _j(cookies), ts, ts, pid)) _db.commit() return True except Exception as e: log("WARN", "db", "touch_login_failed", str(e)[:140]) return False def db_get_profile(pid): row = None if USE_SUPABASE: r = httpx.get(SUPABASE_URL + "/rest/v1/players?id=eq." + str(pid) + "&select=id,username,is_admin,admin_rank,character_data,rank_id,level,xp,money,inventory,guns,stats", headers=sb_headers(), timeout=15) if r.status_code < 400 and r.json(): row = r.json()[0] else: with _lk: cur = _db.execute("SELECT id,username,is_admin,admin_rank,character_data,rank_id,level,xp,money,inventory,guns,stats FROM players WHERE id=?", (pid,)) r0 = cur.fetchone() if r0: row = {"id": r0[0], "username": r0[1], "is_admin": r0[2], "admin_rank": r0[3], "character_data": r0[4], "rank_id": r0[5], "level": r0[6], "xp": r0[7], "money": r0[8], "inventory": r0[9], "guns": r0[10], "stats": r0[11]} if not row: return None def ld(k, dflt): try: return json.loads(row.get(k) or "") except Exception: return dflt return {"character_data": ld("character_data", dict(DEFAULT_CHAR)), "rank_id": row.get("rank_id") or 1, "level": row.get("level") or 1, "xp": row.get("xp") or 0, "money": row.get("money") or 0, "inventory": ld("inventory", []), "guns": ld("guns", dict(DEFAULT_GUNS)), "stats": ld("stats", {}), "is_admin": _row_is_admin(row), "admin_rank": row.get("admin_rank") or 0} def db_save_profile(pid, char_data, rank_id): ts = now_iso() if USE_SUPABASE: r = httpx.patch(SUPABASE_URL + "/rest/v1/players?id=eq." + str(pid), headers=sb_headers(), timeout=15, json={ "character_data": _j(char_data or DEFAULT_CHAR), "rank_id": int(rank_id or 1), "updated_at": ts}) return r.status_code < 400 with _lk: cur = _db.execute("UPDATE players SET character_data=?, rank_id=?, updated_at=? WHERE id=?", (_j(char_data or DEFAULT_CHAR), int(rank_id or 1), ts, pid)) _db.commit() return cur.rowcount > 0 def db_audit(admin_id, admin_name, action, target_id=None, target_name=None, detail=""): try: ts = now_iso() if USE_SUPABASE: httpx.post(SUPABASE_URL + "/rest/v1/audit_log", headers=sb_headers(), timeout=15, json={ "admin_id": admin_id, "admin_name": admin_name, "action": action, "target_id": target_id, "target_name": target_name, "detail": str(detail)[:300], "created_at": ts}) else: with _lk: _db.execute("INSERT INTO audit_log (admin_id,admin_name,action,target_id,target_name,detail,created_at)" " VALUES (?,?,?,?,?,?,?)", (admin_id, admin_name, action, target_id, target_name, str(detail)[:300], ts)) _db.commit() except Exception as e: log("WARN", "db", "audit_failed", str(e)[:140]) def db_log_chat(pid, name, msg, room): try: ts = now_iso() if USE_SUPABASE: httpx.post(SUPABASE_URL + "/rest/v1/chat_log", headers=sb_headers(), timeout=15, json={ "player_id": pid, "player_name": name, "msg": msg, "room": room, "created_at": ts}) else: with _lk: _db.execute("INSERT INTO chat_log (player_id,player_name,msg,room,created_at) VALUES (?,?,?,?,?)", (pid, name, msg, room, ts)) _db.commit() except Exception as e: log("WARN", "db", "chat_log_failed", str(e)[:140]) # ============================ Validation helpers ============================ USERNAME_RE = re.compile(r"^[A-Za-z0-9_\.\u0600-\u06FF]{3,16}$") EMOJI_RE = re.compile("[\U0001F000-\U0001FAFF\U0001F1E6-\U0001F1FF\u2600-\u27BF\u2B00-\u2BFF\uFE0F]") def normalize_username(u): return unicodedata.normalize("NFKC", u).strip().casefold() def password_ok(pw): return len(pw) >= 8 and re.search("[A-Za-z]", pw) and re.search("[0-9]", pw) def validate_chat(raw): text = unicodedata.normalize("NFC", str(raw)) if len(text) > 30: return None, "الرسالة طويلة جدًا (الحد الأقصى 30 حرفًا)" text = text.strip() if not text: return None, "empty" if EMOJI_RE.search(text): return None, "الإيموجي غير مسموح في الدردشة" if len(text) >= 6 and len(set(text)) <= 2: return None, "تم رفض الرسالة (تكرار مفرط)" return text, None def chat_delay(player_count): if player_count <= 10: return random.uniform(1, 3) if player_count <= 20: return random.uniform(3, 5) return random.uniform(5, 10) # ============================ Rate limiter (in-memory) ============================ RL = defaultdict(deque) RL_BYPASS = os.environ.get("RL_BYPASS", "") == "1" def rate_ok(key, limit, per_sec): if RL_BYPASS: return True dq = RL[key] t = time.time() while dq and t - dq[0] > per_sec: dq.popleft() if len(dq) >= limit: return False dq.append(t) return True # ============================ Sessions ============================ SESSIONS = {} HELPER_CD = {} def cd_ok(key, sec): t = time.time() if HELPER_CD.get(key, 0) > t: return False, int(HELPER_CD[key] - t) + 1 HELPER_CD[key] = t + sec return True, 0 def make_session(pid, username, role, arank=0): token = secrets.token_urlsafe(32) SESSIONS[token] = {"pid": pid, "username": username, "role": role, "arank": arank, "exp": time.time() + SESSION_TTL} return token def get_session(token): s = SESSIONS.get(token) if not s: return None if s["exp"] < time.time(): SESSIONS.pop(token, None) return None s["exp"] = time.time() + SESSION_TTL return s def drop_session(token): SESSIONS.pop(token, None) # ============================ Game state ============================ def grid_key(x, y): return (int(x // GRID_CELL), int(y // GRID_CELL)) class Player: def __init__(self, pid, name, role, rank_id, profile, ws, arank=0): self.pid = pid self.name = name self.role = role self.rank_id = rank_id self.profile = profile self.ws = ws self.arank = arank self.pub = 0 self._sal_flag = False self.last_zhit = 0.0 h = 0 for ch in name: h = (h * 31 + ord(ch)) & 0xffff self.x = WORLD_W / 2 + (h % 160) - 80 self.y = WORLD_H / 2 + ((h * 7) % 120) - 60 self.dir = 0 self.mov = 0 self.wt = 0.0 self.sal = 0 self.last_seq = 0 self.last_move_at = 0.0 self.last_shot_at = 0.0 self.last_chat_at = 0.0 self.chat_wait = 0.0 self.muted_until = 0.0 self.last_seen = time.time() self.view_set = set() self.msg_times = deque(maxlen=64) self.transport = "ws" self.events = deque(maxlen=200) self.ping = 0 self.has_w = 0 self.hol_w = 0 self.invisible = False self.noclip = False self.jail_until = 0.0 def public_full(self): return {"id": self.pid, "name": self.name, "role": self.role, "arank": self.arank, "pub": self.pub, "level": self.rank_id, "x": round(self.x), "y": round(self.y), "dir": self.dir, "mov": self.mov, "wt": round(self.wt, 1), "sal": self.sal, "has": self.has_w, "hol": self.hol_w, "ping": self.ping, "rankId": self.rank_id, "profile": self.profile} class Room: def __init__(self, name): self.name = name self.players = {} self.grid = defaultdict(set) def add(self, p): self.players[p.pid] = p self.grid[grid_key(p.x, p.y)].add(p.pid) def remove(self, pid): p = self.players.pop(pid, None) if p: cell = self.grid.get(grid_key(p.x, p.y)) if cell: cell.discard(pid) return p def rekey(self, p, nx, ny): old = grid_key(p.x, p.y) new = grid_key(nx, ny) if old != new: c = self.grid.get(old) if c: c.discard(p.pid) self.grid[new].add(p.pid) def visible(self, me): cx, cy = grid_key(me.x, me.y) r = int(math.ceil(VIEW_RANGE / GRID_CELL)) out = [] for gx in range(cx - r, cx + r + 1): for gy in range(cy - r, cy + r + 1): for pid in list(self.grid.get((gx, gy), ())): if pid == me.pid: continue p = self.players.get(pid) if p and not p.invisible and math.hypot(p.x - me.x, p.y - me.y) <= VIEW_RANGE: out.append(p) return out ROOMS = {} DB_READY = False MAIN_LOOP = None JAIL_X = 2400.0 JAIL_Y = 2320.0 JAIL_R = 130.0 def get_room(name): if name not in ROOMS: ROOMS[name] = Room(name) return ROOMS[name] def find_player(pid): for r in ROOMS.values(): if pid in r.players: return r, r.players[pid] return None, None def deliver(p, obj): """توصيل آمن للرسائل يعمل من أي سياق (async أو sync) عبر الحلقة الرئيسية.""" if p.transport == "ws" and p.ws is not None and MAIN_LOOP is not None: try: ws_, o_ = p.ws, obj MAIN_LOOP.call_soon_threadsafe( lambda: MAIN_LOOP.create_task(safe_send(ws_, o_))) return except Exception: pass p.events.append(obj) async def safe_send(ws, obj): try: await ws.send_json(obj) except Exception: pass # ============================ App ============================ app = FastAPI(title="Soldier Life 2D Server", docs_url=None, redoc_url=None) app.add_middleware( CORSMiddleware, allow_origins=ALLOWED_ORIGINS or ["*"], allow_methods=["*"], allow_headers=["*"], ) @app.middleware("http") async def sec_headers(request, call_next): resp = await call_next(request) resp.headers["X-Content-Type-Options"] = "nosniff" resp.headers["X-Frame-Options"] = "DENY" resp.headers["Referrer-Policy"] = "no-referrer" return resp class AuthIn(BaseModel): username: str = Field(min_length=1, max_length=24) password: str = Field(min_length=1, max_length=128) class ProfileIn(BaseModel): characterData: dict = Field(default_factory=dict) rankId: int = Field(default=1, ge=1, le=41) class ReportIn(BaseModel): msg: str = Field(min_length=1, max_length=300) url: str = Field(default="", max_length=300) class PollHelloIn(BaseModel): token: str = Field(min_length=1, max_length=300) class PollSyncIn(BaseModel): token: str = Field(min_length=1, max_length=300) seq: int = 0 x: float = 0 y: float = 0 dir: int = 0 mov: int = 0 wt: float = 0 sal: int = 0 ping: int = 0 spd: float = 1 has: int = 0 hol: int = 0 class PollShotIn(BaseModel): token: str = Field(min_length=1, max_length=300) x: float = 0 y: float = 0 rad: float = 0 class PollChatIn(BaseModel): token: str = Field(min_length=1, max_length=300) msg: str = Field(default="", max_length=60) class PollZhitIn(BaseModel): token: str = Field(min_length=1, max_length=300) zid: int = 0 class KickIn(BaseModel): player_id: int reason: str = Field(default="", max_length=120) class MuteIn(BaseModel): player_id: int minutes: int = Field(default=5, ge=1, le=1440) def client_ip(req): xff = req.headers.get("x-forwarded-for") if xff: return xff.split(",")[0].strip()[:60] return req.client.host if req.client else "?" def bearer(request): auth = request.headers.get("authorization", "") return auth[7:] if auth.startswith("Bearer ") else "" def ensure_db_ready(): if DB_READY: return True log("WARN", "db", "lazy_migrate", "إعادة محاولة إنشاء الجداول تلقائيًا...") return run_migrations() DB_NOT_READY_MSG = ("قاعدة البيانات غير مهيأة بعد. افتح Supabase -> SQL Editor والصق محتوى " "server/schema.sql كاملًا ثم نفّذه، ثم أعد المحاولة هنا مباشرة.") def err(status, msg, code=""): return JSONResponse(status_code=status, content={"ok": False, "error": msg, "code": code}) def online_available(): return True # SQLite fallback keeps Online usable in dev; Supabase used when configured. @app.get("/") def root(): return {"ok": True, "name": "soldierlife-server", "docs": "/health", "supabase": USE_SUPABASE} @app.get("/api/netconfig") def netconfig(): """إعداد الشبكة للعميل — App ID يأتي من سر الخادم، ولا يوجد هنا أي رمز جلسة أو كلمة مرور.""" return {"ok": True, "photon_appid": PHOTON_APPID, "photon_enabled": bool(PHOTON_APPID)} @app.get("/health") def health(): total_players = sum(len(r.players) for r in ROOMS.values()) return {"ok": True, "ts": now_iso(), "uptime_s": int(time.time() - BOOT_TS), "players_online": total_players, "rooms": len(ROOMS), "supabase": USE_SUPABASE} # ------------------------------ Auth ------------------------------ @app.post("/api/register") def register(body: AuthIn, request: Request, x_device_id: str = Header(default=""), user_agent: str = Header(default="")): device = (x_device_id or "")[:64] + "|" + (user_agent or "")[:100] ip = client_ip(request) if not rate_ok("reg:" + ip, 5, 300): log("WARN", "auth", "rate_limited", "register", rid=ip) return err(429, "طلبات كثيرة؛ حاول لاحقًا", "rate_limited") if not ensure_db_ready(): return err(503, DB_NOT_READY_MSG, "db_not_ready") username = body.username.strip() if not USERNAME_RE.match(username): return err(400, "اسم مستخدم غير صالح (3-16 حرفًا: أحرف عربية أو إنجليزية أو أرقام أو _ أو .)", "bad_username") norm = normalize_username(username) if ADMIN_USERNAME and norm == normalize_username(ADMIN_USERNAME): return err(403, "اسم مستخدم غير صالح", "reserved") if not password_ok(body.password): return err(400, "كلمة المرور ضعيفة: 8 أحرف على الأقل وتتضمن حرفًا ورقمًا", "weak_password") try: if db_find_by_norm(norm): return err(409, "اسم المستخدم موجود بالفعل", "username_taken") pw_hash = ph.hash(body.password) pid, device_id, pub = db_create_player(username, norm, pw_hash, ip, device) except HTTPException: raise except Exception as e: log("ERROR", "db", "register_failed", str(e)[:200], rid=ip) if "404" in str(e): return err(503, DB_NOT_READY_MSG, "db_not_ready") return err(500, "فشل إنشاء الحساب", "db_error") db_touch_login(pid, ip, device, None) token = make_session(pid, username, "player", 0) log("INFO", "auth", "register", username + " ip=" + ip, rid=ip) return {"ok": True, "token": token, "device_id": device_id, "user": {"id": pid, "username": username, "role": "player", "pub": pub}, "profile": {"character_data": dict(DEFAULT_CHAR), "rank_id": 1, "level": 1, "xp": 0, "money": 0, "inventory": [], "guns": dict(DEFAULT_GUNS), "stats": {}, "admin_rank": 0}} @app.post("/api/login") def login(body: AuthIn, request: Request, x_device_id: str = Header(default=""), user_agent: str = Header(default="")): ip = client_ip(request) device = (x_device_id or "")[:64] + "|" + (user_agent or "")[:100] if not rate_ok("login:" + ip, 8, 300): log("WARN", "auth", "rate_limited", "login", rid=ip) return err(429, "طلبات كثيرة؛ حاول لاحقًا", "rate_limited") if not ensure_db_ready(): return err(503, DB_NOT_READY_MSG, "db_not_ready") norm = normalize_username(body.username.strip()) # حساب الإدارة من أسرار البيئة (لا يُخزّن في DB ولا يصل للعميل) if ADMIN_USERNAME and ADMIN_PASSWORD and norm == normalize_username(ADMIN_USERNAME) \ and body.password == ADMIN_PASSWORD: token = make_session(-1, ADMIN_USERNAME, "admin", ADMIN_RANK) log("INFO", "auth", "admin_login", ADMIN_USERNAME + " ip=" + ip, rid=ip) return {"ok": True, "token": token, "user": {"id": -1, "username": ADMIN_USERNAME, "role": "admin", "admin_rank": ADMIN_RANK}, "profile": {"character_data": dict(DEFAULT_CHAR), "rank_id": 41, "level": 41, "xp": 0, "money": 0, "inventory": [], "guns": dict(DEFAULT_GUNS), "stats": {}, "admin_rank": ADMIN_RANK}} row = db_find_by_norm(norm) if not row: log("WARN", "auth", "login_failed", body.username[:24], rid=ip) return err(401, "بيانات الدخول غير صحيحة", "bad_credentials") # فحص الحظر try: bu = row.get("banned_until") if bu: bu_dt = datetime.fromisoformat(str(bu).replace("Z", "+00:00")) if bu_dt.tzinfo is None: bu_dt = bu_dt.replace(tzinfo=timezone.utc) if bu_dt.timestamp() > time.time(): log("WARN", "auth", "banned_login", row["username"], rid=ip) return err(403, "هذا الحساب محظور: " + str(row.get("ban_reason") or "")[:80], "banned") except Exception: pass try: ph.verify(row["password_hash"], body.password) except (VerifyMismatchError, VerificationError): log("WARN", "auth", "login_failed", row["username"], rid=ip) return err(401, "بيانات الدخول غير صحيحة", "bad_credentials") except Exception as e: log("ERROR", "db", "hash_error", str(e)[:120], rid=ip) return err(500, "حدث خطأ داخلي", "internal") pid = row["id"] is_admin = _row_is_admin(row) role = "admin" if is_admin else "player" db_touch_login(pid, ip, device, x_device_id or None) profile = db_get_profile(pid) or {"character_data": dict(DEFAULT_CHAR), "rank_id": 1, "inventory": [], "guns": dict(DEFAULT_GUNS)} token = make_session(pid, row["username"], role, (row.get("admin_rank") or 0) if is_admin else 0) log("INFO", "auth", "login", row["username"] + " ip=" + ip, rid=ip) return {"ok": True, "token": token, "user": {"id": pid, "username": row["username"], "role": role, "pub": db_get_pub(pid), "admin_rank": (row.get("admin_rank") or 0) if is_admin else 0}, "profile": profile} @app.post("/api/logout") def logout(request: Request): token = bearer(request) s = get_session(token) if s and s["pid"] > 0: flush_prog(s["pid"]) if token: drop_session(token) return {"ok": True} @app.get("/api/session") def session_info(request: Request): s = get_session(bearer(request)) if not s: return err(401, "انتهت الجلسة", "session_expired") return {"ok": True, "user": {"id": s["pid"], "username": s["username"], "role": s["role"]}} # ------------------------------ Profile ------------------------------ @app.get("/api/profile") def profile_get(request: Request): s = get_session(bearer(request)) if not s or s["pid"] < 0: return err(401, "انتهت الجلسة", "session_expired") p = db_get_profile(s["pid"]) if not p: return err(404, "الملف الشخصي غير موجود", "not_found") return {"ok": True, "profile": p} @app.post("/api/profile") def profile_save(body: ProfileIn, request: Request): s = get_session(bearer(request)) if not s or s["pid"] < 0: return err(401, "انتهت الجلسة", "session_expired") ok = db_save_profile(s["pid"], body.characterData, body.rankId) if not ok: log("ERROR", "db", "profile_save_failed", s["username"]) return err(500, "فشل حفظ البيانات", "db_error") return {"ok": True} # ------------------------------ Client error reports ------------------------------ @app.post("/api/report") def report(body: ReportIn, request: Request): ip = client_ip(request) if not rate_ok("report:" + ip, 10, 60): return err(429, "طلبات كثيرة؛ حاول لاحقًا", "rate_limited") log("WARN", "client", "js_error", (body.msg + " @ " + body.url)[:380], rid=ip) return {"ok": True} # ------------------------------ Admin ------------------------------ def require_admin(request): s = get_session(bearer(request)) if not s or s["role"] != "admin": log("WARN", "admin", "unauthorized_access", rid=client_ip(request)) raise HTTPException(status_code=401, detail="غير مصرح") return s @app.get("/api/admin/logs") def admin_logs(request: Request, level: str = "", q: str = ""): require_perm(request, "logs") out = [e for e in LOGS if (not level or e["level"] == level) and (not q or q in e["event"] or q in e.get("detail", ""))] return {"ok": True, "logs": list(out[-300:]), "total": len(LOGS)} @app.get("/api/admin/overview") def admin_overview(request: Request): require_admin(request) return {"ok": True, "uptime_s": int(time.time() - BOOT_TS), "supabase": USE_SUPABASE, "rooms": [{"name": r.name, "players": len(r.players)} for r in ROOMS.values()], "players": [{"id": p.pid, "name": p.name, "role": p.role, "arank": p.arank, "pub": p.pub, "room": r.name, "x": round(p.x), "y": round(p.y)} for r in ROOMS.values() for p in r.players.values()], "admin_ranks": ADMIN_RANKS} @app.post("/api/admin/kick") def admin_kick(body: KickIn, request: Request, background_tasks: BackgroundTasks): s = require_perm(request, "kick") for r in ROOMS.values(): p = r.players.get(body.player_id) if p: r.remove(body.player_id) deliver(p, {"t": "kicked", "by": s["username"], "reason": body.reason}) async def _notify(ws_p, pid_p, n_p): await safe_send(ws_p, {"t": "pleave", "id": pid_p}) await safe_send(ws_p, {"t": "count", "n": n_p, "max": MAX_PER_ROOM}) for other in list(r.players.values()): if other.transport == "poll": other.events.append({"t": "pleave", "id": body.player_id}) other.events.append({"t": "count", "n": len(r.players), "max": MAX_PER_ROOM}) else: background_tasks.add_task(asyncio.run, _notify(other.ws, body.player_id, len(r.players))) async def _close_ws(ws_p): try: await ws_p.close(code=4002) except Exception: pass background_tasks.add_task(asyncio.run, _close_ws(p.ws)) db_audit(s["pid"], s["username"], "kick", body.player_id, p.name, "room=" + r.name) log("WARN", "admin", "kick", "%s kicked %s" % (s["username"], p.name)) event("kick", "طرد %s اللاعب %s" % (s["username"], p.name)) for o in list(r.players.values()): deliver(o, {"t": "chat", "id": 0, "name": "الخادم", "msg": "تم طرد %s — من طرف %s" % (p.name, s["username"]), "color": "yellow", "sys": True}) return {"ok": True} return err(404, "اللاعب غير متصل", "not_found") @app.post("/api/admin/mute") def admin_mute(body: MuteIn, request: Request): s = require_perm(request, "mute") if s["arank"] == 1: ok_cd, left = cd_ok("mute:" + str(s["pid"]), 60) if not ok_cd: raise HTTPException(status_code=429, detail="انتظر %d ثانية بين عمليات الكتم" % left) for r in ROOMS.values(): p = r.players.get(body.player_id) if p: p.muted_until = time.time() + body.minutes * 60 db_audit(s["pid"], s["username"], "mute", body.player_id, p.name, "%dm" % body.minutes) log("WARN", "admin", "mute", "%s muted %s for %dm" % (s["username"], p.name, body.minutes)) event("mute", "كتم %s اللاعب %s لمدة %d دقيقة" % (s["username"], p.name, body.minutes)) for o in list(r.players.values()): deliver(o, {"t": "chat", "id": 0, "name": "الخادم", "msg": "تم كتم %s لمدة %d دقيقة — من طرف %s" % (p.name, body.minutes, s["username"]), "color": "yellow", "sys": True}) return {"ok": True} return err(404, "اللاعب غير متصل", "not_found") # ------------------------------ Polling transport (HTTPS fallback) ------------------------------ @app.post("/api/poll/hello") async def poll_hello(body: PollHelloIn): s = get_session(body.token) if not s: return err(401, "انتهت الجلسة", "session_expired") pid, username, role = s["pid"], s["username"], s["role"] room = get_room("global") if pid in room.players: old = room.players[pid] room.remove(pid) if old.transport == "ws" and old.ws is not None: try: await old.ws.close(code=4000) except Exception: pass log("INFO", "ws", "replaced_duplicate", username) if len(room.players) >= MAX_PER_ROOM: return err(429, "الغرفة ممتلئة", "room_full") profile = {"character_data": dict(DEFAULT_CHAR), "rank_id": 41} if pid < 0 else db_get_profile(pid) rank_id = (profile or {}).get("rank_id") or 1 me = Player(pid, username, role, rank_id, (profile or {}).get("character_data") or dict(DEFAULT_CHAR), None, s.get("arank", 0)) me.pub = db_get_pub(pid) if pid > 0 else 0 me.transport = "poll" me.last_seen = time.time() room.add(me) me.view_set = set(p.pid for p in room.visible(me)) welcome = {"t": "welcome", "id": pid, "room": "global", "count": len(room.players), "max": MAX_PER_ROOM, "players": [p.public_full() for p in room.players.values() if p.pid != pid and p.pid in me.view_set and not p.invisible]} welcome["spawn"] = {"x": round(me.x), "y": round(me.y)} me.events.clear() for p in room.players.values(): if p.pid != pid and p.pid in me.view_set and not me.invisible: deliver(p, {"t": "penter", "p": me.public_full(), "count": len(room.players), "max": MAX_PER_ROOM}) await broadcast(room, {"t": "count", "n": len(room.players), "max": MAX_PER_ROOM}, exclude_pid=pid) log("INFO", "ws", "poll_join", "%s (%d/%d)" % (username, len(room.players), MAX_PER_ROOM), rid=str(pid)) event("join", "انضم %s إلى الغرفة" % username) return {"ok": True, "welcome": welcome} @app.post("/api/poll/sync") async def poll_sync(body: PollSyncIn): s = get_session(body.token) if not s: return err(401, "انتهت الجلسة", "session_expired") room, me = find_player(s["pid"]) if not me: return err(409, "غير منضم للغرفة — أعد تحميل الصفحة", "not_joined") me.last_seen = time.time() await ws_on_move(room, me, {"seq": body.seq, "x": body.x, "y": body.y, "dir": body.dir, "mov": body.mov, "wt": body.wt, "sal": body.sal, "ping": body.ping, "spd": body.spd, "has": body.has, "hol": body.hol}) events = list(me.events) me.events.clear() return {"ok": True, "events": events} @app.post("/api/poll/shot") async def poll_shot(body: PollShotIn): s = get_session(body.token) if not s: return err(401, "انتهت الجلسة", "session_expired") room, me = find_player(s["pid"]) if not me: return err(409, "غير منضم للغرفة", "not_joined") me.last_seen = time.time() await ws_on_shot(room, me, {"x": body.x, "y": body.y, "rad": body.rad}) events = list(me.events) me.events.clear() return {"ok": True, "events": events} @app.post("/api/poll/chat") async def poll_chat(body: PollChatIn): s = get_session(body.token) if not s: return err(401, "انتهت الجلسة", "session_expired") room, me = find_player(s["pid"]) if not me: return err(409, "غير منضم للغرفة", "not_joined") me.last_seen = time.time() await ws_on_chat(room, me, {"msg": body.msg}) events = list(me.events) me.events.clear() return {"ok": True, "events": events} @app.post("/api/poll/zhit") async def poll_zhit(body: PollZhitIn): s = get_session(body.token) if not s: return err(401, "انتهت الجلسة", "session_expired") room, me = find_player(s["pid"]) if not me: return err(409, "غير منضم للغرفة", "not_joined") me.last_seen = time.time() await ws_on_zhit(room, me, {"zid": body.zid}) events = list(me.events) me.events.clear() return {"ok": True, "events": events} def _admin_player(s): # حساب الإدارة من متغيرات البيئة (pid=-1) يملك Player حقيقيًا في الغرفة — لا حظر return find_player(s["pid"]) class BanIn(BaseModel): player_id: int minutes: int = Field(default=60, ge=-1, le=525600) reason: str = Field(default="", max_length=120) class UnbanIn(BaseModel): player_id: int class TPIn(BaseModel): player_id: int class JailIn(BaseModel): player_id: int minutes: int = Field(default=10, ge=1, le=1440) reason: str = Field(default="", max_length=120) class MoneyIn(BaseModel): player_id: int amount: int = Field(ge=-1000000, le=1000000) class SetRankIn(BaseModel): player_id: int rank_id: int = Field(ge=1, le=41) class SelfFlagIn(BaseModel): flag: str on: bool = True class SetIdIn(BaseModel): player_id: int public_id: int = Field(ge=1000000, le=9999999) class SetARankIn(BaseModel): player_id: int arank: int = Field(ge=0, le=5) class ClaimIn(BaseModel): tid: str = Field(min_length=1, max_length=24) def db_ban(pid, minutes, reason): ts = now_iso() try: if minutes < 0: until = datetime.fromtimestamp(time.time() + 10 * 365 * 86400, timezone.utc).isoformat() else: until = datetime.fromtimestamp(time.time() + minutes * 60, timezone.utc).isoformat() if USE_SUPABASE: r = httpx.patch(SUPABASE_URL + "/rest/v1/players?id=eq." + str(pid), headers=sb_headers(), timeout=15, json={ "banned_until": until, "ban_reason": reason, "updated_at": ts}) return r.status_code < 400 with _lk: _db.execute("UPDATE players SET banned_until=?, ban_reason=?, updated_at=? WHERE id=?", (until, reason, ts, pid)) _db.commit() return True except Exception as e: log("WARN", "db", "ban_failed", str(e)[:140]) return False def db_unban(pid): ts = now_iso() try: if USE_SUPABASE: r = httpx.patch(SUPABASE_URL + "/rest/v1/players?id=eq." + str(pid), headers=sb_headers(), timeout=15, json={ "banned_until": None, "ban_reason": "", "updated_at": ts}) return r.status_code < 400 with _lk: _db.execute("UPDATE players SET banned_until=NULL, ban_reason='', updated_at=? WHERE id=?", (ts, pid)) _db.commit() return True except Exception as e: log("WARN", "db", "unban_failed", str(e)[:140]) return False def db_add_money(pid, delta): try: if USE_SUPABASE: r = httpx.get(SUPABASE_URL + "/rest/v1/players?id=eq." + str(pid) + "&select=money", headers=sb_headers(), timeout=15) cur = (r.json()[0].get("money") or 0) if r.status_code < 400 and r.json() else 0 r2 = httpx.patch(SUPABASE_URL + "/rest/v1/players?id=eq." + str(pid), headers=sb_headers(), timeout=15, json={ "money": max(0, cur + delta), "updated_at": now_iso()}) return r2.status_code < 400 with _lk: _db.execute("UPDATE players SET money=max(0, money+?), updated_at=? WHERE id=?", (delta, now_iso(), pid)) _db.commit() return True except Exception as e: log("WARN", "db", "money_failed", str(e)[:140]) return False def db_set_rank(pid, rank_id): return db_save_profile(pid, None, rank_id) async def _target(player_id): return find_player(player_id) @app.post("/api/admin/ban") async def admin_ban(body: BanIn, request: Request): s = require_perm(request, "ban") room, p = await _target(body.player_id) db_ban(body.player_id, body.minutes, body.reason) label = "دائم" if body.minutes < 0 else ("%d دقيقة" % body.minutes) if p: deliver(p, {"t": "banned", "by": s["username"], "minutes": body.minutes, "reason": body.reason}) if p.transport == "ws" and p.ws is not None: try: await p.ws.close(code=4004, reason="محظور %s" % label) except Exception: pass else: room.remove(p.pid) db_audit(s["pid"], s["username"], "ban", body.player_id, (p.name if p else str(body.player_id)), "%s | %s" % (label, body.reason)) log("WARN", "admin", "ban", "%s banned %s (%s)" % (s["username"], body.player_id, label)) event("ban", "حظر %s اللاعب %s (%s)" % (s["username"], (p.name if p else str(body.player_id)), label)) if room: await room_announce(room, "تم حظر %s — من طرف %s" % ((p.name if p else ("اللاعب #%d" % body.player_id)), s["username"]), "red") return {"ok": True} @app.post("/api/admin/unban") def admin_unban(body: UnbanIn, request: Request): s = require_perm(request, "unban") db_unban(body.player_id) db_audit(s["pid"], s["username"], "unban", body.player_id) log("WARN", "admin", "unban", "%s unbanned %s" % (s["username"], body.player_id)) return {"ok": True} @app.post("/api/admin/tpto") async def admin_tpto(body: TPIn, request: Request): s = require_perm(request, "tpto") if s["arank"] == 1: ok_cd, left = cd_ok("tp:" + str(s["pid"]), 120) if not ok_cd: raise HTTPException(status_code=429, detail="انتظر %d ثانية قبل التنقل التالي" % left) _r, mep = _admin_player(s) room, p = await _target(body.player_id) if not mep or not p: return err(404, "اللاعب غير متصل", "not_found") deliver(mep, {"t": "tp", "x": round(p.x), "y": round(p.y)}) db_audit(s["pid"], s["username"], "tpto", body.player_id, p.name) return {"ok": True} @app.post("/api/admin/bring") async def admin_bring(body: TPIn, request: Request): s = require_perm(request, "bring") _r, mep = _admin_player(s) room, p = await _target(body.player_id) if not mep or not p: return err(404, "اللاعب غير متصل", "not_found") deliver(p, {"t": "tp", "x": round(mep.x), "y": round(mep.y)}) db_audit(s["pid"], s["username"], "bring", body.player_id, p.name) return {"ok": True} @app.post("/api/admin/jail") async def admin_jail(body: JailIn, request: Request): s = require_perm(request, "jail") room, p = await _target(body.player_id) if not p: return err(404, "اللاعب غير متصل", "not_found") p.jail_until = time.time() + body.minutes * 60 deliver(p, {"t": "tp", "x": round(JAIL_X), "y": round(JAIL_Y)}) deliver(p, {"t": "sys", "msg": "سُجن لمدة %d دقيقة | السبب: %s" % (body.minutes, body.reason or "بدون")}) db_audit(s["pid"], s["username"], "jail", body.player_id, p.name, "%dm | %s" % (body.minutes, body.reason)) event("jail", "سجن %s اللاعب %s لمدة %d دقيقة" % (s["username"], p.name, body.minutes)) await room_announce(room, "تم سجن %s لمدة %d دقيقة — من طرف %s" % (p.name, body.minutes, s["username"]), "yellow") log("WARN", "admin", "jail", "%s jailed %s %dm" % (s["username"], p.name, body.minutes)) return {"ok": True} @app.post("/api/admin/money") def admin_money(body: MoneyIn, request: Request): s = require_perm(request, "money") ok = db_add_money(body.player_id, body.amount) room, p = find_player(body.player_id) if p: deliver(p, {"t": "money", "amount": body.amount}) db_audit(s["pid"], s["username"], "money", body.player_id, (p.name if p else str(body.player_id)), str(body.amount)) event("money", "أعطى %s مبلغ %d للاعب %s" % (s["username"], body.amount, (p.name if p else str(body.player_id)))) return {"ok": ok} @app.post("/api/admin/setrank") async def admin_setrank(body: SetRankIn, request: Request): s = require_perm(request, "setrank") room, p = await _target(body.player_id) old_rank = p.rank_id if p else 1 if not p: try: if USE_SUPABASE: rr = httpx.get(SUPABASE_URL + "/rest/v1/players?id=eq." + str(body.player_id) + "&select=rank_id&limit=1", headers=sb_headers(), timeout=15) old_rank = rr.json()[0].get("rank_id") or 1 if rr.status_code < 400 and rr.json() else 1 else: with _lk: cur = _db.execute("SELECT rank_id FROM players WHERE id=?", (body.player_id,)) rowx = cur.fetchone() old_rank = rowx[0] if rowx else 1 except Exception: old_rank = 1 ok = db_set_rank(body.player_id, body.rank_id) if not ok: return err(500, "فشل حفظ الرتبة في قاعدة البيانات", "db_error") if p: p.rank_id = body.rank_id p.profile = p.profile or {} deliver(p, {"t": "rank", "rankId": body.rank_id}) # حدث فوري لكل العملاء — تحديث Lv فورًا دون انتظار حركة if room: for o in room.players.values(): deliver(o, {"t": "rankupd", "id": body.player_id, "rankId": body.rank_id}) db_audit(s["pid"], s["username"], "setrank", body.player_id, (p.name if p else str(body.player_id)), "rank %s -> %s" % (old_rank, body.rank_id)) event("setrank", "غيّر %s رتبة %s من %s إلى %d" % (s["username"], (p.name if p else str(body.player_id)), old_rank, body.rank_id)) if room: await room_announce(room, "ترقية: حصل %s على الرتبة (%d)" % ((p.name if p else ("اللاعب #%d" % body.player_id)), body.rank_id), "red") return {"ok": ok} @app.post("/api/admin/self") async def admin_self(body: SelfFlagIn, request: Request): s = require_perm(request, "self_inv") room, mep = _admin_player(s) if not mep: return err(404, "أنت غير متصل بالغرفة", "not_found") if body.flag == "invisible": mep.invisible = body.on vis = room.visible(mep) if body.on: for pid in mep.view_set: p2 = room.players.get(pid) if p2: deliver(p2, {"t": "pviewleave", "id": mep.pid}) mep.view_set = set() else: for p2 in vis: deliver(p2, {"t": "penter", "p": mep.public_full(), "count": len(room.players), "max": MAX_PER_ROOM}) mep.view_set = set(p.pid for p in vis) db_audit(s["pid"], s["username"], "invisible", mep.pid, mep.name, str(body.on)) return {"ok": True} if body.flag == "noclip": if not has_perm(s, "self_nc"): raise HTTPException(status_code=403, detail="غير مصرح") mep.noclip = body.on db_audit(s["pid"], s["username"], "noclip", mep.pid, mep.name, str(body.on)) return {"ok": True} return err(400, "أداة غير معروفة", "bad_flag") def db_list_banned(): import urllib.parse now_raw = datetime.now(timezone.utc).isoformat(timespec="seconds") try: if USE_SUPABASE: now = urllib.parse.quote(now_raw, safe="") r = httpx.get(SUPABASE_URL + "/rest/v1/players?banned_until=gte." + now + "&select=id,username,admin_rank,banned_until,ban_reason&order=banned_until.desc&limit=100", headers=sb_headers(), timeout=20) return r.json() if r.status_code < 400 else [] with _lk: cur = _db.execute("SELECT id,username,admin_rank,banned_until,ban_reason FROM players " "WHERE banned_until IS NOT NULL AND banned_until > ? " "ORDER BY banned_until DESC LIMIT 100", (now_raw,)) cols = [c[0] for c in cur.description] return [dict(zip(cols, row)) for row in cur.fetchall()] except Exception as e: log("WARN", "db", "banned_list_failed", str(e)[:140]) return [] @app.post("/api/admin/unmute") def admin_unmute(body: UnbanIn, request: Request): s = require_perm(request, "unmute") for r in ROOMS.values(): p = r.players.get(body.player_id) if p: p.muted_until = 0 deliver(p, {"t": "sys", "msg": "تم إلغاء كتمك — التزم بقواعد الدردشة"}) db_audit(s["pid"], s["username"], "unmute", body.player_id, p.name) event("unmute", "ألغى %s كتم اللاعب %s" % (s["username"], p.name)) return {"ok": True} return err(404, "اللاعب غير متصل", "not_found") @app.get("/api/admin/banned") def admin_banned(request: Request): s = require_perm(request, "banned") return {"ok": True, "banned": db_list_banned()} @app.get("/api/admin/events") def admin_events(request: Request): s = require_perm(request, "events") return {"ok": True, "events": list(EVENTS)[::-1][:200]} # ============================ Daily Missions ============================ PROGRESS = {} def _day_key(): return datetime.now(timezone.utc).strftime("%Y-%m-%d") def get_prog(pid): d = _day_key() rec = PROGRESS.get(pid) if not rec or rec["day"] != d: rec = {"day": d, "c": defaultdict(float)} PROGRESS[pid] = rec return rec["c"] def bump(pid, key, amt): if pid and pid > 0: get_prog(pid)[key] += amt def flush_prog(pid): day = _day_key() st = db_missions_load(pid, day) if not st or not st.get("tasks"): return live = get_prog(pid) sp = st.setdefault("saved_prog", {}) changed = False for k, v in live.items(): if v > sp.get(k, 0): sp[k] = v changed = True if changed: db_missions_save(pid, day, st) MISSION_NORMAL = [ {"tid": "walk1", "name": "سير ميداني", "desc": "امشِ مسافة %d متر داخل القاعدة", "key": "walk", "n": [400, 600, 800], "r": {"xp": 25, "gold": 15}}, {"tid": "shots1", "name": "تدريب رماية", "desc": "أطلق %d طلقة أثناء التدريب", "key": "shots", "n": [40, 60], "r": {"xp": 25, "gold": 20}}, {"tid": "sal1", "name": "انضباط عسكري", "desc": "قدّم التحية العسكرية %d مرات", "key": "salutes", "n": [3, 5], "r": {"xp": 15, "gold": 10}}, {"tid": "chat1", "name": "تواصل", "desc": "أرسل %d رسائل في الدردشة العامة", "key": "chat", "n": [4, 6], "r": {"xp": 15, "gold": 10}}, {"tid": "time1", "name": "مثابرة", "desc": "ابقَ داخل اللعبة %d دقيقة", "key": "playmin", "n": [10, 15], "r": {"xp": 30, "gold": 20}}, ] MISSION_HARD = [ {"tid": "hshots", "name": "رماية مكثفة", "desc": "أطلق %d طلقة خلال اليوم", "key": "shots", "n": [150, 200], "r": {"xp": 90, "gold": 60}}, {"tid": "hwalk", "name": "مسيرة طويلة", "desc": "امشِ %d متر خلال اليوم", "key": "walk", "n": [1500, 2000], "r": {"xp": 70, "gold": 50}}, {"tid": "htime", "name": "خدمة كاملة", "desc": "العب %d دقيقة اليوم", "key": "playmin", "n": [30, 45], "r": {"xp": 100, "gold": 70}}, {"tid": "hsal", "name": "تحيات متقنة", "desc": "قدّم التحية العسكرية %d مرات", "key": "salutes", "n": [10, 12], "r": {"xp": 60, "gold": 45}}, {"tid": "hchat", "name": "نشاط مجتمعي", "desc": "شارك بـ %d رسائل محترمة في الدردشة", "key": "chat", "n": [15, 20], "r": {"xp": 60, "gold": 45}}, ] def gen_daily_tasks(day): rng = random.Random(day) normal = rng.sample(MISSION_NORMAL, 5) hard = rng.sample(MISSION_HARD, 2) out = [] for t in normal + hard: n = rng.choice(t["n"]) out.append({"tid": t["tid"], "name": t["name"], "desc": t["desc"] % n, "key": t["key"], "target": n, "reward": t["r"], "hard": t in MISSION_HARD, "claimed": False}) return out def db_missions_load(pid, day): try: if USE_SUPABASE: r = httpx.get(SUPABASE_URL + "/rest/v1/daily_missions?player_id=eq." + str(pid) + "&day=eq." + day + "&select=tasks&limit=1", headers=sb_headers(), timeout=15) if r.status_code < 400 and r.json(): return json.loads(r.json()[0]["tasks"] or "{}") else: with _lk: cur = _db.execute("SELECT tasks FROM daily_missions WHERE player_id=? AND day=?", (pid, day)) row = cur.fetchone() if row: return json.loads(row[0] or "{}") except Exception as e: log("WARN", "db", "missions_load_failed", str(e)[:140]) return None def db_missions_save(pid, day, payload): try: body = _j(payload) if USE_SUPABASE: r = httpx.post(SUPABASE_URL + "/rest/v1/daily_missions", headers=sb_headers(), timeout=15, json={ "player_id": pid, "day": day, "tasks": body, "updated_at": now_iso()}, params={"on_conflict": "player_id,day"}) if r.status_code >= 400: httpx.patch(SUPABASE_URL + "/rest/v1/daily_missions?player_id=eq." + str(pid) + "&day=eq." + day, headers=sb_headers(), timeout=15, json={"tasks": body, "updated_at": now_iso()}) else: with _lk: _db.execute("INSERT OR REPLACE INTO daily_missions (player_id,day,tasks,updated_at) VALUES (?,?,?,?)", (pid, day, body, now_iso())) _db.commit() except Exception as e: log("WARN", "db", "missions_save_failed", str(e)[:140]) def missions_state(pid): day = _day_key() st = db_missions_load(pid, day) if not st or not st.get("tasks"): st = {"tasks": gen_daily_tasks(day), "saved_prog": {}} db_missions_save(pid, day, st) live = get_prog(pid) out = [] for t in st["tasks"]: prog = max(live.get(t["key"], 0), st.get("saved_prog", {}).get(t["key"], 0)) out.append({"tid": t["tid"], "name": t["name"], "desc": t["desc"], "hard": t["hard"], "target": t["target"], "reward": t["reward"], "progress": int(round(min(prog, t["target"] * 10))), "done": prog >= t["target"], "claimed": t.get("claimed", False)}) return {"ok": True, "day": day, "tasks": out} @app.get("/api/missions") def missions_get(request: Request): s = get_session(bearer(request)) if not s or s["pid"] < 0: return err(401, "انتهت الجلسة", "session_expired") return missions_state(s["pid"]) @app.post("/api/missions/claim") def missions_claim(body: ClaimIn, request: Request): s = get_session(bearer(request)) if not s or s["pid"] < 0: return err(401, "انتهت الجلسة", "session_expired") pid = s["pid"] day = _day_key() st = db_missions_load(pid, day) if not st or not st.get("tasks"): return err(404, "لا توجد مهام اليوم", "not_found") live = get_prog(pid) t = next((x for x in st["tasks"] if x["tid"] == body.tid), None) if not t: return err(404, "مهمة غير موجودة", "not_found") if t.get("claimed"): return err(409, "استلمت مكافأة هذه المهمة مسبقًا", "already_claimed") prog = max(live.get(t["key"], 0), st.get("saved_prog", {}).get(t["key"], 0)) if prog < t["target"]: return err(400, "لم تكتمل المهمة بعد", "not_done") t["claimed"] = True st.setdefault("saved_prog", {})[t["key"]] = prog db_missions_save(pid, day, st) db_add_xp(pid, t["reward"].get("xp", 0)) if t["reward"].get("gold"): db_add_money(pid, t["reward"]["gold"]) event("mission", "أكمل %s مهمة «%s»" % (s["username"], t["name"])) return {"ok": True, "reward": t["reward"], "state": missions_state(pid)} # ============================ Staff / Users / ID management ============================ @app.post("/api/admin/setid") def admin_setid(body: SetIdIn, request: Request): s = require_admin(request) if s["arank"] < 4: raise HTTPException(status_code=403, detail="تغيير المعرف متاح لـ Owner فقط") if not public_id_ok(body.public_id): return err(400, "معرف غير مقبول — 7 أرقام غير نمطية", "bad_id") if db_pub_exists(body.public_id): return err(409, "هذا المعرف مستخدم من لاعب آخر", "taken") ok = db_set_pub(body.player_id, body.public_id) _r, p = find_player(body.player_id) if p: p.pub = body.public_id deliver(p, {"t": "sys", "msg": "تم تحديث معرفك العام إلى " + str(body.public_id)}) db_audit(s["pid"], s["username"], "setid", body.player_id, (p.name if p else str(body.player_id)), str(body.public_id)) event("setid", "غيّر %s معرف اللاعب %s إلى %d" % (s["username"], (p.name if p else str(body.player_id)), body.public_id)) return {"ok": ok} @app.post("/api/admin/setarank") async def admin_setarank(body: SetARankIn, request: Request): s = require_perm(request, "setarank") # Owner وحيد: الرتب 3+ محجوزة لحساب env — لا يمكن إسنادها عبر الواجهة أو API if body.arank >= 3: raise HTTPException(status_code=403, detail="هذه الرتبة محجوزة لحساب المالك — لا يمكن إسنادها") if body.player_id < 0: raise HTTPException(status_code=403, detail="حساب المالك محمي ولا يمكن تعديل رتبته") if body.player_id == s["pid"]: raise HTTPException(status_code=403, detail="لا يمكنك تعديل رتبتك الإدارية من هنا") old = db_get_arank(body.player_id) if old >= 3: raise HTTPException(status_code=403, detail="لا يمكن تعديل رتبة هذا الحساب") ok = db_set_arank(body.player_id, body.arank) if not ok: return err(500, "فشل الحفظ في قاعدة البيانات — لم تُطبق أي تغييرات", "db_error") # مزامنة الجلسات النشطة دون كسرها (الهوية والاتصال يبقيان كما هما) refresh_sessions(body.player_id, body.arank) room, p = await _target(body.player_id) if p: # تحديث الرتبة والصلاحيات فقط — لا نمس: pid أو pub أو الموضع أو الغرفة أو view_set p.arank = body.arank p.role = "admin" if body.arank > 0 else "player" deliver(p, {"t": "role_updated", "arank": body.arank, "role": p.role}) if room: for o in room.players.values(): deliver(o, {"t": "role_updated", "id": p.pid, "arank": body.arank, "role": p.role, "name": p.name, "pub": p.pub}) name = (p.name if p else str(body.player_id)) db_audit(s["pid"], s["username"], "setarank", body.player_id, name, "admin_rank %s -> %s" % (old, body.arank)) event("setarank", "%s: %s (%s -> %s)" % (s["username"], name, ADMIN_RANKS.get(old, old), ADMIN_RANKS.get(body.arank, body.arank))) if room: await room_announce(room, "تغيير في طاقم الإدارة: %s (%s)" % (name, ADMIN_RANKS.get(body.arank, "player")), "yellow") return {"ok": True} @app.get("/api/admin/staff") def admin_staff(request: Request): s = require_perm(request, "staff") online = {} for r in ROOMS.values(): for pid in r.players: online[pid] = True try: if USE_SUPABASE: r = httpx.get(SUPABASE_URL + "/rest/v1/players?is_admin=eq.true&select=id,username,admin_rank,last_login_at,public_id" "&order=admin_rank.desc,last_login_at.desc&limit=100", headers=sb_headers(), timeout=20) rows = r.json() if r.status_code < 400 else [] else: with _lk: cur = _db.execute("SELECT id,username,admin_rank,last_login_at,public_id FROM players " "WHERE is_admin=1 ORDER BY admin_rank DESC, last_login_at DESC LIMIT 100") cols = [c[0] for c in cur.description] rows = [dict(zip(cols, row)) for row in cur.fetchall()] except Exception as e: log("WARN", "db", "staff_failed", str(e)[:140]) rows = [] out = [] for row in rows: pid = row.get("id") out.append({"id": pid, "name": row.get("username"), "arank": row.get("admin_rank") or 0, "pub": row.get("public_id") or 0, "online": bool(online.get(pid)), "last_login_at": str(row.get("last_login_at") or "")}) return {"ok": True, "staff": out} @app.get("/api/admin/users") def admin_users(request: Request, page: int = 0): s = require_perm(request, "users") page = max(0, int(page)) try: if USE_SUPABASE: r = httpx.get(SUPABASE_URL + "/rest/v1/players?select=id,username,admin_rank,rank_id,public_id,last_login_at" "&order=is_admin.desc,admin_rank.desc,rank_id.desc,id.asc&limit=11&offset=" + str(page * 10), headers=sb_headers(), timeout=20) rows = r.json() if r.status_code < 400 else [] else: with _lk: cur = _db.execute("SELECT id,username,admin_rank,rank_id,public_id,last_login_at FROM players " "ORDER BY is_admin DESC, admin_rank DESC, rank_id DESC, id ASC LIMIT 11 OFFSET ?", (page * 10,)) cols = [c[0] for c in cur.description] rows = [dict(zip(cols, row)) for row in cur.fetchall()] except Exception as e: log("WARN", "db", "users_failed", str(e)[:140]) rows = [] has_more = len(rows) > 10 rows = rows[:10] return {"ok": True, "users": rows, "page": page, "has_more": has_more} async def room_announce(room, msg, color="yellow"): await broadcast(room, {"t": "chat", "id": 0, "name": "الخادم", "msg": msg, "color": color, "sys": True}) SERVER_TIPS = [ "التزم بقواعد الاحترام داخل الدردشة — العقوبات تُطبق تلقائيًا", "استغلال الثغرات يؤدي إلى حظر دائم دون سابق إنذار", "لن تطلب الإدارة كلمة المرور أبدًا — أي طلب من هذا النوع احتيال", "حركات غير طبيعية أو متكررة تُراجع يدويًا — العب بعدل", "الرسائل المتكررة تُقيَّد تلقائيًا لتجنب الإزعاج", "انتحال صفة الإدارة يؤدي إلى حظر فوري", "تجنب مشاركة معلوماتك الشخصية مع أي لاعب", "الروابط الخارجية في الدردشة ليست مسؤولية الإدارة", "الغش يُكتشف — النزاهة تحفظ حسابك", "أبلغ عن المخالفات بدل المواجهة — التقرير أسرع وأدق", "المتاجرة بالحسابات خارج نطاق المسؤولية وتعرضك للحظر", "الحفاظ على اتصال مستقر يحسن تجربة اللعب الجماعي", "لا تضغط الأزرار المتاحة للإدارة إلا إذا كنت مسؤولًا معتمدًا", "الإيموجي ممنوع في الدردشة لتجنب الإزعاج البصري", "أي محاولة للتلاعب بالخادم تُسجل وتُحظر تلقائيًا", "احترم وقت الجميع — اللعبة تجربة مشتركة", "الحسابات مرتبطة بالجهاز — المخالفات تتبعك بين الجلسات", "تغيير المناطق المقيدة يُعتبر اختراقًا للمنطقة العسكرية", "إطلاق النار داخل القاعدة يُقيَّد — استعمل السلاح بمسؤولية", "التحديثات تُطبق على الجميع بالتساوي — لا استثناءات", "احتفظ بمعرفك العام (7 أرقام) — هو هويتك الرسمية", "المهام اليومية تتجدد عند 00:00 بتوقيت UTC", "المكافآت تُستلم مرة واحدة لكل مهمة — لا يمكن تكرارها", "مخالفة قواعد الدردشة تبدأ بالكتم وتصعَّد حسب التكرار", "الحظر المؤقت لا يلغي سجل المخالفات", "استعمل زر التحية العسكرية عند لقاء الرتب العليا", "أداء جهازك يتأثر بالتطبيقات الخلفية — أغلقها أثناء اللعب", "تقارير الأخطاء تُرسل تلقائيًا وتساعدنا على التحسين", ] async def server_tips(): await asyncio.sleep(240) while True: try: room = ROOMS.get("global") if room and room.players: await room_announce(room, random.choice(SERVER_TIPS), "green") except Exception as e: log("WARN", "server", "tips_error", str(e)[:120]) await asyncio.sleep(random.randint(300, 600)) # ============================ Zombies (server-authoritative) ============================ ZCELL = 512 zombies = {} zombies_grid = defaultdict(set) ZOMBIE_ZONES = [ (900, 900), (3900, 900), (900, 3900), (3900, 3900), (2400, 800), (800, 2400), (4000, 2400), (2400, 4000), (1500, 1500), (3300, 3300), ] Z_PER_ZONE = 4 Z_SPEED = 42.0 Z_AGGRO = 320.0 Z_ATTACK = 30.0 Z_HP = 100 Z_HIT = 34 Z_RESPAWN = 30 def zkey(x, y): return (int(x // ZCELL), int(y // ZCELL)) def init_zombies(): if zombies: return zid = 1 for zi, (zx, zy) in enumerate(ZOMBIE_ZONES): for k in range(Z_PER_ZONE): x = float(zx + (k % 2) * 90 - 45 + zi * 7) y = float(zy + (k // 2) * 90 - 45) zombies[zid] = {"id": zid, "zone": zi, "x": x, "y": y, "dir": 0, "hp": Z_HP, "state": "idle", "wt": 0.0, "dead_until": 0.0} zombies_grid[zkey(x, y)].add(zid) zid += 1 log("INFO", "zombies", "spawned", "%d zombies in %d fixed zones" % (len(zombies), len(ZOMBIE_ZONES))) async def zombie_ai(): # ذكاء خفيف: يعمل فقط للزومبي القريبين من لاعبين — بعيدًا = نائم دون تغيير حالة عادل while True: await asyncio.sleep(0.12) try: t = time.time() room = ROOMS.get("global") players = list(room.players.values()) if room else [] active = set() for p in players: cx, cy = int(p.x // ZCELL), int(p.y // ZCELL) for gx2 in range(cx - 1, cx + 2): for gy2 in range(cy - 1, cy + 2): active |= zombies_grid.get((gx2, gy2), set()) pending = defaultdict(list) for zid in active: z = zombies.get(zid) if not z or z["state"] == "dead" or z["hp"] <= 0: continue nearest, nd = None, 1e9 for p in players: d = math.hypot(p.x - z["x"], p.y - z["y"]) if d < nd: nd, nearest = d, p moved = False if nearest and nd < Z_AGGRO: if nd > Z_ATTACK: dx = (nearest.x - z["x"]) / nd dy = (nearest.y - z["y"]) / nd nx = z["x"] + dx * Z_SPEED * 0.12 ny = z["y"] + dy * Z_SPEED * 0.12 okc, nkc = zkey(z["x"], z["y"]), zkey(nx, ny) if okc != nkc: zombies_grid[okc].discard(zid) zombies_grid[nkc].add(zid) z["x"], z["y"] = nx, ny z["state"] = "walk" z["dir"] = 1 if dx > 0 else 3 if abs(dx) > abs(dy) else (0 if dy > 0 else 2) if abs(dy) >= abs(dx): z["dir"] = 0 if dy > 0 else 2 z["wt"] += 0.12 moved = True else: z["state"] = "attack" if not moved and z["state"] != "idle": z["state"] = "idle" row = [zid, round(z["x"]), round(z["y"]), z["dir"], 1 if z["state"] == "walk" else (2 if z["state"] == "attack" else 0), round(z["wt"], 1)] for p in players: if math.hypot(p.x - z["x"], p.y - z["y"]) <= VIEW_RANGE: pending[p.pid].append(row) for p in players: if pending.get(p.pid): deliver(p, {"t": "zmove", "z": pending[p.pid]}) for zid, z in zombies.items(): if z["state"] == "dead" and t > z["dead_until"]: zx, zy = ZOMBIE_ZONES[z["zone"]] z["x"] = float(zx + random.randint(-60, 60)) z["y"] = float(zy + random.randint(-60, 60)) z["hp"] = Z_HP z["state"] = "idle" z["wt"] = 0.0 zombies_grid[zkey(z["x"], z["y"])].add(zid) except Exception as e: log("ERROR", "zombies", "ai_error", str(e)[:160]) async def ws_on_zhit(room, me, d): t = time.time() if t - me.last_zhit < 0.09: return me.last_zhit = t zid = int(d.get("zid", 0) or 0) z = zombies.get(zid) if not z or z["state"] == "dead" or z["hp"] <= 0: return if math.hypot(me.x - z["x"], me.y - z["y"]) > 280: log("WARN", "zombies", "hit_too_far", "%s zid=%d" % (me.name, zid)) return z["hp"] -= Z_HIT if z["hp"] <= 0: z["state"] = "dead" z["dead_until"] = time.time() + Z_RESPAWN zombies_grid[zkey(z["x"], z["y"])].discard(zid) db_add_xp(me.pid, 15) db_add_money(me.pid, 5) await broadcast(room, {"t": "zdie", "zid": zid, "x": round(z["x"]), "y": round(z["y"]), "by": me.pid, "byname": me.name}) event("zkill", "قضى %s على زومبي #%d" % (me.name, zid)) else: await broadcast(room, {"t": "zhit", "zid": zid, "hp": z["hp"]}) # ============================ WebSocket ============================ async def ws_on_move(room, me, d): seq = int(d.get("seq", 0) or 0) if seq <= me.last_seq: return t = time.time() if t - me.last_move_at < MOVE_MIN_INTERVAL: return try: nx = float(d.get("x", me.x)) ny = float(d.get("y", me.y)) except Exception: return # تصحيح سلس: قبول الحركة مع تقليص التجاوز بدل الرفض الصلب (لا ارتداد مطاطي) interval = max(0.05, t - me.last_move_at) if me.noclip: allowed = 10 ** 9 elif me.role == "admin": # حد أعلى ×10 لسرعة الإداري (96*10≈960px/s + هامش) allowed = min(220.0, 1500.0 * interval * 1.5 + 14) else: allowed = min(90.0, 420.0 * interval * 1.5 + 14) dx, dy = nx - me.x, ny - me.y dist = math.hypot(dx, dy) if dist > allowed: k = allowed / max(dist, 0.001) nx = me.x + dx * k ny = me.y + dy * k deliver(me, {"t": "snap", "x": round(nx), "y": round(ny)}) if not me.noclip: nx = max(160.0, min(WORLD_W - 160.0, nx)) ny = max(150.0, min(WORLD_H - 160.0, ny)) # السجن: تقييد داخل دائرة السجن أثناء مدة الحبس if me.jail_until > t: jdx, jdy = nx - JAIL_X, ny - JAIL_Y jd = math.hypot(jdx, jdy) if jd > JAIL_R: nx = JAIL_X + jdx / jd * JAIL_R ny = JAIL_Y + jdy / jd * JAIL_R me.last_seq = seq me.last_move_at = t moved = math.hypot(nx - me.x, ny - me.y) if moved > 0.5: bump(me.pid, "walk", moved / 32.0) sal_flag = 1 if d.get("sal") else 0 if sal_flag and not me._sal_flag: bump(me.pid, "salutes", 1) me._sal_flag = bool(sal_flag) room.rekey(me, nx, ny) me.x, me.y = nx, ny try: me.ping = max(0, min(5000, int(d.get("ping", me.ping) or 0))) me.has_w = 1 if d.get("has") else 0 me.hol_w = 1 if d.get("hol") else 0 except Exception: pass try: me.dir = int(d.get("dir", me.dir)) % 4 except Exception: pass me.mov = 1 if d.get("mov") else 0 try: me.wt = float(d.get("wt", me.wt)) except Exception: pass me.sal = 1 if d.get("sal") else 0 # Interest management: full state to newly visible, view-leave event, delta to the rest. vis = room.visible(me) new_set = set(p.pid for p in vis) for pid in (new_set - me.view_set): p = room.players.get(pid) if p: deliver(me, {"t": "penter", "p": p.public_full(), "count": len(room.players), "max": MAX_PER_ROOM}) if not me.invisible: deliver(p, {"t": "penter", "p": me.public_full(), "count": len(room.players), "max": MAX_PER_ROOM}) for pid in (me.view_set - new_set): p = room.players.get(pid) if p: deliver(me, {"t": "pviewleave", "id": pid}) deliver(p, {"t": "pviewleave", "id": me.pid}) me.view_set = new_set if me.invisible: # وضع الاختفاء: لا مزامنة حركة للآخرين إطلاقًا return msg = {"t": "pmove", "id": me.pid, "x": round(me.x), "y": round(me.y), "dir": me.dir, "mov": me.mov, "wt": round(me.wt, 1), "sal": me.sal, "has": me.has_w, "hol": me.hol_w, "ping": me.ping, "seq": seq} for p in vis: deliver(p, msg) async def ws_on_shot(room, me, d): t = time.time() if t - me.last_shot_at < SHOT_MIN_INTERVAL: return try: x = float(d.get("x", me.x)) y = float(d.get("y", me.y)) rad = float(d.get("rad", 0)) except Exception: return if math.hypot(x - me.x, y - me.y) > 90: log("WARN", "ws", "shot_far_muzzle", me.name) return me.last_shot_at = t bump(me.pid, "shots", 1) msg = {"t": "shot", "id": me.pid, "x": round(x), "y": round(y), "rad": round(rad, 3)} for p in room.visible(me): deliver(p, msg) async def ws_on_chat(room, me, d): text, why = validate_chat(d.get("msg", "")) if not text: if why != "empty": deliver(me, {"t": "error", "code": "chat_rejected", "msg": why}) return t = time.time() if t < me.muted_until: deliver(me, {"t": "error", "code": "chat_rejected", "msg": "تم رفض الرسالة (كتم إداري)"}) return if t - me.last_chat_at < me.chat_wait: wait = int(math.ceil(me.chat_wait - (t - me.last_chat_at))) deliver(me, {"t": "error", "code": "chat_slow", "msg": "انتظر %d ثوانٍ ثم أعد المحاولة" % wait, "wait": wait}) return me.chat_wait = chat_delay(len(room.players)) me.last_chat_at = t bump(me.pid, "chat", 1) msg = {"t": "chat", "id": me.pid, "name": me.name, "msg": text, "arank": me.arank, "role": me.role} for p in list(room.players.values()): deliver(p, msg) try: loop = asyncio.get_running_loop() loop.run_in_executor(None, db_log_chat, me.pid, me.name, text, room.name) except Exception: pass async def broadcast(room, obj, exclude_pid=None): for p in list(room.players.values()): if p.pid != exclude_pid: deliver(p, obj) @app.websocket("/ws") async def ws_endpoint(ws: WebSocket, token: str = ""): log("DEBUG", "ws", "handshake", "token_len=%d" % len(token or ""), rid=(token[:8] if token else None)) await ws.accept() s = get_session(token) if not s: log("WARN", "ws", "auth_failed", rid=token[:8] if token else None) await ws.close(code=4401) return pid, username, role = s["pid"], s["username"], s["role"] room_name = "global" room = get_room(room_name) # Prevent double presence from reconnects: replace the old connection. if pid in room.players: old = room.players[pid] room.remove(pid) if old.transport == "ws" and old.ws is not None: try: await old.ws.close(code=4000) except Exception: pass log("INFO", "ws", "replaced_duplicate", username) if len(room.players) >= MAX_PER_ROOM: await safe_send(ws, {"t": "error", "code": "room_full", "msg": "الغرفة ممتلئة (%d/%d)" % (MAX_PER_ROOM, MAX_PER_ROOM)}) await ws.close(code=4429) log("WARN", "ws", "room_full_reject", username) return profile = db_get_profile(pid) if pid > 0 else {"character_data": dict(DEFAULT_CHAR), "rank_id": 41} rank_id = (profile or {}).get("rank_id") or 1 me = Player(pid, username, role, rank_id, (profile or {}).get("character_data") or dict(DEFAULT_CHAR), ws, s.get("arank", 0)) me.pub = db_get_pub(pid) if pid > 0 else 0 room.add(me) me.view_set = set(p.pid for p in room.visible(me)) welcome = {"t": "welcome", "id": pid, "room": room_name, "count": len(room.players), "max": MAX_PER_ROOM, "players": [p.public_full() for p in room.players.values() if p.pid != pid and p.pid in me.view_set and not p.invisible]} welcome["spawn"] = {"x": round(me.x), "y": round(me.y)} await safe_send(ws, welcome) for p in room.players.values(): if p.pid != pid and p.pid in me.view_set and not me.invisible: deliver(p, {"t": "penter", "p": me.public_full(), "count": len(room.players), "max": MAX_PER_ROOM}) await broadcast(room, {"t": "count", "n": len(room.players), "max": MAX_PER_ROOM}, exclude_pid=pid) log("INFO", "ws", "join", "%s -> %s (%d/%d)" % (username, room_name, len(room.players), MAX_PER_ROOM), rid=str(pid)) event("join", "انضم %s إلى الغرفة" % username) try: while True: raw = await ws.receive_text() me.last_seen = time.time() if len(raw) > MAX_MSG_BYTES: log("WARN", "ws", "oversize_msg", me.name) continue try: d = json.loads(raw) except Exception: log("WARN", "ws", "bad_json", me.name) continue if not isinstance(d, dict) or "t" not in d: continue tnow = time.time() me.msg_times.append(tnow) if len(me.msg_times) >= 8 and tnow - me.msg_times[0] < 1.0: if tnow - me.msg_times[0] < 1.0 / WS_MSG_PER_SEC * 8: log("WARN", "ws", "msg_flood", me.name) continue typ = d.get("t") if typ == "ping": if "ts" in d: deliver(me, {"t": "pong", "ts": d.get("ts")}) elif typ == "move": await ws_on_move(room, me, d) elif typ == "shot": await ws_on_shot(room, me, d) elif typ == "chat": await ws_on_chat(room, me, d) elif typ == "zhit": await ws_on_zhit(room, me, d) else: log("WARN", "ws", "unknown_type", typ, rid=me.name) except WebSocketDisconnect: pass except Exception as e: log("ERROR", "ws", "conn_error", str(e)[:200], rid=str(pid)) finally: flush_prog(pid) removed = room.remove(pid) if removed: for p in list(room.players.values()): deliver(p, {"t": "pleave", "id": pid}) await broadcast(room, {"t": "count", "n": len(room.players), "max": MAX_PER_ROOM}) log("INFO", "ws", "leave", "%s (%d/%d)" % (username, len(room.players), MAX_PER_ROOM), rid=str(pid)) event("leave", "غادر %s الغرفة" % username) # ============================ Janitor ============================ from contextlib import asynccontextmanager @asynccontextmanager async def lifespan(app): global MAIN_LOOP MAIN_LOOP = asyncio.get_running_loop() ok = await asyncio.to_thread(run_migrations) if not ok: log("CRITICAL", "db", "schema_not_ready", DB_NOT_READY_MSG) init_zombies() jan = asyncio.create_task(janitor()) tips = asyncio.create_task(server_tips()) ztask = asyncio.create_task(zombie_ai()) log("INFO", "server", "startup", "port=%d supabase=%s schema=%s" % (PORT, USE_SUPABASE, "ok" if ok else "FAILED (سأعيد المحاولة عند أول طلب)")) yield jan.cancel() tips.cancel() ztask.cancel() app.router.lifespan_context = lifespan async def janitor(): while True: await asyncio.sleep(20) t = time.time() for room in list(ROOMS.values()): for p in list(room.players.values()): bump(p.pid, "playmin", 20.0 / 60.0) if t - p.last_seen > 90: if p.transport == "poll": flush_prog(p.pid) room.remove(p.pid) for o in list(room.players.values()): deliver(o, {"t": "pleave", "id": p.pid}) await broadcast(room, {"t": "count", "n": len(room.players), "max": MAX_PER_ROOM}) log("INFO", "ws", "poll_ghost_removed", p.name) else: try: await p.ws.close(code=4001) except Exception: pass if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=PORT, log_level="info")
# Soldier Life 2D - Game Backend Server
# FastAPI + WebSocket: auth (username/password, Argon2id), rooms (max 50),
# interest management, chat throttling, admin tools, protected diagnostics logs.
import os, re, json, time, math, random, secrets, string, sqlite3, threading, asyncio, unicodedata
from collections import deque, defaultdict
from datetime import datetime, timezone
import httpx
import uvicorn
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError, VerificationError
from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect, HTTPException, BackgroundTasks, Header
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
# ============================ Configuration ============================
PORT = int(os.environ.get("PORT", "7860"))
SUPABASE_URL = os.environ.get("SUPABASE_URL", "").rstrip("/")
SUPABASE_KEY = os.environ.get("SUPABASE_SERVICE_ROLE_KEY", "")
ADMIN_USERNAME = os.environ.get("ADMIN_USERNAME", "")
ADMIN_PASSWORD = os.environ.get("ADMIN_PASSWORD", "")
SESSION_SECRET = os.environ.get("SESSION_SECRET", "") or secrets.token_hex(32)
# App ID الخاص بـ Photon — يُضبط كمتغير بيئة سري على الخادم فقط، ولا يُكتب في ملفات الواجهة.
# إن تُرك فارغًا يبقى وضع WebSocket هو الفعّال افتراضيًا ويعمل كل شيء كما قبل.
PHOTON_APPID = os.environ.get("PHOTON_APPID", "").strip()
ALLOWED_ORIGINS = [x.strip() for x in os.environ.get("ALLOWED_ORIGINS", "*").split(",") if x.strip()]
SQLITE_PATH = os.environ.get("SQLITE_PATH", "./soldierlife.db")
USE_SUPABASE = bool(SUPABASE_URL and SUPABASE_KEY)
MAX_PER_ROOM = 50
WORLD_W = 4800
WORLD_H = 4800
VIEW_RANGE = 1700.0
GRID_CELL = 512
SESSION_TTL = 12 * 3600
MAX_MSG_BYTES = 2048
MOVE_MIN_INTERVAL = 0.04
MOVE_MAX_DIST = 26.0
SHOT_MIN_INTERVAL = 0.08
WS_MSG_PER_SEC = 40
BOOT_TS = time.time()
ph = PasswordHasher()
# ============================ Logging (ring buffer) ============================
LOGS = deque(maxlen=5000)
EVENTS = deque(maxlen=800)
def now_iso():
return datetime.now(timezone.utc).isoformat(timespec="seconds")
def log(level, source, event, detail="", rid=None):
entry = {"ts": now_iso(), "level": level, "source": source, "event": event,
"detail": str(detail)[:400], "rid": rid}
LOGS.append(entry)
try:
print(json.dumps(entry, ensure_ascii=False), flush=True)
except Exception:
pass
def event(kind, text):
e = {"ts": now_iso(), "kind": kind, "text": str(text)[:220]}
EVENTS.append(e)
try:
print(json.dumps({"ts": e["ts"], "level": "INFO", "source": "events", "event": kind, "detail": e["text"]}, ensure_ascii=False), flush=True)
except Exception:
pass
# ============================ Database layer ============================
# Production: Supabase (PostgREST via service-role key, never sent to clients).
# Fallback (local dev/testing only): SQLite when Supabase env vars are absent.
DEFAULT_CHAR = {"skin": 1, "eyeType": 0, "eyeColor": 0, "hairStyle": 1, "hairColor": 0}
DEFAULT_GUNS = {"owned": [], "equipped": None}
SCHEMA_VERSION = "2"
# أسماء مستويات الإدارة
ADMIN_RANKS = {0: "player", 1: "helper", 2: "moderator", 3: "admin", 4: "senior_admin", 5: "owner"}
ADMIN_RANK = int(os.environ.get("ADMIN_RANK", "5"))
ADMIN_COLORS = {1: "#7ec8ff", 2: "#4a86ff", 3: "#ff7777", 4: "#ff4444", 5: "#ff2222"}
# صلاحيات الإدارة — Allowlist صارمة: أي إجراء غير موجود هنا = ممنوع افتراضيًا.
# Owner الوحيد هو حساب env (pid<0 أو arank>=4) — يتجاوز كل الفحوص ولا يُنشأ عبر API.
PERMS = {
"kick": 2, "ban": 2, "unban": 2, "jail": 2, "bring": 2, "unmute": 2,
"mute": 1, "tpto": 1, "staff": 1, "overview": 1,
"banned": 2, "events": 2, "users": 2,
"money": 3, "setrank": 3, "logs": 3,
"self_inv": 2, "self_nc": 2,
"setid": 4, "setarank": 4,
}
def has_perm(s, action):
if s["pid"] < 0 or s.get("arank", 0) >= 4:
return True
need = PERMS.get(action)
if need is None:
return False
return s.get("arank", 0) >= need