"""Hang MU backend — FastAPI + WebSocket. Tái hiện đầy đủ tính năng hangmu.online: - Phòng hang chung (capacity 500), hàng chờ, giữ chỗ khi rớt mạng (~30s) - Chat chung (rate-limit, lọc từ ngữ), chat riêng "giao lưu mồm" (DM, che link/SĐT) - Lời mời: talk / duel (giao lưu võ thuật) / penalty (sút luân lưu) / tug (kéo co) / ball (giữ bóng) - Mini-game: kéo co (tug), giữ bóng (ball) - Đấm (punch), ăn mừng (celebrate), poll, feed sự kiện - Bảng phong thần (leaderboard tuần: duel/penalty/tug/ball) - Màn hình lớn: kênh Highlight MU + nhạc (YouTube), overlay tỷ số trực tiếp (ESPN proxy) - Thông báo đẩy (Web Push — endpoint đăng ký), quiz, version.json - API bổ sung (đã materialize khỏi patch): /api/log /api/logs /api/attendance /api/legends /api/onthisday — chuyên cần bia đá, tường huyền thoại, ngày này năm xưa. """ import asyncio import json import math import os import random import re import time import uuid import urllib.request from collections import defaultdict from dataclasses import dataclass, field from typing import Dict, List, Optional from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException from fastapi.staticfiles import StaticFiles from fastapi.responses import FileResponse, JSONResponse, HTMLResponse import video_proxy # V43: /api/video-proxy — màn hình lớn tự render YouTube embed (không phụ thuộc VNEWS), HTMLResponse import video_proxy # V43: /api/video-proxy — màn hình lớn tự render YouTube embed (không phụ thuộc VNEWS) from pydantic import BaseModel import uvicorn app = FastAPI(title="Hang MU Backend") # VERSION ổn định — khớp cache-bust ?v=10 của bundle. Không đổi ngẫu nhiên # theo uuid (trước đây uuid4().hex[:8] đổi mỗi lần restart → client tưởng # "Có bản mới" và tự reload liên tục). Chỉ đổi khi ta chủ động deploy bản mới. VERSION_ID = "v117" # ============ Client error log (từ ErrorBoundary / window.onerror) ============ _client_logs = [] @app.post("/api/log") async def api_log(req: dict): entry = {"at": time.time()} if isinstance(req, dict): entry.update(req) _client_logs.append(entry) del _client_logs[:-400] return {"ok": True} @app.get("/api/logs") async def api_logs(): return {"logs": _client_logs[-200:]} # ============ Attendance (chuyên cần bia đá) ============ def _att_pick_thumb(item): for tag in ("media:thumbnail", "media:content", "enclosure"): m = re.search(rf"<{tag}[^>]*url=[\"']([^\"']+)[\"']", item) if m: return m.group(1) return "" @app.get("/api/attendance") async def api_attendance(): plist = list(rooms.get("lobby", {}).values()) names = [p.name for p in plist] rows = [] idx = 0 for r in range(5): row = [] for c in range(10): if idx < len(names): row.append({"name": names[idx], "number": getattr(plist[idx], "number", None)}) idx += 1 else: row.append(None) rows.append(row) return {"rows": rows, "today": len(plist)} # ============ Legends + On-this-day (tường huyền thoại + ngày này năm xưa) ============ _LEGENDS = [ {"key": "rooney", "name": "Wayne Rooney", "years": "2004–2017", "img": "/images/legends/rooney.jpg"}, {"key": "ronaldo", "name": "Cristiano Ronaldo", "years": "2003–2009, 2021–2022", "img": "/images/legends/ronaldo.jpg"}, {"key": "giggs", "name": "Ryan Giggs", "years": "1991–2014", "img": "/images/legends/giggs.jpg"}, {"key": "scholes", "name": "Paul Scholes", "years": "1994–2013", "img": "/images/legends/scholes.jpg"}, {"key": "neville", "name": "Gary Neville", "years": "1992–2011", "img": "/images/legends/neville.jpg"}, {"key": "ferdinand", "name": "Rio Ferdinand", "years": "2002–2014", "img": "/images/legends/ferdinand.jpg"}, {"key": "vidic", "name": "Nemanja Vidić", "years": "2006–2014", "img": "/images/legends/vidic.jpg"}, {"key": "vandersar", "name": "Edwin van der Sar", "years": "2005–2011", "img": "/images/legends/vandersar.jpg"}, {"key": "carrick", "name": "Michael Carrick", "years": "2006–2018", "img": "/images/legends/carrick.jpg"}, {"key": "evra", "name": "Patrice Evra", "years": "2006–2014", "img": "/images/legends/evra.jpg"}, ] _ON_THIS_DAY = [ (1, 21, 2017, "Rooney thành vua phá lưới CLB", "Cú sút phạt ở phút bù giờ trước Stoke là bàn thứ 250 — vượt kỷ lục của Sir Bobby Charlton."), (2, 5, 1985, "Cristiano Ronaldo chào đời", "Sinh ở Madeira. 2008: Quả bóng Vàng đầu tiên trong màu áo Quỷ Đỏ."), (2, 6, 1958, "Thảm hoạ Munich", "Chuyến bay chở đội bóng gặp nạn trên đường về từ Belgrade — 8 cầu thủ Busby Babes ra đi. Mãi không quên."), (2, 19, 1910, "Trận đầu tiên ở Old Trafford", "Sân mới khai trương với trận gặp Liverpool. Nhà hát của những giấc mơ bắt đầu từ đây."), (2, 19, 1958, "Trận đầu sau Munich", "13 ngày sau thảm hoạ, MU thắng Sheffield Wednesday 3–0 ở FA Cup trong nước mắt cả Old Trafford."), (2, 21, 1958, "Duncan Edwards ra đi", "Viên ngọc của Busby Babes qua đời sau 15 ngày chiến đấu với vết thương từ Munich, mới 21 tuổi."), (2, 24, 1940, "Denis Law chào đời", "The King của Stretford End, Quả bóng Vàng 1964."), (2, 26, 1973, "Ole Gunnar Solskjær chào đời", "Người ghi bàn thắng định mệnh ở Camp Nou 1999."), (3, 2, 1991, "Ryan Giggs ra mắt", "Trận đầu tiên của cầu thủ sau này khoác áo MU nhiều trận nhất lịch sử."), (3, 4, 1995, "Thắng Ipswich 9–0", "Chiến thắng đậm nhất lịch sử Premier League lúc đó — Andy Cole ghi 5 bàn."), (4, 14, 1999, "Siêu phẩm của Giggs", "Bán kết lại FA Cup với Arsenal: Giggs solo qua cả hàng thủ ở hiệp phụ, cởi áo ăn mừng."), (4, 21, 1999, "Ngược dòng ở Turin", "Bị Juventus dẫn 2–0, Keane khơi mào, MU thắng 3–2 vào chung kết Champions League."), (4, 22, 2013, "Chức vô địch thứ 20", "Van Persie lập hat-trick vào lưới Aston Villa, MU vô địch Ngoại hạng Anh lần thứ 20."), (5, 8, 2013, "Sir Alex chia tay", "Sau hơn 26 năm và 38 danh hiệu, Sir Alex Ferguson thông báo nghỉ hưu."), (5, 11, 1996, "FA Cup 1996 — cú đúp thứ hai", "Cantona ghi bàn duy nhất vào lưới Liverpool, MU giành cú đúp quốc nội lần thứ hai."), (5, 14, 1999, "Cúp C2 châu Âu", "Thắng Barcelona 2–1 ở Rotterdam, Mark Hughes lập cú đúp."), (5, 16, 1999, "Mảnh ghép thứ nhất của cú ăn ba", "Thắng Tottenham 2–1 ngày cuối mùa, giành chức vô địch Premier League."), (5, 17, 1990, "Danh hiệu đầu tiên của Sir Alex", "Đá lại chung kết FA Cup, Lee Martin ghi bàn duy nhất vào lưới Crystal Palace."), (5, 21, 2008, "Vô địch châu Âu ở Moscow", "Hoà Chelsea 1–1 dưới mưa, Van der Sar cản phạt Anelka — MU lần thứ ba vô địch châu Âu."), (5, 22, 1999, "Mảnh ghép thứ hai của cú ăn ba", "Thắng Newcastle 2–0 ở chung kết FA Cup — Sheringham và Scholes ghi bàn."), (5, 24, 2017, "Vô địch Europa League", "Thắng Ajax 2–0 ở Stockholm — danh hiệu châu Âu duy nhất còn thiếu trong tủ."), (5, 25, 2024, "FA Cup 2024", "Thắng Man City 2–1 ở chung kết — Garnacho và Mainoo ghi bàn."), (5, 26, 1999, "Cú ăn ba — Camp Nou", "Bị Bayern dẫn tới phút 90, Sheringham rồi Solskjær ghi bàn bù giờ — MU vô địch châu Âu, đúng sinh nhật Sir Matt."), (5, 29, 1968, "Lần đầu vô địch châu Âu", "Thắng Benfica 4–1 sau hiệp phụ ở Wembley — 10 năm sau Munich. Charlton lập cú đúp."), (8, 17, 1996, "Beckham ghi bàn từ giữa sân", "Cú sút từ vạch giữa sân vào lưới Wimbledon khiến cả nước Anh biết tên số 10 trẻ tuổi."), (8, 28, 2011, "Thắng Arsenal 8–2", "Rooney lập hat-trick ở Old Trafford trong một chiều không thể quên."), (9, 11, 2021, "Ronaldo trở về", "Lần thứ hai ra mắt ở Old Trafford, lập cú đúp vào lưới Newcastle."), (10, 24, 1985, "Wayne Rooney chào đời", "Chân sút vĩ đại nhất lịch sử CLB với 253 bàn thắng."), (11, 6, 1986, "Sir Alex Ferguson nhậm chức", "Ngày một người Scotland tới Old Trafford — mở ra 26 năm và 38 danh hiệu."), (12, 2, 2008, "Ronaldo đoạt Quả bóng Vàng", "Cầu thủ MU đầu tiên giành Quả bóng Vàng sau George Best 1968."), (12, 31, 1941, "Sir Alex Ferguson chào đời", "HLV vĩ đại nhất lịch sử bóng đá Anh, sinh ở Govan, Glasgow."), ] # ============ BẢNG TIN AI (Nguồn: bep40/VNEWS) — cache 8 giờ ============ # V67: "Bảng tin AI hôm nay" — 10 tin mới nhất theo từ khoá AI / trí tuệ nhân tạo. # Lấy từ Space bep40/VNEWS (endpoint công khai /api/hashtag/sources); server giữ # cache 8 giờ để không gọi VNEWS liên tục (VNEWS cũng tự cache). AI_NEWS_URL = "https://bep40-vnews.hf.space/api/hashtag/sources" AI_NEWS_TOPIC = "AI trí tuệ nhân tạo" AI_NEWS_TTL = 8 * 3600 # 8 giờ _ai_news_cache = {"at": 0.0, "items": []} def _ai_news_fetch(): """Gọi Google News RSS lấy 10 tin AI mới nhất. Trả list {title, url, via, pubDate, thumbnail}.""" import xml.etree.ElementTree as ET from urllib.parse import quote as _q url = ("https://news.google.com/rss/search?q=" + _q(AI_NEWS_TOPIC) + "&hl=vi&gl=VN&ceid=VN:vi") req = urllib.request.Request(url, headers={ "User-Agent": "Mozilla/5.0 (HangMU/1.0)", "Accept": "application/rss+xml, application/xml, text/xml, */*", "Accept-Encoding": "identity", }) with urllib.request.urlopen(req, timeout=15) as resp: xml_data = resp.read() # Dac biet: Google News co the tra ve gzip - thu giai nen neu can if xml_data[:2] == b'\x1f\x8b': import gzip xml_data = gzip.decompress(xml_data) # Parse XML try: root = ET.fromstring(xml_data) except ET.ParseError: text = xml_data.decode("utf-8", "ignore") root = ET.fromstring(text) out = [] for item in root.iter("item"): title_el = item.find("title") link_el = item.find("link") source_el = item.find("source") pubdate_el = item.find("pubDate") desc_el = item.find("description") # Try to extract thumbnail from media:content or media:thumbnail thumb = "" for media in item.iter(): tag = media.tag.split("}")[-1] if "}" in media.tag else media.tag if tag in ("thumbnail", "content") and media.get("url"): thumb = media.get("url") break title = (title_el.text or "").strip() if title_el is not None else "" link = (link_el.text or "").strip() if link_el is not None else "" via = (source_el.text or "").strip() if source_el is not None else "" pubdate = (pubdate_el.text or "").strip() if pubdate_el is not None else "" desc = (desc_el.text or "").strip() if desc_el is not None else "" # Strip HTML tags from description if desc: import re as _re desc = _re.sub(r'<[^>]+>', '', desc).strip()[:300] if not title: continue out.append({"title": title[:200], "url": link, "via": via, "pubDate": pubdate, "thumbnail": thumb, "description": desc}) if len(out) >= 10: break return out # ============ V92: ẢNH THẬT CHO TIN AI ============ # Google News RSS không kèm ảnh. BBC Vietnamese RSS có media:thumbnail thật # → dùng làm nguồn ảnh. Nếu thiếu ảnh, sinh ảnh đại diện tại /api/ai-thumb. _AI_IMG_URL = "https://feeds.bbci.co.uk/vietnamese/rss.xml" _ai_img_cache = {"at": 0.0, "items": []} def _ai_img_fetch(): """Lấy danh sách URL ảnh từ BBC Vietnamese RSS (media:thumbnail).""" import re as _re try: r = urllib.request.Request(_AI_IMG_URL, headers={ "User-Agent": "Mozilla/5.0 (HangMU/1.0)", "Accept": "application/rss+xml, application/xml, text/xml", }) with urllib.request.urlopen(r, timeout=12) as resp: xml = resp.read().decode("utf-8", "ignore") except Exception: return [] urls = _re.findall(r']*url=["\']([^"\']+)["\']', xml) if not urls: urls = _re.findall(r']*url=["\']([^"\']+)["\']', xml) return [u for u in urls if u.startswith("http")] def _ai_thumb_for(idx: int) -> str: """Ảnh cho tin thứ idx: ảnh BBC cùng chỉ mục, hoặc ảnh đại diện.""" imgs = _ai_img_cache.get("items") or [] if idx < len(imgs): return imgs[idx] return "/api/ai-thumb?i=%d" % (idx % 12) @app.get("/api/ai-thumb") async def api_ai_thumb(i: int = 0): """Sinh ảnh đại diện (SVG) cho tin thứ i — luôn có ảnh, deterministic.""" import html as _html palette = [ ("#0d1b2a", "#4fa3ff"), ("#1a0d24", "#b06bff"), ("#0a2418", "#3ddc97"), ("#2a1206", "#ff9a4f"), ("#24060f", "#ff4f6d"), ("#06181f", "#4fd8e8"), ] bg, fg = palette[i % len(palette)] label = "AI" svg = ( f'' f'' f'' f'' f'' f'' f'' f'{_html.escape(label)}' f'' ) from fastapi.responses import Response as _Resp return _Resp(content=svg, media_type="image/svg+xml", headers={"Cache-Control": "public, max-age=86400"}) # ============ Tin AI (V95: bep40/VAINEWS, đầy đủ tiêu đề + mô tả + ảnh) ============ import os as _os95 import re as _re95 import json as _json95 import time as _time95 import threading as _threading95 import requests as _rq95 from bs4 import BeautifulSoup as _BS95 _v95_ai_news = {"items": [], "at": 0.0} _v95_lock = _threading95.Lock() _v95_TTL = 30 * 60 # 30 phút _v95_KEY = "AI trí tuệ nhân tạo" _v95_VAINEWS = "https://bep40-vainews.hf.space" _v95_UA = { "User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) " "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120 Safari/537.36"), "Accept-Language": "vi,en;q=0.8", } # từ khoá nhận diện tin AI _v95_AIWORDS = ("ai", "trí tuệ nhân tạo", "tri tue nhan tao", "machine learning", "học máy", "chatbot", "chatgpt", "openai", "gemini", "llm", "mô hình", "thuật toán", "robot", "tự động hoá", "deepfake", "generative", "anthropic", "claude", "midjourney", "stable diffusion", "copilot", "nvidia", "gpu", "dữ liệu lớn", "tự hành") def _v95_is_ai(text: str) -> bool: t = (text or "").lower() for w in _v95_AIWORDS: if w in ("ai",): # 'ai' phải đứng riêng, tránh khớp bừa trong 'hai','mai','phải' if _re95.search(r"(? dict: """Lấy mô tả + ảnh + vài đoạn nội dung từ trang gốc.""" out = {"description": "", "image": "", "body": "", "site": ""} try: r = _rq95.get(url, headers=_v95_UA, timeout=15, allow_redirects=True) if r.status_code != 200: return out r.encoding = r.apparent_encoding or "utf-8" soup = _BS95(r.text, "lxml") def meta(*props): for p in props: el = soup.find("meta", property=p) or soup.find("meta", attrs={"name": p}) if el and el.get("content"): return el.get("content").strip() return "" out["description"] = meta("og:description", "description", "twitter:description") out["image"] = meta("og:image", "twitter:image") out["site"] = meta("og:site_name") # các đoạn nội dung đầu paras = [] for sel in (".knc-content p", ".content p", "article p", ".article-body p", ".detail-content p", "#mainContent p", ".body-text p", "div.content-detail p"): for p in soup.select(sel): txt = p.get_text(" ", strip=True) if len(txt) > 70 and txt not in paras: paras.append(txt) if len(paras) >= 4: break if not paras: for p in soup.find_all("p"): txt = p.get_text(" ", strip=True) if len(txt) > 90: paras.append(txt) if len(paras) >= 4: break out["body"] = "\n\n".join(paras[:4]) if not out["description"] and paras: out["description"] = paras[0][:300] except Exception as e: print("[v95] deep fail", url[:60], e) return out def _v95_from_vainews(limit: int = 10): """Tin AI từ Space bep40/VAINEWS (private -> cần token).""" hdr = dict(_v95_UA) tok = _os95.environ.get("HF_TOKEN") or "" if tok: hdr["Authorization"] = "Bearer " + tok raw = [] for attempt in (1, 2, 3): try: r = _rq95.get(_v95_VAINEWS + "/api/category/cong-nghe", headers=hdr, timeout=60) if r.status_code == 200: raw = r.json() or [] print("[v95] VAINEWS:", len(raw), "tin") break print("[v95] VAINEWS HTTP", r.status_code, "lan", attempt) except Exception as e: print("[v95] VAINEWS fail lan", attempt, ":", str(e)[:90]) if attempt < 3: _time95.sleep(4) if not isinstance(raw, list): raw = [] # ưu tiên tin có từ khoá AI ai = [a for a in raw if _v95_is_ai((a.get("title") or "") + " " + (a.get("link") or ""))] pool = ai if len(ai) >= 4 else raw items, seen = [], set() for a in pool: if len(items) >= limit: break title = (a.get("title") or "").strip() link = (a.get("link") or "").strip() if not title or not link or link in seen: continue seen.add(link) items.append({ "title": title, "url": link, "thumbnail": (a.get("img") or "").strip(), "via": (a.get("source") or "VAINEWS").strip(), "description": "", "body": "", "pubDate": "", "site": "", }) return items def _v95_refresh(limit: int = 10): items = _v95_from_vainews(limit) if not items: return [] # lấy mô tả + ảnh + nội dung song song try: from concurrent.futures import ThreadPoolExecutor with ThreadPoolExecutor(max_workers=6) as ex: deeps = list(ex.map(lambda it: _v95_deep(it["url"]), items)) for it, d in zip(items, deeps): if d.get("description"): it["description"] = d["description"] if not it["thumbnail"] and d.get("image"): it["thumbnail"] = d["image"] if d.get("body"): it["body"] = d["body"] if d.get("site"): it["site"] = d["site"] except Exception as e: print("[v95] deep pool fail:", e) # điền mô tả dự phòng nếu vẫn trống for it in items: if not it["description"]: it["description"] = it["title"] return items def _v95_get(): now = _time95.time() with _v95_lock: if _v95_ai_news["items"] and now - _v95_ai_news["at"] < _v95_TTL: return _v95_ai_news["items"] items = _v95_refresh(10) with _v95_lock: if items: _v95_ai_news["items"] = items _v95_ai_news["at"] = now return _v95_ai_news["items"] def _v95_warm(): try: _v95_get() print("[v95] warm tin AI:", len(_v95_ai_news["items"]), "tin") except Exception as e: print("[v95] warm fail", e) try: _threading95.Thread(target=_v95_warm, daemon=True).start() except Exception: pass # ============ Tin AI (V95 end) ============ @app.get("/api/img-proxy") async def api_img_proxy(url: str = ""): """Proxy ảnh tin tức -> cùng origin nên canvas đọc được pixel (không CORS).""" from fastapi.responses import Response as _Resp if not url.startswith("http"): return _Resp(status_code=400) try: hdr = {"User-Agent": _v95_UA["User-Agent"], "Accept": "image/avif,image/webp,image/*,*/*;q=0.8", "Referer": _re95.sub(r"^(https?://[^/]+)", r"\1/", url)} r = _rq95.get(url, headers=hdr, timeout=15, stream=True) if r.status_code != 200: return _Resp(status_code=404) ct = r.headers.get("content-type", "image/jpeg") if not ct.startswith("image/"): ct = "image/jpeg" return _Resp(content=r.content, media_type=ct, headers={"Cache-Control": "public, max-age=86400", "Access-Control-Allow-Origin": "*"}) except Exception as e: print("[v96] img-proxy fail", e) return _Resp(status_code=502) @app.get("/api/ai-news/item") async def api_ai_news_item(url: str = ""): """Chi tiết 1 tin cho modal: mô tả + nội dung + ảnh lớn.""" if not url: return {"ok": False, "error": "missing url"} d = _v95_deep(url) return {"ok": True, "url": url, "description": d.get("description", ""), "body": d.get("body", ""), "image": d.get("image", ""), "site": d.get("site", "")} @app.get("/api/ai-news") async def api_ai_news(): # V95: tin đầy đủ (tiêu đề + mô tả + ảnh thật) từ bep40/VAINEWS try: items = _v95_get() except Exception as e: print("[v95] handler fail", e) items = [] return {"items": items, "keyword": _v95_KEY, "updated": int(_time95.time()), "source": "bep40/VAINEWS"} # ============ BẢNG VÀNG ĐIỂM DANH ============ # V67: user siêng vào hang nhất — tên · số lần ghé hang · số lần trò chuyện. # Đếm trong RAM (không cần DB), giữ qua restart bằng /data nếu ghi được. _att_stats: Dict[str, dict] = {} # name -> {"visits": int, "chats": int} _att_lock = __import__("threading").Lock() # ---- V85: BỀN VỮNG — ghi xuống file để không mất khi restart ---- # Space cpu-basic có filesystem ephemeral; ta vẫn thử /data (persistent volume # nếu được gắn) rồi fallback /app, ./ — có file còn hơn mất sạch. def _att_path() -> str: for d in ("/data", "/app", "."): try: if os.path.isdir(d) and os.access(d, os.W_OK): return os.path.join(d, "attendance.json") except Exception: continue return "attendance.json" _ATT_FILE = _att_path() _att_dirty = False def _att_save(): """Ghi atomic: tmp -> os.replace, tránh hỏng file giữa chừng.""" global _att_dirty try: tmp = _ATT_FILE + ".tmp" with open(tmp, "w", encoding="utf-8") as f: json.dump(_att_stats, f, ensure_ascii=False) os.replace(tmp, _ATT_FILE) _att_dirty = False try: _att_bg_push() # V86: mirror lên Hub (thread nền) except NameError: pass # hàm định nghĩa sau — bỏ qua, lần gọi sau sẽ đẩy return True except Exception as e: print("[v85] _att_save loi:", e) return False def _att_load(): """Nạp lại số liệu đã lưu (nếu có).""" try: if os.path.isfile(_ATT_FILE): with open(_ATT_FILE, "r", encoding="utf-8") as f: d = json.load(f) if isinstance(d, dict): for k, v in d.items(): if isinstance(v, dict): _att_stats[str(k)[:60]] = { "visits": int(v.get("visits", 0)), "chats": int(v.get("chats", 0)), "joins": int(v.get("joins", 0)), "votes": int(v.get("votes", 0)),} print("[v85] _att_load: nạp", len(_att_stats), "user từ", _ATT_FILE) except Exception as e: print("[v85] _att_load loi:", e) _att_load() # ---- V86: MIRROR HUB — số liệu sống sót qua restart/rebuild ---- # Space cpu-basic không có volume; ta mirror lên dataset private trên Hub. # Ghi kiểu best-effort: lỗi mạng KHÔNG được làm hỏng request. ATT_DATASET = os.environ.get("ATT_DATASET", "bep40/hangmu-attendance") ATT_FILE_IN_REPO = "attendance.json" _att_push_fail = 0 def _att_push(snapshot=None): """Đẩy _att_stats (hoặc snapshot) lên Hub dataset (best-effort).""" try: from huggingface_hub import HfApi api = HfApi(token=os.environ.get("HF_TOKEN")) data = snapshot if snapshot is not None else _att_stats api.upload_file( path_or_fileobj=json.dumps(data, ensure_ascii=False).encode("utf-8"), path_in_repo=ATT_FILE_IN_REPO, repo_id=ATT_DATASET, repo_type="dataset", commit_message="attendance autosave", ) return True except Exception as e: global _att_push_fail _att_push_fail += 1 if _att_push_fail <= 3: print("[v86] _att_push loi:", e) return False def _att_pull(): """Đọc _att_stats từ Hub dataset lúc khởi động.""" try: from huggingface_hub import hf_hub_download p = hf_hub_download( repo_id=ATT_DATASET, repo_type="dataset", filename=ATT_FILE_IN_REPO, token=os.environ.get("HF_TOKEN"), ) with open(p, "r", encoding="utf-8") as f: d = json.load(f) if isinstance(d, dict): for k, v in d.items(): if isinstance(v, dict): _att_stats[str(k)[:60]] = { "visits": int(v.get("visits", 0)), "chats": int(v.get("chats", 0)), "votes": int(v.get("votes", 0)),} print("[v86] _att_pull: nạp", len(_att_stats), "user từ Hub") # ghi bản địa phương luôn để cờ persisted=true + có fallback offline try: tmp = _ATT_FILE + ".tmp" with open(tmp, "w", encoding="utf-8") as f: json.dump(_att_stats, f, ensure_ascii=False) os.replace(tmp, _ATT_FILE) except Exception as _e: print("[v86] _att_pull: không ghi được file local:", _e) except Exception as e: print("[v86] _att_pull: chưa có dữ liệu Hub (" + type(e).__name__ + ")") # nạp từ Hub lúc khởi động (file local là bản nháp) _att_pull() # V86d: cố đẩy lần cuối khi Space tắt (nếu còn dirty) try: import atexit atexit.register(lambda: _att_push() if _att_stats else None) except Exception: pass _att_push_lock = None # tạo trễ để tránh import-time phức tạp _att_push_busy = {"v": False} def _att_bg_push(): """Đẩy lên Hub ở thread nền, TUẦN TỰ — tránh 2 lần ghi đè nhau (lần cũ đến sau sẽ ghi đè số liệu mới).""" global _att_push_lock import threading if _att_push_lock is None: _att_push_lock = threading.Lock() if _att_push_busy["v"]: _att_push_busy["again"] = True # đang đẩy dở → nhắc đẩy lại bản mới nhất return _att_push_busy["v"] = True def _run(): try: with _att_push_lock: # CHỤP SNAPSHOT muộn nhất ngay trước khi đẩy — tránh đẩy # phải bản cũ (các bump sau đã vào _att_stats). import copy snap = copy.deepcopy(_att_stats) _att_push(snap) finally: _att_push_busy["v"] = False if _att_push_busy.get("again"): _att_push_busy["again"] = False _att_bg_push() # còn bump mới trong lúc đẩy → đẩy tiếp threading.Thread(target=_run, daemon=True).start() # V89: "visits" = số NGÀY khác nhau ghé hang (công bằng với mạng chập chờn). # "joins" = số lần vào thật. _att_seen_today reset theo ngày. _att_seen_today: Dict[str, str] = {} # name -> "YYYY-MM-DD" đã viếng hôm nay def _att_day() -> str: try: return time.strftime("%Y-%m-%d", time.gmtime(time.time() + 7 * 3600)) # UTC+7 except Exception: return "1970-01-01" def _att_join(name: str): """Gọi khi user join. Tính visits theo NGÀY, joins theo LẦN.""" nm = (name or "").strip()[:60] if not nm: return today = _att_day() if _att_seen_today.get(nm) != today: _att_seen_today[nm] = today _att_bump(nm, "visits") # lần đầu trong ngày mới +1 visits _att_bump(nm, "joins") # mỗi lần vào hang đều +1 def _att_bump(name: str, key: str): nm = (name or "").strip()[:60] if not nm: return global _att_dirty with _att_lock: e = _att_stats.setdefault(nm, {"visits": 0, "chats": 0, "joins": 0, "votes": 0}) e[key] = int(e.get(key, 0)) + 1 _att_dirty = True # ghi ngay (lượng ghi nhỏ, an toàn khi process bị kill) _att_save() def _att_bump_visit(name: str): _att_bump(name, "visits") def _att_bump_chat(name: str): _att_bump(name, "chats") def _att_score(r: dict) -> int: """V90: điểm siêng = visits*20 + chats*2 + joins*1. visits (số NGÀY) áp đảo → user vào đều mỗi ngày luôn xếp trên user chỉ vào 1 ngày nhưng nhắn nhiều tin.""" return int(r.get("visits", 0)) * 20 + int(r.get("chats", 0)) * 2 + int(r.get("joins", 0)) + int(r.get("votes", 0)) * 3 # V116: + binh chon @app.get("/api/attendance/top") async def api_attendance_top(): """Top 10 user siêng vào hang nhất: tên, số lần ghé hang, số lần trò chuyện.""" with _att_lock: rows = sorted( [{"name": k, "visits": int(v.get("visits", 0)), "chats": int(v.get("chats", 0)), "joins": int(v.get("joins", 0)), "votes": int(v.get("votes", 0))} for k, v in _att_stats.items()], # V90: điểm = visits*20 + chats*2 + joins*1 (số NGÀY áp đảo) key=lambda r: (-_att_score(r), -r["visits"], -r["chats"], r["name"].lower()), )[:10] for _r in rows: _r["score"] = _att_score(_r) return {"top": rows, "total": len(_att_stats), "updated": int(time.time()), "persisted": os.path.isfile(_ATT_FILE)} @app.post("/api/attendance/reset") async def api_attendance_reset(): """Xoá sạch bảng điểm danh (cả RAM, file và Hub).""" with _att_lock: _att_stats.clear() _att_save() return {"ok": True, "top": [], "total": 0} @app.get("/api/legends") async def api_legends(): return {"legends": _LEGENDS} @app.get("/api/onthisday") async def api_onthisday(): utc = time.gmtime() today = [(m, d, y, title, text) for (m, d, y, title, text) in _ON_THIS_DAY if m == utc.tm_mon and d == utc.tm_mday] return {"today": [{"m": m, "d": d, "y": y, "title": title, "text": text} for (m, d, y, title, text) in today]} # ============ Hằng số (khớp game-constants gốc) ============ GAME = { "simHz": 30, "moveSpeed": 8, "accel": 14, "turnRate": 12, "playerRadius": 0.32, "caveRadius": 58, "walkRadius": 42, "fireRadius": 2.65, "spawnX": 0, "spawnZ": 36, "roomCapacity": 500, "chatMaxChars": 200, "chatMinIntervalMs": 1500, "punchRange": 2.5, "punchCooldownMs": 1500, "punchImmuneMs": 3000, "inviteRange": 6, "boardMaxIds": 200, } ROOM_CAPACITY = GAME["roomCapacity"] # ============ Lọc từ ngữ ============ _BAD_WORDS = ["địt", "lồn", "cặc", "buồi", "đĩ", "chó má", "ngu dốt", "súc vật", "đm", "vcl", "cmm", "clmm"] _BAD_RE = re.compile("|".join(re.escape(w) for w in _BAD_WORDS), re.I) def filter_text(s: str) -> str: s = _BAD_RE.sub(lambda m: "*" * len(m.group(0)), s) return s def scrub_contact(s: str) -> str: """Che link + số điện thoại trong tin riêng (chống lừa đảo).""" s = re.sub(r"(https?://|www\.)\S+", "[liên kết bị che]", s) s = re.sub(r"(? (Player, room_id, expires) hold_slots: Dict[str, tuple] = {} # ---- chat ---- chat_log: List[dict] = [] MAX_CHAT_LOG = 120 # ---- invites ---- invites: Dict[str, dict] = {} # invite_id -> {kind, from, to, expires, ...} INVITE_KINDS = { "talk": {"icon": "💬", "asking": "giao lưu mồm", "title": "muốn giao lưu mồm", "sub": "Đồng ý thì cả hai đứng yên để chat riêng, cả hang không đọc được"}, "duel": {"icon": "🥊", "asking": "giao lưu võ thuật", "title": "muốn giao lưu võ thuật", "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"}, "penalty": {"icon": "⚽", "asking": "sút luân lưu", "title": "thách bạn sút luân lưu", "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ờ"}, "tug": {"icon": "💪", "asking": "kéo co", "title": "thách bạn kéo co", "sub": "Giữ nút để kéo, thả đúng vạch vàng để combo. Kéo dây về phía mình là thắng"}, "ball": {"icon": "👑", "asking": "giữ bóng", "title": "thách bạn giữ bóng", "sub": "Cướp bóng và giữ đến hết giờ. Ai là người giữ cuối cùng thì thắng"}, } # 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 INVITE_TTL_MS = 20000 # ---- minigames ---- # duel: {id, p1, p2, hp1, hp2, until, over} games: Dict[str, dict] = {} GAME_TTL = 90.0 # ---- polls ---- polls: Dict[str, dict] = {} POLL_INTERVAL_S = 180 # cứ 3 phút phát 1 poll nếu chưa có POLL_QUESTIONS = [ {"question": "Mô hình ngôn ngữ lớn (LLM) viết tắt của cụm nào?", "options": [{"icon": "🧠", "text": "Large Language Model"}, {"icon": "📐", "text": "Logical Layer Model"}, {"icon": "⚡", "text": "Long Latency Memory"}, {"icon": "🔁", "text": "Linear Learning Machine"}]}, {"question": "ChatGPT do công ty nào phát triển?", "options": [{"icon": "🤖", "text": "OpenAI"}, {"icon": "🔎", "text": "Google"}, {"icon": "🐦", "text": "xAI"}, {"icon": "🦙", "text": "Meta"}]}, {"question": "CUDA — nền tảng tính toán song song cho AI — do ai tạo ra?", "options": [{"icon": "🟩", "text": "NVIDIA"}, {"icon": "🔴", "text": "AMD"}, {"icon": "🔵", "text": "Intel"}, {"icon": "🍎", "text": "Apple"}]}, {"question": "Tham số \"temperature\" của một LLM điều chỉnh gì?", "options": [{"icon": "🎲", "text": "Mức ngẫu nhiên của câu trả lời"}, {"icon": "📏", "text": "Số token tối đa"}, {"icon": "🚀", "text": "Tốc độ sinh chữ"}, {"icon": "💾", "text": "Kích thước mô hình"}]}, ] def _make_poll(): q = _rand_pick(POLL_QUESTIONS) return {"id": uuid.uuid4().hex[:8], "question": q["question"], "options": q["options"], "counts": [0] * len(q["options"]), "voted": {}, "expires": time.time() + POLL_INTERVAL_S} # ---- board (video/music playlist) ---- # V34: màn hình lớn TỰ CẬP NHẬT video MU mới nhất — backend định kỳ quét # bongdaplus.vn (nguồn highlight bóng đá mở, không cần API key) để lấy # YouTube ID các clip Highlight MU / Premier League mới, đưa lên đầu playlist. # Nếu quét thất bại → GIỮ NGUYÊN playlist cũ (không làm trống màn hình). def _yt_meta(vid, title=""): """Chuẩn hoá YouTube ID / watch URL / embed URL / youtu.be -> object {url, title, img}. Frontend phát qua proxy bep40-vnews.hf.space (xem được tại VN; youtube-nocookie bị chặn nên trước đây màn hình lớn chỉ hiện fallback, không có video).""" s = str(vid or "").strip() m = re.search(r'(?:youtube(?:-nocookie)?\.com/(?:watch\?[^#]*v=|embed/|shorts/)|youtu\.be/)([a-zA-Z0-9_-]{11})', s) if m: vid = m.group(1) else: vid = (s or "")[:11] return {"url": "https://www.youtube.com/watch?v=" + vid, "title": title or "Highlight MU", "img": "https://i.ytimg.com/vi/" + vid + "/hqdefault.jpg"} BOARD = { "videos": [ _yt_meta("1LH4319g6Gw", "THẾ GIỚI NGOẠI HẠNG (9/11): MAN UNITED THOÁT HIỂM, MỘT HLV SẮP MẤT VIỆC"), _yt_meta("JuRD8gSdmps"), ], "music": [_yt_meta("VKmVJKDoPwk", "Glory Glory Man United — bài hát chính thức của MU")], } try: from fastapi import Request as _Request except Exception: _Request = None # V51: playlist màn hình lớn = YouTube RSS channel FPT Bóng Đá (rss2json), realtime 10 phút. _VNEWS_AI = "https://bep40-vnews.hf.space/api/fptplay/videos" # fallback 2 (không dùng trực tiếp) _FPT_RSS_CHANNEL = "UC4LvrpNXujjbGOS4RDvr41g" # FPT Bóng Đá (YouTube) _FPT_RSS_URL = None _VNEWS_CACHE = {"at": 0.0, "posts": None} _VNEWS_TTL = 600 # 10 phút import urllib.request as _urq def _http_get_json(url: str, timeout: int = 12): """GET JSON bằng stdlib urllib.""" try: with _urq.urlopen(url, timeout=timeout) as r: if r.status != 200: return None if "json" not in (r.headers.get("Content-Type") or ""): return None return json.loads(r.read().decode("utf-8", "replace")) except Exception as e: print(f"[board] vnews fetch error: {e}", flush=True) return None def _urllib_quote(s: str) -> str: """URL-encode bằng stdlib (an toàn khi runtime thiếu urllib.parse).""" try: import urllib.parse as _up return _up.quote(s, safe="") except Exception: return "".join(c if (c.isalnum() or c in "-_.~") else "%%%02X" % ord(c) for c in s) def _fpt_rss_fetch(): """Fetch YouTube RSS channel FPT Bóng Đá qua rss2json — 15 video mới nhất.""" try: global _FPT_RSS_URL if _FPT_RSS_URL is None: _FPT_RSS_URL = "https://api.rss2json.com/v1/api.json?rss_url=" + _urllib_quote( "https://www.youtube.com/feeds/videos.xml?channel_id=" + _FPT_RSS_CHANNEL) with _urq.urlopen(_FPT_RSS_URL, timeout=20) as r: if r.status != 200: print(f"[board] fpt rss HTTP {r.status}", flush=True) return None d = json.loads(r.read().decode("utf-8", "replace")) items = d.get("items") or [] out = [] for it in items[:15]: vid = (it.get("guid") or "").replace("yt:video:", "").strip() if not vid or len(vid) != 11: continue title = (it.get("title") or "FPT Bóng Đá").strip() thumb = (it.get("thumbnail") or ("https://i.ytimg.com/vi/" + vid + "/hqdefault.jpg")) out.append({ "url": "https://www.youtube.com/watch?v=" + vid, "title": title[:200], "img": thumb, "yt": vid, "published": (it.get("pubDate") or "")[:16], }) if out: print(f"[board] fpt rss OK: {len(out)} videos, first={out[0][chr(116)+chr(105)+chr(116)+chr(108)+chr(101)]}", flush=True) return out or None except Exception as e: print(f"[board] fpt rss error: {e}", flush=True) return None def _board_vnews(refresh: bool = False): """Playlist màn hình: ưu tiên RSS FPT Bóng Đá -> fallback /api/fptplay/videos -> cache cũ.""" now = time.time() if not refresh and _VNEWS_CACHE["posts"] is not None and now - _VNEWS_CACHE["at"] < _VNEWS_TTL: return _VNEWS_CACHE["posts"] out = _fpt_rss_fetch() if not out: data = _http_get_json(_VNEWS_AI, timeout=12) if data: try: posts = data.get("videos", []) or [] out = [] for p in posts[:28]: vid = (p.get("id") or "").strip() if not vid: continue link = (p.get("link") or "").strip() video_url = link if (link and link.startswith("http")) else ("https://www.youtube.com/watch?v=" + vid) out.append({ "url": video_url, "title": (p.get("title") or "FPT Bóng Đá").strip(), "img": (p.get("img") or ("https://i.ytimg.com/vi/" + vid + "/hqdefault.jpg")).strip(), "yt": vid, }) if not out: out = None except Exception as e: print(f"[board] fptplay fallback error: {e}", flush=True) out = None if out: _VNEWS_CACHE["posts"] = out _VNEWS_CACHE["at"] = now return out return _VNEWS_CACHE["posts"] _BOARD_LOCK = asyncio.Lock() _BOARD_SCRAPE = {"at": 0.0, "last_refresh": 0, "error": ""} # V35: persist playlist vào /data (ổ HF persistent — sống sót qua restart), # thư mục an toàn cũng được HF Jobs dùng; nếu read-only thì rơi về bộ nhớ. _BOARD_FILE = os.environ.get("BOARD_FILE", os.path.join(os.sep, "data", "board.json")) def _yt_meta(vid, title=""): """Chuẩn hoá YouTube ID / watch URL / embed URL / shorts / youtu.be -> object {url, title, img} — frontend phát qua proxy bep40-vnews.hf.space (xem được tại VN; youtube-nocookie bị chặn nên màn hình lớn không thể iframe thẳng).""" s = str(vid or "").strip() m = re.search(r'(?:youtube(?:-nocookie)?\.com/(?:watch\?[^#]*v=|embed/|shorts/|live/)|youtu\.be/|m\.youtube\.com/(?:watch\?[^#]*v=|embed/|shorts/))([a-zA-Z0-9_-]{11})', s) if m: vid = m.group(1) else: vid = (s or "")[:11] return {"url": "https://www.youtube.com/watch?v=" + vid, "title": title or "Highlight MU", "img": "https://i.ytimg.com/vi/" + vid + "/hqdefault.jpg"} def _yt_meta(vid, title=""): """Chuẩn hoá YouTube ID / watch URL / embed URL / shorts / youtu.be -> object {url, title, img} — frontend phát qua proxy bep40-vnews.hf.space (xem được tại VN; youtube-nocookie bị chặn nên màn hình lớn không thể iframe thẳng).""" s = str(vid or "").strip() m = re.search(r'(?:youtube(?:-nocookie)?\.com/(?:watch\?[^#]*v=|embed/|shorts/|live/)|youtu\.be/|m\.youtube\.com/(?:watch\?[^#]*v=|embed/|shorts/))([a-zA-Z0-9_-]{11})', s) if m: vid = m.group(1) else: vid = (s or "")[:11] return {"url": "https://www.youtube.com/watch?v=" + vid, "title": title or "Highlight MU", "img": "https://i.ytimg.com/vi/" + vid + "/hqdefault.jpg"} def _board_persist(): """Ghi playlist hiện tại xuống đĩa (fail-safe — không bao giờ ném lỗi).""" try: os.makedirs(os.path.dirname(_BOARD_FILE), exist_ok=True) with open(_BOARD_FILE, "w", encoding="utf-8") as f: json.dump({"videos": BOARD["videos"], "music": BOARD["music"], "scraped": _BOARD_SCRAPE["at"], "last_refresh": _BOARD_SCRAPE["last_refresh"]}, f) except Exception as e: print(f"[board] persist skipped ({e})") def _board_load(): """Khôi phục playlist từ đĩa lúc khởi động — màn hình có nội dung NGAY, không phải chờ lượt quét đầu tiên.""" try: if os.path.exists(_BOARD_FILE): with open(_BOARD_FILE, "r", encoding="utf-8") as f: d = json.load(f) if isinstance(d.get("videos"), list) and d["videos"]: def _norm(v): if isinstance(v, str): return _yt_meta(v) if isinstance(v, dict) and v.get("url"): return _yt_meta(v["url"], v.get("title") or "") return None BOARD["videos"] = [x for x in (_norm(v) for v in d["videos"]) if x][:12] _BOARD_SCRAPE["at"] = float(d.get("scraped", 0)) _BOARD_SCRAPE["last_refresh"] = int(d.get("last_refresh", 0)) print(f"[board] loaded {len(BOARD['videos'])} videos from {_BOARD_FILE}") except Exception as e: print(f"[board] load skipped ({e})") _MU_TITLE_KW = ["man united", "manchester united", "m.u", "mu", "quỷ đỏ", "quy do", "man utd", "m.u united", "của mu", "của man", "old trafford"] _PL_TITLE_KW = ["premier league", "ngoại hạng", "ngoai hang", "vòng ", "epl"] def _board_fetch(url: str, timeout: int = 12): req = urllib.request.Request(url, headers={ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124 Safari/537.36", "Accept-Language": "vi-VN,vi;q=0.9,en;q=0.6", }) with urllib.request.urlopen(req, timeout=timeout) as r: return r.read().decode("utf-8", "ignore") def _board_yt_id(html: str) -> Optional[str]: m = re.search(r"youtube(?:-nocookie)?\.com/embed/([a-zA-Z0-9_-]{11})", html) if m: return m.group(1) m = re.search(r"youtube\.com/watch\?v=([a-zA-Z0-9_-]{11})", html) return m.group(1) if m else None def _board_extract_listing(html: str, limit: int = 12): """Lấy các video Highlight từ trang danh sách bongdaplus (/video/premier-league).""" out = [] # anchor class="title" href="/video/.html" — nội dung là tiêu đề for m in re.finditer(r']*class="title"[^>]*href="(/video/[^"]+\.html)"[^>]*>(.*?)', html, re.S): slug = m.group(1) title = re.sub(r"<[^>]+>", "", m.group(2)) title = re.sub(r"\s+", " ", title).strip() if not title or len(title) < 5: continue out.append({"link": slug, "title": title}) if len(out) >= limit: break if out: return out # fallback: mọi anchor có href /video/...html for m in re.finditer(r']*href="(/video/[^"]+\.html)"[^>]*>(.*?)', html, re.S): slug = m.group(1) title = re.sub(r"<[^>]+>", "", m.group(2)) title = re.sub(r"\s+", " ", title).strip() if not title or len(title) < 5: continue out.append({"link": slug, "title": title}) if len(out) >= limit: break return out def _board_score_mu(title: str) -> int: """Điểm ưu tiên: 2 = liên quan trực tiếp MU; 1 = Highlight Premier League/ bàn thắng nói chung; 0 = không liên quan (tin chuyển nhượng, đội tuyển...).""" t = title.lower() if any(k in t for k in _MU_TITLE_KW): return 2 if any(k in t for k in _PL_TITLE_KW): return 1 if any(k in t for k in ["highlight", "tổng hợp", "tổng hơp", "bàn thắng", "hat-trick", "hat trick"]): return 1 # trận đấu dạng "A vs B: tỉ số" — chấp nhận như clip bóng đá (ưu tiên thấp) if re.search(r"\s+vs\s+", t) and re.search(r"\d+\s*[-:]\s*\d+", t): return 1 return 0 def _board_refresh_playlist() -> List[str]: """Quét bongdaplus Premier League → lấy YouTube ID (embed) cho video MU/PL mới. Sắp xếp ưu tiên: clip MU trước, kế đến Highlight PL/trận đấu, cuối cùng là clip bóng đá chung — màn hình lớn luôn có video MU mới nhất phía trước. Trên lỗi trả về [] để caller GIỮ playlist cũ (màn hình không bao giờ trống). """ try: html = _board_fetch("https://bongdaplus.vn/video/premier-league") items = _board_extract_listing(html, 20) if not items: raise RuntimeError("empty listing") scored: Dict[int, List[str]] = {2: [], 1: [], 0: []} seen = set() for item in items: try: detail = _board_fetch("https://bongdaplus.vn" + item["link"], timeout=10) vid = _board_yt_id(detail) if not vid or vid in seen: continue seen.add(vid) scored[_board_score_mu(item["title"])].append(vid) except Exception: continue ids = [] # ưu tiên: MU (2) → PL/trận (1) → chung (0), tối đa 10 for rank in (2, 1): for vid in scored[rank]: ids.append(vid) if len(ids) >= 10: break if len(ids) >= 10: break if len(ids) < 3: for vid in scored[0]: ids.append(vid) if len(ids) >= 10: break if not ids: raise RuntimeError("no youtube ids found") # playlist cũ giữ ở cuối làm dự phòng độ dài (hỗ trợ cả string lẫn object) base = [v if isinstance(v, str) else (v.get("url") or "") for v in BOARD["videos"]] base = [v for v in base if v and v not in seen][:4] return (ids + base)[:12] except Exception as e: _BOARD_SCRAPE["error"] = str(e)[:200] return [] async def _board_loop(): """Vòng lặp nền: quét NGAY lúc khởi động rồi mỗi 20 phút thử cập nhật playlist; persist xuống /data sau mỗi lần refresh; broadcast nếu đổi. V35: playlist nằm trên đĩa (không chỉ RAM) → sau restart màn hình lớn vẫn có đầy đủ video MU, không phải chờ lượt quét đầu tiên. """ # quét ngay lượt đầu (không sleep trước) — bắt đầu có nội dung mới tức thì try: if not _BOARD_LOCK.locked(): async with _BOARD_LOCK: fresh = await asyncio.get_event_loop().run_in_executor(None, _board_refresh_playlist) now = time.time() _BOARD_SCRAPE["at"] = now if fresh and fresh != BOARD["videos"]: old = BOARD["videos"] BOARD["videos"] = [_yt_meta(v) for v in fresh] _BOARD_SCRAPE["last_refresh"] = int(now) print(f"[board] initial refresh: {len(old)} -> {len(fresh)} videos, first={_yt_meta(fresh[0])['url']}") vn = await asyncio.get_event_loop().run_in_executor(None, _board_vnews) if vn: keep = [v for v in BOARD.get("videos", []) if not (v.get("mp4") or "").startswith("https://bep40-vnews.hf.space")][:12] BOARD["videos"] = vn + keep _board_persist() except Exception as e: print(f"[board] initial refresh error: {e}") while True: try: await asyncio.sleep(20 * 60) if not _BOARD_LOCK.locked(): async with _BOARD_LOCK: fresh = await asyncio.get_event_loop().run_in_executor(None, _board_refresh_playlist) now = time.time() _BOARD_SCRAPE["at"] = now if fresh and fresh != BOARD["videos"]: old = BOARD["videos"] BOARD["videos"] = [_yt_meta(v) for v in fresh] _BOARD_SCRAPE["last_refresh"] = int(now) print(f"[board] playlist refreshed: {len(old)} -> {len(fresh)} videos, first={_yt_meta(fresh[0])['url']}") vn = await asyncio.get_event_loop().run_in_executor(None, _board_vnews) if vn: keep = [v for v in BOARD.get("videos", []) if not (v.get("mp4") or "").startswith("https://bep40-vnews.hf.space")][:12] BOARD["videos"] = vn + keep _board_persist() try: await broadcast("lobby", {"type": "board", "videos": BOARD["videos"], "music": BOARD["music"]}) except Exception: pass except Exception as e: print(f"[board] loop error: {e}") await asyncio.sleep(5 * 60) # ---- leaderboard (tuần) ---- weekly: Dict[str, dict] = defaultdict(lambda: {"name": "", "number": None, "wins": defaultdict(int)}) # ---- push subscriptions (Web Push) ---- push_subs: Dict[str, dict] = {} # endpoint -> subscription JSON # ============ Models ============ class JoinRequest(BaseModel): room_id: str = "lobby" player_name: str player_number: Optional[int] = None class MeRequest(BaseModel): name: Optional[str] = None number: Optional[int] = None class QuizAnswerRequest(BaseModel): questionId: str answerId: str class PushSubscribeRequest(BaseModel): subscription: dict class PushUnsubscribeRequest(BaseModel): endpoint: str # ============ Quiz ============ QUIZ_QUESTIONS = [ {"id": "q1", "q": "Model Grok thuộc về công ty nào?", "answers": [{"id": "a1", "text": "xAI"}, {"id": "a2", "text": "OpenAI"}, {"id": "a3", "text": "Google DeepMind"}, {"id": "a4", "text": "Anthropic"}], "correct": "a1"}, {"id": "q2", "q": "Ai là cha đẻ của NVIDIA?", "answers": [{"id": "a1", "text": "Jensen Huang"}, {"id": "a2", "text": "Sam Altman"}, {"id": "a3", "text": "Elon Musk"}, {"id": "a4", "text": "Sundar Pichai"}], "correct": "a1"}, {"id": "q3", "q": "ChatGPT do công ty nào phát triển?", "answers": [{"id": "a1", "text": "OpenAI"}, {"id": "a2", "text": "Meta"}, {"id": "a3", "text": "Microsoft"}, {"id": "a4", "text": "xAI"}], "correct": "a1"}, {"id": "q4", "q": "AlphaGo — hệ thống đánh bại kỳ thủ cờ vây Hàn Quốc Lee Sedol — do ai phát triển?", "answers": [{"id": "a1", "text": "Google DeepMind"}, {"id": "a2", "text": "IBM"}, {"id": "a3", "text": "OpenAI"}, {"id": "a4", "text": "NVIDIA"}], "correct": "a1"}, {"id": "q5", "q": "Google Gemini do công ty nào phát triển?", "answers": [{"id": "a1", "text": "Google"}, {"id": "a2", "text": "OpenAI"}, {"id": "a3", "text": "Meta"}, {"id": "a4", "text": "Amazon"}], "correct": "a1"}, {"id": "q6", "q": "Llama là dòng mô hình ngôn ngữ mở của công ty nào?", "answers": [{"id": "a1", "text": "Meta"}, {"id": "a2", "text": "Google"}, {"id": "a3", "text": "Anthropic"}, {"id": "a4", "text": "Mistral"}], "correct": "a1"}, {"id": "q7", "q": "Anthropic là công ty đứng sau dòng model AI nào?", "answers": [{"id": "a1", "text": "Claude"}, {"id": "a2", "text": "Gemini"}, {"id": "a3", "text": "Grok"}, {"id": "a4", "text": "Copilot"}], "correct": "a1"}, {"id": "q8", "q": "GPU là viết tắt của cụm từ nào?", "answers": [{"id": "a1", "text": "Graphics Processing Unit"}, {"id": "a2", "text": "General Program Unit"}, {"id": "a3", "text": "Grid Power Unit"}, {"id": "a4", "text": "Global Processor Utility"}], "correct": "a1"}, {"id": "q9", "q": "Deep Learning là một nhánh của lĩnh vực nào?", "answers": [{"id": "a1", "text": "Machine Learning"}, {"id": "a2", "text": "Khoa học vật liệu"}, {"id": "a3", "text": "Cơ sở dữ liệu"}, {"id": "a4", "text": "Mạng máy tính"}], "correct": "a1"}, {"id": "q10", "q": "Mô hình ngôn ngữ lớn (LLM) thường được viết tắt từ cụm nào?", "answers": [{"id": "a1", "text": "Large Language Model"}, {"id": "a2", "text": "Linear Learning Machine"}, {"id": "a3", "text": "Logical Layer Model"}, {"id": "a4", "text": "Long Latency Memory"}], "correct": "a1"}, {"id": "q11", "q": "Phát biểu nào mô tả đúng nhất về \"học có giám sát\" (supervised learning)?", "answers": [{"id": "a1", "text": "Học từ dữ liệu đã có nhãn đúng"}, {"id": "a2", "text": "Học không cần dữ liệu"}, {"id": "a3", "text": "Học chỉ từ phần thưởng"}, {"id": "a4", "text": "Học bằng cách nén dữ liệu"}], "correct": "a1"}, {"id": "q12", "q": "Tham số \"temperature\" của một LLM chủ yếu điều chỉnh điều gì?", "answers": [{"id": "a1", "text": "Mức độ ngẫu nhiên / sáng tạo của câu trả lời"}, {"id": "a2", "text": "Số token tối đa"}, {"id": "a3", "text": "Tốc độ mạng"}, {"id": "a4", "text": "Kích thước mô hình"}], "correct": "a1"}, {"id": "q13", "q": "Ai được mệnh danh là \"cha đẻ của trí tuệ nhân tạo\" với bài kiểm tra Turing?", "answers": [{"id": "a1", "text": "Alan Turing"}, {"id": "a2", "text": "Geoffrey Hinton"}, {"id": "a3", "text": "Yann LeCun"}, {"id": "a4", "text": "John McCarthy"}], "correct": "a1"}, {"id": "q14", "q": "CUDA — nền tảng tính toán song song phổ biến cho AI — do công ty nào tạo ra?", "answers": [{"id": "a1", "text": "NVIDIA"}, {"id": "a2", "text": "AMD"}, {"id": "a3", "text": "Intel"}, {"id": "a4", "text": "Qualcomm"}], "correct": "a1"}, ] _right_messages = ["Chuẩn! Kiến thức AI của bạn vững thật.", "Chính xác! Mời vào hang cùng anh em.", "Đúng rồi! Trí tuệ nhân tạo đang chờ bạn trong hang."] _wrong_messages = ["Chưa đúng — không sao, vào hang anh em trao đổi thêm.", "Sai một chút thôi, hang vẫn mở cửa chào bạn.", "Hụt rồi! Đáp án đúng đang được tô xanh đó."] def _rand_pick(arr): return arr[random.randrange(len(arr))] def _room_players(room_id: str) -> Dict[str, dict]: return {pid: p.__dict__ for pid, p in rooms.get(room_id, {}).items()} # ============ REST ============ @app.get("/health") async def health(): return {"status": "ok"} @app.get("/version.json") async def version(): return {"id": VERSION_ID} @app.get("/rooms") async def get_rooms(): return {"rooms": [{"id": rid, "name": "Hang chung", "players": len(players), "max_players": ROOM_CAPACITY} for rid, players in rooms.items()]} @app.get("/room/status") async def room_status(): lobby = rooms.get("lobby", {}) return {"inRoom": len(lobby), "waiting": len(waitlists.get("lobby", [])), "maxRoom": ROOM_CAPACITY, "capacity": ROOM_CAPACITY} @app.get("/quiz") async def get_quiz(): q = _rand_pick(QUIZ_QUESTIONS) answers = list(q["answers"]) random.shuffle(answers) return {"questions": [{"id": q["id"], "q": q["q"], "answers": answers}]} @app.post("/quiz/answer") async def quiz_answer(req: QuizAnswerRequest): q = next((x for x in QUIZ_QUESTIONS if x["id"] == req.questionId), None) if not q: raise HTTPException(404, "Question not found") correct = req.answerId == q["correct"] return {"correct": correct, "message": _rand_pick(_right_messages) if correct else _rand_pick(_wrong_messages), "correctAnswerId": q["correct"] if not correct else None} # --- profile (hm_sid cookie) --- @app.get("/me") async def me_get(): return {"name": "", "number": None} @app.post("/me") async def me_post(req: MeRequest): name = filter_text((req.name or "").strip()) if len(name) > 60: raise HTTPException(422, "Name too long") return {"name": name, "number": req.number if (req.number and 1 <= req.number <= 99) else None} @app.post("/join", response_model=None) async def join_room(req: JoinRequest): if req.room_id not in rooms: raise HTTPException(404, "Room not found") if len(rooms[req.room_id]) >= ROOM_CAPACITY: wl = waitlists.setdefault(req.room_id, []) wl.append({"name": req.player_name, "number": req.player_number}) return {"player_id": None, "room": {"id": req.room_id, "name": "Hang chung"}, "players": {}, "queue_position": len(wl), "queued": True} player_id = uuid.uuid4().hex[:8] number = req.player_number if number is not None and not (1 <= number <= 99): raise HTTPException(422, "Jersey number must be 1-99") player = Player(id=player_id, name=req.player_name, number=number, sid=uuid.uuid4().hex[:12]) _att_join(req.player_name) # V89: visits theo ngày rooms[req.room_id][player_id] = player player_rooms[player_id] = req.room_id return {"player_id": player_id, "room": {"id": req.room_id, "name": "Hang chung"}, "players": _room_players(req.room_id), "queued": False} @app.post("/queue/leave") async def leave_queue(req: JoinRequest): wl = waitlists.get(req.room_id) if wl: waitlists[req.room_id] = [w for w in wl if w.get("name") != req.player_name] return {"ok": True} @app.get("/board") async def board(): return {"videos": BOARD["videos"], "music": BOARD["music"]} @app.get("/api/diag") async def api_diag(ok: str = "0", y: str = "0", px: str = "0", pz: str = "0", d: str = "", n: str = "0"): print(f"[diag] boardPx.ok={ok} yaw={y} cam=({px},{pz}) disp={d} n={n}") return {"ok": True} @app.get("/api/board") async def api_board(): vids = list(BOARD.get("videos", [])) # V46: cố lấy short AI Tường AI mới nhất (cache) — chèn đầu playlist vn = await asyncio.get_event_loop().run_in_executor(None, _board_vnews) if vn: keep = [v for v in vids if not (v.get("mp4") or "").startswith("https://bep40-vnews.hf.space")][:12] vids = vn + keep return {"videos": vids, "music": BOARD["music"]} @app.get("/api/board/video") async def api_board_video(url: str = "", request: _Request = None): """V46: proxy stream mp4 short AI từ VNEWS — trình duyệt user chỉ tải từ domain hangmu (tránh CORS + lệ thuộc + chặn mạng). Range supported.""" if not url.startswith("https://bep40-vnews.hf.space/api/ai/short-file/"): return JSONResponse({"error": "bad url"}, status_code=400) try: hdrs = {"User-Agent": "hangmu-board/1.0"} if request is not None: rg = request.headers.get("range") if rg: hdrs["Range"] = rg req = _urq.Request(url, headers=hdrs) resp = _urq.urlopen(req, timeout=30) code = resp.status if code not in (200, 206): try: resp.close() except Exception: pass return JSONResponse({"error": "origin " + str(code)}, status_code=502) ctype = resp.headers.get("Content-Type", "video/mp4") out_h = {"Cache-Control": "public, max-age=3600", "Accept-Ranges": "bytes"} if resp.headers.get("Content-Range"): out_h["Content-Range"] = resp.headers["Content-Range"] if resp.headers.get("Content-Length"): out_h["Content-Length"] = resp.headers["Content-Length"] def _stream(): try: while True: chunk = resp.read(65536) if not chunk: break yield chunk finally: try: resp.close() except Exception: pass from fastapi.responses import StreamingResponse return StreamingResponse(_stream(), media_type=ctype, status_code=code, headers=out_h) except Exception as e: return JSONResponse({"error": str(e)[:160]}, status_code=502) @app.get("/api/video-proxy") async def api_video_proxy(url: str = "", title: str = "", img: str = "", loop: int = 1): """V43: trang embed YouTube nội bộ (xem ở VN, gửi hangmu-playing trung thực) — màn hình lớn không phụ thuộc VNEWS build.""" return video_proxy.render_video_proxy(url, title, img, loop) @app.get("/api/video-proxy") async def api_video_proxy(url: str = "", title: str = "", img: str = "", loop: int = 1): """V43: trang embed YouTube nội bộ (xem ở VN, gửi hangmu-playing trung thực) — màn hình lớn không phụ thuộc VNEWS build.""" return video_proxy.render_video_proxy(url, title, img, loop) @app.get("/api/board/status") async def api_board_status(): return {"videos": BOARD["videos"], "music": BOARD["music"], "scraped": int(_BOARD_SCRAPE["at"]), "last_refresh": _BOARD_SCRAPE["last_refresh"], "error": _BOARD_SCRAPE["error"], "limit": 10} @app.post("/api/board/refresh") async def api_board_refresh(): async with _BOARD_LOCK: fresh = await asyncio.get_event_loop().run_in_executor(None, _board_refresh_playlist) _BOARD_SCRAPE["at"] = time.time() if fresh and fresh != BOARD["videos"]: BOARD["videos"] = [_yt_meta(v) for v in fresh] _BOARD_SCRAPE["last_refresh"] = int(time.time()) _board_persist() return {"ok": True, "videos": BOARD["videos"], "refreshed": bool(fresh)} @app.get("/leaderboard") async def leaderboard(): out = {} for g in ("duel", "penalty", "tug", "ball"): rows = sorted(weekly.items(), key=lambda kv: -kv[1]["wins"].get(g, 0))[:5] out[g] = [{"name": v["name"], "number": v["number"], "wins": v["wins"].get(g, 0)} for _, v in rows if v["wins"].get(g, 0) > 0] return out # --- Web Push đăng ký --- @app.post("/push/subscribe") async def push_subscribe(req: PushSubscribeRequest): sub = req.subscription or {} ep = sub.get("endpoint", "") if not ep: raise HTTPException(422, "Missing endpoint") push_subs[ep] = sub return {"ok": True, "total": len(push_subs)} @app.post("/push/unsubscribe") async def push_unsubscribe(req: PushUnsubscribeRequest): push_subs.pop(req.endpoint, None) return {"ok": True} # --- ESPN proxy (điểm danh MU — team 360) --- ESPN_BASE = "https://site.api.espn.com/apis/site/v2/sports/soccer/eng.1" _espn_cache: Dict[str, tuple] = {} # path -> (at, data) @app.get("/ext/espn/{path:path}") async def ext_espn(path: str): now = time.time() cached = _espn_cache.get(path) if cached and now - cached[0] < 45: return JSONResponse(cached[1]) url = f"{ESPN_BASE}/{path}" try: req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0", "Accept": "application/json"}) with urllib.request.urlopen(req, timeout=6) as r: data = json.loads(r.read().decode("utf-8")) _espn_cache[path] = (now, data) return JSONResponse(data) except Exception as e: if cached: return JSONResponse(cached[1]) return JSONResponse({"error": str(e)}, status_code=502) # ============ Bảng xếp hạng Ngoại hạng Anh (thật, qua ESPN) ============ # Lưu ý: standings của ESPN nằm ở /apis/v2 (khác base /site/v2 của proxy ủy quyền) EPL_STANDINGS_URL = "https://site.api.espn.com/apis/v2/sports/soccer/eng.1/standings" _standings_cache = {"at": 0.0, "data": None} @app.get("/api/standings") async def api_standings(): now = time.time() if _standings_cache["data"] and now - _standings_cache["at"] < 300: return JSONResponse(_standings_cache["data"]) try: req = urllib.request.Request(EPL_STANDINGS_URL, headers={"User-Agent": "Mozilla/5.0", "Accept": "application/json"}) with urllib.request.urlopen(req, timeout=8) as r: raw = json.loads(r.read().decode("utf-8")) children = raw.get("children") or [] entries = (children[0].get("standings") or {}).get("entries") or [] if children else [] teams = [] for e in entries: stats = {s.get("name"): (s.get("displayValue") or "0") for s in (e.get("stats") or [])} teams.append({ "name": (e.get("team") or {}).get("displayName", "?"), "short": (e.get("team") or {}).get("abbreviation", ""), "rank": int(stats.get("rank", 0) or 0), "played": int(stats.get("gamesPlayed", 0) or 0), "won": int(stats.get("wins", 0) or 0), "drawn": int(stats.get("ties", 0) or 0), "lost": int(stats.get("losses", 0) or 0), "gf": int(stats.get("pointsFor", 0) or 0), "ga": int(stats.get("pointsAgainst", 0) or 0), "pts": int(stats.get("points", 0) or 0), }) data = {"teams": teams, "at": int(now)} _standings_cache["data"] = data _standings_cache["at"] = now return JSONResponse(data) except Exception as e: if _standings_cache["data"]: return JSONResponse(_standings_cache["data"]) return JSONResponse({"error": str(e)}, status_code=502) # ============ Trận đấu MU: trận gần nhất + trận sắp tới (ESPN team 360) ============ MU_SCHEDULE_URL = "https://site.api.espn.com/apis/site/v2/sports/soccer/eng.1/teams/360/schedule" _mu_sched_cache = {"at": 0.0, "data": None} def _mu_parse_events(raw): """Tách trận đã đá (post) và trận sắp tới (pre/in) của MU từ schedule ESPN.""" last = None next_ = None for e in raw.get("events") or []: comps = e.get("competitions") or [] if not comps: continue c = comps[0] st = ((c.get("status") or {}).get("type") or {}).get("state") or "pre" opp = None; mu_score = None; opp_score = None; mu_home = None for t in c.get("competitors") or []: tid = (t.get("team") or {}).get("id") sc = t.get("score") if isinstance(sc, dict): sc = sc.get("displayValue") if tid == "360": mu_score = sc; mu_home = t.get("homeAway") == "home" else: opp = (t.get("team") or {}).get("displayName") or "?" opp_score = sc mu_home = bool(mu_home) venue_name = ((c.get("venue") or {}).get("fullName")) or (mu_home and "Old Trafford" or "Sân khách") row = { "event_id": c.get("id") or e.get("id"), "date": e.get("date"), "opponent": opp, "mu_score": mu_score, "opp_score": opp_score, "home": mu_home, "venue": venue_name, "short": e.get("shortName"), } if st == "post": if last is None or (e.get("date") or "") > (last.get("date") or ""): last = row else: if next_ is None or (e.get("date") or "") < (next_.get("date") or ""): next_ = row return last, next_ ESPN_SUMMARY_URL = "https://site.api.espn.com/apis/site/v2/sports/soccer/eng.1/summary" _mu_summary_cache = {"at": 0.0, "data": {}} async def _fetch_mu_summary(event_id: str): """Lấy danh sách cầu thủ ghi bàn + phút của trận MU từ ESPN summary (keyEvents).""" now = time.time() if event_id in _mu_summary_cache["data"] and now - _mu_summary_cache["at"] < 3600: return _mu_summary_cache["data"][event_id] try: url = f"{ESPN_SUMMARY_URL}?event={event_id}" req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0", "Accept": "application/json"}) with urllib.request.urlopen(req, timeout=8) as r: raw = json.loads(r.read().decode("utf-8")) events = raw.get("keyEvents") or [] scorers = [] for e in events: ttype = (e.get("type") or {}).get("type") or "" text = (e.get("type") or {}).get("text") or "" is_goal = ("goal" in (ttype or "").lower()) or (ttype == "goal") or (ttype == "penalty") if not is_goal or not e.get("scoringPlay"): continue team_id = ((e.get("team") or {}).get("id")) or "" ps = e.get("participants") or [] scorer = (ps[0].get("athlete") or {}).get("displayName") if ps else "" minute = ((e.get("clock") or {}).get("displayValue")) or "" scorers.append({ "minute": minute, "player": scorer or "?", "side": "mu" if team_id == "360" else "opp", "kind": ttype, }) _mu_summary_cache["data"][event_id] = scorers _mu_summary_cache["at"] = now return scorers except Exception: return [] @app.get("/api/mu/last") async def api_mu_last(): now = time.time() if _mu_sched_cache["data"] and now - _mu_sched_cache["at"] < 600: last, _ = _mu_parse_events(_mu_sched_cache["data"]) if last and last.get("event_id"): last.setdefault("scorers", await _fetch_mu_summary(str(last["event_id"]))) return JSONResponse(last or {"error": "no data"}) try: req = urllib.request.Request(MU_SCHEDULE_URL, headers={"User-Agent": "Mozilla/5.0", "Accept": "application/json"}) with urllib.request.urlopen(req, timeout=8) as r: raw = json.loads(r.read().decode("utf-8")) _mu_sched_cache["data"] = raw _mu_sched_cache["at"] = now last, _ = _mu_parse_events(raw) if last and last.get("event_id"): last.setdefault("scorers", await _fetch_mu_summary(str(last["event_id"]))) return JSONResponse(last or {"error": "no data"}) except Exception as e: return JSONResponse({"error": str(e)}, status_code=502) @app.get("/api/mu/next") async def api_mu_next(): now = time.time() if _mu_sched_cache["data"] and now - _mu_sched_cache["at"] < 600: _, nxt = _mu_parse_events(_mu_sched_cache["data"]) return JSONResponse(nxt or {"none": True}) try: req = urllib.request.Request(MU_SCHEDULE_URL, headers={"User-Agent": "Mozilla/5.0", "Accept": "application/json"}) with urllib.request.urlopen(req, timeout=8) as r: raw = json.loads(r.read().decode("utf-8")) _mu_sched_cache["data"] = raw _mu_sched_cache["at"] = now _, nxt = _mu_parse_events(raw) return JSONResponse(nxt or {"none": True}) except Exception as e: return JSONResponse({"error": str(e)}, status_code=502) # ============ WebSocket helpers ============ async def send(ws: WebSocket, msg: dict): try: await ws.send_text(json.dumps(msg)) except Exception: pass async def broadcast(room_id: str, msg: dict, exclude: Optional[str] = None): dead = [] for pid, ws in connections.items(): if pid == exclude: continue if player_rooms.get(pid) == room_id: try: await ws.send_text(json.dumps(msg)) except Exception: dead.append(pid) for pid in dead: connections.pop(pid, None) async def to_player(pid: str, msg: dict): ws = connections.get(pid) if ws: await send(ws, msg) def add_feed(room_id: str, text: str): chat_log.append({"text": text, "at": time.time()}) del chat_log[:max(0, len(chat_log) - MAX_CHAT_LOG)] def _player_of(pid: str): rid = player_rooms.get(pid) if not rid: return None return rooms.get(rid, {}).get(pid) def _distance(a: Player, b: Player) -> float: return ((a.position.get("x", 0) - b.position.get("x", 0)) ** 2 + (a.position.get("z", 0) - b.position.get("z", 0)) ** 2) ** 0.5 # ---- leaderboard helpers ---- def _record_win(game: str, player: Player, loser_name: str = ""): entry = weekly[player.id] entry["name"] = player.name entry["number"] = player.number entry["wins"][game] += 1 # ============ Mini-game state machines (server-authoritative, JSON) ============ def _end_duel(gid: str): g = games.pop(gid, None) if not g: return p1, p2 = _player_of(g["p1"]), _player_of(g["p2"]) if p1: p1.busy = False; p1.inGame = None if p2: p2.busy = False; p2.inGame = None if not p1 or not p2: return if g.get("hp1", 100) <= 0 and g.get("hp2", 100) <= 0: msg = f"{p1.name} và {p2.name} cùng gục — hoà 🥊" elif g.get("hp1", 100) <= 0: msg = f"{p2.name} đấm vỡ mồm {p1.name} 💥"; _record_win("duel", p2) elif g.get("hp2", 100) <= 0: msg = f"{p1.name} đấm vỡ mồm {p2.name} 💥"; _record_win("duel", p1) elif g.get("hp1", 100) > g.get("hp2", 100): msg = f"{p1.name} thắng {p2.name} sát nút 🥊"; _record_win("duel", p1) elif g.get("hp2", 100) > g.get("hp1", 100): msg = f"{p2.name} thắng {p1.name} sát nút 🥊"; _record_win("duel", p2) else: msg = f"{p1.name} và {p2.name} bất phân thắng bại 🥊" add_feed("lobby", msg) asyncio.ensure_future(broadcast("lobby", {"type": "feed", "text": msg})) asyncio.ensure_future(broadcast("lobby", {"type": "game_over", "game": "duel", "text": msg, "p1": g["p1"], "p2": g["p2"], "hp1": g.get("hp1", 0), "hp2": g.get("hp2", 0)})) def _end_penalty(gid: str): g = games.pop(gid, None) if not g: return p1, p2 = _player_of(g["p1"]), _player_of(g["p2"]) if p1: p1.busy = False; p1.inGame = None if p2: p2.busy = False; p2.inGame = None if not p1 or not p2: return s1, s2 = g.get("s1", 0), g.get("s2", 0) if s1 > s2: msg = f"{p1.name} thắng luân lưu {s1}–{s2} ⚽"; _record_win("penalty", p1) elif s2 > s1: msg = f"{p2.name} thắng luân lưu {s2}–{s1} ⚽"; _record_win("penalty", p2) else: msg = f"{p1.name} và {p2.name} hoà luân lưu {s1}–{s2} ⚽" add_feed("lobby", msg) asyncio.ensure_future(broadcast("lobby", {"type": "feed", "text": msg})) asyncio.ensure_future(broadcast("lobby", {"type": "game_over", "game": "penalty", "text": msg, "p1": g["p1"], "p2": g["p2"], "s1": s1, "s2": s2})) def _end_tug(gid: str): g = games.pop(gid, None) if not g: return for pid in (g.get("p1"), g.get("p2")): p = _player_of(pid) if p: p.busy = False; p.inGame = None p1, p2 = _player_of(g.get("p1", "")), _player_of(g.get("p2", "")) if not p1 or not p2: return if g.get("pos", 0) >= 100: msg = f"{p1.name} thắng kéo co 💪"; _record_win("tug", p1) elif g.get("pos", 0) <= -100: msg = f"{p2.name} thắng kéo co 💪"; _record_win("tug", p2) else: msg = "Hết giờ kéo co — hoà 💪" add_feed("lobby", msg) asyncio.ensure_future(broadcast("lobby", {"type": "feed", "text": msg})) asyncio.ensure_future(broadcast("lobby", {"type": "game_over", "game": "tug", "text": msg})) def _end_ball(gid: str): g = games.pop(gid, None) if not g: return for pid in g.get("players", []): p = _player_of(pid) if p: p.busy = False; p.inGame = None holder = g.get("holder") if holder: p = _player_of(holder) if p: _record_win("ball", p) msg = f"👑 {p.name} giữ bóng đến hết giờ!" add_feed("lobby", msg) asyncio.ensure_future(broadcast("lobby", {"type": "feed", "text": msg})) # ============ WebSocket ============ @app.websocket("/ws/{player_id}") async def websocket_endpoint(ws: WebSocket, player_id: str): await ws.accept() room_id = player_rooms.get(player_id) if not room_id: await send(ws, {"type": "error", "message": "Not in a room"}) await ws.close() return connections[player_id] = ws player = rooms[room_id].get(player_id) if player: player.connected = True player.lastSeen = time.time() await send(ws, {"type": "connected", "player_id": player_id, "timestamp": time.time(), "inRoom": len(rooms[room_id])}) await broadcast(room_id, {"type": "player_joined", "player": player.__dict__}, exclude=player_id) add_feed(room_id, f"{player.name} đã vào hang 🏰") await broadcast(room_id, {"type": "feed", "text": f"{player.name} đã vào hang 🏰"}, exclude=player_id) await send(ws, {"type": "feed", "text": f"Chào mừng {player.name} đến với Hang MU! 🏰"}) await send(ws, {"type": "board", "videos": BOARD["videos"], "music": BOARD["music"]}) await send(ws, {"type": "leaderboard", "board": await leaderboard()}) # gửi poll đang mở (nếu có) poll = polls.get("lobby") if poll and not poll.get("voted", {}).get(player_id): await send(ws, {"type": "poll", "poll": poll}) else: await send(ws, {"type": "error", "message": "Not in a room"}) await ws.close() return try: while True: data = await ws.receive_text() try: msg = json.loads(data) except json.JSONDecodeError: continue t = msg.get("type") now = time.time() if t == "update": p = _player_of(player_id) if p: if isinstance(msg.get("position"), dict): p.position = {k: float(msg["position"][k]) for k in ("x", "y", "z") if k in msg["position"]} if "rotation" in msg: p.rotation = float(msg["rotation"]) if "animation" in msg: p.animation = str(msg["animation"])[:16] p.lastSeen = now await broadcast(room_id, {"type": "player_update", "player_id": player_id, "position": p.position, "rotation": p.rotation, "animation": p.animation}, exclude=player_id) elif t == "chat": p = _player_of(player_id) if not p: continue now_ms = now * 1000 if now_ms - p.lastChatAt * 1000 < GAME["chatMinIntervalMs"]: await send(ws, {"type": "chatDropped", "reason": "rate", "id": msg.get("id")}) continue text = filter_text(str(msg.get("message", "")))[:GAME["chatMaxChars"]] if not text.strip(): continue p.lastChatAt = now _att_bump(p.name, "chats") await broadcast(room_id, {"type": "chat", "player_id": player_id, "player_name": p.name, "message": text, "timestamp": now}) add_feed(room_id, f"{p.name}: {text}") elif t == "dm": p = _player_of(player_id) if not p: continue target = msg.get("target") tp = _player_of(target) if not tp: await send(ws, {"type": "dmFailed", "reason": "gone"}) continue text = scrub_contact(filter_text(str(msg.get("message", ""))[:400])) if not text.strip(): continue await to_player(target, {"type": "dm", "from": player_id, "player_name": p.name, "message": text, "timestamp": now}) await send(ws, {"type": "dmAck", "to": target, "text": text, "timestamp": now}) elif t == "punch": p = _player_of(player_id) if not p: continue if p.busy or p.inGame: continue if now < p.punchImmuneUntil: continue # tìm người gần nhất trong tầm target = None for pid, q in rooms[room_id].items(): if pid == player_id or q.busy: continue if _distance(p, q) <= GAME["punchRange"]: target = q break if not target: continue if now < target.punchedUntil: continue target.punchedUntil = now + 1.2 target.punchImmuneUntil = now + GAME["punchImmuneMs"] / 1000 await to_player(target.id, {"type": "punched", "by": p.name, "seq": msg.get("seq", 0)}) await broadcast(room_id, {"type": "punchHit", "target": target.id, "by": p.name, "by_id": player_id}) add_feed(room_id, f"{p.name} đấm {target.name} 💥") elif t == "celebrate": p = _player_of(player_id) if p: await broadcast(room_id, {"type": "celebrate", "player_id": player_id, "player_name": p.name}) elif t == "vote": p = _player_of(player_id) poll = polls.get("lobby") if p and poll and not poll.get("voted", {}).get(player_id): poll["voted"][player_id] = True poll["counts"][int(msg.get("option", 0)) % len(poll["options"])] += 1 _att_bump(p.name, "votes") # V116: diem danh theo luot binh chon await send(ws, {"type": "poll_result", "poll": poll}) elif t == "inviteAsk": p = _player_of(player_id) if not p or p.busy: continue target = msg.get("target") kind = msg.get("kind") if kind not in INVITE_KINDS: continue tp = _player_of(target) if not tp: await send(ws, {"type": "inviteDeclined", "kind": kind, "target": target, "reason": "gone", "waitMs": 0}) continue if tp.busy or tp.inGame: await send(ws, {"type": "inviteDeclined", "kind": kind, "target": target, "reason": "busy", "waitMs": 0}) continue if _distance(p, tp) > GAME["inviteRange"]: await send(ws, {"type": "inviteDeclined", "kind": kind, "target": target, "reason": "far", "waitMs": 0}) continue if any(v.get("to") == target for v in invites.values()): await send(ws, {"type": "inviteDeclined", "kind": kind, "target": target, "reason": "busy", "waitMs": 0}) continue inv_id = uuid.uuid4().hex[:8] invites[inv_id] = {"id": inv_id, "kind": kind, "from": player_id, "to": target, "expires": now + INVITE_TTL_MS / 1000} await to_player(target, {"type": "invite", "id": inv_id, "kind": kind, "from": player_id, "name": p.name, "ms": INVITE_TTL_MS}) await send(ws, {"type": "inviteAsked", "target": target, "kind": kind, "ms": INVITE_TTL_MS}) asyncio.get_event_loop().call_later(INVITE_TTL_MS / 1000 + 0.5, lambda iid=inv_id: _expire_invite(iid)) elif t == "inviteCancel": for iid in list(invites): v = invites[iid] if v["from"] == player_id: invites.pop(iid, None) elif t == "inviteAnswer": inv = invites.pop(msg.get("id"), None) if not inv or inv["to"] != player_id: continue accept = bool(msg.get("accept")) a = _player_of(inv["from"]) b = _player_of(inv["to"]) if not a or not b: continue if not accept: await to_player(inv["from"], {"type": "inviteDeclined", "kind": inv["kind"], "target": inv["to"], "reason": "declined", "waitMs": 30000}) continue a.busy = True; b.busy = True kind = inv["kind"] if kind == "talk": a.inGame = "talk"; b.inGame = "talk" await send(ws, {"type": "talk_start", "peer": inv["from"]}) await to_player(inv["from"], {"type": "talk_start", "peer": inv["to"]}) elif kind == "duel": gid = uuid.uuid4().hex[:8] g = {"id": gid, "kind": "duel", "p1": inv["from"], "p2": inv["to"], "hp1": 100, "hp2": 100, "until": now + 30} games[gid] = g a.inGame = "duel"; b.inGame = "duel" await send(ws, {"type": "duel_start", "game": g}) await to_player(inv["from"], {"type": "duel_start", "game": g}) asyncio.get_event_loop().call_later(31, lambda: _end_duel(gid)) elif kind == "penalty": gid = uuid.uuid4().hex[:8] g = {"id": gid, "kind": "penalty", "p1": inv["from"], "p2": inv["to"], "s1": 0, "s2": 0, "round": 1, "turn": inv["from"], "state": "pick", "choices": {}, "until": now + 120} games[gid] = g a.inGame = "penalty"; b.inGame = "penalty" await send(ws, {"type": "penalty_start", "game": g}) await to_player(inv["from"], {"type": "penalty_start", "game": g}) asyncio.get_event_loop().call_later(121, lambda: _end_penalty(gid)) elif kind == "tug": gid = uuid.uuid4().hex[:8] g = {"id": gid, "kind": "tug", "p1": inv["from"], "p2": inv["to"], "pos": 0, "until": now + 30} games[gid] = g a.inGame = "tug"; b.inGame = "tug" await send(ws, {"type": "tug_state", "game": g}) await to_player(inv["from"], {"type": "tug_state", "game": g}) asyncio.get_event_loop().call_later(31, lambda: _end_tug(gid)) elif kind == "ball": gid = uuid.uuid4().hex[:8] g = {"id": gid, "kind": "ball", "p1": inv["from"], "p2": inv["to"], "players": [inv["from"], inv["to"]], "holder": None, "holderName": "", "until": now + 60} games[gid] = g a.inGame = "ball"; b.inGame = "ball" await send(ws, {"type": "ball_state", "game": g}) await to_player(inv["from"], {"type": "ball_state", "game": g}) asyncio.get_event_loop().call_later(61, lambda: _end_ball(gid)) elif t == "duel_action": g = next((x for x in games.values() if x["kind"] == "duel" and player_id in (x["p1"], x["p2"])), None) if not g: continue p = _player_of(player_id) if not p: continue act = msg.get("action") if act == "punch": opp = g["p2"] if player_id == g["p1"] else g["p1"] # ngẫu nhiên trúng (trừ khi đối thủ đang đỡ) blocking = msg.get("blocking") or False dmg = 7 + random.randint(0, 8) if blocking: dmg = max(1, dmg - 6) if player_id == g["p1"]: g["hp2"] = max(0, g["hp2"] - dmg) else: g["hp1"] = max(0, g["hp1"] - dmg) if g["hp1"] <= 0 or g["hp2"] <= 0: _end_duel(g["id"]) else: await broadcast(room_id, {"type": "duel_state", "game": g}) elif t == "penalty_action": g = next((x for x in games.values() if x["kind"] == "penalty" and player_id in (x["p1"], x["p2"])), None) if not g or g["state"] != "pick": continue # 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 side = msg.get("side") # 'L'|'C'|'R' if side not in ("L", "C", "R"): continue g["choices"][player_id] = side if len(g["choices"]) >= 2: shooter = g["turn"] keeper = g["p2"] if shooter == g["p1"] else g["p1"] shot = g["choices"].get(shooter) keep = g["choices"].get(keeper) scored = shot != keep if scored: if shooter == g["p1"]: g["s1"] += 1 else: g["s2"] += 1 g["round"] += 1 g["turn"] = keeper if g["round"] <= 5 else shooter # đổi vai sau 5 lượt if g["round"] > 10: _end_penalty(g["id"]) else: g["state"] = "pick" g["choices"] = {} await broadcast(room_id, {"type": "penalty_state", "game": g, "last": {"scored": scored, "round": g["round"] - 1}}) elif t == "tug_pull": g = next((x for x in games.values() if x["kind"] == "tug" and player_id in (x["p1"], x["p2"])), None) if g: power = float(msg.get("power", 1)) side = 1 if player_id == g["p1"] else -1 g["pos"] = max(-100, min(100, g.get("pos", 0) + side * power)) if abs(g["pos"]) >= 100: _end_tug(g["id"]) else: await broadcast(room_id, {"type": "tug_state", "game": g}) elif t == "ball_claim": g = next((x for x in games.values() if x["kind"] == "ball"), None) if g and not g.get("holder") and player_id in g["players"]: g["holder"] = player_id g["holderName"] = _player_of(player_id).name if _player_of(player_id) else "" await broadcast(room_id, {"type": "ball_state", "game": g}) elif t == "ball_steal": g = next((x for x in games.values() if x["kind"] == "ball"), None) if g and g.get("holder") and g["holder"] != player_id and player_id in g["players"]: g["holder"] = player_id g["holderName"] = _player_of(player_id).name if _player_of(player_id) else "" await broadcast(room_id, {"type": "ball_state", "game": g}) elif t == "ping": await send(ws, {"type": "pong", "t": msg.get("t", 0)}) elif t == "christmas_decor": # Trang tri cay thong — broadcast cho tat ca trong phong decor = { "type": "christmas_decor", "player_id": player_id, "kind": str(msg.get("kind", ""))[:20], "x": float(msg.get("x", 0)), "y": float(msg.get("y", 0)), "z": float(msg.get("z", 0)), "color": str(msg.get("color", "#e8262b"))[:20], } await broadcast(room_id, decor) # Gui lai cho nguoi gui de ho biet da nhan await send(ws, {"type": "christmas_ack", "seq": msg.get("seq", 0)}) except WebSocketDisconnect: pass finally: connections.pop(player_id, None) p = rooms.get(room_id, {}).get(player_id) name = p.name if p else "Ai đó" # giữ chỗ 30s khi rớt mạng (không rời hang chủ động) if room_id and room_id in rooms and player_id in rooms[room_id]: hold_slots[player_id] = (rooms[room_id][player_id], room_id, time.time() + 30) rooms[room_id][player_id].connected = False await broadcast(room_id, {"type": "player_hold", "player_id": player_id, "player_name": name}) # rời game đang dở for gid in list(games): g = games[gid] if player_id in (g.get("p1"), g.get("p2")) or player_id in g.get("players", []): if g["kind"] == "duel": _end_duel(gid) elif g["kind"] == "penalty": _end_penalty(gid) elif g["kind"] == "tug": _end_tug(gid) elif g["kind"] == "ball": _end_ball(gid) for iid in list(invites): v = invites[iid] if v["from"] == player_id or v["to"] == player_id: invites.pop(iid, None) def _expire_invite(iid: str): v = invites.pop(iid, None) if v: asyncio.ensure_future(to_player(v["from"], {"type": "inviteDeclined", "kind": v["kind"], "target": v["to"], "reason": "timeout", "waitMs": 0})) # định kỳ: dọn hold hết hạn + game quá hạn + phát poll mới async def _janitor(): while True: await asyncio.sleep(5) now = time.time() for pid in list(hold_slots): player, rid, exp = hold_slots[pid] if now > exp: hold_slots.pop(pid, None) if rid in rooms and pid in rooms[rid]: name = rooms[rid][pid].name del rooms[rid][pid] player_rooms.pop(pid, None) await broadcast(rid, {"type": "player_left", "player_id": pid, "player_name": name}) add_feed(rid, f"{name} đã rời hang 🚪") await broadcast(rid, {"type": "feed", "text": f"{name} đã rời hang 🚪"}) # trống chỗ → người đầu hàng chờ được gọi (client poll /room/status rồi /join) wl = waitlists.get(rid, []) if wl: wl.pop(0) for gid in list(games): g = games[gid] if now > g.get("until", now): if g["kind"] == "duel": _end_duel(gid) elif g["kind"] == "penalty": _end_penalty(gid) elif g["kind"] == "tug": _end_tug(gid) elif g["kind"] == "ball": _end_ball(gid) # poll định kỳ: nếu chưa có poll hoặc poll quá hạn thì phát cái mới cur = polls.get("lobby") if not cur or now > cur.get("expires", 0): poll = _make_poll() polls["lobby"] = poll add_feed("lobby", f"📊 Bình chọn mới: {poll['question']}") await broadcast("lobby", {"type": "poll", "poll": poll}) await broadcast("lobby", {"type": "feed", "text": f"📊 Bình chọn mới: {poll['question']}"}) @app.on_event("startup") async def _startup(): asyncio.get_event_loop().create_task(_janitor()) # V35: khôi phục playlist từ /data → màn hình lớn có nội dung NGAY sau restart, # rồi quét nền mỗi 20 phút để tự cập nhật video MU mới nhất. _board_load() asyncio.get_event_loop().create_task(_board_loop()) # ============ Static ============ app.mount("/static", StaticFiles(directory="frontend"), name="static") @app.get("/") async def serve_index(): # V38: no-store — cấm trình duyệt cache index.html (trước đây heuristic # cache giữ bản HTML cũ nhiều giờ -> server v37 mà user vẫn chạy bundle v34 # "màn hình vẫn y như cũ" dù đã fix). return FileResponse("frontend/index.html", headers={"Cache-Control": "no-store"}) @app.get("/env.js") async def env_js(): return FileResponse("frontend/env.js", media_type="application/javascript") _PWA_ROOT = ["manifest.json", "sw.js", "icon-192.png", "icon-512.png", "favicon.ico", "favicon.svg", "apple-touch-icon.png", "og-image.png"] @app.get("/{path:path}") async def serve_static(path: str): import os # không nuốt websocket / API routes if path.startswith("ws/") or path.startswith("ext/") or path.startswith("push/") or path.startswith("api/"): raise HTTPException(404, "Not found") if path in _PWA_ROOT: pf = os.path.join("frontend", "pwa", path) if os.path.exists(pf): return FileResponse(pf) file_path = os.path.join("frontend", path) if os.path.exists(file_path) and os.path.isfile(file_path): return FileResponse(file_path) # V38: fallback SPA cũng no-store (tránh cache HTML ở route ảo) return FileResponse("frontend/index.html", headers={"Cache-Control": "no-store"}) if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=7860)