Files
2025-10-31 14:32:42 +11:00

95 lines
2.8 KiB
Python

from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks, Header
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from typing import Optional
import json
from app.db.session import get_db
from app.models.models import DownloadJob, APIKey
from app.schemas.schemas import DownloadJobCreate, DownloadJobResponse
from app.services.search import music_searcher
from app.services.downloader import music_downloader
from app.core.config import settings
import os
from datetime import datetime
# Import the background task processor from auto_download
import sys
sys.path.append(os.path.dirname(__file__))
from auto_download import process_download_job
router = APIRouter()
async def verify_api_key(x_api_key: Optional[str] = Header(None), db: AsyncSession = Depends(get_db)):
"""Verify API key for public v1 endpoints"""
if not x_api_key:
raise HTTPException(status_code=401, detail="API key required")
result = await db.execute(
select(APIKey).where(
APIKey.key == x_api_key,
APIKey.is_active == True
)
)
api_key = result.scalar_one_or_none()
if not api_key:
raise HTTPException(status_code=401, detail="Invalid API key")
# Check expiration
if api_key.expires_at and api_key.expires_at < datetime.utcnow():
raise HTTPException(status_code=401, detail="API key expired")
# Update last used
api_key.last_used_at = datetime.utcnow()
await db.commit()
return api_key
@router.post("/auto-download/job", response_model=DownloadJobResponse)
async def create_download_job_public(
job_data: DownloadJobCreate,
background_tasks: BackgroundTasks,
db: AsyncSession = Depends(get_db),
api_key: APIKey = Depends(verify_api_key)
):
"""
Public API endpoint to create an auto-download job.
Requires API key authentication via X-API-Key header.
"""
# Create new job
new_job = DownloadJob(
song_name=job_data.song_name,
status="pending"
)
db.add(new_job)
await db.commit()
await db.refresh(new_job)
# Start background processing
background_tasks.add_task(process_download_job, new_job.id, db)
return new_job
@router.get("/auto-download/jobs/{job_id}", response_model=DownloadJobResponse)
async def get_download_job_public(
job_id: int,
db: AsyncSession = Depends(get_db),
api_key: APIKey = Depends(verify_api_key)
):
"""
Get status of a download job.
Requires API key authentication via X-API-Key header.
"""
result = await db.execute(select(DownloadJob).where(DownloadJob.id == job_id))
job = result.scalar_one_or_none()
if not job:
raise HTTPException(status_code=404, detail="Job not found")
return job