1160 lines
40 KiB
Python
Executable File
1160 lines
40 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 ipaddress
|
|
import json
|
|
import os
|
|
import secrets
|
|
import socket
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
from typing import Optional
|
|
from urllib.parse import urlsplit
|
|
|
|
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'}
|
|
_VIDEO_EXTS = {'.mp4', '.mkv', '.webm', '.mov', '.m4v'}
|
|
_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 Exception:
|
|
pass # If disk write fails, still serve from env
|
|
return env_cfg
|
|
|
|
return None
|
|
|
|
|
|
def save_config(config: dict) -> None:
|
|
"""
|
|
Persist Subsonic config with the password encrypted at rest.
|
|
If SECRET_KEY is not set, saves as plaintext (which will be purged on startup).
|
|
"""
|
|
f = _get_fernet()
|
|
if f:
|
|
# Encrypt if SECRET_KEY is available
|
|
stored = {
|
|
'url': config['url'],
|
|
'username': config['username'],
|
|
'password': _encrypt(config['password']),
|
|
'_enc': True,
|
|
}
|
|
else:
|
|
# Fallback to plaintext if no SECRET_KEY (deprecated, will be purged on startup)
|
|
stored = {
|
|
'url': config['url'],
|
|
'username': config['username'],
|
|
'password': config['password'],
|
|
'_enc': False,
|
|
}
|
|
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 _contains(haystack: str, needle: str) -> bool:
|
|
return needle.strip().lower() in (haystack or '').lower()
|
|
|
|
|
|
def _normalize_search_text(value: str) -> str:
|
|
collapsed = []
|
|
last_was_space = False
|
|
for char in (value or '').casefold():
|
|
if char.isalnum():
|
|
collapsed.append(char)
|
|
last_was_space = False
|
|
continue
|
|
if not last_was_space:
|
|
collapsed.append(' ')
|
|
last_was_space = True
|
|
return ''.join(collapsed).strip()
|
|
|
|
|
|
def _rank_search_match(value: str, query: str) -> int | None:
|
|
normalized_value = _normalize_search_text(value)
|
|
normalized_query = _normalize_search_text(query)
|
|
if not normalized_query:
|
|
return 3
|
|
if not normalized_value:
|
|
return None
|
|
if normalized_value == normalized_query:
|
|
return 0
|
|
if normalized_value.startswith(normalized_query):
|
|
return 1
|
|
if normalized_query in normalized_value:
|
|
return 2
|
|
return None
|
|
|
|
|
|
def _best_rank(item: dict, fields: list[str], query: str) -> int | None:
|
|
ranks = [_rank_search_match(str(item.get(field) or ''), query) for field in fields]
|
|
matched = [rank for rank in ranks if rank is not None]
|
|
return min(matched) if matched else None
|
|
|
|
|
|
def _sort_ranked(items: list[dict], fields: list[str], query: str, limit: int) -> list[dict]:
|
|
if limit <= 0:
|
|
return []
|
|
decorated = []
|
|
for item in items:
|
|
rank = _best_rank(item, fields, query)
|
|
if rank is None:
|
|
continue
|
|
label = ' '.join(str(item.get(field) or '') for field in fields)
|
|
decorated.append((rank, _normalize_search_text(label), item))
|
|
decorated.sort(key=lambda row: (row[0], row[1]))
|
|
return [item for _, _, item in decorated[:limit]]
|
|
|
|
|
|
def _as_list(value) -> list:
|
|
if isinstance(value, list):
|
|
return value
|
|
if isinstance(value, dict):
|
|
return [value]
|
|
return []
|
|
|
|
|
|
def _normalize_album_summary(album: dict) -> dict:
|
|
return {
|
|
'id': album.get('id', ''),
|
|
'name': album.get('name', 'Unknown Album'),
|
|
'artist': album.get('artist', 'Unknown Artist'),
|
|
'songCount': int(album.get('songCount') or 0),
|
|
'duration': int(album.get('duration') or 0),
|
|
'year': int(album.get('year') or 0) if album.get('year') else None,
|
|
'coverArt': album.get('coverArt', ''),
|
|
}
|
|
|
|
|
|
def _normalize_artist_summary(artist: dict) -> dict:
|
|
return {
|
|
'id': artist.get('id', ''),
|
|
'name': artist.get('name', 'Unknown Artist'),
|
|
'albumCount': int(artist.get('albumCount') or 0),
|
|
}
|
|
|
|
|
|
def _normalize_playlist_summary(item: dict) -> dict:
|
|
return {
|
|
'id': item.get('id', ''),
|
|
'name': item.get('name', 'Untitled Playlist'),
|
|
'songCount': int(item.get('songCount') or 0),
|
|
'duration': int(item.get('duration') or 0),
|
|
'public': bool(item.get('public', False)),
|
|
'owner': item.get('owner', ''),
|
|
'created': item.get('created', ''),
|
|
'changed': item.get('changed', ''),
|
|
}
|
|
|
|
|
|
def _safe_filename(value: str) -> str:
|
|
return "".join(c for c in value if c.isalnum() or c in ' -_().[]').strip()
|
|
|
|
|
|
def validate_public_ytdl_url(url: str) -> str:
|
|
"""Validate yt-dlp URL target and reject private/internal SSRF destinations."""
|
|
cleaned = (url or "").strip()
|
|
parsed = urlsplit(cleaned)
|
|
|
|
if parsed.scheme not in {"http", "https"}:
|
|
raise RuntimeError("A valid http(s) URL is required")
|
|
|
|
host = (parsed.hostname or "").strip()
|
|
if not host:
|
|
raise RuntimeError("URL must include a hostname")
|
|
|
|
# Reject obvious internal hostnames (Docker/K8s/local aliases).
|
|
if "." not in host and not host.replace(":", "").isdigit():
|
|
raise RuntimeError("URL host must be a public DNS hostname")
|
|
|
|
blocked_reasons = []
|
|
try:
|
|
addr_info = socket.getaddrinfo(host, None, type=socket.SOCK_STREAM)
|
|
except socket.gaierror as exc:
|
|
raise RuntimeError(f"Unable to resolve URL hostname: {host}") from exc
|
|
|
|
for entry in addr_info:
|
|
addr = entry[4][0]
|
|
ip = ipaddress.ip_address(addr)
|
|
if ip.is_private:
|
|
blocked_reasons.append(f"private address {ip}")
|
|
elif ip.is_loopback:
|
|
blocked_reasons.append(f"loopback address {ip}")
|
|
elif ip.is_link_local:
|
|
blocked_reasons.append(f"link-local address {ip}")
|
|
elif ip.is_multicast:
|
|
blocked_reasons.append(f"multicast address {ip}")
|
|
elif ip.is_unspecified:
|
|
blocked_reasons.append(f"unspecified address {ip}")
|
|
elif ip.is_reserved:
|
|
blocked_reasons.append(f"reserved address {ip}")
|
|
|
|
if blocked_reasons:
|
|
raise RuntimeError("Blocked URL target: " + ", ".join(sorted(set(blocked_reasons))))
|
|
|
|
return cleaned
|
|
|
|
|
|
def _sidecar_path(media_path: Path) -> Path:
|
|
return media_path.with_suffix(media_path.suffix + '.json')
|
|
|
|
|
|
def _write_import_metadata(media_path: Path, payload: dict) -> None:
|
|
data = {
|
|
**payload,
|
|
'filename': media_path.name,
|
|
'path': str(media_path),
|
|
'updated_at': datetime.now(timezone.utc).isoformat(),
|
|
}
|
|
_sidecar_path(media_path).write_text(json.dumps(data, indent=2), encoding='utf-8')
|
|
|
|
|
|
def _read_import_metadata(media_path: Path) -> dict:
|
|
sidecar = _sidecar_path(media_path)
|
|
if not sidecar.exists():
|
|
return {}
|
|
try:
|
|
raw = json.loads(sidecar.read_text(encoding='utf-8'))
|
|
return raw if isinstance(raw, dict) else {}
|
|
except Exception:
|
|
return {}
|
|
|
|
|
|
def search_songs(
|
|
query: str = '',
|
|
count: int = 20,
|
|
offset: int = 0,
|
|
*,
|
|
title: str = '',
|
|
artist: str = '',
|
|
album: str = '',
|
|
album_artist: str = '',
|
|
) -> list[dict]:
|
|
"""Search songs with optional structured filters.
|
|
|
|
The returned `artist` field prefers Subsonic `albumArtist` over `artist`.
|
|
"""
|
|
config = load_config()
|
|
if not config:
|
|
raise RuntimeError("Subsonic server not configured")
|
|
|
|
effective_query = query.strip() or " ".join(
|
|
x for x in [title.strip(), artist.strip(), album.strip(), album_artist.strip()] if x
|
|
)
|
|
if not effective_query:
|
|
# Browsing mode fallback when no explicit query is provided.
|
|
# Most Subsonic-compatible servers accept '*' as wildcard for search3.
|
|
effective_query = '*'
|
|
|
|
p = _params(config)
|
|
# Over-fetch and post-filter so advanced fields (title/album/albumArtist)
|
|
# behave predictably across Subsonic-compatible servers.
|
|
fetch_count = min(max(int(count or 20) * 3, int(count or 20), 20), 250)
|
|
p.update({
|
|
'query': effective_query,
|
|
'songCount': fetch_count,
|
|
'songOffset': max(0, int(offset or 0)),
|
|
'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)
|
|
|
|
songs = []
|
|
for s in resp.get('searchResult3', {}).get('song', []):
|
|
song_title = s.get('title', 'Unknown')
|
|
song_artist = s.get('artist', '')
|
|
song_album_artist = s.get('albumArtist', '')
|
|
song_album = s.get('album', '')
|
|
|
|
if title and not _contains(song_title, title):
|
|
continue
|
|
if artist and not _contains(song_artist, artist) and not _contains(song_album_artist, artist):
|
|
continue
|
|
if album and not _contains(song_album, album):
|
|
continue
|
|
if album_artist and not _contains(song_album_artist, album_artist):
|
|
continue
|
|
|
|
display_artist = song_album_artist or song_artist
|
|
songs.append({
|
|
'id': s.get('id', ''),
|
|
'title': song_title,
|
|
'artist': display_artist,
|
|
'songArtist': song_artist,
|
|
'albumArtist': song_album_artist,
|
|
'album': song_album,
|
|
'coverArt': s.get('coverArt', ''),
|
|
'year': int(s.get('year') or 0) if s.get('year') else None,
|
|
'genre': s.get('genre', ''),
|
|
'track': int(s.get('track') or 0) if s.get('track') else None,
|
|
'duration': s.get('duration', 0),
|
|
'suffix': s.get('suffix', 'mp3'),
|
|
'size': s.get('size', 0),
|
|
'bitRate': s.get('bitRate', 0),
|
|
})
|
|
|
|
return songs[: max(1, int(count or 20))]
|
|
|
|
|
|
def search_grouped(
|
|
query: str = '',
|
|
*,
|
|
title: str = '',
|
|
artist: str = '',
|
|
album: str = '',
|
|
album_artist: str = '',
|
|
song_count: int = 8,
|
|
album_count: int = 5,
|
|
artist_count: int = 5,
|
|
playlist_count: int = 5,
|
|
) -> dict:
|
|
"""Search grouped Subsonic entities with deterministic client-friendly ranking."""
|
|
config = load_config()
|
|
if not config:
|
|
raise RuntimeError("Subsonic server not configured")
|
|
|
|
requested_song_count = max(0, min(int(song_count or 0), 50))
|
|
requested_album_count = max(0, min(int(album_count or 0), 50))
|
|
requested_artist_count = max(0, min(int(artist_count or 0), 50))
|
|
requested_playlist_count = max(0, min(int(playlist_count or 0), 50))
|
|
|
|
effective_query = query.strip() or " ".join(
|
|
value for value in [title.strip(), artist.strip(), album.strip(), album_artist.strip()] if value
|
|
)
|
|
if not effective_query:
|
|
effective_query = '*'
|
|
|
|
overfetch_song_count = min(max(requested_song_count * 3, requested_song_count, 20), 250) if requested_song_count else 0
|
|
overfetch_album_count = min(max(requested_album_count * 3, requested_album_count, 15), 100) if requested_album_count else 0
|
|
overfetch_artist_count = min(max(requested_artist_count * 3, requested_artist_count, 15), 100) if requested_artist_count else 0
|
|
|
|
grouped_results = {
|
|
'songs': [],
|
|
'albums': [],
|
|
'artists': [],
|
|
'playlists': [],
|
|
}
|
|
|
|
if requested_song_count or requested_album_count or requested_artist_count:
|
|
p = _params(config)
|
|
p.update({
|
|
'query': effective_query,
|
|
'songCount': overfetch_song_count,
|
|
'songOffset': 0,
|
|
'albumCount': overfetch_album_count,
|
|
'artistCount': overfetch_artist_count,
|
|
})
|
|
|
|
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)
|
|
|
|
payload = resp.get('searchResult3', {})
|
|
|
|
if requested_song_count:
|
|
songs = []
|
|
for song in _as_list(payload.get('song')):
|
|
normalized_song = _normalize_song(song)
|
|
if not normalized_song.get('id'):
|
|
continue
|
|
if title and not _contains(normalized_song['title'], title):
|
|
continue
|
|
if artist and not _contains(normalized_song['songArtist'], artist) and not _contains(normalized_song['albumArtist'], artist):
|
|
continue
|
|
if album and not _contains(normalized_song['album'], album):
|
|
continue
|
|
if album_artist and not _contains(normalized_song['albumArtist'], album_artist):
|
|
continue
|
|
songs.append(normalized_song)
|
|
song_query = query.strip() or title.strip() or artist.strip() or album.strip() or album_artist.strip()
|
|
grouped_results['songs'] = _sort_ranked(songs, ['title', 'songArtist', 'albumArtist', 'album'], song_query, requested_song_count)
|
|
|
|
if requested_album_count:
|
|
albums = []
|
|
for album_item in _as_list(payload.get('album')):
|
|
normalized_album = _normalize_album_summary(album_item)
|
|
if not normalized_album.get('id') or not normalized_album.get('name'):
|
|
continue
|
|
if album and not _contains(normalized_album['name'], album):
|
|
continue
|
|
if artist and not _contains(normalized_album['artist'], artist):
|
|
continue
|
|
albums.append(normalized_album)
|
|
album_query = album.strip() or query.strip() or artist.strip()
|
|
grouped_results['albums'] = _sort_ranked(albums, ['name', 'artist'], album_query, requested_album_count)
|
|
|
|
if requested_artist_count:
|
|
artists = []
|
|
for artist_item in _as_list(payload.get('artist')):
|
|
normalized_artist = _normalize_artist_summary(artist_item)
|
|
if not normalized_artist.get('id') or not normalized_artist.get('name'):
|
|
continue
|
|
if artist and not _contains(normalized_artist['name'], artist):
|
|
continue
|
|
artists.append(normalized_artist)
|
|
artist_query = artist.strip() or query.strip()
|
|
grouped_results['artists'] = _sort_ranked(artists, ['name'], artist_query, requested_artist_count)
|
|
|
|
if requested_playlist_count:
|
|
playlists = list_playlists()
|
|
playlist_query = query.strip() or title.strip() or artist.strip() or album.strip() or album_artist.strip()
|
|
grouped_results['playlists'] = _sort_ranked(
|
|
[playlist for playlist in playlists if playlist.get('id') and playlist.get('name')],
|
|
['name', 'owner'],
|
|
playlist_query,
|
|
requested_playlist_count,
|
|
)
|
|
|
|
return grouped_results
|
|
|
|
|
|
def get_song(song_id: str) -> dict:
|
|
"""Fetch a single song by ID using Subsonic getSong.view."""
|
|
config = load_config()
|
|
if not config:
|
|
raise RuntimeError("Subsonic server not configured")
|
|
|
|
p = _params(config)
|
|
p['id'] = song_id
|
|
r = _requests.get(_url(config, 'getSong.view'), params=p, timeout=10)
|
|
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)
|
|
|
|
song = resp.get('song')
|
|
if not song:
|
|
raise RuntimeError(f"Song not found: {song_id}")
|
|
return _normalize_song(song)
|
|
|
|
|
|
def get_similar_songs(song_id: str, count: int = 5) -> list[dict]:
|
|
"""Fetch similar songs for a given track using Subsonic getSimilarSongs2.view."""
|
|
config = load_config()
|
|
if not config:
|
|
raise RuntimeError("Subsonic server not configured")
|
|
|
|
p = _params(config)
|
|
p['id'] = song_id
|
|
p['count'] = max(1, min(int(count or 5), 20))
|
|
r = _requests.get(_url(config, 'getSimilarSongs2.view'), params=p, timeout=20)
|
|
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)
|
|
|
|
songs = resp.get('similarSongs2', {}).get('song', []) or []
|
|
if isinstance(songs, dict):
|
|
songs = [songs]
|
|
return [_normalize_song(song) for song in songs][: p['count']]
|
|
|
|
|
|
def list_playlists() -> list[dict]:
|
|
"""Return playlists from Subsonic server."""
|
|
config = load_config()
|
|
if not config:
|
|
raise RuntimeError("Subsonic server not configured")
|
|
|
|
p = _params(config)
|
|
r = _requests.get(_url(config, 'getPlaylists.view'), params=p, timeout=20)
|
|
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)
|
|
|
|
playlists = resp.get('playlists', {}).get('playlist', []) or []
|
|
return [_normalize_playlist_summary(item) for item in playlists]
|
|
|
|
|
|
def get_playlist(playlist_id: str) -> dict:
|
|
"""Return playlist details with songs."""
|
|
config = load_config()
|
|
if not config:
|
|
raise RuntimeError("Subsonic server not configured")
|
|
|
|
p = _params(config)
|
|
p['id'] = playlist_id
|
|
r = _requests.get(_url(config, 'getPlaylist.view'), params=p, timeout=20)
|
|
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)
|
|
|
|
playlist = resp.get('playlist') or {}
|
|
entries = playlist.get('entry') or []
|
|
|
|
songs = []
|
|
for s in entries:
|
|
song_artist = s.get('artist', '')
|
|
song_album_artist = s.get('albumArtist', '')
|
|
songs.append({
|
|
'id': s.get('id', ''),
|
|
'title': s.get('title', 'Unknown'),
|
|
'artist': song_album_artist or song_artist,
|
|
'songArtist': song_artist,
|
|
'albumArtist': song_album_artist,
|
|
'album': s.get('album', ''),
|
|
'coverArt': s.get('coverArt', ''),
|
|
'year': int(s.get('year') or 0) if s.get('year') else None,
|
|
'genre': s.get('genre', ''),
|
|
'track': int(s.get('track') or 0) if s.get('track') else None,
|
|
'duration': int(s.get('duration') or 0),
|
|
'suffix': s.get('suffix', 'mp3'),
|
|
'size': int(s.get('size') or 0),
|
|
'bitRate': int(s.get('bitRate') or 0),
|
|
})
|
|
|
|
return {
|
|
'id': playlist.get('id', ''),
|
|
'name': playlist.get('name', 'Untitled Playlist'),
|
|
'songCount': int(playlist.get('songCount') or len(songs)),
|
|
'duration': int(playlist.get('duration') or 0),
|
|
'public': bool(playlist.get('public', False)),
|
|
'owner': playlist.get('owner', ''),
|
|
'created': playlist.get('created', ''),
|
|
'changed': playlist.get('changed', ''),
|
|
'songs': songs,
|
|
}
|
|
|
|
|
|
def _normalize_song(s: dict) -> dict:
|
|
song_artist = s.get('artist', '')
|
|
song_album_artist = s.get('albumArtist', '')
|
|
return {
|
|
'id': s.get('id', ''),
|
|
'title': s.get('title', 'Unknown'),
|
|
'artist': song_album_artist or song_artist,
|
|
'songArtist': song_artist,
|
|
'albumArtist': song_album_artist,
|
|
'album': s.get('album', ''),
|
|
'coverArt': s.get('coverArt', ''),
|
|
'year': int(s.get('year') or 0) if s.get('year') else None,
|
|
'genre': s.get('genre', ''),
|
|
'track': int(s.get('track') or 0) if s.get('track') else None,
|
|
'duration': int(s.get('duration') or 0),
|
|
'suffix': s.get('suffix', 'mp3'),
|
|
'size': int(s.get('size') or 0),
|
|
'bitRate': int(s.get('bitRate') or 0),
|
|
}
|
|
|
|
|
|
def list_albums(offset: int = 0, size: int = 50, query: str = '', artist_id: str = '') -> list[dict]:
|
|
"""Return paged album browse results from Subsonic server."""
|
|
config = load_config()
|
|
if not config:
|
|
raise RuntimeError("Subsonic server not configured")
|
|
|
|
p = _params(config)
|
|
p.update({
|
|
'type': 'alphabeticalByName',
|
|
'size': max(1, min(int(size or 50), 500)),
|
|
'offset': max(0, int(offset or 0)),
|
|
})
|
|
if artist_id:
|
|
p['artistId'] = artist_id
|
|
|
|
r = _requests.get(_url(config, 'getAlbumList2.view'), params=p, timeout=20)
|
|
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)
|
|
|
|
albums = resp.get('albumList2', {}).get('album', []) or []
|
|
q = (query or '').strip().lower()
|
|
|
|
results = []
|
|
for album in albums:
|
|
title = album.get('name', 'Unknown Album')
|
|
artist = album.get('artist', 'Unknown Artist')
|
|
if q and q not in title.lower() and q not in artist.lower():
|
|
continue
|
|
results.append({
|
|
'id': album.get('id', ''),
|
|
'name': title,
|
|
'artist': artist,
|
|
'songCount': int(album.get('songCount') or 0),
|
|
'duration': int(album.get('duration') or 0),
|
|
'year': int(album.get('year') or 0) if album.get('year') else None,
|
|
'coverArt': album.get('coverArt', ''),
|
|
})
|
|
return results
|
|
|
|
|
|
def get_album(album_id: str) -> dict:
|
|
"""Return album details with tracks."""
|
|
config = load_config()
|
|
if not config:
|
|
raise RuntimeError("Subsonic server not configured")
|
|
|
|
p = _params(config)
|
|
p['id'] = album_id
|
|
r = _requests.get(_url(config, 'getAlbum.view'), params=p, timeout=20)
|
|
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)
|
|
|
|
album = resp.get('album') or {}
|
|
songs = [_normalize_song(s) for s in (album.get('song') or [])]
|
|
|
|
return {
|
|
'id': album.get('id', ''),
|
|
'name': album.get('name', 'Unknown Album'),
|
|
'artist': album.get('artist', 'Unknown Artist'),
|
|
'songCount': int(album.get('songCount') or len(songs)),
|
|
'duration': int(album.get('duration') or 0),
|
|
'year': int(album.get('year') or 0) if album.get('year') else None,
|
|
'coverArt': album.get('coverArt', ''),
|
|
'songs': songs,
|
|
}
|
|
|
|
|
|
def list_artists(offset: int = 0, size: int = 200, query: str = '') -> list[dict]:
|
|
"""Return artist browse results from Subsonic server.
|
|
|
|
Subsonic `getArtists` is index-based (non-paged), so pagination is applied
|
|
in-process after flattening.
|
|
"""
|
|
config = load_config()
|
|
if not config:
|
|
raise RuntimeError("Subsonic server not configured")
|
|
|
|
p = _params(config)
|
|
r = _requests.get(_url(config, 'getArtists.view'), params=p, timeout=20)
|
|
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)
|
|
|
|
flat = []
|
|
for bucket in (resp.get('artists', {}).get('index', []) or []):
|
|
for artist in (bucket.get('artist', []) or []):
|
|
flat.append({
|
|
'id': artist.get('id', ''),
|
|
'name': artist.get('name', 'Unknown Artist'),
|
|
'albumCount': int(artist.get('albumCount') or 0),
|
|
})
|
|
|
|
q = (query or '').strip().lower()
|
|
if q:
|
|
flat = [a for a in flat if q in a['name'].lower()]
|
|
|
|
start = max(0, int(offset or 0))
|
|
end = start + max(1, min(int(size or 200), 1000))
|
|
return flat[start:end]
|
|
|
|
|
|
def get_artist(artist_id: str) -> dict:
|
|
"""Return artist details including albums."""
|
|
config = load_config()
|
|
if not config:
|
|
raise RuntimeError("Subsonic server not configured")
|
|
|
|
p = _params(config)
|
|
p['id'] = artist_id
|
|
r = _requests.get(_url(config, 'getArtist.view'), params=p, timeout=20)
|
|
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)
|
|
|
|
artist = resp.get('artist') or {}
|
|
albums = []
|
|
for album in (artist.get('album') or []):
|
|
albums.append({
|
|
'id': album.get('id', ''),
|
|
'name': album.get('name', 'Unknown Album'),
|
|
'artist': album.get('artist', artist.get('name', 'Unknown Artist')),
|
|
'songCount': int(album.get('songCount') or 0),
|
|
'duration': int(album.get('duration') or 0),
|
|
'year': int(album.get('year') or 0) if album.get('year') else None,
|
|
'coverArt': album.get('coverArt', ''),
|
|
})
|
|
|
|
normalized_artist = _normalize_artist_summary(artist)
|
|
normalized_artist['albumCount'] = int(artist.get('albumCount') or len(albums))
|
|
normalized_artist['albums'] = albums
|
|
return normalized_artist
|
|
|
|
|
|
def import_song(
|
|
song_id: str,
|
|
title: str,
|
|
artist: str = '',
|
|
suffix: str = 'mp3',
|
|
*,
|
|
album_artist: str = '',
|
|
album: str = '',
|
|
) -> dict:
|
|
"""Download a Subsonic song to IMPORTS_DIR."""
|
|
config = load_config()
|
|
if not config:
|
|
raise RuntimeError("Subsonic server not configured")
|
|
|
|
safe_title = _safe_filename(title) or 'Unknown'
|
|
effective_artist = (album_artist or artist or '').strip()
|
|
safe_artist = _safe_filename(effective_artist)
|
|
base_name = f"{safe_artist} - {safe_title}" if safe_artist else safe_title
|
|
clean_suffix = "".join(c for c in (suffix or 'mp3').lower() if c.isalnum()) or 'mp3'
|
|
dest = IMPORTS_DIR / f"{base_name}.{clean_suffix}"
|
|
|
|
counter = 1
|
|
while dest.exists():
|
|
dest = IMPORTS_DIR / f"{base_name} ({counter}).{clean_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)
|
|
|
|
_write_import_metadata(dest, {
|
|
'source': 'subsonic',
|
|
'id': song_id,
|
|
'title': title,
|
|
'artist': effective_artist,
|
|
'song_artist': artist,
|
|
'album_artist': album_artist,
|
|
'album': album,
|
|
'suffix': clean_suffix,
|
|
})
|
|
|
|
return {
|
|
'filename': dest.name,
|
|
'path': str(dest),
|
|
'size': dest.stat().st_size,
|
|
'title': title,
|
|
'artist': effective_artist,
|
|
'song_artist': artist,
|
|
'album_artist': album_artist,
|
|
'album': album,
|
|
'source': 'subsonic',
|
|
}
|
|
|
|
|
|
def stream_song(
|
|
song_id: str,
|
|
range_header: str | None = None,
|
|
*,
|
|
audio_format: str | None = None,
|
|
max_bit_rate: int | None = None,
|
|
):
|
|
"""Return an upstream streaming response for a Subsonic song id."""
|
|
config = load_config()
|
|
if not config:
|
|
raise RuntimeError("Subsonic server not configured")
|
|
|
|
p = _params(config)
|
|
p['id'] = song_id
|
|
if audio_format:
|
|
cleaned_format = ''.join(ch for ch in str(audio_format).lower() if ch.isalnum())
|
|
if cleaned_format:
|
|
p['format'] = cleaned_format
|
|
if isinstance(max_bit_rate, int) and max_bit_rate > 0:
|
|
p['maxBitRate'] = str(max_bit_rate)
|
|
headers = {}
|
|
if range_header:
|
|
headers['Range'] = range_header
|
|
|
|
r = _requests.get(
|
|
_url(config, 'stream.view'),
|
|
params=p,
|
|
headers=headers,
|
|
stream=True,
|
|
timeout=120,
|
|
)
|
|
if r.status_code >= 400:
|
|
try:
|
|
detail = r.json().get('subsonic-response', {}).get('error', {}).get('message')
|
|
except Exception:
|
|
detail = r.text
|
|
raise RuntimeError(detail or f"Subsonic stream failed with HTTP {r.status_code}")
|
|
return r
|
|
|
|
|
|
def cover_art(cover_id: str, size: int | None = None):
|
|
"""Return an upstream response stream for Subsonic cover art."""
|
|
config = load_config()
|
|
if not config:
|
|
raise RuntimeError("Subsonic server not configured")
|
|
|
|
p = _params(config)
|
|
p['id'] = cover_id
|
|
if isinstance(size, int) and size > 0:
|
|
p['size'] = min(size, 2000)
|
|
|
|
r = _requests.get(
|
|
_url(config, 'getCoverArt.view'),
|
|
params=p,
|
|
stream=True,
|
|
timeout=60,
|
|
)
|
|
if r.status_code >= 400:
|
|
try:
|
|
detail = r.json().get('subsonic-response', {}).get('error', {}).get('message')
|
|
except Exception:
|
|
detail = r.text
|
|
raise RuntimeError(detail or f"Subsonic cover art failed with HTTP {r.status_code}")
|
|
return r
|
|
|
|
|
|
def run_ytdl_import(job_id: str, url: str, title: str = '', artist: str = '') -> None:
|
|
"""Background worker — runs inside _general_executor, updates job state."""
|
|
from .. import job_manager as jm
|
|
try:
|
|
jm.update_job(job_id, status=jm.JobStatus.RUNNING, progress='Starting download…')
|
|
result = import_ytdl(url, title, artist, _progress_cb=lambda msg: jm.update_job(job_id, progress=msg))
|
|
jm.update_job(
|
|
job_id,
|
|
status=jm.JobStatus.DONE,
|
|
progress='Download complete.',
|
|
result={
|
|
'filename': result['filename'],
|
|
'title': result['title'],
|
|
'artist': result['artist'],
|
|
'is_video': result['is_video'],
|
|
'source': 'yt-dlp',
|
|
},
|
|
)
|
|
except Exception as exc:
|
|
jm.update_job(job_id, status=jm.JobStatus.ERROR, error=str(exc), progress='Download failed.')
|
|
|
|
|
|
def import_ytdl(url: str, title: str = '', artist: str = '', _progress_cb=None) -> dict:
|
|
"""Download a YouTube/media URL via yt-dlp into IMPORTS_DIR."""
|
|
url = validate_public_ytdl_url(url)
|
|
|
|
try:
|
|
from yt_dlp import YoutubeDL
|
|
except Exception as exc:
|
|
raise RuntimeError('yt-dlp is not installed on the backend runtime') from exc
|
|
|
|
def _ydl_progress_hook(d: dict) -> None:
|
|
if _progress_cb is None:
|
|
return
|
|
status = d.get('status', '')
|
|
if status == 'downloading':
|
|
pct = d.get('_percent_str', '').strip()
|
|
speed = d.get('_speed_str', '').strip()
|
|
eta = d.get('_eta_str', '').strip()
|
|
parts = [f'Downloading… {pct}']
|
|
if speed:
|
|
parts.append(speed)
|
|
if eta:
|
|
parts.append(f'ETA {eta}')
|
|
_progress_cb(' · '.join(parts))
|
|
elif status == 'finished':
|
|
_progress_cb('Download finished, processing…')
|
|
|
|
outtmpl = str(IMPORTS_DIR / '%(title).160B [%(id)s].%(ext)s')
|
|
ydl_opts = {
|
|
'outtmpl': outtmpl,
|
|
'noplaylist': True,
|
|
'format': 'bestvideo+bestaudio/best',
|
|
'merge_output_format': 'mp4',
|
|
'quiet': True,
|
|
'no_warnings': True,
|
|
'restrictfilenames': False,
|
|
'progress_hooks': [_ydl_progress_hook],
|
|
}
|
|
|
|
try:
|
|
with YoutubeDL(ydl_opts) as ydl:
|
|
info = ydl.extract_info(url, download=True)
|
|
prepared = Path(ydl.prepare_filename(info))
|
|
except Exception as exc:
|
|
raise RuntimeError(f'yt-dlp download failed: {exc}') from exc
|
|
|
|
downloaded = prepared
|
|
if not downloaded.exists():
|
|
merged_mp4 = prepared.with_suffix('.mp4')
|
|
if merged_mp4.exists():
|
|
downloaded = merged_mp4
|
|
if not downloaded.exists():
|
|
raise RuntimeError('yt-dlp completed but output file was not found')
|
|
|
|
info_title = str(info.get('title') or '').strip()
|
|
info_uploader = str(info.get('uploader') or info.get('channel') or '').strip()
|
|
info_id = str(info.get('id') or '').strip()
|
|
info_album = str(info.get('album') or '').strip()
|
|
|
|
effective_title = (title or info_title or downloaded.stem).strip()
|
|
effective_artist = (artist or info_uploader).strip()
|
|
safe_title = _safe_filename(effective_title) or 'YouTube Import'
|
|
safe_artist = _safe_filename(effective_artist)
|
|
safe_id = _safe_filename(info_id)
|
|
base = f'{safe_artist} - {safe_title}' if safe_artist else safe_title
|
|
if safe_id:
|
|
base = f'{base} [{safe_id}]'
|
|
ext = downloaded.suffix or '.mp4'
|
|
dest = IMPORTS_DIR / f'{base}{ext}'
|
|
n = 1
|
|
while dest.exists() and dest.resolve() != downloaded.resolve():
|
|
dest = IMPORTS_DIR / f'{base} ({n}){ext}'
|
|
n += 1
|
|
|
|
if downloaded.resolve() != dest.resolve():
|
|
downloaded.rename(dest)
|
|
|
|
_write_import_metadata(dest, {
|
|
'source': 'yt-dlp',
|
|
'url': url.strip(),
|
|
'id': info_id,
|
|
'title': effective_title,
|
|
'artist': effective_artist,
|
|
'uploader': info_uploader,
|
|
'album': info_album,
|
|
'duration': int(info.get('duration') or 0),
|
|
'webpage_url': str(info.get('webpage_url') or url).strip(),
|
|
'thumbnail': str(info.get('thumbnail') or '').strip(),
|
|
})
|
|
|
|
return {
|
|
'filename': dest.name,
|
|
'path': str(dest),
|
|
'size': dest.stat().st_size,
|
|
'title': effective_title,
|
|
'artist': effective_artist,
|
|
'album': info_album,
|
|
'duration': int(info.get('duration') or 0),
|
|
'source': 'yt-dlp',
|
|
'is_video': dest.suffix.lower() in _VIDEO_EXTS,
|
|
}
|
|
|
|
|
|
def list_imports(
|
|
*,
|
|
query: str = "",
|
|
offset: int = 0,
|
|
limit: int = 500,
|
|
) -> list[dict]:
|
|
"""Return metadata for imported media files, newest first.
|
|
|
|
Supports lightweight search + pagination for imports UX surfaces.
|
|
"""
|
|
if not IMPORTS_DIR.exists():
|
|
return []
|
|
|
|
safe_query = (query or "").strip().lower()
|
|
safe_offset = max(0, int(offset or 0))
|
|
safe_limit = max(1, min(1000, int(limit or 500)))
|
|
|
|
results = []
|
|
for f in sorted(IMPORTS_DIR.iterdir(), key=lambda x: x.stat().st_mtime, reverse=True):
|
|
ext = f.suffix.lower()
|
|
if f.is_file() and ext in (_AUDIO_EXTS | _VIDEO_EXTS):
|
|
meta = _read_import_metadata(f)
|
|
if safe_query:
|
|
haystack = " ".join([
|
|
f.name,
|
|
str(f),
|
|
str(meta.get('title') or ''),
|
|
str(meta.get('artist') or ''),
|
|
str(meta.get('album') or ''),
|
|
str(meta.get('album_artist') or ''),
|
|
str(meta.get('source') or ''),
|
|
]).lower()
|
|
if safe_query not in haystack:
|
|
continue
|
|
results.append({
|
|
'filename': f.name,
|
|
'path': str(f),
|
|
'size': f.stat().st_size,
|
|
'is_video': ext in _VIDEO_EXTS,
|
|
**meta,
|
|
})
|
|
return results[safe_offset:safe_offset + safe_limit]
|