dragonxd1 commited on
Commit
5b2b140
·
verified ·
1 Parent(s): 0d860ca

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -85
app.py CHANGED
@@ -2,19 +2,17 @@ import os
2
  import subprocess
3
  import threading
4
  from fastapi import FastAPI, Request
5
- from fastapi.responses import JSONResponse
6
- import httpx
7
 
8
- app = FastAPI()
9
 
10
- # Clean env variables (removes newline issues)
11
- GITHUB_USERNAME = os.getenv("GITHUB_USERNAME", "").strip()
12
- GITHUB_TOKEN = os.getenv("GITHUB_TOKEN", "").strip()
13
- REPO_NAME = os.getenv("REPO_NAME", "").strip()
14
-
15
- # Userbot internal API port
16
- USERBOT_API_PORT = 8888
17
 
 
 
18
 
19
  def clone_repo():
20
  if not os.path.exists("repo"):
@@ -23,103 +21,79 @@ def clone_repo():
23
  else:
24
  repo_url = f"https://github.com/{GITHUB_USERNAME}/{REPO_NAME}.git"
25
 
26
- print(f"Cloning repository: {GITHUB_USERNAME}/{REPO_NAME}")
27
  subprocess.run(["git", "clone", repo_url, "repo"], check=True)
28
 
29
-
30
  def install_requirements():
31
  req_file = "repo/requirements.txt"
32
  if os.path.exists(req_file):
33
- print("Installing requirements...")
34
- subprocess.run(
35
- ["pip", "install", "--no-cache-dir", "-r", req_file],
36
- check=True
37
- )
38
-
39
 
40
  def start_script():
41
- startup_path = "repo/startup"
42
-
43
- if os.path.exists(startup_path):
44
- print("Running startup script...")
45
- subprocess.Popen(["bash", "startup"], cwd="repo")
46
- else:
47
- print("startup script not found!")
48
-
49
 
50
  def run_app():
51
- try:
52
- clone_repo()
53
- install_requirements()
54
- start_script()
55
- except Exception as e:
56
- print(f"Startup error: {e}")
57
-
58
 
59
  @app.on_event("startup")
60
  def startup_event():
61
  threading.Thread(target=run_app).start()
62
 
63
-
64
  @app.get("/")
65
  def home():
66
- return {
67
- "status": "repo cloned, requirements installed, startup script running 🚀"
68
- }
69
-
70
 
71
- # -------------------------
72
- # Proxy /api → port 8888
73
- # -------------------------
74
 
75
- @app.api_route("/api/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH"])
76
- async def proxy_to_userbot(request: Request, path: str):
77
-
78
- url = f"http://127.0.0.1:{USERBOT_API_PORT}/api/{path}"
 
 
 
 
79
 
 
 
 
80
  headers = dict(request.headers)
81
- headers.pop("host", None)
82
-
83
- body = await request.body()
84
-
85
  try:
86
- async with httpx.AsyncClient(timeout=120) as client:
87
-
88
- response = await client.request(
89
- request.method,
90
- url,
91
- headers=headers,
92
- content=body
93
- )
94
-
95
- try:
96
- return JSONResponse(
97
- status_code=response.status_code,
98
- content=response.json()
99
- )
100
- except Exception:
101
- return JSONResponse(
102
- status_code=response.status_code,
103
- content={"response": response.text}
104
- )
105
-
106
- except Exception as e:
107
- return JSONResponse(
108
- status_code=502,
109
- content={
110
- "error": "Userbot API is offline or still booting",
111
- "exception": str(e)
112
- }
113
- )
114
-
115
 
116
- @app.get("/status")
117
- async def proxy_status():
 
 
 
118
  try:
119
- async with httpx.AsyncClient(timeout=20) as client:
120
- response = await client.get(
121
- f"http://127.0.0.1:{USERBOT_API_PORT}/status"
122
- )
123
  return response.json()
124
  except Exception:
