44 lines
1.6 KiB
Python
44 lines
1.6 KiB
Python
from fastapi import APIRouter, HTTPException, Depends
|
|
from fastapi.responses import StreamingResponse
|
|
from backend.services.youtube import YouTubeService
|
|
import requests
|
|
|
|
router = APIRouter()
|
|
|
|
def get_youtube_service():
|
|
return YouTubeService()
|
|
|
|
@router.get("/stream")
|
|
async def stream_audio(id: str, yt: YouTubeService = Depends(get_youtube_service)):
|
|
try:
|
|
stream_url = yt.get_stream_url(id)
|
|
|
|
def iterfile():
|
|
with requests.get(stream_url, stream=True) as r:
|
|
r.raise_for_status()
|
|
for chunk in r.iter_content(chunk_size=64*1024):
|
|
yield chunk
|
|
|
|
return StreamingResponse(iterfile(), media_type="audio/mpeg")
|
|
except Exception as e:
|
|
print(f"Stream Error: {e}")
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
@router.get("/download")
|
|
async def download_audio(id: str, title: str = "audio", yt: YouTubeService = Depends(get_youtube_service)):
|
|
try:
|
|
stream_url = yt.get_stream_url(id)
|
|
|
|
def iterfile():
|
|
with requests.get(stream_url, stream=True) as r:
|
|
r.raise_for_status()
|
|
for chunk in r.iter_content(chunk_size=1024*1024):
|
|
yield chunk
|
|
|
|
safe_filename = "".join([c for c in title if c.isalnum() or c in (' ', '-', '_')]).strip()
|
|
headers = {
|
|
"Content-Disposition": f'attachment; filename="{safe_filename}.mp3"'
|
|
}
|
|
return StreamingResponse(iterfile(), media_type="audio/mpeg", headers=headers)
|
|
except Exception as e:
|
|
raise HTTPException(status_code=500, detail=str(e))
|