Spaces:
Runtime error

LUISGDUV commited on
Commit
aa31883
·
verified ·
1 Parent(s): d4dcbc6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +19 -311
app.py CHANGED
@@ -1,318 +1,26 @@
1
- import os, json, base64, hashlib, secrets, re
2
- from datetime import datetime, timedelta
3
- from typing import List
4
 
5
- import gradio as gr
6
- from fastapi import UploadFile, File, Form, HTTPException, Header, Depends
7
- from pydantic import BaseModel
8
- import requests as rq
9
- import spaces
10
- from spaces import GPU
11
-
12
- # Stub exigido pelo runtime ZeroGPU
13
- @spaces.GPU(duration=1)
14
- def _zerogpu_probe():
15
- """Apenas para satisfazer a verificação de inicialização do ZeroGPU."""
16
- return "ready"
17
-
18
  # ================= CONFIG =================
19
- GITHUB_TOKEN = os.getenv("GITHUB_TOKEN", "")
20
- GITHUB_USER = os.getenv("GITHUB_USER", "LUISGDUV")
21
- GITHUB_REPO = os.getenv("GITHUB_REPO", "Protix-host")
22
- DB_FOLDER = os.getenv("DB_FOLDER", "ProtixHost Database")
23
- BASE_DOMAIN = os.getenv("BASE_DOMAIN", "ProtixHost.sytes.net")
24
- SECRET_KEY = os.getenv("SECRET_KEY", "troque-esta-chave")
25
- LIMITE_PADRAO = int(os.getenv("LIMITE_PADRAO", "10"))
26
-
27
- GH_API = "https://api.github.com"
28
- GH_HEADERS = {
29
- "Authorization": f"token {GITHUB_TOKEN}",
30
- "Accept": "application/vnd.github+json",
31
- }
32
-
33
- # ================= HELPERS =================
34
- def hash_pass(pwd):
35
- salt = secrets.token_hex(16)
36
- return f"{salt}${hashlib.sha256((salt + pwd).encode()).hexdigest()}"
37
-
38
- def check_pass(pwd, stored):
39
- try:
40
- salt, h = stored.split("$")
41
- return hashlib.sha256((salt + pwd).encode()).hexdigest() == h
42
- except Exception:
43
- return False
44
-
45
- def create_token(email):
46
- payload = {"email": email, "exp": (datetime.utcnow() + timedelta(days=30)).isoformat()}
47
- data = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode()
48
- sig = hashlib.sha256((data + SECRET_KEY).encode()).hexdigest()[:32]
49
- return f"{data}.{sig}"
50
-
51
- def verify_token(token):
52
- try:
53
- data, sig = token.split(".")
54
- if sig != hashlib.sha256((data + SECRET_KEY).encode()).hexdigest()[:32]:
55
- return None
56
- p = json.loads(base64.urlsafe_b64decode(data))
57
- if datetime.fromisoformat(p["exp"]) < datetime.utcnow():
58
- return None
59
- return p["email"]
60
- except Exception:
61
- return None
62
-
63
- def auth_user(authorization: str = Header(None)):
64
- if not authorization or not authorization.startswith("Bearer "):
65
- raise HTTPException(401, "Não autenticado")
66
- email = verify_token(authorization[7:])
67
- if not email:
68
- raise HTTPException(401, "Token inválido ou expirado")
69
- return email
70
-
71
- def gh_get(path):
72
- return rq.get(
73
- f"{GH_API}/repos/{GITHUB_USER}/{GITHUB_REPO}/contents/{path}",
74
- headers=GH_HEADERS, timeout=30
75
- )
76
-
77
- def gh_read_json(path):
78
- r = gh_get(path)
79
- if r.status_code != 200:
80
- return None
81
- return json.loads(base64.b64decode(r.json()["content"]).decode())
82
-
83
- def gh_put(path, content, message="update"):
84
- r = gh_get(path)
85
- sha = r.json().get("sha") if r.status_code == 200 else None
86
- payload = {"message": message, "content": base64.b64encode(content).decode()}
87
- if sha:
88
- payload["sha"] = sha
89
- return rq.put(
90
- f"{GH_API}/repos/{GITHUB_USER}/{GITHUB_REPO}/contents/{path}",
91
- headers=GH_HEADERS, json=payload, timeout=60
92
- )
93
-
94
- def gh_delete(path, message="delete"):
95
- r = gh_get(path)
96
- if r.status_code != 200:
97
- return None
98
- return rq.delete(
99
- f"{GH_API}/repos/{GITHUB_USER}/{GITHUB_REPO}/contents/{path}",
100
- headers=GH_HEADERS,
101
- json={"message": message, "sha": r.json()["sha"]},
102
- timeout=30
103
- )
104
-
105
- def user_path(email):
106
- safe = email.lower().replace("@", "_at_").replace("/", "_")
107
- return f"{DB_FOLDER}/usuarios/{safe}"
108
-
109
- def get_user(email):
110
- return gh_read_json(f"{user_path(email)}/user.json")
111
-
112
- def save_user(email, data, msg="update"):
113
- return gh_put(
114
- f"{user_path(email)}/user.json",
115
- json.dumps(data, indent=2, ensure_ascii=False).encode(),
116
- msg
117
- )
118
-
119
- # ================= MODELS =================
120
- class RegisterBody(BaseModel):
121
- nome: str
122
- email: str
123
- senha: str
124
-
125
- class LoginBody(BaseModel):
126
- email: str
127
- senha: str
128
-
129
- # ================= GRADIO UI =================
130
- def _info():
131
- return (
132
- "ProtixHost API rodando ✅\n\n"
133
- "Endpoints:\n"
134
- "POST /api/register\n"
135
- "POST /api/login\n"
136
- "GET /api/me\n"
137
- "GET /api/sites\n"
138
- "POST /api/deploy\n"
139
- "DELETE /api/sites/{nome}\n"
140
- "GET /api/health\n\n"
141
- "Docs: /docs"
142
- )
143
-
144
- demo = gr.Interface(
145
- fn=_info,
146
- inputs=[],
147
- outputs="text",
148
- title="ProtixHost API",
149
- description="Backend rodando. Endpoints em /api/*",
150
- )
151
-
152
- # ⚠️ ESSENCIAL: pega o FastAPI interno do Gradio ANTES de lançar
153
- app = demo.app
154
-
155
- # ================= ROTAS (prefixo /api) =================
156
- @app.get("/api/health")
157
- def health():
158
- return {
159
- "status": "ok",
160
- "service": "ProtixHost API",
161
- "github": f"{GITHUB_USER}/{GITHUB_REPO}",
162
- "dominio": BASE_DOMAIN,
163
- }
164
-
165
- @app.post("/api/register")
166
- def register(body: RegisterBody):
167
- email = body.email.lower().strip()
168
- if not email or not body.senha or not body.nome:
169
- raise HTTPException(400, "Dados incompletos")
170
- if "@" not in email:
171
- raise HTTPException(400, "E-mail inválido")
172
- if get_user(email):
173
- raise HTTPException(400, "E-mail já cadastrado")
174
-
175
- user = {
176
- "nome": body.nome,
177
- "email": email,
178
- "senha": hash_pass(body.senha),
179
- "limite_sites": LIMITE_PADRAO,
180
- "sites": [],
181
- "criado_em": datetime.utcnow().isoformat(),
182
- }
183
- r = save_user(email, user, f"Criar usuário {email}")
184
- if r.status_code not in (200, 201):
185
- raise HTTPException(500, f"Erro GitHub: {r.text[:200]}")
186
-
187
- return {
188
- "token": create_token(email),
189
- "user": {
190
- "nome": user["nome"],
191
- "email": email,
192
- "limite_sites": LIMITE_PADRAO,
193
- "total_sites": 0,
194
- },
195
- }
196
-
197
- @app.post("/api/login")
198
- def login(body: LoginBody):
199
- email = body.email.lower().strip()
200
- user = get_user(email)
201
- if not user or not check_pass(body.senha, user["senha"]):
202
- raise HTTPException(401, "E-mail ou senha incorretos")
203
- return {
204
- "token": create_token(email),
205
- "user": {
206
- "nome": user["nome"],
207
- "email": email,
208
- "limite_sites": user.get("limite_sites", LIMITE_PADRAO),
209
- "total_sites": len(user.get("sites", [])),
210
- },
211
- }
212
-
213
- @app.get("/api/me")
214
- def me(email: str = Depends(auth_user)):
215
- user = get_user(email)
216
- if not user:
217
- raise HTTPException(404, "Usuário não encontrado")
218
- return {
219
- "nome": user["nome"],
220
- "email": email,
221
- "limite_sites": user.get("limite_sites", LIMITE_PADRAO),
222
- "total_sites": len(user.get("sites", [])),
223
- "sites": user.get("sites", []),
224
- }
225
-
226
- @app.get("/api/sites")
227
- def list_sites(email: str = Depends(auth_user)):
228
- user = get_user(email)
229
- if not user:
230
- raise HTTPException(404, "Usuário não encontrado")
231
- return {
232
- "sites": user.get("sites", []),
233
- "limite": user.get("limite_sites", LIMITE_PADRAO),
234
- "total": len(user.get("sites", [])),
235
- }
236
-
237
- @app.post("/api/deploy")
238
- async def deploy(
239
- tipo: str = Form(...),
240
- nome_site: str = Form(...),
241
- arquivos: List[UploadFile] = File(...),
242
- email: str = Depends(auth_user),
243
- ):
244
- tipo = tipo.lower().strip()
245
- if tipo not in ("frontend", "backend", "both"):
246
- raise HTTPException(400, "Tipo deve ser: frontend, backend ou both")
247
-
248
- nome_site = nome_site.strip().lower()
249
- if not re.match(r"^[a-z0-9](?:[a-z0-9-]{1,28}[a-z0-9])?$", nome_site):
250
- raise HTTPException(400, "Nome inválido (3-30 chars: a-z, 0-9, hífen)")
251
-
252
- user = get_user(email)
253
- if not user:
254
- raise HTTPException(404, "Usuário não encontrado")
255
-
256
- sites = user.get("sites", [])
257
- limite = user.get("limite_sites", LIMITE_PADRAO)
258
-
259
- if len(sites) >= limite:
260
- raise HTTPException(400, f"Limite de {limite} sites atingido")
261
- if any(s["nome"] == nome_site for s in sites):
262
- raise HTTPException(400, "Você já tem um site com esse nome")
263
-
264
- sub = {"frontend": "frontend", "backend": "backend", "both": "site"}[tipo]
265
- saved = []
266
- for f in arquivos:
267
- raw = await f.read()
268
- safe = os.path.basename(f.filename or "")
269
- if not safe:
270
- continue
271
- path = f"{user_path(email)}/sites/{nome_site}/{sub}/{safe}"
272
- r = gh_put(path, raw, f"Upload {safe} -> {nome_site}")
273
- if r.status_code in (200, 201):
274
- saved.append(safe)
275
-
276
- if not saved:
277
- raise HTTPException(500, "Nenhum arquivo foi salvo")
278
-
279
- novo = {
280
- "nome": nome_site,
281
- "tipo": tipo,
282
- "url": f"{BASE_DOMAIN}/{nome_site}",
283
- "arquivos": saved,
284
- "criado_em": datetime.utcnow().isoformat(),
285
- }
286
- sites.append(novo)
287
- user["sites"] = sites
288
- save_user(email, user, f"Novo site {nome_site}")
289
-
290
- return {
291
- "ok": True,
292
- "site": novo,
293
- "url": f"https://{BASE_DOMAIN}/{nome_site}",
294
- "espera_segundos": 40,
295
- }
296
 
