282 lines
9.2 KiB
Python
Executable File
282 lines
9.2 KiB
Python
Executable File
"""
|
|
Subsonic REST API client and local import service.
|
|
|
|
Auth: token-based (md5(password+salt)), salt generated per request.
|
|
Config priority:
|
|
1. MEDIA_DIR/subsonic.json (written by the Settings UI or seed_from_env())
|
|
2. Environment variables SUBSONIC_URL / SUBSONIC_USERNAME / SUBSONIC_PASSWORD
|
|
— on first use these are written to subsonic.json so the UI reflects them.
|
|
|
|
Credential storage:
|
|
The password is never written to disk in plaintext. It is encrypted with
|
|
Fernet (AES-128-CBC + HMAC-SHA256) using a key derived from SECRET_KEY.
|
|
If SECRET_KEY is not set, credentials can still be supplied via environment
|
|
variables but cannot be persisted to disk (the Settings UI will save only
|
|
URL + username and prompt for the password on every restart).
|
|
"""
|
|
import base64
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import secrets
|
|
from pathlib import Path
|
|
from typing import Optional
|
|
|
|
import requests as _requests
|
|
from cryptography.fernet import Fernet, InvalidToken
|
|
|
|
from ..config import SUBSONIC_CONFIG_PATH, IMPORTS_DIR
|
|
|
|
_AUDIO_EXTS = {'.mp3', '.flac', '.wav', '.m4a', '.ogg', '.opus', '.aac'}
|
|
_CLIENT_ID = 'StemEngine'
|
|
_API_VERSION = '1.16.1'
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Encryption helpers
|
|
# ---------------------------------------------------------------------------
|
|
|
|
_fernet: Optional[Fernet] = None
|
|
_fernet_init = False # sentinel: False = derivation not yet attempted
|
|
|
|
|
|
def _get_fernet() -> Optional[Fernet]:
|
|
"""
|
|
Return a Fernet instance keyed by SECRET_KEY, or None if SECRET_KEY is not set.
|
|
Key is derived once via PBKDF2-SHA256 (200k rounds) and cached for the
|
|
process lifetime.
|
|
"""
|
|
global _fernet, _fernet_init
|
|
if _fernet_init:
|
|
return _fernet
|
|
_fernet_init = True
|
|
|
|
raw_key = os.environ.get('SECRET_KEY', '').strip()
|
|
if not raw_key:
|
|
_fernet = None
|
|
return None
|
|
|
|
# Derive a 32-byte key from whatever the user provides
|
|
derived = hashlib.pbkdf2_hmac(
|
|
'sha256', raw_key.encode(), b'stemengine-subsonic', 200_000, dklen=32
|
|
)
|
|
_fernet = Fernet(base64.urlsafe_b64encode(derived))
|
|
return _fernet
|
|
|
|
|
|
def _encrypt(plaintext: str) -> str:
|
|
f = _get_fernet()
|
|
if f is None:
|
|
raise RuntimeError(
|
|
"SECRET_KEY is not set — cannot persist credentials to disk. "
|
|
"Add SECRET_KEY to docker-compose.yml to enable Settings UI credential storage."
|
|
)
|
|
return f.encrypt(plaintext.encode()).decode()
|
|
|
|
|
|
def _decrypt(ciphertext: str) -> str:
|
|
f = _get_fernet()
|
|
if f is None:
|
|
raise RuntimeError(
|
|
"SECRET_KEY is not set — cannot decrypt stored credentials. "
|
|
"Set SECRET_KEY or re-enter credentials via the Settings UI."
|
|
)
|
|
try:
|
|
return f.decrypt(ciphertext.encode()).decode()
|
|
except InvalidToken as exc:
|
|
raise RuntimeError(
|
|
"Credential decryption failed — SECRET_KEY may have changed. "
|
|
"Re-enter credentials via the Settings UI."
|
|
) from exc
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Config helpers
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def _config_from_env() -> Optional[dict]:
|
|
"""Return config from environment variables, or None if not fully set."""
|
|
url = os.environ.get('SUBSONIC_URL', '').strip()
|
|
username = os.environ.get('SUBSONIC_USERNAME', '').strip()
|
|
password = os.environ.get('SUBSONIC_PASSWORD', '').strip()
|
|
if url and username and password:
|
|
return {'url': url, 'username': username, 'password': password}
|
|
return None
|
|
|
|
|
|
def load_config() -> Optional[dict]:
|
|
"""
|
|
Return the active Subsonic config dict (plaintext password ready for use),
|
|
or None if no credentials are available.
|
|
|
|
Handles encrypted-at-rest configs (_enc=True) and the legacy plaintext format.
|
|
"""
|
|
if SUBSONIC_CONFIG_PATH.exists():
|
|
try:
|
|
stored = json.loads(SUBSONIC_CONFIG_PATH.read_text())
|
|
if stored.get('_enc'):
|
|
pwd = _decrypt(stored['password'])
|
|
return {'url': stored['url'], 'username': stored['username'], 'password': pwd}
|
|
else:
|
|
# Legacy plaintext — serve as-is; the UI can re-save to upgrade
|
|
return {k: v for k, v in stored.items() if not k.startswith('_')}
|
|
except RuntimeError:
|
|
raise # Surface decryption / key errors to the caller
|
|
except Exception:
|
|
pass
|
|
|
|
env_cfg = _config_from_env()
|
|
if env_cfg:
|
|
try:
|
|
save_config(env_cfg) # Persist encrypted if SECRET_KEY is available
|
|
except RuntimeError:
|
|
pass # No key — serve from env, don't write to disk
|
|
return env_cfg
|
|
|
|
return None
|
|
|
|
|
|
def save_config(config: dict) -> None:
|
|
"""
|
|
Persist Subsonic config with the password encrypted at rest.
|
|
Raises RuntimeError if SECRET_KEY is not set.
|
|
"""
|
|
stored = {
|
|
'url': config['url'],
|
|
'username': config['username'],
|
|
'password': _encrypt(config['password']),
|
|
'_enc': True,
|
|
}
|
|
SUBSONIC_CONFIG_PATH.write_text(json.dumps(stored, indent=2))
|
|
|
|
|
|
def delete_config() -> None:
|
|
if SUBSONIC_CONFIG_PATH.exists():
|
|
SUBSONIC_CONFIG_PATH.unlink()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Auth / URL helpers
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def _make_token(password: str) -> tuple[str, str]:
|
|
"""Return (token, salt) for Subsonic token auth."""
|
|
salt = secrets.token_hex(8)
|
|
token = hashlib.md5((password + salt).encode()).hexdigest()
|
|
return token, salt
|
|
|
|
|
|
def _params(config: dict) -> dict:
|
|
token, salt = _make_token(config['password'])
|
|
return {
|
|
'u': config['username'],
|
|
't': token,
|
|
's': salt,
|
|
'v': _API_VERSION,
|
|
'c': _CLIENT_ID,
|
|
'f': 'json',
|
|
}
|
|
|
|
|
|
def _url(config: dict, endpoint: str) -> str:
|
|
return f"{config['url'].rstrip('/')}/rest/{endpoint}"
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# API methods
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def test_connection(config: dict) -> bool:
|
|
"""Ping the Subsonic server; return True if auth succeeds."""
|
|
try:
|
|
r = _requests.get(_url(config, 'ping.view'), params=_params(config), timeout=10)
|
|
data = r.json()
|
|
return data.get('subsonic-response', {}).get('status') == 'ok'
|
|
except Exception:
|
|
return False
|
|
|
|
|
|
def search_songs(query: str, count: int = 20) -> list[dict]:
|
|
"""Search for songs by keyword. Returns a list of song dicts."""
|
|
config = load_config()
|
|
if not config:
|
|
raise RuntimeError("Subsonic server not configured")
|
|
|
|
p = _params(config)
|
|
p.update({'query': query, 'songCount': count, 'artistCount': 0, 'albumCount': 0})
|
|
|
|
r = _requests.get(_url(config, 'search3.view'), params=p, timeout=15)
|
|
r.raise_for_status()
|
|
resp = r.json().get('subsonic-response', {})
|
|
|
|
if resp.get('status') != 'ok':
|
|
msg = resp.get('error', {}).get('message', 'Subsonic API error')
|
|
raise RuntimeError(msg)
|
|
|
|
return [
|
|
{
|
|
'id': s.get('id', ''),
|
|
'title': s.get('title', 'Unknown'),
|
|
'artist': s.get('artist', ''),
|
|
'album': s.get('album', ''),
|
|
'duration': s.get('duration', 0),
|
|
'suffix': s.get('suffix', 'mp3'),
|
|
'size': s.get('size', 0),
|
|
'bitRate': s.get('bitRate', 0),
|
|
}
|
|
for s in resp.get('searchResult3', {}).get('song', [])
|
|
]
|
|
|
|
|
|
def import_song(song_id: str, title: str, artist: str = '', suffix: str = 'mp3') -> dict:
|
|
"""Download a Subsonic song to IMPORTS_DIR."""
|
|
config = load_config()
|
|
if not config:
|
|
raise RuntimeError("Subsonic server not configured")
|
|
|
|
def _safe(s: str) -> str:
|
|
return "".join(c for c in s if c.isalnum() or c in ' -_().').strip()
|
|
|
|
safe_title = _safe(title) or 'Unknown'
|
|
safe_artist = _safe(artist)
|
|
base_name = f"{safe_artist} - {safe_title}" if safe_artist else safe_title
|
|
dest = IMPORTS_DIR / f"{base_name}.{suffix}"
|
|
|
|
counter = 1
|
|
while dest.exists():
|
|
dest = IMPORTS_DIR / f"{base_name} ({counter}).{suffix}"
|
|
counter += 1
|
|
|
|
p = _params(config)
|
|
p['id'] = song_id
|
|
|
|
r = _requests.get(_url(config, 'stream.view'), params=p, stream=True, timeout=120)
|
|
r.raise_for_status()
|
|
|
|
with open(dest, 'wb') as f:
|
|
for chunk in r.iter_content(chunk_size=65536):
|
|
if chunk:
|
|
f.write(chunk)
|
|
|
|
return {
|
|
'filename': dest.name,
|
|
'path': str(dest),
|
|
'size': dest.stat().st_size,
|
|
'title': title,
|
|
'artist': artist,
|
|
}
|
|
|
|
|
|
def list_imports() -> list[dict]:
|
|
"""Return metadata for all audio files in IMPORTS_DIR, newest first."""
|
|
if not IMPORTS_DIR.exists():
|
|
return []
|
|
results = []
|
|
for f in sorted(IMPORTS_DIR.iterdir(), key=lambda x: x.stat().st_mtime, reverse=True):
|
|
if f.is_file() and f.suffix.lower() in _AUDIO_EXTS:
|
|
results.append({
|
|
'filename': f.name,
|
|
'path': str(f),
|
|
'size': f.stat().st_size,
|
|
})
|
|
return results
|