mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Initial implementation of remote library system
This commit is contained in:
1 parent
e8a53eee07
commit
e5fb0f0dbb
65 files changed
+6000
-183
No files matched your search
@@ -10,7 +10,7 @@
|
||||
# - python-multipart is imported as `multipart` by starlette → hidden import
|
||||
# - dulwich (version-history backups) imports git backends dynamically →
|
||||
# collect_submodules('dulwich')
|
||||
from PyInstaller.utils.hooks import collect_submodules, collect_all
|
||||
from PyInstaller.utils.hooks import collect_all, collect_submodules, copy_metadata
|
||||
|
||||
hiddenimports = []
|
||||
datas = []
|
||||
@@ -31,6 +31,12 @@ for pkg in ("uvloop", "httptools", "websockets", "av"):
|
||||
# Imported by name, not statically discoverable.
|
||||
hiddenimports += ["multipart", "anyio"]
|
||||
|
||||
# A remote library's password lives in the OS keychain through `keyring`, which
|
||||
# finds its backends (macOS Keychain, Windows Credential Manager) by entry point
|
||||
# — so both the modules AND the package metadata that names them must ship.
|
||||
hiddenimports += collect_submodules("keyring")
|
||||
datas += copy_metadata("keyring")
|
||||
|
||||
# Bundle the canonical version file so konduktor.__version__ can read it at
|
||||
# runtime from sys._MEIPASS (frontend/package.json is the single source of the
|
||||
# app version — see konduktor/__init__.py). Path is relative to this spec.
|
||||
|
||||
@@ -21,7 +21,7 @@ from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from ...core.adapter import InvalidCommand, Unsupported
|
||||
from ...core.adapter import InvalidCommand, Unsupported, local_audio_facts
|
||||
from ...core.capabilities import Capabilities
|
||||
from ...core.model import GridMarker, HotcueChip, PlaylistNode, Track, TrackCues
|
||||
from ...core.pathmap import PathMapping, common_dir_prefix
|
||||
@@ -223,6 +223,9 @@ class OneLibraryAdapter:
|
||||
def audio_path(self, track_id: str):
|
||||
return self._store.audio_path(track_id)
|
||||
|
||||
def audio_facts(self, track_ids: list[str]):
|
||||
return local_audio_facts(self, track_ids)
|
||||
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None:
|
||||
"""Ignored: a drive's paths are relative to wherever it is mounted.
|
||||
|
||||
|
||||
@@ -21,13 +21,14 @@ from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from ...core.adapter import InvalidCommand, Unsupported
|
||||
from ...core.adapter import InvalidCommand, Unsupported, local_audio_facts
|
||||
from ...core.capabilities import Capabilities
|
||||
from ...core.model import GridMarker, PlaylistNode, Track, TrackCues
|
||||
from ...core.pathmap import PathMapping, common_dir_prefix
|
||||
from ...core.query import TrackIndex
|
||||
from . import capabilities as caps
|
||||
from . import palette, projection, timebase
|
||||
from ...core import add_analysis
|
||||
from .store import RekordboxStore
|
||||
|
||||
|
||||
@@ -202,6 +203,9 @@ class RekordboxAdapter:
|
||||
def audio_path(self, track_id: str):
|
||||
return self._store.audio_path(track_id)
|
||||
|
||||
def audio_facts(self, track_ids: list[str]):
|
||||
return local_audio_facts(self, track_ids)
|
||||
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None:
|
||||
self._store.set_path_mapping(mapping)
|
||||
# The FILE decides a track's media kind, and the mapping moves files.
|
||||
@@ -215,6 +219,10 @@ class RekordboxAdapter:
|
||||
def set_session_mappings(self, mappings: list[PathMapping]) -> None:
|
||||
return None
|
||||
|
||||
def set_write_stored_paths(self, enabled: bool) -> None:
|
||||
"""OPTIONAL: see `TraktorAdapter.set_write_stored_paths`."""
|
||||
self._store.set_write_stored_paths(enabled)
|
||||
|
||||
def path_prefix_suggestions(self) -> dict:
|
||||
paths = self._store.all_audio_paths()
|
||||
primary = common_dir_prefix(paths)
|
||||
@@ -388,6 +396,12 @@ class RekordboxAdapter:
|
||||
def dirty(self) -> bool:
|
||||
return self._store.dirty
|
||||
|
||||
def edit_summary(self) -> str:
|
||||
"""OPTIONAL: this session's unsaved edits in one line ("edited 3
|
||||
tracks; added 6 hotcues") — what a server tells the next computer to
|
||||
open the library about the edits it is inheriting."""
|
||||
return self._store._journal.summary()
|
||||
|
||||
def save(self):
|
||||
self._require_writable("Saving")
|
||||
return self._store.save()
|
||||
@@ -422,6 +436,14 @@ class RekordboxAdapter:
|
||||
if self._cloud_synced:
|
||||
raise Unsupported(self._readonly_reason(what))
|
||||
|
||||
def analysis_lead(self, audio: Path) -> float:
|
||||
"""The time-base lead `add_tracks` measures a file's waveform with —
|
||||
rekordbox's clock against the decoded audio, read from the file's
|
||||
header (`timebase.py`). OPTIONAL on the protocol: a platform that does
|
||||
not analyse what it adds has none, and whoever prepares an analysis
|
||||
for this one (a client of a server-held library) asks for it."""
|
||||
return timebase.offset(Path(audio))
|
||||
|
||||
def add_tracks(self, items: list, *, checkpoint=None) -> list[str]:
|
||||
"""Add tracks that came from somewhere else, with their prep.
|
||||
|
||||
@@ -443,7 +465,7 @@ class RekordboxAdapter:
|
||||
bank or already taken becomes a memory cue at the same position rather
|
||||
than being dropped.
|
||||
"""
|
||||
from ...core import audio_tags, grid_detect, key_detect, waveform
|
||||
from ...core import audio_tags
|
||||
|
||||
self._require_writable("Adding tracks")
|
||||
held = set(self._store.all_audio_paths())
|
||||
@@ -459,18 +481,22 @@ class RekordboxAdapter:
|
||||
if str(audio) in held:
|
||||
raise InvalidCommand(f"The library already holds {audio}")
|
||||
held.add(str(audio))
|
||||
samples = waveform.decode(audio)
|
||||
measured = waveform.analyse_samples(samples, lead=timebase.offset(audio))
|
||||
markers = list(item.cues.grid_markers) if item.cues else []
|
||||
if not markers and samples is not None:
|
||||
try:
|
||||
found = grid_detect.detect_grid(str(audio), y=samples, sr=waveform.SR)
|
||||
markers = [GridMarker(start=found.anchor, bpm=found.bpm)]
|
||||
except ValueError:
|
||||
pass # no pulse to fit (a one-shot, silence): no grid
|
||||
if item.analysis is not None:
|
||||
# Measured by whoever added it — a library held by a server is
|
||||
# never asked to decode audio (see `PreparedAnalysis`).
|
||||
analysed = item.analysis
|
||||
if not markers:
|
||||
markers = list(analysed.markers)
|
||||
else:
|
||||
analysed = add_analysis.prepare(audio, lead=self.analysis_lead(audio),
|
||||
detect=not markers,
|
||||
detect_key=item.track.key_wheel is None)
|
||||
markers = markers or list(analysed.markers)
|
||||
measured = analysed.measured
|
||||
# A file with no key of its own gets one, as it gets a grid
|
||||
# (decided: arrive ready to prep). Rekordbox's own add analyses one.
|
||||
track = key_detect.with_detected_key(item.track, samples, waveform.SR)
|
||||
track = add_analysis.with_key(item.track, analysed.key)
|
||||
art = item.art or audio_tags.read_cover(audio)
|
||||
prepared.append((item, track, audio, measured, markers, art[0] if art else None))
|
||||
|
||||
|
||||
@@ -46,7 +46,7 @@ from ...core.adapter import (
|
||||
)
|
||||
from ...core.edit_journal import EditJournal
|
||||
from ...core.grid_edit import ReplaceGridCommands
|
||||
from ...core.pathmap import PathMapping
|
||||
from ...core.pathmap import PathMapping, stored_form
|
||||
from . import timebase
|
||||
from .cue_types import beat_loop_size, kind_for, role_and_slot
|
||||
|
||||
@@ -117,6 +117,8 @@ class RekordboxStore(ReplaceGridCommands):
|
||||
def __init__(self, path: Path):
|
||||
self.path = Path(path)
|
||||
self._mapping = PathMapping()
|
||||
# Write an added file in the library's STORED form (`pathmap.stored_form`).
|
||||
self._write_stored_paths = False
|
||||
self._grid_cache: dict[str, tuple[list[float], list[float], list[int]] | None] = {}
|
||||
self._journal = EditJournal()
|
||||
# Grid edits buffered until save(): ANLZ files are written to disk, so
|
||||
@@ -375,6 +377,14 @@ class RekordboxStore(ReplaceGridCommands):
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None:
|
||||
self._mapping = mapping or PathMapping()
|
||||
|
||||
def set_write_stored_paths(self, enabled: bool) -> None:
|
||||
self._write_stored_paths = bool(enabled)
|
||||
|
||||
def _stored(self, audio: Path) -> Path:
|
||||
if not self._write_stored_paths:
|
||||
return Path(audio)
|
||||
return stored_form(Path(audio), [self._mapping])
|
||||
|
||||
def is_stem(self, track_id: str) -> bool:
|
||||
"""Whether the track's FILE is a native-instruments stem file — read
|
||||
from its contents (only `.m4a`/`.mp4` are opened, ~0.7 ms each), and
|
||||
@@ -649,8 +659,10 @@ class RekordboxStore(ReplaceGridCommands):
|
||||
if not audio.is_file():
|
||||
raise InvalidCommand(f"No audio file at {audio}")
|
||||
t = self._tables
|
||||
if self._db.session.query(t.DjmdContent).filter_by(FolderPath=str(audio)).count():
|
||||
raise InvalidCommand(f"The library already holds {audio}")
|
||||
stored = self._stored(audio)
|
||||
for form in {str(audio), str(stored)}:
|
||||
if self._db.session.query(t.DjmdContent).filter_by(FolderPath=form).count():
|
||||
raise InvalidCommand(f"The library already holds {audio}")
|
||||
facts = _file_facts(audio)
|
||||
content = self._db.add_content(
|
||||
str(audio),
|
||||
@@ -676,6 +688,10 @@ class RekordboxStore(ReplaceGridCommands):
|
||||
# Rekordbox's ("10m" is "Cm" here), and a row it already has is reused.
|
||||
content.KeyID = self._key_id(track.key_wheel, track.key_mode)
|
||||
content.ContentLink = new_content.CONTENT_LINK
|
||||
if stored != audio:
|
||||
# pyrekordbox reads the file where it IS; the row names it as the
|
||||
# library stores every other path (the server's mapping, inverted).
|
||||
content.FolderPath = str(stored)
|
||||
|
||||
track_uuid = str(content.UUID)
|
||||
rel = new_content.anlz_rel(track_uuid)
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Remote libraries: a library held by a Konduktor server, opened from here.
|
||||
|
||||
NOT a registered driver: a remote is not a file `can_open` could probe, and it
|
||||
is chosen from the picker's own "Remote" step, by the saved remote's id. What
|
||||
opening one returns is everything `AppState.open_remote` installs — the
|
||||
adapter, the services that keep history and export sets on the server, and the
|
||||
session that keeps this computer's hold on it.
|
||||
|
||||
Imports no platform adapter (`test_layering.py`): what platform the server
|
||||
holds is the server's business, and reaches this side only as capabilities.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from ... import exports
|
||||
from . import config
|
||||
from .adapter import RemoteAdapter
|
||||
from .client import AuthFailed, InUse, RemoteClient, SessionLost, Unreachable, VersionMismatch
|
||||
from .services import RemotePending, RemoteServices, RemoteSetStore
|
||||
from .session import RemoteSession
|
||||
|
||||
__all__ = [
|
||||
"AuthFailed", "InUse", "Opened", "RemoteAdapter", "SessionLost", "Unreachable",
|
||||
"VersionMismatch", "handshake", "open_remote",
|
||||
]
|
||||
|
||||
|
||||
@dataclass
|
||||
class Opened:
|
||||
remote: config.Remote
|
||||
path: Path
|
||||
adapter: RemoteAdapter
|
||||
services: RemoteServices
|
||||
session: RemoteSession
|
||||
library_id: str
|
||||
pending: object | None
|
||||
#: Edits another computer left unsaved: {machine, summary}, or None.
|
||||
pending_edits: dict | None
|
||||
|
||||
|
||||
def open_remote(remote: config.Remote, *, takeover: bool = False, batch_probe=None,
|
||||
password: str | None = None, cache=None) -> Opened:
|
||||
"""Connect, take the session, and mirror the library. Raises `InUse` when
|
||||
another computer holds it (and `takeover` is not set), `AuthFailed`,
|
||||
`VersionMismatch` or `Unreachable` — all before anything is installed."""
|
||||
secret = password if password is not None else config.password(remote.id)
|
||||
if not secret:
|
||||
raise AuthFailed("No password is saved for this remote — edit it to enter one")
|
||||
client = RemoteClient(remote, secret)
|
||||
try:
|
||||
client_id = config.client_id()
|
||||
hello = client.hello(client_id)
|
||||
machine = config.machine_name()
|
||||
acquired = client.acquire(client_id, machine, takeover=takeover)
|
||||
session = RemoteSession(client, batch_probe=batch_probe, identity=(client_id, machine))
|
||||
adapter = RemoteAdapter(client, session, hello, cache=cache)
|
||||
session.on_reacquired = adapter.refresh
|
||||
except Exception:
|
||||
client.release()
|
||||
client.close()
|
||||
raise
|
||||
# The server's id for the library, namespaced: this computer's export-set
|
||||
# store for it is the SERVER (`RemoteSetStore`), and nothing this computer
|
||||
# keeps under the server's own id may be mistaken for it.
|
||||
library_id = f"remote:{hello['library_id']}"
|
||||
exports.use_store(library_id, RemoteSetStore(client))
|
||||
session.start()
|
||||
return Opened(
|
||||
remote=remote, path=Path(hello.get("path") or remote.name), adapter=adapter,
|
||||
services=RemoteServices(client), session=session, library_id=library_id,
|
||||
pending=RemotePending(client), pending_edits=acquired.get("pending_edits"),
|
||||
)
|
||||
|
||||
|
||||
def handshake(remote: config.Remote, password: str) -> list[dict]:
|
||||
"""Try each of the remote's addresses on its own: what a Save of the
|
||||
remote's settings reports. Each result is {address, url, ok, error, kind},
|
||||
`kind` one of ok / unreachable / auth / version / other."""
|
||||
results = []
|
||||
for label, url in remote.addresses():
|
||||
single = config.Remote(id=remote.id, name=remote.name, host=url, username=remote.username)
|
||||
client = RemoteClient(single, password, timeout=8.0)
|
||||
try:
|
||||
info = client.hello()
|
||||
results.append({"address": label, "url": url, "ok": True, "error": None, "kind": "ok",
|
||||
"name": info.get("name"), "platform": info.get("platform")})
|
||||
except Unreachable as ex:
|
||||
results.append({"address": label, "url": url, "ok": False, "error": str(ex), "kind": "unreachable"})
|
||||
except AuthFailed as ex:
|
||||
results.append({"address": label, "url": url, "ok": False, "error": str(ex), "kind": "auth"})
|
||||
except VersionMismatch as ex:
|
||||
results.append({"address": label, "url": url, "ok": False, "error": str(ex), "kind": "version"})
|
||||
except Exception as ex: # noqa: BLE001 — anything else is that address's answer
|
||||
results.append({"address": label, "url": url, "ok": False, "error": str(ex), "kind": "other"})
|
||||
finally:
|
||||
client.close()
|
||||
return results
|
||||
@@ -0,0 +1,446 @@
|
||||
"""`RemoteAdapter`: a library held by a Konduktor server, as a `LibraryAdapter`.
|
||||
|
||||
Everything above the adapter layer — routes, export, import, batches, the UI —
|
||||
works on a remote library unchanged, because this IS the adapter: the server
|
||||
holds the native model (`konduktor.server`), and every command travels to it
|
||||
over `remote_protocol`.
|
||||
|
||||
* **The projection is mirrored here.** The server's tracks are fetched once
|
||||
into a local `TrackIndex`, and each command's answer carries the tracks it
|
||||
changed — so filtering, sorting, facets and stats are as instant as on a
|
||||
local library, and use the SAME query code (`core/query.py`). Every answer
|
||||
carries the server's revision; a gap (an answer out of order, a reconnect)
|
||||
re-fetches the whole projection rather than guessing.
|
||||
* **`audio_path` downloads.** It must return a readable file on THIS
|
||||
computer, so it fetches the track into the shared cache (`cache.py`).
|
||||
Anything that only needs to know WHICH file a track is asks `audio_facts`,
|
||||
which never downloads.
|
||||
* **Read-only when the session is not ours** — taken over, or the server out
|
||||
of reach — through `capabilities()`, so the UI gates itself as it does for
|
||||
any read-only library. A command the server refuses for that reason (423)
|
||||
turns the session `taken_over` on the spot, not at the next heartbeat.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from ... import remote_protocol as rp
|
||||
from ...core.adapter import (
|
||||
AudioFacts,
|
||||
FileTagResult,
|
||||
SaveOutcome,
|
||||
Unavailable,
|
||||
Unsupported,
|
||||
)
|
||||
from ...core.capabilities import Capabilities
|
||||
from ...core.query import TrackIndex
|
||||
from .cache import RemoteAudioCache, StaleFacts
|
||||
from .cache import shared as shared_cache
|
||||
from .client import RemoteClient, SessionLost
|
||||
from .session import RemoteSession
|
||||
|
||||
_NOT_HERE = "A remote library's paths are the server's configuration"
|
||||
|
||||
|
||||
class RemoteAdapter:
|
||||
def __init__(self, client: RemoteClient, session: RemoteSession, hello: dict, *,
|
||||
cache: RemoteAudioCache | None = None):
|
||||
self.platform = hello["platform"]
|
||||
self.path = Path(hello.get("path") or "")
|
||||
self.hello = hello
|
||||
self.client = client
|
||||
self.session = session
|
||||
self.cache = cache or shared_cache()
|
||||
self._index = TrackIndex()
|
||||
self._lock = threading.RLock()
|
||||
self._rev: int | None = None
|
||||
self._caps: tuple[int, Capabilities] | None = None
|
||||
self._facts: dict[str, AudioFacts] = {}
|
||||
#: Server path of an upload → (the local file it came from, its analysis lead).
|
||||
self._uploads: dict[str, tuple[Path, float | None]] = {}
|
||||
self._dirty = bool(hello.get("dirty"))
|
||||
self._load()
|
||||
|
||||
# ---- following the server ---------------------------------------------------
|
||||
def _load(self) -> None:
|
||||
envelope = self.client.rpc("tracks")
|
||||
with self._lock:
|
||||
self._index.rebuild(list(envelope["result"]))
|
||||
self._rev = envelope["rev"]
|
||||
self._facts.clear()
|
||||
self._caps = None
|
||||
|
||||
def _apply(self, envelope: dict) -> None:
|
||||
"""Fold a command's answer into the mirror — or re-fetch on any gap."""
|
||||
with self._lock:
|
||||
rev = envelope.get("rev")
|
||||
if envelope.get("reset") or self._rev is None or rev != self._rev + 1:
|
||||
in_order = False
|
||||
else:
|
||||
in_order = True
|
||||
from ...core.model import Track
|
||||
|
||||
removed = set(envelope.get("removed") or [])
|
||||
if removed:
|
||||
self._index.rebuild([t for t in self._index.tracks if t.id not in removed])
|
||||
for raw in envelope.get("changed") or []:
|
||||
track = Track.model_validate(raw)
|
||||
self._index.add(track)
|
||||
self._facts.pop(track.id, None)
|
||||
for track_id in removed:
|
||||
self._facts.pop(track_id, None)
|
||||
self._rev = rev
|
||||
if not in_order:
|
||||
self._load()
|
||||
|
||||
def _call(self, method: str, /, **args):
|
||||
try:
|
||||
envelope = self.client.rpc(method, **args)
|
||||
except SessionLost as ex:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
if rp.RPC[method].mutating:
|
||||
self.session.reached()
|
||||
self._apply(envelope)
|
||||
return envelope["result"]
|
||||
|
||||
def refresh(self) -> None:
|
||||
"""Re-read everything from the server (after a restore, a reconnect)."""
|
||||
self._load()
|
||||
|
||||
# ---- identity -----------------------------------------------------------------
|
||||
def capabilities(self) -> Capabilities:
|
||||
with self._lock:
|
||||
cached = self._caps
|
||||
if cached is None or cached[0] != self._rev:
|
||||
try:
|
||||
caps = self._call("capabilities")
|
||||
except Unavailable:
|
||||
# Out of reach: the last answer, read-only (below) — the UI
|
||||
# must still render, and gate every edit.
|
||||
if cached is None:
|
||||
raise
|
||||
caps = cached[1]
|
||||
else:
|
||||
with self._lock:
|
||||
self._caps = (self._rev, caps)
|
||||
else:
|
||||
caps = cached[1]
|
||||
if self.session.writable:
|
||||
return caps
|
||||
return caps.model_copy(update={"writable": False, "readonly_cause": self.session.readonly_cause})
|
||||
|
||||
def reload(self) -> None:
|
||||
# The server is what holds (and drops) the edits — `AppState.discard`
|
||||
# asks it to discard first; this is the mirror following.
|
||||
self._load()
|
||||
|
||||
# ---- read projection (the mirror) -------------------------------------------
|
||||
@property
|
||||
def tracks(self):
|
||||
return self._index.tracks
|
||||
|
||||
def track(self, track_id: str):
|
||||
return self._index.get(track_id)
|
||||
|
||||
def query_tracks(self, **kw):
|
||||
return self._index.query_tracks(**kw)
|
||||
|
||||
def facets(self):
|
||||
return self._index.facets()
|
||||
|
||||
def stats(self, playlist_count: int):
|
||||
return self._index.stats(playlist_count)
|
||||
|
||||
# ---- read projection (the server) -------------------------------------------
|
||||
def playlist_tree(self):
|
||||
return self._call("playlist_tree")
|
||||
|
||||
def playlist_count(self) -> int:
|
||||
return self._call("playlist_count")
|
||||
|
||||
def playlist_entries(self, node_id: str):
|
||||
return self._call("playlist_entries", node_id=node_id)
|
||||
|
||||
def playlist_tracks(self, node_id: str):
|
||||
entries = self.playlist_entries(node_id)
|
||||
if entries is None:
|
||||
return None
|
||||
return [t for k in entries if (t := self._index.get(k)) is not None]
|
||||
|
||||
def track_cues(self, track_id: str):
|
||||
return self._call("track_cues", track_id=track_id)
|
||||
|
||||
@property
|
||||
def dirty(self) -> bool:
|
||||
try:
|
||||
self._dirty = self._call("dirty")
|
||||
except Unavailable:
|
||||
pass # out of reach: what it was
|
||||
return self._dirty
|
||||
|
||||
# ---- commands -------------------------------------------------------------------
|
||||
def create_playlist(self, name, parent_id=None):
|
||||
return self._call("create_playlist", name=name, parent_id=parent_id)
|
||||
|
||||
def create_folder(self, name, parent_id=None):
|
||||
return self._call("create_folder", name=name, parent_id=parent_id)
|
||||
|
||||
def rename_playlist(self, node_id, name):
|
||||
return self._call("rename_playlist", node_id=node_id, name=name)
|
||||
|
||||
def delete_playlist(self, node_id):
|
||||
return self._call("delete_playlist", node_id=node_id)
|
||||
|
||||
def set_playlist_entries(self, node_id, track_ids):
|
||||
return self._call("set_playlist_entries", node_id=node_id, track_ids=list(track_ids))
|
||||
|
||||
def remove_tracks(self, track_ids):
|
||||
return self._call("remove_tracks", track_ids=list(track_ids))
|
||||
|
||||
def set_track_metadata(self, track_id, fields):
|
||||
return self._call("set_track_metadata", track_id=track_id, fields=fields)
|
||||
|
||||
def set_key(self, track_id, wheel, mode):
|
||||
return self._call("set_key", track_id=track_id, wheel=wheel, mode=mode)
|
||||
|
||||
def set_cue(self, track_id, *, slot, start_sec, cue_type, length_sec=0.0, role="hotcue", name=None):
|
||||
return self._call("set_cue", track_id=track_id, slot=slot, start_sec=start_sec,
|
||||
cue_type=cue_type, length_sec=length_sec, role=role, name=name)
|
||||
|
||||
def set_cue_type(self, track_id, slot, cue_type):
|
||||
return self._call("set_cue_type", track_id=track_id, slot=slot, cue_type=cue_type)
|
||||
|
||||
def set_cue_color(self, track_id, slot, color):
|
||||
return self._call("set_cue_color", track_id=track_id, slot=slot, color=color)
|
||||
|
||||
def delete_cue(self, track_id, slot):
|
||||
return self._call("delete_cue", track_id=track_id, slot=slot)
|
||||
|
||||
def place_cues(self, track_id, cues, *, overwrite=False):
|
||||
return self._call("place_cues", track_id=track_id, cues=list(cues), overwrite=overwrite)
|
||||
|
||||
def add_grid_marker(self, track_id, start_sec, bpm=None):
|
||||
return self._call("add_grid_marker", track_id=track_id, start_sec=start_sec, bpm=bpm)
|
||||
|
||||
def move_grid_marker(self, track_id, index, start_sec):
|
||||
return self._call("move_grid_marker", track_id=track_id, index=index, start_sec=start_sec)
|
||||
|
||||
def set_grid_marker_bpm(self, track_id, index, bpm):
|
||||
return self._call("set_grid_marker_bpm", track_id=track_id, index=index, bpm=bpm)
|
||||
|
||||
def delete_grid_marker(self, track_id, index):
|
||||
return self._call("delete_grid_marker", track_id=track_id, index=index)
|
||||
|
||||
def replace_grid(self, track_id, markers):
|
||||
return self._call("replace_grid", track_id=track_id, markers=_pairs(markers))
|
||||
|
||||
def set_analysed_grid(self, track_id, markers):
|
||||
return self._call("set_analysed_grid", track_id=track_id, markers=_pairs(markers))
|
||||
|
||||
def delete_grid(self, track_id):
|
||||
return self._call("delete_grid", track_id=track_id)
|
||||
|
||||
def set_grid_lock(self, track_id, locked):
|
||||
return self._call("set_grid_lock", track_id=track_id, locked=locked)
|
||||
|
||||
# ---- adding tracks ------------------------------------------------------------------
|
||||
def upload_audio(self, source: Path, folder: str, name: str, *, progress=None) -> Path:
|
||||
"""Send `source` into `folder` on the server; the path it landed at (a
|
||||
taken name gets `-2`…, as a local copy does). What a local import's
|
||||
file copy becomes when the library's destination is the server's."""
|
||||
try:
|
||||
landed = self.client.upload(Path(source), folder, name, progress=progress)
|
||||
except SessionLost as ex:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
self._uploads[landed["path"]] = (Path(source), landed.get("analysis_lead"))
|
||||
return Path(landed["path"])
|
||||
|
||||
def free_space(self, path: str) -> int:
|
||||
"""Free space on the SERVER's disk at `path` (an import's destination)."""
|
||||
return self.client.fs_space(path)
|
||||
|
||||
def delete_upload(self, path) -> None:
|
||||
"""Undo `upload_audio` (a cancelled or failed import)."""
|
||||
self._uploads.pop(str(path), None)
|
||||
self.client.delete_upload(str(path))
|
||||
|
||||
def add_tracks(self, items, *, checkpoint=None):
|
||||
"""Add uploaded files. Where the platform analyses what it adds (the
|
||||
server said so with an analysis lead), the analysis is done HERE, on
|
||||
the copy this computer uploaded — the server never decodes audio."""
|
||||
from ...core import add_analysis
|
||||
|
||||
wire = []
|
||||
total = len(items)
|
||||
for n, item in enumerate(items, start=1):
|
||||
key = str(item.audio_path)
|
||||
source, lead = self._uploads.get(key, (None, None))
|
||||
analysis = item.analysis
|
||||
if analysis is None and lead is not None and source is not None:
|
||||
if checkpoint is not None:
|
||||
checkpoint(f"Analysing {item.track.title or source.name} ({n}/{total})", step=n, of=total)
|
||||
has_grid = bool(item.cues and item.cues.grid_markers)
|
||||
analysis = add_analysis.prepare(source, lead=lead, detect=not has_grid,
|
||||
detect_key=item.track.key_wheel is None)
|
||||
art = rp.WireArt(data=base64.b64encode(item.art[0]).decode("ascii"), mime=item.art[1]) \
|
||||
if item.art else None
|
||||
wire.append(rp.WireNewTrack(track=item.track, audio_path=key, cues=item.cues, art=art,
|
||||
analysis=rp.pack_analysis(analysis)))
|
||||
if checkpoint is not None:
|
||||
checkpoint(f"Adding {total} track{'' if total == 1 else 's'} on the server",
|
||||
step=total, of=total)
|
||||
try:
|
||||
envelope = self.client.rpc("add_tracks", items=wire, timeout=None)
|
||||
except SessionLost as ex:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
self._apply(envelope)
|
||||
for item in items:
|
||||
self._uploads.pop(str(item.audio_path), None)
|
||||
return envelope["result"]
|
||||
|
||||
def apply_stem_swaps(self, swaps, *, add_to_playlist=None):
|
||||
raise Unsupported("A remote library's stem files are swapped in on the server")
|
||||
|
||||
# ---- Convert to Stems (the library side lives on the server) ---------------------
|
||||
# `stems/remote_convert.py` drives these: the server plans and swaps, this
|
||||
# computer separates. See the server's stem routes for why.
|
||||
def stems_plan(self, body: dict) -> dict:
|
||||
return self.client.stems_plan(body)
|
||||
|
||||
def stage_stem(self, track_id: str, target: str, local: Path, *, bit_rate: int,
|
||||
duration: float, progress=None) -> dict:
|
||||
import hashlib
|
||||
|
||||
digest = hashlib.sha256()
|
||||
with open(local, "rb") as f:
|
||||
while chunk := f.read(1 << 20):
|
||||
digest.update(chunk)
|
||||
try:
|
||||
return self.client.stems_stage(track_id, target, local, sha256=digest.hexdigest(),
|
||||
bit_rate=bit_rate, duration=duration, progress=progress)
|
||||
except SessionLost as ex:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
|
||||
def abandon_stems(self, targets: list[str]) -> None:
|
||||
self.client.stems_abandon(targets)
|
||||
|
||||
def publish_stems(self, items: list[dict], options: dict) -> dict:
|
||||
try:
|
||||
result = self.client.stems_publish(items, options)
|
||||
except SessionLost as ex:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
self._load() # ids changed (repoint) or entries were added
|
||||
return result
|
||||
|
||||
# ---- metadata / art ------------------------------------------------------------------
|
||||
def set_cover_art(self, track_id, data, mime):
|
||||
try:
|
||||
envelope = self.client.put_art(track_id, data, mime)
|
||||
except SessionLost as ex:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
self._apply({**envelope, "removed": [], "reset": False})
|
||||
|
||||
def cover_art(self, track_id):
|
||||
return self.client.art(track_id)
|
||||
|
||||
# ---- audio ------------------------------------------------------------------------------
|
||||
def audio_facts(self, track_ids):
|
||||
wanted = list(dict.fromkeys(track_ids))
|
||||
with self._lock:
|
||||
missing = [t for t in wanted if t not in self._facts]
|
||||
if missing:
|
||||
found = {}
|
||||
for start in range(0, len(missing), 2000):
|
||||
found.update(self._call("audio_facts", track_ids=missing[start:start + 2000]))
|
||||
with self._lock:
|
||||
self._facts.update(found)
|
||||
with self._lock:
|
||||
return {t: self._facts[t] for t in wanted if t in self._facts}
|
||||
|
||||
def audio_path(self, track_id, *, progress=None):
|
||||
"""A local copy of the track's audio, downloaded if this computer has
|
||||
none of this version. None when the server has no file for it."""
|
||||
for attempt in range(2):
|
||||
facts = self.audio_facts([track_id]).get(track_id)
|
||||
if facts is None:
|
||||
return None
|
||||
cached = self.cache.get(facts)
|
||||
if cached is not None:
|
||||
return cached
|
||||
try:
|
||||
return self.cache.fetch(
|
||||
facts, lambda partial: self.client.download(track_id, partial, progress=progress))
|
||||
except StaleFacts:
|
||||
with self._lock:
|
||||
self._facts.pop(track_id, None)
|
||||
if attempt:
|
||||
raise
|
||||
return None
|
||||
|
||||
def cached_audio(self, track_id) -> Path | None:
|
||||
"""The local copy if there already is one — never downloads."""
|
||||
facts = self.audio_facts([track_id]).get(track_id)
|
||||
return self.cache.get(facts) if facts else None
|
||||
|
||||
# ---- paths: the server's business ------------------------------------------------
|
||||
def set_path_mapping(self, mapping):
|
||||
raise Unsupported(_NOT_HERE)
|
||||
|
||||
def set_session_mappings(self, mappings):
|
||||
raise Unsupported(_NOT_HERE)
|
||||
|
||||
def unresolved_path_groups(self):
|
||||
return []
|
||||
|
||||
def path_prefix_suggestions(self):
|
||||
raise Unsupported(_NOT_HERE)
|
||||
|
||||
def remap_preview(self, mapping):
|
||||
raise Unsupported(_NOT_HERE)
|
||||
|
||||
def remap_locations(self, mapping):
|
||||
raise Unsupported(_NOT_HERE)
|
||||
|
||||
# ---- save ----------------------------------------------------------------------------
|
||||
def save(self):
|
||||
try:
|
||||
result = self.client.save()
|
||||
except SessionLost as ex:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
outcome = SaveOutcome(
|
||||
summary=result.get("summary") or "",
|
||||
snapshot=None,
|
||||
tag_results=[FileTagResult(**r) for r in result.get("tag_results") or []],
|
||||
)
|
||||
# Versioned on the server; `RemoteServices.commit_save` hands it on.
|
||||
outcome.commit = result.get("commit")
|
||||
self._load()
|
||||
return outcome
|
||||
|
||||
def snapshot(self) -> bytes:
|
||||
raise Unsupported("A remote library's version history is kept on the server")
|
||||
|
||||
def close(self) -> None:
|
||||
self.session.stop()
|
||||
self.client.release()
|
||||
self.client.close()
|
||||
|
||||
|
||||
def _pairs(markers) -> list[tuple[float, float]]:
|
||||
out = []
|
||||
for m in markers:
|
||||
if hasattr(m, "start"):
|
||||
out.append((float(m.start), float(m.bpm)))
|
||||
else:
|
||||
start, bpm = m
|
||||
out.append((float(start), float(bpm)))
|
||||
return out
|
||||
@@ -0,0 +1,194 @@
|
||||
"""This computer's copies of a remote library's audio.
|
||||
|
||||
Everything that needs a track's audio as a FILE runs here, not on the server —
|
||||
the deck's decode, grid and cue analysis, stem separation and extraction, an
|
||||
export's copy onto a stick. One cache serves them all, so a track analysed and
|
||||
then exported downloads once.
|
||||
|
||||
* **Keyed by what the server says the file IS** — its path there, size and
|
||||
mtime (`AudioFacts`) — never by when it was fetched: an edited file (Save
|
||||
writes tags into it) is a new entry, and the same file fetched again after
|
||||
an eviction, or by another computer exporting the same set, is recognised.
|
||||
* **A partial, renamed into place**, so a cut connection never leaves a
|
||||
truncated file under a real entry's name, and a download whose size does
|
||||
not match the facts is refused rather than kept.
|
||||
* **Least recently used, under a cap** (`remoteCacheBytes` in prefs). The
|
||||
entry just written and anything touched in the last few minutes are never
|
||||
the ones evicted: they are being played or copied right now.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import shutil
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from ... import paths, prefs
|
||||
from ...core.adapter import AudioFacts, Unavailable
|
||||
|
||||
DEFAULT_CAP = 10 * 1024 ** 3
|
||||
_RECENT = 300.0 # seconds: an entry touched this recently is in use
|
||||
_PART = ".part"
|
||||
|
||||
|
||||
class StaleFacts(Unavailable):
|
||||
"""The server's file changed between asking about it and downloading it."""
|
||||
|
||||
|
||||
def cache_root() -> Path:
|
||||
return paths.app_data_dir() / "remote-cache"
|
||||
|
||||
|
||||
def cap_bytes() -> int:
|
||||
try:
|
||||
value = int(prefs.load_prefs().get("remoteCacheBytes") or DEFAULT_CAP)
|
||||
except (TypeError, ValueError):
|
||||
value = DEFAULT_CAP
|
||||
return max(value, 256 * 1024 ** 2)
|
||||
|
||||
|
||||
class RemoteAudioCache:
|
||||
def __init__(self, root: Path | None = None, *, cap=None, clock=time.time):
|
||||
self.root = Path(root) if root is not None else cache_root()
|
||||
self._cap = cap if cap is not None else cap_bytes
|
||||
self._clock = clock
|
||||
self._locks: dict[str, threading.Lock] = {}
|
||||
self._guard = threading.Lock()
|
||||
#: Recent download speeds (bytes/s), newest last — for time estimates.
|
||||
self._speeds: list[float] = []
|
||||
|
||||
# ---- naming ----------------------------------------------------------------
|
||||
@staticmethod
|
||||
def key(facts: AudioFacts) -> str:
|
||||
text = f"{facts.key}|{facts.size}|{facts.mtime_ns}"
|
||||
return hashlib.sha256(text.encode("utf-8")).hexdigest()[:32]
|
||||
|
||||
def path_for(self, facts: AudioFacts) -> Path:
|
||||
# The original's suffix, so a MIME type and a decoder's guess still work.
|
||||
suffix = Path(facts.key.replace("\\", "/")).suffix.lower()
|
||||
return self.root / f"{self.key(facts)}{suffix}"
|
||||
|
||||
def _lock_for(self, key: str) -> threading.Lock:
|
||||
with self._guard:
|
||||
return self._locks.setdefault(key, threading.Lock())
|
||||
|
||||
# ---- use -------------------------------------------------------------------
|
||||
def get(self, facts: AudioFacts) -> Path | None:
|
||||
path = self.path_for(facts)
|
||||
if path.is_file():
|
||||
self._touch(path)
|
||||
return path
|
||||
return None
|
||||
|
||||
def fetch(self, facts: AudioFacts, download) -> Path:
|
||||
"""The cached copy, downloading it first if needed. `download(partial)`
|
||||
writes the file and returns the server's `{size, mtime_ns}` for it."""
|
||||
path = self.path_for(facts)
|
||||
with self._lock_for(path.name):
|
||||
if path.is_file():
|
||||
self._touch(path)
|
||||
return path
|
||||
self.root.mkdir(parents=True, exist_ok=True)
|
||||
partial = path.with_name(f"{path.name}.{os.getpid()}.{threading.get_ident()}{_PART}")
|
||||
started = time.monotonic()
|
||||
try:
|
||||
meta = download(partial) or {}
|
||||
got = partial.stat().st_size
|
||||
if got != facts.size or (meta.get("size") and meta["size"] != facts.size):
|
||||
raise StaleFacts(f"{Path(facts.key).name} changed on the server while downloading")
|
||||
os.replace(partial, path)
|
||||
finally:
|
||||
partial.unlink(missing_ok=True)
|
||||
elapsed = max(time.monotonic() - started, 1e-3)
|
||||
if facts.size > 1 << 20:
|
||||
self._speeds = (self._speeds + [facts.size / elapsed])[-8:]
|
||||
self._touch(path)
|
||||
self.prune(keep={path})
|
||||
return path
|
||||
|
||||
def speed(self) -> float | None:
|
||||
"""A recent download speed in bytes/s, or None before the first."""
|
||||
if not self._speeds:
|
||||
return None
|
||||
ordered = sorted(self._speeds)
|
||||
return ordered[len(ordered) // 2]
|
||||
|
||||
def _touch(self, path: Path) -> None:
|
||||
now = self._clock()
|
||||
try:
|
||||
os.utime(path, (now, now))
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# ---- housekeeping ------------------------------------------------------------
|
||||
def _entries(self) -> list[tuple[float, int, Path]]:
|
||||
out = []
|
||||
if not self.root.is_dir():
|
||||
return out
|
||||
for p in self.root.iterdir():
|
||||
if p.name.endswith(_PART) or not p.is_file():
|
||||
continue
|
||||
try:
|
||||
st = p.stat()
|
||||
except OSError:
|
||||
continue
|
||||
out.append((st.st_mtime, st.st_size, p))
|
||||
return out
|
||||
|
||||
def prune(self, keep: set[Path] | None = None) -> int:
|
||||
"""Evict least-recently-used entries until under the cap. Returns bytes freed."""
|
||||
cap = self._cap() if callable(self._cap) else self._cap
|
||||
entries = sorted(self._entries())
|
||||
total = sum(size for _, size, _ in entries)
|
||||
freed = 0
|
||||
now = self._clock()
|
||||
for used, size, p in entries:
|
||||
if total <= cap:
|
||||
break
|
||||
if (keep and p in keep) or now - used < _RECENT:
|
||||
continue
|
||||
try:
|
||||
p.unlink()
|
||||
except OSError:
|
||||
continue # held open (Windows): next time
|
||||
total -= size
|
||||
freed += size
|
||||
return freed
|
||||
|
||||
def usage(self) -> dict:
|
||||
entries = self._entries()
|
||||
cap = self._cap() if callable(self._cap) else self._cap
|
||||
return {"bytes": sum(s for _, s, _ in entries), "files": len(entries), "cap": cap,
|
||||
"free": _free(self.root)}
|
||||
|
||||
def clear(self) -> int:
|
||||
freed = 0
|
||||
for _, size, p in self._entries():
|
||||
try:
|
||||
p.unlink()
|
||||
freed += size
|
||||
except OSError:
|
||||
pass
|
||||
return freed
|
||||
|
||||
|
||||
def _free(folder: Path) -> int:
|
||||
probe = folder
|
||||
while not probe.exists() and probe != probe.parent:
|
||||
probe = probe.parent
|
||||
try:
|
||||
return shutil.disk_usage(probe).free
|
||||
except OSError:
|
||||
return 0
|
||||
|
||||
|
||||
_shared: RemoteAudioCache | None = None
|
||||
|
||||
|
||||
def shared() -> RemoteAudioCache:
|
||||
global _shared
|
||||
if _shared is None:
|
||||
_shared = RemoteAudioCache()
|
||||
return _shared
|
||||
@@ -0,0 +1,302 @@
|
||||
"""Talking to a Konduktor server: addresses, sign-in, and the error vocabulary.
|
||||
|
||||
Every request tries the address that last worked, then the others in the
|
||||
remote's order (primary, then fallback) — so a laptop that leaves the house
|
||||
moves from the LAN address to the VPN one without being asked, and back again.
|
||||
Only a CONNECT failure moves on: the request never reached that server, so
|
||||
sending it to the other one cannot apply it twice. A request that reached a
|
||||
server and then failed is that server's answer.
|
||||
|
||||
The server's refusals come back as the adapter's own error classes (the same
|
||||
status codes `main.py` maps them from), so a route on this computer reports a
|
||||
remote library's refusal exactly as it would a local one's.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
|
||||
from ... import remote_protocol as rp
|
||||
from ...core.adapter import (
|
||||
AdapterError,
|
||||
InvalidCommand,
|
||||
LibraryNotSupported,
|
||||
NotFound,
|
||||
Unavailable,
|
||||
Unsupported,
|
||||
)
|
||||
from .config import Remote
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
_CONNECT_ERRORS = (httpx.ConnectError, httpx.ConnectTimeout)
|
||||
|
||||
|
||||
class Unreachable(Unavailable):
|
||||
"""No address of the remote answered."""
|
||||
|
||||
|
||||
class AuthFailed(LibraryNotSupported):
|
||||
"""The server refused the username or password."""
|
||||
|
||||
|
||||
class VersionMismatch(LibraryNotSupported):
|
||||
def __init__(self, update: str, server_version: str):
|
||||
side = "Konduktor on this computer" if update == "app" else "the Konduktor server"
|
||||
super().__init__(
|
||||
f"This server speaks a different version of Konduktor's protocol "
|
||||
f"(server {server_version}): update {side}."
|
||||
)
|
||||
self.update = update
|
||||
|
||||
|
||||
class InUse(AdapterError):
|
||||
"""Another computer holds the session: `holder` = {machine, since, batch}."""
|
||||
|
||||
def __init__(self, holder: dict):
|
||||
super().__init__(f"In use by {holder.get('machine') or 'another computer'}")
|
||||
self.holder = holder
|
||||
|
||||
|
||||
class SessionLost(Unavailable):
|
||||
"""This computer no longer holds the session (another one took over)."""
|
||||
|
||||
def __init__(self, holder: dict | None):
|
||||
who = (holder or {}).get("machine")
|
||||
super().__init__(
|
||||
f"{who} has taken over this library — it is read-only here" if who
|
||||
else "This computer no longer holds the library's session"
|
||||
)
|
||||
self.holder = holder
|
||||
|
||||
|
||||
def _detail(response: httpx.Response):
|
||||
try:
|
||||
return response.json().get("detail")
|
||||
except Exception: # noqa: BLE001
|
||||
return response.text[:300]
|
||||
|
||||
|
||||
class RemoteClient:
|
||||
def __init__(self, remote: Remote, password: str, *, timeout: float = 30.0):
|
||||
self.remote = remote
|
||||
self._addresses = remote.addresses()
|
||||
self._active: int | None = None
|
||||
self.token: str | None = None
|
||||
self._lock = threading.Lock()
|
||||
self._http = httpx.Client(
|
||||
auth=(remote.username, password),
|
||||
timeout=httpx.Timeout(timeout, connect=4.0),
|
||||
follow_redirects=False,
|
||||
)
|
||||
|
||||
def close(self) -> None:
|
||||
self._http.close()
|
||||
|
||||
@property
|
||||
def via(self) -> str | None:
|
||||
"""Which address is in use: "primary" / "fallback" (None until one answers)."""
|
||||
return None if self._active is None else self._addresses[self._active][0]
|
||||
|
||||
# ---- transport ----------------------------------------------------------------
|
||||
def _order(self) -> list[int]:
|
||||
everything = list(range(len(self._addresses)))
|
||||
if self._active is None:
|
||||
return everything
|
||||
return [self._active] + [i for i in everything if i != self._active]
|
||||
|
||||
def request(self, method: str, path: str, *, retry: bool = True, session: bool = True,
|
||||
**kw) -> httpx.Response:
|
||||
headers = dict(kw.pop("headers", None) or {})
|
||||
if session and self.token:
|
||||
headers[rp.SESSION_HEADER] = self.token
|
||||
order = self._order() if retry else ([self._active] if self._active is not None else [0])
|
||||
last: Exception | None = None
|
||||
for i in order:
|
||||
base = self._addresses[i][1]
|
||||
try:
|
||||
response = self._http.request(method, base + path, headers=headers, **kw)
|
||||
except _CONNECT_ERRORS as ex:
|
||||
last = ex
|
||||
continue
|
||||
except httpx.TimeoutException as ex:
|
||||
self._active = i
|
||||
raise Unreachable(f"The server at {base} stopped answering") from ex
|
||||
except httpx.TransportError as ex:
|
||||
last = ex
|
||||
continue
|
||||
self._active = i
|
||||
return self.check(response)
|
||||
names = " or ".join(b for _, b in (self._addresses[i] for i in order))
|
||||
raise Unreachable(f"Cannot reach the server at {names}") from last
|
||||
|
||||
def stream(self, method: str, path: str, **kw):
|
||||
"""A streaming request on the address in use (a download)."""
|
||||
headers = dict(kw.pop("headers", None) or {})
|
||||
if self.token:
|
||||
headers[rp.SESSION_HEADER] = self.token
|
||||
# Pick the address first with a cheap call, so the stream itself is not
|
||||
# the request that discovers the primary is gone.
|
||||
if self._active is None:
|
||||
self.request("GET", "/v1/hello", session=False)
|
||||
base = self._addresses[self._active][1]
|
||||
return self._http.stream(method, base + path, headers=headers, **kw)
|
||||
|
||||
@staticmethod
|
||||
def check(response: httpx.Response) -> httpx.Response:
|
||||
status = response.status_code
|
||||
if status < 400:
|
||||
return response
|
||||
detail = _detail(response)
|
||||
if status == 401:
|
||||
raise AuthFailed("The server refused the username or password")
|
||||
if status == 423:
|
||||
raise SessionLost((detail or {}).get("holder") if isinstance(detail, dict) else None)
|
||||
if status == 409 and isinstance(detail, dict) and detail.get("code") == "in_use":
|
||||
raise InUse(detail)
|
||||
text = detail if isinstance(detail, str) else (detail or {}).get("message", str(detail))
|
||||
cls = {404: NotFound, 400: InvalidCommand, 422: Unsupported, 503: Unavailable}.get(status)
|
||||
if cls is not None:
|
||||
raise cls(text)
|
||||
raise AdapterError(f"The server answered {status}: {text}")
|
||||
|
||||
# ---- handshake + session ----------------------------------------------------------
|
||||
def hello(self, client_id: str | None = None) -> dict:
|
||||
info = self.request("GET", "/v1/hello", params={"client_id": client_id} if client_id else None,
|
||||
session=False).json()
|
||||
server_version = tuple(info.get("api_version") or (0, 0))
|
||||
update = rp.compatible(rp.API_VERSION, (int(server_version[0]), int(server_version[1])))
|
||||
if update:
|
||||
raise VersionMismatch(update, info.get("app_version") or ".".join(map(str, server_version)))
|
||||
return info
|
||||
|
||||
def acquire(self, client_id: str, machine: str, *, takeover: bool = False) -> dict:
|
||||
body = self.request("POST", "/v1/session/acquire", session=False,
|
||||
json={"client_id": client_id, "machine": machine, "takeover": takeover}).json()
|
||||
self.token = body["token"]
|
||||
return body
|
||||
|
||||
def heartbeat(self, batch: str | None) -> dict:
|
||||
return self.request("POST", "/v1/session/heartbeat", json={"batch": batch}).json()
|
||||
|
||||
def release(self, *, timeout: float | None = None) -> None:
|
||||
if not self.token:
|
||||
return
|
||||
try:
|
||||
kw = {"timeout": timeout} if timeout is not None else {}
|
||||
self.request("POST", "/v1/session/release", retry=False, **kw)
|
||||
except AdapterError:
|
||||
pass
|
||||
self.token = None
|
||||
|
||||
# ---- the protocol -------------------------------------------------------------------
|
||||
def rpc(self, method: str, /, *, timeout=..., **args) -> dict:
|
||||
"""Call one protocol method; the envelope `{result, rev, changed, removed, reset}`
|
||||
with `result` already deserialised."""
|
||||
kw = {} if timeout is ... else {"timeout": timeout}
|
||||
body = self.request("POST", f"/v1/rpc/{method}", json={"args": rp.dump_args(method, args)}, **kw).json()
|
||||
body["result"] = rp.load_result(method, body.get("result"))
|
||||
return body
|
||||
|
||||
# ---- bytes -----------------------------------------------------------------------------
|
||||
def download(self, track_id: str, target: Path, *, progress=None) -> dict:
|
||||
"""Stream a track's audio into `target`; its server-side size and mtime."""
|
||||
with self.stream("GET", "/v1/audio", params={"track_id": track_id}, timeout=None) as response:
|
||||
if response.status_code >= 400:
|
||||
response.read()
|
||||
self.check(response)
|
||||
with open(target, "wb") as out:
|
||||
for chunk in response.iter_bytes(1 << 20):
|
||||
out.write(chunk)
|
||||
if progress is not None:
|
||||
progress(len(chunk))
|
||||
return {
|
||||
"size": int(response.headers.get("X-Konduktor-Size") or 0),
|
||||
"mtime_ns": int(response.headers.get("X-Konduktor-Mtime-Ns") or 0),
|
||||
}
|
||||
|
||||
def upload(self, source: Path, folder: str, name: str, *, progress=None) -> dict:
|
||||
def body():
|
||||
with open(source, "rb") as f:
|
||||
while chunk := f.read(1 << 20):
|
||||
if progress is not None:
|
||||
progress(len(chunk))
|
||||
yield chunk
|
||||
|
||||
return self.request("POST", "/v1/upload", params={"dir": folder, "name": name},
|
||||
content=body(), retry=False, timeout=None).json()
|
||||
|
||||
def delete_upload(self, path: str) -> None:
|
||||
self.request("DELETE", "/v1/upload", params={"path": path})
|
||||
|
||||
def art(self, track_id: str) -> tuple[bytes, str] | None:
|
||||
try:
|
||||
r = self.request("GET", "/v1/art", params={"track_id": track_id})
|
||||
except NotFound:
|
||||
return None
|
||||
return r.content, r.headers.get("content-type", "image/jpeg").split(";")[0]
|
||||
|
||||
def put_art(self, track_id: str, data: bytes, mime: str) -> dict:
|
||||
return self.request("PUT", "/v1/art", params={"track_id": track_id, "mime": mime},
|
||||
content=data).json()
|
||||
|
||||
def fs_list(self, path: str | None) -> dict:
|
||||
return self.request("GET", "/v1/fs/list", params={"path": path} if path else None).json()
|
||||
|
||||
def fs_space(self, path: str | None) -> int:
|
||||
return int(self.request("GET", "/v1/fs/space", params={"path": path} if path else None).json()["free"])
|
||||
|
||||
# ---- Convert to Stems ----------------------------------------------------------------
|
||||
def stems_plan(self, body: dict) -> dict:
|
||||
return self.request("POST", "/v1/stems/plan", json=body, timeout=None).json()
|
||||
|
||||
def stems_stage(self, track_id: str, target: str, source: Path, *, sha256: str,
|
||||
bit_rate: int, duration: float, progress=None) -> dict:
|
||||
def body():
|
||||
with open(source, "rb") as f:
|
||||
while chunk := f.read(1 << 20):
|
||||
if progress is not None:
|
||||
progress(len(chunk))
|
||||
yield chunk
|
||||
|
||||
return self.request(
|
||||
"PUT", "/v1/stems/stage",
|
||||
params={"track_id": track_id, "target": target, "sha256": sha256,
|
||||
"bit_rate": bit_rate, "duration": duration},
|
||||
content=body(), retry=False, timeout=None,
|
||||
).json()
|
||||
|
||||
def stems_abandon(self, targets: list[str]) -> None:
|
||||
self.request("POST", "/v1/stems/abandon", json={"targets": targets})
|
||||
|
||||
def stems_publish(self, items: list[dict], options: dict) -> dict:
|
||||
return self.request("POST", "/v1/stems/publish", json={"items": items, "options": options},
|
||||
timeout=None).json()
|
||||
|
||||
def stems_pending(self) -> dict:
|
||||
return self.request("GET", "/v1/stems/pending").json()
|
||||
|
||||
# ---- save / history / export sets -------------------------------------------------
|
||||
def save(self) -> dict:
|
||||
return self.request("POST", "/v1/save", timeout=None).json()
|
||||
|
||||
def discard(self) -> dict:
|
||||
return self.request("POST", "/v1/discard", timeout=None).json()
|
||||
|
||||
def history(self) -> list[dict]:
|
||||
return self.request("GET", "/v1/history").json()
|
||||
|
||||
def restore(self, commit_id: str) -> dict:
|
||||
return self.request("POST", f"/v1/history/{commit_id}/restore", timeout=None).json()
|
||||
|
||||
def clear_history(self) -> None:
|
||||
self.request("DELETE", "/v1/history")
|
||||
|
||||
def export_sets(self) -> dict:
|
||||
return self.request("GET", "/v1/export-sets").json()
|
||||
|
||||
def put_export_sets(self, doc: dict) -> None:
|
||||
self.request("PUT", "/v1/export-sets", json=doc)
|
||||
@@ -0,0 +1,192 @@
|
||||
"""Saved remotes: the servers this computer knows how to reach.
|
||||
|
||||
A remote is where a Konduktor server is (an address, an optional port, and a
|
||||
fallback address — typically the LAN address first and a VPN one second) and
|
||||
who to sign in as. Everything but the password is a plain preference
|
||||
(`userprefs.json`, key `remotes`); the password lives in the OS keychain
|
||||
(macOS Keychain, Windows Credential Manager) through `keyring`, never in a JSON
|
||||
file beside the app's other data.
|
||||
|
||||
This computer also has a stable `client_id`, which is how a server tells "the
|
||||
same laptop back from sleep" (renew its session silently) from "another
|
||||
computer" (offer a takeover).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import socket
|
||||
import uuid
|
||||
from dataclasses import asdict, dataclass
|
||||
|
||||
from ... import prefs
|
||||
|
||||
DEFAULT_PORT = 8765
|
||||
_PREFS_KEY = "remotes"
|
||||
_CLIENT_KEY = "remoteClientId"
|
||||
_KEYRING_SERVICE = "Konduktor"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Remote:
|
||||
id: str
|
||||
name: str
|
||||
host: str
|
||||
port: int | None = None
|
||||
fallback_host: str | None = None
|
||||
fallback_port: int | None = None
|
||||
username: str = ""
|
||||
|
||||
def addresses(self) -> list[tuple[str, str]]:
|
||||
"""`(label, base url)`, primary first — the order every connect tries."""
|
||||
out = [("primary", _base(self.host, self.port))]
|
||||
if self.fallback_host:
|
||||
out.append(("fallback", _base(self.fallback_host, self.fallback_port or self.port)))
|
||||
return out
|
||||
|
||||
def public(self) -> dict:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
def _base(host: str, port: int | None) -> str:
|
||||
host = host.strip()
|
||||
if host.startswith("http://") or host.startswith("https://"):
|
||||
# A full URL (behind the user's own reverse proxy): taken as given.
|
||||
return host.rstrip("/")
|
||||
bare, inline = split_host(host)
|
||||
if inline is not None:
|
||||
host, port = bare, port or inline
|
||||
if ":" in host and not host.startswith("["):
|
||||
host = f"[{host}]" # an IPv6 literal
|
||||
return f"http://{host}:{port or DEFAULT_PORT}"
|
||||
|
||||
|
||||
def split_host(text: str) -> tuple[str, int | None]:
|
||||
"""`"nas.local:9000"` → `("nas.local", 9000)`; a bare host keeps no port."""
|
||||
text = (text or "").strip()
|
||||
if text.startswith("http://") or text.startswith("https://"):
|
||||
return text, None
|
||||
if text.count(":") == 1:
|
||||
host, _, port = text.partition(":")
|
||||
if port.isdigit():
|
||||
return host, int(port)
|
||||
return text, None
|
||||
|
||||
|
||||
# ---- the list ------------------------------------------------------------------
|
||||
|
||||
|
||||
def remotes() -> list[Remote]:
|
||||
raw = prefs.load_prefs().get(_PREFS_KEY) or []
|
||||
out = []
|
||||
for item in raw if isinstance(raw, list) else []:
|
||||
try:
|
||||
out.append(Remote(**{k: item.get(k) for k in Remote.__dataclass_fields__ if k in item}))
|
||||
except TypeError:
|
||||
continue
|
||||
return out
|
||||
|
||||
|
||||
def get(remote_id: str) -> Remote | None:
|
||||
return next((r for r in remotes() if r.id == remote_id), None)
|
||||
|
||||
|
||||
def save(remote: Remote) -> Remote:
|
||||
items = [r for r in remotes() if r.id != remote.id] + [remote]
|
||||
prefs.update_prefs({_PREFS_KEY: [r.public() for r in items]})
|
||||
return remote
|
||||
|
||||
|
||||
def delete(remote_id: str) -> bool:
|
||||
before = remotes()
|
||||
items = [r for r in before if r.id != remote_id]
|
||||
prefs.update_prefs({_PREFS_KEY: [r.public() for r in items]})
|
||||
forget_password(remote_id)
|
||||
return len(items) != len(before)
|
||||
|
||||
|
||||
def new_id() -> str:
|
||||
return uuid.uuid4().hex[:12]
|
||||
|
||||
|
||||
# ---- this computer ---------------------------------------------------------------
|
||||
|
||||
|
||||
def client_id() -> str:
|
||||
current = prefs.load_prefs().get(_CLIENT_KEY)
|
||||
if isinstance(current, str) and current:
|
||||
return current
|
||||
fresh = uuid.uuid4().hex
|
||||
prefs.update_prefs({_CLIENT_KEY: fresh})
|
||||
return fresh
|
||||
|
||||
|
||||
def machine_name() -> str:
|
||||
"""What another computer is told holds the library ("Ben's MacBook")."""
|
||||
try:
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
if sys.platform == "darwin":
|
||||
name = subprocess.run(["scutil", "--get", "ComputerName"], capture_output=True,
|
||||
text=True, timeout=2).stdout.strip()
|
||||
if name:
|
||||
return name
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
name = socket.gethostname()
|
||||
return name[:-6] if name.endswith(".local") else name
|
||||
|
||||
|
||||
# ---- the password ------------------------------------------------------------------
|
||||
# A seam for tests (and any machine without a keychain): `use_password_store`.
|
||||
|
||||
|
||||
class _Keyring:
|
||||
def get(self, account: str) -> str | None:
|
||||
import keyring
|
||||
|
||||
return keyring.get_password(_KEYRING_SERVICE, account)
|
||||
|
||||
def set(self, account: str, password: str) -> None:
|
||||
import keyring
|
||||
|
||||
keyring.set_password(_KEYRING_SERVICE, account, password)
|
||||
|
||||
def delete(self, account: str) -> None:
|
||||
import keyring
|
||||
from keyring.errors import PasswordDeleteError
|
||||
|
||||
try:
|
||||
keyring.delete_password(_KEYRING_SERVICE, account)
|
||||
except PasswordDeleteError:
|
||||
pass
|
||||
|
||||
|
||||
_store = _Keyring()
|
||||
|
||||
|
||||
def use_password_store(store) -> None:
|
||||
"""Replace the keychain (`get`/`set`/`delete` by account) — tests only."""
|
||||
global _store
|
||||
_store = store if store is not None else _Keyring()
|
||||
|
||||
|
||||
def _account(remote_id: str) -> str:
|
||||
return f"remote:{remote_id}"
|
||||
|
||||
|
||||
def password(remote_id: str) -> str | None:
|
||||
try:
|
||||
return _store.get(_account(remote_id))
|
||||
except Exception: # noqa: BLE001 — a locked keychain reads as "no password"
|
||||
return None
|
||||
|
||||
|
||||
def set_password(remote_id: str, value: str) -> None:
|
||||
_store.set(_account(remote_id), value)
|
||||
|
||||
|
||||
def forget_password(remote_id: str) -> None:
|
||||
try:
|
||||
_store.delete(_account(remote_id))
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
@@ -0,0 +1,85 @@
|
||||
"""A remote library's app-level bookkeeping — kept on the server, beside it.
|
||||
|
||||
Version history, export sets and the stems ledger belong with the library, not
|
||||
with whichever computer opened it: they are what every computer that opens it
|
||||
should see. So for a remote library these are calls to the server, and this
|
||||
computer's app-data holds none of them (`services.py` is the local half).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from ...core.adapter import NotFound
|
||||
from ...history import HistoryEntry
|
||||
from .client import RemoteClient
|
||||
|
||||
|
||||
class RemoteServices:
|
||||
remote = True
|
||||
|
||||
def __init__(self, client: RemoteClient):
|
||||
self.client = client
|
||||
|
||||
def baseline(self) -> None:
|
||||
pass # the server records its own "as I found it" version when it opens
|
||||
|
||||
def commit_save(self, adapter, outcome) -> str | None:
|
||||
# The server versioned the save itself; its commit rides on the outcome.
|
||||
return getattr(outcome, "commit", None)
|
||||
|
||||
def history(self) -> list[HistoryEntry]:
|
||||
return [HistoryEntry(**e) for e in self.client.history()]
|
||||
|
||||
def restore(self, commit_id: str) -> bool:
|
||||
try:
|
||||
self.client.restore(commit_id)
|
||||
except NotFound:
|
||||
return False
|
||||
return True
|
||||
|
||||
def clear_history(self) -> None:
|
||||
self.client.clear_history()
|
||||
|
||||
def discard(self) -> None:
|
||||
self.client.discard()
|
||||
|
||||
|
||||
class RemoteSetStore:
|
||||
"""`exports.use_store`'s store for a remote library: its sets, on the server."""
|
||||
|
||||
def __init__(self, client: RemoteClient):
|
||||
self.client = client
|
||||
|
||||
def read(self) -> dict:
|
||||
return self.client.export_sets()
|
||||
|
||||
def write(self, doc: dict) -> None:
|
||||
self.client.put_export_sets(doc)
|
||||
|
||||
|
||||
class RemotePending:
|
||||
"""`AppState.pending` for a remote library: the SERVER keeps the ledger of
|
||||
converted tracks awaiting Save (and commits, restores and recovers it
|
||||
itself), so on this computer there is nothing to commit or restore — only
|
||||
the server's summary to report, and its "blocking" to honour."""
|
||||
|
||||
items: list = []
|
||||
|
||||
def __init__(self, client: RemoteClient):
|
||||
self.client = client
|
||||
|
||||
def summary(self) -> dict:
|
||||
try:
|
||||
return self.client.stems_pending()
|
||||
except Exception: # noqa: BLE001 — out of reach: nothing known to be pending
|
||||
return {"tracks": 0, "parked": 0, "bytes": 0}
|
||||
|
||||
def blocking(self) -> bool:
|
||||
return bool(self.summary().get("tracks"))
|
||||
|
||||
def swapped(self) -> list:
|
||||
return []
|
||||
|
||||
def restore(self) -> int:
|
||||
return 0
|
||||
|
||||
def commit(self) -> dict:
|
||||
return {}
|
||||
@@ -0,0 +1,159 @@
|
||||
"""This computer's hold on a remote library's session.
|
||||
|
||||
The server lets ONE computer edit at a time (`server/session.py`); this keeps
|
||||
this computer's hold alive with a heartbeat every `HEARTBEAT_SECONDS`, and is
|
||||
the one place that knows how this computer stands:
|
||||
|
||||
connected — holding the session; edits go through
|
||||
reconnecting — a heartbeat failed to reach the server; edits still try
|
||||
(each request walks the addresses again)
|
||||
offline — several in a row failed; read-only until one gets through
|
||||
taken_over — another computer took the session; read-only, for good
|
||||
|
||||
Coming back from `reconnecting` or `offline` needs no new sign-in: the server
|
||||
renews a lapsed lease for the computer that held it, as long as nobody else
|
||||
has taken it meanwhile — and says so (423) if somebody has.
|
||||
|
||||
The heartbeat names the batch running here, so a computer asking to take over
|
||||
is told what it would cancel. Being taken over cancels it (`on_change`).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
|
||||
from ...core.adapter import Unavailable
|
||||
from ...remote_protocol import HEARTBEAT_SECONDS
|
||||
from .client import RemoteClient, SessionLost
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
#: Missed heartbeats in a row before `reconnecting` becomes `offline`.
|
||||
OFFLINE_AFTER = 3
|
||||
|
||||
|
||||
class RemoteSession:
|
||||
def __init__(self, client: RemoteClient, *, batch_probe=None, interval: float = HEARTBEAT_SECONDS,
|
||||
identity: tuple[str, str] | None = None):
|
||||
self.client = client
|
||||
self.interval = interval
|
||||
self._batch_probe = batch_probe or (lambda: None)
|
||||
#: (client_id, machine) — to take the session back when the server has
|
||||
#: forgotten it (a restart) and nobody else holds it.
|
||||
self.identity = identity
|
||||
self.state = "connected"
|
||||
self.machine: str | None = None # who took it over
|
||||
#: The last thing worth telling the user that is not a state ("the
|
||||
#: server restarted"), with a counter so the UI shows each once.
|
||||
self.notice: str | None = None
|
||||
self.notices = 0
|
||||
#: Called after the session was taken back: the library must be re-read.
|
||||
self.on_reacquired = None
|
||||
self._failures = 0
|
||||
self._listeners: list = []
|
||||
self._stop = threading.Event()
|
||||
self._thread: threading.Thread | None = None
|
||||
self._lock = threading.Lock()
|
||||
|
||||
# ---- facts ---------------------------------------------------------------------
|
||||
@property
|
||||
def writable(self) -> bool:
|
||||
return self.state in ("connected", "reconnecting")
|
||||
|
||||
@property
|
||||
def readonly_cause(self) -> str | None:
|
||||
return {"taken_over": "taken_over", "offline": "offline"}.get(self.state)
|
||||
|
||||
def describe(self) -> dict:
|
||||
return {"state": self.state, "via": self.client.via if self.state != "offline" else None,
|
||||
"machine": self.machine, "notice": self.notice, "notices": self.notices}
|
||||
|
||||
def on_change(self, listener) -> None:
|
||||
"""`listener(state)` after every change of state (from the heartbeat thread)."""
|
||||
self._listeners.append(listener)
|
||||
|
||||
# ---- running -------------------------------------------------------------------
|
||||
def start(self) -> None:
|
||||
if self._thread is None:
|
||||
self._thread = threading.Thread(target=self._run, name="konduktor-remote-heartbeat",
|
||||
daemon=True)
|
||||
self._thread.start()
|
||||
|
||||
def stop(self) -> None:
|
||||
self._stop.set()
|
||||
|
||||
def _run(self) -> None:
|
||||
while not self._stop.wait(self.interval):
|
||||
if self.state == "taken_over":
|
||||
return
|
||||
self.beat()
|
||||
|
||||
def beat(self) -> None:
|
||||
try:
|
||||
self.client.heartbeat(self._batch_probe())
|
||||
except SessionLost as ex:
|
||||
self.lost(ex.holder)
|
||||
return
|
||||
except Unavailable:
|
||||
self._failures += 1
|
||||
self._set("offline" if self._failures >= OFFLINE_AFTER else "reconnecting")
|
||||
return
|
||||
except Exception: # noqa: BLE001 — a bad answer is a missed beat, not a crash
|
||||
log.exception("heartbeat failed")
|
||||
self._failures += 1
|
||||
self._set("offline" if self._failures >= OFFLINE_AFTER else "reconnecting")
|
||||
return
|
||||
self._failures = 0
|
||||
self._set("connected")
|
||||
|
||||
def _take_back(self) -> bool:
|
||||
"""The server no longer knows this computer's token and nobody holds the
|
||||
session — it restarted (unsaved edits went with it, an accepted loss).
|
||||
Take the session back without asking, unless the library now holds
|
||||
someone ELSE's unsaved edits: those deserve the Save / Discard question
|
||||
that reopening asks, so then this stays read-only."""
|
||||
if self.identity is None:
|
||||
return False
|
||||
try:
|
||||
got = self.client.acquire(*self.identity)
|
||||
except Exception: # noqa: BLE001 — someone got there first, or no server
|
||||
return False
|
||||
if got.get("pending_edits"):
|
||||
self.client.release()
|
||||
return False
|
||||
if self.on_reacquired is not None:
|
||||
try:
|
||||
self.on_reacquired()
|
||||
except Exception: # noqa: BLE001
|
||||
log.exception("re-reading the library after a reconnect failed")
|
||||
self.notice = "The server restarted — any edits not yet saved there were lost"
|
||||
self.notices += 1
|
||||
self._failures = 0
|
||||
self._set("connected")
|
||||
return True
|
||||
|
||||
def lost(self, holder: dict | None) -> None:
|
||||
"""Another computer holds the session — from a heartbeat, or a command
|
||||
the server refused with 423. Nobody holding it means the server forgot
|
||||
this computer's token (a restart): take it back if that is safe."""
|
||||
if holder is None and self.state != "taken_over" and self._take_back():
|
||||
return
|
||||
self.machine = (holder or {}).get("machine")
|
||||
self._set("taken_over")
|
||||
|
||||
def reached(self) -> None:
|
||||
"""A request got through: whatever the heartbeat last saw, the server is there."""
|
||||
if self.state in ("reconnecting", "offline"):
|
||||
self._failures = 0
|
||||
self._set("connected")
|
||||
|
||||
def _set(self, state: str) -> None:
|
||||
with self._lock:
|
||||
if state == self.state:
|
||||
return
|
||||
self.state = state
|
||||
for listener in list(self._listeners):
|
||||
try:
|
||||
listener(state)
|
||||
except Exception: # noqa: BLE001
|
||||
log.exception("remote session listener failed")
|
||||
@@ -15,7 +15,7 @@ from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
from ...core.adapter import InvalidCommand, NotFound, Unsupported
|
||||
from ...core.adapter import InvalidCommand, NotFound, Unsupported, local_audio_facts
|
||||
from ...core.capabilities import Capabilities
|
||||
from ...core.model import PlaylistNode, Track, TrackCues
|
||||
from ...core.pathmap import PathMapping
|
||||
@@ -383,12 +383,22 @@ class TraktorAdapter:
|
||||
def audio_path(self, track_id: str):
|
||||
return self._store.audio_path(track_id)
|
||||
|
||||
def audio_facts(self, track_ids: list[str]):
|
||||
return local_audio_facts(self, track_ids)
|
||||
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None:
|
||||
self._store.set_path_mapping(mapping)
|
||||
|
||||
def set_session_mappings(self, mappings: list[PathMapping]) -> None:
|
||||
self._store.set_session_mappings(mappings)
|
||||
|
||||
def set_write_stored_paths(self, enabled: bool) -> None:
|
||||
"""OPTIONAL: write a file added through the path mapping in the
|
||||
library's STORED form (see `pathmap.stored_form`). A Konduktor server
|
||||
holding a collection made on another computer turns this on, so a
|
||||
track uploaded there is stored as that computer would have stored it."""
|
||||
self._store.set_write_stored_paths(enabled)
|
||||
|
||||
def unresolved_path_groups(self) -> list[PathGroup]:
|
||||
return self._store.unresolved_path_groups()
|
||||
|
||||
@@ -411,6 +421,12 @@ class TraktorAdapter:
|
||||
def dirty(self) -> bool:
|
||||
return self._store.dirty
|
||||
|
||||
def edit_summary(self) -> str:
|
||||
"""OPTIONAL: this session's unsaved edits in one line ("edited 3
|
||||
tracks; added 6 hotcues") — what a server tells the next computer to
|
||||
open the library about the edits it is inheriting."""
|
||||
return self._store._edit_summary()
|
||||
|
||||
def save(self):
|
||||
outcome = self._store.save()
|
||||
self._rebuild() # save() re-parses, so every object identity changed
|
||||
|
||||
@@ -49,7 +49,7 @@ from xsdata.formats.dataclass.serializers import XmlSerializer
|
||||
from ...core.adapter import FileTagResult, InvalidCommand, SaveOutcome, StemSwapResult
|
||||
from ...core.edit_journal import EditJournal
|
||||
from ...core.pathmap import common_dir_prefix
|
||||
from ...core.pathmap import PathMapping
|
||||
from ...core.pathmap import PathMapping, stored_form
|
||||
from ...core.relocate import PathGroup
|
||||
from ...core.stem_file import NML_STEMS_JSON, nml_stems_for
|
||||
from ...schemas import PlaylistNode
|
||||
@@ -79,6 +79,9 @@ class TraktorStore:
|
||||
self.dirty = False
|
||||
# Active OS-path prefix remapping (empty = identity). Survives _load().
|
||||
self._path_mapping = PathMapping()
|
||||
# Write a file added through a mapping in the library's STORED form
|
||||
# (`pathmap.stored_form`) — a Konduktor server sets this.
|
||||
self._write_stored_paths = False
|
||||
# Mappings the user confirmed in the open-time missing-files check.
|
||||
# Session-only: never saved, re-derived on every open.
|
||||
self._session_mappings: list[PathMapping] = []
|
||||
@@ -494,7 +497,7 @@ class TraktorStore:
|
||||
# Read before the lock: it opens the file.
|
||||
stems = nml_stems_for(audio_path)
|
||||
with self._lock:
|
||||
volume, dir_, file = os_path_to_location(Path(audio_path))
|
||||
volume, dir_, file = os_path_to_location(self._stored(Path(audio_path)))
|
||||
key = f"{volume}{dir_}{file}"
|
||||
if key in self._entry_by_key:
|
||||
raise PlaylistError(
|
||||
@@ -1060,6 +1063,15 @@ class TraktorStore:
|
||||
with self._lock:
|
||||
self._path_mapping = mapping
|
||||
|
||||
def set_write_stored_paths(self, enabled: bool) -> None:
|
||||
self._write_stored_paths = bool(enabled)
|
||||
|
||||
def _stored(self, os_path: Path) -> Path:
|
||||
"""Where a NEW entry points, as the collection stores paths."""
|
||||
if not self._write_stored_paths:
|
||||
return Path(os_path)
|
||||
return stored_form(Path(os_path), [self._path_mapping, *self._session_mappings])
|
||||
|
||||
def set_session_mappings(self, mappings: list[PathMapping]) -> None:
|
||||
"""Set the mappings confirmed for this session (applied at resolve time)."""
|
||||
with self._lock:
|
||||
@@ -1355,7 +1367,7 @@ class TraktorStore:
|
||||
if swap.mode not in ("repoint", "add"):
|
||||
raise PlaylistError(f"Unknown stem swap mode: {swap.mode}")
|
||||
seen_ids.add(swap.track_id)
|
||||
loc = os_path_to_location(Path(swap.stem_path))
|
||||
loc = os_path_to_location(self._stored(Path(swap.stem_path)))
|
||||
new_key = "".join(x or "" for x in loc)
|
||||
if new_key in self._entry_by_key or new_key in new_keys:
|
||||
raise PlaylistError(
|
||||
|
||||
@@ -28,11 +28,12 @@ import os
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from . import __version__, adapters, history, library_id, prefs # noqa: F401 — registers adapters
|
||||
from . import adapters, library_id, prefs # noqa: F401 — registers adapters
|
||||
from .core import registry
|
||||
from .core.adapter import LibraryAdapter
|
||||
from .core.pathmap import PathMapping
|
||||
from .relocation import RelocationCheck
|
||||
from .services import LibraryServices, LocalServices
|
||||
|
||||
|
||||
class AppState:
|
||||
@@ -61,6 +62,18 @@ class AppState:
|
||||
# and what the last open's crash recovery did about any left over.
|
||||
self.pending = None
|
||||
self.recovery: dict | None = None
|
||||
# Where this library's history (and, for a remote, its export sets and
|
||||
# ledger) are kept — see `services.py`.
|
||||
self.services: LibraryServices | None = None
|
||||
# The open remote's connection (`adapters/remote/session.py`), or None
|
||||
# for a library on this computer.
|
||||
self.remote = None
|
||||
# …and the saved remote it was opened through (`adapters/remote/config.py`).
|
||||
self.remote_config = None
|
||||
# Called with the adapter at the end of every open (and so after a
|
||||
# restore, which reopens): how a Konduktor SERVER re-applies the path
|
||||
# mapping its configuration names, which lives in no prefs file.
|
||||
self.open_hooks: list = []
|
||||
|
||||
@property
|
||||
def loaded(self) -> bool:
|
||||
@@ -120,16 +133,7 @@ class AppState:
|
||||
# write-ahead log beside a file another process replaces is how a SQLite
|
||||
# library gets corrupted. Only close once the new one has parsed, so a
|
||||
# failed open leaves the current library intact.
|
||||
previous = self.adapter
|
||||
# Leaving a library discards its unsaved edits (the UI has confirmed), so
|
||||
# a stem conversion's parked originals go back under their own names.
|
||||
if self.pending is not None and self.pending.items:
|
||||
self.pending.restore()
|
||||
if previous is not None and hasattr(previous, "close"):
|
||||
try:
|
||||
previous.close()
|
||||
except Exception: # noqa: BLE001 — a failed close must not block the open
|
||||
pass
|
||||
self._release_previous()
|
||||
# Apply this library's saved OS-path remapping (per-machine, keyed by the
|
||||
# library's local path) so runtime translation is live on open.
|
||||
saved = prefs.get_path_mapping(str(path))
|
||||
@@ -161,9 +165,55 @@ class AppState:
|
||||
# Started after the saved mapping is applied, so a volume that mapping
|
||||
# already fixes is not asked about.
|
||||
self.relocation = RelocationCheck(adapter)
|
||||
# Version history: record an "as I found it" baseline (deduped, so
|
||||
# re-opening an unchanged library is a no-op). Best-effort.
|
||||
history.ensure_baseline(path)
|
||||
self.services = LocalServices(path)
|
||||
self.services.baseline()
|
||||
for hook in self.open_hooks:
|
||||
hook(adapter)
|
||||
|
||||
def _release_previous(self) -> None:
|
||||
previous = self.adapter
|
||||
# Leaving a library discards its unsaved edits (the UI has confirmed), so
|
||||
# a stem conversion's parked originals go back under their own names.
|
||||
if self.pending is not None and self.pending.items:
|
||||
self.pending.restore()
|
||||
if previous is not None and hasattr(previous, "close"):
|
||||
try:
|
||||
previous.close()
|
||||
except Exception: # noqa: BLE001 — a failed close must not block the open
|
||||
pass
|
||||
if self.remote is not None and self.library_id:
|
||||
# A remote library's export sets were the server's; stop asking it.
|
||||
from . import exports
|
||||
|
||||
exports.use_store(self.library_id, None)
|
||||
self.adapter = None
|
||||
self.remote = None
|
||||
self.remote_config = None
|
||||
|
||||
def open_remote(self, opened) -> None:
|
||||
"""Make an already-connected remote library THE library.
|
||||
|
||||
`opened` is what `adapters.remote.open_remote` returns: the adapter, its
|
||||
services and session, and the server's identity for the library. The
|
||||
connection (handshake, version check, session) is made BEFORE this, so
|
||||
a refusal leaves the current library intact, as a failed parse does.
|
||||
"""
|
||||
with self.mutation:
|
||||
self._release_previous()
|
||||
self.path = opened.path
|
||||
self.adapter = opened.adapter
|
||||
self.services = opened.services
|
||||
self.remote = opened.session
|
||||
self.remote_config = opened.remote
|
||||
# The server's id for the library: export sets are keyed by it, and
|
||||
# they live on the server too, so every computer sees the same ones.
|
||||
self.library_id = opened.library_id
|
||||
# The server keeps its own ledger of converted tracks; nothing of a
|
||||
# remote library's lives in this computer's.
|
||||
self.pending = opened.pending
|
||||
self.recovery = None
|
||||
# A remote library's files are not on this computer's drives.
|
||||
self.relocation = None
|
||||
|
||||
def save(self):
|
||||
"""Write the library, then record the saved bytes in version history.
|
||||
@@ -178,15 +228,7 @@ class AppState:
|
||||
|
||||
def _save(self):
|
||||
outcome = self.adapter.save()
|
||||
# Not every platform is versioned. A library that is more than one file
|
||||
# has no single blob that IS the library, and it says so through its
|
||||
# capabilities rather than this module knowing which platforms those are.
|
||||
versioned = self.adapter.capabilities().save.history
|
||||
commit = None
|
||||
if versioned and outcome.snapshot is not None:
|
||||
commit = history.commit(
|
||||
self.path, outcome.snapshot, outcome.summary, __version__
|
||||
)
|
||||
commit = self.services.commit_save(self.adapter, outcome)
|
||||
# The swap is now on disk: what it replaced can go. After the library
|
||||
# write, so a failed save deletes nothing; here rather than in the save
|
||||
# route, because import and path remap save too.
|
||||
@@ -209,8 +251,25 @@ class AppState:
|
||||
with self.mutation:
|
||||
if self.pending is not None and self.pending.items:
|
||||
self.pending.restore()
|
||||
if self.services is not None and self.services.remote:
|
||||
# The server holds the edits; it is what drops them.
|
||||
self.services.discard()
|
||||
self.adapter.reload()
|
||||
|
||||
def restore_version(self, commit_id: str) -> bool:
|
||||
"""Write a past version back as a new save and re-read the library.
|
||||
False when the version is unknown."""
|
||||
assert self.adapter is not None and self.services is not None
|
||||
with self.mutation:
|
||||
if not self.services.restore(commit_id):
|
||||
return False
|
||||
if self.services.remote:
|
||||
# The server reopened its own library; follow it.
|
||||
self.adapter.reload()
|
||||
else:
|
||||
self._open(self.path) # rebuild read + edit models from the restored file
|
||||
return True
|
||||
|
||||
|
||||
STATE = AppState()
|
||||
|
||||
|
||||
@@ -65,6 +65,60 @@ class SaveOutcome:
|
||||
tag_results: list = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AudioFacts:
|
||||
"""One track's audio file as its library's host sees it — WITHOUT reading it.
|
||||
|
||||
`key` is the file's path on the machine that holds it (a string, because on
|
||||
a remote library that is not this machine), `size` and `mtime_ns` its stat.
|
||||
Together they name one version of one file: what an export's manifest
|
||||
records, what the analysis cache keys on, and how a downloaded copy is
|
||||
recognised. Callers that only need a file's IDENTITY ask for these rather
|
||||
than `audio_path`, which on a remote library means downloading it.
|
||||
"""
|
||||
|
||||
key: str
|
||||
size: int
|
||||
mtime_ns: int
|
||||
|
||||
|
||||
def local_audio_facts(adapter, track_ids) -> dict[str, AudioFacts]:
|
||||
"""`audio_facts` for a library whose files are on this machine: stat each
|
||||
`audio_path`. A track whose file is missing is left out."""
|
||||
out: dict[str, AudioFacts] = {}
|
||||
for track_id in track_ids:
|
||||
try:
|
||||
path = adapter.audio_path(track_id)
|
||||
if path is None:
|
||||
continue
|
||||
st = Path(path).stat()
|
||||
except (OSError, AdapterError):
|
||||
continue
|
||||
if not Path(path).is_file():
|
||||
continue
|
||||
out[track_id] = AudioFacts(key=str(path), size=st.st_size, mtime_ns=st.st_mtime_ns)
|
||||
return out
|
||||
|
||||
|
||||
@dataclass
|
||||
class PreparedAnalysis:
|
||||
"""What adding a track would otherwise decode the file to learn.
|
||||
|
||||
A platform that must ANALYSE what it adds (Rekordbox: the waveform and grid
|
||||
live in its ANLZ files) decodes each file in `add_tracks`. When the library
|
||||
lives on a server that never decodes audio, the client does that work on
|
||||
its own copy and the result travels with the track. `measured` is a
|
||||
`core.waveform.Analysis` measured with the file's own time-base lead,
|
||||
`markers` the detected grid (empty: none found) and `key` the detected
|
||||
`core.key_detect.KeyResult` (None: not asked for, or none found). Absent,
|
||||
the adapter decodes as before.
|
||||
"""
|
||||
|
||||
measured: object
|
||||
markers: list = field(default_factory=list)
|
||||
key: object | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class NewTrack:
|
||||
"""A track to ADD to a library, described generically.
|
||||
@@ -93,6 +147,9 @@ class NewTrack:
|
||||
# For a platform that keeps its own copy of the art (Rekordbox); one that
|
||||
# reads the file's tags (Traktor) ignores it.
|
||||
art: tuple[bytes, str] | None = None
|
||||
# Precomputed analysis for a platform that would otherwise decode the file
|
||||
# (see `PreparedAnalysis`); ignored by one that does not analyse.
|
||||
analysis: PreparedAnalysis | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -153,6 +210,11 @@ class Unsupported(AdapterError):
|
||||
"""The platform cannot represent this edit at all."""
|
||||
|
||||
|
||||
class Unavailable(AdapterError):
|
||||
"""The library's host cannot be reached, or no longer lets this computer
|
||||
write (a library held by a server, taken over by another computer)."""
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class LibraryAdapter(Protocol):
|
||||
"""One open library. Stateful; exactly one is loaded at a time."""
|
||||
@@ -172,6 +234,7 @@ class LibraryAdapter(Protocol):
|
||||
def facets(self) -> Facets: ...
|
||||
def stats(self, playlist_count: int) -> Stats: ...
|
||||
def playlist_tree(self) -> list[PlaylistNode]: ...
|
||||
def playlist_count(self) -> int: ...
|
||||
def playlist_entries(self, node_id: str) -> list[str] | None: ...
|
||||
def playlist_tracks(self, node_id: str) -> list[Track] | None: ...
|
||||
def track_cues(self, track_id: str) -> TrackCues | None: ...
|
||||
@@ -260,7 +323,12 @@ class LibraryAdapter(Protocol):
|
||||
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues: ...
|
||||
|
||||
# ---- audio / paths ---------------------------------------------------
|
||||
# A READABLE file on this machine — which, for a library held by a server,
|
||||
# means downloading it. Anything that only needs to know WHICH file a track
|
||||
# is (an export plan, "is this already in the library?") asks `audio_facts`
|
||||
# instead, which never reads the file and never downloads.
|
||||
def audio_path(self, track_id: str) -> Path | None: ...
|
||||
def audio_facts(self, track_ids: list[str]) -> dict[str, AudioFacts]: ...
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None: ...
|
||||
# The open-time missing-files check (`core/relocate.py`): the stored volumes
|
||||
# in which NO track resolves, and the mappings the user confirmed for them —
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
"""The analysis a platform that ANALYSES what it adds needs for one new track.
|
||||
|
||||
Rekordbox draws a new track's waveform and grid from its ANLZ files, so adding a
|
||||
track means decoding it once: the waveform measured on the platform's own clock
|
||||
(`lead`, read from the file's header by that platform) plus a detected grid and
|
||||
key when the track brings none. One definition, used both by the adapter (a library on
|
||||
this computer) and by the client of a library held by a server — which never
|
||||
decodes audio, so the client measures its own copy and sends the result
|
||||
(`PreparedAnalysis`) with the track.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
from .adapter import PreparedAnalysis
|
||||
from .model import GridMarker
|
||||
|
||||
|
||||
def prepare(path: Path, *, lead: float, detect: bool = True,
|
||||
detect_key: bool = False) -> PreparedAnalysis:
|
||||
"""Decode `path` once: its waveform at `lead`, and (with `detect`) a grid,
|
||||
(with `detect_key`) a key."""
|
||||
from . import grid_detect, waveform
|
||||
|
||||
samples = waveform.decode(Path(path))
|
||||
measured = waveform.analyse_samples(samples, lead=lead)
|
||||
markers: list[GridMarker] = []
|
||||
if detect and samples is not None:
|
||||
try:
|
||||
found = grid_detect.detect_grid(str(path), y=samples, sr=waveform.SR)
|
||||
markers = [GridMarker(start=found.anchor, bpm=found.bpm)]
|
||||
except ValueError:
|
||||
pass # no pulse to fit (a one-shot, silence): no grid
|
||||
key = None
|
||||
if detect_key and samples is not None:
|
||||
from . import key_detect
|
||||
|
||||
try:
|
||||
key = key_detect.detect_key_samples(samples, waveform.SR)
|
||||
except Exception: # noqa: BLE001 - a missing key is not worth failing an add over
|
||||
logging.getLogger(__name__).warning("key detection failed", exc_info=True)
|
||||
return PreparedAnalysis(measured=measured, markers=markers, key=key)
|
||||
|
||||
|
||||
def with_key(track, key):
|
||||
"""`track` (a generic `Track`) with the detected `key` if it has none of its
|
||||
own. A key the track already carries (its tags, its source library) is
|
||||
never second-guessed."""
|
||||
if key is None or getattr(track, "key_wheel", None) is not None:
|
||||
return track
|
||||
return track.model_copy(update={"key": key.name, "key_wheel": key.wheel, "key_mode": key.mode})
|
||||
@@ -25,7 +25,12 @@ from pydantic import BaseModel
|
||||
# `browsing` is an editable library opened only to READ alongside the loaded one
|
||||
# (a OneLibrary stick in the sidebar's Devices): the way to edit it is to open it
|
||||
# as THE library, which one SaveBar and one dirty state can then follow.
|
||||
ReadonlyCause = Literal["platform_incomplete", "cloud_synced", "not_in_library", "browsing"]
|
||||
# `taken_over` is a library held by a server that another computer has taken
|
||||
# over; `offline` one whose server cannot be reached. Both are temporary, and
|
||||
# both mean "nothing you do here can be saved" until the session is back.
|
||||
ReadonlyCause = Literal[
|
||||
"platform_incomplete", "cloud_synced", "not_in_library", "browsing", "taken_over", "offline",
|
||||
]
|
||||
|
||||
CueType = Literal["cue", "fade_in", "fade_out", "load", "loop"]
|
||||
CueRole = Literal["hotcue", "memory"]
|
||||
@@ -87,6 +92,14 @@ class TrackCapabilities(BaseModel):
|
||||
audio_formats: list[str] = [".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a"]
|
||||
artwork: bool = False
|
||||
artwork_note: str | None = None
|
||||
# Whose filesystem an import destination is on. "host": this computer's,
|
||||
# browsed with the ordinary file browser. "library": the machine that holds
|
||||
# the library (a server), whose folders are listed through the library —
|
||||
# added audio is UPLOADED there.
|
||||
audio_destination: Literal["host", "library"] = "host"
|
||||
# Whether added files can be left where they are ("reference") rather than
|
||||
# copied. False where the library cannot see this computer's files at all.
|
||||
reference: bool = True
|
||||
|
||||
|
||||
class PlaylistCapabilities(BaseModel):
|
||||
@@ -95,6 +108,13 @@ class PlaylistCapabilities(BaseModel):
|
||||
reorder: bool = False
|
||||
|
||||
|
||||
class PathCapabilities(BaseModel):
|
||||
# Path mapping, path rewriting and the open-time missing-files check apply.
|
||||
# False for a library held by a server: its mapping is the server's own
|
||||
# configuration, and this computer's drives are not where its files are.
|
||||
remappable: bool = True
|
||||
|
||||
|
||||
class SaveCapabilities(BaseModel):
|
||||
"""Structured facts, never finished sentences.
|
||||
|
||||
@@ -129,4 +149,5 @@ class Capabilities(BaseModel):
|
||||
grid: GridCapabilities = GridCapabilities()
|
||||
tracks: TrackCapabilities = TrackCapabilities()
|
||||
playlists: PlaylistCapabilities = PlaylistCapabilities()
|
||||
paths: PathCapabilities = PathCapabilities()
|
||||
save: SaveCapabilities
|
||||
@@ -150,6 +150,11 @@ class FolderSource:
|
||||
def audio_path(self, track_id: str) -> Path | None:
|
||||
return Path(track_id) if track_id in self._by_id else None
|
||||
|
||||
def audio_facts(self, track_ids: list[str]):
|
||||
from .adapter import local_audio_facts
|
||||
|
||||
return local_audio_facts(self, track_ids)
|
||||
|
||||
def playlist_tree(self) -> list[PlaylistNode]:
|
||||
return []
|
||||
|
||||
|
||||
@@ -194,6 +194,9 @@ class LibraryInfo(BaseModel):
|
||||
path: str
|
||||
display_name: str # short label for the status bar
|
||||
version: str | None = None
|
||||
# Set when the library is held by a server: {id, name, via} of the saved
|
||||
# remote it was opened through. None for a library on this computer.
|
||||
remote: dict | None = None
|
||||
|
||||
|
||||
class PlatformOption(BaseModel):
|
||||
@@ -208,7 +211,7 @@ class PlatformOption(BaseModel):
|
||||
platform: str
|
||||
name: str
|
||||
library_label: str
|
||||
selects: Literal["file", "directory"] = "file"
|
||||
selects: Literal["file", "directory", "remote"] = "file"
|
||||
installed: bool = False
|
||||
#: How many libraries this platform has right now; `installed` is `found > 0`.
|
||||
found: int = 0
|
||||
|
||||
@@ -54,6 +54,10 @@ class PathMapping:
|
||||
return True
|
||||
return s.startswith(self.from_prefix + os.sep) or s.startswith(self.from_prefix + "/")
|
||||
|
||||
def inverted(self) -> "PathMapping":
|
||||
"""The mapping back: a path HERE → the form the library stores."""
|
||||
return PathMapping(self.to_prefix, self.from_prefix)
|
||||
|
||||
def apply(self, os_path: Path) -> Path:
|
||||
"""Rebase ``os_path`` from ``from_prefix`` onto ``to_prefix``. Returns the
|
||||
path unchanged when it doesn't match (non-matching tracks untouched)."""
|
||||
@@ -81,3 +85,21 @@ def common_dir_prefix(paths: list[str]) -> str:
|
||||
else:
|
||||
break
|
||||
return "/".join(common)
|
||||
|
||||
|
||||
def stored_form(os_path: Path, mappings) -> Path:
|
||||
"""`os_path` as the library STORES its paths, when it sits under where one
|
||||
of `mappings` points (the first that does).
|
||||
|
||||
A library opened through a mapping (a server holding a collection made on
|
||||
another computer) stores every path in the other computer's form. A file
|
||||
added through that mapping is written in the same form, so the library
|
||||
keeps ONE convention — and still opens, mapping and all, where it was made.
|
||||
"""
|
||||
for mapping in mappings:
|
||||
if mapping is None or mapping.empty:
|
||||
continue
|
||||
back = mapping.inverted()
|
||||
if back.matches(os_path):
|
||||
return back.apply(os_path)
|
||||
return os_path
|
||||
@@ -356,17 +356,14 @@ def stem_layout(path: Path | str) -> list[dict] | None:
|
||||
MP3 entries in the real collection carry that element."""
|
||||
import json
|
||||
|
||||
import av
|
||||
|
||||
path = Path(path)
|
||||
try:
|
||||
raw = read_stem_box(path)
|
||||
if raw is None:
|
||||
return None
|
||||
return None # not a stem file: nothing to count, no decoder needed
|
||||
stems = json.loads(raw).get("stems") or []
|
||||
with av.open(str(path), metadata_errors="ignore") as c:
|
||||
streams = len(c.streams.audio)
|
||||
except (OSError, ValueError, av.FFmpegError):
|
||||
streams = _audio_stream_count(path)
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
if not stems or streams < 1 + len(stems):
|
||||
return None
|
||||
@@ -374,6 +371,39 @@ def stem_layout(path: Path | str) -> list[dict] | None:
|
||||
for i, s in enumerate(stems)]
|
||||
|
||||
|
||||
def _audio_stream_count(path: Path) -> int:
|
||||
"""How many audio streams an MP4 holds. Through PyAV where it is installed;
|
||||
otherwise (the Konduktor SERVER ships without it — it never decodes) by
|
||||
counting the `trak`s whose handler is `soun`, which is what PyAV counts."""
|
||||
try:
|
||||
import av
|
||||
except ImportError:
|
||||
av = None
|
||||
if av is not None:
|
||||
try:
|
||||
with av.open(str(path), metadata_errors="ignore") as c:
|
||||
return len(c.streams.audio)
|
||||
except av.FFmpegError as ex:
|
||||
raise ValueError(str(ex))
|
||||
size = path.stat().st_size
|
||||
count = 0
|
||||
with open(path, "rb") as f:
|
||||
moov = _find(f, 0, size, b"moov")
|
||||
if moov is None:
|
||||
return 0
|
||||
for kind, body, end in mp4_edit._boxes(f, moov[1], moov[2]):
|
||||
if kind != b"trak":
|
||||
continue
|
||||
mdia = _find(f, body, end, b"mdia")
|
||||
hdlr = _find(f, mdia[1], mdia[2], b"hdlr") if mdia else None
|
||||
if hdlr is None:
|
||||
continue
|
||||
f.seek(hdlr[1] + 8) # version/flags (4) + pre_defined (4), then the type
|
||||
if f.read(4) == b"soun":
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
def _traktor_json(v) -> str:
|
||||
if isinstance(v, bool):
|
||||
return "true" if v else "false"
|
||||
|
||||
@@ -341,11 +341,15 @@ def plan(adapter, export_set) -> ExportPlan:
|
||||
resolved = exports.resolve(adapter, export_set)
|
||||
tracks = [t for t in (adapter.track(i) for i in resolved.track_ids) if t is not None]
|
||||
|
||||
# The source is the adapter's `audio_path`, never `Track.filepath`: that is
|
||||
# a DISPLAY path, which on Traktor omits the volume and ignores the active
|
||||
# The source is the adapter's file, never `Track.filepath`: that is a
|
||||
# DISPLAY path, which on Traktor omits the volume and ignores the active
|
||||
# path mapping — so every track off the boot volume (or on a remapped
|
||||
# Windows drive) read as missing and the export was "empty".
|
||||
sources = {t.id: adapter.audio_path(t.id) for t in tracks}
|
||||
# Windows drive) read as missing and the export was "empty". Its FACTS,
|
||||
# not `audio_path`: planning must not read a file, and on a library held
|
||||
# by a server reading one means downloading it. `run` fetches each file
|
||||
# only when it copies it.
|
||||
facts = adapter.audio_facts([t.id for t in tracks])
|
||||
sources = {tid: Path(f.key) for tid, f in facts.items()}
|
||||
|
||||
# Mirror relative to the deepest shared folder, so the export carries the
|
||||
# user's structure without carrying their home directory.
|
||||
@@ -355,16 +359,10 @@ def plan(adapter, export_set) -> ExportPlan:
|
||||
previous = _previous_copies(destination)
|
||||
claimed: set[Path] = set()
|
||||
for track in tracks:
|
||||
source = sources[track.id]
|
||||
exists = False
|
||||
size = mtime_ns = 0
|
||||
try:
|
||||
exists = bool(source and source.is_file())
|
||||
if exists:
|
||||
st = source.stat()
|
||||
size, mtime_ns = st.st_size, st.st_mtime_ns
|
||||
except OSError:
|
||||
exists = False
|
||||
source = sources.get(track.id)
|
||||
fact = facts.get(track.id)
|
||||
exists = fact is not None
|
||||
size, mtime_ns = (fact.size, fact.mtime_ns) if fact else (0, 0)
|
||||
planned = PlannedTrack(
|
||||
track_id=track.id,
|
||||
title=track.title or (source.name if source else track.id),
|
||||
@@ -519,7 +517,10 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict:
|
||||
done += n
|
||||
handle.progress(done=done)
|
||||
|
||||
copy_file(planned.source_path, partial, handle, advance)
|
||||
# The file to READ: on this machine that is the source itself;
|
||||
# on a library held by a server, a downloaded copy of it.
|
||||
local = adapter.audio_path(planned.track_id) or planned.source_path
|
||||
copy_file(local, partial, handle, advance)
|
||||
os.replace(partial, target)
|
||||
payload_tracks.append(
|
||||
ExportTrack(
|
||||
|
||||
@@ -123,8 +123,39 @@ def _store_path(library_id: str) -> Path:
|
||||
return paths.app_data_dir() / "exports" / f"{library_id}.json"
|
||||
|
||||
|
||||
# A library whose sets are kept somewhere other than this computer's app-data —
|
||||
# a library held by a server keeps them beside itself, so every computer that
|
||||
# opens it sees the same sets. Each store reads and writes the WHOLE document
|
||||
# (`{"library_id", "sets"}`); everything else here is unchanged by where it is.
|
||||
_STORES: dict[str, object] = {}
|
||||
|
||||
|
||||
def use_store(library_id: str, store) -> None:
|
||||
"""Keep `library_id`'s sets in `store` (`read() -> dict`, `write(dict)`);
|
||||
None returns them to this computer's app-data."""
|
||||
if store is None:
|
||||
_STORES.pop(library_id, None)
|
||||
else:
|
||||
_STORES[library_id] = store
|
||||
|
||||
|
||||
def _read_doc(library_id: str) -> dict:
|
||||
store = _STORES.get(library_id)
|
||||
if store is not None:
|
||||
return store.read()
|
||||
return paths.read_json(_store_path(library_id), {})
|
||||
|
||||
|
||||
def _write_doc(library_id: str, doc: dict) -> None:
|
||||
store = _STORES.get(library_id)
|
||||
if store is not None:
|
||||
store.write(doc)
|
||||
else:
|
||||
paths.write_json(_store_path(library_id), doc)
|
||||
|
||||
|
||||
def _load(library_id: str) -> dict[str, ExportSet]:
|
||||
data = paths.read_json(_store_path(library_id), {})
|
||||
data = _read_doc(library_id)
|
||||
raw = data.get("sets") if isinstance(data, dict) else None
|
||||
out: dict[str, ExportSet] = {}
|
||||
if isinstance(raw, dict):
|
||||
@@ -158,8 +189,8 @@ def _targets(values: dict) -> list[str]:
|
||||
|
||||
|
||||
def _save(library_id: str, sets: dict[str, ExportSet]) -> None:
|
||||
paths.write_json(
|
||||
_store_path(library_id),
|
||||
_write_doc(
|
||||
library_id,
|
||||
{"library_id": library_id, "sets": {k: v.as_dict() for k, v in sets.items()}},
|
||||
)
|
||||
|
||||
|
||||
@@ -112,18 +112,19 @@ def _key(path: Path) -> str:
|
||||
def _existing_files(dest) -> dict[str, str]:
|
||||
"""Every audio file the destination points at → its track id.
|
||||
|
||||
Resolved through the adapter's own `audio_path`, which is the only answer
|
||||
Resolved through the adapter's own `audio_facts`, which is the only answer
|
||||
that includes the volume and the active path mapping; the projected
|
||||
`filepath` is a display string and is not good enough to match on.
|
||||
`filepath` is a display string and is not good enough to match on. Facts,
|
||||
not `audio_path`: on a library held by a server that would download every
|
||||
file it has.
|
||||
"""
|
||||
out: dict[str, str] = {}
|
||||
for track in dest.tracks:
|
||||
try:
|
||||
path = dest.audio_path(track.id)
|
||||
except Exception: # noqa: BLE001
|
||||
path = None
|
||||
if path is not None:
|
||||
out.setdefault(_key(path), track.id)
|
||||
try:
|
||||
facts = dest.audio_facts([t.id for t in dest.tracks])
|
||||
except Exception: # noqa: BLE001
|
||||
return out
|
||||
for track_id, fact in facts.items():
|
||||
out.setdefault(_key(Path(fact.key)), track_id)
|
||||
return out
|
||||
|
||||
|
||||
@@ -216,7 +217,16 @@ def _all_playlists(source) -> list[tuple[str, str]]:
|
||||
return out
|
||||
|
||||
|
||||
def free_bytes(path: Path) -> int | None:
|
||||
def free_bytes(path: Path, dest=None) -> int | None:
|
||||
"""Free space where the audio will land. On the DESTINATION's machine: a
|
||||
library held by a server reports its own disk (`free_space`), since the
|
||||
path names a folder there, not here."""
|
||||
remote_free = getattr(dest, "free_space", None) if dest is not None and uploads_audio(dest) else None
|
||||
if remote_free is not None:
|
||||
try:
|
||||
return remote_free(str(path))
|
||||
except Exception: # noqa: BLE001 — unknown is not "full"
|
||||
return None
|
||||
try:
|
||||
target = path if path.exists() else path.parent
|
||||
return shutil.disk_usage(target).free
|
||||
@@ -224,6 +234,15 @@ def free_bytes(path: Path) -> int | None:
|
||||
return None
|
||||
|
||||
|
||||
def uploads_audio(dest) -> bool:
|
||||
"""Whether added audio is SENT to the machine holding the library (a
|
||||
server) rather than copied on this one — `tracks.audio_destination`."""
|
||||
try:
|
||||
return dest.capabilities().tracks.audio_destination == "library" and hasattr(dest, "upload_audio")
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
|
||||
|
||||
def _unique_target(folder: Path, name: str, taken: set[str]) -> Path:
|
||||
"""A free filename in `folder`, suffixing on collision.
|
||||
|
||||
@@ -298,7 +317,13 @@ def run(
|
||||
"""
|
||||
destination = plan.destination
|
||||
places = places_audio(dest)
|
||||
if not reference and not places:
|
||||
# A library held by a server: each file is UPLOADED into `destination`,
|
||||
# a folder on the server, instead of copied here. Nothing can be left in
|
||||
# place — the server cannot see this computer's files.
|
||||
uploads = not places and uploads_audio(dest)
|
||||
if uploads and reference:
|
||||
raise ValueError("A remote library cannot reference files on this computer")
|
||||
if not reference and not places and not uploads:
|
||||
assert destination is not None
|
||||
destination.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -312,6 +337,8 @@ def run(
|
||||
# from it leaves the half-written file behind — which then makes the next
|
||||
# attempt suffix around a file that is not really there.
|
||||
created: list[Path] = []
|
||||
# Files sent to the server, which a failure asks it to delete again.
|
||||
uploaded: list[Path] = []
|
||||
taken: set[str] = set()
|
||||
moved = 0
|
||||
|
||||
@@ -333,6 +360,19 @@ def run(
|
||||
elif reference:
|
||||
copied.append((planned, planned.source_path))
|
||||
continue
|
||||
elif uploads:
|
||||
handle.progress(message=f"Uploading {planned.title}")
|
||||
|
||||
def sent(n: int) -> None:
|
||||
handle.raise_if_cancelled() # mid-file: the server drops the partial
|
||||
bump(n)
|
||||
|
||||
# The server never overwrites: a taken name comes back `-2`…
|
||||
target = dest.upload_audio(planned.source_path, str(destination),
|
||||
planned.source_path.name, progress=sent)
|
||||
uploaded.append(target)
|
||||
copied.append((planned, target))
|
||||
continue
|
||||
else:
|
||||
target = _unique_target(destination, planned.source_path.name, taken)
|
||||
handle.progress(message=f"Copying {planned.title}")
|
||||
@@ -409,6 +449,11 @@ def run(
|
||||
target.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
log.debug("could not clean up %s", target, exc_info=True)
|
||||
for target in uploaded:
|
||||
try:
|
||||
dest.delete_upload(target) # refused once the library names it
|
||||
except Exception: # noqa: BLE001
|
||||
log.debug("could not clean up upload %s", target, exc_info=True)
|
||||
raise
|
||||
|
||||
|
||||
|
||||
+239
-21
@@ -15,7 +15,7 @@ from fastapi import FastAPI, File, Form, HTTPException, Query, Response, UploadF
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
|
||||
from . import __version__, exporter, exports, history, prefs
|
||||
from . import __version__, exporter, exports, prefs
|
||||
from .app_state import STATE
|
||||
from .core import auto_hotcues as ah
|
||||
from .core import grid_detect, key_detect, structure
|
||||
@@ -30,6 +30,7 @@ from .core.adapter import (
|
||||
LibraryAdapter,
|
||||
LibraryNotSupported,
|
||||
NotFound,
|
||||
Unavailable,
|
||||
Unsupported,
|
||||
)
|
||||
from .core.capabilities import Capabilities
|
||||
@@ -81,7 +82,9 @@ from .schemas import (
|
||||
ImportRequest,
|
||||
JobStatus,
|
||||
OpenCollection,
|
||||
OpenRemote,
|
||||
OpenSource,
|
||||
RemoteIn,
|
||||
PathMappingInfo,
|
||||
PlaylistNode,
|
||||
PrefixSuggestions,
|
||||
@@ -141,7 +144,7 @@ def _adapter_error(_request, exc: AdapterError):
|
||||
InvalidCommand: 400,
|
||||
Unsupported: 422,
|
||||
LibraryNotSupported: 400,
|
||||
}.get(type(exc), 400)
|
||||
}.get(type(exc), 503 if isinstance(exc, Unavailable) else 400)
|
||||
return JSONResponse(status_code=status, content={"detail": str(exc)})
|
||||
|
||||
|
||||
@@ -207,6 +210,171 @@ def collection_options(platform: str | None = None) -> CollectionOptions:
|
||||
)
|
||||
|
||||
|
||||
# ---- remote libraries ----------------------------------------------------------
|
||||
# A library held by a Konduktor server (a container on the user's NAS), opened
|
||||
# from the picker's "Remote" step. The saved remotes are this computer's; the
|
||||
# password is in the OS keychain (`adapters/remote/config.py`).
|
||||
|
||||
|
||||
def _remote_out(remote) -> dict:
|
||||
out = remote.public()
|
||||
out["has_password"] = bool(remote_cfg().password(remote.id))
|
||||
return out
|
||||
|
||||
|
||||
def remote_cfg():
|
||||
from .adapters.remote import config
|
||||
|
||||
return config
|
||||
|
||||
|
||||
def _checked_remote(body: RemoteIn, remote_id: str | None):
|
||||
"""Build the remote from the form and handshake every address. Refuses —
|
||||
nothing saved — when an address answers but refuses (wrong password, a
|
||||
version that cannot talk), or when none answers at all; an unreachable
|
||||
FALLBACK alone is fine (a VPN address is often unreachable at home)."""
|
||||
from .adapters import remote as remote_lib
|
||||
|
||||
config = remote_cfg()
|
||||
host, port = config.split_host(body.host)
|
||||
fallback, fallback_port = config.split_host(body.fallback_host or "")
|
||||
previous = config.get(remote_id) if remote_id else None
|
||||
password = body.password if body.password else (config.password(remote_id) if remote_id else None)
|
||||
if not body.name.strip() or not host or not body.username.strip():
|
||||
raise HTTPException(400, "A name, an address and a username are all needed")
|
||||
if not password:
|
||||
raise HTTPException(400, "Enter the server's password")
|
||||
remote = config.Remote(
|
||||
id=previous.id if previous else config.new_id(), name=body.name.strip(), host=host,
|
||||
port=body.port or port, fallback_host=fallback or None,
|
||||
fallback_port=(body.fallback_port or fallback_port) if fallback else None,
|
||||
username=body.username.strip(),
|
||||
)
|
||||
results = remote_lib.handshake(remote, password)
|
||||
refused = [r for r in results if r["kind"] in ("auth", "version", "other")]
|
||||
if refused:
|
||||
raise HTTPException(400, {"message": refused[0]["error"], "results": results})
|
||||
if not any(r["ok"] for r in results):
|
||||
raise HTTPException(400, {"message": results[0]["error"], "results": results})
|
||||
return remote, password, results
|
||||
|
||||
|
||||
@app.get("/api/remotes")
|
||||
def list_remotes() -> list[dict]:
|
||||
return [_remote_out(r) for r in remote_cfg().remotes()]
|
||||
|
||||
|
||||
@app.post("/api/remotes")
|
||||
def add_remote(body: RemoteIn) -> dict:
|
||||
remote, password, results = _checked_remote(body, None)
|
||||
config = remote_cfg()
|
||||
config.set_password(remote.id, password)
|
||||
config.save(remote)
|
||||
return {"remote": _remote_out(remote), "results": results}
|
||||
|
||||
|
||||
@app.patch("/api/remotes/{remote_id}")
|
||||
def edit_remote(remote_id: str, body: RemoteIn) -> dict:
|
||||
config = remote_cfg()
|
||||
if config.get(remote_id) is None:
|
||||
raise HTTPException(404, "No such remote")
|
||||
remote, password, results = _checked_remote(body, remote_id)
|
||||
config.set_password(remote.id, password)
|
||||
config.save(remote)
|
||||
return {"remote": _remote_out(remote), "results": results}
|
||||
|
||||
|
||||
@app.delete("/api/remotes/{remote_id}")
|
||||
def delete_remote(remote_id: str) -> dict:
|
||||
if STATE.remote_config is not None and STATE.remote_config.id == remote_id:
|
||||
raise HTTPException(409, "That remote is open — open another library first")
|
||||
if not remote_cfg().delete(remote_id):
|
||||
raise HTTPException(404, "No such remote")
|
||||
return {"status": "deleted"}
|
||||
|
||||
|
||||
def _running_batch() -> str | None:
|
||||
"""The kind of batch running here, for the heartbeat: another computer
|
||||
asking to take over is told what it would cancel."""
|
||||
for kind in BATCH_JOBS + ("import", "export"):
|
||||
if JOBS.active(kind):
|
||||
return kind
|
||||
return None
|
||||
|
||||
|
||||
def _on_remote_change(state: str) -> None:
|
||||
# Taken over: whatever batch is running here is now writing into a library
|
||||
# this computer no longer holds — cancel it, as Cancel does (finished
|
||||
# tracks stay as the edits the new holder inherits).
|
||||
if state == "taken_over":
|
||||
import threading
|
||||
|
||||
threading.Thread(target=_stop_batches, name="konduktor-takeover-stop", daemon=True).start()
|
||||
|
||||
|
||||
@app.post("/api/library/open-remote", response_model=CollectionStatus)
|
||||
def open_remote(body: OpenRemote) -> CollectionStatus:
|
||||
"""Connect to a saved remote and make its library THE library.
|
||||
|
||||
409 `{code: "in_use", machine, since, batch}` when another computer holds
|
||||
it — the picker asks, and retries with `takeover`. On success, the edits
|
||||
another computer left unsaved are reported (`pending_edits`) for the user
|
||||
to save or discard.
|
||||
"""
|
||||
from .adapters import remote as remote_lib
|
||||
|
||||
remote = remote_cfg().get(body.remote_id)
|
||||
if remote is None:
|
||||
raise HTTPException(404, "No such remote")
|
||||
_stop_batches()
|
||||
try:
|
||||
opened = remote_lib.open_remote(remote, takeover=body.takeover, batch_probe=_running_batch)
|
||||
except remote_lib.InUse as ex:
|
||||
raise HTTPException(409, {"code": "in_use", **ex.holder})
|
||||
except AdapterError as ex:
|
||||
raise HTTPException(400, str(ex))
|
||||
STATE.open_remote(opened)
|
||||
opened.session.on_change(_on_remote_change)
|
||||
status = collection_status()
|
||||
status.pending_edits = opened.pending_edits
|
||||
return status
|
||||
|
||||
|
||||
def _require_remote():
|
||||
adapter = require_adapter()
|
||||
if STATE.remote is None:
|
||||
raise HTTPException(409, "The open library is not a remote one")
|
||||
return adapter
|
||||
|
||||
|
||||
@app.get("/api/library/fs/list", response_model=FsListing)
|
||||
def library_fs_list(path: str | None = None) -> FsListing:
|
||||
"""Folders on the machine that HOLDS the library — where an import into a
|
||||
remote library lands (`tracks.audio_destination == "library"`). Confined by
|
||||
the server to its content folder; `home` is that folder."""
|
||||
adapter = _require_remote()
|
||||
listing = adapter.client.fs_list(path)
|
||||
return FsListing(
|
||||
path=listing["path"], parent=listing["parent"], home=listing["root"],
|
||||
dirs=[FsEntry(name=e["name"], path=e["path"]) for e in listing["entries"] if e["is_dir"]],
|
||||
files=[],
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/remote-cache")
|
||||
def remote_cache_status() -> dict:
|
||||
from .adapters.remote import cache
|
||||
|
||||
return cache.shared().usage()
|
||||
|
||||
|
||||
@app.delete("/api/remote-cache")
|
||||
def clear_remote_cache() -> dict:
|
||||
from .adapters.remote import cache
|
||||
|
||||
return {"freed": cache.shared().clear()}
|
||||
|
||||
|
||||
@app.get("/api/library/path-mapping", response_model=PathMappingInfo)
|
||||
def get_path_mapping() -> PathMappingInfo:
|
||||
"""The current collection's saved OS-path remapping (blank if none)."""
|
||||
@@ -687,9 +855,15 @@ def _library_info() -> LibraryInfo:
|
||||
driver = next((d for d in registry.drivers() if d.platform == caps.platform), None)
|
||||
namer = getattr(driver, "display_name_for", None)
|
||||
try:
|
||||
display_name = namer(path) if namer else path.name
|
||||
display_name = namer(path) if namer and STATE.remote_config is None else path.name
|
||||
except OSError:
|
||||
display_name = path.name
|
||||
remote = None
|
||||
if STATE.remote_config is not None:
|
||||
# A remote is called what the user called it, not its file's name.
|
||||
display_name = STATE.remote_config.name
|
||||
remote = {"id": STATE.remote_config.id, "name": STATE.remote_config.name,
|
||||
"via": STATE.remote.client.via if STATE.remote else None}
|
||||
return LibraryInfo(
|
||||
platform=caps.platform,
|
||||
name=caps.save.app_name,
|
||||
@@ -697,6 +871,7 @@ def _library_info() -> LibraryInfo:
|
||||
path=str(STATE.path),
|
||||
display_name=display_name,
|
||||
version=caps.version,
|
||||
remote=remote,
|
||||
)
|
||||
|
||||
|
||||
@@ -727,6 +902,14 @@ def platforms() -> list[PlatformOption]:
|
||||
# that keep a library in a known place come before the ones that are a
|
||||
# plugged-in drive, which is the real distinction a chooser is making.
|
||||
out.sort(key=lambda o: (o.removable, o.name.lower()))
|
||||
# A library held by a Konduktor server — not a platform of its own (the
|
||||
# server says which it holds), but a way to reach one, so it is offered
|
||||
# last, after every platform on this computer.
|
||||
from .adapters.remote import config as remote_config
|
||||
|
||||
saved = len(remote_config.remotes())
|
||||
out.append(PlatformOption(platform="remote", name="Remote", library_label="remote library",
|
||||
selects="remote", installed=saved > 0, found=saved))
|
||||
return out
|
||||
|
||||
|
||||
@@ -743,7 +926,8 @@ def state() -> EditState:
|
||||
return EditState(dirty=require_adapter().dirty, library=_library_info(),
|
||||
pending_stems=pending if pending and pending["tracks"] else None,
|
||||
stem_job=stem_job[0].id if stem_job else None,
|
||||
stem_recovery=STATE.recovery)
|
||||
stem_recovery=STATE.recovery,
|
||||
remote=STATE.remote.describe() if STATE.remote is not None else None)
|
||||
|
||||
|
||||
# ---- stem engine (download / side-load / remove) --------------------------
|
||||
@@ -822,26 +1006,46 @@ def _require_no_pending_stems(what: str) -> None:
|
||||
def _stem_options(body):
|
||||
from .stems import convert
|
||||
|
||||
# A remote library's destination is a folder ON THE SERVER: not expanded
|
||||
# here, where `~` is this computer's home.
|
||||
remote = STATE.remote is not None
|
||||
destination = None
|
||||
if body.destination:
|
||||
destination = Path(body.destination) if remote else Path(body.destination).expanduser()
|
||||
return convert.Options(
|
||||
mode=body.mode, destination=Path(body.destination).expanduser() if body.destination else None,
|
||||
mode=body.mode, destination=destination,
|
||||
collection=body.collection, playlist_id=body.playlist_id, new_playlist=body.new_playlist,
|
||||
device=prefs.load_prefs().get("stemDevice", "auto"),
|
||||
)
|
||||
|
||||
|
||||
def _stem_plan(body):
|
||||
from .stems import convert
|
||||
from .stems import convert, remote_convert
|
||||
|
||||
adapter = require_adapter()
|
||||
caps = adapter.capabilities()
|
||||
if not (caps.writable and caps.tracks.stem_convertible):
|
||||
raise HTTPException(422, "This library cannot hold stem files")
|
||||
try:
|
||||
if _remote_stems(adapter):
|
||||
return adapter, remote_convert.plan(adapter, body.track_ids, _stem_options(body))
|
||||
return adapter, convert.plan(adapter, body.track_ids, _stem_options(body), STATE.pending)
|
||||
except convert.ConvertError as ex:
|
||||
raise HTTPException(400, str(ex))
|
||||
|
||||
|
||||
def _remote_stems(adapter) -> bool:
|
||||
"""A library held by a server: it plans and swaps, this computer separates
|
||||
(`stems/remote_convert.py`)."""
|
||||
return hasattr(adapter, "publish_stems")
|
||||
|
||||
|
||||
def _needs_engine(planned) -> bool:
|
||||
if hasattr(planned, "server"):
|
||||
return any(i.get("reuse") is None for i in planned.items)
|
||||
return any(p.reuse is None for p in planned.items)
|
||||
|
||||
|
||||
@app.post("/api/tracks/stems/preview")
|
||||
def preview_stem_conversion(body: StemConvert) -> dict:
|
||||
"""What a conversion would do — converted, skipped (and why), disk space."""
|
||||
@@ -863,11 +1067,16 @@ def convert_to_stems(body: StemConvert) -> JobStatus:
|
||||
raise HTTPException(409, planned.blocked)
|
||||
if not planned.items:
|
||||
raise HTTPException(400, "None of these tracks can be converted")
|
||||
if any(p.reuse is None for p in planned.items) and not em.default_manager().ready():
|
||||
if _needs_engine(planned) and not em.default_manager().ready():
|
||||
raise HTTPException(409, "The stem engine is not installed")
|
||||
opts = _stem_options(body)
|
||||
|
||||
def run(handle):
|
||||
if _remote_stems(adapter):
|
||||
from .stems import remote_convert
|
||||
|
||||
return remote_convert.run(handle, adapter, planned, opts,
|
||||
still_current=lambda: STATE.adapter is adapter)
|
||||
return convert.run(handle, adapter, planned, opts, STATE.pending, mutation=STATE.mutation,
|
||||
still_current=lambda: STATE.adapter is adapter)
|
||||
|
||||
@@ -930,10 +1139,25 @@ def reload_collection() -> dict:
|
||||
_require_no_pending_stems("Reloading")
|
||||
if not STATE.loaded:
|
||||
raise HTTPException(409, "No collection loaded")
|
||||
STATE.open(STATE.path) # re-parse current file from disk
|
||||
if STATE.remote is not None:
|
||||
STATE.adapter.refresh() # a remote library is re-read from its server
|
||||
else:
|
||||
STATE.open(STATE.path) # re-parse current file from disk
|
||||
return {"status": "reloaded", "tracks": len(require_adapter().tracks)}
|
||||
|
||||
|
||||
@app.on_event("shutdown")
|
||||
def _release_remote_session() -> None:
|
||||
"""A graceful stop hands a remote library's session back (see sidecar.py
|
||||
for the abrupt one)."""
|
||||
if STATE.remote is not None:
|
||||
try:
|
||||
STATE.remote.stop()
|
||||
STATE.remote.client.release(timeout=2.0)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
|
||||
# ---- read: stats / facets / tracks ------------------------------------
|
||||
|
||||
|
||||
@@ -1735,7 +1959,7 @@ def save() -> SaveResult:
|
||||
def get_history() -> list[HistoryEntry]:
|
||||
"""All saved versions of the current collection, newest first."""
|
||||
require_adapter()
|
||||
return [HistoryEntry(**e.__dict__) for e in history.list_history(STATE.path)]
|
||||
return [HistoryEntry(**e.__dict__) for e in STATE.services.history()]
|
||||
|
||||
|
||||
@app.post("/api/history/{commit_id}/restore", response_model=CollectionStatus)
|
||||
@@ -1745,14 +1969,8 @@ def restore_version(commit_id: str) -> CollectionStatus:
|
||||
reloads. The user should close Traktor first (it overwrites on exit)."""
|
||||
_require_no_pending_stems("Restoring a version")
|
||||
require_adapter()
|
||||
data = history.read_version(STATE.path, commit_id)
|
||||
if data is None:
|
||||
if not STATE.restore_version(commit_id):
|
||||
raise HTTPException(404, f"Version not found: {commit_id}")
|
||||
path = STATE.path
|
||||
# The adapter's driver owns writing its own format back, even for a restore.
|
||||
registry.driver_for(path).restore(path, data)
|
||||
history.commit(path, data, f"Restored version {commit_id[:8]}", __version__)
|
||||
STATE.open(path) # rebuild read + edit models from the restored file
|
||||
return collection_status()
|
||||
|
||||
|
||||
@@ -1760,7 +1978,7 @@ def restore_version(commit_id: str) -> CollectionStatus:
|
||||
def clear_history() -> dict:
|
||||
"""Permanently delete ALL version history for the current collection."""
|
||||
require_adapter()
|
||||
history.clear_history(STATE.path)
|
||||
STATE.services.clear_history()
|
||||
return {"status": "cleared"}
|
||||
|
||||
|
||||
@@ -2088,7 +2306,7 @@ def _folder_add_plan(body: FolderAddRequest):
|
||||
@app.post("/api/folder/add/preview")
|
||||
def folder_add_preview(body: FolderAddRequest) -> dict:
|
||||
_source, dest, destination, plan = _folder_add_plan(body)
|
||||
out = plan.as_dict(free_bytes=importer.free_bytes(destination) if destination else None)
|
||||
out = plan.as_dict(free_bytes=importer.free_bytes(destination, dest) if destination else None)
|
||||
if importer.places_audio(dest):
|
||||
_placed_space(out, dest, plan, destination)
|
||||
elif body.mode == "reference":
|
||||
@@ -2107,7 +2325,7 @@ def folder_add(body: FolderAddRequest) -> JobStatus:
|
||||
if not plan.importable and not plan.existing:
|
||||
raise HTTPException(400, "Nothing to add (none of those files exist)")
|
||||
if body.mode == "copy" or importer.places_audio(dest):
|
||||
free = importer.free_bytes(destination)
|
||||
free = importer.free_bytes(destination, dest)
|
||||
needed = importer.placed_bytes(dest, plan) if importer.places_audio(dest) else plan.total_bytes
|
||||
if free is not None and free < needed + importer.SPACE_HEADROOM:
|
||||
raise HTTPException(
|
||||
@@ -2176,7 +2394,7 @@ def import_preview(body: ImportRequest) -> dict:
|
||||
between the preview and the import, and a stale preview is worse than none.
|
||||
"""
|
||||
_source, dest, destination, plan = _import_plan(body)
|
||||
out = plan.as_dict(free_bytes=importer.free_bytes(destination))
|
||||
out = plan.as_dict(free_bytes=importer.free_bytes(destination, dest))
|
||||
if importer.places_audio(dest):
|
||||
_placed_space(out, dest, plan, destination)
|
||||
return out
|
||||
@@ -2189,7 +2407,7 @@ def start_import(body: ImportRequest) -> JobStatus:
|
||||
source, dest, destination, plan = _import_plan(body)
|
||||
if not plan.importable:
|
||||
raise HTTPException(400, "Nothing to import (no tracks, or none of their files exist)")
|
||||
free = importer.free_bytes(destination)
|
||||
free = importer.free_bytes(destination, dest)
|
||||
needed = importer.placed_bytes(dest, plan) if importer.places_audio(dest) else plan.total_bytes
|
||||
if free is not None and free < needed + importer.SPACE_HEADROOM:
|
||||
raise HTTPException(
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
"""The wire contract between a Konduktor SERVER and the app that opens it.
|
||||
|
||||
A library held by a server (`konduktor.server`, a container on the user's NAS)
|
||||
is opened on a laptop through `adapters/remote`'s `RemoteAdapter`, which speaks
|
||||
THIS protocol to the server. Both sides import this module, so the method list,
|
||||
which commands need the session, and the version they speak cannot drift apart.
|
||||
|
||||
The protocol is the `LibraryAdapter` protocol itself, not the UI's `/api`
|
||||
routes: commands in, projections out. Every member of `LibraryAdapter` is
|
||||
either in `RPC` or in `EXCLUDED` with the reason it does not travel —
|
||||
`test_remote_protocol.py` fails the moment a new protocol member is neither, so
|
||||
a command added later cannot silently be missing from remote libraries.
|
||||
|
||||
Arguments and results are (de)serialised with pydantic `TypeAdapter`s built
|
||||
from the protocol's own type hints; the model classes are pydantic already and
|
||||
the dataclasses convert. Bytes never travel as JSON — art, audio and uploads
|
||||
have routes of their own.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import inspect
|
||||
import io
|
||||
import typing
|
||||
from dataclasses import dataclass
|
||||
from functools import lru_cache
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel, TypeAdapter
|
||||
|
||||
from .core.adapter import LibraryAdapter
|
||||
from .core.model import AutoHotcue, Track, TrackCues
|
||||
|
||||
#: (major, minor). A client speaks to a server of the SAME major whose minor is
|
||||
#: at least its own: minors only add. Bump the minor for an added route or
|
||||
#: method, the major for anything an older client would misread.
|
||||
API_VERSION: tuple[int, int] = (1, 0)
|
||||
|
||||
#: How long a session survives without a heartbeat, and how often the holder
|
||||
#: sends one. Long enough to ride out a Wi-Fi blip or a switch to the fallback
|
||||
#: address; short enough that moving to another computer after closing a lid
|
||||
#: rarely needs a takeover (decided 2026-10-02).
|
||||
LEASE_SECONDS = 120.0
|
||||
HEARTBEAT_SECONDS = 15.0
|
||||
|
||||
#: The header that carries the session token on every command.
|
||||
SESSION_HEADER = "X-Konduktor-Session"
|
||||
|
||||
|
||||
def compatible(client: tuple[int, int], server: tuple[int, int]) -> str | None:
|
||||
"""None when `client` can talk to `server`; otherwise which side to update."""
|
||||
if client[0] != server[0]:
|
||||
return "app" if server[0] > client[0] else "server"
|
||||
if server[1] < client[1]:
|
||||
return "server"
|
||||
return None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Method:
|
||||
name: str
|
||||
#: Changes the library — needs the session token, bumps the revision.
|
||||
mutating: bool
|
||||
#: A property on the protocol rather than a method (`tracks`, `dirty`).
|
||||
prop: bool = False
|
||||
#: Parameter types where the protocol's hint is too loose to validate.
|
||||
overrides: tuple[tuple[str, Any], ...] = ()
|
||||
|
||||
|
||||
_READ = (
|
||||
"capabilities", "track", "query_tracks", "facets", "stats", "playlist_tree",
|
||||
"playlist_count", "playlist_entries", "playlist_tracks", "track_cues", "audio_facts",
|
||||
)
|
||||
_MUTATING = (
|
||||
"create_playlist", "create_folder", "rename_playlist", "delete_playlist",
|
||||
"set_playlist_entries", "remove_tracks", "set_track_metadata", "set_key", "set_cue",
|
||||
"set_cue_type", "set_cue_color", "delete_cue", "place_cues", "add_grid_marker",
|
||||
"move_grid_marker", "set_grid_marker_bpm", "delete_grid_marker", "replace_grid",
|
||||
"set_analysed_grid", "delete_grid", "set_grid_lock", "add_tracks",
|
||||
)
|
||||
|
||||
RPC: dict[str, Method] = {
|
||||
**{n: Method(n, False) for n in _READ},
|
||||
"tracks": Method("tracks", False, prop=True),
|
||||
"dirty": Method("dirty", False, prop=True),
|
||||
**{n: Method(n, True) for n in _MUTATING},
|
||||
}
|
||||
RPC["place_cues"] = Method("place_cues", True, overrides=(("cues", list[AutoHotcue]),))
|
||||
|
||||
#: Protocol members that do not travel as RPC, and why.
|
||||
EXCLUDED: dict[str, str] = {
|
||||
"reload": "POST /v1/discard — a discard on the server is what drops its edits",
|
||||
"save": "POST /v1/save — the server saves, versions and backs up beside the library",
|
||||
"snapshot": "version history lives on the server",
|
||||
"audio_path": "GET /v1/audio — a server path names no file on this computer",
|
||||
"cover_art": "GET /v1/art — bytes",
|
||||
"set_cover_art": "PUT /v1/art — bytes",
|
||||
"apply_stem_swaps": "the server applies stem swaps itself (POST /v1/stems/publish)",
|
||||
"set_path_mapping": "the server's path mapping is its own configuration",
|
||||
"set_session_mappings": "the missing-files check searches THIS computer's drives",
|
||||
"unresolved_path_groups": "the missing-files check searches THIS computer's drives",
|
||||
"path_prefix_suggestions": "paths.remappable is false for a remote library",
|
||||
"remap_preview": "paths.remappable is false for a remote library",
|
||||
"remap_locations": "paths.remappable is false for a remote library",
|
||||
}
|
||||
|
||||
|
||||
def protocol_members() -> set[str]:
|
||||
"""Every method and property `LibraryAdapter` declares (not its attributes)."""
|
||||
out = set()
|
||||
for name, value in vars(LibraryAdapter).items():
|
||||
if name.startswith("_"):
|
||||
continue
|
||||
if inspect.isfunction(value) or isinstance(value, property):
|
||||
out.add(name)
|
||||
return out
|
||||
|
||||
|
||||
def _callable(name: str):
|
||||
member = getattr(LibraryAdapter, name)
|
||||
return member.fget if isinstance(member, property) else member
|
||||
|
||||
|
||||
@lru_cache(maxsize=None)
|
||||
def _hints(name: str) -> dict[str, Any]:
|
||||
hints = typing.get_type_hints(_callable(name))
|
||||
method = RPC[name]
|
||||
hints.update(dict(method.overrides))
|
||||
return hints
|
||||
|
||||
|
||||
@lru_cache(maxsize=None)
|
||||
def _params(name: str) -> tuple[tuple[str, Any, Any], ...]:
|
||||
"""(name, type, default) for each parameter the RPC takes."""
|
||||
if name == "query_tracks":
|
||||
# `**kw` on the protocol: the index's own signature is the real one.
|
||||
from .core.query import TrackIndex
|
||||
|
||||
sig = inspect.signature(TrackIndex.query_tracks)
|
||||
hints = typing.get_type_hints(TrackIndex.query_tracks)
|
||||
else:
|
||||
sig = inspect.signature(_callable(name))
|
||||
hints = _hints(name)
|
||||
out = []
|
||||
for p in sig.parameters.values():
|
||||
if p.name == "self" or p.kind in (p.VAR_KEYWORD, p.VAR_POSITIONAL):
|
||||
continue
|
||||
if name == "add_tracks" and p.name == "checkpoint":
|
||||
continue # a callable; the server reports progress instead
|
||||
hint = hints.get(p.name, Any)
|
||||
if name == "add_tracks" and p.name == "items":
|
||||
hint = list[WireNewTrack]
|
||||
out.append((p.name, hint, p.default))
|
||||
return tuple(out)
|
||||
|
||||
|
||||
@lru_cache(maxsize=None)
|
||||
def _adapter(hint) -> TypeAdapter:
|
||||
return TypeAdapter(hint)
|
||||
|
||||
|
||||
def dump_args(name: str, args: dict) -> dict:
|
||||
"""Arguments → JSON-able, by the protocol's own types."""
|
||||
out = {}
|
||||
for pname, hint, _default in _params(name):
|
||||
if pname in args:
|
||||
out[pname] = _adapter(hint).dump_python(args[pname], mode="json")
|
||||
return out
|
||||
|
||||
|
||||
def load_args(name: str, raw: dict) -> dict:
|
||||
"""JSON → validated arguments. Unknown names are refused rather than
|
||||
ignored: a misspelt argument silently taking its default is a wrong edit."""
|
||||
params = {p: (h, d) for p, h, d in _params(name)}
|
||||
unknown = set(raw) - set(params)
|
||||
if unknown:
|
||||
raise ValueError(f"{name}: unknown argument(s) {sorted(unknown)}")
|
||||
out = {}
|
||||
for pname, (hint, default) in params.items():
|
||||
if pname in raw:
|
||||
out[pname] = _adapter(hint).validate_python(raw[pname])
|
||||
elif default is inspect.Parameter.empty:
|
||||
raise ValueError(f"{name}: missing argument {pname!r}")
|
||||
return out
|
||||
|
||||
|
||||
def _result_hint(name: str):
|
||||
if name == "add_tracks":
|
||||
return list[str]
|
||||
return _hints(name).get("return", Any)
|
||||
|
||||
|
||||
def dump_result(name: str, value) -> Any:
|
||||
return _adapter(_result_hint(name)).dump_python(value, mode="json")
|
||||
|
||||
|
||||
def load_result(name: str, raw) -> Any:
|
||||
return _adapter(_result_hint(name)).validate_python(raw)
|
||||
|
||||
|
||||
# ---- adding tracks -------------------------------------------------------------
|
||||
|
||||
|
||||
class WireArt(BaseModel):
|
||||
data: str # base64
|
||||
mime: str
|
||||
|
||||
|
||||
class WireNewTrack(BaseModel):
|
||||
"""`NewTrack` as it crosses the wire. `audio_path` is a path ON THE SERVER —
|
||||
the client uploaded the file first (`POST /v1/upload`), exactly as a local
|
||||
import copies it first. The analysis is the client's (the server never
|
||||
decodes audio)."""
|
||||
|
||||
track: Track
|
||||
audio_path: str
|
||||
cues: TrackCues | None = None
|
||||
art: WireArt | None = None
|
||||
analysis: str | None = None # base64 `.npz`, see `pack_analysis`
|
||||
|
||||
|
||||
def pack_analysis(prepared) -> str | None:
|
||||
"""A `PreparedAnalysis` → base64 `.npz` (float32: what the writers use)."""
|
||||
if prepared is None or prepared.measured is None:
|
||||
return None
|
||||
import numpy as np
|
||||
|
||||
m = prepared.measured
|
||||
buf = io.BytesIO()
|
||||
markers = np.array([[g.start, g.bpm] for g in prepared.markers], dtype=np.float64).reshape(-1, 2)
|
||||
np.savez(
|
||||
buf,
|
||||
rms=np.asarray(m.columns.rms, dtype=np.float32),
|
||||
brightness=np.asarray(m.columns.brightness, dtype=np.float32),
|
||||
columns_duration=np.float64(m.columns.duration),
|
||||
bands=np.asarray(m.frames.bands, dtype=np.float32),
|
||||
frames_duration=np.float64(m.frames.duration),
|
||||
markers=markers,
|
||||
**({} if prepared.key is None else {
|
||||
"key": np.array([prepared.key.pitch_class, prepared.key.wheel,
|
||||
prepared.key.mode == "minor", prepared.key.confidence], dtype=np.float64)}),
|
||||
)
|
||||
return base64.b64encode(buf.getvalue()).decode("ascii")
|
||||
|
||||
|
||||
def unpack_analysis(text: str | None):
|
||||
"""The inverse of `pack_analysis` → `PreparedAnalysis` (or None)."""
|
||||
if not text:
|
||||
return None
|
||||
import numpy as np
|
||||
|
||||
from .core import waveform
|
||||
from .core.adapter import PreparedAnalysis
|
||||
from .core.model import GridMarker
|
||||
|
||||
with np.load(io.BytesIO(base64.b64decode(text))) as z:
|
||||
measured = waveform.Analysis(
|
||||
columns=waveform.Columns(rms=z["rms"], brightness=z["brightness"],
|
||||
duration=float(z["columns_duration"])),
|
||||
frames=waveform.Frames(bands=z["bands"], duration=float(z["frames_duration"])),
|
||||
)
|
||||
markers = [GridMarker(start=float(s), bpm=float(b)) for s, b in z["markers"]]
|
||||
key = None
|
||||
if "key" in z:
|
||||
from .core.key_detect import KeyResult
|
||||
|
||||
pitch, wheel, minor, confidence = z["key"]
|
||||
key = KeyResult(pitch_class=int(pitch), mode="minor" if minor else "major",
|
||||
wheel=int(wheel), confidence=float(confidence))
|
||||
return PreparedAnalysis(measured=measured, markers=markers, key=key)
|
||||
@@ -221,6 +221,8 @@ class EditState(BaseModel):
|
||||
stem_job: str | None = None
|
||||
# What this open's crash recovery did about an interrupted conversion.
|
||||
stem_recovery: dict | None = None
|
||||
# A remote library's connection: {state, via, machine}. None when local.
|
||||
remote: dict | None = None
|
||||
|
||||
|
||||
# ---- collection selection ----
|
||||
@@ -234,12 +236,34 @@ class CollectionStatus(BaseModel):
|
||||
# Identity of the loaded library, so the UI can name it without parsing the
|
||||
# path (a Serato library is a directory, not a file).
|
||||
library: LibraryInfo | None = None
|
||||
# Opening a remote library: the unsaved edits another computer left there,
|
||||
# {machine, summary} — the user chooses to save or discard them.
|
||||
pending_edits: dict | None = None
|
||||
|
||||
|
||||
class OpenCollection(BaseModel):
|
||||
path: str
|
||||
|
||||
|
||||
class RemoteIn(BaseModel):
|
||||
"""A remote's settings as the picker's form sends them. `password` may be
|
||||
omitted on an edit, which keeps the saved one."""
|
||||
|
||||
name: str
|
||||
host: str
|
||||
port: int | None = None
|
||||
fallback_host: str | None = None
|
||||
fallback_port: int | None = None
|
||||
username: str
|
||||
password: str | None = None
|
||||
|
||||
|
||||
class OpenRemote(BaseModel):
|
||||
remote_id: str
|
||||
# Take the session from the computer holding it (the user confirmed).
|
||||
takeover: bool = False
|
||||
|
||||
|
||||
class CollectionCandidate(BaseModel):
|
||||
path: str
|
||||
label: str # folder name, e.g. "Traktor 4.5.0"
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
"""Konduktor's server: one library, held on the machine where its audio lives,
|
||||
opened from the desktop app as a "Remote" library. See `app.py`."""
|
||||
@@ -0,0 +1,37 @@
|
||||
"""`python -m konduktor.server` — what the container runs.
|
||||
|
||||
Configuration is the environment (see `config.py`); a bad setting stops here
|
||||
with one clear line instead of serving a library that half-works.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import sys
|
||||
|
||||
import uvicorn
|
||||
|
||||
from .config import ConfigError, from_env
|
||||
|
||||
|
||||
def main() -> int:
|
||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
|
||||
try:
|
||||
config = from_env()
|
||||
except ConfigError as ex:
|
||||
print(f"konduktor-server: {ex}", file=sys.stderr)
|
||||
return 2
|
||||
from .app import Server, create_app
|
||||
|
||||
server = Server(config)
|
||||
try:
|
||||
server.open()
|
||||
except ConfigError as ex:
|
||||
print(f"konduktor-server: {ex}", file=sys.stderr)
|
||||
return 2
|
||||
uvicorn.run(create_app(server), host=config.host, port=config.port,
|
||||
log_level="info", proxy_headers=True)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,657 @@
|
||||
"""The Konduktor SERVER: one library, held where its audio lives.
|
||||
|
||||
Runs in a container on the user's NAS (`server/Dockerfile`) and is opened from
|
||||
the desktop app as a "Remote" library. It is deliberately NOT `main.py` behind a
|
||||
password: the UI's routes would become a public contract, and half of them are
|
||||
about THIS computer (its drives, its stem engine, its sticks). What it serves is
|
||||
the `LibraryAdapter` protocol itself (`remote_protocol.py`), plus the few things
|
||||
that are bytes — audio, art, uploads — and the app-level bookkeeping that lives
|
||||
beside the library: save + backups + version history, export sets, the stems
|
||||
ledger.
|
||||
|
||||
Lightweight by decision: the server never DECODES audio. Analysis, waveforms and
|
||||
stem separation all run on the computer that opened the library; what arrives
|
||||
here are the results, as ordinary commands. Its work is file IO, the native
|
||||
model, tags, and header reads.
|
||||
|
||||
One computer at a time (`session.py`): every command carries the session token,
|
||||
and anything that changes the library without it is answered 423 with who holds
|
||||
it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import mimetypes
|
||||
import os
|
||||
import secrets
|
||||
import shutil
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import Body, Depends, FastAPI, Header, HTTPException, Query, Request, Response
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
from fastapi.security import HTTPBasic, HTTPBasicCredentials
|
||||
|
||||
from .. import __version__, exports
|
||||
from .. import remote_protocol as rp
|
||||
from ..app_state import AppState
|
||||
from ..core import registry
|
||||
from ..core.adapter import (
|
||||
AdapterError,
|
||||
InvalidCommand,
|
||||
LibraryNotSupported,
|
||||
NewTrack,
|
||||
NotFound,
|
||||
Unsupported,
|
||||
)
|
||||
from ..core.places import is_os_housekeeping
|
||||
from .config import ConfigError, ServerConfig
|
||||
from .session import InUse, Lost, SessionLock
|
||||
|
||||
log = logging.getLogger("konduktor.server")
|
||||
|
||||
#: Upload partials, published by a rename that never overwrites.
|
||||
PARTIAL_SUFFIX = ".konduktor-upload"
|
||||
_CHUNK = 1 << 20
|
||||
|
||||
|
||||
class Server:
|
||||
"""The open library, its session, and the revision counter clients follow."""
|
||||
|
||||
def __init__(self, config: ServerConfig, *, state: AppState | None = None,
|
||||
lock: SessionLock | None = None):
|
||||
self.config = config
|
||||
self.state = state if state is not None else _default_state()
|
||||
self.lock = lock or SessionLock()
|
||||
self.rev = 0
|
||||
self._rev_lock = threading.Lock()
|
||||
|
||||
# ---- opening ---------------------------------------------------------------
|
||||
def open(self) -> None:
|
||||
cfg = self.config
|
||||
try:
|
||||
driver = registry.driver_for(cfg.library)
|
||||
except LibraryNotSupported as ex:
|
||||
raise ConfigError(f"KONDUKTOR_LIBRARY: {ex}")
|
||||
if driver.platform != cfg.platform:
|
||||
raise ConfigError(
|
||||
f"KONDUKTOR_PLATFORM is {cfg.platform!r} but {cfg.library} is a "
|
||||
f"{driver.display_name} library"
|
||||
)
|
||||
self.state.open_hooks.append(self._configure)
|
||||
self.state.open(cfg.library)
|
||||
|
||||
def _configure(self, adapter) -> None:
|
||||
"""After every (re)open: the configured path mapping, and no missing-files
|
||||
search of a container's empty drives."""
|
||||
maps = self.config.path_maps
|
||||
if maps:
|
||||
adapter.set_path_mapping(maps[0])
|
||||
adapter.set_session_mappings(list(maps[1:]))
|
||||
# A file uploaded here is stored as the library stores every other
|
||||
# path — so it still opens, mapping and all, where it was made.
|
||||
write_stored = getattr(adapter, "set_write_stored_paths", None)
|
||||
if write_stored is not None:
|
||||
write_stored(True)
|
||||
self.state.relocation = None
|
||||
|
||||
@property
|
||||
def adapter(self):
|
||||
if self.state.adapter is None:
|
||||
raise HTTPException(503, "The library is not open")
|
||||
return self.state.adapter
|
||||
|
||||
def bump(self) -> int:
|
||||
with self._rev_lock:
|
||||
self.rev += 1
|
||||
return self.rev
|
||||
|
||||
# ---- facts -------------------------------------------------------------------
|
||||
def capabilities(self):
|
||||
"""The adapter's own, plus what being held by a server changes."""
|
||||
caps = self.adapter.capabilities().model_copy(deep=True)
|
||||
caps.tracks.audio_destination = "library"
|
||||
caps.tracks.reference = False
|
||||
caps.paths.remappable = False
|
||||
# Nothing runs a DJ app against a library on a NAS while it is being
|
||||
# saved: the "close Traktor first" warning would only confuse.
|
||||
caps.save.overwrite_risk = "none"
|
||||
return caps
|
||||
|
||||
def name(self) -> str:
|
||||
return self.config.name or self.config.library.stem
|
||||
|
||||
def pending_edits(self, client_id: str | None = None) -> dict | None:
|
||||
"""The unsaved edits someone else left, for the computer arriving."""
|
||||
adapter = self.adapter
|
||||
if not adapter.dirty:
|
||||
return None
|
||||
editor = self.lock.last_editor or {}
|
||||
if client_id and editor.get("client_id") == client_id:
|
||||
return None
|
||||
summary = getattr(adapter, "edit_summary", None)
|
||||
return {
|
||||
"machine": editor.get("machine"),
|
||||
"summary": (summary() if summary else "") or "unsaved changes",
|
||||
}
|
||||
|
||||
def confine(self, raw: str | None) -> Path:
|
||||
"""A path inside the content folder, or 400. Resolved first, so neither
|
||||
`..` nor a symlink can lead out of it."""
|
||||
root = self.config.content
|
||||
candidate = Path(raw) if raw else root
|
||||
if not candidate.is_absolute():
|
||||
candidate = root / candidate
|
||||
resolved = candidate.resolve()
|
||||
if resolved != root and not resolved.is_relative_to(root):
|
||||
raise HTTPException(400, f"{raw} is outside the library's content folder")
|
||||
return resolved
|
||||
|
||||
|
||||
def _default_state() -> AppState:
|
||||
# The process-wide STATE: a server holds one library, and the stem end step
|
||||
# reaches for `app_state.STATE.mutation` like the desktop app's does.
|
||||
from ..app_state import STATE
|
||||
|
||||
return STATE
|
||||
|
||||
|
||||
def create_app(server: Server) -> FastAPI:
|
||||
cfg = server.config
|
||||
security = HTTPBasic(realm="Konduktor")
|
||||
|
||||
def auth(creds: HTTPBasicCredentials = Depends(security)) -> None:
|
||||
user_ok = secrets.compare_digest(creds.username.encode(), cfg.username.encode())
|
||||
pass_ok = secrets.compare_digest(creds.password.encode(), cfg.password.encode())
|
||||
if not (user_ok and pass_ok):
|
||||
raise HTTPException(401, "Wrong username or password",
|
||||
headers={"WWW-Authenticate": 'Basic realm="Konduktor"'})
|
||||
|
||||
app = FastAPI(title="Konduktor server", version=__version__, dependencies=[Depends(auth)])
|
||||
app.state.server = server
|
||||
|
||||
@app.exception_handler(AdapterError)
|
||||
def _adapter_error(_request, exc: AdapterError):
|
||||
status = {NotFound: 404, InvalidCommand: 400, Unsupported: 422,
|
||||
LibraryNotSupported: 400}.get(type(exc), 400)
|
||||
return JSONResponse(status_code=status, content={"detail": str(exc)})
|
||||
|
||||
def session(token: str | None = Header(None, alias=rp.SESSION_HEADER)):
|
||||
try:
|
||||
return server.lock.check(token)
|
||||
except Lost as ex:
|
||||
raise HTTPException(423, {
|
||||
"code": "taken_over", "message": str(ex), "holder": server.lock.describe(),
|
||||
})
|
||||
|
||||
# ---- handshake + session -----------------------------------------------------
|
||||
@app.get("/v1/hello")
|
||||
def hello(client_id: str | None = None) -> dict:
|
||||
state = server.state
|
||||
caps = server.capabilities()
|
||||
return {
|
||||
"api_version": list(rp.API_VERSION),
|
||||
"app_version": __version__,
|
||||
"platform": caps.platform,
|
||||
"app_name": caps.save.app_name,
|
||||
"library_label": caps.save.library_label,
|
||||
"name": server.name(),
|
||||
"path": str(state.path),
|
||||
"library_id": state.library_id,
|
||||
"holder": server.lock.describe(),
|
||||
"dirty": server.adapter.dirty,
|
||||
"pending_edits": server.pending_edits(client_id),
|
||||
"rev": server.rev,
|
||||
}
|
||||
|
||||
@app.post("/v1/session/acquire")
|
||||
def acquire(body: dict = Body(...)) -> dict:
|
||||
client_id = str(body.get("client_id") or "")
|
||||
machine = str(body.get("machine") or "another computer")
|
||||
if not client_id:
|
||||
raise HTTPException(400, "client_id is required")
|
||||
try:
|
||||
holder = server.lock.acquire(client_id, machine, takeover=bool(body.get("takeover")))
|
||||
except InUse as ex:
|
||||
h = ex.holder
|
||||
raise HTTPException(409, {"code": "in_use", "machine": h.machine,
|
||||
"since": h.since, "batch": h.batch})
|
||||
return {
|
||||
"token": holder.token,
|
||||
"lease": server.lock.lease,
|
||||
"heartbeat": rp.HEARTBEAT_SECONDS,
|
||||
"pending_edits": server.pending_edits(client_id),
|
||||
"rev": server.rev,
|
||||
}
|
||||
|
||||
@app.post("/v1/session/heartbeat")
|
||||
def heartbeat(body: dict = Body(default={}),
|
||||
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
try:
|
||||
server.lock.heartbeat(token, body.get("batch"))
|
||||
except Lost as ex:
|
||||
raise HTTPException(423, {"code": "taken_over", "message": str(ex),
|
||||
"holder": server.lock.describe()})
|
||||
return {"rev": server.rev, "dirty": server.adapter.dirty}
|
||||
|
||||
@app.post("/v1/session/release")
|
||||
def release(token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
server.lock.release(token)
|
||||
return {"status": "released"}
|
||||
|
||||
# ---- the protocol ------------------------------------------------------------
|
||||
@app.post("/v1/rpc/{name}")
|
||||
def rpc(name: str, body: dict = Body(default={}),
|
||||
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
method = rp.RPC.get(name)
|
||||
if method is None:
|
||||
raise HTTPException(404, f"No such method: {name}")
|
||||
holder = session(token) if method.mutating else None
|
||||
try:
|
||||
args = rp.load_args(name, body.get("args") or {})
|
||||
except ValueError as ex:
|
||||
raise HTTPException(400, str(ex))
|
||||
adapter = server.adapter
|
||||
changed: list = []
|
||||
removed: list[str] = []
|
||||
reset = False
|
||||
if name == "capabilities":
|
||||
value = server.capabilities()
|
||||
elif name == "add_tracks":
|
||||
with server.state.mutation:
|
||||
value = adapter.add_tracks([_new_track(server, w) for w in args["items"]])
|
||||
changed = [t for i in value if (t := adapter.track(i)) is not None]
|
||||
elif method.prop:
|
||||
value = getattr(adapter, name)
|
||||
else:
|
||||
value = getattr(adapter, name)(**args)
|
||||
if method.mutating:
|
||||
if name == "remove_tracks":
|
||||
removed = list(args["track_ids"])
|
||||
elif "track_id" in args:
|
||||
track = adapter.track(args["track_id"])
|
||||
if track is None:
|
||||
removed = [args["track_id"]]
|
||||
else:
|
||||
changed = [track]
|
||||
server.lock.touch(holder)
|
||||
rev = server.bump()
|
||||
else:
|
||||
rev = server.rev
|
||||
return {
|
||||
"result": rp.dump_result(name, value),
|
||||
"rev": rev,
|
||||
"changed": [t.model_dump(mode="json") for t in changed],
|
||||
"removed": removed,
|
||||
"reset": reset,
|
||||
}
|
||||
|
||||
# ---- bytes -------------------------------------------------------------------
|
||||
@app.get("/v1/audio")
|
||||
def audio(track_id: str):
|
||||
path = server.adapter.audio_path(track_id)
|
||||
if path is None or not Path(path).is_file():
|
||||
raise HTTPException(404, "The audio file is missing")
|
||||
st = Path(path).stat()
|
||||
media = mimetypes.guess_type(str(path))[0] or "application/octet-stream"
|
||||
return FileResponse(path, media_type=media, headers={
|
||||
"X-Konduktor-Size": str(st.st_size),
|
||||
"X-Konduktor-Mtime-Ns": str(st.st_mtime_ns),
|
||||
})
|
||||
|
||||
@app.get("/v1/art")
|
||||
def art(track_id: str):
|
||||
found = server.adapter.cover_art(track_id)
|
||||
if not found:
|
||||
raise HTTPException(404, "No cover art")
|
||||
data, mime = found
|
||||
return Response(content=data, media_type=mime)
|
||||
|
||||
@app.put("/v1/art")
|
||||
async def put_art(request: Request, track_id: str, mime: str,
|
||||
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
holder = session(token)
|
||||
data = await request.body()
|
||||
server.adapter.set_cover_art(track_id, data, mime)
|
||||
server.lock.touch(holder)
|
||||
track = server.adapter.track(track_id)
|
||||
return {"rev": server.bump(), "changed": [track.model_dump(mode="json")] if track else []}
|
||||
|
||||
@app.post("/v1/upload")
|
||||
async def upload(request: Request, dir: str, name: str,
|
||||
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
"""Receive one audio file into `dir` (created if needed) under the content
|
||||
folder. Never overwrites: a name already taken gets `-2`, `-3`, … as a
|
||||
local import's copy does. The partial is renamed in only when complete,
|
||||
so a cut connection leaves no half file under a real name."""
|
||||
holder = session(token)
|
||||
folder = server.confine(dir)
|
||||
clean = _safe_name(name)
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
partial = folder / f".{clean}.{secrets.token_hex(4)}{PARTIAL_SUFFIX}"
|
||||
try:
|
||||
with open(partial, "wb") as out:
|
||||
async for chunk in request.stream():
|
||||
out.write(chunk)
|
||||
target = _publish(partial, folder / clean)
|
||||
finally:
|
||||
partial.unlink(missing_ok=True)
|
||||
holder.uploads.add(str(target))
|
||||
st = target.stat()
|
||||
# A platform that analyses what it adds measures on its own clock, read
|
||||
# from the file's header — which only the server can read. The client
|
||||
# measures with this (`PreparedAnalysis`); None: nothing to measure.
|
||||
lead = getattr(server.adapter, "analysis_lead", None)
|
||||
return {"path": str(target), "size": st.st_size, "mtime_ns": st.st_mtime_ns,
|
||||
"analysis_lead": lead(target) if lead else None}
|
||||
|
||||
@app.delete("/v1/upload")
|
||||
def delete_upload(path: str, token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
"""Remove a file THIS session uploaded and the library does not name —
|
||||
how a cancelled or failed import cleans up after itself."""
|
||||
holder = session(token)
|
||||
target = server.confine(path)
|
||||
if str(target) not in holder.uploads:
|
||||
raise HTTPException(403, "Only a file this session uploaded can be removed")
|
||||
adapter = server.adapter
|
||||
named = {f.key for f in adapter.audio_facts([t.id for t in adapter.tracks]).values()}
|
||||
if str(target) in named:
|
||||
raise HTTPException(409, "The library names that file")
|
||||
target.unlink(missing_ok=True)
|
||||
holder.uploads.discard(str(target))
|
||||
return {"status": "deleted"}
|
||||
|
||||
# ---- the content folder ------------------------------------------------------
|
||||
@app.get("/v1/fs/list")
|
||||
def fs_list(path: str | None = None) -> dict:
|
||||
folder = server.confine(path)
|
||||
if not folder.is_dir():
|
||||
raise HTTPException(404, f"Not a folder: {folder}")
|
||||
entries = []
|
||||
try:
|
||||
children = sorted(folder.iterdir(), key=lambda p: p.name.lower())
|
||||
except OSError as ex:
|
||||
raise HTTPException(400, f"Cannot list {folder}: {ex}")
|
||||
for child in children:
|
||||
if child.name.startswith(".") or is_os_housekeeping(child.name):
|
||||
continue
|
||||
try:
|
||||
is_dir = child.is_dir()
|
||||
except OSError:
|
||||
continue
|
||||
entries.append({"name": child.name, "path": str(child), "is_dir": is_dir})
|
||||
root = server.config.content
|
||||
return {
|
||||
"path": str(folder),
|
||||
"parent": None if folder == root else str(folder.parent),
|
||||
"root": str(root),
|
||||
"entries": entries,
|
||||
}
|
||||
|
||||
@app.get("/v1/fs/space")
|
||||
def fs_space(path: str | None = None) -> dict:
|
||||
folder = server.confine(path)
|
||||
probe = folder
|
||||
while not probe.exists() and probe != server.config.content:
|
||||
probe = probe.parent
|
||||
return {"free": shutil.disk_usage(probe).free}
|
||||
|
||||
# ---- save / discard / history ------------------------------------------------
|
||||
@app.post("/v1/save")
|
||||
def save(token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
session(token)
|
||||
adapter = server.adapter
|
||||
if not adapter.dirty:
|
||||
return {"saved": False, "commit": None, "summary": "",
|
||||
"tag_results": [], "playlists": adapter.playlist_count(), "rev": server.rev}
|
||||
outcome, commit = server.state.save()
|
||||
server.lock.clear_editor()
|
||||
return {
|
||||
"saved": True,
|
||||
"commit": commit,
|
||||
"summary": outcome.summary,
|
||||
"tag_results": [r.__dict__ for r in outcome.tag_results],
|
||||
"playlists": adapter.playlist_count(),
|
||||
"rev": server.bump(),
|
||||
}
|
||||
|
||||
@app.post("/v1/discard")
|
||||
def discard(token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
session(token)
|
||||
server.state.discard()
|
||||
server._configure(server.adapter)
|
||||
server.lock.clear_editor()
|
||||
return {"rev": server.bump()}
|
||||
|
||||
@app.get("/v1/history")
|
||||
def history() -> list[dict]:
|
||||
return [e.__dict__ for e in server.state.services.history()]
|
||||
|
||||
@app.post("/v1/history/{commit_id}/restore")
|
||||
def restore(commit_id: str, token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
session(token)
|
||||
if not server.state.restore_version(commit_id):
|
||||
raise HTTPException(404, f"Version not found: {commit_id}")
|
||||
server.lock.clear_editor()
|
||||
return {"rev": server.bump()}
|
||||
|
||||
@app.delete("/v1/history")
|
||||
def clear_history(token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
session(token)
|
||||
server.state.services.clear_history()
|
||||
return {"status": "cleared"}
|
||||
|
||||
# ---- export sets -------------------------------------------------------------
|
||||
@app.get("/v1/export-sets")
|
||||
def get_export_sets() -> dict:
|
||||
return exports._read_doc(server.state.library_id)
|
||||
|
||||
@app.put("/v1/export-sets")
|
||||
def put_export_sets(doc: dict = Body(...),
|
||||
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
session(token)
|
||||
if not isinstance(doc.get("sets"), dict):
|
||||
raise HTTPException(400, "Expected {'sets': {...}}")
|
||||
exports._write_doc(server.state.library_id,
|
||||
{"library_id": server.state.library_id, "sets": doc["sets"]})
|
||||
return {"status": "saved"}
|
||||
|
||||
# ---- Convert to Stems: the library side ---------------------------------------
|
||||
# The SEPARATION runs on the computer that opened the library (the server
|
||||
# never decodes audio); what lives here is everything about the FILES and the
|
||||
# library: where each stem file goes, what is skipped and why, the verified
|
||||
# files it uploads (kept as leftovers until the batch's end step, so a
|
||||
# takeover mid-batch loses nothing — the next run reuses them), and the end
|
||||
# step itself, under the library's mutation lock, with the server's ledger.
|
||||
def stem_options(body: dict):
|
||||
from ..stems import convert
|
||||
|
||||
destination = body.get("destination")
|
||||
if body.get("mode") == "destination":
|
||||
if not destination:
|
||||
raise HTTPException(400, "Choose a destination folder")
|
||||
destination = server.confine(destination)
|
||||
return convert.Options(
|
||||
mode=body.get("mode") or "replace", destination=Path(destination) if destination else None,
|
||||
collection=body.get("collection") or "repoint", playlist_id=body.get("playlist_id"),
|
||||
new_playlist=body.get("new_playlist"),
|
||||
)
|
||||
|
||||
@app.post("/v1/stems/plan")
|
||||
def stems_plan(body: dict = Body(...)) -> dict:
|
||||
from ..stems import convert
|
||||
|
||||
adapter = server.adapter
|
||||
caps = adapter.capabilities()
|
||||
if not caps.tracks.stem_convertible:
|
||||
raise HTTPException(422, "This library cannot hold stem files")
|
||||
try:
|
||||
planned = convert.plan(adapter, list(body.get("track_ids") or []), stem_options(body),
|
||||
server.state.pending)
|
||||
except convert.ConvertError as ex:
|
||||
raise HTTPException(400, str(ex))
|
||||
out = planned.as_dict()
|
||||
out["items"] = [{
|
||||
"track_id": p.track_id, "title": p.title, "source": str(p.source), "target": str(p.target),
|
||||
"seconds": p.seconds, "source_size": p.source.stat().st_size if p.source.exists() else 0,
|
||||
"reuse": p.reuse["written"] if p.reuse else None,
|
||||
} for p in planned.items]
|
||||
return out
|
||||
|
||||
def stem_item(track_id: str, target: str) -> tuple[Path, Path]:
|
||||
"""The source and target a stem upload / publish names, checked against
|
||||
the library rather than trusted: a target outside the content folder, or
|
||||
one not named after its own track's file, is refused."""
|
||||
from ..core import stem_file as sf
|
||||
|
||||
source = server.adapter.audio_path(track_id)
|
||||
if source is None or not Path(source).is_file():
|
||||
raise HTTPException(404, "The track's audio file is missing")
|
||||
dest = server.confine(target)
|
||||
if dest.name != sf.stem_target_name(Path(source).name):
|
||||
raise HTTPException(400, f"{dest.name} is not the stem file of {Path(source).name}")
|
||||
return Path(source), dest
|
||||
|
||||
@app.put("/v1/stems/stage")
|
||||
async def stems_stage(request: Request, track_id: str, target: str, sha256: str,
|
||||
bit_rate: int, duration: float,
|
||||
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
import hashlib
|
||||
|
||||
from ..stems.pending import partial_name, source_facts
|
||||
|
||||
session(token)
|
||||
source, dest = stem_item(track_id, target)
|
||||
if dest.exists():
|
||||
raise HTTPException(409, f"A stem file already exists: {dest.name}")
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
partial = partial_name(dest)
|
||||
incoming = dest.with_name(f".{dest.name}.{secrets.token_hex(4)}{PARTIAL_SUFFIX}")
|
||||
digest = hashlib.sha256()
|
||||
size = 0
|
||||
try:
|
||||
with open(incoming, "wb") as out:
|
||||
async for chunk in request.stream():
|
||||
out.write(chunk)
|
||||
digest.update(chunk)
|
||||
size += len(chunk)
|
||||
if digest.hexdigest() != sha256.lower():
|
||||
raise HTTPException(400, "The stem file arrived damaged (checksum mismatch)")
|
||||
os.replace(incoming, partial)
|
||||
finally:
|
||||
incoming.unlink(missing_ok=True)
|
||||
pending = server.state.pending
|
||||
with pending._lock:
|
||||
pending.leftovers = [lo for lo in pending.leftovers if lo["partial"] != str(partial)]
|
||||
pending.leftovers.append({
|
||||
"source": str(source), "facts": source_facts(source), "partial": str(partial),
|
||||
"written": {"bit_rate": bit_rate, "duration": duration, "size": size},
|
||||
})
|
||||
pending._write()
|
||||
return {"partial": str(partial), "size": size}
|
||||
|
||||
@app.post("/v1/stems/abandon")
|
||||
def stems_abandon(body: dict = Body(...),
|
||||
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
"""A cancelled batch: delete the files it uploaded (a cancel deletes
|
||||
only new files, as on this computer)."""
|
||||
from ..stems.pending import partial_name
|
||||
|
||||
session(token)
|
||||
pending = server.state.pending
|
||||
wanted = {str(partial_name(server.confine(t))) for t in body.get("targets") or []}
|
||||
for lo in [lo for lo in pending.leftovers if lo["partial"] in wanted]:
|
||||
pending.forget_leftover(lo, delete=True)
|
||||
return {"status": "abandoned"}
|
||||
|
||||
@app.post("/v1/stems/publish")
|
||||
def stems_publish(body: dict = Body(...),
|
||||
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
"""The batch's END STEP, here where the files are: publish each staged
|
||||
stem file, park originals (Replace), swap every entry at once."""
|
||||
from ..core import stem_file as sf
|
||||
from ..stems import convert
|
||||
from ..stems.pending import partial_name
|
||||
|
||||
holder = session(token)
|
||||
opts = stem_options(body.get("options") or {})
|
||||
pending = server.state.pending
|
||||
result = {"converted": [], "renamed": {}, "added": {}, "failed": [], "clamped": {}}
|
||||
with server.state.mutation:
|
||||
finished = []
|
||||
for entry in body.get("items") or []:
|
||||
source, dest = stem_item(entry["track_id"], entry["target"])
|
||||
partial = partial_name(dest)
|
||||
lo = next((x for x in pending.leftovers if x["partial"] == str(partial)), None)
|
||||
track = server.adapter.track(entry["track_id"])
|
||||
title = convert._title(track)
|
||||
if lo is None or not partial.is_file():
|
||||
result["failed"].append({"track_id": entry["track_id"], "title": title,
|
||||
"reason": "the converted file never reached the server"})
|
||||
continue
|
||||
written = lo["written"]
|
||||
pitem = pending.add({"track_id": entry["track_id"], "mode": opts.collection,
|
||||
"source": str(source), "stem": str(dest), "state": "converted",
|
||||
"facts": lo.get("facts"), "written": written})
|
||||
pending.forget_leftover(lo, delete=False)
|
||||
planned = convert.Planned(entry["track_id"], title, source, dest, float(written["duration"]))
|
||||
finished.append((planned, pitem, sf.Written(path=partial, bit_rate=int(written["bit_rate"]),
|
||||
duration=float(written["duration"]),
|
||||
size=int(written["size"]), tags={})))
|
||||
convert._end_step(server.adapter, finished, opts, pending, result)
|
||||
server.lock.touch(holder)
|
||||
result["rev"] = server.bump()
|
||||
return result
|
||||
|
||||
@app.get("/v1/stems/pending")
|
||||
def stems_pending() -> dict:
|
||||
pending = server.state.pending
|
||||
return pending.summary() if pending is not None else {"tracks": 0, "parked": 0, "bytes": 0}
|
||||
|
||||
return app
|
||||
|
||||
|
||||
def _safe_name(name: str) -> str:
|
||||
clean = os.path.basename((name or "").replace("\\", "/")).strip()
|
||||
if not clean or clean in (".", "..") or clean.startswith("."):
|
||||
raise HTTPException(400, f"Not a usable file name: {name!r}")
|
||||
return clean
|
||||
|
||||
|
||||
def _publish(partial: Path, wanted: Path) -> Path:
|
||||
"""Rename `partial` to `wanted`, or `wanted-2`… — never over an existing file
|
||||
(a hard link fails rather than replaces)."""
|
||||
stem, suffix = wanted.stem, wanted.suffix
|
||||
# `.stem.m4a` keeps its double suffix together.
|
||||
if stem.endswith(".stem"):
|
||||
stem, suffix = stem[: -len(".stem")], ".stem" + suffix
|
||||
n = 1
|
||||
while True:
|
||||
target = wanted if n == 1 else wanted.with_name(f"{stem}-{n}{suffix}")
|
||||
try:
|
||||
os.link(partial, target)
|
||||
return target
|
||||
except FileExistsError:
|
||||
n += 1
|
||||
|
||||
|
||||
def _new_track(server: Server, wire: rp.WireNewTrack) -> NewTrack:
|
||||
import base64
|
||||
|
||||
path = server.confine(wire.audio_path)
|
||||
art = (base64.b64decode(wire.art.data), wire.art.mime) if wire.art else None
|
||||
return NewTrack(track=wire.track, audio_path=path, cues=wire.cues, art=art,
|
||||
analysis=rp.unpack_analysis(wire.analysis))
|
||||
|
||||
|
||||
# ---- entry points ------------------------------------------------------------------
|
||||
|
||||
|
||||
def create_from_env() -> FastAPI:
|
||||
"""`uvicorn --factory konduktor.server.app:create_from_env`."""
|
||||
from .config import from_env
|
||||
|
||||
server = Server(from_env())
|
||||
server.open()
|
||||
log.info("Serving %s (%s) to remote clients", server.config.library, server.config.platform)
|
||||
return create_app(server)
|
||||
@@ -0,0 +1,101 @@
|
||||
"""The server's configuration: the container's environment (its `.env`).
|
||||
|
||||
Everything is read once at start and checked before the library is opened, and
|
||||
a bad setting stops the container with ONE clear line rather than a library
|
||||
that half-works: a missing content folder would otherwise show up as every
|
||||
track "missing", and an empty password as an open door.
|
||||
|
||||
KONDUKTOR_PLATFORM traktor | rekordbox — checked against the library file
|
||||
KONDUKTOR_LIBRARY the library file (collection.nml / master.db)
|
||||
KONDUKTOR_CONTENT the folder holding the audio; uploads and the folder
|
||||
browser are confined to it
|
||||
KONDUKTOR_USERNAME the one account
|
||||
KONDUKTOR_PASSWORD
|
||||
KONDUKTOR_PATH_MAP optional: "stored => here", e.g.
|
||||
"/Users/ben/Music => /music"; several separated by ";".
|
||||
Applied for the session only — the library keeps its
|
||||
stored paths, so it still opens on the computer it
|
||||
was made on.
|
||||
KONDUKTOR_NAME optional: what the library is called on screen
|
||||
KONDUKTOR_DATA_DIR where history, export sets and the ledger live
|
||||
(read by `paths.app_data_dir`)
|
||||
KONDUKTOR_HOST / KONDUKTOR_PORT where to listen (0.0.0.0:8765)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from ..core.pathmap import PathMapping
|
||||
|
||||
PLATFORMS = ("traktor", "rekordbox")
|
||||
|
||||
|
||||
class ConfigError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ServerConfig:
|
||||
platform: str
|
||||
library: Path
|
||||
content: Path
|
||||
username: str
|
||||
password: str
|
||||
path_maps: tuple[PathMapping, ...] = field(default_factory=tuple)
|
||||
name: str = ""
|
||||
host: str = "0.0.0.0"
|
||||
port: int = 8765
|
||||
|
||||
|
||||
def parse_path_maps(text: str | None) -> tuple[PathMapping, ...]:
|
||||
"""`"a => b; c => d"` → mappings. Raises `ConfigError` on a malformed one."""
|
||||
out = []
|
||||
for part in (text or "").split(";"):
|
||||
part = part.strip()
|
||||
if not part:
|
||||
continue
|
||||
if "=>" not in part:
|
||||
raise ConfigError(f"KONDUKTOR_PATH_MAP: expected 'stored => here', got {part!r}")
|
||||
src, dst = (s.strip() for s in part.split("=>", 1))
|
||||
mapping = PathMapping.make(src, dst)
|
||||
if mapping.empty:
|
||||
raise ConfigError(f"KONDUKTOR_PATH_MAP: both sides are needed in {part!r}")
|
||||
out.append(mapping)
|
||||
return tuple(out)
|
||||
|
||||
|
||||
def from_env(env=None) -> ServerConfig:
|
||||
env = os.environ if env is None else env
|
||||
|
||||
def need(key: str) -> str:
|
||||
value = (env.get(key) or "").strip()
|
||||
if not value:
|
||||
raise ConfigError(f"{key} is not set")
|
||||
return value
|
||||
|
||||
platform = need("KONDUKTOR_PLATFORM").lower()
|
||||
if platform not in PLATFORMS:
|
||||
raise ConfigError(f"KONDUKTOR_PLATFORM must be one of {', '.join(PLATFORMS)}, not {platform!r}")
|
||||
library = Path(need("KONDUKTOR_LIBRARY"))
|
||||
if not library.exists():
|
||||
raise ConfigError(f"KONDUKTOR_LIBRARY: {library} does not exist")
|
||||
content = Path(need("KONDUKTOR_CONTENT"))
|
||||
if not content.is_dir():
|
||||
raise ConfigError(f"KONDUKTOR_CONTENT: {content} is not a folder")
|
||||
username = need("KONDUKTOR_USERNAME")
|
||||
password = env.get("KONDUKTOR_PASSWORD") or ""
|
||||
if not password:
|
||||
raise ConfigError("KONDUKTOR_PASSWORD is not set")
|
||||
try:
|
||||
port = int(env.get("KONDUKTOR_PORT") or 8765)
|
||||
except ValueError:
|
||||
raise ConfigError("KONDUKTOR_PORT must be a number")
|
||||
return ServerConfig(
|
||||
platform=platform, library=library, content=content.resolve(),
|
||||
username=username, password=password,
|
||||
path_maps=parse_path_maps(env.get("KONDUKTOR_PATH_MAP")),
|
||||
name=(env.get("KONDUKTOR_NAME") or "").strip(),
|
||||
host=(env.get("KONDUKTOR_HOST") or "0.0.0.0").strip(), port=port,
|
||||
)
|
||||
@@ -0,0 +1,133 @@
|
||||
"""One computer at a time: the server's session lock.
|
||||
|
||||
A library held by a server is edited by ONE computer at a time (decided: a
|
||||
shared or merged session was rejected). That computer holds the session; every
|
||||
command carries its token, and anything else is told who holds it.
|
||||
|
||||
* **A lease, renewed by heartbeat.** The holder's app sends one every
|
||||
`HEARTBEAT_SECONDS`; `LEASE_SECONDS` without one and the session is free.
|
||||
A crashed laptop or a closed lid therefore never locks the library for
|
||||
good, and a Wi-Fi blip does not lose it.
|
||||
* **Takeover** is how a second computer gets in before the lease runs out:
|
||||
it is told who holds the session (and what batch is running there) and may
|
||||
take it. The old token is refused from then on, which is how the displaced
|
||||
computer finds out.
|
||||
* **The same computer coming back** — after sleep, after a reconnect through
|
||||
its fallback address — renews its expired lease silently, as long as
|
||||
nobody else has taken the session meanwhile.
|
||||
|
||||
Unsaved edits are NOT the session's: they live in the one native model the
|
||||
server holds, so whoever holds the session next inherits them (and is asked to
|
||||
save or discard them — `last_editor` says whose they were).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from ..remote_protocol import LEASE_SECONDS
|
||||
|
||||
|
||||
@dataclass
|
||||
class Holder:
|
||||
token: str
|
||||
client_id: str
|
||||
machine: str
|
||||
since: str # ISO 8601, UTC
|
||||
last_seen: float # on the lock's clock
|
||||
batch: str | None = None # the kind of batch job running there, if any
|
||||
uploads: set[str] = field(default_factory=set)
|
||||
|
||||
|
||||
class InUse(Exception):
|
||||
"""Another computer holds the session."""
|
||||
|
||||
def __init__(self, holder: Holder):
|
||||
super().__init__(f"In use by {holder.machine}")
|
||||
self.holder = holder
|
||||
|
||||
|
||||
class Lost(Exception):
|
||||
"""This token no longer holds the session."""
|
||||
|
||||
def __init__(self, holder: Holder | None):
|
||||
super().__init__("Another computer has taken over this library" if holder
|
||||
else "This computer no longer holds the session")
|
||||
self.holder = holder
|
||||
|
||||
|
||||
def _now_iso() -> str:
|
||||
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
|
||||
|
||||
class SessionLock:
|
||||
def __init__(self, *, lease: float = LEASE_SECONDS, clock=time.monotonic):
|
||||
self.lease = lease
|
||||
self._clock = clock
|
||||
self._lock = threading.Lock()
|
||||
self._holder: Holder | None = None
|
||||
#: The machine whose commands made the unsaved edits (see `touch`).
|
||||
self.last_editor: dict | None = None
|
||||
|
||||
# ---- reading --------------------------------------------------------------
|
||||
def _live(self, holder: Holder | None) -> bool:
|
||||
return holder is not None and self._clock() - holder.last_seen < self.lease
|
||||
|
||||
def holder(self) -> Holder | None:
|
||||
"""Who holds the session right now (None: free, or the lease ran out)."""
|
||||
with self._lock:
|
||||
return self._holder if self._live(self._holder) else None
|
||||
|
||||
def describe(self) -> dict | None:
|
||||
h = self.holder()
|
||||
return None if h is None else {"machine": h.machine, "since": h.since, "batch": h.batch}
|
||||
|
||||
# ---- changing -------------------------------------------------------------
|
||||
def acquire(self, client_id: str, machine: str, *, takeover: bool = False) -> Holder:
|
||||
"""Hold the session. Raises `InUse` when another computer holds it and
|
||||
`takeover` is not set. The same client re-acquiring keeps its uploads."""
|
||||
with self._lock:
|
||||
current = self._holder
|
||||
live = self._live(current)
|
||||
if live and current.client_id != client_id and not takeover:
|
||||
raise InUse(current)
|
||||
uploads = current.uploads if current is not None and current.client_id == client_id else set()
|
||||
self._holder = Holder(
|
||||
token=secrets.token_urlsafe(24), client_id=client_id, machine=machine,
|
||||
since=_now_iso(), last_seen=self._clock(), uploads=uploads,
|
||||
)
|
||||
return self._holder
|
||||
|
||||
def check(self, token: str | None) -> Holder:
|
||||
"""The holder this token names, renewing its lease. Raises `Lost`.
|
||||
|
||||
A token whose lease ran out is still honoured when nobody else has
|
||||
taken the session since — the same computer back from sleep."""
|
||||
with self._lock:
|
||||
current = self._holder
|
||||
if current is None or not token or not secrets.compare_digest(current.token, token):
|
||||
raise Lost(current if self._live(current) else None)
|
||||
current.last_seen = self._clock()
|
||||
return current
|
||||
|
||||
def heartbeat(self, token: str | None, batch: str | None) -> Holder:
|
||||
holder = self.check(token)
|
||||
holder.batch = batch
|
||||
return holder
|
||||
|
||||
def release(self, token: str | None) -> None:
|
||||
with self._lock:
|
||||
current = self._holder
|
||||
if current is not None and token and secrets.compare_digest(current.token, token):
|
||||
self._holder = None
|
||||
|
||||
def touch(self, holder: Holder) -> None:
|
||||
"""Record that `holder` made an edit — whose the unsaved ones are."""
|
||||
self.last_editor = {"client_id": holder.client_id, "machine": holder.machine}
|
||||
|
||||
def clear_editor(self) -> None:
|
||||
"""After a save or discard, nobody's edits are pending."""
|
||||
self.last_editor = None
|
||||
@@ -0,0 +1,70 @@
|
||||
"""The app-level bookkeeping around ONE open library, wherever it is kept.
|
||||
|
||||
Version history belongs to the app, not the adapter (see `app_state.py`), and
|
||||
until a library could live on a server it could only mean one thing: a git repo
|
||||
in this computer's app-data, keyed by the library's local path. A library held
|
||||
by a server is versioned THERE, beside the file it describes — so the open
|
||||
library carries the services that know where its history lives, and the routes
|
||||
ask them rather than the history module directly.
|
||||
|
||||
`LocalServices` is the whole of what used to be inline: nothing about a library
|
||||
on this computer changes. The remote implementation lives with the remote
|
||||
adapter (`adapters/remote/services.py`).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Protocol
|
||||
|
||||
from . import __version__, history
|
||||
from .core import registry
|
||||
|
||||
|
||||
class LibraryServices(Protocol):
|
||||
#: Whether this library is held by a server (its history lives there).
|
||||
remote: bool
|
||||
|
||||
def baseline(self) -> None: ...
|
||||
def commit_save(self, adapter, outcome) -> str | None: ...
|
||||
def history(self) -> list[history.HistoryEntry]: ...
|
||||
def restore(self, commit_id: str) -> bool: ...
|
||||
def clear_history(self) -> None: ...
|
||||
|
||||
|
||||
class LocalServices:
|
||||
"""History in this computer's app-data, keyed by the library's path."""
|
||||
|
||||
remote = False
|
||||
|
||||
def __init__(self, path: Path):
|
||||
self.path = path
|
||||
|
||||
def baseline(self) -> None:
|
||||
# An "as I found it" version (deduped, so re-opening an unchanged
|
||||
# library is a no-op). Best-effort.
|
||||
history.ensure_baseline(self.path)
|
||||
|
||||
def commit_save(self, adapter, outcome) -> str | None:
|
||||
# Not every platform is versioned. A library that is more than one file
|
||||
# has no single blob that IS the library, and it says so through its
|
||||
# capabilities rather than this module knowing which platforms those are.
|
||||
if adapter.capabilities().save.history and outcome.snapshot is not None:
|
||||
return history.commit(self.path, outcome.snapshot, outcome.summary, __version__)
|
||||
return None
|
||||
|
||||
def history(self) -> list[history.HistoryEntry]:
|
||||
return history.list_history(self.path)
|
||||
|
||||
def restore(self, commit_id: str) -> bool:
|
||||
"""Write a past version back as a NEW forward save. False if unknown.
|
||||
The caller reopens the library afterwards."""
|
||||
data = history.read_version(self.path, commit_id)
|
||||
if data is None:
|
||||
return False
|
||||
# The adapter's driver owns writing its own format back, even for a restore.
|
||||
registry.driver_for(self.path).restore(self.path, data)
|
||||
history.commit(self.path, data, f"Restored version {commit_id[:8]}", __version__)
|
||||
return True
|
||||
|
||||
def clear_history(self) -> None:
|
||||
history.clear_history(self.path)
|
||||
@@ -0,0 +1,216 @@
|
||||
"""Convert to Stems on a library held by a Konduktor server.
|
||||
|
||||
The same batch as `convert.py`, split where the machines split:
|
||||
|
||||
* **The server plans** — where each stem file goes, what is skipped and why,
|
||||
whether its disk has room — because the files and the library are there.
|
||||
* **This computer separates.** The server never decodes audio, so each source
|
||||
is downloaded into the shared cache (`adapters/remote/cache.py`), separated
|
||||
and encoded here with the local engine, verified, and UPLOADED. The server
|
||||
keeps each upload as a verified leftover until the end step, so a batch
|
||||
interrupted by a takeover loses no separation: the next run reuses it.
|
||||
* **The server swaps.** One end step there — publish, park the original
|
||||
(Replace), swap every entry at once — under its own mutation lock, with its
|
||||
own ledger, which its Save commits and its Discard restores.
|
||||
|
||||
Cancel deletes what this run uploaded, as a local cancel deletes what it wrote.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import shutil
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from ..core import stem_file as sf
|
||||
from ..core.adapter import AdapterError
|
||||
from ..importer import SPACE_HEADROOM
|
||||
from . import convert
|
||||
from . import engine_manager as em
|
||||
from .engine_process import EngineCancelled, EngineProcess, keep_awake
|
||||
|
||||
#: Before this computer has measured a download, a conservative LAN speed.
|
||||
DEFAULT_SPEED = 20 * 1024 ** 2 # bytes / s
|
||||
|
||||
|
||||
def options_body(opts: convert.Options) -> dict:
|
||||
return {
|
||||
"mode": opts.mode,
|
||||
"destination": str(opts.destination) if opts.destination else None,
|
||||
"collection": opts.collection,
|
||||
"playlist_id": opts.playlist_id,
|
||||
"new_playlist": opts.new_playlist,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class RemotePlan:
|
||||
server: dict
|
||||
items: list[dict] = field(default_factory=list)
|
||||
blocked: str | None = None
|
||||
#: Bytes to download (sources this computer has no copy of) and upload.
|
||||
download: int = 0
|
||||
upload: int = 0
|
||||
speed: float | None = None
|
||||
space: list[dict] = field(default_factory=list)
|
||||
|
||||
def as_dict(self) -> dict:
|
||||
out = dict(self.server)
|
||||
out.pop("items", None)
|
||||
out["blocked"] = self.blocked
|
||||
out["space"] = self.space
|
||||
out["transfer"] = {"download": self.download, "upload": self.upload,
|
||||
"speed": self.speed or DEFAULT_SPEED, "measured": self.speed is not None}
|
||||
return out
|
||||
|
||||
|
||||
def plan(adapter, track_ids: list[str], opts: convert.Options) -> RemotePlan:
|
||||
"""The server's plan, plus what only this computer can answer: how much it
|
||||
must download and upload, and whether its cache and work folder have room."""
|
||||
from ..importer import free_bytes
|
||||
|
||||
try:
|
||||
server = adapter.stems_plan({"track_ids": list(track_ids), **options_body(opts)})
|
||||
except AdapterError as ex:
|
||||
raise convert.ConvertError(str(ex))
|
||||
items = list(server.get("items") or [])
|
||||
result = RemotePlan(server=server, items=items, blocked=server.get("blocked"))
|
||||
to_separate = [i for i in items if i.get("reuse") is None]
|
||||
# Server volumes, named as the server's.
|
||||
result.space = [{**e, "volume": f"the server ({e.get('volume')})"} for e in server.get("space") or []]
|
||||
result.download = sum(int(i.get("source_size") or 0) for i in to_separate
|
||||
if adapter.cached_audio(i["track_id"]) is None)
|
||||
result.upload = int(server.get("bytes") or 0)
|
||||
result.speed = adapter.cache.speed()
|
||||
if to_separate:
|
||||
biggest = max(float(i.get("seconds") or 0) for i in to_separate) * convert._WORK_BYTES_PER_SECOND
|
||||
work = convert.work_root()
|
||||
work_free = free_bytes(work)
|
||||
cache_usage = adapter.cache.usage()
|
||||
# Downloads land in the cache and the stem file is written in the work
|
||||
# folder before it is uploaded — both on THIS computer's disk.
|
||||
need_here = biggest + max((int(i.get("source_size") or 0) for i in to_separate), default=0)
|
||||
result.space.append({"volume": "this computer", "folder": str(work), "bytes": int(need_here),
|
||||
"free": work_free})
|
||||
if result.blocked is None and work_free is not None and need_here + SPACE_HEADROOM > work_free:
|
||||
result.blocked = (f"Not enough space on this computer: about {need_here / 1e9:.1f} GB is needed "
|
||||
f"while a track is downloaded and converted, {work_free / 1e9:.1f} GB is free")
|
||||
if result.blocked is None and cache_usage["free"] and result.download > cache_usage["free"]:
|
||||
result.blocked = "Not enough space on this computer for the downloads"
|
||||
return result
|
||||
|
||||
|
||||
def run(handle, adapter, planned: RemotePlan, opts: convert.Options, *, still_current,
|
||||
manager: em.EngineManager | None = None) -> dict:
|
||||
mgr = manager or em.default_manager()
|
||||
result = {"converted": [], "renamed": {}, "added": {}, "skipped": list(planned.server.get("skipped") or []),
|
||||
"failed": [], "clamped": {}, "cancelled": False}
|
||||
items = planned.items
|
||||
handle.progress(done=0, total=len(items), unit="tracks", message="Starting the stem engine…")
|
||||
work = convert.work_root() / f"remote-batch-{id(handle):x}"
|
||||
work.mkdir(parents=True, exist_ok=True)
|
||||
staged: list[dict] = []
|
||||
uploaded: list[str] = [] # targets THIS run uploaded (a cancel deletes them)
|
||||
if any(i.get("reuse") is None for i in items) and not mgr.ready():
|
||||
raise convert.ConvertError("The stem engine is not installed")
|
||||
|
||||
def checkpoint() -> None:
|
||||
if handle.cancelled:
|
||||
raise convert._Cancel()
|
||||
|
||||
with contextlib.ExitStack() as stack:
|
||||
engine: EngineProcess | None = None
|
||||
try:
|
||||
for n, item in enumerate(items):
|
||||
checkpoint()
|
||||
handle.progress(done=n, message=item["title"], fraction=0.0, status="")
|
||||
if item.get("reuse") is not None:
|
||||
staged.append(item) # already on the server, verified
|
||||
continue
|
||||
size = max(int(item.get("source_size") or 0), 1)
|
||||
got = 0
|
||||
|
||||
def downloaded(k: int) -> None:
|
||||
nonlocal got
|
||||
got += k
|
||||
checkpoint()
|
||||
f = min(got / size, 1.0) * 0.05
|
||||
handle.progress(fraction=f, status=f"downloading {f * 100:.0f} %")
|
||||
|
||||
local = adapter.audio_path(item["track_id"], progress=downloaded)
|
||||
if local is None:
|
||||
result["failed"].append({"track_id": item["track_id"], "title": item["title"],
|
||||
"reason": "the file is missing on the server"})
|
||||
continue
|
||||
if engine is None:
|
||||
handle.progress(status="starting…")
|
||||
engine = stack.enter_context(EngineProcess(mgr.executable(), mgr.weights_dir(), device=opts.device))
|
||||
stack.enter_context(keep_awake(engine.proc.pid))
|
||||
|
||||
def on_progress(f: float) -> None:
|
||||
frac = 0.05 + f * 0.80
|
||||
handle.progress(fraction=frac, status=f"separating {frac * 100:.0f} %")
|
||||
|
||||
def separate(pcm):
|
||||
handle.progress(fraction=0.05, status="separating 5 %")
|
||||
stems = engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled)
|
||||
handle.progress(fraction=0.85, status="encoding 85 %")
|
||||
return stems
|
||||
|
||||
partial = work / f"{n}.stem.m4a"
|
||||
try:
|
||||
written = sf.build(local, partial, separate, checkpoint=checkpoint)
|
||||
except (convert._Cancel, EngineCancelled):
|
||||
partial.unlink(missing_ok=True)
|
||||
raise
|
||||
except Exception as ex: # noqa: BLE001 — one track's failure is reported, not fatal
|
||||
partial.unlink(missing_ok=True)
|
||||
result["failed"].append({"track_id": item["track_id"], "title": item["title"],
|
||||
"reason": str(ex) or type(ex).__name__})
|
||||
if isinstance(ex, em.EngineError) and engine.proc.poll() is not None:
|
||||
engine = None
|
||||
continue
|
||||
sent = 0
|
||||
|
||||
def uploading(k: int) -> None:
|
||||
nonlocal sent
|
||||
sent += k
|
||||
checkpoint()
|
||||
f = 0.9 + min(sent / max(written.size, 1), 1.0) * 0.1
|
||||
handle.progress(fraction=f, status=f"uploading {f * 100:.0f} %")
|
||||
|
||||
try:
|
||||
adapter.stage_stem(item["track_id"], item["target"], partial, bit_rate=written.bit_rate,
|
||||
duration=written.duration, progress=uploading)
|
||||
finally:
|
||||
partial.unlink(missing_ok=True)
|
||||
uploaded.append(item["target"])
|
||||
staged.append(item)
|
||||
except (convert._Cancel, EngineCancelled):
|
||||
# Cancel = delete what this run uploaded; nothing else was touched.
|
||||
# (If another computer took over, this is refused — and the uploads
|
||||
# stay as verified leftovers the next run reuses, as decided.)
|
||||
with contextlib.suppress(AdapterError):
|
||||
if uploaded:
|
||||
adapter.abandon_stems(uploaded)
|
||||
result["cancelled"] = True
|
||||
return result
|
||||
finally:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
|
||||
if not staged:
|
||||
return result
|
||||
if not still_current():
|
||||
with contextlib.suppress(AdapterError):
|
||||
adapter.abandon_stems(uploaded)
|
||||
raise convert.ConvertError("The library changed while converting; nothing was swapped in")
|
||||
handle.progress(done=len(items), message="Swapping the converted tracks in on the server…", status="")
|
||||
swapped = adapter.publish_stems([{"track_id": i["track_id"], "target": i["target"]} for i in staged],
|
||||
options_body(opts))
|
||||
for key in ("converted", "renamed", "added", "clamped"):
|
||||
if key in swapped:
|
||||
result[key] = swapped[key]
|
||||
result["failed"] += swapped.get("failed") or []
|
||||
if swapped.get("playlist_missing"):
|
||||
result["playlist_missing"] = True
|
||||
return result
|
||||
@@ -0,0 +1,18 @@
|
||||
# The Konduktor SERVER (a container on the user's NAS — see server/Dockerfile).
|
||||
#
|
||||
# Deliberately NOT requirements.txt: the server never DECODES audio (analysis,
|
||||
# waveforms and stem separation run on the computer that opened the library),
|
||||
# so librosa, scikit-learn and PyAV stay out of the image. What it does is file
|
||||
# IO, the native model, tags and header reads. `test_layering.py` checks that
|
||||
# importing `konduktor.server` pulls none of them in.
|
||||
fastapi>=0.115
|
||||
uvicorn[standard]>=0.34
|
||||
pydantic>=2.11
|
||||
mutagen>=1.47 # tags written into the audio files at Save
|
||||
numpy>=2.0 # a prepared analysis arrives as arrays (Rekordbox's ANLZ writer)
|
||||
Pillow>=11 # a Rekordbox add writes the cover's artwork files
|
||||
dulwich>=0.22 # version history, beside the library
|
||||
platformdirs>=4.0
|
||||
# From GitHub, NOT PyPI — see requirements.txt for why.
|
||||
traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git
|
||||
pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git
|
||||
@@ -34,3 +34,8 @@ pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git
|
||||
# The stem engine and its weights are downloaded over HTTPS by the sidecar; a
|
||||
# frozen Python on macOS has no system CA bundle of its own.
|
||||
certifi>=2024.7
|
||||
# Remote libraries (a Konduktor server on the user's NAS): the HTTP client the
|
||||
# remote adapter speaks to it with, and the OS keychain (macOS Keychain /
|
||||
# Windows Credential Manager) its password is kept in — never userprefs.json.
|
||||
httpx>=0.27
|
||||
keyring>=25
|
||||
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
|
||||
source .venv/bin/activate
|
||||
|
||||
fail=0
|
||||
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_key_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_prefs.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py test_discard.py; do
|
||||
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_key_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_prefs.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py test_discard.py test_remote_protocol.py test_remote_server.py test_remote_adapter.py test_remote_stems.py; do
|
||||
echo "──────────────────────────────────────────"
|
||||
echo "▶ $t"
|
||||
echo "──────────────────────────────────────────"
|
||||
|
||||
@@ -34,9 +34,24 @@ def _watch_parent_and_exit() -> None:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
_release_remote()
|
||||
os._exit(0)
|
||||
|
||||
|
||||
def _release_remote() -> None:
|
||||
"""Hand back a remote library's session on the way out, so the next
|
||||
computer opens it at once instead of waiting out the lease (or being asked
|
||||
to take over a laptop that has already quit). Best-effort and brief."""
|
||||
try:
|
||||
from konduktor.app_state import STATE
|
||||
|
||||
if STATE.remote is not None:
|
||||
STATE.remote.stop()
|
||||
STATE.remote.client.release(timeout=2.0)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _free_port() -> int:
|
||||
"""Grab an unused loopback port. There's a tiny bind→close→rebind race, but
|
||||
it's harmless on 127.0.0.1 for a single local sidecar."""
|
||||
|
||||
@@ -95,5 +95,40 @@ for platform, module in NATIVE.items():
|
||||
]
|
||||
check(f"the {platform} adapter does import {module} somewhere", bool(own), "nowhere")
|
||||
|
||||
print("== remote libraries ==")
|
||||
# The remote adapter speaks a PROTOCOL; which platform the server holds is the
|
||||
# server's business. Importing a platform's adapter (or its library) here would
|
||||
# make a remote library quietly platform-shaped again.
|
||||
remote_pkg = CORE.parent / "adapters" / "remote"
|
||||
strays = []
|
||||
for src in sorted(remote_pkg.rglob("*.py")):
|
||||
tree = ast.parse(src.read_text())
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.ImportFrom):
|
||||
mod = node.module or ""
|
||||
if node.level and any(mod == p or mod.startswith(p + ".") for p in NATIVE):
|
||||
strays.append(f"{src.name}: ..{mod}")
|
||||
if not node.level and any(mod.startswith(m) for m in set(NATIVE.values())):
|
||||
strays.append(f"{src.name}: {mod}")
|
||||
elif isinstance(node, ast.Import):
|
||||
for a in node.names:
|
||||
if any(a.name.startswith(m) for m in set(NATIVE.values())):
|
||||
strays.append(f"{src.name}: {a.name}")
|
||||
check("the remote adapter imports no platform adapter or library", not strays, "; ".join(strays))
|
||||
|
||||
# The server is lightweight by decision: it never decodes audio, so importing
|
||||
# it must not pull in the analysis stack (and its image ships without it).
|
||||
import subprocess
|
||||
|
||||
probe = subprocess.run(
|
||||
[sys.executable, "-c",
|
||||
"import sys, konduktor.server.app; "
|
||||
"print(','.join(m for m in ('librosa', 'sklearn', 'torch', 'numba', 'av') if m in sys.modules))"],
|
||||
capture_output=True, text=True, cwd=str(CORE.parents[1]),
|
||||
)
|
||||
heavy = probe.stdout.strip()
|
||||
check("the server imports no audio-analysis library", probe.returncode == 0 and not heavy,
|
||||
heavy or probe.stderr[-300:])
|
||||
|
||||
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -36,13 +36,19 @@ def check(label, cond, detail=""):
|
||||
failed = True
|
||||
|
||||
|
||||
opts = platforms()
|
||||
everything = platforms()
|
||||
# A remote library is offered LAST, after every platform on this computer: it is
|
||||
# a way to reach a library (held by a Konduktor server), not a driver here.
|
||||
opts = [p for p in everything if p.platform != "remote"]
|
||||
by_name = {p.platform: p for p in opts}
|
||||
|
||||
print("== /api/platforms reports the facts the platform step needs ==")
|
||||
check("every registered driver is offered", len(opts) == len(registry.drivers()),
|
||||
f"{len(opts)} of {len(registry.drivers())}")
|
||||
check("all three platforms present", {"traktor", "rekordbox", "onelibrary"} <= set(by_name))
|
||||
check("Remote is offered once, after them, as a remote",
|
||||
[p.platform for p in everything].count("remote") == 1 and everything[-1].platform == "remote"
|
||||
and everything[-1].selects == "remote")
|
||||
check("selects is per-platform, not assumed",
|
||||
by_name["traktor"].selects == "file"
|
||||
and by_name["rekordbox"].selects == "file"
|
||||
@@ -61,7 +67,7 @@ check("ordered fixed-location first, then by name",
|
||||
[p.platform for p in opts] == [p.platform for p in
|
||||
sorted(opts, key=lambda o: (o.removable, o.name.lower()))],
|
||||
[p.platform for p in opts])
|
||||
check("a second call gives the same order", [p.platform for p in platforms()] == [p.platform for p in opts])
|
||||
check("a second call gives the same order", [p.platform for p in platforms()] == [p.platform for p in everything])
|
||||
|
||||
print("== /api/library/options is scoped to ONE platform ==")
|
||||
for plat in ("traktor", "rekordbox", "onelibrary"):
|
||||
|
||||
@@ -0,0 +1,342 @@
|
||||
"""A remote library, end to end: a real server, the app's own routes.
|
||||
|
||||
A Konduktor server (`konduktor.server`) runs in a thread on a temp copy of the
|
||||
real collection, its audio mapped onto generated MP3s; the app (`main.py`)
|
||||
opens it through the picker's routes, exactly as the desktop app would. Pins:
|
||||
|
||||
* a remote is saved only after a handshake — a wrong password is refused with
|
||||
nothing saved, and an unreachable PRIMARY falls back to the fallback;
|
||||
* the remote is offered as a platform, and opens as THE library: projection,
|
||||
capabilities (destination on the library, no reference, no remapping);
|
||||
* edits go to the server and come back in the mirror; Save writes on the
|
||||
server and touches only the edited ENTRY (the fidelity guarantee survives
|
||||
the trip); a no-op save writes nothing; history lists the server's
|
||||
versions; discard drops edits there;
|
||||
* audio is downloaded once into the cache, by what the server says the file
|
||||
is; analysis (Analyze grid) runs here on that copy and lands on the server;
|
||||
* another computer taking over makes this one read-only — at the next
|
||||
command, not the next heartbeat — and reopening says who holds it, offers
|
||||
the takeover and names the edits left behind;
|
||||
* export sets are kept by the server, and an export from the remote library
|
||||
copies the audio, then re-exports copying nothing;
|
||||
* importing a file UPLOADS it into a folder on the server and adds it there;
|
||||
* opening a local library releases the server's session.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-remote-appdata-")
|
||||
os.environ.pop("KONDUKTOR_NML", None)
|
||||
|
||||
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
|
||||
failed = False
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
global failed
|
||||
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
|
||||
if not cond:
|
||||
failed = True
|
||||
|
||||
|
||||
import uvicorn
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from konduktor import history
|
||||
from konduktor import remote_protocol as rp
|
||||
from konduktor.adapters.remote import config as remote_config
|
||||
from konduktor.adapters.remote.client import RemoteClient
|
||||
from konduktor.adapters.traktor.adapter import TraktorAdapter
|
||||
from konduktor.app_state import AppState
|
||||
from konduktor.core.pathmap import PathMapping
|
||||
from konduktor.server.app import Server, create_app
|
||||
from konduktor.server.config import ServerConfig
|
||||
from konduktor.server.session import SessionLock
|
||||
from stem_test_support import make_mp3
|
||||
|
||||
|
||||
class MemoryKeychain:
|
||||
def __init__(self):
|
||||
self.items = {}
|
||||
|
||||
def get(self, account):
|
||||
return self.items.get(account)
|
||||
|
||||
def set(self, account, password):
|
||||
self.items[account] = password
|
||||
|
||||
def delete(self, account):
|
||||
self.items.pop(account, None)
|
||||
|
||||
|
||||
remote_config.use_password_store(MemoryKeychain())
|
||||
|
||||
|
||||
def serve(app):
|
||||
server = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=0, log_level="warning"))
|
||||
thread = threading.Thread(target=server.run, daemon=True)
|
||||
thread.start()
|
||||
for _ in range(200):
|
||||
if server.started:
|
||||
break
|
||||
time.sleep(0.05)
|
||||
return server, server.servers[0].sockets[0].getsockname()[1]
|
||||
|
||||
|
||||
def entry_span(data: bytes, file_name: str):
|
||||
marker = f'FILE="{file_name}"'.encode()
|
||||
i = data.find(marker)
|
||||
return data.rfind(b"<ENTRY ", 0, i), data.find(b"</ENTRY>", i) + len(b"</ENTRY>")
|
||||
|
||||
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
root = Path(d)
|
||||
work = root / "library" / "collection.nml"
|
||||
work.parent.mkdir()
|
||||
shutil.copy2(REAL, work)
|
||||
content = (root / "music").resolve()
|
||||
content.mkdir()
|
||||
|
||||
# Map one folder of the collection onto generated audio on the "server".
|
||||
probe = TraktorAdapter(work)
|
||||
by_dir: dict[Path, list[str]] = {}
|
||||
for t in probe.tracks:
|
||||
p = probe.audio_path(t.id)
|
||||
if p is not None and p.suffix.lower() == ".mp3":
|
||||
by_dir.setdefault(p.parent, []).append(t.id)
|
||||
folder, ids = max(by_dir.items(), key=lambda kv: len(kv[1]))
|
||||
ids = ids[:3]
|
||||
mapped = content / "Mapped"
|
||||
for n, tid in enumerate(ids):
|
||||
make_mp3(mapped / probe.audio_path(tid).name, seconds=4, seed=n + 1)
|
||||
probe_paths = {tid: probe.audio_path(tid) for tid in ids}
|
||||
del probe
|
||||
|
||||
t = [1000.0]
|
||||
cfg = ServerConfig(platform="traktor", library=work, content=content, username="dj",
|
||||
password="secret", name="NAS",
|
||||
path_maps=(PathMapping.make(str(folder), str(mapped)),))
|
||||
srv = Server(cfg, state=AppState(), lock=SessionLock(clock=lambda: t[0]))
|
||||
srv.open()
|
||||
uv, port = serve(create_app(srv))
|
||||
server_adapter = srv.state.adapter
|
||||
|
||||
import konduktor.main as main
|
||||
|
||||
c = TestClient(main.app)
|
||||
print("== saving a remote ==")
|
||||
form = {"name": "NAS", "host": "127.0.0.1:1", "fallback_host": f"127.0.0.1:{port}",
|
||||
"username": "dj", "password": "wrong"}
|
||||
r = c.post("/api/remotes", json=form)
|
||||
check("a wrong password is refused, nothing saved",
|
||||
r.status_code == 400 and "password" in r.json()["detail"]["message"].lower()
|
||||
and c.get("/api/remotes").json() == [], r.text[:200])
|
||||
form["password"] = "secret"
|
||||
r = c.post("/api/remotes", json=form)
|
||||
body = r.json()
|
||||
check("the right one saves, reporting each address",
|
||||
r.status_code == 200 and [x["kind"] for x in body["results"]] == ["unreachable", "ok"], r.text[:300])
|
||||
remote_id = body["remote"]["id"]
|
||||
check("the password is in the keychain, not prefs",
|
||||
"secret" not in Path(os.environ["KONDUKTOR_DATA_DIR"], "userprefs.json").read_text())
|
||||
plats = c.get("/api/platforms").json()
|
||||
check("Remote is offered as a platform, last", plats[-1]["platform"] == "remote"
|
||||
and plats[-1]["found"] == 1 and plats[-1]["selects"] == "remote")
|
||||
|
||||
print("== opening it ==")
|
||||
r = c.post("/api/library/open-remote", json={"remote_id": remote_id})
|
||||
status = r.json()
|
||||
check("it opens as THE library", r.status_code == 200 and status["loaded"]
|
||||
and status["tracks"] == len(server_adapter.tracks), r.text[:300])
|
||||
check("…named as saved, reached through the fallback",
|
||||
status["library"]["display_name"] == "NAS" and status["library"]["remote"]["via"] == "fallback")
|
||||
caps = c.get("/api/capabilities").json()
|
||||
check("its capabilities: the destination is the server's, nothing referenced, nothing remapped",
|
||||
caps["writable"] and caps["tracks"]["audio_destination"] == "library"
|
||||
and not caps["tracks"]["reference"] and not caps["paths"]["remappable"])
|
||||
page = c.get("/api/tracks", params={"limit": 20000}).json()
|
||||
check("the table reads from the mirror", page["total"] == len(server_adapter.tracks))
|
||||
check("the server shows this computer holding the session",
|
||||
srv.lock.describe()["machine"] == remote_config.machine_name())
|
||||
|
||||
print("== edits and saves ==")
|
||||
target = ids[0]
|
||||
file_name = probe_paths[target].name
|
||||
original = work.read_bytes()
|
||||
r = c.patch("/api/tracks", json={"track_id": target, "fields": {"genre": "Remote Edit"}})
|
||||
check("an edit applies on the server", r.status_code == 200
|
||||
and server_adapter.track(target).genre == "Remote Edit")
|
||||
check("…and in the mirror", main.require_adapter().track(target).genre == "Remote Edit")
|
||||
r = c.post("/api/tracks/cue", json={"track_id": target, "slot": 4, "start": 1.0, "type": "cue"})
|
||||
check("a hotcue goes to the server", r.status_code == 200
|
||||
and any(cu["slot"] == 4 for cu in server_adapter.track_cues(target).model_dump()["cues"]), r.text[:200])
|
||||
check("the state says unsaved", c.get("/api/state").json()["dirty"] is True)
|
||||
versions = len(history.list_history(work))
|
||||
r = c.post("/api/save").json()
|
||||
saved = work.read_bytes()
|
||||
check("save writes on the server", r["saved"] and saved != original)
|
||||
s0, e0 = entry_span(original, file_name)
|
||||
s1, e1 = entry_span(saved, file_name)
|
||||
check("…changing nothing outside the edited ENTRY",
|
||||
original[:s0] == saved[:s1] and original[e0:] == saved[e1:])
|
||||
check("…and is versioned there", len(history.list_history(work)) == versions + 1
|
||||
and len(c.get("/api/history").json()) == versions + 1)
|
||||
r = c.post("/api/save").json()
|
||||
check("a no-op save writes nothing", r["saved"] is False and work.read_bytes() == saved)
|
||||
c.patch("/api/tracks", json={"track_id": target, "fields": {"genre": "Throw away"}})
|
||||
r = c.post("/api/discard")
|
||||
check("discard drops the edit on the server", r.status_code == 200 and not server_adapter.dirty
|
||||
and server_adapter.track(target).genre == "Remote Edit"
|
||||
and main.require_adapter().track(target).genre == "Remote Edit", r.text[:200])
|
||||
|
||||
print("== version history, on the server ==")
|
||||
listed = c.get("/api/history").json()
|
||||
oldest = listed[-1]["id"]
|
||||
r = c.post(f"/api/history/{oldest}/restore")
|
||||
check("restoring a version writes it back ON THE SERVER", r.status_code == 200
|
||||
and work.read_bytes() == original, r.text[:200])
|
||||
check("…as a new version", len(c.get("/api/history").json()) == len(listed) + 1)
|
||||
server_adapter = srv.state.adapter # a restore reopens the library there
|
||||
check("…and the mirror follows", main.require_adapter().track(target).genre
|
||||
== server_adapter.track(target).genre)
|
||||
# Back to the edited state, for what follows.
|
||||
c.patch("/api/tracks", json={"track_id": target, "fields": {"genre": "Remote Edit"}})
|
||||
c.post("/api/save")
|
||||
|
||||
print("== audio, on this computer ==")
|
||||
adapter = main.require_adapter()
|
||||
downloads = []
|
||||
real_download = adapter.client.download
|
||||
adapter.client.download = lambda *a, **k: (downloads.append(a[0]), real_download(*a, **k))[1]
|
||||
r = c.get("/api/tracks/audio", params={"track_id": target})
|
||||
served = (mapped / file_name).read_bytes()
|
||||
check("the deck's audio is the server's file", r.status_code == 200 and r.content == served)
|
||||
c.get("/api/tracks/audio", params={"track_id": target})
|
||||
check("…downloaded once, then served from the cache", downloads == [target], downloads)
|
||||
cached = adapter.cached_audio(target)
|
||||
check("the cache keys it by what the server says the file is",
|
||||
cached is not None and cached.read_bytes() == served and cached.suffix == ".mp3")
|
||||
r = c.post("/api/tracks/grid/auto", json={"track_id": target})
|
||||
grid = server_adapter.track_cues(target).grid_markers
|
||||
check("Analyze runs here and the grid lands on the server",
|
||||
r.status_code == 200 and grid and abs(grid[0].bpm - 120) < 1.5, r.text[:200])
|
||||
check("…with no second download", downloads == [target], downloads)
|
||||
c.post("/api/save")
|
||||
|
||||
print("== export, from the server's library ==")
|
||||
dest = root / "stick"
|
||||
r = c.post("/api/exports", json={"name": "Gig", "targets": ["traktor"], "destination": str(dest)})
|
||||
set_id = r.json().get("id")
|
||||
c.post(f"/api/exports/{set_id}/add", json={"track_ids": ids})
|
||||
doc = c.get("/api/exports").json()
|
||||
check("an export set is created", set_id and any(s["id"] == set_id for s in doc), r.text[:300])
|
||||
import httpx
|
||||
|
||||
kept = httpx.get(f"http://127.0.0.1:{port}/v1/export-sets", auth=("dj", "secret")).json()
|
||||
check("…and kept by the server", set_id in kept["sets"], kept)
|
||||
|
||||
def run_export():
|
||||
job = c.post(f"/api/exports/{set_id}/run").json()
|
||||
for _ in range(600):
|
||||
j = c.get(f"/api/jobs/{job['id']}").json()
|
||||
if j["state"] != "running":
|
||||
return j
|
||||
time.sleep(0.05)
|
||||
return j
|
||||
|
||||
downloads.clear()
|
||||
job = run_export()
|
||||
copies = sorted(p for p in (dest / "Contents").rglob("*.mp3"))
|
||||
check("the export copies every track's audio onto the stick",
|
||||
job["state"] == "done" and len(copies) == len(ids), job.get("error"))
|
||||
check("…downloading only what the cache lacked", sorted(downloads) == sorted(ids[1:]), downloads)
|
||||
inodes = {p: p.stat().st_ino for p in copies}
|
||||
downloads.clear()
|
||||
job = run_export()
|
||||
check("a re-export copies nothing", job["state"] == "done"
|
||||
and all(p.stat().st_ino == i for p, i in inodes.items()) and downloads == [], downloads)
|
||||
|
||||
print("== importing: an upload into the server ==")
|
||||
incoming = make_mp3(root / "laptop" / "Brand New.mp3", seconds=3, seed=9)
|
||||
# The folder-add path: a folder of loose files on THIS computer.
|
||||
c.get("/api/folder/tracks", params={"path": str(incoming.parent)}) # the scan the add reads
|
||||
add = {"track_ids": [str(incoming)], "mode": "copy", "destination": str(mapped / "Incoming")}
|
||||
r = c.post("/api/folder/add/preview", json=add)
|
||||
check("(preview) adding a local file to the remote library, space read from the server",
|
||||
r.status_code == 200 and r.json()["free_bytes"], r.text[:300])
|
||||
job = c.post("/api/folder/add", json=add).json()
|
||||
for _ in range(400):
|
||||
j = c.get(f"/api/jobs/{job['id']}").json()
|
||||
if j["state"] != "running":
|
||||
break
|
||||
time.sleep(0.05)
|
||||
landed = mapped / "Incoming" / "Brand New.mp3"
|
||||
check("the file is uploaded into the chosen folder ON THE SERVER",
|
||||
j["state"] == "done" and landed.read_bytes() == incoming.read_bytes(), j.get("error"))
|
||||
added = [tr for tr in server_adapter.tracks if (tr.filepath or "").endswith("Brand New.mp3")]
|
||||
check("…and added to the server's library", len(added) == 1)
|
||||
from konduktor.adapters.traktor.locations import os_path_to_location
|
||||
|
||||
stored = "".join(os_path_to_location(folder / "Incoming" / "Brand New.mp3"))
|
||||
check("…stored as the collection stores every other path (the mapping, inverted)",
|
||||
added and added[0].id == stored, added[0].id if added else None)
|
||||
check("…and still resolving to the uploaded file", added and server_adapter.audio_path(added[0].id) == landed)
|
||||
check("…and to the mirror here", any((tr.filepath or "").endswith("Brand New.mp3")
|
||||
for tr in main.require_adapter().tracks))
|
||||
|
||||
print("== another computer takes over ==")
|
||||
other = RemoteClient(remote_config.Remote(id="o", name="NAS", host=f"127.0.0.1:{port}", username="dj"), "secret")
|
||||
other.acquire("other-client", "Studio iMac", takeover=True)
|
||||
other.rpc("set_track_metadata", track_id=ids[1], fields={"comment": "from the studio"})
|
||||
r = c.patch("/api/tracks", json={"track_id": target, "fields": {"genre": "Too late"}})
|
||||
check("this computer's next command is refused, naming who took it",
|
||||
r.status_code == 503 and "Studio iMac" in r.json()["detail"], r.text[:200])
|
||||
st = c.get("/api/state").json()
|
||||
check("…and it is read-only now, at once", st["remote"]["state"] == "taken_over"
|
||||
and st["remote"]["machine"] == "Studio iMac")
|
||||
caps = c.get("/api/capabilities").json()
|
||||
check("…through its capabilities", not caps["writable"] and caps["readonly_cause"] == "taken_over")
|
||||
check("the server still has the genre this computer saved", server_adapter.track(target).genre == "Remote Edit")
|
||||
r = c.post("/api/library/open-remote", json={"remote_id": remote_id})
|
||||
check("reopening says who holds it", r.status_code == 409
|
||||
and r.json()["detail"]["machine"] == "Studio iMac", r.text[:200])
|
||||
r = c.post("/api/library/open-remote", json={"remote_id": remote_id, "takeover": True})
|
||||
pending = r.json().get("pending_edits")
|
||||
check("taking it back names the edits the other computer left",
|
||||
r.status_code == 200 and pending and pending["machine"] == "Studio iMac", r.text[:300])
|
||||
check("…which the mirror shows", main.require_adapter().track(ids[1]).comment == "from the studio")
|
||||
other.close()
|
||||
|
||||
print("== the server forgets the session (a restart) ==")
|
||||
c.post("/api/save") # nobody's edits pending, as after a real restart
|
||||
srv.lock = SessionLock(clock=lambda: t[0])
|
||||
main.STATE.remote.beat()
|
||||
d = c.get("/api/state").json()["remote"]
|
||||
h = srv.lock.holder()
|
||||
check("the session is taken back without asking, and the user told",
|
||||
d["state"] == "connected" and d["notices"] == 1 and d["notice"]
|
||||
and h is not None and h.machine == remote_config.machine_name(), d)
|
||||
r = c.patch("/api/tracks", json={"track_id": target, "fields": {"comment": "after restart"}})
|
||||
check("…and edits go through again", r.status_code == 200
|
||||
and server_adapter.track(target).comment == "after restart", r.text[:200])
|
||||
|
||||
print("== leaving ==")
|
||||
local = root / "local.nml"
|
||||
shutil.copy2(REAL, local)
|
||||
r = c.post("/api/library/open", json={"path": str(local)})
|
||||
check("opening a local library releases the server's session",
|
||||
r.status_code == 200 and srv.lock.holder() is None, r.text[:200])
|
||||
uv.should_exit = True
|
||||
|
||||
print()
|
||||
print("RESULT:", "FAILURES" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -0,0 +1,133 @@
|
||||
"""The wire contract between a Konduktor server and the app (`remote_protocol.py`).
|
||||
|
||||
Pure: no library, no network. Pins what would go wrong SILENTLY:
|
||||
|
||||
* every member of `LibraryAdapter` is either an RPC or excluded with a reason
|
||||
— a command added to the protocol later cannot be quietly missing from
|
||||
remote libraries (the remote adapter would raise AttributeError mid-edit);
|
||||
* every command is MUTATING — one that was not would skip the session check,
|
||||
letting a displaced computer keep editing;
|
||||
* arguments and results survive JSON by the protocol's own types (tuples,
|
||||
dataclasses, pydantic models, `None`), and a misspelt argument is refused;
|
||||
* a prepared analysis (waveform, grid, key) crosses intact;
|
||||
* the version rule: same major, server minor ≥ client's.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import warnings
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
failed = False
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
global failed
|
||||
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
|
||||
if not cond:
|
||||
failed = True
|
||||
|
||||
|
||||
import numpy as np
|
||||
|
||||
from konduktor import remote_protocol as rp
|
||||
from konduktor.core import waveform
|
||||
from konduktor.core.adapter import AudioFacts, PreparedAnalysis
|
||||
from konduktor.core.model import AutoHotcue, GridMarker, Track, TrackCues
|
||||
|
||||
print("== coverage ==")
|
||||
members = rp.protocol_members()
|
||||
missing = members - set(rp.RPC) - set(rp.EXCLUDED)
|
||||
check("every protocol member is an RPC or excluded", not missing, sorted(missing))
|
||||
stray = (set(rp.RPC) | set(rp.EXCLUDED)) - members
|
||||
check("…and nothing is listed that the protocol lacks", not stray, sorted(stray))
|
||||
check("no member is both", not (set(rp.RPC) & set(rp.EXCLUDED)))
|
||||
check("every exclusion says why", all(len(r) > 10 for r in rp.EXCLUDED.values()))
|
||||
VERBS = ("set_", "create_", "delete_", "rename_", "add_", "remove_", "move_", "replace_", "place_", "apply_")
|
||||
commands = {m for m in members if m.startswith(VERBS)}
|
||||
unguarded = {m for m in commands if m in rp.RPC and not rp.RPC[m].mutating}
|
||||
check("every command that travels needs the session", not unguarded, sorted(unguarded))
|
||||
reads = {"tracks", "track", "track_cues", "query_tracks", "capabilities", "audio_facts", "dirty"}
|
||||
check("reads do not", all(not rp.RPC[m].mutating for m in reads))
|
||||
for name in rp.RPC:
|
||||
try:
|
||||
rp._params(name)
|
||||
rp._adapter(rp._result_hint(name))
|
||||
except Exception as ex: # noqa: BLE001
|
||||
check(f"{name}: types resolve", False, repr(ex))
|
||||
|
||||
print("== round trips ==")
|
||||
|
||||
|
||||
def through_json(name, args):
|
||||
wire = json.loads(json.dumps({"args": rp.dump_args(name, args)}))
|
||||
return rp.load_args(name, wire["args"])
|
||||
|
||||
|
||||
got = through_json("set_cue", {"track_id": "a", "slot": 2, "start_sec": 1.5, "cue_type": "loop",
|
||||
"length_sec": 4.0, "name": None})
|
||||
check("set_cue's arguments survive", got == {"track_id": "a", "slot": 2, "start_sec": 1.5,
|
||||
"cue_type": "loop", "length_sec": 4.0, "name": None}, got)
|
||||
got = through_json("replace_grid", {"track_id": "a", "markers": [(0.1, 128.0), (60.0, 130.0)]})
|
||||
check("a grid's (start, bpm) tuples survive", got["markers"] == [(0.1, 128.0), (60.0, 130.0)], got)
|
||||
cue = AutoHotcue(slot=1, start=12.0, name="Drop")
|
||||
got = through_json("place_cues", {"track_id": "a", "cues": [cue], "overwrite": True})
|
||||
check("place_cues gets AutoHotcue objects back", isinstance(got["cues"][0], AutoHotcue)
|
||||
and got["cues"][0].start == 12.0 and got["overwrite"] is True, got)
|
||||
got = through_json("query_tracks", {"q": "acid", "bpm_min": 120.0, "limit": 5})
|
||||
check("query_tracks' keywords survive", got == {"q": "acid", "bpm_min": 120.0, "limit": 5}, got)
|
||||
try:
|
||||
rp.load_args("track", {"track_id": "a", "trak_id": "b"})
|
||||
check("a misspelt argument is refused", False)
|
||||
except ValueError:
|
||||
check("a misspelt argument is refused", True)
|
||||
try:
|
||||
rp.load_args("set_cue", {"track_id": "a"})
|
||||
check("a missing argument is refused", False)
|
||||
except ValueError:
|
||||
check("a missing argument is refused", True)
|
||||
|
||||
facts = {"t1": AudioFacts(key="/music/a.mp3", size=10, mtime_ns=123)}
|
||||
back = rp.load_result("audio_facts", json.loads(json.dumps(rp.dump_result("audio_facts", facts))))
|
||||
check("audio facts survive as dataclasses", back == facts, back)
|
||||
cues = TrackCues(track_id="t1", grid_markers=[GridMarker(start=0.1, bpm=128)])
|
||||
back = rp.load_result("track_cues", json.loads(json.dumps(rp.dump_result("track_cues", cues))))
|
||||
check("TrackCues survive", back == cues)
|
||||
check("None survives", rp.load_result("track", rp.dump_result("track", None)) is None)
|
||||
t = Track(id="x", title="T")
|
||||
check("a Track survives", rp.load_result("track", rp.dump_result("track", t)) == t)
|
||||
|
||||
print("== a prepared analysis ==")
|
||||
rng = np.random.default_rng(1)
|
||||
measured = waveform.Analysis(
|
||||
columns=waveform.Columns(rms=rng.random(400).astype(np.float32),
|
||||
brightness=rng.random(400).astype(np.float32), duration=181.5),
|
||||
frames=waveform.Frames(bands=rng.random((27225, 3)).astype(np.float32), duration=181.5),
|
||||
)
|
||||
packed = rp.pack_analysis(PreparedAnalysis(measured=measured, markers=[GridMarker(start=0.25, bpm=124.0)]))
|
||||
back = rp.unpack_analysis(packed)
|
||||
check("columns, frames and durations cross intact",
|
||||
np.array_equal(back.measured.columns.rms, measured.columns.rms)
|
||||
and np.array_equal(back.measured.frames.bands, measured.frames.bands)
|
||||
and back.measured.duration == 181.5)
|
||||
check("…and the detected grid", [(m.start, m.bpm) for m in back.markers] == [(0.25, 124.0)])
|
||||
check("…with no key when none was detected", back.key is None)
|
||||
from konduktor.core.key_detect import KeyResult
|
||||
|
||||
key = KeyResult(pitch_class=9, mode="minor", wheel=8, confidence=0.83)
|
||||
back = rp.unpack_analysis(rp.pack_analysis(PreparedAnalysis(measured=measured, key=key)))
|
||||
check("…and the detected key", back.key == key, back.key)
|
||||
check("no analysis is None", rp.pack_analysis(None) is None and rp.unpack_analysis(None) is None)
|
||||
|
||||
print("== versions ==")
|
||||
check("same version talks", rp.compatible((1, 0), (1, 0)) is None)
|
||||
check("a newer server minor talks", rp.compatible((1, 0), (1, 3)) is None)
|
||||
check("an older server minor: update the server", rp.compatible((1, 2), (1, 1)) == "server")
|
||||
check("a newer server major: update the app", rp.compatible((1, 0), (2, 0)) == "app")
|
||||
check("an older server major: update the server", rp.compatible((2, 0), (1, 9)) == "server")
|
||||
|
||||
print()
|
||||
print("RESULT:", "FAILURES" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -0,0 +1,259 @@
|
||||
"""The Konduktor SERVER (`konduktor.server`), through its own routes.
|
||||
|
||||
A library held on the user's NAS and opened from the desktop app as a "Remote".
|
||||
Run against a temp copy of the real collection, with a FAKE clock for the
|
||||
session lease. Pins the things that would fail quietly or dangerously:
|
||||
|
||||
* every route needs the one account — a wrong password is a 401, not a
|
||||
read-only view;
|
||||
* ONE computer at a time: a command without the session token is refused
|
||||
(423), a second computer is told who holds it (409) and may take over,
|
||||
after which the first one's token is dead; a lease that ran out frees the
|
||||
session, and the SAME computer coming back renews it silently;
|
||||
* the edits a computer leaves behind are offered to the next one, named;
|
||||
* Save writes and versions ON THE SERVER; Discard drops the edits;
|
||||
* the folder browser and uploads cannot leave the content folder (`..`, a
|
||||
symlink), an upload never overwrites, and a session can only delete what
|
||||
it uploaded;
|
||||
* audio streams with Range; a track added from an upload plays.
|
||||
* the configuration refuses a missing password, a wrong platform and a
|
||||
malformed path map with one clear line.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-server-appdata-")
|
||||
os.environ.pop("KONDUKTOR_NML", None)
|
||||
|
||||
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
|
||||
failed = False
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
global failed
|
||||
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
|
||||
if not cond:
|
||||
failed = True
|
||||
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from konduktor import history
|
||||
from konduktor import remote_protocol as rp
|
||||
from konduktor.app_state import AppState
|
||||
from konduktor.server.app import Server, create_app
|
||||
from konduktor.server.config import ConfigError, ServerConfig, from_env, parse_path_maps
|
||||
from konduktor.server.session import SessionLock
|
||||
from stem_test_support import make_mp3
|
||||
|
||||
print("== configuration ==")
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
lib = Path(d) / "collection.nml"
|
||||
lib.write_text("x")
|
||||
content = Path(d) / "music"
|
||||
content.mkdir()
|
||||
base = {"KONDUKTOR_PLATFORM": "traktor", "KONDUKTOR_LIBRARY": str(lib),
|
||||
"KONDUKTOR_CONTENT": str(content), "KONDUKTOR_USERNAME": "dj",
|
||||
"KONDUKTOR_PASSWORD": "pw"}
|
||||
|
||||
def refused(env, needle):
|
||||
try:
|
||||
from_env(env)
|
||||
except ConfigError as ex:
|
||||
return needle in str(ex)
|
||||
return False
|
||||
|
||||
check("a complete environment parses", from_env(base).content == content.resolve())
|
||||
check("an empty password is refused", refused({**base, "KONDUKTOR_PASSWORD": ""}, "PASSWORD"))
|
||||
check("an unknown platform is refused", refused({**base, "KONDUKTOR_PLATFORM": "serato"}, "PLATFORM"))
|
||||
check("a missing content folder is refused",
|
||||
refused({**base, "KONDUKTOR_CONTENT": str(Path(d) / "nope")}, "CONTENT"))
|
||||
check("a malformed path map is refused", refused({**base, "KONDUKTOR_PATH_MAP": "/a -> /b"}, "PATH_MAP"))
|
||||
maps = parse_path_maps("/Users/ben/Music => /music ; X: => /ssd")
|
||||
check("several path maps parse, in order",
|
||||
[(m.from_prefix, m.to_prefix) for m in maps] == [("/Users/ben/Music", "/music"), ("X:", "/ssd")])
|
||||
|
||||
print("== the server ==")
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
work = Path(d) / "library" / "collection.nml"
|
||||
work.parent.mkdir()
|
||||
shutil.copy2(REAL, work)
|
||||
original = work.read_bytes()
|
||||
content = (Path(d) / "music").resolve()
|
||||
content.mkdir()
|
||||
outside = Path(d) / "outside"
|
||||
outside.mkdir()
|
||||
(content / "Sneaky").symlink_to(outside)
|
||||
(content / "Crates").mkdir()
|
||||
|
||||
cfg = ServerConfig(platform="traktor", library=work, content=content,
|
||||
username="dj", password="secret", name="NAS")
|
||||
t = [1000.0]
|
||||
server = Server(cfg, state=AppState(), lock=SessionLock(clock=lambda: t[0]))
|
||||
wrong = ServerConfig(**{**cfg.__dict__, "platform": "rekordbox"})
|
||||
try:
|
||||
Server(wrong, state=AppState()).open()
|
||||
check("a platform that does not match the library file is refused", False)
|
||||
except ConfigError as ex:
|
||||
check("a platform that does not match the library file is refused", "Traktor" in str(ex), str(ex))
|
||||
server.open()
|
||||
app = create_app(server)
|
||||
c = TestClient(app)
|
||||
c.auth = ("dj", "secret")
|
||||
anon = TestClient(app)
|
||||
|
||||
check("no credentials → 401", anon.get("/v1/hello").status_code == 401)
|
||||
check("a wrong password → 401",
|
||||
TestClient(app).get("/v1/hello", auth=("dj", "nope")).status_code == 401)
|
||||
hello = c.get("/v1/hello").json()
|
||||
check("hello names the API version, platform and library",
|
||||
hello["api_version"] == list(rp.API_VERSION) and hello["platform"] == "traktor"
|
||||
and hello["name"] == "NAS" and hello["library_id"], hello)
|
||||
check("…nobody holds it yet, nothing is unsaved",
|
||||
hello["holder"] is None and hello["dirty"] is False and hello["pending_edits"] is None)
|
||||
|
||||
def call(name, token=None, **args):
|
||||
headers = {rp.SESSION_HEADER: token} if token else {}
|
||||
return c.post(f"/v1/rpc/{name}", json={"args": rp.dump_args(name, args)}, headers=headers)
|
||||
|
||||
adapter = server.state.adapter
|
||||
r = call("tracks")
|
||||
check("the projection reads without a session",
|
||||
r.status_code == 200 and len(r.json()["result"]) == len(adapter.tracks))
|
||||
caps = call("capabilities").json()["result"]
|
||||
check("capabilities say: destination on the library, no reference, no remapping",
|
||||
caps["tracks"]["audio_destination"] == "library" and caps["tracks"]["reference"] is False
|
||||
and caps["paths"]["remappable"] is False, caps["tracks"])
|
||||
check("an unknown argument is refused, not ignored",
|
||||
c.post("/v1/rpc/track", json={"args": {"track_id": "x", "trak": 1}}).status_code == 400)
|
||||
track = next(t for t in adapter.tracks if t.genre)
|
||||
r = call("set_track_metadata", track_id=track.id, fields={"genre": "Remote"})
|
||||
check("a command without the session → 423", r.status_code == 423, r.text[:120])
|
||||
|
||||
print("== one computer at a time ==")
|
||||
a = c.post("/v1/session/acquire", json={"client_id": "A", "machine": "Laptop"}).json()
|
||||
r = c.post("/v1/session/acquire", json={"client_id": "B", "machine": "Studio"})
|
||||
check("a second computer is told who holds it",
|
||||
r.status_code == 409 and r.json()["detail"]["machine"] == "Laptop", r.text[:160])
|
||||
r = call("set_track_metadata", a["token"], track_id=track.id, fields={"genre": "Remote"})
|
||||
body = r.json()
|
||||
check("the holder's command applies and returns the changed track",
|
||||
r.status_code == 200 and body["changed"][0]["genre"] == "Remote" and body["rev"] == 1, r.text[:200])
|
||||
pending = c.get("/v1/hello", params={"client_id": "B"}).json()["pending_edits"]
|
||||
check("another computer is told whose unsaved edits these are",
|
||||
pending and pending["machine"] == "Laptop" and "track" in pending["summary"], pending)
|
||||
check("…but the computer that made them is not",
|
||||
c.get("/v1/hello", params={"client_id": "A"}).json()["pending_edits"] is None)
|
||||
b = c.post("/v1/session/acquire", json={"client_id": "B", "machine": "Studio", "takeover": True}).json()
|
||||
check("a takeover hands over the edits too", b["pending_edits"]["machine"] == "Laptop", b)
|
||||
r = call("set_track_metadata", a["token"], track_id=track.id, fields={"genre": "Late"})
|
||||
check("the displaced computer's token is dead (423, naming the new holder)",
|
||||
r.status_code == 423 and r.json()["detail"]["holder"]["machine"] == "Studio", r.text[:160])
|
||||
hb = c.post("/v1/session/heartbeat", json={}, headers={rp.SESSION_HEADER: a["token"]})
|
||||
check("…and its heartbeat says so", hb.status_code == 423)
|
||||
c.post("/v1/session/heartbeat", json={"batch": "grid-analysis"}, headers={rp.SESSION_HEADER: b["token"]})
|
||||
r = c.post("/v1/session/acquire", json={"client_id": "C", "machine": "Phone"})
|
||||
check("the holder's running batch is named to whoever asks",
|
||||
r.status_code == 409 and r.json()["detail"]["batch"] == "grid-analysis", r.text[:160])
|
||||
t[0] += rp.LEASE_SECONDS + 1
|
||||
r = c.post("/v1/session/acquire", json={"client_id": "C", "machine": "Phone"})
|
||||
check("an expired lease frees the session without a takeover", r.status_code == 200, r.text[:160])
|
||||
cc = r.json()
|
||||
t[0] += rp.LEASE_SECONDS * 3
|
||||
hb = c.post("/v1/session/heartbeat", json={}, headers={rp.SESSION_HEADER: cc["token"]})
|
||||
check("the same computer coming back renews its lease silently", hb.status_code == 200, hb.text[:160])
|
||||
tok = cc["token"]
|
||||
|
||||
print("== save / discard / history ==")
|
||||
versions = len(history.list_history(work))
|
||||
r = c.post("/v1/save", headers={rp.SESSION_HEADER: tok}).json()
|
||||
check("save writes the library on the server", r["saved"] and work.read_bytes() != original, r)
|
||||
check("…and versions it there", len(history.list_history(work)) == versions + 1)
|
||||
check("…and nobody's edits are pending afterwards",
|
||||
c.get("/v1/hello", params={"client_id": "Z"}).json()["pending_edits"] is None)
|
||||
saved = work.read_bytes()
|
||||
call("set_track_metadata", tok, track_id=track.id, fields={"genre": "Throw away"})
|
||||
check("(setup) a second edit is unsaved", c.get("/v1/hello").json()["dirty"])
|
||||
c.post("/v1/discard", headers={rp.SESSION_HEADER: tok})
|
||||
check("discard drops it", not c.get("/v1/hello").json()["dirty"]
|
||||
and call("track", track_id=track.id).json()["result"]["genre"] == "Remote")
|
||||
check("…and leaves the file as saved", work.read_bytes() == saved)
|
||||
listed = c.get("/v1/history").json()
|
||||
check("history lists the server's versions", len(listed) == versions + 1)
|
||||
|
||||
print("== the content folder ==")
|
||||
r = c.get("/v1/fs/list")
|
||||
names = [e["name"] for e in r.json()["entries"]]
|
||||
check("the browser starts at the content folder", r.json()["path"] == str(content) and "Crates" in names)
|
||||
check("`..` cannot leave it", c.get("/v1/fs/list", params={"path": str(content / "..")}).status_code == 400)
|
||||
check("nor can a symlink", c.get("/v1/fs/list", params={"path": str(content / "Sneaky")}).status_code == 400)
|
||||
check("free space is reported", c.get("/v1/fs/space", params={"path": str(content / "New")}).json()["free"] > 0)
|
||||
|
||||
print("== uploads ==")
|
||||
mp3 = make_mp3(Path(d) / "src" / "Kick Tune.mp3")
|
||||
data = mp3.read_bytes()
|
||||
up = lambda name, folder: c.post("/v1/upload", params={"dir": folder, "name": name},
|
||||
content=data, headers={rp.SESSION_HEADER: tok})
|
||||
r1 = up("Kick Tune.mp3", str(content / "Crates" / "New"))
|
||||
r2 = up("Kick Tune.mp3", str(content / "Crates" / "New"))
|
||||
p1, p2 = Path(r1.json()["path"]), Path(r2.json()["path"])
|
||||
check("an upload lands in the chosen folder (created)", p1 == content / "Crates" / "New" / "Kick Tune.mp3"
|
||||
and p1.read_bytes() == data, r1.text[:200])
|
||||
check("a second upload of the same name never overwrites", p2.name == "Kick Tune-2.mp3")
|
||||
check("no partial is left behind", not list((content / "Crates" / "New").glob(".*")))
|
||||
check("an upload outside the content folder is refused", up("x.mp3", str(outside)).status_code == 400)
|
||||
check("a name that hides or climbs is refused", up("../x.mp3", str(content)).status_code == 400
|
||||
or up(".x.mp3", str(content)).status_code == 400)
|
||||
check("without the session, refused", c.post("/v1/upload", params={"dir": str(content), "name": "y.mp3"},
|
||||
content=data).status_code == 423)
|
||||
r = c.delete("/v1/upload", params={"path": str(p2)}, headers={rp.SESSION_HEADER: tok})
|
||||
check("a session deletes what it uploaded", r.status_code == 200 and not p2.exists(), r.text[:160])
|
||||
keep = content / "Crates" / "mine.mp3"
|
||||
keep.write_bytes(b"user's")
|
||||
r = c.delete("/v1/upload", params={"path": str(keep)}, headers={rp.SESSION_HEADER: tok})
|
||||
check("…and nothing else", r.status_code == 403 and keep.exists())
|
||||
|
||||
print("== adding an uploaded track, and its audio ==")
|
||||
from konduktor.core.model import Track
|
||||
|
||||
wire = rp.WireNewTrack(track=Track(id="", title="Kick Tune", artist="Tester"), audio_path=str(p1))
|
||||
r = c.post("/v1/rpc/add_tracks", json={"args": {"items": [wire.model_dump(mode="json")]}},
|
||||
headers={rp.SESSION_HEADER: tok})
|
||||
ids = r.json()["result"] if r.status_code == 200 else []
|
||||
check("an uploaded file is added by the ordinary add_tracks",
|
||||
len(ids) == 1 and r.json()["changed"][0]["title"] == "Kick Tune", r.text[:300])
|
||||
if ids:
|
||||
whole = c.get("/v1/audio", params={"track_id": ids[0]})
|
||||
check("its audio streams", whole.status_code == 200 and whole.content == data
|
||||
and int(whole.headers["X-Konduktor-Size"]) == len(data))
|
||||
part = c.get("/v1/audio", params={"track_id": ids[0]}, headers={"Range": "bytes=10-19"})
|
||||
check("…with Range", part.status_code == 206 and part.content == data[10:20])
|
||||
facts = call("audio_facts", track_ids=ids).json()["result"]
|
||||
check("its facts name the server's file", facts[ids[0]]["key"] == str(p1))
|
||||
r = c.delete("/v1/upload", params={"path": str(p1)}, headers={rp.SESSION_HEADER: tok})
|
||||
check("an upload the library now names is not deleted", r.status_code == 409 and p1.exists())
|
||||
|
||||
print("== export sets ==")
|
||||
doc = {"sets": {"s1": {"name": "Gig", "targets": ["traktor"], "destination": "/Volumes/STICK",
|
||||
"playlist_ids": [], "track_ids": []}}}
|
||||
check("export sets need the session to change",
|
||||
c.put("/v1/export-sets", json=doc).status_code == 423)
|
||||
c.put("/v1/export-sets", json=doc, headers={rp.SESSION_HEADER: tok})
|
||||
got = c.get("/v1/export-sets").json()
|
||||
check("…and are kept by the server, keyed by its library id",
|
||||
got["sets"]["s1"]["name"] == "Gig" and got["library_id"] == hello["library_id"], got)
|
||||
|
||||
c.post("/v1/session/release", headers={rp.SESSION_HEADER: tok})
|
||||
check("release frees the session", c.get("/v1/hello").json()["holder"] is None)
|
||||
check("the original collection beside the tests was never touched", REAL.exists())
|
||||
|
||||
print()
|
||||
print("RESULT:", "FAILURES" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -0,0 +1,235 @@
|
||||
"""Convert to Stems on a REMOTE library, with a FAKE engine.
|
||||
|
||||
A Konduktor server runs in a thread on a temp copy of the real collection whose
|
||||
playlisted tracks point at generated MP3s on "the server"; the app converts
|
||||
through its own routes. The server never decodes audio, so this pins the split:
|
||||
|
||||
* the server plans (targets, skips) and this computer reports what it must
|
||||
download and upload, and the room it needs here;
|
||||
* a Replace batch separates HERE, uploads, and the SERVER publishes, parks
|
||||
the original and swaps the entry — its saved collection untouched until
|
||||
Save, which deletes the parked original there; Discard puts it back;
|
||||
* Cancel deletes what the run uploaded, and nothing else;
|
||||
* another computer taking over mid-batch loses no separation: the uploaded,
|
||||
verified stem file stays on the server and the next run reuses it without
|
||||
the engine.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-remotestems-appdata-")
|
||||
os.environ.pop("KONDUKTOR_NML", None)
|
||||
|
||||
import uvicorn # noqa: E402
|
||||
from fastapi.testclient import TestClient # noqa: E402
|
||||
|
||||
import konduktor.main as main # noqa: E402
|
||||
from konduktor.adapters.remote import config as remote_config # noqa: E402
|
||||
from konduktor.adapters.remote.client import RemoteClient # noqa: E402
|
||||
from konduktor.adapters.traktor.locations import os_path_to_location # noqa: E402
|
||||
from konduktor.adapters.traktor.store import TraktorStore # noqa: E402
|
||||
from konduktor.app_state import AppState # noqa: E402
|
||||
from konduktor.core import stem_file as sf # noqa: E402
|
||||
from konduktor.server.app import Server, create_app # noqa: E402
|
||||
from konduktor.server.config import ServerConfig # noqa: E402
|
||||
from konduktor.stems import convert as convert_mod # noqa: E402
|
||||
from konduktor.stems import engine_manager as em # noqa: E402
|
||||
from konduktor.stems import remote_convert # noqa: E402
|
||||
from konduktor.stems.pending import parked_name, partial_name # noqa: E402
|
||||
from stem_test_support import install_fake_engine, make_mp3 # noqa: E402
|
||||
|
||||
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
|
||||
failed = False
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
global failed
|
||||
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
|
||||
if not cond:
|
||||
failed = True
|
||||
|
||||
|
||||
class MemoryKeychain(dict):
|
||||
def get(self, account): # noqa: D401
|
||||
return dict.get(self, account)
|
||||
|
||||
def set(self, account, password):
|
||||
self[account] = password
|
||||
|
||||
def delete(self, account):
|
||||
self.pop(account, None)
|
||||
|
||||
|
||||
remote_config.use_password_store(MemoryKeychain())
|
||||
ROOT = Path(tempfile.mkdtemp(prefix="konduktor-remotestems-"))
|
||||
em._DEFAULT = install_fake_engine(ROOT / "engine")
|
||||
|
||||
# ---- a server library: playlisted tracks pointed at generated MP3s -------------------
|
||||
music = (ROOT / "server" / "Music").resolve()
|
||||
music.mkdir(parents=True)
|
||||
work = ROOT / "server" / "collection.nml"
|
||||
shutil.copy2(REAL, work)
|
||||
st = TraktorStore(work)
|
||||
in_pl = {k for n in st._iter_nodes(st._root()) if n.playlist for k in st._entry_keys_of(n.playlist)}
|
||||
entries = [e for e in st._nml.collection.entry if e.location and st._key_of(e) in in_pl and e.stems is None][:5]
|
||||
ids = []
|
||||
for n, e in enumerate(entries):
|
||||
path = make_mp3(music / f"Track {n}.mp3", seed=n + 1)
|
||||
old = st._key_of(e)
|
||||
e.location.volume, e.location.dir, e.location.file = os_path_to_location(path)
|
||||
new = st._key_of(e)
|
||||
for node in st._iter_nodes(st._root()):
|
||||
for pe in (node.playlist.entry if node.playlist else None) or []:
|
||||
if pe.primarykey and pe.primarykey.key == old:
|
||||
pe.primarykey.key = new
|
||||
st._entry_by_key = {st._key_of(x): x for x in st._nml.collection.entry if x.location}
|
||||
e.cue_v2 = []
|
||||
st.set_hotcue(new, 1, 1.0, 0, name="Drop")
|
||||
st.replace_grid(new, [(0.5, 120.0)])
|
||||
ids.append(new)
|
||||
st.save()
|
||||
del st
|
||||
|
||||
cfg = ServerConfig(platform="traktor", library=work, content=music, username="dj", password="pw", name="NAS")
|
||||
srv = Server(cfg, state=AppState())
|
||||
srv.open()
|
||||
uv = uvicorn.Server(uvicorn.Config(create_app(srv), host="127.0.0.1", port=0, log_level="warning"))
|
||||
threading.Thread(target=uv.run, daemon=True).start()
|
||||
while not uv.started:
|
||||
time.sleep(0.05)
|
||||
port = uv.servers[0].sockets[0].getsockname()[1]
|
||||
|
||||
|
||||
def wait(c, jid, timeout=120):
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
j = c.get(f"/api/jobs/{jid}").json()
|
||||
if j["state"] != "running":
|
||||
return j
|
||||
time.sleep(0.05)
|
||||
raise AssertionError("job did not finish")
|
||||
|
||||
|
||||
with TestClient(main.app) as c:
|
||||
remote_id = c.post("/api/remotes", json={"name": "NAS", "host": f"127.0.0.1:{port}",
|
||||
"username": "dj", "password": "pw"}).json()["remote"]["id"]
|
||||
r = c.post("/api/library/open-remote", json={"remote_id": remote_id})
|
||||
assert r.status_code == 200, r.text
|
||||
server_adapter = srv.state.adapter
|
||||
|
||||
print("== the plan: the server's, plus this computer's ==")
|
||||
p = c.post("/api/tracks/stems/preview", json={"track_ids": ids[:1], "mode": "replace"}).json()
|
||||
check("one track to convert, its target beside it on the server",
|
||||
len(p["convert"]) == 1 and p["convert"][0]["target"] == str(music / "Track 0.stem.m4a"), p)
|
||||
check("…and what must cross the network", p["transfer"]["download"] > 0 and p["transfer"]["upload"] > 0,
|
||||
p.get("transfer"))
|
||||
check("…and the room needed on BOTH machines",
|
||||
any(s["volume"] == "this computer" for s in p["space"])
|
||||
and any(s["volume"].startswith("the server") for s in p["space"]), p["space"])
|
||||
|
||||
print("== a Replace batch ==")
|
||||
saved_bytes = work.read_bytes()
|
||||
r = c.post("/api/tracks/stems/convert", json={"track_ids": ids[:1], "mode": "replace"})
|
||||
job = wait(c, r.json()["id"])
|
||||
res = job.get("result") or {}
|
||||
target = music / "Track 0.stem.m4a"
|
||||
check("the job converts the track", job["state"] == "done" and len(res.get("converted", [])) == 1,
|
||||
job.get("error") or res)
|
||||
check("the stem file is on the server, the original parked beside it",
|
||||
target.is_file() and sf.is_stem_file(target) and parked_name(music / "Track 0.mp3").is_file())
|
||||
new_id = res.get("renamed", {}).get(ids[0])
|
||||
check("the server's entry now names the stem file", new_id and server_adapter.track(new_id) is not None)
|
||||
check("…and the mirror here follows", main.require_adapter().track(new_id) is not None)
|
||||
check("the SAVED collection is untouched until Save", work.read_bytes() == saved_bytes)
|
||||
st_ = c.get("/api/state").json()
|
||||
check("the state reports the conversion awaiting Save (from the server's ledger)",
|
||||
st_["pending_stems"] and st_["pending_stems"]["tracks"] == 1, st_.get("pending_stems"))
|
||||
check("…and blocks what would save or drop it", c.post("/api/reload").status_code == 409)
|
||||
c.post("/api/save")
|
||||
check("Save deletes the parked original on the server",
|
||||
not parked_name(music / "Track 0.mp3").exists() and target.is_file())
|
||||
check("…and the ledger is clear", not (c.get("/api/state").json()["pending_stems"] or {}).get("tracks"))
|
||||
|
||||
print("== playing a remote stem file ==")
|
||||
layout = c.get("/api/tracks/stems", params={"track_id": new_id})
|
||||
stems = layout.json().get("stems") if layout.status_code == 200 else None
|
||||
check("the deck is offered the stem file's four stems",
|
||||
isinstance(stems, list) and len(stems) == 4, layout.text[:200])
|
||||
one = c.get("/api/tracks/audio", params={"track_id": new_id, "stem": 1})
|
||||
check("…and each streams, extracted HERE from the downloaded file",
|
||||
one.status_code == 200 and len(one.content) > 1000, one.status_code)
|
||||
|
||||
print("== Discard puts it back ==")
|
||||
r = c.post("/api/tracks/stems/convert", json={"track_ids": [ids[1]], "mode": "replace"})
|
||||
job = wait(c, r.json()["id"])
|
||||
check("(setup) a second conversion", job["state"] == "done" and (music / "Track 1.stem.m4a").is_file(),
|
||||
job.get("error"))
|
||||
c.post("/api/discard")
|
||||
check("Discard restores the original and removes the stem file, on the server",
|
||||
(music / "Track 1.mp3").is_file() and not (music / "Track 1.stem.m4a").exists()
|
||||
and not parked_name(music / "Track 1.mp3").exists())
|
||||
|
||||
print("== Cancel deletes what the run uploaded ==")
|
||||
adapter = main.require_adapter()
|
||||
opts = convert_mod.Options(mode="replace")
|
||||
planned = remote_convert.plan(adapter, [ids[2], ids[3]], opts)
|
||||
|
||||
class Handle:
|
||||
cancelled = False
|
||||
|
||||
def progress(self, **kw):
|
||||
pass
|
||||
|
||||
h = Handle()
|
||||
real_stage = adapter.stage_stem
|
||||
|
||||
def stage_then_cancel(*a, **k):
|
||||
out = real_stage(*a, **k)
|
||||
h.cancelled = True
|
||||
return out
|
||||
|
||||
adapter.stage_stem = stage_then_cancel
|
||||
out = remote_convert.run(h, adapter, planned, opts, still_current=lambda: True)
|
||||
adapter.stage_stem = real_stage
|
||||
check("a cancel after one upload stops the batch", out["cancelled"])
|
||||
check("…and the uploaded stem file is deleted on the server",
|
||||
not partial_name(music / "Track 2.stem.m4a").exists() and not srv.state.pending.leftovers,
|
||||
srv.state.pending.leftovers)
|
||||
check("…nothing else changed", (music / "Track 2.mp3").is_file() and not server_adapter.dirty)
|
||||
|
||||
print("== a takeover mid-batch loses no separation ==")
|
||||
planned = remote_convert.plan(adapter, [ids[4]], opts)
|
||||
item = planned.items[0]
|
||||
local = adapter.audio_path(ids[4])
|
||||
staged = ROOT / "staged.stem.m4a"
|
||||
written = sf.build(local, staged, lambda pcm: [pcm * g for g in (0.5, 0.25, -0.2, 0.1)])
|
||||
adapter.stage_stem(ids[4], item["target"], staged, bit_rate=written.bit_rate, duration=written.duration)
|
||||
other = RemoteClient(remote_config.Remote(id="o", name="NAS", host=f"127.0.0.1:{port}", username="dj"), "pw")
|
||||
other.acquire("other", "Studio iMac", takeover=True)
|
||||
other.release()
|
||||
check("the uploaded file stays on the server as a verified leftover",
|
||||
partial_name(music / "Track 4.stem.m4a").is_file() and len(srv.state.pending.leftovers) == 1)
|
||||
r = c.post("/api/library/open-remote", json={"remote_id": remote_id})
|
||||
p = c.post("/api/tracks/stems/preview", json={"track_ids": [ids[4]], "mode": "replace"}).json()
|
||||
check("the next plan reuses it", p["convert"] and p["convert"][0]["reuse"] and p["seconds"] == 0, p)
|
||||
em._DEFAULT = em.EngineManager(ROOT / "no-engine") # an engine call would now fail
|
||||
r = c.post("/api/tracks/stems/convert", json={"track_ids": [ids[4]], "mode": "replace"})
|
||||
job = wait(c, r.json()["id"]) if r.status_code == 200 else {"state": "refused", "error": r.text}
|
||||
check("…and converts without the engine", job["state"] == "done"
|
||||
and len((job.get("result") or {}).get("converted", [])) == 1, job.get("error") or job.get("result"))
|
||||
c.post("/api/save")
|
||||
check("…to a stem file on the server", sf.is_stem_file(music / "Track 4.stem.m4a"))
|
||||
uv.should_exit = True
|
||||
|
||||
print()
|
||||
print("RESULT:", "FAILURES" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
Reference in new issue
Block a user