134 lines
5.8 KiB
Python
134 lines
5.8 KiB
Python
"""Download task routes."""
|
|
import uuid
|
|
import os
|
|
import logging
|
|
from fastapi import APIRouter, HTTPException, Depends, BackgroundTasks
|
|
from fastapi.responses import FileResponse, StreamingResponse
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from sqlalchemy import select
|
|
from app.schemas import DownloadRequest, DownloadResponse, TaskStatus
|
|
from app.database import get_db
|
|
from app.models import Video
|
|
from app.auth import get_current_user, optional_auth
|
|
from app.services.downloader import download_video, get_video_path
|
|
|
|
logger = logging.getLogger(__name__)
|
|
router = APIRouter(prefix="/api", tags=["download"])
|
|
|
|
|
|
async def _do_download(task_id: str, url: str, format_id: str):
|
|
"""Background download task."""
|
|
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()
|
|
if not video:
|
|
return
|
|
try:
|
|
video.status = "downloading"
|
|
await db.commit()
|
|
|
|
def update_progress(pct):
|
|
pass # Progress tracking in sync context is complex; keep simple
|
|
|
|
result = download_video(url, format_id, progress_callback=update_progress)
|
|
video.title = result["title"]
|
|
video.thumbnail = result["thumbnail"]
|
|
video.duration = result["duration"]
|
|
video.filename = result["filename"]
|
|
video.file_path = result["file_path"]
|
|
video.file_size = result["file_size"]
|
|
video.platform = result["platform"]
|
|
video.status = "done"
|
|
video.progress = 100
|
|
await db.commit()
|
|
except Exception as e:
|
|
logger.error(f"Download failed for {task_id}: {e}")
|
|
video.status = "error"
|
|
video.error_message = str(e)[:500]
|
|
await db.commit()
|
|
|
|
|
|
@router.post("/download", response_model=DownloadResponse)
|
|
async def start_download(req: DownloadRequest, background_tasks: BackgroundTasks, db: AsyncSession = Depends(get_db)):
|
|
# Dedup: reuse existing completed download if file still on disk
|
|
existing = (await db.execute(
|
|
select(Video).where(
|
|
Video.url == req.url,
|
|
Video.format_id == req.format_id,
|
|
Video.status == "done",
|
|
).order_by(Video.created_at.desc()).limit(1)
|
|
)).scalar_one_or_none()
|
|
|
|
if existing and os.path.exists(existing.file_path):
|
|
logger.info(f"Reusing existing download task_id={existing.task_id} for url={req.url} format={req.format_id}")
|
|
return DownloadResponse(task_id=existing.task_id, status="done")
|
|
|
|
task_id = str(uuid.uuid4())[:8]
|
|
video = Video(task_id=task_id, url=req.url, quality=req.quality, format_id=req.format_id, status="pending")
|
|
db.add(video)
|
|
await db.commit()
|
|
background_tasks.add_task(_do_download, task_id, req.url, req.format_id)
|
|
return DownloadResponse(task_id=task_id, status="pending")
|
|
|
|
|
|
@router.get("/download/{task_id}", response_model=TaskStatus)
|
|
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")
|
|
return TaskStatus(
|
|
task_id=video.task_id,
|
|
status=video.status,
|
|
progress=video.progress,
|
|
title=video.title,
|
|
error_message=video.error_message or "",
|
|
video_id=video.id if video.status == "done" else None,
|
|
)
|
|
|
|
|
|
@router.get("/file/{video_id}")
|
|
async def download_file(video_id: int, 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()
|
|
if not video or video.status != "done":
|
|
raise HTTPException(status_code=404, detail="Video not found")
|
|
if not os.path.exists(video.file_path):
|
|
raise HTTPException(status_code=404, detail="File not found on disk")
|
|
return FileResponse(video.file_path, filename=video.filename, media_type="video/mp4")
|
|
|
|
|
|
@router.get("/stream/{video_id}")
|
|
async def stream_video(video_id: int, token: str = None, user: dict = Depends(optional_auth), db: AsyncSession = Depends(get_db)):
|
|
# Allow token via query param for video player
|
|
if not user and token:
|
|
from app.auth import verify_token
|
|
user = verify_token(token)
|
|
if not user:
|
|
from fastapi import HTTPException, status
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Authentication required")
|
|
video = (await db.execute(select(Video).where(Video.id == video_id))).scalar_one_or_none()
|
|
if not video or video.status != "done":
|
|
raise HTTPException(status_code=404, detail="Video not found")
|
|
if not os.path.exists(video.file_path):
|
|
raise HTTPException(status_code=404, detail="File not found on disk")
|
|
|
|
def iter_file():
|
|
with open(video.file_path, "rb") as f:
|
|
while chunk := f.read(1024 * 1024):
|
|
yield chunk
|
|
|
|
return StreamingResponse(iter_file(), media_type="video/mp4", headers={
|
|
"Content-Disposition": f"inline; filename={video.filename}",
|
|
"Content-Length": str(video.file_size),
|
|
})
|
|
|
|
|
|
@router.get("/file/task/{task_id}")
|
|
async def download_file_by_task(task_id: str, db: AsyncSession = Depends(get_db)):
|
|
"""Download file by task_id - no auth required (public download)."""
|
|
video = (await db.execute(select(Video).where(Video.task_id == task_id))).scalar_one_or_none()
|
|
if not video or video.status != "done":
|
|
raise HTTPException(status_code=404, detail="Video not found")
|
|
if not os.path.exists(video.file_path):
|
|
raise HTTPException(status_code=404, detail="File not found on disk")
|
|
return FileResponse(video.file_path, filename=video.filename, media_type="video/mp4")
|