297
- @app.delete("/api/sites/{nome_site}")
298
- def delete_site(nome_site: str, email: str = Depends(auth_user)):
299
- user = get_user(email)
300
- if not user:
301
- raise HTTPException(404, "Usuário não encontrado")
302
 
303
- sites = user.get("sites", [])
304
- site = next((s for s in sites if s["nome"] == nome_site), None)
305
- if not site:
306
- raise HTTPException(404, "Site não encontrado")
307
 
308
- sub = {"frontend": "frontend", "backend": "backend", "both": "site"}[site["tipo"]]
309
- for arq in site.get("arquivos", []):
310
- gh_delete(f"{user_path(email)}/sites/{nome_site}/{sub}/{arq}")
 
 
311
 
312
- user["sites"] = [s for s in sites if s["nome"] != nome_site]
313
- save_user(email, user, f"Remover site {nome_site}")
314
- return {"ok": True}
315
 
316
- # ================= ⚠️ ESSENCIAL: LAUNCH =================
317
- # Sem isso o container morre com Exit code 0.
318
- demo.launch(ssr_mode=False)
 
 
1
+ import os
2
+ import sys
3
+ import importlib.util
4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  # ================= CONFIG =================
6
+ CODE_FILE = os.getenv("CODE", "server.py") # nome do arquivo que tem o código real
7
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
8
+ CODE_PATH = os.path.join(BASE_DIR, CODE_FILE)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
 
 
 
 
 
10
 
11
+ def _load_module(path, name="real_app"):
12
+ """Carrega um .py dinamicamente e devolve o módulo."""
13
+ if not os.path.isfile(path):
14
+ raise FileNotFoundError(f"Não encontrei o arquivo: {path}")
15
 
16
+ spec = importlib.util.spec_from_file_location(name, path)
17
+ module = importlib.util.module_from_spec(spec)
18
+ sys.modules[name] = module
19
+ spec.loader.exec_module(module)
20
+ return module
21
 
 
 
 
22
 
23
+ if __name__ == "__main__":
24
+ print(f"[bootstrapper] Carregando: {CODE_PATH}")
25
+ _load_module(CODE_PATH)
26
+ print("[bootstrapper] OK — código real iniciado.")