Spaces:
Sleeping
Sleeping
feat: lịch sử cá nhân + auto-save lên Google Drive
Browse files- Backend: service Google Drive (service account), history storage
- API: /api/drive/setup, /api/drive/status, /api/history, /api/history/auto-save
- Dub tool: tự động lưu kết quả sau khi xử lý + username tracking
- Frontend: trang Lịch sử cá nhân, liên kết Drive, button sidebar
- backend/app/api/__init__.py +0 -1
- backend/app/api/drive.py +49 -0
- backend/app/api/dub.py +44 -1
- backend/app/api/history_api.py +86 -0
- backend/app/main.py +3 -1
- backend/app/services/drive/__init__.py +0 -0
- backend/app/services/drive/service.py +155 -0
- backend/app/services/history/__init__.py +0 -0
- backend/app/services/history/storage.py +67 -0
- backend/requirements.txt +1 -0
- frontend/src/App.jsx +2 -0
- frontend/src/api.js +8 -0
- frontend/src/components/Icons.jsx +2 -0
- frontend/src/components/Sidebar.jsx +2 -1
- frontend/src/pages/DubVideo.jsx +3 -0
- frontend/src/pages/PersonalHistory.jsx +194 -0
backend/app/api/__init__.py
CHANGED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
"""Gói router FastAPI cho các tool."""
|
|
|
|
|
|
backend/app/api/drive.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from fastapi import APIRouter
|
| 4 |
+
|
| 5 |
+
from ..services.drive import service as drive_svc
|
| 6 |
+
from ..services.history import storage as hist
|
| 7 |
+
|
| 8 |
+
router = APIRouter(prefix="/api/drive", tags=["drive"])
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@router.get("/status")
|
| 12 |
+
def drive_status(username: str = ""):
|
| 13 |
+
configured = drive_svc.is_configured()
|
| 14 |
+
if not username:
|
| 15 |
+
return {"ok": True, "configured": configured, "linked": False}
|
| 16 |
+
folder_id = hist.get_drive_folder(username)
|
| 17 |
+
return {
|
| 18 |
+
"ok": True,
|
| 19 |
+
"configured": configured,
|
| 20 |
+
"linked": bool(folder_id),
|
| 21 |
+
"folder_id": folder_id or "",
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@router.post("/setup")
|
| 26 |
+
def drive_setup(body: dict):
|
| 27 |
+
username = (body.get("username") or "").strip()
|
| 28 |
+
folder_link = (body.get("folder_link") or "").strip()
|
| 29 |
+
if not username:
|
| 30 |
+
return {"ok": False, "error": "Missing username"}
|
| 31 |
+
if not folder_link:
|
| 32 |
+
return {"ok": False, "error": "Missing folder_link"}
|
| 33 |
+
if not drive_svc.is_configured():
|
| 34 |
+
return {"ok": False, "error": "Google Drive chưa được cấu hình trên máy chủ"}
|
| 35 |
+
|
| 36 |
+
folder_id = drive_svc.extract_folder_id(folder_link)
|
| 37 |
+
if not folder_id:
|
| 38 |
+
return {"ok": False, "error": "Link Google Drive không hợp lệ"}
|
| 39 |
+
|
| 40 |
+
hist.save_drive_folder(username, folder_id, folder_link)
|
| 41 |
+
return {"ok": True, "folder_id": folder_id}
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@router.delete("/setup")
|
| 45 |
+
def drive_remove(username: str = ""):
|
| 46 |
+
if not username:
|
| 47 |
+
return {"ok": False, "error": "Missing username"}
|
| 48 |
+
hist.save_drive_folder(username, "", "")
|
| 49 |
+
return {"ok": True}
|
backend/app/api/dub.py
CHANGED
|
@@ -19,6 +19,8 @@ from ..core.files import new_session, session_dir, sub_dir, save_upload
|
|
| 19 |
from ..core.jobs import jobs
|
| 20 |
from ..services.dubber import pipeline
|
| 21 |
from ..services.dubber import tts as tts_svc
|
|
|
|
|
|
|
| 22 |
|
| 23 |
router = APIRouter(prefix="/api/dub", tags=["dub"])
|
| 24 |
|
|
@@ -69,6 +71,7 @@ class DubReq(BaseModel):
|
|
| 69 |
temperature: float | None = None
|
| 70 |
top_k: int | None = None
|
| 71 |
repetition_penalty: float | None = None
|
|
|
|
| 72 |
|
| 73 |
|
| 74 |
@router.post("/start")
|
|
@@ -95,6 +98,7 @@ def start(req: DubReq):
|
|
| 95 |
)
|
| 96 |
|
| 97 |
job = jobs.create("dub")
|
|
|
|
| 98 |
|
| 99 |
def work(h):
|
| 100 |
n = len(req.files)
|
|
@@ -106,7 +110,6 @@ def start(req: DubReq):
|
|
| 106 |
out_dir = sub_dir(req.session, "out", base)
|
| 107 |
try:
|
| 108 |
def prog(p, m, _i=idx, _it=it):
|
| 109 |
-
# tiến độ tổng = (đã xong video + p video hiện tại) / n
|
| 110 |
h.set_progress((_i + p) / max(1, n))
|
| 111 |
h.item_status(_it, "running", detail=m)
|
| 112 |
|
|
@@ -132,12 +135,52 @@ def start(req: DubReq):
|
|
| 132 |
except Exception as e:
|
| 133 |
h.item_status(it, "error", error=str(e))
|
| 134 |
h.set_progress((idx + 1) / max(1, n))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
return {"session": req.session, "outputs": outputs}
|
| 136 |
|
| 137 |
jobs.submit(job, work)
|
| 138 |
return {"job_id": job.id, "session": req.session, "videos": len(req.files)}
|
| 139 |
|
| 140 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
# ------------------------------------------------------- TTS từ text ---
|
| 142 |
|
| 143 |
class TtsReq(BaseModel):
|
|
|
|
| 19 |
from ..core.jobs import jobs
|
| 20 |
from ..services.dubber import pipeline
|
| 21 |
from ..services.dubber import tts as tts_svc
|
| 22 |
+
from ..services.history import storage as hist
|
| 23 |
+
from ..services.drive import service as drive_svc
|
| 24 |
|
| 25 |
router = APIRouter(prefix="/api/dub", tags=["dub"])
|
| 26 |
|
|
|
|
| 71 |
temperature: float | None = None
|
| 72 |
top_k: int | None = None
|
| 73 |
repetition_penalty: float | None = None
|
| 74 |
+
username: str = ""
|
| 75 |
|
| 76 |
|
| 77 |
@router.post("/start")
|
|
|
|
| 98 |
)
|
| 99 |
|
| 100 |
job = jobs.create("dub")
|
| 101 |
+
_username = req.username
|
| 102 |
|
| 103 |
def work(h):
|
| 104 |
n = len(req.files)
|
|
|
|
| 110 |
out_dir = sub_dir(req.session, "out", base)
|
| 111 |
try:
|
| 112 |
def prog(p, m, _i=idx, _it=it):
|
|
|
|
| 113 |
h.set_progress((_i + p) / max(1, n))
|
| 114 |
h.item_status(_it, "running", detail=m)
|
| 115 |
|
|
|
|
| 135 |
except Exception as e:
|
| 136 |
h.item_status(it, "error", error=str(e))
|
| 137 |
h.set_progress((idx + 1) / max(1, n))
|
| 138 |
+
|
| 139 |
+
# Auto-save to history + Drive
|
| 140 |
+
if _username:
|
| 141 |
+
_auto_save_dub(_username, req.session, outputs)
|
| 142 |
+
|
| 143 |
return {"session": req.session, "outputs": outputs}
|
| 144 |
|
| 145 |
jobs.submit(job, work)
|
| 146 |
return {"job_id": job.id, "session": req.session, "videos": len(req.files)}
|
| 147 |
|
| 148 |
|
| 149 |
+
def _auto_save_dub(username: str, session: str, outputs: list[dict]):
|
| 150 |
+
from datetime import datetime
|
| 151 |
+
sd = session_dir(session)
|
| 152 |
+
now_str = datetime.now().strftime("%Y-%m-%d %H:%M")
|
| 153 |
+
for o in outputs:
|
| 154 |
+
files_meta = []
|
| 155 |
+
for key in ("video_url", "audio_url", "srt_url"):
|
| 156 |
+
fpath = os.path.join(sd, o.get(key, "").replace("/api/files/", "").lstrip("/"))
|
| 157 |
+
if os.path.exists(fpath):
|
| 158 |
+
files_meta.append({"path": fpath, "name": os.path.basename(fpath)})
|
| 159 |
+
|
| 160 |
+
hist.add_entry(username, {
|
| 161 |
+
"type": "tool_result",
|
| 162 |
+
"tool": "dub",
|
| 163 |
+
"title": f"Dịch video: {o['name']}",
|
| 164 |
+
"summary": f"{o.get('n_lines', 0)} câu · {o.get('language', '')} · {now_str}",
|
| 165 |
+
"files": files_meta,
|
| 166 |
+
"session": session,
|
| 167 |
+
})
|
| 168 |
+
|
| 169 |
+
# Upload to Drive
|
| 170 |
+
folder_id = hist.get_drive_folder(username)
|
| 171 |
+
if folder_id and drive_svc.is_configured():
|
| 172 |
+
try:
|
| 173 |
+
tool_fid = drive_svc.ensure_path(folder_id, ["dub"])
|
| 174 |
+
date_str = datetime.now().strftime("%Y-%m-%d")
|
| 175 |
+
time_str = datetime.now().strftime("%H-%M-%S")
|
| 176 |
+
run_fid = drive_svc.ensure_path(tool_fid, [date_str, time_str])
|
| 177 |
+
if run_fid:
|
| 178 |
+
for fm in files_meta:
|
| 179 |
+
drive_svc.upload_file(run_fid, fm["path"], fm["name"])
|
| 180 |
+
except Exception:
|
| 181 |
+
pass
|
| 182 |
+
|
| 183 |
+
|
| 184 |
# ------------------------------------------------------- TTS từ text ---
|
| 185 |
|
| 186 |
class TtsReq(BaseModel):
|
backend/app/api/history_api.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
from fastapi import APIRouter
|
| 6 |
+
|
| 7 |
+
from ..core.files import session_dir
|
| 8 |
+
from ..services.drive import service as drive_svc
|
| 9 |
+
from ..services.history import storage as hist
|
| 10 |
+
|
| 11 |
+
router = APIRouter(prefix="/api/history", tags=["history"])
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@router.get("")
|
| 15 |
+
def get_history(username: str = "", limit: int = 50):
|
| 16 |
+
if not username:
|
| 17 |
+
return {"ok": False, "error": "Missing username"}
|
| 18 |
+
entries = hist.get_entries(username, limit)
|
| 19 |
+
return {"ok": True, "entries": entries}
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@router.post("/save")
|
| 23 |
+
def save_history(body: dict):
|
| 24 |
+
username = (body.get("username") or "").strip()
|
| 25 |
+
if not username:
|
| 26 |
+
return {"ok": False, "error": "Missing username"}
|
| 27 |
+
entry = {
|
| 28 |
+
"type": body.get("type", "manual"),
|
| 29 |
+
"tool": body.get("tool", ""),
|
| 30 |
+
"title": body.get("title", ""),
|
| 31 |
+
"summary": body.get("summary", ""),
|
| 32 |
+
"files": body.get("files", []),
|
| 33 |
+
"session": body.get("session", ""),
|
| 34 |
+
}
|
| 35 |
+
saved = hist.add_entry(username, entry)
|
| 36 |
+
return {"ok": True, "entry": saved}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@router.post("/auto-save")
|
| 40 |
+
def auto_save(body: dict):
|
| 41 |
+
username = (body.get("username") or "").strip()
|
| 42 |
+
tool = (body.get("tool") or "").strip()
|
| 43 |
+
session = (body.get("session") or "").strip()
|
| 44 |
+
files = body.get("files", [])
|
| 45 |
+
title = body.get("title", "")
|
| 46 |
+
|
| 47 |
+
if not username or not tool or not session:
|
| 48 |
+
return {"ok": False, "error": "Missing required fields"}
|
| 49 |
+
|
| 50 |
+
# Save history entry on server
|
| 51 |
+
entry = {
|
| 52 |
+
"type": "tool_result",
|
| 53 |
+
"tool": tool,
|
| 54 |
+
"title": title,
|
| 55 |
+
"summary": body.get("summary", ""),
|
| 56 |
+
"files": files,
|
| 57 |
+
"session": session,
|
| 58 |
+
}
|
| 59 |
+
saved = hist.add_entry(username, entry)
|
| 60 |
+
|
| 61 |
+
# Upload to Google Drive if configured
|
| 62 |
+
folder_id = hist.get_drive_folder(username)
|
| 63 |
+
uploaded = []
|
| 64 |
+
if folder_id and drive_svc.is_configured():
|
| 65 |
+
import time
|
| 66 |
+
from datetime import datetime
|
| 67 |
+
|
| 68 |
+
tool_folder_id = drive_svc.ensure_path(folder_id, [tool])
|
| 69 |
+
date_str = datetime.now().strftime("%Y-%m-%d")
|
| 70 |
+
time_str = datetime.now().strftime("%H-%M-%S")
|
| 71 |
+
run_folder_id = drive_svc.ensure_path(tool_folder_id, [date_str, time_str]) if tool_folder_id else None
|
| 72 |
+
|
| 73 |
+
if run_folder_id:
|
| 74 |
+
for f in files:
|
| 75 |
+
fpath = f.get("path", "")
|
| 76 |
+
fname = f.get("name", os.path.basename(fpath))
|
| 77 |
+
if fpath and os.path.exists(fpath):
|
| 78 |
+
result = drive_svc.upload_file(run_folder_id, fpath, fname)
|
| 79 |
+
if result:
|
| 80 |
+
uploaded.append({
|
| 81 |
+
"name": fname,
|
| 82 |
+
"drive_id": result.get("id"),
|
| 83 |
+
"link": result.get("webViewLink"),
|
| 84 |
+
})
|
| 85 |
+
|
| 86 |
+
return {"ok": True, "entry": saved, "drive_uploaded": uploaded}
|
backend/app/main.py
CHANGED
|
@@ -24,7 +24,7 @@ _here = os.path.dirname(os.path.abspath(__file__))
|
|
| 24 |
_parent = os.path.dirname(_here)
|
| 25 |
sys.path.insert(0, _parent)
|
| 26 |
|
| 27 |
-
from .api import common, download, cut, shuffle, dub, listing, video, auth
|
| 28 |
|
| 29 |
app = FastAPI(title="TNT Group - AI Content Create", version="1.0.0")
|
| 30 |
|
|
@@ -44,6 +44,8 @@ app.include_router(dub.router)
|
|
| 44 |
app.include_router(listing.router)
|
| 45 |
app.include_router(video.router)
|
| 46 |
app.include_router(auth.router)
|
|
|
|
|
|
|
| 47 |
|
| 48 |
|
| 49 |
@app.get("/api/health")
|
|
|
|
| 24 |
_parent = os.path.dirname(_here)
|
| 25 |
sys.path.insert(0, _parent)
|
| 26 |
|
| 27 |
+
from .api import common, download, cut, shuffle, dub, listing, video, auth, drive, history_api
|
| 28 |
|
| 29 |
app = FastAPI(title="TNT Group - AI Content Create", version="1.0.0")
|
| 30 |
|
|
|
|
| 44 |
app.include_router(listing.router)
|
| 45 |
app.include_router(video.router)
|
| 46 |
app.include_router(auth.router)
|
| 47 |
+
app.include_router(drive.router)
|
| 48 |
+
app.include_router(history_api.router)
|
| 49 |
|
| 50 |
|
| 51 |
@app.get("/api/health")
|
backend/app/services/drive/__init__.py
ADDED
|
File without changes
|
backend/app/services/drive/service.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import re
|
| 6 |
+
import time
|
| 7 |
+
|
| 8 |
+
import requests
|
| 9 |
+
from google.auth.transport.requests import Request
|
| 10 |
+
from google.oauth2.service_account import Credentials
|
| 11 |
+
|
| 12 |
+
SCOPES = ["https://www.googleapis.com/auth/drive.file"]
|
| 13 |
+
FOLDER_MIME = "application/vnd.google-apps.folder"
|
| 14 |
+
API_BASE = "https://www.googleapis.com/drive/v3"
|
| 15 |
+
UPLOAD_BASE = "https://www.googleapis.com/upload/drive/v3"
|
| 16 |
+
|
| 17 |
+
_creds: Credentials | None = None
|
| 18 |
+
_token_expiry: float = 0
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _get_token() -> str | None:
|
| 22 |
+
global _creds, _token_expiry
|
| 23 |
+
now = time.time()
|
| 24 |
+
if _creds and now < _token_expiry - 60:
|
| 25 |
+
return _creds.token
|
| 26 |
+
|
| 27 |
+
sa_json = os.environ.get("GOOGLE_DRIVE_SERVICE_ACCOUNT")
|
| 28 |
+
if not sa_json:
|
| 29 |
+
return None
|
| 30 |
+
try:
|
| 31 |
+
info = json.loads(sa_json)
|
| 32 |
+
_creds = Credentials.from_service_account_info(info, scopes=SCOPES)
|
| 33 |
+
_creds.refresh(Request())
|
| 34 |
+
_token_expiry = now + 3600
|
| 35 |
+
return _creds.token
|
| 36 |
+
except Exception:
|
| 37 |
+
return None
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _headers() -> dict | None:
|
| 41 |
+
token = _get_token()
|
| 42 |
+
if not token:
|
| 43 |
+
return None
|
| 44 |
+
return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _auth_header() -> dict | None:
|
| 48 |
+
token = _get_token()
|
| 49 |
+
if not token:
|
| 50 |
+
return None
|
| 51 |
+
return {"Authorization": f"Bearer {token}"}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def extract_folder_id(link: str) -> str | None:
|
| 55 |
+
patterns = [
|
| 56 |
+
r"folders/([a-zA-Z0-9_-]+)",
|
| 57 |
+
r"id=([a-zA-Z0-9_-]+)",
|
| 58 |
+
r"^(?:https?://)?(?:www\.)?drive\.google\.com.*[/?]id=([a-zA-Z0-9_-]+)",
|
| 59 |
+
r"^([a-zA-Z0-9_-]{25,})$",
|
| 60 |
+
]
|
| 61 |
+
for p in patterns:
|
| 62 |
+
m = re.search(p, link)
|
| 63 |
+
if m:
|
| 64 |
+
return m.group(1)
|
| 65 |
+
return None
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def create_folder(name: str, parent_id: str) -> str | None:
|
| 69 |
+
h = _headers()
|
| 70 |
+
if not h:
|
| 71 |
+
return None
|
| 72 |
+
body = {"name": name, "mimeType": FOLDER_MIME, "parents": [parent_id]}
|
| 73 |
+
r = requests.post(
|
| 74 |
+
f"{API_BASE}/files", json=body, headers=h, params={"fields": "id,name"}
|
| 75 |
+
)
|
| 76 |
+
if r.status_code == 200:
|
| 77 |
+
return r.json().get("id")
|
| 78 |
+
return None
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def ensure_path(parent_id: str, path_parts: list[str]) -> str | None:
|
| 82 |
+
current = parent_id
|
| 83 |
+
for part in path_parts:
|
| 84 |
+
h = _headers()
|
| 85 |
+
if not h:
|
| 86 |
+
return None
|
| 87 |
+
q = (
|
| 88 |
+
f"name='{part}' and '{current}' in parents "
|
| 89 |
+
f"and mimeType='{FOLDER_MIME}' and trashed=false"
|
| 90 |
+
)
|
| 91 |
+
r = requests.get(
|
| 92 |
+
f"{API_BASE}/files",
|
| 93 |
+
headers=h,
|
| 94 |
+
params={"q": q, "fields": "files(id,name)", "pageSize": 1},
|
| 95 |
+
)
|
| 96 |
+
existing = None
|
| 97 |
+
if r.status_code == 200:
|
| 98 |
+
files = r.json().get("files", [])
|
| 99 |
+
if files:
|
| 100 |
+
existing = files[0]["id"]
|
| 101 |
+
if existing:
|
| 102 |
+
current = existing
|
| 103 |
+
else:
|
| 104 |
+
new_id = create_folder(part, current)
|
| 105 |
+
if new_id:
|
| 106 |
+
current = new_id
|
| 107 |
+
else:
|
| 108 |
+
return None
|
| 109 |
+
return current
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def upload_file(folder_id: str, file_path: str, name: str | None = None) -> dict | None:
|
| 113 |
+
if not os.path.exists(file_path):
|
| 114 |
+
return None
|
| 115 |
+
if not name:
|
| 116 |
+
name = os.path.basename(file_path)
|
| 117 |
+
|
| 118 |
+
h = _auth_header()
|
| 119 |
+
if not h:
|
| 120 |
+
return None
|
| 121 |
+
|
| 122 |
+
metadata = json.dumps({"name": name, "parents": [folder_id]})
|
| 123 |
+
filesize = os.path.getsize(file_path)
|
| 124 |
+
|
| 125 |
+
if filesize < 5 * 1024 * 1024:
|
| 126 |
+
cr = requests.post(
|
| 127 |
+
f"{UPLOAD_BASE}/files?uploadType=multipart&fields=id,name,webViewLink",
|
| 128 |
+
headers=h,
|
| 129 |
+
data={
|
| 130 |
+
"metadata": ("metadata", metadata, "application/json; charset=UTF-8"),
|
| 131 |
+
"file": (name, open(file_path, "rb"), "application/octet-stream"),
|
| 132 |
+
},
|
| 133 |
+
)
|
| 134 |
+
else:
|
| 135 |
+
# resumable upload
|
| 136 |
+
cr = requests.post(
|
| 137 |
+
f"{UPLOAD_BASE}/files?uploadType=resumable&fields=id,name,webViewLink",
|
| 138 |
+
headers={**h, "Content-Type": "application/json"},
|
| 139 |
+
data=metadata,
|
| 140 |
+
)
|
| 141 |
+
if cr.status_code != 200:
|
| 142 |
+
return None
|
| 143 |
+
location = cr.headers.get("Location")
|
| 144 |
+
if not location:
|
| 145 |
+
return None
|
| 146 |
+
with open(file_path, "rb") as f:
|
| 147 |
+
cr = requests.put(location, data=f, headers={"Content-Type": "application/octet-stream"})
|
| 148 |
+
|
| 149 |
+
if cr.status_code in (200, 201):
|
| 150 |
+
return cr.json()
|
| 151 |
+
return None
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def is_configured() -> bool:
|
| 155 |
+
return bool(os.environ.get("GOOGLE_DRIVE_SERVICE_ACCOUNT"))
|
backend/app/services/history/__init__.py
ADDED
|
File without changes
|
backend/app/services/history/storage.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import time
|
| 6 |
+
|
| 7 |
+
from ...config import settings
|
| 8 |
+
|
| 9 |
+
HISTORY_DIR = os.path.join(settings.STORAGE_DIR, "_history")
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _user_path(username: str) -> str:
|
| 13 |
+
os.makedirs(HISTORY_DIR, exist_ok=True)
|
| 14 |
+
safe = username.replace("/", "_").replace("\\", "_").strip()
|
| 15 |
+
return os.path.join(HISTORY_DIR, f"{safe}.json")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _read(username: str) -> list[dict]:
|
| 19 |
+
path = _user_path(username)
|
| 20 |
+
if not os.path.exists(path):
|
| 21 |
+
return []
|
| 22 |
+
try:
|
| 23 |
+
with open(path, "r", encoding="utf-8") as f:
|
| 24 |
+
return json.load(f)
|
| 25 |
+
except Exception:
|
| 26 |
+
return []
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _write(username: str, entries: list[dict]):
|
| 30 |
+
path = _user_path(username)
|
| 31 |
+
with open(path, "w", encoding="utf-8") as f:
|
| 32 |
+
json.dump(entries, f, ensure_ascii=False, indent=2)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def add_entry(username: str, entry: dict) -> dict:
|
| 36 |
+
entries = _read(username)
|
| 37 |
+
entry["id"] = f"hist_{int(time.time()*1000)}_{len(entries)}"
|
| 38 |
+
entry["created_at"] = time.time()
|
| 39 |
+
entries.append(entry)
|
| 40 |
+
_write(username, entries)
|
| 41 |
+
return entry
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def get_entries(username: str, limit: int = 50) -> list[dict]:
|
| 45 |
+
entries = _read(username)
|
| 46 |
+
return list(reversed(entries))[:limit]
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def get_drive_folder(username: str) -> str | None:
|
| 50 |
+
entries = _read(username)
|
| 51 |
+
for e in entries:
|
| 52 |
+
if e.get("type") == "drive_setup":
|
| 53 |
+
return e.get("folder_id")
|
| 54 |
+
return None
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def save_drive_folder(username: str, folder_id: str, folder_link: str):
|
| 58 |
+
entries = _read(username)
|
| 59 |
+
# remove old drive_setup entries
|
| 60 |
+
entries = [e for e in entries if e.get("type") != "drive_setup"]
|
| 61 |
+
entries.append({
|
| 62 |
+
"type": "drive_setup",
|
| 63 |
+
"folder_id": folder_id,
|
| 64 |
+
"folder_link": folder_link,
|
| 65 |
+
"created_at": time.time(),
|
| 66 |
+
})
|
| 67 |
+
_write(username, entries)
|
backend/requirements.txt
CHANGED
|
@@ -32,4 +32,5 @@ Pillow>=10.0 # xử lý ảnh (listing: resize, composite)
|
|
| 32 |
requests>=2.31 # HTTP cho Cloudflare Flux API (listing)
|
| 33 |
gradio-client>=1.3 # Video Gen (Gradio proxy)
|
| 34 |
httpx>=0.24 # Video Gen
|
|
|
|
| 35 |
psycopg2-binary>=2.9 # Database (optional - PostgreSQL)
|
|
|
|
| 32 |
requests>=2.31 # HTTP cho Cloudflare Flux API (listing)
|
| 33 |
gradio-client>=1.3 # Video Gen (Gradio proxy)
|
| 34 |
httpx>=0.24 # Video Gen
|
| 35 |
+
google-auth>=2.0 # Google Drive service account auth
|
| 36 |
psycopg2-binary>=2.9 # Database (optional - PostgreSQL)
|
frontend/src/App.jsx
CHANGED
|
@@ -12,6 +12,7 @@ import ListingImage from "./pages/ListingImage";
|
|
| 12 |
import CreateVideo from "./pages/CreateVideo";
|
| 13 |
import AdminUsers from "./pages/AdminUsers";
|
| 14 |
import Login from "./pages/Login";
|
|
|
|
| 15 |
|
| 16 |
const router = createBrowserRouter([
|
| 17 |
{
|
|
@@ -31,6 +32,7 @@ const router = createBrowserRouter([
|
|
| 31 |
{ path: "/huong-dan", element: <Guide /> },
|
| 32 |
{ path: "/ho-tro", element: <Support /> },
|
| 33 |
{ path: "/quan-tri", element: <AdminUsers /> },
|
|
|
|
| 34 |
{ path: "*", element: <Placeholder title="Không tìm thấy" desc="Trang bạn tìm không tồn tại." /> },
|
| 35 |
],
|
| 36 |
},
|
|
|
|
| 12 |
import CreateVideo from "./pages/CreateVideo";
|
| 13 |
import AdminUsers from "./pages/AdminUsers";
|
| 14 |
import Login from "./pages/Login";
|
| 15 |
+
import PersonalHistory from "./pages/PersonalHistory";
|
| 16 |
|
| 17 |
const router = createBrowserRouter([
|
| 18 |
{
|
|
|
|
| 32 |
{ path: "/huong-dan", element: <Guide /> },
|
| 33 |
{ path: "/ho-tro", element: <Support /> },
|
| 34 |
{ path: "/quan-tri", element: <AdminUsers /> },
|
| 35 |
+
{ path: "/lich-su", element: <PersonalHistory /> },
|
| 36 |
{ path: "*", element: <Placeholder title="Không tìm thấy" desc="Trang bạn tìm không tồn tại." /> },
|
| 37 |
],
|
| 38 |
},
|
frontend/src/api.js
CHANGED
|
@@ -61,6 +61,14 @@ export const api = {
|
|
| 61 |
dubVoices: (lang) => fetch(BASE + `/api/dub/voices?lang=${lang}`).then((r) => r.json()),
|
| 62 |
dubStart: (req) => jpost("/api/dub/start", req),
|
| 63 |
dubTts: (req) => jpost("/api/dub/tts", req),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
};
|
| 65 |
|
| 66 |
// Poll một job tới khi xong. onTick(job) gọi mỗi lần cập nhật.
|
|
|
|
| 61 |
dubVoices: (lang) => fetch(BASE + `/api/dub/voices?lang=${lang}`).then((r) => r.json()),
|
| 62 |
dubStart: (req) => jpost("/api/dub/start", req),
|
| 63 |
dubTts: (req) => jpost("/api/dub/tts", req),
|
| 64 |
+
|
| 65 |
+
// Drive
|
| 66 |
+
driveStatus: (username) => fetch(BASE + `/api/drive/status?username=${encodeURIComponent(username)}`).then((r) => r.json()),
|
| 67 |
+
driveSetup: (username, folder_link) => jpost("/api/drive/setup", { username, folder_link }),
|
| 68 |
+
driveRemove: (username) => fetch(BASE + `/api/drive/setup?username=${encodeURIComponent(username)}`, { method: "DELETE" }).then((r) => r.json()),
|
| 69 |
+
|
| 70 |
+
// History
|
| 71 |
+
getHistory: (username) => fetch(BASE + `/api/history?username=${encodeURIComponent(username)}`).then((r) => r.json()),
|
| 72 |
};
|
| 73 |
|
| 74 |
// Poll một job tới khi xong. onTick(job) gọi mỗi lần cập nhật.
|
frontend/src/components/Icons.jsx
CHANGED
|
@@ -35,3 +35,5 @@ export const IcPlus = (p) => <S {...p}><path d="M12 5v14M5 12h14" /></S>;
|
|
| 35 |
export const IcLock = (p) => <S {...p}><rect x="5" y="11" width="14" height="9" rx="2" /><path d="M8 11V7a4 4 0 0 1 8 0v4" /></S>;
|
| 36 |
export const IcMessage = (p) => <S {...p}><path d="M21 12a8 8 0 0 1-11.6 7.1L4 20l1-4.4A8 8 0 1 1 21 12z" /></S>;
|
| 37 |
export const IcInfo = (p) => <S {...p}><circle cx="12" cy="12" r="9" /><path d="M12 11v5" /><path d="M12 7.5h.01" /></S>;
|
|
|
|
|
|
|
|
|
| 35 |
export const IcLock = (p) => <S {...p}><rect x="5" y="11" width="14" height="9" rx="2" /><path d="M8 11V7a4 4 0 0 1 8 0v4" /></S>;
|
| 36 |
export const IcMessage = (p) => <S {...p}><path d="M21 12a8 8 0 0 1-11.6 7.1L4 20l1-4.4A8 8 0 1 1 21 12z" /></S>;
|
| 37 |
export const IcInfo = (p) => <S {...p}><circle cx="12" cy="12" r="9" /><path d="M12 11v5" /><path d="M12 7.5h.01" /></S>;
|
| 38 |
+
export const IcHistory = (p) => <S {...p}><circle cx="12" cy="12" r="9" /><path d="M12 8v4l3 3" /><path d="M4 5v5h5" /><path d="M4 5a9 9 0 1 1-1 5" /></S>;
|
| 39 |
+
export const IcDrive = (p) => <S {...p}><rect x="3" y="5" width="18" height="14" rx="2" /><path d="M3 10h18" /><path d="M7 5v14M17 5v14" /></S>;
|
frontend/src/components/Sidebar.jsx
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
import { NavLink } from "react-router-dom";
|
| 2 |
import {
|
| 3 |
IcHome, IcDownload, IcImage, IcVideo, IcScissors, IcShuffle, IcMic,
|
| 4 |
-
IcBook, IcHelp, IcLock,
|
| 5 |
} from "./Icons";
|
| 6 |
|
| 7 |
const item = (to, Icon, label) => (
|
|
@@ -34,6 +34,7 @@ export default function Sidebar() {
|
|
| 34 |
{item("/cut", IcScissors, "Cut video")}
|
| 35 |
{item("/xao", IcShuffle, "Xào video")}
|
| 36 |
{item("/dub", IcMic, "Dịch / đổi giọng")}
|
|
|
|
| 37 |
</div>
|
| 38 |
|
| 39 |
<div className="nav-group">
|
|
|
|
| 1 |
import { NavLink } from "react-router-dom";
|
| 2 |
import {
|
| 3 |
IcHome, IcDownload, IcImage, IcVideo, IcScissors, IcShuffle, IcMic,
|
| 4 |
+
IcBook, IcHelp, IcLock, IcHistory,
|
| 5 |
} from "./Icons";
|
| 6 |
|
| 7 |
const item = (to, Icon, label) => (
|
|
|
|
| 34 |
{item("/cut", IcScissors, "Cut video")}
|
| 35 |
{item("/xao", IcShuffle, "Xào video")}
|
| 36 |
{item("/dub", IcMic, "Dịch / đổi giọng")}
|
| 37 |
+
{item("/lich-su", IcHistory, "Lịch sử cá nhân")}
|
| 38 |
</div>
|
| 39 |
|
| 40 |
<div className="nav-group">
|
frontend/src/pages/DubVideo.jsx
CHANGED
|
@@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from "react";
|
|
| 2 |
import { useSearchParams } from "react-router-dom";
|
| 3 |
import { api, pollJob, fileUrl } from "../api";
|
| 4 |
import { useToolState } from "../store";
|
|
|
|
| 5 |
import { ProcessRail, FileDrop, Toggle, ProcessingOverlay, CacheNote } from "../components/ui";
|
| 6 |
import { IcMic, IcDownload, IcPlay, IcDoc, IcText } from "../components/Icons";
|
| 7 |
|
|
@@ -51,6 +52,7 @@ function QualityControls({ q, onChange }) {
|
|
| 51 |
}
|
| 52 |
|
| 53 |
export default function DubVideo() {
|
|
|
|
| 54 |
const [sp] = useSearchParams();
|
| 55 |
const [st, set] = useToolState("dub", {
|
| 56 |
session: null, videos: [],
|
|
@@ -148,6 +150,7 @@ export default function DubVideo() {
|
|
| 148 |
speaker_file: st.speakerFile,
|
| 149 |
preset: (!fil && src === "preset") ? st.voice : "",
|
| 150 |
style: st.style, engine: "auto", multi_speaker: st.multiSpeaker,
|
|
|
|
| 151 |
...qualityPayload(!fil && st.useQuality, st.temperature, st.topK, st.repPen),
|
| 152 |
});
|
| 153 |
const done = await pollJob(job_id, setJob);
|
|
|
|
| 2 |
import { useSearchParams } from "react-router-dom";
|
| 3 |
import { api, pollJob, fileUrl } from "../api";
|
| 4 |
import { useToolState } from "../store";
|
| 5 |
+
import { useAuth } from "../stores/authStore";
|
| 6 |
import { ProcessRail, FileDrop, Toggle, ProcessingOverlay, CacheNote } from "../components/ui";
|
| 7 |
import { IcMic, IcDownload, IcPlay, IcDoc, IcText } from "../components/Icons";
|
| 8 |
|
|
|
|
| 52 |
}
|
| 53 |
|
| 54 |
export default function DubVideo() {
|
| 55 |
+
const { user } = useAuth();
|
| 56 |
const [sp] = useSearchParams();
|
| 57 |
const [st, set] = useToolState("dub", {
|
| 58 |
session: null, videos: [],
|
|
|
|
| 150 |
speaker_file: st.speakerFile,
|
| 151 |
preset: (!fil && src === "preset") ? st.voice : "",
|
| 152 |
style: st.style, engine: "auto", multi_speaker: st.multiSpeaker,
|
| 153 |
+
username: user,
|
| 154 |
...qualityPayload(!fil && st.useQuality, st.temperature, st.topK, st.repPen),
|
| 155 |
});
|
| 156 |
const done = await pollJob(job_id, setJob);
|
frontend/src/pages/PersonalHistory.jsx
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { useState, useEffect, useCallback } from "react";
|
| 2 |
+
import { useAuth } from "../stores/authStore";
|
| 3 |
+
import { fileUrl } from "../api";
|
| 4 |
+
import { IcHistory, IcDrive, IcFolder, IcTrash, IcRefresh, IcVideo, IcMic, IcDoc, IcImage, IcDownload } from "../components/Icons";
|
| 5 |
+
|
| 6 |
+
const BASE = "";
|
| 7 |
+
|
| 8 |
+
async function jpost(path, body) {
|
| 9 |
+
const r = await fetch(BASE + path, {
|
| 10 |
+
method: "POST", headers: { "Content-Type": "application/json" },
|
| 11 |
+
body: JSON.stringify(body),
|
| 12 |
+
});
|
| 13 |
+
if (!r.ok) throw new Error((await r.text()) || r.statusText);
|
| 14 |
+
return r.json();
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
const TOOL_LABELS = {
|
| 18 |
+
dub: "Dịch / đổi giọng",
|
| 19 |
+
tts: "Tạo voice từ text",
|
| 20 |
+
cut: "Cut video",
|
| 21 |
+
shuffle: "Xào video",
|
| 22 |
+
download: "Down list video",
|
| 23 |
+
listing: "Listing ảnh",
|
| 24 |
+
videogen: "Tạo video",
|
| 25 |
+
};
|
| 26 |
+
const TOOL_ICONS = {
|
| 27 |
+
dub: IcMic, tts: IcMic, cut: IcVideo,
|
| 28 |
+
shuffle: IcVideo, download: IcDownload, listing: IcImage, videogen: IcVideo,
|
| 29 |
+
};
|
| 30 |
+
|
| 31 |
+
export default function PersonalHistory() {
|
| 32 |
+
const { user } = useAuth();
|
| 33 |
+
const [entries, setEntries] = useState([]);
|
| 34 |
+
const [loading, setLoading] = useState(false);
|
| 35 |
+
const [driveLink, setDriveLink] = useState("");
|
| 36 |
+
const [driveStatus, setDriveStatus] = useState(null);
|
| 37 |
+
const [showDriveSetup, setShowDriveSetup] = useState(false);
|
| 38 |
+
|
| 39 |
+
const loadHistory = useCallback(async () => {
|
| 40 |
+
if (!user) return;
|
| 41 |
+
setLoading(true);
|
| 42 |
+
try {
|
| 43 |
+
const r = await fetch(`/api/history?username=${encodeURIComponent(user)}&limit=100`);
|
| 44 |
+
const data = await r.json();
|
| 45 |
+
if (data.ok) setEntries(data.entries || []);
|
| 46 |
+
} catch (e) {
|
| 47 |
+
console.error(e);
|
| 48 |
+
}
|
| 49 |
+
setLoading(false);
|
| 50 |
+
}, [user]);
|
| 51 |
+
|
| 52 |
+
const loadDriveStatus = useCallback(async () => {
|
| 53 |
+
if (!user) return;
|
| 54 |
+
try {
|
| 55 |
+
const r = await fetch(`/api/drive/status?username=${encodeURIComponent(user)}`);
|
| 56 |
+
const data = await r.json();
|
| 57 |
+
setDriveStatus(data);
|
| 58 |
+
} catch (e) {
|
| 59 |
+
console.error(e);
|
| 60 |
+
}
|
| 61 |
+
}, [user]);
|
| 62 |
+
|
| 63 |
+
useEffect(() => { loadHistory(); loadDriveStatus(); }, [loadHistory, loadDriveStatus]);
|
| 64 |
+
|
| 65 |
+
const setupDrive = async () => {
|
| 66 |
+
if (!driveLink.trim()) return alert("Nhập link Google Drive folder");
|
| 67 |
+
const r = await jpost("/api/drive/setup", { username: user, folder_link: driveLink.trim() });
|
| 68 |
+
if (r.ok) {
|
| 69 |
+
setShowDriveSetup(false);
|
| 70 |
+
setDriveLink("");
|
| 71 |
+
loadDriveStatus();
|
| 72 |
+
} else {
|
| 73 |
+
alert(r.error || "Lỗi khi liên kết Drive");
|
| 74 |
+
}
|
| 75 |
+
};
|
| 76 |
+
|
| 77 |
+
const removeDrive = async () => {
|
| 78 |
+
await fetch(`/api/drive/setup?username=${encodeURIComponent(user)}`, { method: "DELETE" });
|
| 79 |
+
loadDriveStatus();
|
| 80 |
+
};
|
| 81 |
+
|
| 82 |
+
const toolEntries = {};
|
| 83 |
+
for (const e of entries) {
|
| 84 |
+
if (e.type === "tool_result") {
|
| 85 |
+
const tool = e.tool || "other";
|
| 86 |
+
if (!toolEntries[tool]) toolEntries[tool] = [];
|
| 87 |
+
toolEntries[tool].push(e);
|
| 88 |
+
}
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
const groupedTools = Object.keys(toolEntries).sort();
|
| 92 |
+
const hasEntries = groupedTools.length > 0;
|
| 93 |
+
|
| 94 |
+
const formatDate = (ts) => {
|
| 95 |
+
const d = new Date((ts || 0) * 1000);
|
| 96 |
+
return d.toLocaleString("vi-VN", { day: "2-digit", month: "2-digit", year: "numeric", hour: "2-digit", minute: "2-digit" });
|
| 97 |
+
};
|
| 98 |
+
|
| 99 |
+
return (
|
| 100 |
+
<div>
|
| 101 |
+
<div className="h1"><IcHistory size={22} /> Lịch sử cá nhân</div>
|
| 102 |
+
<p className="subtitle">Lịch sử kết quả làm việc của bạn. Mỗi tool có kết quả riêng, lưu theo thời gian.</p>
|
| 103 |
+
|
| 104 |
+
{/* Drive setup */}
|
| 105 |
+
<div className="card" style={{ marginBottom: 16 }}>
|
| 106 |
+
<div className="flex between center">
|
| 107 |
+
<div className="flex center gap8">
|
| 108 |
+
<IcDrive size={20} />
|
| 109 |
+
<b>Google Drive</b>
|
| 110 |
+
{driveStatus && (
|
| 111 |
+
<span className={`badge ${driveStatus.linked ? "done" : "queued"}`}>
|
| 112 |
+
<span className="dot" /> {driveStatus.linked ? "Đã liên kết" : "Chưa liên kết"}
|
| 113 |
+
</span>
|
| 114 |
+
)}
|
| 115 |
+
</div>
|
| 116 |
+
<div className="flex gap8">
|
| 117 |
+
{driveStatus?.linked ? (
|
| 118 |
+
<button className="btn sm" onClick={removeDrive}><IcTrash size={14} /> Huỷ liên kết</button>
|
| 119 |
+
) : (
|
| 120 |
+
<button className="btn sm primary" onClick={() => setShowDriveSetup(!showDriveSetup)}>
|
| 121 |
+
<IcDrive size={14} /> Liên kết Drive
|
| 122 |
+
</button>
|
| 123 |
+
)}
|
| 124 |
+
</div>
|
| 125 |
+
</div>
|
| 126 |
+
{showDriveSetup && (
|
| 127 |
+
<div className="mt12" style={{ borderTop: "1px solid var(--line)", paddingTop: 12 }}>
|
| 128 |
+
<p className="small muted">Tạo một folder trên Google Drive, share với email <b>tnt-content-bot@tnt-content-ai.iam.gserviceaccount.com</b> (quyền Editor), rồi dán link folder vào đây.</p>
|
| 129 |
+
<div className="flex gap8 mt8">
|
| 130 |
+
<input type="text" style={{ flex: 1 }}
|
| 131 |
+
placeholder="https://drive.google.com/drive/folders/..."
|
| 132 |
+
value={driveLink} onChange={(e) => setDriveLink(e.target.value)} />
|
| 133 |
+
<button className="btn primary" onClick={setupDrive}>Lưu</button>
|
| 134 |
+
</div>
|
| 135 |
+
</div>
|
| 136 |
+
)}
|
| 137 |
+
{!driveStatus?.configured && (
|
| 138 |
+
<div className="small mt8" style={{ color: "var(--orange-700)" }}>
|
| 139 |
+
⚠ Tính năng Drive chưa được cấu hình trên máy chủ (thiếu GOOGLE_DRIVE_SERVICE_ACCOUNT).
|
| 140 |
+
</div>
|
| 141 |
+
)}
|
| 142 |
+
</div>
|
| 143 |
+
|
| 144 |
+
{/* History list */}
|
| 145 |
+
{loading && <div className="small muted">Đang tải lịch sử...</div>}
|
| 146 |
+
|
| 147 |
+
{!hasEntries && !loading && (
|
| 148 |
+
<div className="card muted center" style={{ padding: 40, textAlign: "center" }}>
|
| 149 |
+
<IcHistory size={48} />
|
| 150 |
+
<p className="mt8">Chưa có lịch sử. Sử dụng công cụ để bắt đầu.</p>
|
| 151 |
+
</div>
|
| 152 |
+
)}
|
| 153 |
+
|
| 154 |
+
{hasEntries && groupedTools.map((tool) => (
|
| 155 |
+
<div key={tool} className="card" style={{ marginBottom: 16 }}>
|
| 156 |
+
<div className="panel-title flex center gap8">
|
| 157 |
+
{TOOL_ICONS[tool] ? TOOL_ICONS[tool]({ size: 18 }) : <IcDoc size={18} />}
|
| 158 |
+
{TOOL_LABELS[tool] || tool}
|
| 159 |
+
<span className="badge queued" style={{ marginLeft: 8 }}>{toolEntries[tool].length} kết quả</span>
|
| 160 |
+
</div>
|
| 161 |
+
<div className="stack mt8">
|
| 162 |
+
{toolEntries[tool].map((e) => (
|
| 163 |
+
<div key={e.id} className="filerow" style={{ flexDirection: "column", alignItems: "stretch", gap: 4 }}>
|
| 164 |
+
<div className="flex between center">
|
| 165 |
+
<div>
|
| 166 |
+
<div className="fn">{e.title || "Kết quả"}</div>
|
| 167 |
+
<div className="meta">{formatDate(e.created_at)}</div>
|
| 168 |
+
</div>
|
| 169 |
+
<span className="small muted">{e.summary}</span>
|
| 170 |
+
</div>
|
| 171 |
+
{e.files?.length > 0 && (
|
| 172 |
+
<div className="flex gap8 mt4" style={{ flexWrap: "wrap" }}>
|
| 173 |
+
{e.files.map((f, fi) => (
|
| 174 |
+
<a key={fi} className="btn sm" href={f.path ? fileUrl(`/api/files/${e.session}/${f.name}`) : "#"} download
|
| 175 |
+
style={{ fontSize: 12 }} target="_blank" rel="noreferrer">
|
| 176 |
+
<IcDownload size={12} /> {f.name}
|
| 177 |
+
</a>
|
| 178 |
+
))}
|
| 179 |
+
</div>
|
| 180 |
+
)}
|
| 181 |
+
</div>
|
| 182 |
+
))}
|
| 183 |
+
</div>
|
| 184 |
+
</div>
|
| 185 |
+
))}
|
| 186 |
+
|
| 187 |
+
<div className="flex center mt16">
|
| 188 |
+
<button className="btn" onClick={loadHistory} disabled={loading}>
|
| 189 |
+
<IcRefresh size={16} /> {loading ? "Đang tải..." : "Tải lại"}
|
| 190 |
+
</button>
|
| 191 |
+
</div>
|
| 192 |
+
</div>
|
| 193 |
+
);
|
| 194 |
+
}
|