from __future__ import annotations import asyncio import json import os import tempfile import time from urllib.parse import unquote, urlparse import httpx from fastapi import APIRouter, HTTPException, UploadFile, File, Form, Request from fastapi.responses import FileResponse, Response, StreamingResponse from pydantic import BaseModel from ..services.videogen.service import ( get_proxy, connect as svc_connect, disconnect as svc_disconnect, get_connection_status, get_endpoints, submit as svc_submit, predict as svc_predict, cancel as svc_cancel, get_job_status, get_job_result, get_user_jobs, _is_allowed_local, ) router = APIRouter(prefix="/api/video", tags=["videogen"]) # ─── Request models ─── class ConnectBody(BaseModel): url: str class SubmitBody(BaseModel): api_name: str params: dict = {} user_id: str = "" username: str = "" class PredictBody(BaseModel): api_name: str params: dict = {} class CancelBody(BaseModel): user_id: str = "" # ───── Kết nối ───── @router.get("/status") def status_connection(): return get_connection_status() @router.post("/connect") def api_connect(body: ConnectBody): url = body.url.strip() if not url: raise HTTPException(400, "Cần nhập link.") try: return svc_connect(url) except ValueError as e: raise HTTPException(400, str(e)) except Exception as e: raise HTTPException(500, f"Không kết nối được: {e}") @router.post("/disconnect") def api_disconnect(): return svc_disconnect() # ───── Khám phá ───── @router.get("/endpoints") def api_endpoints(): proxy = get_proxy() if not proxy: raise HTTPException(409, "Chưa kết nối.") return get_endpoints() @router.get("/gradio-config") def api_gradio_config(): proxy = get_proxy() if not proxy: raise HTTPException(409, "Chưa kết nối.") config = proxy.get_gradio_config() return config or {} # ───── Chạy job ───── @router.post("/submit") def api_submit(body: SubmitBody): proxy = get_proxy() if not proxy: raise HTTPException(409, "Chưa kết nối.") if not body.api_name: raise HTTPException(400, "Thiếu api_name.") try: job_id = svc_submit(body.api_name, body.params, user_id=body.user_id, username=body.username) return {"job_id": job_id} except Exception as e: raise HTTPException(500, str(e)) @router.post("/predict") def api_predict(body: PredictBody): proxy = get_proxy() if not proxy: raise HTTPException(409, "Chưa kết nối.") if not body.api_name: raise HTTPException(400, "Thiếu api_name.") try: return svc_predict(body.api_name, body.params) except Exception as e: raise HTTPException(500, str(e)) @router.post("/cancel/{job_id}") def api_cancel(job_id: str, body: CancelBody = CancelBody()): proxy = get_proxy() if not proxy: raise HTTPException(409, "Chưa kết nối.") ok = svc_cancel(job_id, user_id=body.user_id) return {"cancelled": ok} @router.get("/user-jobs") def api_user_jobs(user_id: str = ""): return get_user_jobs(user_id) @router.get("/status/{job_id}") async def api_status(job_id: str): async def event_generator(): proxy = get_proxy() if not proxy: yield f"data: {json.dumps({'error': 'Chưa kết nối.'})}\n\n" return if job_id not in proxy.jobs: yield f"data: {json.dumps({'error': 'Không tìm thấy job.'})}\n\n" return last = None start = time.time() while True: if time.time() - start > 60 * 60: yield f"data: {json.dumps({'error': 'Hết thời gian theo dõi.'})}\n\n" break try: status = get_job_status(job_id) if status != last: yield f"data: {json.dumps(status)}\n\n" last = status if status.get("done"): break except Exception as e: yield f"data: {json.dumps({'error': str(e)})}\n\n" break await asyncio.sleep(0.5) return StreamingResponse( event_generator(), media_type="text/event-stream", headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}, ) @router.get("/result/{job_id}") def api_result(job_id: str): proxy = get_proxy() if not proxy: raise HTTPException(409, "Chưa kết nối.") result = get_job_result(job_id) if isinstance(result, tuple): data, status_code = result from fastapi.responses import JSONResponse return JSONResponse(content=data, status_code=status_code) return result # ───── File ───── @router.post("/upload") def api_upload(file: UploadFile = File(...)): if not file.filename: raise HTTPException(400, "Tên file rỗng.") suffix = os.path.splitext(file.filename)[1] or "" fd, tmp_path = tempfile.mkstemp(suffix=suffix, prefix="gradio_upload_") try: content = file.read() with open(tmp_path, "wb") as f: f.write(content) finally: os.close(fd) return {"path": tmp_path, "filename": file.filename} @router.get("/localfile") def api_localfile(path: str = ""): path = unquote(path) if not path or not _is_allowed_local(path) or not os.path.isfile(path): raise HTTPException(404) return FileResponse(path) @router.get("/remote") def api_remote(u: str = ""): proxy = get_proxy() if not proxy: raise HTTPException(409, "Chưa kết nối.") target = unquote(u) allowed_host = urlparse(proxy.url).hostname if urlparse(target).hostname != allowed_host: raise HTTPException(403) try: with httpx.Client(timeout=300.0, follow_redirects=True) as client: resp = client.get(target) ct = resp.headers.get("content-type", "application/octet-stream") return Response(resp.read(), media_type=ct, status_code=resp.status_code) except Exception as e: raise HTTPException(500, str(e)) # ───── Gradio Reverse Proxy (cho iframe) ───── @router.api_route("/gradio-proxy/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD", "PATCH"]) async def gradio_reverse_proxy(path: str, request: Request): """Reverse proxy for Gradio app so iframe traffic goes through our backend.""" proxy = get_proxy() if not proxy: raise HTTPException(409, "Chưa kết nối.") target = f"{proxy.url}/{path}" if request.url.query: target += f"?{request.url.query}" body = await request.body() headers = { k: v for k, v in request.headers.items() if k.lower() not in ("host", "content-length", "x-forwarded-for", "x-forwarded-proto", "x-forwarded-host", "x-real-ip") } async with httpx.AsyncClient(timeout=600.0, follow_redirects=True) as client: resp = await client.request( method=request.method, url=target, headers=headers, content=body, ) resp_headers = { k: v for k, v in resp.headers.items() if k.lower() not in ("transfer-encoding", "content-encoding") } return Response( content=resp.content, status_code=resp.status_code, headers=resp_headers, ) @router.api_route("/gradio-proxy/", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD", "PATCH"]) async def gradio_reverse_proxy_root(request: Request): return await gradio_reverse_proxy("", request)