feat: real-time download progress, cancel support, admin auto-poll
This commit is contained in:
@@ -12,7 +12,10 @@ from app.schemas import DownloadRequest, DownloadResponse, TaskStatus
|
||||
from app.database import get_db, async_session
|
||||
from app.models import Video, DownloadLog
|
||||
from app.auth import get_current_user, optional_auth
|
||||
from app.services.downloader import download_video, get_video_path, detect_platform
|
||||
from app.services.downloader import (
|
||||
download_video, get_video_path, detect_platform,
|
||||
register_task, get_progress, request_cancel, cleanup_task,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter(prefix="/api", tags=["download"])
|
||||
@@ -107,7 +110,7 @@ async def _log_download(video_id: int, request: Request):
|
||||
|
||||
|
||||
async def _do_download(task_id: str, url: str, format_id: str):
|
||||
"""Background download task."""
|
||||
"""Background download task with real-time progress and cancel support."""
|
||||
from app.database import async_session
|
||||
async with async_session() as db:
|
||||
video = (await db.execute(select(Video).where(Video.task_id == task_id))).scalar_one_or_none()
|
||||
@@ -117,10 +120,9 @@ async def _do_download(task_id: str, url: str, format_id: str):
|
||||
video.status = "downloading"
|
||||
await db.commit()
|
||||
|
||||
def update_progress(pct):
|
||||
pass # Progress tracking in sync context is complex; keep simple
|
||||
register_task(task_id)
|
||||
result = download_video(url, format_id, task_id=task_id)
|
||||
|
||||
result = download_video(url, format_id, progress_callback=update_progress)
|
||||
video.title = result["title"]
|
||||
video.thumbnail = result["thumbnail"]
|
||||
video.duration = result["duration"]
|
||||
@@ -133,9 +135,13 @@ async def _do_download(task_id: str, url: str, format_id: str):
|
||||
await db.commit()
|
||||
except Exception as e:
|
||||
logger.error(f"Download failed for {task_id}: {e}")
|
||||
is_cancel = "Cancelled" in str(e) or "DownloadCancelled" in type(e).__name__
|
||||
video.status = "error"
|
||||
video.error_message = str(e)[:500]
|
||||
video.error_message = "下载已取消,请重试" if is_cancel else str(e)[:500]
|
||||
video.progress = 0
|
||||
await db.commit()
|
||||
finally:
|
||||
cleanup_task(task_id)
|
||||
|
||||
|
||||
@router.post("/download", response_model=DownloadResponse)
|
||||
@@ -167,16 +173,29 @@ async def get_download_status(task_id: str, db: AsyncSession = Depends(get_db)):
|
||||
video = (await db.execute(select(Video).where(Video.task_id == task_id))).scalar_one_or_none()
|
||||
if not video:
|
||||
raise HTTPException(status_code=404, detail="Task not found")
|
||||
# Inject real-time progress for active downloads
|
||||
progress = get_progress(task_id) if video.status == "downloading" else video.progress
|
||||
return TaskStatus(
|
||||
task_id=video.task_id,
|
||||
status=video.status,
|
||||
progress=video.progress,
|
||||
progress=progress,
|
||||
title=video.title,
|
||||
error_message=video.error_message or "",
|
||||
video_id=video.id if video.status == "done" else None,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/download/{task_id}/cancel")
|
||||
async def cancel_download(task_id: str, db: AsyncSession = Depends(get_db)):
|
||||
video = (await db.execute(select(Video).where(Video.task_id == task_id))).scalar_one_or_none()
|
||||
if not video:
|
||||
raise HTTPException(status_code=404, detail="Task not found")
|
||||
if video.status != "downloading":
|
||||
raise HTTPException(status_code=400, detail="Task is not downloading")
|
||||
request_cancel(task_id)
|
||||
return {"ok": True, "message": "Cancel requested"}
|
||||
|
||||
|
||||
@router.get("/file/{video_id}")
|
||||
async def download_file(video_id: int, request: Request, background_tasks: BackgroundTasks, user: dict = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
|
||||
video = (await db.execute(select(Video).where(Video.id == video_id))).scalar_one_or_none()
|
||||
|
||||
Reference in New Issue
Block a user