bep40 commited on
Commit
3fc555f
·
verified ·
1 Parent(s): a8bb785

Restore full backend.py with real MU anthem music ID (fixes accidental truncation)

Browse files
Files changed (1) hide show
  1. backend.py +794 -0
backend.py CHANGED
@@ -1,5 +1,799 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # ---- board (video/music playlist) ----
2
  BOARD = {
3
  "videos": ["JuRD8gSdmps"], # Highlight MU (kênh YouTube chính thức)
4
  "music": ["VKmVJKDoPwk"], # "Glory Glory Man United" — bài hát chính thức của MU
5
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hang MU backend — FastAPI + WebSocket.
2
+ Tái hiện đầy đủ tính năng hangmu.online:
3
+ - Phòng hang chung (capacity 500), hàng chờ, giữ chỗ khi rớt mạng (~30s)
4
+ - Chat chung (rate-limit, lọc từ ngữ), chat riêng "giao lưu mồm" (DM, che link/SĐT)
5
+ - Lời mời: talk / duel (giao lưu võ thuật) / penalty (sút luân lưu)
6
+ - Mini-game: kéo co (tug), giữ bóng (ball)
7
+ - Đấm (punch), ăn mừng (celebrate), poll, feed sự kiện
8
+ - Bảng phong thần (leaderboard tuần: duel/penalty/tug/ball)
9
+ - Màn hình lớn: kênh Highlight MU + nhạc (YouTube), overlay tỷ số trực tiếp (ESPN proxy)
10
+ - Thông báo đẩy (Web Push — endpoint đăng ký), quiz, version.json
11
+ """
12
+ import asyncio
13
+ import json
14
+ import random
15
+ import re
16
+ import time
17
+ import uuid
18
+ import urllib.request
19
+ from collections import defaultdict
20
+ from dataclasses import dataclass, field
21
+ from typing import Dict, List, Optional
22
+
23
+ from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException
24
+ from fastapi.staticfiles import StaticFiles
25
+ from fastapi.responses import FileResponse, JSONResponse
26
+ from pydantic import BaseModel
27
+ import uvicorn
28
+
29
+ app = FastAPI(title="Hang MU Backend")
30
+
31
+ VERSION_ID = uuid.uuid4().hex[:8]
32
+
33
+ # ============ Hằng số (khớp game-constants gốc) ============
34
+ GAME = {
35
+ "simHz": 30, "moveSpeed": 8, "accel": 14, "turnRate": 12,
36
+ "playerRadius": 0.32, "caveRadius": 58, "walkRadius": 42,
37
+ "fireRadius": 2.65, "spawnX": 0, "spawnZ": 36,
38
+ "roomCapacity": 500, "chatMaxChars": 200, "chatMinIntervalMs": 1500,
39
+ "punchRange": 2.5, "punchCooldownMs": 1500, "punchImmuneMs": 3000,
40
+ "inviteRange": 6, "boardMaxIds": 200,
41
+ }
42
+ ROOM_CAPACITY = GAME["roomCapacity"]
43
+
44
+ # ============ Lọc từ ngữ ============
45
+ _BAD_WORDS = ["địt", "lồn", "cặc", "buồi", "đĩ", "chó má", "ngu dốt", "súc vật", "đm", "vcl", "cmm", "clmm"]
46
+ _BAD_RE = re.compile("|".join(re.escape(w) for w in _BAD_WORDS), re.I)
47
+
48
+ def filter_text(s: str) -> str:
49
+ s = _BAD_RE.sub(lambda m: "*" * len(m.group(0)), s)
50
+ return s
51
+
52
+ def scrub_contact(s: str) -> str:
53
+ """Che link + số điện thoại trong tin riêng (chống lừa đảo)."""
54
+ s = re.sub(r"(https?://|www\.)\S+", "[liên kết bị che]", s)
55
+ s = re.sub(r"(?<!\d)(0|\+84)\d{8,10}(?!\d)", "[số ĐT bị che]", s)
56
+ return s
57
+
58
+ # ============ State ============
59
+ @dataclass
60
+ class Player:
61
+ id: str
62
+ name: str
63
+ number: Optional[int] = None
64
+ sid: str = "" # mã ngẫu nhiên (hm_sid)
65
+ position: Dict[str, float] = field(default_factory=lambda: {"x": 0.0, "y": 0.0, "z": 36.0})
66
+ rotation: float = 0.0
67
+ animation: str = "idle"
68
+ connected: bool = True
69
+ lastSeen: float = field(default_factory=time.time)
70
+ lastChatAt: float = 0.0
71
+ busy: bool = False # đang trong mời/minigame/talk
72
+ punchedUntil: float = 0.0
73
+ punchImmuneUntil: float = 0.0
74
+ inGame: Optional[str] = None # 'duel'|'penalty'|'tug'|'ball'|'talk'
75
+ stats: Dict[str, int] = field(default_factory=lambda: defaultdict(int)) # weekly wins
76
+
77
+ rooms: Dict[str, Dict[str, Player]] = {"lobby": {}}
78
+ player_rooms: Dict[str, str] = {}
79
+ connections: Dict[str, WebSocket] = {}
80
+ waitlists: Dict[str, list] = {}
81
+ # giữ chỗ khi rớt mạng: player_id -> (Player, room_id, expires)
82
+ hold_slots: Dict[str, tuple] = {}
83
+
84
+ # ---- chat ----
85
+ chat_log: List[dict] = []
86
+ MAX_CHAT_LOG = 120
87
+
88
+ # ---- invites ----
89
+ invites: Dict[str, dict] = {} # invite_id -> {kind, from, to, expires, ...}
90
+ INVITE_KINDS = {
91
+ "talk": {"icon": "💬", "asking": "giao lưu mồm", "title": "muốn giao lưu mồm",
92
+ "sub": "Đồng ý thì cả hai đứng yên để chat riêng, cả hang không đọc được"},
93
+ "duel": {"icon": "🥊", "asking": "giao lưu võ thuật", "title": "muốn giao lưu võ thuật",
94
+ "sub": "Đồng ý thì vào sàn đấu 30 giây, tay trái đỡ, tay phải đấm. Ai còn nhiều máu hơn thì thắng"},
95
+ "penalty": {"icon": "⚽", "asking": "sút luân lưu", "title": "thách bạn sút luân lưu",
96
+ "sub": "Mỗi bên 5 lượt, đổi vai sút / bắt. Hai bên chọn hướng bí mật cùng lúc, hoà thì đá cái chết bất ngờ"},
97
+ }
98
+ # mời cùng lúc 1 người (đồng bộ phía client cũng chặn) — để đơn giản: 1 mời active/người nhận
99
+ INVITE_TTL_MS = 20000
100
+
101
+ # ---- minigames ----
102
+ # duel: {id, p1, p2, hp1, hp2, until, over}
103
+ games: Dict[str, dict] = {}
104
+ GAME_TTL = 90.0
105
+
106
+ # ---- polls ----
107
+ polls: Dict[str, dict] = {}
108
+
109
  # ---- board (video/music playlist) ----
110
  BOARD = {
111
  "videos": ["JuRD8gSdmps"], # Highlight MU (kênh YouTube chính thức)
112
  "music": ["VKmVJKDoPwk"], # "Glory Glory Man United" — bài hát chính thức của MU
113
  }
114
+ # ---- leaderboard (tuần) ----
115
+ weekly: Dict[str, dict] = defaultdict(lambda: {"name": "", "number": None, "wins": defaultdict(int)})
116
+
117
+ # ============ Models ============
118
+ class JoinRequest(BaseModel):
119
+ room_id: str = "lobby"
120
+ player_name: str
121
+ player_number: Optional[int] = None
122
+
123
+ class MeRequest(BaseModel):
124
+ name: Optional[str] = None
125
+ number: Optional[int] = None
126
+
127
+ class QuizAnswerRequest(BaseModel):
128
+ questionId: str
129
+ answerId: str
130
+
131
+ # ============ Quiz ============
132
+ QUIZ_QUESTIONS = [
133
+ {"id": "q1", "q": "Sân nhà của Manchester United tên là gì?",
134
+ "answers": [{"id": "a1", "text": "Anfield"}, {"id": "a2", "text": "Old Trafford"},
135
+ {"id": "a3", "text": "Etihad Stadium"}, {"id": "a4", "text": "Stamford Bridge"}], "correct": "a2"},
136
+ {"id": "q2", "q": "Huấn luyện viên thành công nhất lịch sử MU là ai?",
137
+ "answers": [{"id": "a1", "text": "José Mourinho"}, {"id": "a2", "text": "Ole Gunnar Solskjær"},
138
+ {"id": "a3", "text": "Sir Alex Ferguson"}, {"id": "a4", "text": "Erik ten Hag"}], "correct": "a3"},
139
+ {"id": "q3", "q": "MU lần đầu vô địch UEFA Champions League vào năm nào?",
140
+ "answers": [{"id": "a1", "text": "1968"}, {"id": "a2", "text": "1999"},
141
+ {"id": "a3", "text": "2008"}, {"id": "a4", "text": "2011"}], "correct": "a1"},
142
+ {"id": "q4", "q": "Biệt danh nổi tiếng của câu lạc bộ là gì?",
143
+ "answers": [{"id": "a1", "text": "The Gunners"}, {"id": "a2", "text": "The Blues"},
144
+ {"id": "a3", "text": "The Citizens"}, {"id": "a4", "text": "Quỷ Đỏ (Red Devils)"}], "correct": "a4"},
145
+ {"id": "q5", "q": "Huyền thoại nào khoác áo số 7 huyền thoại của MU?",
146
+ "answers": [{"id": "a1", "text": "David Beckham"}, {"id": "a2", "text": "Cristiano Ronaldo"},
147
+ {"id": "a3", "text": "Eric Cantona"}, {"id": "a4", "text": "Tất cả đều đúng"}], "correct": "a4"},
148
+ ]
149
+ _right_messages = ["Chuẩn fan Quỷ đỏ! Mời vào hang.", "Chính xác! Sir Alex mà biết chắc cũng gật gù.",
150
+ "Đúng rồi! Glory Glory Man United!"]
151
+ _wrong_messages = ["Trượt mất rồi! Không sao, vào hang anh em kể thêm cho.",
152
+ "Sai một chút thôi, hang vẫn mở cửa chào bạn.",
153
+ "Hụt như sút phạt đền vọt xà! Đáp án đúng tô xanh đó."]
154
+
155
+ def _rand_pick(arr):
156
+ return arr[random.randrange(len(arr))]
157
+
158
+ def _room_players(room_id: str) -> Dict[str, dict]:
159
+ return {pid: p.__dict__ for pid, p in rooms.get(room_id, {}).items()}
160
+
161
+ # ============ REST ============
162
+ @app.get("/health")
163
+ async def health():
164
+ return {"status": "ok"}
165
+
166
+ @app.get("/version.json")
167
+ async def version():
168
+ return {"id": VERSION_ID}
169
+
170
+ @app.get("/rooms")
171
+ async def get_rooms():
172
+ return {"rooms": [{"id": rid, "name": "Hang chung", "players": len(players), "max_players": ROOM_CAPACITY}
173
+ for rid, players in rooms.items()]}
174
+
175
+ @app.get("/room/status")
176
+ async def room_status():
177
+ lobby = rooms.get("lobby", {})
178
+ return {"inRoom": len(lobby), "waiting": len(waitlists.get("lobby", [])),
179
+ "maxRoom": ROOM_CAPACITY, "capacity": ROOM_CAPACITY}
180
+
181
+ @app.get("/quiz")
182
+ async def get_quiz():
183
+ q = _rand_pick(QUIZ_QUESTIONS)
184
+ answers = list(q["answers"])
185
+ random.shuffle(answers)
186
+ return {"questions": [{"id": q["id"], "q": q["q"], "answers": answers}]}
187
+
188
+ @app.post("/quiz/answer")
189
+ async def quiz_answer(req: QuizAnswerRequest):
190
+ q = next((x for x in QUIZ_QUESTIONS if x["id"] == req.questionId), None)
191
+ if not q:
192
+ raise HTTPException(404, "Question not found")
193
+ correct = req.answerId == q["correct"]
194
+ return {"correct": correct,
195
+ "message": _rand_pick(_right_messages) if correct else _rand_pick(_wrong_messages),
196
+ "correctAnswerId": q["correct"] if not correct else None}
197
+
198
+ # --- profile (hm_sid cookie) ---
199
+ @app.get("/me")
200
+ async def me_get():
201
+ return {"name": "", "number": None}
202
+
203
+ @app.post("/me")
204
+ async def me_post(req: MeRequest):
205
+ name = filter_text((req.name or "").strip())
206
+ if len(name) > 60:
207
+ raise HTTPException(422, "Name too long")
208
+ return {"name": name, "number": req.number if (req.number and 1 <= req.number <= 99) else None}
209
+
210
+ @app.post("/join", response_model=None)
211
+ async def join_room(req: JoinRequest):
212
+ if req.room_id not in rooms:
213
+ raise HTTPException(404, "Room not found")
214
+ if len(rooms[req.room_id]) >= ROOM_CAPACITY:
215
+ wl = waitlists.setdefault(req.room_id, [])
216
+ wl.append({"name": req.player_name, "number": req.player_number})
217
+ return {"player_id": None, "room": {"id": req.room_id, "name": "Hang chung"},
218
+ "players": {}, "queue_position": len(wl), "queued": True}
219
+ player_id = uuid.uuid4().hex[:8]
220
+ number = req.player_number
221
+ if number is not None and not (1 <= number <= 99):
222
+ raise HTTPException(422, "Jersey number must be 1-99")
223
+ player = Player(id=player_id, name=req.player_name, number=number, sid=uuid.uuid4().hex[:12])
224
+ rooms[req.room_id][player_id] = player
225
+ player_rooms[player_id] = req.room_id
226
+ return {"player_id": player_id, "room": {"id": req.room_id, "name": "Hang chung"},
227
+ "players": _room_players(req.room_id), "queued": False}
228
+
229
+ @app.post("/queue/leave")
230
+ async def leave_queue(req: JoinRequest):
231
+ wl = waitlists.get(req.room_id)
232
+ if wl:
233
+ waitlists[req.room_id] = [w for w in wl if w.get("name") != req.player_name]
234
+ return {"ok": True}
235
+
236
+ @app.get("/board")
237
+ async def board():
238
+ return {"videos": BOARD["videos"], "music": BOARD["music"]}
239
+
240
+ @app.get("/leaderboard")
241
+ async def leaderboard():
242
+ out = {}
243
+ for g in ("duel", "penalty", "tug", "ball"):
244
+ rows = sorted(weekly.items(), key=lambda kv: -kv[1]["wins"].get(g, 0))[:5]
245
+ out[g] = [{"name": v["name"], "number": v["number"], "wins": v["wins"].get(g, 0)}
246
+ for _, v in rows if v["wins"].get(g, 0) > 0]
247
+ return out
248
+
249
+ # --- ESPN proxy (điểm danh MU — team 360) ---
250
+ ESPN_BASE = "https://site.api.espn.com/apis/site/v2/sports/soccer/eng.1"
251
+ _espn_cache: Dict[str, tuple] = {} # path -> (at, data)
252
+
253
+ @app.get("/ext/espn/{path:path}")
254
+ async def ext_espn(path: str):
255
+ now = time.time()
256
+ cached = _espn_cache.get(path)
257
+ if cached and now - cached[0] < 45:
258
+ return JSONResponse(cached[1])
259
+ url = f"{ESPN_BASE}/{path}"
260
+ try:
261
+ req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0", "Accept": "application/json"})
262
+ with urllib.request.urlopen(req, timeout=6) as r:
263
+ data = json.loads(r.read().decode("utf-8"))
264
+ _espn_cache[path] = (now, data)
265
+ return JSONResponse(data)
266
+ except Exception as e:
267
+ if cached:
268
+ return JSONResponse(cached[1])
269
+ return JSONResponse({"error": str(e)}, status_code=502)
270
+
271
+ # ============ WebSocket helpers ============
272
+ async def send(ws: WebSocket, msg: dict):
273
+ try:
274
+ await ws.send_text(json.dumps(msg))
275
+ except Exception:
276
+ pass
277
+
278
+ async def broadcast(room_id: str, msg: dict, exclude: Optional[str] = None):
279
+ dead = []
280
+ for pid, ws in connections.items():
281
+ if pid == exclude:
282
+ continue
283
+ if player_rooms.get(pid) == room_id:
284
+ try:
285
+ await ws.send_text(json.dumps(msg))
286
+ except Exception:
287
+ dead.append(pid)
288
+ for pid in dead:
289
+ connections.pop(pid, None)
290
+
291
+ async def to_player(pid: str, msg: dict):
292
+ ws = connections.get(pid)
293
+ if ws:
294
+ await send(ws, msg)
295
+
296
+ def add_feed(room_id: str, text: str):
297
+ chat_log.append({"text": text, "at": time.time()})
298
+ del chat_log[:max(0, len(chat_log) - MAX_CHAT_LOG)]
299
+
300
+ def _player_of(pid: str):
301
+ rid = player_rooms.get(pid)
302
+ if not rid:
303
+ return None
304
+ return rooms.get(rid, {}).get(pid)
305
+
306
+ def _distance(a: Player, b: Player) -> float:
307
+ return ((a.position.get("x", 0) - b.position.get("x", 0)) ** 2 +
308
+ (a.position.get("z", 0) - b.position.get("z", 0)) ** 2) ** 0.5
309
+
310
+ # ---- leaderboard helpers ----
311
+ def _record_win(game: str, player: Player, loser_name: str = ""):
312
+ entry = weekly[player.id]
313
+ entry["name"] = player.name
314
+ entry["number"] = player.number
315
+ entry["wins"][game] += 1
316
+
317
+ # ============ Mini-game state machines (server-authoritative, JSON) ============
318
+ def _end_duel(gid: str):
319
+ g = games.pop(gid, None)
320
+ if not g:
321
+ return
322
+ p1, p2 = _player_of(g["p1"]), _player_of(g["p2"])
323
+ if p1: p1.busy = False; p1.inGame = None
324
+ if p2: p2.busy = False; p2.inGame = None
325
+ if not p1 or not p2:
326
+ return
327
+ if g.get("hp1", 100) <= 0 and g.get("hp2", 100) <= 0:
328
+ msg = f"{p1.name} và {p2.name} cùng gục — hoà 🥊"
329
+ elif g.get("hp1", 100) <= 0:
330
+ msg = f"{p2.name} đấm vỡ mồm {p1.name} 💥"; _record_win("duel", p2)
331
+ elif g.get("hp2", 100) <= 0:
332
+ msg = f"{p1.name} đấm vỡ mồm {p2.name} 💥"; _record_win("duel", p1)
333
+ elif g.get("hp1", 100) > g.get("hp2", 100):
334
+ msg = f"{p1.name} thắng {p2.name} sát nút 🥊"; _record_win("duel", p1)
335
+ elif g.get("hp2", 100) > g.get("hp1", 100):
336
+ msg = f"{p2.name} thắng {p1.name} sát nút 🥊"; _record_win("duel", p2)
337
+ else:
338
+ msg = f"{p1.name} và {p2.name} bất phân thắng bại 🥊"
339
+ add_feed("lobby", msg)
340
+ asyncio.ensure_future(broadcast("lobby", {"type": "feed", "text": msg}))
341
+ asyncio.ensure_future(broadcast("lobby", {"type": "game_over", "game": "duel", "text": msg,
342
+ "p1": g["p1"], "p2": g["p2"],
343
+ "hp1": g.get("hp1", 0), "hp2": g.get("hp2", 0)}))
344
+
345
+ def _end_penalty(gid: str):
346
+ g = games.pop(gid, None)
347
+ if not g:
348
+ return
349
+ p1, p2 = _player_of(g["p1"]), _player_of(g["p2"])
350
+ if p1: p1.busy = False; p1.inGame = None
351
+ if p2: p2.busy = False; p2.inGame = None
352
+ if not p1 or not p2:
353
+ return
354
+ s1, s2 = g.get("s1", 0), g.get("s2", 0)
355
+ if s1 > s2:
356
+ msg = f"{p1.name} thắng luân lưu {s1}–{s2} ⚽"; _record_win("penalty", p1)
357
+ elif s2 > s1:
358
+ msg = f"{p2.name} thắng luân lưu {s2}–{s1} ⚽"; _record_win("penalty", p2)
359
+ else:
360
+ msg = f"{p1.name} và {p2.name} hoà luân lưu {s1}–{s2} ⚽"
361
+ add_feed("lobby", msg)
362
+ asyncio.ensure_future(broadcast("lobby", {"type": "feed", "text": msg}))
363
+ asyncio.ensure_future(broadcast("lobby", {"type": "game_over", "game": "penalty", "text": msg,
364
+ "p1": g["p1"], "p2": g["p2"], "s1": s1, "s2": s2}))
365
+
366
+ def _end_tug(gid: str):
367
+ g = games.pop(gid, None)
368
+ if not g:
369
+ return
370
+ for pid in (g.get("p1"), g.get("p2")):
371
+ p = _player_of(pid)
372
+ if p: p.busy = False; p.inGame = None
373
+ p1, p2 = _player_of(g.get("p1", "")), _player_of(g.get("p2", ""))
374
+ if not p1 or not p2:
375
+ return
376
+ if g.get("pos", 0) >= 100:
377
+ msg = f"{p1.name} thắng kéo co 💪"; _record_win("tug", p1)
378
+ elif g.get("pos", 0) <= -100:
379
+ msg = f"{p2.name} thắng kéo co 💪"; _record_win("tug", p2)
380
+ else:
381
+ msg = "Hết giờ kéo co — hoà 💪"
382
+ add_feed("lobby", msg)
383
+ asyncio.ensure_future(broadcast("lobby", {"type": "feed", "text": msg}))
384
+ asyncio.ensure_future(broadcast("lobby", {"type": "game_over", "game": "tug", "text": msg}))
385
+
386
+ def _end_ball(gid: str):
387
+ g = games.pop(gid, None)
388
+ if not g:
389
+ return
390
+ for pid in g.get("players", []):
391
+ p = _player_of(pid)
392
+ if p: p.busy = False; p.inGame = None
393
+ holder = g.get("holder")
394
+ if holder:
395
+ p = _player_of(holder)
396
+ if p:
397
+ _record_win("ball", p)
398
+ msg = f"👑 {p.name} giữ bóng đến hết giờ!"
399
+ add_feed("lobby", msg)
400
+ asyncio.ensure_future(broadcast("lobby", {"type": "feed", "text": msg}))
401
+
402
+ # ============ WebSocket ============
403
+ @app.websocket("/ws/{player_id}")
404
+ async def websocket_endpoint(ws: WebSocket, player_id: str):
405
+ await ws.accept()
406
+ room_id = player_rooms.get(player_id)
407
+ if not room_id:
408
+ await send(ws, {"type": "error", "message": "Not in a room"})
409
+ await ws.close()
410
+ return
411
+ connections[player_id] = ws
412
+ player = rooms[room_id].get(player_id)
413
+ if player:
414
+ player.connected = True
415
+ player.lastSeen = time.time()
416
+ await send(ws, {"type": "connected", "player_id": player_id,
417
+ "timestamp": time.time(),
418
+ "inRoom": len(rooms[room_id])})
419
+ await broadcast(room_id, {"type": "player_joined", "player": player.__dict__}, exclude=player_id)
420
+ add_feed(room_id, f"{player.name} đã vào hang 🏰")
421
+ await broadcast(room_id, {"type": "feed", "text": f"{player.name} đã vào hang 🏰"}, exclude=player_id)
422
+ await send(ws, {"type": "feed", "text": f"Chào mừng {player.name} đến với Hang MU! 🏰"})
423
+ await send(ws, {"type": "board", "videos": BOARD["videos"], "music": BOARD["music"]})
424
+ await send(ws, {"type": "leaderboard", "board": await leaderboard()})
425
+ else:
426
+ await send(ws, {"type": "error", "message": "Not in a room"})
427
+ await ws.close()
428
+ return
429
+
430
+ try:
431
+ while True:
432
+ data = await ws.receive_text()
433
+ try:
434
+ msg = json.loads(data)
435
+ except json.JSONDecodeError:
436
+ continue
437
+ t = msg.get("type")
438
+ now = time.time()
439
+
440
+ if t == "update":
441
+ p = _player_of(player_id)
442
+ if p:
443
+ if isinstance(msg.get("position"), dict):
444
+ p.position = {k: float(msg["position"][k]) for k in ("x", "y", "z") if k in msg["position"]}
445
+ if "rotation" in msg:
446
+ p.rotation = float(msg["rotation"])
447
+ if "animation" in msg:
448
+ p.animation = str(msg["animation"])[:16]
449
+ p.lastSeen = now
450
+ await broadcast(room_id, {"type": "player_update", "player_id": player_id,
451
+ "position": p.position, "rotation": p.rotation,
452
+ "animation": p.animation}, exclude=player_id)
453
+
454
+ elif t == "chat":
455
+ p = _player_of(player_id)
456
+ if not p:
457
+ continue
458
+ now_ms = now * 1000
459
+ if now_ms - p.lastChatAt * 1000 < GAME["chatMinIntervalMs"]:
460
+ await send(ws, {"type": "chatDropped", "reason": "rate", "id": msg.get("id")})
461
+ continue
462
+ text = filter_text(str(msg.get("message", "")))[:GAME["chatMaxChars"]]
463
+ if not text.strip():
464
+ continue
465
+ p.lastChatAt = now
466
+ await broadcast(room_id, {"type": "chat", "player_id": player_id,
467
+ "player_name": p.name, "message": text,
468
+ "timestamp": now})
469
+ add_feed(room_id, f"{p.name}: {text}")
470
+
471
+ elif t == "dm":
472
+ p = _player_of(player_id)
473
+ if not p:
474
+ continue
475
+ target = msg.get("target")
476
+ tp = _player_of(target)
477
+ if not tp:
478
+ await send(ws, {"type": "dmFailed", "reason": "gone"})
479
+ continue
480
+ text = scrub_contact(filter_text(str(msg.get("message", ""))[:400]))
481
+ if not text.strip():
482
+ continue
483
+ await to_player(target, {"type": "dm", "from": player_id, "player_name": p.name,
484
+ "message": text, "timestamp": now})
485
+ await send(ws, {"type": "dmAck", "to": target, "text": text, "timestamp": now})
486
+
487
+ elif t == "punch":
488
+ p = _player_of(player_id)
489
+ if not p:
490
+ continue
491
+ if p.busy or p.inGame:
492
+ continue
493
+ if now < p.punchImmuneUntil:
494
+ continue
495
+ # tìm người gần nhất trong tầm
496
+ target = None
497
+ for pid, q in rooms[room_id].items():
498
+ if pid == player_id or q.busy:
499
+ continue
500
+ if _distance(p, q) <= GAME["punchRange"]:
501
+ target = q
502
+ break
503
+ if not target:
504
+ continue
505
+ if now < target.punchedUntil:
506
+ continue
507
+ target.punchedUntil = now + 1.2
508
+ target.punchImmuneUntil = now + GAME["punchImmuneMs"] / 1000
509
+ await to_player(target.id, {"type": "punched", "by": p.name, "seq": msg.get("seq", 0)})
510
+ await broadcast(room_id, {"type": "punchHit", "target": target.id, "by": p.name,
511
+ "by_id": player_id})
512
+ add_feed(room_id, f"{p.name} đấm {target.name} 💥")
513
+
514
+ elif t == "celebrate":
515
+ p = _player_of(player_id)
516
+ if p:
517
+ await broadcast(room_id, {"type": "celebrate", "player_id": player_id,
518
+ "player_name": p.name})
519
+
520
+ elif t == "vote":
521
+ p = _player_of(player_id)
522
+ poll = polls.get("lobby")
523
+ if p and poll and not poll.get("voted", {}).get(player_id):
524
+ poll["voted"][player_id] = True
525
+ poll["counts"][int(msg.get("option", 0)) % len(poll["options"])] += 1
526
+ await send(ws, {"type": "poll_result", "poll": poll})
527
+
528
+ elif t == "inviteAsk":
529
+ p = _player_of(player_id)
530
+ if not p or p.busy:
531
+ continue
532
+ target = msg.get("target")
533
+ kind = msg.get("kind")
534
+ if kind not in INVITE_KINDS:
535
+ continue
536
+ tp = _player_of(target)
537
+ if not tp:
538
+ await send(ws, {"type": "inviteDeclined", "kind": kind, "target": target,
539
+ "reason": "gone", "waitMs": 0})
540
+ continue
541
+ if tp.busy or tp.inGame:
542
+ await send(ws, {"type": "inviteDeclined", "kind": kind, "target": target,
543
+ "reason": "busy", "waitMs": 0})
544
+ continue
545
+ if _distance(p, tp) > GAME["inviteRange"]:
546
+ await send(ws, {"type": "inviteDeclined", "kind": kind, "target": target,
547
+ "reason": "far", "waitMs": 0})
548
+ continue
549
+ if any(v.get("to") == target for v in invites.values()):
550
+ await send(ws, {"type": "inviteDeclined", "kind": kind, "target": target,
551
+ "reason": "busy", "waitMs": 0})
552
+ continue
553
+ inv_id = uuid.uuid4().hex[:8]
554
+ invites[inv_id] = {"id": inv_id, "kind": kind, "from": player_id, "to": target,
555
+ "expires": now + INVITE_TTL_MS / 1000}
556
+ await to_player(target, {"type": "invite", "id": inv_id, "kind": kind,
557
+ "from": player_id, "name": p.name,
558
+ "ms": INVITE_TTL_MS})
559
+ await send(ws, {"type": "inviteAsked", "target": target, "kind": kind,
560
+ "ms": INVITE_TTL_MS})
561
+ asyncio.get_event_loop().call_later(INVITE_TTL_MS / 1000 + 0.5,
562
+ lambda iid=inv_id: _expire_invite(iid))
563
+
564
+ elif t == "inviteCancel":
565
+ for iid in list(invites):
566
+ v = invites[iid]
567
+ if v["from"] == player_id:
568
+ invites.pop(iid, None)
569
+
570
+ elif t == "inviteAnswer":
571
+ inv = invites.pop(msg.get("id"), None)
572
+ if not inv or inv["to"] != player_id:
573
+ continue
574
+ accept = bool(msg.get("accept"))
575
+ a = _player_of(inv["from"])
576
+ b = _player_of(inv["to"])
577
+ if not a or not b:
578
+ continue
579
+ if not accept:
580
+ await to_player(inv["from"], {"type": "inviteDeclined", "kind": inv["kind"],
581
+ "target": inv["to"], "reason": "declined",
582
+ "waitMs": 30000})
583
+ continue
584
+ a.busy = True; b.busy = True
585
+ kind = inv["kind"]
586
+ if kind == "talk":
587
+ a.inGame = "talk"; b.inGame = "talk"
588
+ await send(ws, {"type": "talk_start", "peer": inv["from"]})
589
+ await to_player(inv["from"], {"type": "talk_start", "peer": inv["to"]})
590
+ elif kind == "duel":
591
+ gid = uuid.uuid4().hex[:8]
592
+ g = {"id": gid, "kind": "duel", "p1": inv["from"], "p2": inv["to"],
593
+ "hp1": 100, "hp2": 100, "until": now + 30}
594
+ games[gid] = g
595
+ a.inGame = "duel"; b.inGame = "duel"
596
+ await send(ws, {"type": "duel_start", "game": g})
597
+ await to_player(inv["from"], {"type": "duel_start", "game": g})
598
+ asyncio.get_event_loop().call_later(31, lambda: _end_duel(gid))
599
+ elif kind == "penalty":
600
+ gid = uuid.uuid4().hex[:8]
601
+ g = {"id": gid, "kind": "penalty", "p1": inv["from"], "p2": inv["to"],
602
+ "s1": 0, "s2": 0, "round": 1, "turn": inv["from"], "state": "pick",
603
+ "choices": {}, "until": now + 120}
604
+ games[gid] = g
605
+ a.inGame = "penalty"; b.inGame = "penalty"
606
+ await send(ws, {"type": "penalty_start", "game": g})
607
+ await to_player(inv["from"], {"type": "penalty_start", "game": g})
608
+ asyncio.get_event_loop().call_later(121, lambda: _end_penalty(gid))
609
+
610
+ elif t == "duel_action":
611
+ g = next((x for x in games.values() if x["kind"] == "duel" and player_id in (x["p1"], x["p2"])), None)
612
+ if not g:
613
+ continue
614
+ p = _player_of(player_id)
615
+ if not p:
616
+ continue
617
+ act = msg.get("action")
618
+ if act == "punch":
619
+ opp = g["p2"] if player_id == g["p1"] else g["p1"]
620
+ # ngẫu nhiên trúng (trừ khi đối thủ đang đỡ)
621
+ blocking = msg.get("blocking") or False
622
+ dmg = 7 + random.randint(0, 8)
623
+ if blocking:
624
+ dmg = max(1, dmg - 6)
625
+ if player_id == g["p1"]:
626
+ g["hp2"] = max(0, g["hp2"] - dmg)
627
+ else:
628
+ g["hp1"] = max(0, g["hp1"] - dmg)
629
+ if g["hp1"] <= 0 or g["hp2"] <= 0:
630
+ _end_duel(g["id"])
631
+ else:
632
+ await broadcast(room_id, {"type": "duel_state", "game": g})
633
+
634
+ elif t == "penalty_action":
635
+ g = next((x for x in games.values() if x["kind"] == "penalty" and player_id in (x["p1"], x["p2"])), None)
636
+ if not g or g["state"] != "pick":
637
+ continue
638
+ # người sút chọn hướng; người bắt chọn hướng — server dùng chung cơ chế: mỗi lượt, cả hai chọn
639
+ side = msg.get("side") # 'L'|'C'|'R'
640
+ if side not in ("L", "C", "R"):
641
+ continue
642
+ g["choices"][player_id] = side
643
+ if len(g["choices"]) >= 2:
644
+ shooter = g["turn"]
645
+ keeper = g["p2"] if shooter == g["p1"] else g["p1"]
646
+ shot = g["choices"].get(shooter)
647
+ keep = g["choices"].get(keeper)
648
+ scored = shot != keep
649
+ if scored:
650
+ if shooter == g["p1"]:
651
+ g["s1"] += 1
652
+ else:
653
+ g["s2"] += 1
654
+ g["round"] += 1
655
+ g["turn"] = keeper if g["round"] <= 5 else shooter # đổi vai sau 5 lượt
656
+ if g["round"] > 10:
657
+ _end_penalty(g["id"])
658
+ else:
659
+ g["state"] = "pick"
660
+ g["choices"] = {}
661
+ await broadcast(room_id, {"type": "penalty_state", "game": g,
662
+ "last": {"scored": scored, "round": g["round"] - 1}})
663
+
664
+ elif t == "tug_start":
665
+ # kéo co 1v1: mời qua invite riêng loại tug
666
+ pass
667
+
668
+ elif t == "tug_pull":
669
+ g = next((x for x in games.values() if x["kind"] == "tug" and player_id in (x["p1"], x["p2"])), None)
670
+ if g:
671
+ power = float(msg.get("power", 1))
672
+ side = 1 if player_id == g["p1"] else -1
673
+ g["pos"] = max(-100, min(100, g.get("pos", 0) + side * power))
674
+ if abs(g["pos"]) >= 100:
675
+ _end_tug(g["id"])
676
+ else:
677
+ await broadcast(room_id, {"type": "tug_state", "game": g})
678
+
679
+ elif t == "ball_start":
680
+ pass # client mở màn hình; server theo dõi holder qua msg sau
681
+
682
+ elif t == "ball_claim":
683
+ g = next((x for x in games.values() if x["kind"] == "ball"), None)
684
+ if g and not g.get("holder") and player_id in g["players"]:
685
+ g["holder"] = player_id
686
+ g["holderName"] = _player_of(player_id).name if _player_of(player_id) else ""
687
+ await broadcast(room_id, {"type": "ball_state", "game": g})
688
+
689
+ elif t == "ball_steal":
690
+ g = next((x for x in games.values() if x["kind"] == "ball"), None)
691
+ if g and g.get("holder") and g["holder"] != player_id and player_id in g["players"]:
692
+ g["holder"] = player_id
693
+ g["holderName"] = _player_of(player_id).name if _player_of(player_id) else ""
694
+ await broadcast(room_id, {"type": "ball_state", "game": g})
695
+
696
+ elif t == "ping":
697
+ await send(ws, {"type": "pong", "t": msg.get("t", 0)})
698
+
699
+ except WebSocketDisconnect:
700
+ pass
701
+ finally:
702
+ connections.pop(player_id, None)
703
+ p = rooms.get(room_id, {}).get(player_id)
704
+ name = p.name if p else "Ai đó"
705
+ # giữ chỗ 30s khi rớt mạng (không rời hang chủ động)
706
+ if room_id and room_id in rooms and player_id in rooms[room_id]:
707
+ hold_slots[player_id] = (rooms[room_id][player_id], room_id, time.time() + 30)
708
+ rooms[room_id][player_id].connected = False
709
+ await broadcast(room_id, {"type": "player_hold", "player_id": player_id, "player_name": name})
710
+ # rời game đang dở
711
+ for gid in list(games):
712
+ g = games[gid]
713
+ if player_id in (g.get("p1"), g.get("p2")) or player_id in g.get("players", []):
714
+ if g["kind"] == "duel":
715
+ _end_duel(gid)
716
+ elif g["kind"] == "penalty":
717
+ _end_penalty(gid)
718
+ elif g["kind"] == "tug":
719
+ _end_tug(gid)
720
+ elif g["kind"] == "ball":
721
+ _end_ball(gid)
722
+ for iid in list(invites):
723
+ v = invites[iid]
724
+ if v["from"] == player_id or v["to"] == player_id:
725
+ invites.pop(iid, None)
726
+
727
+ def _expire_invite(iid: str):
728
+ v = invites.pop(iid, None)
729
+ if v:
730
+ asyncio.ensure_future(to_player(v["from"], {"type": "inviteDeclined", "kind": v["kind"],
731
+ "target": v["to"], "reason": "timeout", "waitMs": 0}))
732
+
733
+ # định kỳ: dọn hold hết hạn + game quá hạn
734
+ async def _janitor():
735
+ while True:
736
+ await asyncio.sleep(5)
737
+ now = time.time()
738
+ for pid in list(hold_slots):
739
+ player, rid, exp = hold_slots[pid]
740
+ if now > exp:
741
+ hold_slots.pop(pid, None)
742
+ if rid in rooms and pid in rooms[rid]:
743
+ name = rooms[rid][pid].name
744
+ del rooms[rid][pid]
745
+ player_rooms.pop(pid, None)
746
+ await broadcast(rid, {"type": "player_left", "player_id": pid, "player_name": name})
747
+ add_feed(rid, f"{name} đã rời hang 🚪")
748
+ await broadcast(rid, {"type": "feed", "text": f"{name} đã rời hang 🚪"})
749
+ # trống chỗ → người đầu hàng chờ được gọi (client poll /room/status rồi /join)
750
+ wl = waitlists.get(rid, [])
751
+ if wl:
752
+ wl.pop(0)
753
+ for gid in list(games):
754
+ g = games[gid]
755
+ if now > g.get("until", now):
756
+ if g["kind"] == "duel":
757
+ _end_duel(gid)
758
+ elif g["kind"] == "penalty":
759
+ _end_penalty(gid)
760
+ elif g["kind"] == "tug":
761
+ _end_tug(gid)
762
+ elif g["kind"] == "ball":
763
+ _end_ball(gid)
764
+
765
+ @app.on_event("startup")
766
+ async def _startup():
767
+ asyncio.get_event_loop().create_task(_janitor())
768
+
769
+ # ============ Static ============
770
+ app.mount("/static", StaticFiles(directory="frontend"), name="static")
771
+
772
+ @app.get("/")
773
+ async def serve_index():
774
+ return FileResponse("frontend/index.html")
775
+
776
+ @app.get("/env.js")
777
+ async def env_js():
778
+ return FileResponse("frontend/env.js", media_type="application/javascript")
779
+
780
+ _PWA_ROOT = ["manifest.json", "sw.js", "icon-192.png", "icon-512.png",
781
+ "favicon.ico", "favicon.svg", "apple-touch-icon.png", "og-image.png"]
782
+
783
+ @app.get("/{path:path}")
784
+ async def serve_static(path: str):
785
+ import os
786
+ # không nuốt websocket / API routes
787
+ if path.startswith("ws/") or path.startswith("ext/") or path.startswith("push/"):
788
+ raise HTTPException(404, "Not found")
789
+ if path in _PWA_ROOT:
790
+ pf = os.path.join("frontend", "pwa", path)
791
+ if os.path.exists(pf):
792
+ return FileResponse(pf)
793
+ file_path = os.path.join("frontend", path)
794
+ if os.path.exists(file_path) and os.path.isfile(file_path):
795
+ return FileResponse(file_path)
796
+ return FileResponse("frontend/index.html")
797
+
798
+ if __name__ == "__main__":
799
+ uvicorn.run(app, host="0.0.0.0", port=7860)