Files
2026-04-27 17:56:54 +09:00

402 lines
13 KiB
Python
Executable File

"""Subsonic server integration — search, import, and config management."""
import json
from fastapi import APIRouter, HTTPException, Query, Request
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
from ..config import SUBSONIC_CONFIG_PATH
from ..services import subsonic_service
from .. import job_manager as jm
router = APIRouter(prefix="/api/subsonic", tags=["subsonic"])
# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------
class SubsonicConfigIn(BaseModel):
url: str
username: str
password: str
class SubsonicConfigPatchIn(BaseModel):
url: str | None = None
username: str | None = None
password: str | None = None
@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.patch("/config")
def patch_config(body: SubsonicConfigPatchIn):
"""Patch Subsonic config. Keeps existing password when password is omitted/blank."""
current = subsonic_service.load_config()
if not current:
raise HTTPException(
status_code=400,
detail="No existing Subsonic configuration. Use POST /api/subsonic/config first.",
)
next_url = (body.url or current.get("url", "")).strip()
next_username = (body.username or current.get("username", "")).strip()
password_updated = body.password is not None and body.password.strip() != ""
next_password = body.password.strip() if password_updated else current.get("password", "")
if not next_url or not next_username or not next_password:
raise HTTPException(
status_code=400,
detail="Subsonic config requires url, username, and password.",
)
cfg = {"url": next_url, "username": next_username, "password": next_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": next_url,
"username": next_username,
"password_updated": password_updated,
}
@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,
offset: int = 0,
title: str = "",
artist: str = "",
album: str = "",
album_artist: str = "",
):
"""Search songs on the configured Subsonic server."""
try:
return subsonic_service.search_songs(
query=q.strip(),
count=count,
offset=offset,
title=title.strip(),
artist=artist.strip(),
album=album.strip(),
album_artist=album_artist.strip(),
)
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}")
@router.get("/search/grouped")
def search_grouped(
q: str = "",
title: str = "",
artist: str = "",
album: str = "",
album_artist: str = "",
song_count: int = Query(default=8, ge=0, le=50),
album_count: int = Query(default=5, ge=0, le=50),
artist_count: int = Query(default=5, ge=0, le=50),
playlist_count: int = Query(default=5, ge=0, le=50),
):
"""Search grouped Subsonic entities for songs, albums, artists, and playlists."""
try:
return subsonic_service.search_grouped(
query=q.strip(),
title=title.strip(),
artist=artist.strip(),
album=album.strip(),
album_artist=album_artist.strip(),
song_count=song_count,
album_count=album_count,
artist_count=artist_count,
playlist_count=playlist_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 grouped search failed: {exc}")
@router.get("/playlists")
def list_playlists():
"""List playlists from the configured Subsonic server."""
try:
return subsonic_service.list_playlists()
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc))
except Exception as exc:
raise HTTPException(status_code=502, detail=f"Subsonic playlist list failed: {exc}")
@router.get("/playlists/{playlist_id}")
def get_playlist(playlist_id: str):
"""Return playlist metadata and songs for a playlist id."""
try:
return subsonic_service.get_playlist(playlist_id)
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc))
except Exception as exc:
raise HTTPException(status_code=502, detail=f"Subsonic playlist fetch failed: {exc}")
@router.get("/albums")
def list_albums(offset: int = 0, size: int = 50, query: str = "", artist_id: str = ""):
"""List albums from the configured Subsonic server (paged browse)."""
try:
return subsonic_service.list_albums(offset=offset, size=size, query=query.strip(), artist_id=artist_id.strip())
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc))
except Exception as exc:
raise HTTPException(status_code=502, detail=f"Subsonic album list failed: {exc}")
@router.get("/albums/{album_id}")
def get_album(album_id: str):
"""Return album metadata and songs by id."""
try:
return subsonic_service.get_album(album_id)
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc))
except Exception as exc:
raise HTTPException(status_code=502, detail=f"Subsonic album fetch failed: {exc}")
@router.get("/artists")
def list_artists(offset: int = 0, size: int = 200, query: str = ""):
"""List artists from the configured Subsonic server."""
try:
return subsonic_service.list_artists(offset=offset, size=size, query=query.strip())
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc))
except Exception as exc:
raise HTTPException(status_code=502, detail=f"Subsonic artist list failed: {exc}")
@router.get("/artists/{artist_id}")
def get_artist(artist_id: str):
"""Return artist metadata and albums by id."""
try:
return subsonic_service.get_artist(artist_id)
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc))
except Exception as exc:
raise HTTPException(status_code=502, detail=f"Subsonic artist fetch failed: {exc}")
@router.get("/songs/{song_id}")
def get_song(song_id: str):
"""Return a single song by Subsonic id (getSong.view)."""
try:
return subsonic_service.get_song(song_id)
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc))
except Exception as exc:
raise HTTPException(status_code=502, detail=f"Subsonic song fetch failed: {exc}")
@router.get("/songs/{song_id}/similar")
def get_similar_songs(song_id: str, count: int = 5):
"""Return a small list of similar songs for a Subsonic track id."""
try:
return subsonic_service.get_similar_songs(song_id, count=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 similar-song fetch failed: {exc}")
@router.get("/stream/{song_id}")
def stream_song(
song_id: str,
request: Request,
format: str | None = Query(default=None, description="Optional output format hint (e.g. mp3)"),
maxBitRate: int | None = Query(default=None, ge=32, le=512, description="Optional transcode bitrate in kbps"),
):
"""Proxy-stream audio for a Subsonic song id to the browser."""
range_header = request.headers.get('range')
try:
upstream = subsonic_service.stream_song(
song_id,
range_header=range_header,
audio_format=format,
max_bit_rate=maxBitRate,
)
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc))
except Exception as exc:
raise HTTPException(status_code=502, detail=f"Subsonic stream failed: {exc}")
passthrough_headers = {}
for key in ('content-length', 'content-range', 'accept-ranges', 'content-type', 'cache-control'):
val = upstream.headers.get(key)
if val:
passthrough_headers[key] = val
def _iter_content():
try:
for chunk in upstream.iter_content(chunk_size=64 * 1024):
if chunk:
yield chunk
finally:
upstream.close()
return StreamingResponse(
_iter_content(),
status_code=upstream.status_code,
headers=passthrough_headers,
media_type=upstream.headers.get('content-type') or 'audio/mpeg',
)
@router.get("/cover-art/{cover_id}")
def cover_art(cover_id: str, size: int | None = None):
"""Proxy album/track cover art from Subsonic by coverArt id."""
try:
upstream = subsonic_service.cover_art(cover_id, size=size)
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc))
except Exception as exc:
raise HTTPException(status_code=502, detail=f"Subsonic cover art failed: {exc}")
passthrough_headers = {}
for key in ('content-length', 'content-type', 'cache-control', 'etag', 'last-modified'):
val = upstream.headers.get(key)
if val:
passthrough_headers[key] = val
def _iter_content():
try:
for chunk in upstream.iter_content(chunk_size=64 * 1024):
if chunk:
yield chunk
finally:
upstream.close()
return StreamingResponse(
_iter_content(),
status_code=upstream.status_code,
headers=passthrough_headers,
media_type=upstream.headers.get('content-type') or 'image/jpeg',
)
class ImportRequest(BaseModel):
id: str
title: str
artist: str = ""
album_artist: str = ""
album: 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,
album_artist=req.album_artist,
album=req.album,
)
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}")
class YtDlImportRequest(BaseModel):
url: str
title: str = ""
artist: str = ""
@router.post("/import-ytdl")
def import_ytdl(req: YtDlImportRequest):
"""Enqueue a yt-dlp download as a background job; returns the job_id immediately."""
try:
safe_url = subsonic_service.validate_public_ytdl_url(req.url)
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
job_id = jm.create_job("ytdl-import")
jm.update_job(job_id, progress="Queued…")
jm.submit(subsonic_service.run_ytdl_import, job_id, safe_url, req.title, req.artist)
return {"job_id": job_id}
@router.get("/imports")
def list_imports(
query: str = Query(""),
offset: int = Query(0, ge=0),
limit: int = Query(500, ge=1, le=1000),
):
"""List all locally imported audio files."""
return subsonic_service.list_imports(query=query, offset=offset, limit=limit)
@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()
sidecar = target.with_suffix(target.suffix + '.json')
if sidecar.exists():
sidecar.unlink()
return {"detail": f"Deleted {filename}"}