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
@@ -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
|
||||
Reference in new issue
Block a user