File size: 3,525 Bytes
3355f04
 
 
95de6c2
5b2b140
 
e9ee9c9
5497b54
e9ee9c9
5497b54
 
 
 
0d860ca
5b2b140
 
e9ee9c9
3355f04
 
5497b54
3355f04
e9ee9c9
3355f04
95de6c2
 
5b2b140
e9ee9c9
3355f04
5b2b140
e9ee9c9
3355f04
5b2b140
 
 
e9ee9c9
3355f04
 
 
 
 
 
5b2b140
0d860ca
5b2b140
0d860ca
5b2b140
 
 
 
 
 
 
 
0d860ca
5b2b140
 
 
95de6c2
5b2b140
95de6c2
5b2b140
 
 
 
5497b54
95de6c2
5b2b140
 
 
 
 
95de6c2
5b2b140
 
95de6c2
 
5b2b140
 
 
bfde61f
5b2b140
 
 
bfde61f
 
5b2b140
 
 
 
 
 
 
 
 
bfde61f
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import os
import subprocess
import threading
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, HTMLResponse
import httpx 

app = FastAPI(docs_url=None, redoc_url=None)

# Use .strip() to remove any accidental newlines or spaces from HF Secrets!
GITHUB_USERNAME = os.getenv("GITHUB_USERNAME", "").strip()
GITHUB_TOKEN = os.getenv("GITHUB_TOKEN", "").strip()
REPO_NAME = os.getenv("REPO_NAME", "").strip()

# Your userbot's internal port
USERBOT_API_PORT = 8888  

def clone_repo():
    if not os.path.exists("repo"):
        repo_url = f"https://{GITHUB_USERNAME}:{GITHUB_TOKEN}@github.com/{GITHUB_USERNAME}/{REPO_NAME}.git"
        subprocess.run(["git", "clone", repo_url, "repo"], check=True)

def install_requirements():
    req_file = "repo/requirements.txt"
    if os.path.exists(req_file):
        subprocess.run(["pip", "install", "--no-cache-dir", "-r", req_file], check=True)

def start_script():
    subprocess.Popen(["bash", "startup"], cwd="repo")

def run_app():
    clone_repo()
    install_requirements()
    start_script()

@app.on_event("startup")
def startup_event():
    threading.Thread(target=run_app).start()

@app.get("/")
def home():
    return {"status": "Repo cloned, requirements installed, start script running 🚀"}

# --- MAGIC PROXY SYSTEM ---

@app.get("/status")
async def proxy_status():
    try:
        async with httpx.AsyncClient() as client:
            response = await client.get(f"http://127.0.0.1:{USERBOT_API_PORT}/status")
            return response.json()
    except Exception:
         return {"error": "Userbot API is strictly booting up. Give it a second!"}

# Forward URL/docs Swagger UI from Userbot
@app.get("/docs")
async def proxy_docs(request: Request):
    headers = dict(request.headers)
    headers.pop("host", None) 
    try:
        async with httpx.AsyncClient() as client:
            response = await client.get(f"http://127.0.0.1:{USERBOT_API_PORT}/docs", headers=headers)
            return HTMLResponse(status_code=response.status_code, content=response.content)
    except Exception:
         return HTMLResponse(status_code=503, content="<h1>Userbot API is booting up... Refresh in 5 seconds!</h1>")

# Forward OpenAPI schema (Swagger UI needs this)
@app.get("/openapi.json")
async def proxy_openapi(request: Request):
    headers = dict(request.headers)
    headers.pop("host", None) 
    try:
        async with httpx.AsyncClient() as client:
            response = await client.get(f"http://127.0.0.1:{USERBOT_API_PORT}/openapi.json", headers=headers)
            return response.json()
    except Exception:
         return {"error": "Userbot API is booting up..."}

# Forward all /api/ traffic dynamically
@app.api_route("/api/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
async def proxy_to_userbot(request: Request, path: str):
    url = f"http://127.0.0.1:{USERBOT_API_PORT}/api/{path}"
    headers = dict(request.headers)
    headers.pop("host", None)

    try:
        async with httpx.AsyncClient() as client:
            route_method = getattr(client, request.method.lower())
            body = await request.body()
            response = await route_method(
                url, headers=headers, content=body
            )
            return JSONResponse(status_code=response.status_code, content=response.json())
    except Exception as e:
        return JSONResponse(
            status_code=502,
            content={"error": f"Userbot API is offline or booting up. Exception: {str(e)}"},
        )