from __future__ import annotations from fastapi import APIRouter from ..services.auth import storage as auth_store from ..services.drive import service as drive_svc from ..services.history import storage as hist router = APIRouter(prefix="/api/drive", tags=["drive"]) @router.get("/status") def drive_status(username: str = ""): configured = drive_svc.is_configured() if not username: return {"ok": True, "configured": configured, "linked": False} fid, link = auth_store.get_drive_folder(username) return { "ok": True, "configured": configured, "linked": bool(fid), "folder_id": fid or "", } @router.post("/setup") def drive_setup(body: dict): username = (body.get("username") or "").strip() folder_link = (body.get("folder_link") or "").strip() if not username: return {"ok": False, "error": "Missing username"} if not folder_link: return {"ok": False, "error": "Missing folder_link"} if not drive_svc.is_configured(): return {"ok": False, "error": "Google Drive chưa được cấu hình trên máy chủ"} folder_id = drive_svc.extract_folder_id(folder_link) if not folder_id: return {"ok": False, "error": "Link Google Drive không hợp lệ"} # Save to persistent auth storage (PostgreSQL / JSON file) auth_store.save_drive_folder(username, folder_id, folder_link) # Also keep history storage in sync for Drive backup mechanism hist.save_drive_folder(username, folder_id, folder_link) # Restore history from Drive backup (if exists) restored = hist.restore_from_drive(username, drive_svc) return {"ok": True, "folder_id": folder_id, "history_restored": restored} @router.delete("/setup") def drive_remove(username: str = ""): if not username: return {"ok": False, "error": "Missing username"} auth_store.save_drive_folder(username, "", "") hist.save_drive_folder(username, "", "") return {"ok": True}