Files
stemengine_old/backend/routers_root_backup/subsonic.py
T
2026-03-03 14:52:19 +09:00

112 lines
3.5 KiB
Python
Executable File

"""Subsonic server integration — search, import, and config management."""
import json
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from ..config import SUBSONIC_CONFIG_PATH
from ..services import subsonic_service
router = APIRouter(prefix="/api/subsonic", tags=["subsonic"])
# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------
class SubsonicConfigIn(BaseModel):
url: str
username: str
password: str
@router.get("/config")
def get_config():
"""Return connection status (never exposes the password)."""
if not SUBSONIC_CONFIG_PATH.exists():
return {"configured": False}
try:
cfg = json.loads(SUBSONIC_CONFIG_PATH.read_text())
return {
"configured": True,
"url": cfg.get("url", ""),
"username": cfg.get("username", ""),
}
except Exception:
return {"configured": False}
@router.post("/config")
def save_config(body: SubsonicConfigIn):
"""Validate credentials against the server, then persist them."""
cfg = {"url": body.url, "username": body.username, "password": body.password}
if not subsonic_service.test_connection(cfg):
raise HTTPException(
status_code=400,
detail="Could not connect to Subsonic server — check URL and credentials.",
)
subsonic_service.save_config(cfg)
return {"configured": True, "url": body.url, "username": body.username}
@router.delete("/config")
def remove_config():
"""Remove stored Subsonic credentials."""
subsonic_service.delete_config()
return {"configured": False}
# ---------------------------------------------------------------------------
# Search & Import
# ---------------------------------------------------------------------------
@router.get("/search")
def search(q: str = "", count: int = 20):
"""Search songs on the configured Subsonic server."""
if not q.strip():
return []
try:
return subsonic_service.search_songs(q.strip(), count)
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc))
except Exception as exc:
raise HTTPException(status_code=502, detail=f"Subsonic search failed: {exc}")
class ImportRequest(BaseModel):
id: str
title: str
artist: str = ""
suffix: str = "mp3"
@router.post("/import")
def import_song(req: ImportRequest):
"""Download a Subsonic song to the local imports directory."""
try:
return subsonic_service.import_song(req.id, req.title, req.artist, req.suffix)
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc))
except Exception as exc:
raise HTTPException(status_code=502, detail=f"Import failed: {exc}")
@router.get("/imports")
def list_imports():
"""List all locally imported audio files."""
return subsonic_service.list_imports()
@router.delete("/imports/{filename}")
def delete_import(filename: str):
"""Delete an imported file from the imports directory."""
from ..config import IMPORTS_DIR
# Security: reject any path traversal
if ".." in filename or "/" in filename or "\\" in filename:
raise HTTPException(status_code=400, detail="Invalid filename")
target = IMPORTS_DIR / filename
if not target.exists():
raise HTTPException(status_code=404, detail="File not found")
target.unlink()
return {"detail": f"Deleted {filename}"}