53 lines
1.4 KiB
Python
53 lines
1.4 KiB
Python
from fastapi import FastAPI, Query, HTTPException
|
|
from fastapi.responses import JSONResponse
|
|
import uvicorn
|
|
from downloader import download_song
|
|
from config import settings
|
|
|
|
app = FastAPI(title="Tunedrop")
|
|
|
|
@app.get("/download")
|
|
def download(query: str = Query(..., description="Song name or YouTube search term")):
|
|
try:
|
|
result = download_song(query)
|
|
return JSONResponse(content={"status": "success", **result})
|
|
except Exception as e:
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
# downloader.py
|
|
import subprocess
|
|
import os
|
|
from config import settings
|
|
import uuid
|
|
import requests
|
|
|
|
def download_song(query: str):
|
|
output_template = os.path.join(settings.MUSIC_DIR, "%(title)s.%(ext)s")
|
|
|
|
command = [
|
|
"yt-dlp",
|
|
f"ytsearch1:{query}",
|
|
"--extract-audio",
|
|
"--audio-format", "mp3",
|
|
"--output", output_template
|
|
]
|
|
|
|
result = subprocess.run(command, capture_output=True, text=True)
|
|
|
|
if result.returncode != 0:
|
|
raise Exception(f"Download failed: {result.stderr}")
|
|
|
|
# Optional: trigger navidrome scan
|
|
if settings.NAVIDROME_SCAN_URL:
|
|
try:
|
|
requests.post(settings.NAVIDROME_SCAN_URL, timeout=5)
|
|
except Exception as e:
|
|
pass # non-critical
|
|
|
|
return {
|
|
"query": query,
|
|
"log": result.stdout
|
|
}
|
|
|
|
if __name__ == "__main__":
|
|
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True) |