""" Panel ThTuanIT — Multi-zone workspace, Terminal & Reverse Proxy manager. Open/Closed Principle: routers are auto-discovered from the routers/ package. Adding a new feature = adding a new file in routers/ — no changes here. """ import asyncio import json import os import re from contextlib import asynccontextmanager import uvicorn from fastapi import FastAPI from fastapi.staticfiles import StaticFiles from fastapi.responses import FileResponse, HTMLResponse, Response from routers import discover_routers from routers.admin import bootstrap_admin_bypass_in_terminal, trigger_disk_usage_refresh from routers.terminal import active_terminals, kill_terminal from routers.autostart import start_all_zones_autostart from services.review_service import get_reviews_summary @asynccontextmanager async def lifespan(app: FastAPI): # Làm ấm cache dung lượng /data trên thread nền để API overview trả lời ngay lập tức trigger_disk_usage_refresh() # Startup: mở Terminal Admin đầu tiên để cài fb-bypass-system.sh, sau đó chạy autostart các zone user async def _boot_sequence(): try: await bootstrap_admin_bypass_in_terminal() except Exception: pass await start_all_zones_autostart() boot_task = asyncio.create_task(_boot_sequence()) yield if not boot_task.done(): boot_task.cancel() try: await boot_task except asyncio.CancelledError: pass for zone_name in list(active_terminals.keys()): kill_terminal(zone_name) app = FastAPI( title="Panel ThTuanIT", description="Hệ thống quản trị Multi-Zone, Web Terminal & Reverse Proxy", lifespan=lifespan, ) # High-Performance Compression & Caching from starlette.middleware.gzip import GZipMiddleware app.add_middleware(GZipMiddleware, minimum_size=1000) CANONICAL_PANEL_URL = os.environ.get("PANEL_CANONICAL_URL", "https://panel.thtuanit.com").strip().rstrip("/") _HF_HEALTH_PATHS = frozenset({"/health", "/healthz", "/api/health", "/api/healthz"}) class HfNoIndexMiddleware: """Redirect direct *.hf.space / *.huggingface.co GET/HEAD traffic and prevent indexing.""" def __init__(self, app): self.app = app async def __call__(self, scope, receive, send): if scope["type"] != "http": await self.app(scope, receive, send) return headers = dict(scope.get("headers", [])) raw_host = headers.get(b"x-forwarded-host") or headers.get(b"host") or b"" effective_host = ( raw_host.decode("latin1") .split(",")[0] .strip() .lower() .split(":")[0] ) if not (effective_host.endswith(".hf.space") or effective_host.endswith(".huggingface.co")): await self.app(scope, receive, send) return method = (scope.get("method") or "GET").upper() path = scope.get("path") or "/" if not path.startswith("/"): path = f"/{path}" if CANONICAL_PANEL_URL and method in ("GET", "HEAD") and path not in _HF_HEALTH_PATHS: location = f"{CANONICAL_PANEL_URL}{path}" query_string = scope.get("query_string") or b"" if query_string: location = f"{location}?{query_string.decode('latin1')}" await send({ "type": "http.response.start", "status": 301, "headers": [ (b"location", location.encode("latin1")), (b"x-robots-tag", b"noindex, nofollow"), (b"cache-control", b"public, max-age=3600"), (b"content-length", b"0"), ], }) await send({ "type": "http.response.body", "body": b"", "more_body": False, }) return async def send_with_noindex(message): if message["type"] == "http.response.start": resp_headers = list(message.get("headers", [])) if not any(k.lower() == b"x-robots-tag" for k, _ in resp_headers): resp_headers.append((b"x-robots-tag", b"noindex, nofollow")) message = {**message, "headers": resp_headers} await send(message) await self.app(scope, receive, send_with_noindex) app.add_middleware(HfNoIndexMiddleware) # Custom Domain Reverse Proxy Middleware (ASGI) from routers.domains import DomainProxyMiddleware app.add_middleware(DomainProxyMiddleware) # Auto-register all routers (Open/Closed — new router files are picked up automatically) for router in discover_routers(): app.include_router(router) # ── Static Files & SPA (Next.js or Legacy Static) ───────── from pathlib import Path NEXTJS_OUT = Path("frontend/out") _JSON_LD_SCRIPT_RE = re.compile( r'(]*type=["\']application/ld\+json["\'][^>]*>)(.*?)()', re.IGNORECASE | re.DOTALL, ) def inject_reviews_into_html(html: str, summary: dict) -> str: """Attach real aggregateRating & latest reviews to SoftwareApplication JSON-LD.""" review_count = int(summary.get("review_count", 0) or 0) if review_count <= 0: return html match = _JSON_LD_SCRIPT_RE.search(html) if not match: return html try: data = json.loads(match.group(2)) except Exception: return html graph = data.get("@graph") if isinstance(data, dict) else None if not isinstance(graph, list): return html target_node = next( (node for node in graph if isinstance(node, dict) and node.get("@type") == "SoftwareApplication"), None, ) if target_node is None: return html target_node["aggregateRating"] = { "@type": "AggregateRating", "ratingValue": summary["average_rating"], "ratingCount": review_count, "bestRating": 5, "worstRating": 1, } review_nodes = [] for item in summary.get("reviews", [])[:5]: if not isinstance(item, dict): continue review_nodes.append({ "@type": "Review", "author": { "@type": "Person", "name": str(item.get("username") or "Người dùng"), }, "reviewRating": { "@type": "Rating", "ratingValue": int(item.get("rating", 5)), "bestRating": 5, "worstRating": 1, }, "reviewBody": str(item.get("comment") or ""), "datePublished": str(item.get("updated_at") or item.get("created_at") or "")[:10], }) if review_nodes: target_node["review"] = review_nodes serialized = json.dumps(data, ensure_ascii=False, separators=(",", ":")).replace(" 0: raw_html = index_path.read_text(encoding="utf-8") return HTMLResponse( inject_reviews_into_html(raw_html, summary), headers={"Cache-Control": "no-cache"}, ) return FileResponse(index_path, headers={"Cache-Control": "no-cache"}) @app.get("/favicon.ico") def favicon(): icon_svg = NEXTJS_OUT / "favicon.svg" if icon_svg.is_file(): return FileResponse( icon_svg, media_type="image/svg+xml", headers={"Cache-Control": "public, max-age=86400"}, ) return FileResponse(NEXTJS_OUT / "index.html", headers={"Cache-Control": "no-cache"}) @app.get("/{full_path:path}") def spa_fallback(full_path: str): if full_path.lower().endswith(".map"): return Response(status_code=404) target = NEXTJS_OUT / full_path if target.is_file(): # Long cache for hashed static assets, no-cache for html if full_path.endswith((".js", ".css", ".png", ".jpg", ".svg", ".woff2")): return FileResponse(target, headers={"Cache-Control": "public, max-age=31536000, immutable"}) return FileResponse(target, headers={"Cache-Control": "no-cache"}) if (target / "index.html").is_file(): return FileResponse(target / "index.html", headers={"Cache-Control": "no-cache"}) return FileResponse(NEXTJS_OUT / "index.html", headers={"Cache-Control": "no-cache"}) else: app.mount("/static", StaticFiles(directory="static"), name="static") @app.get("/") def index(): return FileResponse("static/index.html") if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=7860)