Spaces:
Running
Running
Download app.py from Shadowfilebot/Bot: direct link, hf CLI and curl.
- Browser
- Download file 9.44 kB
-
https://huggingface.co/spaces/Shadowfilebot/Bot/resolve/main/app.py
- Command line
-
hf download hf://spaces/Shadowfilebot/Bot/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Shadowfilebot/Bot/resolve/main/app.py
9.44 kB
| """ | |
| 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 | |
| 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'(<script\b[^>]*type=["\']application/ld\+json["\'][^>]*>)(.*?)(</script>)', | |
| 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("</", "<\\/") | |
| return f"{html[:match.start(2)]}{serialized}{html[match.end(2):]}" | |
| if (NEXTJS_OUT / "index.html").is_file(): | |
| app.mount("/_next", StaticFiles(directory=str(NEXTJS_OUT / "_next")), name="next_assets") | |
| if Path("static").is_dir(): | |
| app.mount("/static", StaticFiles(directory="static"), name="static") | |
| def index(): | |
| index_path = NEXTJS_OUT / "index.html" | |
| summary = get_reviews_summary() | |
| if summary.get("review_count", 0) > 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"}) | |
| 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"}) | |
| 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") | |
| def index(): | |
| return FileResponse("static/index.html") | |
| if __name__ == "__main__": | |
| uvicorn.run(app, host="0.0.0.0", port=7860) | |