125
- return {"status": "Userbot API offline"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import subprocess
3
  import threading
4
  from fastapi import FastAPI, Request
5
+ from fastapi.responses import JSONResponse, HTMLResponse
6
+ import httpx
7
 
8
+ app = FastAPI(docs_url=None, redoc_url=None) # Disable HF Native Docs so Userbot Docs take over
9
 
10
+ GITHUB_USERNAME = os.getenv("GITHUB_USERNAME")
11
+ GITHUB_TOKEN = os.getenv("GITHUB_TOKEN")
12
+ REPO_NAME = os.getenv("REPO_NAME")
 
 
 
 
13
 
14
+ # Your userbot's internal port
15
+ USERBOT_API_PORT = 8888
16
 
17
  def clone_repo():
18
  if not os.path.exists("repo"):
 
21
  else:
22
  repo_url = f"https://github.com/{GITHUB_USERNAME}/{REPO_NAME}.git"
23
 
24
+ print(f"Cloning repo: {GITHUB_USERNAME}/{REPO_NAME}")
25
  subprocess.run(["git", "clone", repo_url, "repo"], check=True)
26
 
 
27
  def install_requirements():
28
  req_file = "repo/requirements.txt"
29
  if os.path.exists(req_file):
30
+ subprocess.run(["pip", "install", "--no-cache-dir", "-r", req_file], check=True)
 
 
 
 
 
31
 
32
  def start_script():
33
+ subprocess.Popen(["bash", "startup"], cwd="repo")
 
 
 
 
 
 
 
34
 
35
  def run_app():
36
+ clone_repo()
37
+ install_requirements()
38
+ start_script()
 
 
 
 
39
 
40
  @app.on_event("startup")
41
  def startup_event():
42
  threading.Thread(target=run_app).start()
43
 
 
44
  @app.get("/")
45
  def home():
46
+ return {"status": "Repo cloned, requirements installed, start script running 🚀"}
 
 
 
47
 
48
+ # --- MAGIC PROXY SYSTEM ---
 
 
49
 
50
+ @app.get("/status")
51
+ async def proxy_status():
52
+ try:
53
+ async with httpx.AsyncClient() as client:
54
+ response = await client.get(f"http://127.0.0.1:{USERBOT_API_PORT}/status")
55
+ return response.json()
56
+ except Exception:
57
+ return {"error": "Userbot API is strictly booting up. Give it a second!"}
58
 
59
+ # Forward URL/docs Swagger UI from Userbot
60
+ @app.get("/docs")
61
+ async def proxy_docs(request: Request):
62
  headers = dict(request.headers)
63
+ headers.pop("host", None)
 
 
 
64
  try:
65
+ async with httpx.AsyncClient() as client:
66
+ response = await client.get(f"http://127.0.0.1:{USERBOT_API_PORT}/docs", headers=headers)
67
+ return HTMLResponse(status_code=response.status_code, content=response.content)
68
+ except Exception:
69
+ return {"error": "Userbot API is strictly booting up. Give it a second!"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
+ # Forward OpenAPI schema (Swagger UI needs this)
72
+ @app.get("/openapi.json")
73
+ async def proxy_openapi(request: Request):
74
+ headers = dict(request.headers)
75
+ headers.pop("host", None)
76
  try:
77
+ async with httpx.AsyncClient() as client:
78
+ response = await client.get(f"http://127.0.0.1:{USERBOT_API_PORT}/openapi.json", headers=headers)
 
 
79
  return response.json()
80
  except Exception:
81
+ return {"error": "Userbot API is booting up..."}
82
+
83
+ # Forward all /api/ traffic dynamically
84
+ @app.route("/api/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
85
+ async def proxy_to_userbot(request: Request, path: str):
86
+ url = f"http://127.0.0.1:{USERBOT_API_PORT}/api/{path}"
87
+ headers = dict(request.headers)
88
+ headers.pop("host", None)
89
+
90
+ try:
91
+ async with httpx.AsyncClient() as client:
92
+ route_method = getattr(client, request.method.lower())
93
+ body = await request.body()
94
+ response = await route_method(
95
+ url, headers=headers, content=body
96
+ )
97
+ return JSONResponse(status_code=response.status_code, content=response.json())
98
+ except Exception as e:
99
+ return JSONResponse(status_code=502, content={"error": f"Userbot API is offline or booting up. Exception: {str(e)}"})