from fastapi import FastAPI, UploadFile, File, Request from fastapi.responses import HTMLResponse, JSONResponse from fastapi.staticfiles import StaticFiles import os, shutil, json, subprocess app = FastAPI() # Folder upload (pakai /tmp biar aman & gak permission denied) UPLOAD_DIR = "/tmp/uploads" os.makedirs(UPLOAD_DIR, exist_ok=True) # Serve file index.html @app.get("/", response_class=HTMLResponse) async def root(): with open("index.html", encoding="utf-8") as f: return f.read() # Upload file @app.post("/upload") async def upload(file: UploadFile = File(...)): dest = os.path.join(UPLOAD_DIR, file.filename) with open(dest, "wb") as f: shutil.copyfileobj(file.file, f) return {"filename": file.filename} # List file yang sudah diupload @app.get("/files") async def files(): return os.listdir(UPLOAD_DIR) # Jalankan file Python (buat panel console) @app.post("/run") async def run_code(request: Request): data = await request.json() filename = data.get("filename") filepath = os.path.join(UPLOAD_DIR, filename) if not os.path.exists(filepath): return {"output": f"File '{filename}' not found."} try: result = subprocess.run( ["python3", filepath], capture_output=True, text=True, timeout=10 ) output = result.stdout + result.stderr return {"output": output} except subprocess.TimeoutExpired: return {"output": "Execution timed out."} except Exception as e: return {"output": f"Error: {str(e)}"} # Simpan konfigurasi Setup Panel @app.post("/setup") async def setup_config(request: Request): data = await request.json() with open("/tmp/setup.json", "w") as f: json.dump(data, f, indent=2) return {"status": "ok", "received": data} # Mount /uploads biar bisa diakses langsung kalau mau app.mount("/uploads", StaticFiles(directory=UPLOAD_DIR), name="uploads")