Initial implementation of remote library system

This commit is contained in:
patben8 committed 2026-10-04 17:13:24 +02:00
1 parent e8a53eee07
commit e5fb0f0dbb
65 files changed
+5994 -177

No files matched your search

+44
View File
@@ -114,6 +114,50 @@ jobs:
if-no-files-found: error if-no-files-found: error
path: installer/* path: installer/*
# The Konduktor SERVER image (server/Dockerfile): a remote library's half,
# pushed to GHCR with the same version as the desktop app, so a TrueNAS app
# can name the tag that matches the app it is opened from.
server-image:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write # push to ghcr.io
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Resolve version and image name
id: meta
run: |
echo "version=$(jq -r .version frontend/package.json)" >> "$GITHUB_OUTPUT"
# GHCR names must be lower-case; the owner may not be.
echo "image=ghcr.io/${GITHUB_REPOSITORY_OWNER,,}/konduktor-server" >> "$GITHUB_OUTPUT"
- name: Log in to GHCR
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Set up Buildx
uses: docker/setup-buildx-action@v3
- name: Build and push
uses: docker/build-push-action@v6
with:
context: .
file: server/Dockerfile
platforms: linux/amd64
push: true
tags: |
${{ steps.meta.outputs.image }}:${{ steps.meta.outputs.version }}-b${{ github.run_number }}
${{ steps.meta.outputs.image }}:${{ steps.meta.outputs.version }}
${{ steps.meta.outputs.image }}:latest
labels: |
org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}
org.opencontainers.image.version=${{ steps.meta.outputs.version }}
# Gather both platforms' installers and publish them as a single new Release. # Gather both platforms' installers and publish them as a single new Release.
# Runs once, after both builds succeed, so the two matrix jobs never race to # Runs once, after both builds succeed, so the two matrix jobs never race to
# create the same tag/release. # create the same tag/release.
+138 -1
View File
@@ -524,6 +524,105 @@ Two independent apps that talk over HTTP:
open / save / discard (and, next, a stem batch's swap step). open / save / discard (and, next, a stem batch's swap step).
History is app-level: the adapter returns the bytes it wrote plus a summary, History is app-level: the adapter returns the bytes it wrote plus a summary,
and `AppState.save()` versions them. Every write path must go through it. and `AppState.save()` versions them. Every write path must go through it.
**Where** it is versioned is the open library's `services` (`services.py`):
`LocalServices` is the history repo in this computer's app-data, keyed by
path (what it always was); a remote library's live on its server. Routes
reach history through `STATE.services` / `STATE.restore_version`, never the
`history` module with `STATE.path`. `open_hooks` run at the end of every
open (and restore) — how the server re-applies its configured path mapping.
- **Remote libraries** (decided 2026-10-01/02 —
[the discussion](.claude/discussions/discuss-remote-library-2026-10-01.md)):
the whole library on the user's NAS, a Konduktor SERVER in a container
holding it, the desktop app opening it as "Remote". Three pieces:
- `remote_protocol.py` — the wire contract BOTH sides import: the
`LibraryAdapter` protocol itself as RPC (`RPC` table, `MUTATING` flag,
`EXCLUDED` with a reason for every member that does not travel —
`test_remote_protocol.py` fails on a protocol member that is neither),
args/results (de)serialised by pydantic `TypeAdapter`s built from the
protocol's own hints (a misspelt argument is refused, not defaulted),
`API_VERSION` (same major, server minor ≥ client's), the lease
(`LEASE_SECONDS` 120 / `HEARTBEAT_SECONDS` 15), `WireNewTrack` and the
prepared-analysis `.npz` packing. Bytes never travel as JSON.
- `server/` — `python -m konduktor.server` (the container's command;
`server/Dockerfile`, `compose.yaml`, `.env.example`). NOT `main.py`
behind a password. `config.py` reads the env (`KONDUKTOR_PLATFORM`
checked against the file, `_LIBRARY`, `_CONTENT`, `_USERNAME`,
`_PASSWORD`, `_PATH_MAP` "stored => here; …") and fails fast with one
line. `app.py`: HTTP Basic on every route; `/v1/hello`, `session/*`,
`rpc/{method}` (every answer carries `rev` plus the tracks it `changed`
/ `removed`), `audio` (Range), `art`, `upload` (into a folder CONFINED
to the content folder — resolve then `is_relative_to`, so neither `..`
nor a symlink escapes — never overwriting, `-2` suffixes, per-session
so a cancel deletes only its own), `fs/list|space`, `save`, `discard`,
`history`, `export-sets`, and the stems routes below. Capabilities are
the adapter's plus `tracks.audio_destination="library"`,
`reference=False`, `paths.remappable=False`, `overwrite_risk="none"`.
`session.py`: ONE holder; a 409 names who holds it (machine, since,
running batch) and `takeover` replaces it; the old token is 423 from
then on; a lapsed lease is renewed silently for the SAME client if
nobody took it. Unsaved edits are the native model's, not the
session's: the next holder inherits them and `pending_edits`
(`last_editor` + the adapter's optional `edit_summary()`) asks them to
save or discard. A container restart loses them — accepted.
**Lightweight by decision: the server never decodes audio** — its
image ships `requirements-server.txt` without librosa / scikit-learn /
PyAV, and `test_layering.py` checks importing it pulls none in
(`stem_file._audio_stream_count` counts `soun` traks when PyAV is
absent). With a path mapping configured the server calls the
adapter's optional `set_write_stored_paths(True)`: a file added (or a
stem file swapped in) through the mapping is written in the library's
STORED form (`pathmap.stored_form`), so the collection keeps one
convention and still opens where it was made.
- `adapters/remote/` — the client, imports no platform adapter.
`RemoteAdapter` IS a `LibraryAdapter`: the frontend, export, import and
batches never learn a library is remote. It mirrors the projection in a
local `TrackIndex` (same query code), folds each command's `changed`
into it, and re-fetches on any `rev` gap. **`audio_path` downloads**
into the shared `cache.py` (keyed by the server's `AudioFacts` — path,
size, mtime — partial-then-rename, LRU under `remoteCacheBytes`, the
recently used never evicted); anything that needs only a file's
IDENTITY asks the new protocol member **`audio_facts`**, which never
downloads (`exporter.plan`, `importer._existing_files`). `client.py`
tries the address that last worked, then the others (primary →
fallback) on CONNECT failures only, and maps status codes back onto the
adapter error classes (423 → `SessionLost`, unreachable → `Unavailable`,
503 in `main.py`). `session.py` heartbeats (reporting the running batch)
and moves `connected / reconnecting / offline / taken_over`; anything
but connected/reconnecting makes `capabilities()` read-only with cause
`taken_over` / `offline`, and a 423 on any command flips it at once;
taken over cancels this computer's batches (`_on_remote_change`).
`config.py`: saved remotes in prefs (`remotes`, plus a stable
`remoteClientId`), passwords in the OS keychain via `keyring`
(`use_password_store` is the test seam). `services.py`: history, export
sets (`exports.use_store`, keyed by `remote:<server id>` so nothing on
this computer is mistaken for the server's) and the stems ledger
(`RemotePending`) all on the server. Imports UPLOAD
(`importer.uploads_audio` → `upload_audio`, cleaned up on failure; free
space from the server) into a folder the user picks on the server;
Rekordbox's add analysis — waveform, grid AND key — is computed HERE
(`core/add_analysis.prepare` with the lead the upload reports, sent as
`NewTrack.analysis`).
**Convert to Stems** (`stems/remote_convert.py`): the server plans
(`/v1/stems/plan`, its `convert.plan`), this computer downloads,
separates and encodes, uploads each verified file (`/v1/stems/stage`,
sha-256 checked, kept on the server as a LEFTOVER), and the server runs
the ordinary `convert._end_step` under its mutation lock with its own
ledger (`/v1/stems/publish`). Cancel abandons this run's uploads; a
takeover cannot, so they stay and the next run reuses them. The preview
adds `transfer` (download / upload / measured speed) and space lines for
both machines.
UI: the picker's platform list ends with **Remote** (`selects:
"remote"`) → `RemotePicker` (saved remotes; the form saves only after
`handshake` — a wrong password or version refuses, an unreachable
fallback alone does not; the in-use → Take over and the leftover-edits
Save / Discard / Decide-later prompts happen before the library shows).
`App` polls `['state']` every 5 s for a remote (`remote` in `EditState`),
re-reads capabilities on a change and toasts it; `StatusBar` shows the
connection. `FileBrowser`/`FolderPicker` take `listing="library"` for the
server's folders; Import / Add Files / Convert to Stems use it when
`tracks.audio_destination === 'library'` (folders remembered per remote:
`remoteImportFolders`, `remoteStemFolders`). Settings → Remote audio is
the cache. Path remapping hides on `paths.remappable === false`.
- `library_id.py` — a **stable identity for a library that survives it being - `library_id.py` — a **stable identity for a library that survives it being
moved**. Everything else keys off the OS path (`history` hashes it, `prefs` moved**. Everything else keys off the OS path (`history` hashes it, `prefs`
stores it), which is fine for things a user shrugs at losing and NOT fine for stores it), which is fine for things a user shrugs at losing and NOT fine for
@@ -913,6 +1012,13 @@ cd backend && source .venv/bin/activate
uvicorn konduktor.main:app --reload --port 8000 uvicorn konduktor.main:app --reload --port 8000
# point at another file: KONDUKTOR_NML=/path/to/collection.nml uvicorn ... # point at another file: KONDUKTOR_NML=/path/to/collection.nml uvicorn ...
# A Konduktor SERVER (a remote library) from source — configured by env, see
# server/.env.example; the container runs the same command:
KONDUKTOR_PLATFORM=traktor KONDUKTOR_LIBRARY=/path/collection.nml \
KONDUKTOR_CONTENT=/path/music KONDUKTOR_USERNAME=dj KONDUKTOR_PASSWORD=pw \
python -m konduktor.server # listens on :8765
docker build -f server/Dockerfile -t konduktor-server . # from the repo root
# Frontend # Frontend
cd frontend cd frontend
npm run dev # dev server (proxies /api -> :8000) npm run dev # dev server (proxies /api -> :8000)
@@ -1223,11 +1329,35 @@ serialization path.** It enforces:
reopen), and a running batch has stopped by the time discard returns; on reopen), and a running batch has stopped by the time discard returns; on
Rekordbox (temp copy, skipped when absent) the library is clean afterwards and Rekordbox (temp copy, skipped when absent) the library is clean afterwards and
a later save writes nothing that was thrown away; read-only libraries 409. a later save writes nothing that was thrown away; read-only libraries 409.
- `test_remote_protocol.py` — pure: every `LibraryAdapter` member is an RPC or
excluded with a reason, every command is `MUTATING`, args/results survive
JSON by the protocol's types (tuples, dataclasses, `None`), a misspelt or
missing argument is refused, a prepared analysis crosses intact, the
version rule.
- `test_remote_server.py` — the server's own routes on a temp copy of the
collection with a FAKE clock: config refusals, 401s, one computer at a time
(423 without the token, 409 naming the holder and its batch, takeover kills
the old token, an expired lease frees it, the same client renews), leftover
edits named, save + history on the server, discard, confinement (`..`,
symlinks), uploads never overwrite and delete only their own, Range audio.
- `test_remote_adapter.py` — END TO END: a real server in a thread, the app's
routes opening it. Handshake refusals, fallback, the mirror, Save touching
only the edited `<ENTRY>` THROUGH the trip, one download per file, Analyze
on the cached copy, export (and a re-export copying nothing), an upload
stored in the mapping's stored form, takeover → read-only at once,
reopening names the holder and the edits left, leaving releases.
- `test_remote_stems.py` — Convert to Stems on a remote with the FAKE engine:
the plan's transfer and two-machine space, Replace parks and swaps ON THE
SERVER (saved file untouched until Save, which deletes the parked
original), Discard restores, Cancel deletes only this run's uploads, a
takeover's uploads are reused without the engine.
- `test_layering.py` — `core/` imports nothing platform-specific, and no adapter - `test_layering.py` — `core/` imports nothing platform-specific, and no adapter
imports another platform's library (checked on real imports via AST, so merely imports another platform's library (checked on real imports via AST, so merely
naming a platform in a comment is fine). Rekordbox and OneLibrary deliberately naming a platform in a comment is fine). Rekordbox and OneLibrary deliberately
**share** `pyrekordbox`: the rule is "no adapter reaches for a rival vendor's **share** `pyrekordbox`: the rule is "no adapter reaches for a rival vendor's
library", and a shared dependency is not a breach. library", and a shared dependency is not a breach. Also: `adapters/remote`
imports no platform adapter, and importing `konduktor.server` pulls in no
librosa / scikit-learn / torch / numba / PyAV.
Also validate the backend interactively at `http://localhost:8000/docs` and the Also validate the backend interactively at `http://localhost:8000/docs` and the
frontend at `http://localhost:5173`. frontend at `http://localhost:5173`.
@@ -1765,6 +1895,13 @@ that number and nothing else — everything derives from it:
yet**, since nothing can be written. Note the OneLibrary work already demonstrated yet**, since nothing can be written. Note the OneLibrary work already demonstrated
creating an `exportLibrary.db` from nothing, and `fixtures/onelibrary/schema.sql` creating an `exportLibrary.db` from nothing, and `fixtures/onelibrary/schema.sql`
is the DDL to do it with. is the DDL to do it with.
- ✅ **Remote libraries** (2026-10-02) — a Konduktor server in a container
(TrueNAS) holds a Traktor or Rekordbox library; the app opens it as
"Remote": browse, prep, edit, Save (versioned on the server), export sticks,
import by upload, Convert to Stems — all with analysis and separation on the
laptop. One computer at a time, with takeover. See "Remote libraries" under
Architecture. Not yet: verified on a real TrueNAS (the image is published by
CI's `server-image` job), a web UI served by the server (decided: not now).
- ⬜ Serato adapter - ⬜ Serato adapter
- ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging - ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging
+43
View File
@@ -200,6 +200,49 @@ play around.
--- ---
## A remote library (Konduktor server on a NAS)
Keep your whole library — the collection file and the music — on a server, and
open it from any computer with Konduktor. Prep tracks, edit playlists, and
export sticks for your gigs without the music ever living on your performance
laptop.
The server is a small container (`server/`). It holds the library and saves it.
Playback, analysis and stem separation run on the computer you open it from,
on copies it downloads, so the server needs no GPU and does very little work.
**On the server (e.g. TrueNAS SCALE):**
1. Copy `server/compose.yaml` and `server/.env.example` (renamed to `.env`)
onto the NAS. Point the volumes at your datasets, and fill in `.env`: the
platform (`traktor` or `rekordbox`), the library file, the music folder, a
username and password, and — for a collection made on a Mac — the path
mapping (`/Users/you/Music => /music`).
2. Install it: on TrueNAS, **Apps → Discover Apps → ⋮ → Install via YAML** and
paste the compose file; anywhere else, `docker compose up -d`. A bad setting
stops the container with one clear line in its log.
**In the app:** choose **Remote** on the platform screen → **Add a remote
library** → enter the server's address (and a fallback, such as its Tailscale
address, for when you're away from home), the username and the password.
Konduktor checks the server before it saves the remote, and keeps the
password in your keychain.
Good to know:
- **One computer at a time.** If another computer has the library open,
Konduktor says who has it and offers to take over. Edits that computer
hadn't saved stay with the library, and you're asked to save or discard
them.
- **Plain HTTP.** Reach the server over your home network or a VPN
(Tailscale / WireGuard). Don't expose its port to the internet.
- **Unsaved edits live on the server** until you save. Restarting the
container drops them.
- Downloaded tracks are cached on your computer (Settings → **Remote audio**
sets the size), so a track you've prepped and then export is fetched once.
---
## Good to know ## Good to know
- Konduktor is built on [`traktor-nml-utils`](https://github.com/MrPatben8/traktor-nml-utils) - Konduktor is built on [`traktor-nml-utils`](https://github.com/MrPatben8/traktor-nml-utils)
+7 -1
View File
@@ -10,7 +10,7 @@
# - python-multipart is imported as `multipart` by starlette → hidden import # - python-multipart is imported as `multipart` by starlette → hidden import
# - dulwich (version-history backups) imports git backends dynamically → # - dulwich (version-history backups) imports git backends dynamically →
# collect_submodules('dulwich') # collect_submodules('dulwich')
from PyInstaller.utils.hooks import collect_submodules, collect_all from PyInstaller.utils.hooks import collect_all, collect_submodules, copy_metadata
hiddenimports = [] hiddenimports = []
datas = [] datas = []
@@ -31,6 +31,12 @@ for pkg in ("uvloop", "httptools", "websockets", "av"):
# Imported by name, not statically discoverable. # Imported by name, not statically discoverable.
hiddenimports += ["multipart", "anyio"] hiddenimports += ["multipart", "anyio"]
# A remote library's password lives in the OS keychain through `keyring`, which
# finds its backends (macOS Keychain, Windows Credential Manager) by entry point
# — so both the modules AND the package metadata that names them must ship.
hiddenimports += collect_submodules("keyring")
datas += copy_metadata("keyring")
# Bundle the canonical version file so konduktor.__version__ can read it at # Bundle the canonical version file so konduktor.__version__ can read it at
# runtime from sys._MEIPASS (frontend/package.json is the single source of the # runtime from sys._MEIPASS (frontend/package.json is the single source of the
# app version — see konduktor/__init__.py). Path is relative to this spec. # app version — see konduktor/__init__.py). Path is relative to this spec.
@@ -21,7 +21,7 @@ from __future__ import annotations
from pathlib import Path from 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.capabilities import Capabilities
from ...core.model import GridMarker, HotcueChip, PlaylistNode, Track, TrackCues from ...core.model import GridMarker, HotcueChip, PlaylistNode, Track, TrackCues
from ...core.pathmap import PathMapping, common_dir_prefix from ...core.pathmap import PathMapping, common_dir_prefix
@@ -223,6 +223,9 @@ class OneLibraryAdapter:
def audio_path(self, track_id: str): def audio_path(self, track_id: str):
return self._store.audio_path(track_id) 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: def set_path_mapping(self, mapping: PathMapping) -> None:
"""Ignored: a drive's paths are relative to wherever it is mounted. """Ignored: a drive's paths are relative to wherever it is mounted.
+37 -11
View File
@@ -21,13 +21,14 @@ from __future__ import annotations
from pathlib import Path 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.capabilities import Capabilities
from ...core.model import GridMarker, PlaylistNode, Track, TrackCues from ...core.model import GridMarker, PlaylistNode, Track, TrackCues
from ...core.pathmap import PathMapping, common_dir_prefix from ...core.pathmap import PathMapping, common_dir_prefix
from ...core.query import TrackIndex from ...core.query import TrackIndex
from . import capabilities as caps from . import capabilities as caps
from . import palette, projection, timebase from . import palette, projection, timebase
from ...core import add_analysis
from .store import RekordboxStore from .store import RekordboxStore
@@ -202,6 +203,9 @@ class RekordboxAdapter:
def audio_path(self, track_id: str): def audio_path(self, track_id: str):
return self._store.audio_path(track_id) 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: def set_path_mapping(self, mapping: PathMapping) -> None:
self._store.set_path_mapping(mapping) self._store.set_path_mapping(mapping)
# The FILE decides a track's media kind, and the mapping moves files. # 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: def set_session_mappings(self, mappings: list[PathMapping]) -> None:
return 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: def path_prefix_suggestions(self) -> dict:
paths = self._store.all_audio_paths() paths = self._store.all_audio_paths()
primary = common_dir_prefix(paths) primary = common_dir_prefix(paths)
@@ -388,6 +396,12 @@ class RekordboxAdapter:
def dirty(self) -> bool: def dirty(self) -> bool:
return self._store.dirty 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): def save(self):
self._require_writable("Saving") self._require_writable("Saving")
return self._store.save() return self._store.save()
@@ -422,6 +436,14 @@ class RekordboxAdapter:
if self._cloud_synced: if self._cloud_synced:
raise Unsupported(self._readonly_reason(what)) 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]: def add_tracks(self, items: list, *, checkpoint=None) -> list[str]:
"""Add tracks that came from somewhere else, with their prep. """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 bank or already taken becomes a memory cue at the same position rather
than being dropped. than being dropped.
""" """
from ...core import audio_tags, grid_detect, key_detect, waveform from ...core import audio_tags
self._require_writable("Adding tracks") self._require_writable("Adding tracks")
held = set(self._store.all_audio_paths()) held = set(self._store.all_audio_paths())
@@ -459,18 +481,22 @@ class RekordboxAdapter:
if str(audio) in held: if str(audio) in held:
raise InvalidCommand(f"The library already holds {audio}") raise InvalidCommand(f"The library already holds {audio}")
held.add(str(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 [] markers = list(item.cues.grid_markers) if item.cues else []
if not markers and samples is not None: if item.analysis is not None:
try: # Measured by whoever added it — a library held by a server is
found = grid_detect.detect_grid(str(audio), y=samples, sr=waveform.SR) # never asked to decode audio (see `PreparedAnalysis`).
markers = [GridMarker(start=found.anchor, bpm=found.bpm)] analysed = item.analysis
except ValueError: if not markers:
pass # no pulse to fit (a one-shot, silence): no grid 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 # 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. # (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) art = item.art or audio_tags.read_cover(audio)
prepared.append((item, track, audio, measured, markers, art[0] if art else None)) prepared.append((item, track, audio, measured, markers, art[0] if art else None))
+18 -2
View File
@@ -46,7 +46,7 @@ from ...core.adapter import (
) )
from ...core.edit_journal import EditJournal from ...core.edit_journal import EditJournal
from ...core.grid_edit import ReplaceGridCommands from ...core.grid_edit import ReplaceGridCommands
from ...core.pathmap import PathMapping from ...core.pathmap import PathMapping, stored_form
from . import timebase from . import timebase
from .cue_types import beat_loop_size, kind_for, role_and_slot from .cue_types import beat_loop_size, kind_for, role_and_slot
@@ -117,6 +117,8 @@ class RekordboxStore(ReplaceGridCommands):
def __init__(self, path: Path): def __init__(self, path: Path):
self.path = Path(path) self.path = Path(path)
self._mapping = PathMapping() 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._grid_cache: dict[str, tuple[list[float], list[float], list[int]] | None] = {}
self._journal = EditJournal() self._journal = EditJournal()
# Grid edits buffered until save(): ANLZ files are written to disk, so # 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: def set_path_mapping(self, mapping: PathMapping) -> None:
self._mapping = mapping or PathMapping() 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: def is_stem(self, track_id: str) -> bool:
"""Whether the track's FILE is a native-instruments stem file — read """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 from its contents (only `.m4a`/`.mp4` are opened, ~0.7 ms each), and
@@ -649,7 +659,9 @@ class RekordboxStore(ReplaceGridCommands):
if not audio.is_file(): if not audio.is_file():
raise InvalidCommand(f"No audio file at {audio}") raise InvalidCommand(f"No audio file at {audio}")
t = self._tables t = self._tables
if self._db.session.query(t.DjmdContent).filter_by(FolderPath=str(audio)).count(): 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}") raise InvalidCommand(f"The library already holds {audio}")
facts = _file_facts(audio) facts = _file_facts(audio)
content = self._db.add_content( content = self._db.add_content(
@@ -676,6 +688,10 @@ class RekordboxStore(ReplaceGridCommands):
# Rekordbox's ("10m" is "Cm" here), and a row it already has is reused. # 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.KeyID = self._key_id(track.key_wheel, track.key_mode)
content.ContentLink = new_content.CONTENT_LINK 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) track_uuid = str(content.UUID)
rel = new_content.anlz_rel(track_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
+194
View File
@@ -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
+302
View File
@@ -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)
+192
View File
@@ -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")
+17 -1
View File
@@ -15,7 +15,7 @@ from contextlib import contextmanager
from pathlib import Path from pathlib import Path
from types import SimpleNamespace 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.capabilities import Capabilities
from ...core.model import PlaylistNode, Track, TrackCues from ...core.model import PlaylistNode, Track, TrackCues
from ...core.pathmap import PathMapping from ...core.pathmap import PathMapping
@@ -383,12 +383,22 @@ class TraktorAdapter:
def audio_path(self, track_id: str): def audio_path(self, track_id: str):
return self._store.audio_path(track_id) 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: def set_path_mapping(self, mapping: PathMapping) -> None:
self._store.set_path_mapping(mapping) self._store.set_path_mapping(mapping)
def set_session_mappings(self, mappings: list[PathMapping]) -> None: def set_session_mappings(self, mappings: list[PathMapping]) -> None:
self._store.set_session_mappings(mappings) 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]: def unresolved_path_groups(self) -> list[PathGroup]:
return self._store.unresolved_path_groups() return self._store.unresolved_path_groups()
@@ -411,6 +421,12 @@ class TraktorAdapter:
def dirty(self) -> bool: def dirty(self) -> bool:
return self._store.dirty 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): def save(self):
outcome = self._store.save() outcome = self._store.save()
self._rebuild() # save() re-parses, so every object identity changed self._rebuild() # save() re-parses, so every object identity changed
+15 -3
View File
@@ -49,7 +49,7 @@ from xsdata.formats.dataclass.serializers import XmlSerializer
from ...core.adapter import FileTagResult, InvalidCommand, SaveOutcome, StemSwapResult from ...core.adapter import FileTagResult, InvalidCommand, SaveOutcome, StemSwapResult
from ...core.edit_journal import EditJournal from ...core.edit_journal import EditJournal
from ...core.pathmap import common_dir_prefix 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.relocate import PathGroup
from ...core.stem_file import NML_STEMS_JSON, nml_stems_for from ...core.stem_file import NML_STEMS_JSON, nml_stems_for
from ...schemas import PlaylistNode from ...schemas import PlaylistNode
@@ -79,6 +79,9 @@ class TraktorStore:
self.dirty = False self.dirty = False
# Active OS-path prefix remapping (empty = identity). Survives _load(). # Active OS-path prefix remapping (empty = identity). Survives _load().
self._path_mapping = PathMapping() 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. # Mappings the user confirmed in the open-time missing-files check.
# Session-only: never saved, re-derived on every open. # Session-only: never saved, re-derived on every open.
self._session_mappings: list[PathMapping] = [] self._session_mappings: list[PathMapping] = []
@@ -494,7 +497,7 @@ class TraktorStore:
# Read before the lock: it opens the file. # Read before the lock: it opens the file.
stems = nml_stems_for(audio_path) stems = nml_stems_for(audio_path)
with self._lock: 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}" key = f"{volume}{dir_}{file}"
if key in self._entry_by_key: if key in self._entry_by_key:
raise PlaylistError( raise PlaylistError(
@@ -1060,6 +1063,15 @@ class TraktorStore:
with self._lock: with self._lock:
self._path_mapping = mapping 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: def set_session_mappings(self, mappings: list[PathMapping]) -> None:
"""Set the mappings confirmed for this session (applied at resolve time).""" """Set the mappings confirmed for this session (applied at resolve time)."""
with self._lock: with self._lock:
@@ -1355,7 +1367,7 @@ class TraktorStore:
if swap.mode not in ("repoint", "add"): if swap.mode not in ("repoint", "add"):
raise PlaylistError(f"Unknown stem swap mode: {swap.mode}") raise PlaylistError(f"Unknown stem swap mode: {swap.mode}")
seen_ids.add(swap.track_id) 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) new_key = "".join(x or "" for x in loc)
if new_key in self._entry_by_key or new_key in new_keys: if new_key in self._entry_by_key or new_key in new_keys:
raise PlaylistError( raise PlaylistError(
+82 -23
View File
@@ -28,11 +28,12 @@ import os
import threading import threading
from pathlib import Path 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 import registry
from .core.adapter import LibraryAdapter from .core.adapter import LibraryAdapter
from .core.pathmap import PathMapping from .core.pathmap import PathMapping
from .relocation import RelocationCheck from .relocation import RelocationCheck
from .services import LibraryServices, LocalServices
class AppState: class AppState:
@@ -61,6 +62,18 @@ class AppState:
# and what the last open's crash recovery did about any left over. # and what the last open's crash recovery did about any left over.
self.pending = None self.pending = None
self.recovery: dict | None = 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 @property
def loaded(self) -> bool: def loaded(self) -> bool:
@@ -120,16 +133,7 @@ class AppState:
# write-ahead log beside a file another process replaces is how a SQLite # 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 # library gets corrupted. Only close once the new one has parsed, so a
# failed open leaves the current library intact. # failed open leaves the current library intact.
previous = self.adapter self._release_previous()
# 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
# Apply this library's saved OS-path remapping (per-machine, keyed by the # Apply this library's saved OS-path remapping (per-machine, keyed by the
# library's local path) so runtime translation is live on open. # library's local path) so runtime translation is live on open.
saved = prefs.get_path_mapping(str(path)) 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 # Started after the saved mapping is applied, so a volume that mapping
# already fixes is not asked about. # already fixes is not asked about.
self.relocation = RelocationCheck(adapter) self.relocation = RelocationCheck(adapter)
# Version history: record an "as I found it" baseline (deduped, so self.services = LocalServices(path)
# re-opening an unchanged library is a no-op). Best-effort. self.services.baseline()
history.ensure_baseline(path) 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): def save(self):
"""Write the library, then record the saved bytes in version history. """Write the library, then record the saved bytes in version history.
@@ -178,15 +228,7 @@ class AppState:
def _save(self): def _save(self):
outcome = self.adapter.save() outcome = self.adapter.save()
# Not every platform is versioned. A library that is more than one file commit = self.services.commit_save(self.adapter, outcome)
# 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__
)
# The swap is now on disk: what it replaced can go. After the library # 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 # write, so a failed save deletes nothing; here rather than in the save
# route, because import and path remap save too. # route, because import and path remap save too.
@@ -209,8 +251,25 @@ class AppState:
with self.mutation: with self.mutation:
if self.pending is not None and self.pending.items: if self.pending is not None and self.pending.items:
self.pending.restore() 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() 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() STATE = AppState()
+68
View File
@@ -65,6 +65,60 @@ class SaveOutcome:
tag_results: list = field(default_factory=list) 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 @dataclass
class NewTrack: class NewTrack:
"""A track to ADD to a library, described generically. """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 # For a platform that keeps its own copy of the art (Rekordbox); one that
# reads the file's tags (Traktor) ignores it. # reads the file's tags (Traktor) ignores it.
art: tuple[bytes, str] | None = None 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) @dataclass(frozen=True)
@@ -153,6 +210,11 @@ class Unsupported(AdapterError):
"""The platform cannot represent this edit at all.""" """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 @runtime_checkable
class LibraryAdapter(Protocol): class LibraryAdapter(Protocol):
"""One open library. Stateful; exactly one is loaded at a time.""" """One open library. Stateful; exactly one is loaded at a time."""
@@ -172,6 +234,7 @@ class LibraryAdapter(Protocol):
def facets(self) -> Facets: ... def facets(self) -> Facets: ...
def stats(self, playlist_count: int) -> Stats: ... def stats(self, playlist_count: int) -> Stats: ...
def playlist_tree(self) -> list[PlaylistNode]: ... def playlist_tree(self) -> list[PlaylistNode]: ...
def playlist_count(self) -> int: ...
def playlist_entries(self, node_id: str) -> list[str] | None: ... def playlist_entries(self, node_id: str) -> list[str] | None: ...
def playlist_tracks(self, node_id: str) -> list[Track] | None: ... def playlist_tracks(self, node_id: str) -> list[Track] | None: ...
def track_cues(self, track_id: str) -> TrackCues | 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: ... def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues: ...
# ---- audio / paths --------------------------------------------------- # ---- 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_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: ... def set_path_mapping(self, mapping: PathMapping) -> None: ...
# The open-time missing-files check (`core/relocate.py`): the stored volumes # 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 — # in which NO track resolves, and the mappings the user confirmed for them —
+52
View File
@@ -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})
+22 -1
View File
@@ -25,7 +25,12 @@ from pydantic import BaseModel
# `browsing` is an editable library opened only to READ alongside the loaded one # `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 # (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. # 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"] CueType = Literal["cue", "fade_in", "fade_out", "load", "loop"]
CueRole = Literal["hotcue", "memory"] CueRole = Literal["hotcue", "memory"]
@@ -87,6 +92,14 @@ class TrackCapabilities(BaseModel):
audio_formats: list[str] = [".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a"] audio_formats: list[str] = [".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a"]
artwork: bool = False artwork: bool = False
artwork_note: str | None = None 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): class PlaylistCapabilities(BaseModel):
@@ -95,6 +108,13 @@ class PlaylistCapabilities(BaseModel):
reorder: bool = False 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): class SaveCapabilities(BaseModel):
"""Structured facts, never finished sentences. """Structured facts, never finished sentences.
@@ -129,4 +149,5 @@ class Capabilities(BaseModel):
grid: GridCapabilities = GridCapabilities() grid: GridCapabilities = GridCapabilities()
tracks: TrackCapabilities = TrackCapabilities() tracks: TrackCapabilities = TrackCapabilities()
playlists: PlaylistCapabilities = PlaylistCapabilities() playlists: PlaylistCapabilities = PlaylistCapabilities()
paths: PathCapabilities = PathCapabilities()
save: SaveCapabilities save: SaveCapabilities
+5
View File
@@ -150,6 +150,11 @@ class FolderSource:
def audio_path(self, track_id: str) -> Path | None: def audio_path(self, track_id: str) -> Path | None:
return Path(track_id) if track_id in self._by_id else 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]: def playlist_tree(self) -> list[PlaylistNode]:
return [] return []
+4 -1
View File
@@ -194,6 +194,9 @@ class LibraryInfo(BaseModel):
path: str path: str
display_name: str # short label for the status bar display_name: str # short label for the status bar
version: str | None = None 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): class PlatformOption(BaseModel):
@@ -208,7 +211,7 @@ class PlatformOption(BaseModel):
platform: str platform: str
name: str name: str
library_label: str library_label: str
selects: Literal["file", "directory"] = "file" selects: Literal["file", "directory", "remote"] = "file"
installed: bool = False installed: bool = False
#: How many libraries this platform has right now; `installed` is `found > 0`. #: How many libraries this platform has right now; `installed` is `found > 0`.
found: int = 0 found: int = 0
+22
View File
@@ -54,6 +54,10 @@ class PathMapping:
return True return True
return s.startswith(self.from_prefix + os.sep) or s.startswith(self.from_prefix + "/") 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: def apply(self, os_path: Path) -> Path:
"""Rebase ``os_path`` from ``from_prefix`` onto ``to_prefix``. Returns the """Rebase ``os_path`` from ``from_prefix`` onto ``to_prefix``. Returns the
path unchanged when it doesn't match (non-matching tracks untouched).""" path unchanged when it doesn't match (non-matching tracks untouched)."""
@@ -81,3 +85,21 @@ def common_dir_prefix(paths: list[str]) -> str:
else: else:
break break
return "/".join(common) 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
+36 -6
View File
@@ -356,17 +356,14 @@ def stem_layout(path: Path | str) -> list[dict] | None:
MP3 entries in the real collection carry that element.""" MP3 entries in the real collection carry that element."""
import json import json
import av
path = Path(path) path = Path(path)
try: try:
raw = read_stem_box(path) raw = read_stem_box(path)
if raw is None: 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 [] stems = json.loads(raw).get("stems") or []
with av.open(str(path), metadata_errors="ignore") as c: streams = _audio_stream_count(path)
streams = len(c.streams.audio) except (OSError, ValueError):
except (OSError, ValueError, av.FFmpegError):
return None return None
if not stems or streams < 1 + len(stems): if not stems or streams < 1 + len(stems):
return None return None
@@ -374,6 +371,39 @@ def stem_layout(path: Path | str) -> list[dict] | None:
for i, s in enumerate(stems)] 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: def _traktor_json(v) -> str:
if isinstance(v, bool): if isinstance(v, bool):
return "true" if v else "false" return "true" if v else "false"
+16 -15
View File
@@ -341,11 +341,15 @@ def plan(adapter, export_set) -> ExportPlan:
resolved = exports.resolve(adapter, export_set) 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] 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 # The source is the adapter's file, never `Track.filepath`: that is a
# a DISPLAY path, which on Traktor omits the volume and ignores the active # 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 # path mapping — so every track off the boot volume (or on a remapped
# Windows drive) read as missing and the export was "empty". # Windows drive) read as missing and the export was "empty". Its FACTS,
sources = {t.id: adapter.audio_path(t.id) for t in tracks} # 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 # Mirror relative to the deepest shared folder, so the export carries the
# user's structure without carrying their home directory. # user's structure without carrying their home directory.
@@ -355,16 +359,10 @@ def plan(adapter, export_set) -> ExportPlan:
previous = _previous_copies(destination) previous = _previous_copies(destination)
claimed: set[Path] = set() claimed: set[Path] = set()
for track in tracks: for track in tracks:
source = sources[track.id] source = sources.get(track.id)
exists = False fact = facts.get(track.id)
size = mtime_ns = 0 exists = fact is not None
try: size, mtime_ns = (fact.size, fact.mtime_ns) if fact else (0, 0)
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
planned = PlannedTrack( planned = PlannedTrack(
track_id=track.id, track_id=track.id,
title=track.title or (source.name if source else 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 done += n
handle.progress(done=done) 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) os.replace(partial, target)
payload_tracks.append( payload_tracks.append(
ExportTrack( ExportTrack(
+34 -3
View File
@@ -123,8 +123,39 @@ def _store_path(library_id: str) -> Path:
return paths.app_data_dir() / "exports" / f"{library_id}.json" 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]: 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 raw = data.get("sets") if isinstance(data, dict) else None
out: dict[str, ExportSet] = {} out: dict[str, ExportSet] = {}
if isinstance(raw, dict): if isinstance(raw, dict):
@@ -158,8 +189,8 @@ def _targets(values: dict) -> list[str]:
def _save(library_id: str, sets: dict[str, ExportSet]) -> None: def _save(library_id: str, sets: dict[str, ExportSet]) -> None:
paths.write_json( _write_doc(
_store_path(library_id), library_id,
{"library_id": library_id, "sets": {k: v.as_dict() for k, v in sets.items()}}, {"library_id": library_id, "sets": {k: v.as_dict() for k, v in sets.items()}},
) )
+54 -9
View File
@@ -112,18 +112,19 @@ def _key(path: Path) -> str:
def _existing_files(dest) -> dict[str, str]: def _existing_files(dest) -> dict[str, str]:
"""Every audio file the destination points at → its track id. """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 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] = {} out: dict[str, str] = {}
for track in dest.tracks:
try: try:
path = dest.audio_path(track.id) facts = dest.audio_facts([t.id for t in dest.tracks])
except Exception: # noqa: BLE001 except Exception: # noqa: BLE001
path = None return out
if path is not None: for track_id, fact in facts.items():
out.setdefault(_key(path), track.id) out.setdefault(_key(Path(fact.key)), track_id)
return out return out
@@ -216,7 +217,16 @@ def _all_playlists(source) -> list[tuple[str, str]]:
return out 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: try:
target = path if path.exists() else path.parent target = path if path.exists() else path.parent
return shutil.disk_usage(target).free return shutil.disk_usage(target).free
@@ -224,6 +234,15 @@ def free_bytes(path: Path) -> int | None:
return 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: def _unique_target(folder: Path, name: str, taken: set[str]) -> Path:
"""A free filename in `folder`, suffixing on collision. """A free filename in `folder`, suffixing on collision.
@@ -298,7 +317,13 @@ def run(
""" """
destination = plan.destination destination = plan.destination
places = places_audio(dest) 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 assert destination is not None
destination.mkdir(parents=True, exist_ok=True) 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 # from it leaves the half-written file behind — which then makes the next
# attempt suffix around a file that is not really there. # attempt suffix around a file that is not really there.
created: list[Path] = [] created: list[Path] = []
# Files sent to the server, which a failure asks it to delete again.
uploaded: list[Path] = []
taken: set[str] = set() taken: set[str] = set()
moved = 0 moved = 0
@@ -333,6 +360,19 @@ def run(
elif reference: elif reference:
copied.append((planned, planned.source_path)) copied.append((planned, planned.source_path))
continue 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: else:
target = _unique_target(destination, planned.source_path.name, taken) target = _unique_target(destination, planned.source_path.name, taken)
handle.progress(message=f"Copying {planned.title}") handle.progress(message=f"Copying {planned.title}")
@@ -409,6 +449,11 @@ def run(
target.unlink(missing_ok=True) target.unlink(missing_ok=True)
except OSError: except OSError:
log.debug("could not clean up %s", target, exc_info=True) 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 raise
+238 -20
View File
@@ -15,7 +15,7 @@ from fastapi import FastAPI, File, Form, HTTPException, Query, Response, UploadF
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse 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 .app_state import STATE
from .core import auto_hotcues as ah from .core import auto_hotcues as ah
from .core import grid_detect, key_detect, structure from .core import grid_detect, key_detect, structure
@@ -30,6 +30,7 @@ from .core.adapter import (
LibraryAdapter, LibraryAdapter,
LibraryNotSupported, LibraryNotSupported,
NotFound, NotFound,
Unavailable,
Unsupported, Unsupported,
) )
from .core.capabilities import Capabilities from .core.capabilities import Capabilities
@@ -81,7 +82,9 @@ from .schemas import (
ImportRequest, ImportRequest,
JobStatus, JobStatus,
OpenCollection, OpenCollection,
OpenRemote,
OpenSource, OpenSource,
RemoteIn,
PathMappingInfo, PathMappingInfo,
PlaylistNode, PlaylistNode,
PrefixSuggestions, PrefixSuggestions,
@@ -141,7 +144,7 @@ def _adapter_error(_request, exc: AdapterError):
InvalidCommand: 400, InvalidCommand: 400,
Unsupported: 422, Unsupported: 422,
LibraryNotSupported: 400, 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)}) 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) @app.get("/api/library/path-mapping", response_model=PathMappingInfo)
def get_path_mapping() -> PathMappingInfo: def get_path_mapping() -> PathMappingInfo:
"""The current collection's saved OS-path remapping (blank if none).""" """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) driver = next((d for d in registry.drivers() if d.platform == caps.platform), None)
namer = getattr(driver, "display_name_for", None) namer = getattr(driver, "display_name_for", None)
try: 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: except OSError:
display_name = path.name 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( return LibraryInfo(
platform=caps.platform, platform=caps.platform,
name=caps.save.app_name, name=caps.save.app_name,
@@ -697,6 +871,7 @@ def _library_info() -> LibraryInfo:
path=str(STATE.path), path=str(STATE.path),
display_name=display_name, display_name=display_name,
version=caps.version, 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 # 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. # plugged-in drive, which is the real distinction a chooser is making.
out.sort(key=lambda o: (o.removable, o.name.lower())) 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 return out
@@ -743,7 +926,8 @@ def state() -> EditState:
return EditState(dirty=require_adapter().dirty, library=_library_info(), return EditState(dirty=require_adapter().dirty, library=_library_info(),
pending_stems=pending if pending and pending["tracks"] else None, pending_stems=pending if pending and pending["tracks"] else None,
stem_job=stem_job[0].id if stem_job 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) -------------------------- # ---- stem engine (download / side-load / remove) --------------------------
@@ -822,26 +1006,46 @@ def _require_no_pending_stems(what: str) -> None:
def _stem_options(body): def _stem_options(body):
from .stems import convert 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( 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, collection=body.collection, playlist_id=body.playlist_id, new_playlist=body.new_playlist,
device=prefs.load_prefs().get("stemDevice", "auto"), device=prefs.load_prefs().get("stemDevice", "auto"),
) )
def _stem_plan(body): def _stem_plan(body):
from .stems import convert from .stems import convert, remote_convert
adapter = require_adapter() adapter = require_adapter()
caps = adapter.capabilities() caps = adapter.capabilities()
if not (caps.writable and caps.tracks.stem_convertible): if not (caps.writable and caps.tracks.stem_convertible):
raise HTTPException(422, "This library cannot hold stem files") raise HTTPException(422, "This library cannot hold stem files")
try: 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) return adapter, convert.plan(adapter, body.track_ids, _stem_options(body), STATE.pending)
except convert.ConvertError as ex: except convert.ConvertError as ex:
raise HTTPException(400, str(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") @app.post("/api/tracks/stems/preview")
def preview_stem_conversion(body: StemConvert) -> dict: def preview_stem_conversion(body: StemConvert) -> dict:
"""What a conversion would do — converted, skipped (and why), disk space.""" """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) raise HTTPException(409, planned.blocked)
if not planned.items: if not planned.items:
raise HTTPException(400, "None of these tracks can be converted") 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") raise HTTPException(409, "The stem engine is not installed")
opts = _stem_options(body) opts = _stem_options(body)
def run(handle): 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, return convert.run(handle, adapter, planned, opts, STATE.pending, mutation=STATE.mutation,
still_current=lambda: STATE.adapter is adapter) still_current=lambda: STATE.adapter is adapter)
@@ -930,10 +1139,25 @@ def reload_collection() -> dict:
_require_no_pending_stems("Reloading") _require_no_pending_stems("Reloading")
if not STATE.loaded: if not STATE.loaded:
raise HTTPException(409, "No collection loaded") raise HTTPException(409, "No collection loaded")
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 STATE.open(STATE.path) # re-parse current file from disk
return {"status": "reloaded", "tracks": len(require_adapter().tracks)} 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 ------------------------------------ # ---- read: stats / facets / tracks ------------------------------------
@@ -1735,7 +1959,7 @@ def save() -> SaveResult:
def get_history() -> list[HistoryEntry]: def get_history() -> list[HistoryEntry]:
"""All saved versions of the current collection, newest first.""" """All saved versions of the current collection, newest first."""
require_adapter() 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) @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).""" reloads. The user should close Traktor first (it overwrites on exit)."""
_require_no_pending_stems("Restoring a version") _require_no_pending_stems("Restoring a version")
require_adapter() require_adapter()
data = history.read_version(STATE.path, commit_id) if not STATE.restore_version(commit_id):
if data is None:
raise HTTPException(404, f"Version not found: {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() return collection_status()
@@ -1760,7 +1978,7 @@ def restore_version(commit_id: str) -> CollectionStatus:
def clear_history() -> dict: def clear_history() -> dict:
"""Permanently delete ALL version history for the current collection.""" """Permanently delete ALL version history for the current collection."""
require_adapter() require_adapter()
history.clear_history(STATE.path) STATE.services.clear_history()
return {"status": "cleared"} return {"status": "cleared"}
@@ -2088,7 +2306,7 @@ def _folder_add_plan(body: FolderAddRequest):
@app.post("/api/folder/add/preview") @app.post("/api/folder/add/preview")
def folder_add_preview(body: FolderAddRequest) -> dict: def folder_add_preview(body: FolderAddRequest) -> dict:
_source, dest, destination, plan = _folder_add_plan(body) _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): if importer.places_audio(dest):
_placed_space(out, dest, plan, destination) _placed_space(out, dest, plan, destination)
elif body.mode == "reference": elif body.mode == "reference":
@@ -2107,7 +2325,7 @@ def folder_add(body: FolderAddRequest) -> JobStatus:
if not plan.importable and not plan.existing: if not plan.importable and not plan.existing:
raise HTTPException(400, "Nothing to add (none of those files exist)") raise HTTPException(400, "Nothing to add (none of those files exist)")
if body.mode == "copy" or importer.places_audio(dest): 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 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: if free is not None and free < needed + importer.SPACE_HEADROOM:
raise HTTPException( 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. between the preview and the import, and a stale preview is worse than none.
""" """
_source, dest, destination, plan = _import_plan(body) _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): if importer.places_audio(dest):
_placed_space(out, dest, plan, destination) _placed_space(out, dest, plan, destination)
return out return out
@@ -2189,7 +2407,7 @@ def start_import(body: ImportRequest) -> JobStatus:
source, dest, destination, plan = _import_plan(body) source, dest, destination, plan = _import_plan(body)
if not plan.importable: if not plan.importable:
raise HTTPException(400, "Nothing to import (no tracks, or none of their files exist)") 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 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: if free is not None and free < needed + importer.SPACE_HEADROOM:
raise HTTPException( raise HTTPException(
+270
View File
@@ -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)
+24
View File
@@ -221,6 +221,8 @@ class EditState(BaseModel):
stem_job: str | None = None stem_job: str | None = None
# What this open's crash recovery did about an interrupted conversion. # What this open's crash recovery did about an interrupted conversion.
stem_recovery: dict | None = None stem_recovery: dict | None = None
# A remote library's connection: {state, via, machine}. None when local.
remote: dict | None = None
# ---- collection selection ---- # ---- collection selection ----
@@ -234,12 +236,34 @@ class CollectionStatus(BaseModel):
# Identity of the loaded library, so the UI can name it without parsing the # Identity of the loaded library, so the UI can name it without parsing the
# path (a Serato library is a directory, not a file). # path (a Serato library is a directory, not a file).
library: LibraryInfo | None = None 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): class OpenCollection(BaseModel):
path: str 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): class CollectionCandidate(BaseModel):
path: str path: str
label: str # folder name, e.g. "Traktor 4.5.0" label: str # folder name, e.g. "Traktor 4.5.0"
+2
View File
@@ -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`."""
+37
View File
@@ -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())
+657
View File
@@ -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)
+101
View File
@@ -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,
)
+133
View File
@@ -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
+70
View File
@@ -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)
+216
View File
@@ -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
+18
View File
@@ -0,0 +1,18 @@
# The Konduktor SERVER (a container on the user's NAS — see server/Dockerfile).
#
# Deliberately NOT requirements.txt: the server never DECODES audio (analysis,
# waveforms and stem separation run on the computer that opened the library),
# so librosa, scikit-learn and PyAV stay out of the image. What it does is file
# IO, the native model, tags and header reads. `test_layering.py` checks that
# importing `konduktor.server` pulls none of them in.
fastapi>=0.115
uvicorn[standard]>=0.34
pydantic>=2.11
mutagen>=1.47 # tags written into the audio files at Save
numpy>=2.0 # a prepared analysis arrives as arrays (Rekordbox's ANLZ writer)
Pillow>=11 # a Rekordbox add writes the cover's artwork files
dulwich>=0.22 # version history, beside the library
platformdirs>=4.0
# From GitHub, NOT PyPI — see requirements.txt for why.
traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git
pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git
+5
View File
@@ -34,3 +34,8 @@ pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git
# The stem engine and its weights are downloaded over HTTPS by the sidecar; a # The stem engine and its weights are downloaded over HTTPS by the sidecar; a
# frozen Python on macOS has no system CA bundle of its own. # frozen Python on macOS has no system CA bundle of its own.
certifi>=2024.7 certifi>=2024.7
# Remote libraries (a Konduktor server on the user's NAS): the HTTP client the
# remote adapter speaks to it with, and the OS keychain (macOS Keychain /
# Windows Credential Manager) its password is kept in — never userprefs.json.
httpx>=0.27
keyring>=25
+1 -1
View File
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
source .venv/bin/activate source .venv/bin/activate
fail=0 fail=0
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_key_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_prefs.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py test_discard.py; do for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_key_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_prefs.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py test_discard.py test_remote_protocol.py test_remote_server.py test_remote_adapter.py test_remote_stems.py; do
echo "──────────────────────────────────────────" echo "──────────────────────────────────────────"
echo "▶ $t" echo "▶ $t"
echo "──────────────────────────────────────────" echo "──────────────────────────────────────────"
+15
View File
@@ -34,9 +34,24 @@ def _watch_parent_and_exit() -> None:
pass pass
except Exception: except Exception:
pass pass
_release_remote()
os._exit(0) os._exit(0)
def _release_remote() -> None:
"""Hand back a remote library's session on the way out, so the next
computer opens it at once instead of waiting out the lease (or being asked
to take over a laptop that has already quit). Best-effort and brief."""
try:
from konduktor.app_state import STATE
if STATE.remote is not None:
STATE.remote.stop()
STATE.remote.client.release(timeout=2.0)
except Exception:
pass
def _free_port() -> int: def _free_port() -> int:
"""Grab an unused loopback port. There's a tiny bind→close→rebind race, but """Grab an unused loopback port. There's a tiny bind→close→rebind race, but
it's harmless on 127.0.0.1 for a single local sidecar.""" it's harmless on 127.0.0.1 for a single local sidecar."""
+35
View File
@@ -95,5 +95,40 @@ for platform, module in NATIVE.items():
] ]
check(f"the {platform} adapter does import {module} somewhere", bool(own), "nowhere") check(f"the {platform} adapter does import {module} somewhere", bool(own), "nowhere")
print("== remote libraries ==")
# The remote adapter speaks a PROTOCOL; which platform the server holds is the
# server's business. Importing a platform's adapter (or its library) here would
# make a remote library quietly platform-shaped again.
remote_pkg = CORE.parent / "adapters" / "remote"
strays = []
for src in sorted(remote_pkg.rglob("*.py")):
tree = ast.parse(src.read_text())
for node in ast.walk(tree):
if isinstance(node, ast.ImportFrom):
mod = node.module or ""
if node.level and any(mod == p or mod.startswith(p + ".") for p in NATIVE):
strays.append(f"{src.name}: ..{mod}")
if not node.level and any(mod.startswith(m) for m in set(NATIVE.values())):
strays.append(f"{src.name}: {mod}")
elif isinstance(node, ast.Import):
for a in node.names:
if any(a.name.startswith(m) for m in set(NATIVE.values())):
strays.append(f"{src.name}: {a.name}")
check("the remote adapter imports no platform adapter or library", not strays, "; ".join(strays))
# The server is lightweight by decision: it never decodes audio, so importing
# it must not pull in the analysis stack (and its image ships without it).
import subprocess
probe = subprocess.run(
[sys.executable, "-c",
"import sys, konduktor.server.app; "
"print(','.join(m for m in ('librosa', 'sklearn', 'torch', 'numba', 'av') if m in sys.modules))"],
capture_output=True, text=True, cwd=str(CORE.parents[1]),
)
heavy = probe.stdout.strip()
check("the server imports no audio-analysis library", probe.returncode == 0 and not heavy,
heavy or probe.stderr[-300:])
print("\nRESULT:", "FAILED" if failed else "ALL PASSED") print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0) sys.exit(1 if failed else 0)
+8 -2
View File
@@ -36,13 +36,19 @@ def check(label, cond, detail=""):
failed = True failed = True
opts = platforms() everything = platforms()
# A remote library is offered LAST, after every platform on this computer: it is
# a way to reach a library (held by a Konduktor server), not a driver here.
opts = [p for p in everything if p.platform != "remote"]
by_name = {p.platform: p for p in opts} by_name = {p.platform: p for p in opts}
print("== /api/platforms reports the facts the platform step needs ==") print("== /api/platforms reports the facts the platform step needs ==")
check("every registered driver is offered", len(opts) == len(registry.drivers()), check("every registered driver is offered", len(opts) == len(registry.drivers()),
f"{len(opts)} of {len(registry.drivers())}") f"{len(opts)} of {len(registry.drivers())}")
check("all three platforms present", {"traktor", "rekordbox", "onelibrary"} <= set(by_name)) check("all three platforms present", {"traktor", "rekordbox", "onelibrary"} <= set(by_name))
check("Remote is offered once, after them, as a remote",
[p.platform for p in everything].count("remote") == 1 and everything[-1].platform == "remote"
and everything[-1].selects == "remote")
check("selects is per-platform, not assumed", check("selects is per-platform, not assumed",
by_name["traktor"].selects == "file" by_name["traktor"].selects == "file"
and by_name["rekordbox"].selects == "file" and by_name["rekordbox"].selects == "file"
@@ -61,7 +67,7 @@ check("ordered fixed-location first, then by name",
[p.platform for p in opts] == [p.platform for p in [p.platform for p in opts] == [p.platform for p in
sorted(opts, key=lambda o: (o.removable, o.name.lower()))], sorted(opts, key=lambda o: (o.removable, o.name.lower()))],
[p.platform for p in opts]) [p.platform for p in opts])
check("a second call gives the same order", [p.platform for p in platforms()] == [p.platform for p in opts]) check("a second call gives the same order", [p.platform for p in platforms()] == [p.platform for p in everything])
print("== /api/library/options is scoped to ONE platform ==") print("== /api/library/options is scoped to ONE platform ==")
for plat in ("traktor", "rekordbox", "onelibrary"): for plat in ("traktor", "rekordbox", "onelibrary"):
+342
View File
@@ -0,0 +1,342 @@
"""A remote library, end to end: a real server, the app's own routes.
A Konduktor server (`konduktor.server`) runs in a thread on a temp copy of the
real collection, its audio mapped onto generated MP3s; the app (`main.py`)
opens it through the picker's routes, exactly as the desktop app would. Pins:
* a remote is saved only after a handshake — a wrong password is refused with
nothing saved, and an unreachable PRIMARY falls back to the fallback;
* the remote is offered as a platform, and opens as THE library: projection,
capabilities (destination on the library, no reference, no remapping);
* edits go to the server and come back in the mirror; Save writes on the
server and touches only the edited ENTRY (the fidelity guarantee survives
the trip); a no-op save writes nothing; history lists the server's
versions; discard drops edits there;
* audio is downloaded once into the cache, by what the server says the file
is; analysis (Analyze grid) runs here on that copy and lands on the server;
* another computer taking over makes this one read-only — at the next
command, not the next heartbeat — and reopening says who holds it, offers
the takeover and names the edits left behind;
* export sets are kept by the server, and an export from the remote library
copies the audio, then re-exports copying nothing;
* importing a file UPLOADS it into a folder on the server and adds it there;
* opening a local library releases the server's session.
"""
from __future__ import annotations
import os
import shutil
import sys
import tempfile
import threading
import time
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-remote-appdata-")
os.environ.pop("KONDUKTOR_NML", None)
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
import uvicorn
from fastapi.testclient import TestClient
from konduktor import history
from konduktor import remote_protocol as rp
from konduktor.adapters.remote import config as remote_config
from konduktor.adapters.remote.client import RemoteClient
from konduktor.adapters.traktor.adapter import TraktorAdapter
from konduktor.app_state import AppState
from konduktor.core.pathmap import PathMapping
from konduktor.server.app import Server, create_app
from konduktor.server.config import ServerConfig
from konduktor.server.session import SessionLock
from stem_test_support import make_mp3
class MemoryKeychain:
def __init__(self):
self.items = {}
def get(self, account):
return self.items.get(account)
def set(self, account, password):
self.items[account] = password
def delete(self, account):
self.items.pop(account, None)
remote_config.use_password_store(MemoryKeychain())
def serve(app):
server = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=0, log_level="warning"))
thread = threading.Thread(target=server.run, daemon=True)
thread.start()
for _ in range(200):
if server.started:
break
time.sleep(0.05)
return server, server.servers[0].sockets[0].getsockname()[1]
def entry_span(data: bytes, file_name: str):
marker = f'FILE="{file_name}"'.encode()
i = data.find(marker)
return data.rfind(b"<ENTRY ", 0, i), data.find(b"</ENTRY>", i) + len(b"</ENTRY>")
with tempfile.TemporaryDirectory() as d:
root = Path(d)
work = root / "library" / "collection.nml"
work.parent.mkdir()
shutil.copy2(REAL, work)
content = (root / "music").resolve()
content.mkdir()
# Map one folder of the collection onto generated audio on the "server".
probe = TraktorAdapter(work)
by_dir: dict[Path, list[str]] = {}
for t in probe.tracks:
p = probe.audio_path(t.id)
if p is not None and p.suffix.lower() == ".mp3":
by_dir.setdefault(p.parent, []).append(t.id)
folder, ids = max(by_dir.items(), key=lambda kv: len(kv[1]))
ids = ids[:3]
mapped = content / "Mapped"
for n, tid in enumerate(ids):
make_mp3(mapped / probe.audio_path(tid).name, seconds=4, seed=n + 1)
probe_paths = {tid: probe.audio_path(tid) for tid in ids}
del probe
t = [1000.0]
cfg = ServerConfig(platform="traktor", library=work, content=content, username="dj",
password="secret", name="NAS",
path_maps=(PathMapping.make(str(folder), str(mapped)),))
srv = Server(cfg, state=AppState(), lock=SessionLock(clock=lambda: t[0]))
srv.open()
uv, port = serve(create_app(srv))
server_adapter = srv.state.adapter
import konduktor.main as main
c = TestClient(main.app)
print("== saving a remote ==")
form = {"name": "NAS", "host": "127.0.0.1:1", "fallback_host": f"127.0.0.1:{port}",
"username": "dj", "password": "wrong"}
r = c.post("/api/remotes", json=form)
check("a wrong password is refused, nothing saved",
r.status_code == 400 and "password" in r.json()["detail"]["message"].lower()
and c.get("/api/remotes").json() == [], r.text[:200])
form["password"] = "secret"
r = c.post("/api/remotes", json=form)
body = r.json()
check("the right one saves, reporting each address",
r.status_code == 200 and [x["kind"] for x in body["results"]] == ["unreachable", "ok"], r.text[:300])
remote_id = body["remote"]["id"]
check("the password is in the keychain, not prefs",
"secret" not in Path(os.environ["KONDUKTOR_DATA_DIR"], "userprefs.json").read_text())
plats = c.get("/api/platforms").json()
check("Remote is offered as a platform, last", plats[-1]["platform"] == "remote"
and plats[-1]["found"] == 1 and plats[-1]["selects"] == "remote")
print("== opening it ==")
r = c.post("/api/library/open-remote", json={"remote_id": remote_id})
status = r.json()
check("it opens as THE library", r.status_code == 200 and status["loaded"]
and status["tracks"] == len(server_adapter.tracks), r.text[:300])
check("…named as saved, reached through the fallback",
status["library"]["display_name"] == "NAS" and status["library"]["remote"]["via"] == "fallback")
caps = c.get("/api/capabilities").json()
check("its capabilities: the destination is the server's, nothing referenced, nothing remapped",
caps["writable"] and caps["tracks"]["audio_destination"] == "library"
and not caps["tracks"]["reference"] and not caps["paths"]["remappable"])
page = c.get("/api/tracks", params={"limit": 20000}).json()
check("the table reads from the mirror", page["total"] == len(server_adapter.tracks))
check("the server shows this computer holding the session",
srv.lock.describe()["machine"] == remote_config.machine_name())
print("== edits and saves ==")
target = ids[0]
file_name = probe_paths[target].name
original = work.read_bytes()
r = c.patch("/api/tracks", json={"track_id": target, "fields": {"genre": "Remote Edit"}})
check("an edit applies on the server", r.status_code == 200
and server_adapter.track(target).genre == "Remote Edit")
check("…and in the mirror", main.require_adapter().track(target).genre == "Remote Edit")
r = c.post("/api/tracks/cue", json={"track_id": target, "slot": 4, "start": 1.0, "type": "cue"})
check("a hotcue goes to the server", r.status_code == 200
and any(cu["slot"] == 4 for cu in server_adapter.track_cues(target).model_dump()["cues"]), r.text[:200])
check("the state says unsaved", c.get("/api/state").json()["dirty"] is True)
versions = len(history.list_history(work))
r = c.post("/api/save").json()
saved = work.read_bytes()
check("save writes on the server", r["saved"] and saved != original)
s0, e0 = entry_span(original, file_name)
s1, e1 = entry_span(saved, file_name)
check("…changing nothing outside the edited ENTRY",
original[:s0] == saved[:s1] and original[e0:] == saved[e1:])
check("…and is versioned there", len(history.list_history(work)) == versions + 1
and len(c.get("/api/history").json()) == versions + 1)
r = c.post("/api/save").json()
check("a no-op save writes nothing", r["saved"] is False and work.read_bytes() == saved)
c.patch("/api/tracks", json={"track_id": target, "fields": {"genre": "Throw away"}})
r = c.post("/api/discard")
check("discard drops the edit on the server", r.status_code == 200 and not server_adapter.dirty
and server_adapter.track(target).genre == "Remote Edit"
and main.require_adapter().track(target).genre == "Remote Edit", r.text[:200])
print("== version history, on the server ==")
listed = c.get("/api/history").json()
oldest = listed[-1]["id"]
r = c.post(f"/api/history/{oldest}/restore")
check("restoring a version writes it back ON THE SERVER", r.status_code == 200
and work.read_bytes() == original, r.text[:200])
check("…as a new version", len(c.get("/api/history").json()) == len(listed) + 1)
server_adapter = srv.state.adapter # a restore reopens the library there
check("…and the mirror follows", main.require_adapter().track(target).genre
== server_adapter.track(target).genre)
# Back to the edited state, for what follows.
c.patch("/api/tracks", json={"track_id": target, "fields": {"genre": "Remote Edit"}})
c.post("/api/save")
print("== audio, on this computer ==")
adapter = main.require_adapter()
downloads = []
real_download = adapter.client.download
adapter.client.download = lambda *a, **k: (downloads.append(a[0]), real_download(*a, **k))[1]
r = c.get("/api/tracks/audio", params={"track_id": target})
served = (mapped / file_name).read_bytes()
check("the deck's audio is the server's file", r.status_code == 200 and r.content == served)
c.get("/api/tracks/audio", params={"track_id": target})
check("…downloaded once, then served from the cache", downloads == [target], downloads)
cached = adapter.cached_audio(target)
check("the cache keys it by what the server says the file is",
cached is not None and cached.read_bytes() == served and cached.suffix == ".mp3")
r = c.post("/api/tracks/grid/auto", json={"track_id": target})
grid = server_adapter.track_cues(target).grid_markers
check("Analyze runs here and the grid lands on the server",
r.status_code == 200 and grid and abs(grid[0].bpm - 120) < 1.5, r.text[:200])
check("…with no second download", downloads == [target], downloads)
c.post("/api/save")
print("== export, from the server's library ==")
dest = root / "stick"
r = c.post("/api/exports", json={"name": "Gig", "targets": ["traktor"], "destination": str(dest)})
set_id = r.json().get("id")
c.post(f"/api/exports/{set_id}/add", json={"track_ids": ids})
doc = c.get("/api/exports").json()
check("an export set is created", set_id and any(s["id"] == set_id for s in doc), r.text[:300])
import httpx
kept = httpx.get(f"http://127.0.0.1:{port}/v1/export-sets", auth=("dj", "secret")).json()
check("…and kept by the server", set_id in kept["sets"], kept)
def run_export():
job = c.post(f"/api/exports/{set_id}/run").json()
for _ in range(600):
j = c.get(f"/api/jobs/{job['id']}").json()
if j["state"] != "running":
return j
time.sleep(0.05)
return j
downloads.clear()
job = run_export()
copies = sorted(p for p in (dest / "Contents").rglob("*.mp3"))
check("the export copies every track's audio onto the stick",
job["state"] == "done" and len(copies) == len(ids), job.get("error"))
check("…downloading only what the cache lacked", sorted(downloads) == sorted(ids[1:]), downloads)
inodes = {p: p.stat().st_ino for p in copies}
downloads.clear()
job = run_export()
check("a re-export copies nothing", job["state"] == "done"
and all(p.stat().st_ino == i for p, i in inodes.items()) and downloads == [], downloads)
print("== importing: an upload into the server ==")
incoming = make_mp3(root / "laptop" / "Brand New.mp3", seconds=3, seed=9)
# The folder-add path: a folder of loose files on THIS computer.
c.get("/api/folder/tracks", params={"path": str(incoming.parent)}) # the scan the add reads
add = {"track_ids": [str(incoming)], "mode": "copy", "destination": str(mapped / "Incoming")}
r = c.post("/api/folder/add/preview", json=add)
check("(preview) adding a local file to the remote library, space read from the server",
r.status_code == 200 and r.json()["free_bytes"], r.text[:300])
job = c.post("/api/folder/add", json=add).json()
for _ in range(400):
j = c.get(f"/api/jobs/{job['id']}").json()
if j["state"] != "running":
break
time.sleep(0.05)
landed = mapped / "Incoming" / "Brand New.mp3"
check("the file is uploaded into the chosen folder ON THE SERVER",
j["state"] == "done" and landed.read_bytes() == incoming.read_bytes(), j.get("error"))
added = [tr for tr in server_adapter.tracks if (tr.filepath or "").endswith("Brand New.mp3")]
check("…and added to the server's library", len(added) == 1)
from konduktor.adapters.traktor.locations import os_path_to_location
stored = "".join(os_path_to_location(folder / "Incoming" / "Brand New.mp3"))
check("…stored as the collection stores every other path (the mapping, inverted)",
added and added[0].id == stored, added[0].id if added else None)
check("…and still resolving to the uploaded file", added and server_adapter.audio_path(added[0].id) == landed)
check("…and to the mirror here", any((tr.filepath or "").endswith("Brand New.mp3")
for tr in main.require_adapter().tracks))
print("== another computer takes over ==")
other = RemoteClient(remote_config.Remote(id="o", name="NAS", host=f"127.0.0.1:{port}", username="dj"), "secret")
other.acquire("other-client", "Studio iMac", takeover=True)
other.rpc("set_track_metadata", track_id=ids[1], fields={"comment": "from the studio"})
r = c.patch("/api/tracks", json={"track_id": target, "fields": {"genre": "Too late"}})
check("this computer's next command is refused, naming who took it",
r.status_code == 503 and "Studio iMac" in r.json()["detail"], r.text[:200])
st = c.get("/api/state").json()
check("…and it is read-only now, at once", st["remote"]["state"] == "taken_over"
and st["remote"]["machine"] == "Studio iMac")
caps = c.get("/api/capabilities").json()
check("…through its capabilities", not caps["writable"] and caps["readonly_cause"] == "taken_over")
check("the server still has the genre this computer saved", server_adapter.track(target).genre == "Remote Edit")
r = c.post("/api/library/open-remote", json={"remote_id": remote_id})
check("reopening says who holds it", r.status_code == 409
and r.json()["detail"]["machine"] == "Studio iMac", r.text[:200])
r = c.post("/api/library/open-remote", json={"remote_id": remote_id, "takeover": True})
pending = r.json().get("pending_edits")
check("taking it back names the edits the other computer left",
r.status_code == 200 and pending and pending["machine"] == "Studio iMac", r.text[:300])
check("…which the mirror shows", main.require_adapter().track(ids[1]).comment == "from the studio")
other.close()
print("== the server forgets the session (a restart) ==")
c.post("/api/save") # nobody's edits pending, as after a real restart
srv.lock = SessionLock(clock=lambda: t[0])
main.STATE.remote.beat()
d = c.get("/api/state").json()["remote"]
h = srv.lock.holder()
check("the session is taken back without asking, and the user told",
d["state"] == "connected" and d["notices"] == 1 and d["notice"]
and h is not None and h.machine == remote_config.machine_name(), d)
r = c.patch("/api/tracks", json={"track_id": target, "fields": {"comment": "after restart"}})
check("…and edits go through again", r.status_code == 200
and server_adapter.track(target).comment == "after restart", r.text[:200])
print("== leaving ==")
local = root / "local.nml"
shutil.copy2(REAL, local)
r = c.post("/api/library/open", json={"path": str(local)})
check("opening a local library releases the server's session",
r.status_code == 200 and srv.lock.holder() is None, r.text[:200])
uv.should_exit = True
print()
print("RESULT:", "FAILURES" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+133
View File
@@ -0,0 +1,133 @@
"""The wire contract between a Konduktor server and the app (`remote_protocol.py`).
Pure: no library, no network. Pins what would go wrong SILENTLY:
* every member of `LibraryAdapter` is either an RPC or excluded with a reason
— a command added to the protocol later cannot be quietly missing from
remote libraries (the remote adapter would raise AttributeError mid-edit);
* every command is MUTATING — one that was not would skip the session check,
letting a displaced computer keep editing;
* arguments and results survive JSON by the protocol's own types (tuples,
dataclasses, pydantic models, `None`), and a misspelt argument is refused;
* a prepared analysis (waveform, grid, key) crosses intact;
* the version rule: same major, server minor ≥ client's.
"""
from __future__ import annotations
import json
import sys
import warnings
warnings.filterwarnings("ignore")
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
import numpy as np
from konduktor import remote_protocol as rp
from konduktor.core import waveform
from konduktor.core.adapter import AudioFacts, PreparedAnalysis
from konduktor.core.model import AutoHotcue, GridMarker, Track, TrackCues
print("== coverage ==")
members = rp.protocol_members()
missing = members - set(rp.RPC) - set(rp.EXCLUDED)
check("every protocol member is an RPC or excluded", not missing, sorted(missing))
stray = (set(rp.RPC) | set(rp.EXCLUDED)) - members
check("…and nothing is listed that the protocol lacks", not stray, sorted(stray))
check("no member is both", not (set(rp.RPC) & set(rp.EXCLUDED)))
check("every exclusion says why", all(len(r) > 10 for r in rp.EXCLUDED.values()))
VERBS = ("set_", "create_", "delete_", "rename_", "add_", "remove_", "move_", "replace_", "place_", "apply_")
commands = {m for m in members if m.startswith(VERBS)}
unguarded = {m for m in commands if m in rp.RPC and not rp.RPC[m].mutating}
check("every command that travels needs the session", not unguarded, sorted(unguarded))
reads = {"tracks", "track", "track_cues", "query_tracks", "capabilities", "audio_facts", "dirty"}
check("reads do not", all(not rp.RPC[m].mutating for m in reads))
for name in rp.RPC:
try:
rp._params(name)
rp._adapter(rp._result_hint(name))
except Exception as ex: # noqa: BLE001
check(f"{name}: types resolve", False, repr(ex))
print("== round trips ==")
def through_json(name, args):
wire = json.loads(json.dumps({"args": rp.dump_args(name, args)}))
return rp.load_args(name, wire["args"])
got = through_json("set_cue", {"track_id": "a", "slot": 2, "start_sec": 1.5, "cue_type": "loop",
"length_sec": 4.0, "name": None})
check("set_cue's arguments survive", got == {"track_id": "a", "slot": 2, "start_sec": 1.5,
"cue_type": "loop", "length_sec": 4.0, "name": None}, got)
got = through_json("replace_grid", {"track_id": "a", "markers": [(0.1, 128.0), (60.0, 130.0)]})
check("a grid's (start, bpm) tuples survive", got["markers"] == [(0.1, 128.0), (60.0, 130.0)], got)
cue = AutoHotcue(slot=1, start=12.0, name="Drop")
got = through_json("place_cues", {"track_id": "a", "cues": [cue], "overwrite": True})
check("place_cues gets AutoHotcue objects back", isinstance(got["cues"][0], AutoHotcue)
and got["cues"][0].start == 12.0 and got["overwrite"] is True, got)
got = through_json("query_tracks", {"q": "acid", "bpm_min": 120.0, "limit": 5})
check("query_tracks' keywords survive", got == {"q": "acid", "bpm_min": 120.0, "limit": 5}, got)
try:
rp.load_args("track", {"track_id": "a", "trak_id": "b"})
check("a misspelt argument is refused", False)
except ValueError:
check("a misspelt argument is refused", True)
try:
rp.load_args("set_cue", {"track_id": "a"})
check("a missing argument is refused", False)
except ValueError:
check("a missing argument is refused", True)
facts = {"t1": AudioFacts(key="/music/a.mp3", size=10, mtime_ns=123)}
back = rp.load_result("audio_facts", json.loads(json.dumps(rp.dump_result("audio_facts", facts))))
check("audio facts survive as dataclasses", back == facts, back)
cues = TrackCues(track_id="t1", grid_markers=[GridMarker(start=0.1, bpm=128)])
back = rp.load_result("track_cues", json.loads(json.dumps(rp.dump_result("track_cues", cues))))
check("TrackCues survive", back == cues)
check("None survives", rp.load_result("track", rp.dump_result("track", None)) is None)
t = Track(id="x", title="T")
check("a Track survives", rp.load_result("track", rp.dump_result("track", t)) == t)
print("== a prepared analysis ==")
rng = np.random.default_rng(1)
measured = waveform.Analysis(
columns=waveform.Columns(rms=rng.random(400).astype(np.float32),
brightness=rng.random(400).astype(np.float32), duration=181.5),
frames=waveform.Frames(bands=rng.random((27225, 3)).astype(np.float32), duration=181.5),
)
packed = rp.pack_analysis(PreparedAnalysis(measured=measured, markers=[GridMarker(start=0.25, bpm=124.0)]))
back = rp.unpack_analysis(packed)
check("columns, frames and durations cross intact",
np.array_equal(back.measured.columns.rms, measured.columns.rms)
and np.array_equal(back.measured.frames.bands, measured.frames.bands)
and back.measured.duration == 181.5)
check("…and the detected grid", [(m.start, m.bpm) for m in back.markers] == [(0.25, 124.0)])
check("…with no key when none was detected", back.key is None)
from konduktor.core.key_detect import KeyResult
key = KeyResult(pitch_class=9, mode="minor", wheel=8, confidence=0.83)
back = rp.unpack_analysis(rp.pack_analysis(PreparedAnalysis(measured=measured, key=key)))
check("…and the detected key", back.key == key, back.key)
check("no analysis is None", rp.pack_analysis(None) is None and rp.unpack_analysis(None) is None)
print("== versions ==")
check("same version talks", rp.compatible((1, 0), (1, 0)) is None)
check("a newer server minor talks", rp.compatible((1, 0), (1, 3)) is None)
check("an older server minor: update the server", rp.compatible((1, 2), (1, 1)) == "server")
check("a newer server major: update the app", rp.compatible((1, 0), (2, 0)) == "app")
check("an older server major: update the server", rp.compatible((2, 0), (1, 9)) == "server")
print()
print("RESULT:", "FAILURES" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+259
View File
@@ -0,0 +1,259 @@
"""The Konduktor SERVER (`konduktor.server`), through its own routes.
A library held on the user's NAS and opened from the desktop app as a "Remote".
Run against a temp copy of the real collection, with a FAKE clock for the
session lease. Pins the things that would fail quietly or dangerously:
* every route needs the one account — a wrong password is a 401, not a
read-only view;
* ONE computer at a time: a command without the session token is refused
(423), a second computer is told who holds it (409) and may take over,
after which the first one's token is dead; a lease that ran out frees the
session, and the SAME computer coming back renews it silently;
* the edits a computer leaves behind are offered to the next one, named;
* Save writes and versions ON THE SERVER; Discard drops the edits;
* the folder browser and uploads cannot leave the content folder (`..`, a
symlink), an upload never overwrites, and a session can only delete what
it uploaded;
* audio streams with Range; a track added from an upload plays.
* the configuration refuses a missing password, a wrong platform and a
malformed path map with one clear line.
"""
from __future__ import annotations
import os
import shutil
import sys
import tempfile
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-server-appdata-")
os.environ.pop("KONDUKTOR_NML", None)
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
from fastapi.testclient import TestClient
from konduktor import history
from konduktor import remote_protocol as rp
from konduktor.app_state import AppState
from konduktor.server.app import Server, create_app
from konduktor.server.config import ConfigError, ServerConfig, from_env, parse_path_maps
from konduktor.server.session import SessionLock
from stem_test_support import make_mp3
print("== configuration ==")
with tempfile.TemporaryDirectory() as d:
lib = Path(d) / "collection.nml"
lib.write_text("x")
content = Path(d) / "music"
content.mkdir()
base = {"KONDUKTOR_PLATFORM": "traktor", "KONDUKTOR_LIBRARY": str(lib),
"KONDUKTOR_CONTENT": str(content), "KONDUKTOR_USERNAME": "dj",
"KONDUKTOR_PASSWORD": "pw"}
def refused(env, needle):
try:
from_env(env)
except ConfigError as ex:
return needle in str(ex)
return False
check("a complete environment parses", from_env(base).content == content.resolve())
check("an empty password is refused", refused({**base, "KONDUKTOR_PASSWORD": ""}, "PASSWORD"))
check("an unknown platform is refused", refused({**base, "KONDUKTOR_PLATFORM": "serato"}, "PLATFORM"))
check("a missing content folder is refused",
refused({**base, "KONDUKTOR_CONTENT": str(Path(d) / "nope")}, "CONTENT"))
check("a malformed path map is refused", refused({**base, "KONDUKTOR_PATH_MAP": "/a -> /b"}, "PATH_MAP"))
maps = parse_path_maps("/Users/ben/Music => /music ; X: => /ssd")
check("several path maps parse, in order",
[(m.from_prefix, m.to_prefix) for m in maps] == [("/Users/ben/Music", "/music"), ("X:", "/ssd")])
print("== the server ==")
with tempfile.TemporaryDirectory() as d:
work = Path(d) / "library" / "collection.nml"
work.parent.mkdir()
shutil.copy2(REAL, work)
original = work.read_bytes()
content = (Path(d) / "music").resolve()
content.mkdir()
outside = Path(d) / "outside"
outside.mkdir()
(content / "Sneaky").symlink_to(outside)
(content / "Crates").mkdir()
cfg = ServerConfig(platform="traktor", library=work, content=content,
username="dj", password="secret", name="NAS")
t = [1000.0]
server = Server(cfg, state=AppState(), lock=SessionLock(clock=lambda: t[0]))
wrong = ServerConfig(**{**cfg.__dict__, "platform": "rekordbox"})
try:
Server(wrong, state=AppState()).open()
check("a platform that does not match the library file is refused", False)
except ConfigError as ex:
check("a platform that does not match the library file is refused", "Traktor" in str(ex), str(ex))
server.open()
app = create_app(server)
c = TestClient(app)
c.auth = ("dj", "secret")
anon = TestClient(app)
check("no credentials → 401", anon.get("/v1/hello").status_code == 401)
check("a wrong password → 401",
TestClient(app).get("/v1/hello", auth=("dj", "nope")).status_code == 401)
hello = c.get("/v1/hello").json()
check("hello names the API version, platform and library",
hello["api_version"] == list(rp.API_VERSION) and hello["platform"] == "traktor"
and hello["name"] == "NAS" and hello["library_id"], hello)
check("…nobody holds it yet, nothing is unsaved",
hello["holder"] is None and hello["dirty"] is False and hello["pending_edits"] is None)
def call(name, token=None, **args):
headers = {rp.SESSION_HEADER: token} if token else {}
return c.post(f"/v1/rpc/{name}", json={"args": rp.dump_args(name, args)}, headers=headers)
adapter = server.state.adapter
r = call("tracks")
check("the projection reads without a session",
r.status_code == 200 and len(r.json()["result"]) == len(adapter.tracks))
caps = call("capabilities").json()["result"]
check("capabilities say: destination on the library, no reference, no remapping",
caps["tracks"]["audio_destination"] == "library" and caps["tracks"]["reference"] is False
and caps["paths"]["remappable"] is False, caps["tracks"])
check("an unknown argument is refused, not ignored",
c.post("/v1/rpc/track", json={"args": {"track_id": "x", "trak": 1}}).status_code == 400)
track = next(t for t in adapter.tracks if t.genre)
r = call("set_track_metadata", track_id=track.id, fields={"genre": "Remote"})
check("a command without the session → 423", r.status_code == 423, r.text[:120])
print("== one computer at a time ==")
a = c.post("/v1/session/acquire", json={"client_id": "A", "machine": "Laptop"}).json()
r = c.post("/v1/session/acquire", json={"client_id": "B", "machine": "Studio"})
check("a second computer is told who holds it",
r.status_code == 409 and r.json()["detail"]["machine"] == "Laptop", r.text[:160])
r = call("set_track_metadata", a["token"], track_id=track.id, fields={"genre": "Remote"})
body = r.json()
check("the holder's command applies and returns the changed track",
r.status_code == 200 and body["changed"][0]["genre"] == "Remote" and body["rev"] == 1, r.text[:200])
pending = c.get("/v1/hello", params={"client_id": "B"}).json()["pending_edits"]
check("another computer is told whose unsaved edits these are",
pending and pending["machine"] == "Laptop" and "track" in pending["summary"], pending)
check("…but the computer that made them is not",
c.get("/v1/hello", params={"client_id": "A"}).json()["pending_edits"] is None)
b = c.post("/v1/session/acquire", json={"client_id": "B", "machine": "Studio", "takeover": True}).json()
check("a takeover hands over the edits too", b["pending_edits"]["machine"] == "Laptop", b)
r = call("set_track_metadata", a["token"], track_id=track.id, fields={"genre": "Late"})
check("the displaced computer's token is dead (423, naming the new holder)",
r.status_code == 423 and r.json()["detail"]["holder"]["machine"] == "Studio", r.text[:160])
hb = c.post("/v1/session/heartbeat", json={}, headers={rp.SESSION_HEADER: a["token"]})
check("…and its heartbeat says so", hb.status_code == 423)
c.post("/v1/session/heartbeat", json={"batch": "grid-analysis"}, headers={rp.SESSION_HEADER: b["token"]})
r = c.post("/v1/session/acquire", json={"client_id": "C", "machine": "Phone"})
check("the holder's running batch is named to whoever asks",
r.status_code == 409 and r.json()["detail"]["batch"] == "grid-analysis", r.text[:160])
t[0] += rp.LEASE_SECONDS + 1
r = c.post("/v1/session/acquire", json={"client_id": "C", "machine": "Phone"})
check("an expired lease frees the session without a takeover", r.status_code == 200, r.text[:160])
cc = r.json()
t[0] += rp.LEASE_SECONDS * 3
hb = c.post("/v1/session/heartbeat", json={}, headers={rp.SESSION_HEADER: cc["token"]})
check("the same computer coming back renews its lease silently", hb.status_code == 200, hb.text[:160])
tok = cc["token"]
print("== save / discard / history ==")
versions = len(history.list_history(work))
r = c.post("/v1/save", headers={rp.SESSION_HEADER: tok}).json()
check("save writes the library on the server", r["saved"] and work.read_bytes() != original, r)
check("…and versions it there", len(history.list_history(work)) == versions + 1)
check("…and nobody's edits are pending afterwards",
c.get("/v1/hello", params={"client_id": "Z"}).json()["pending_edits"] is None)
saved = work.read_bytes()
call("set_track_metadata", tok, track_id=track.id, fields={"genre": "Throw away"})
check("(setup) a second edit is unsaved", c.get("/v1/hello").json()["dirty"])
c.post("/v1/discard", headers={rp.SESSION_HEADER: tok})
check("discard drops it", not c.get("/v1/hello").json()["dirty"]
and call("track", track_id=track.id).json()["result"]["genre"] == "Remote")
check("…and leaves the file as saved", work.read_bytes() == saved)
listed = c.get("/v1/history").json()
check("history lists the server's versions", len(listed) == versions + 1)
print("== the content folder ==")
r = c.get("/v1/fs/list")
names = [e["name"] for e in r.json()["entries"]]
check("the browser starts at the content folder", r.json()["path"] == str(content) and "Crates" in names)
check("`..` cannot leave it", c.get("/v1/fs/list", params={"path": str(content / "..")}).status_code == 400)
check("nor can a symlink", c.get("/v1/fs/list", params={"path": str(content / "Sneaky")}).status_code == 400)
check("free space is reported", c.get("/v1/fs/space", params={"path": str(content / "New")}).json()["free"] > 0)
print("== uploads ==")
mp3 = make_mp3(Path(d) / "src" / "Kick Tune.mp3")
data = mp3.read_bytes()
up = lambda name, folder: c.post("/v1/upload", params={"dir": folder, "name": name},
content=data, headers={rp.SESSION_HEADER: tok})
r1 = up("Kick Tune.mp3", str(content / "Crates" / "New"))
r2 = up("Kick Tune.mp3", str(content / "Crates" / "New"))
p1, p2 = Path(r1.json()["path"]), Path(r2.json()["path"])
check("an upload lands in the chosen folder (created)", p1 == content / "Crates" / "New" / "Kick Tune.mp3"
and p1.read_bytes() == data, r1.text[:200])
check("a second upload of the same name never overwrites", p2.name == "Kick Tune-2.mp3")
check("no partial is left behind", not list((content / "Crates" / "New").glob(".*")))
check("an upload outside the content folder is refused", up("x.mp3", str(outside)).status_code == 400)
check("a name that hides or climbs is refused", up("../x.mp3", str(content)).status_code == 400
or up(".x.mp3", str(content)).status_code == 400)
check("without the session, refused", c.post("/v1/upload", params={"dir": str(content), "name": "y.mp3"},
content=data).status_code == 423)
r = c.delete("/v1/upload", params={"path": str(p2)}, headers={rp.SESSION_HEADER: tok})
check("a session deletes what it uploaded", r.status_code == 200 and not p2.exists(), r.text[:160])
keep = content / "Crates" / "mine.mp3"
keep.write_bytes(b"user's")
r = c.delete("/v1/upload", params={"path": str(keep)}, headers={rp.SESSION_HEADER: tok})
check("…and nothing else", r.status_code == 403 and keep.exists())
print("== adding an uploaded track, and its audio ==")
from konduktor.core.model import Track
wire = rp.WireNewTrack(track=Track(id="", title="Kick Tune", artist="Tester"), audio_path=str(p1))
r = c.post("/v1/rpc/add_tracks", json={"args": {"items": [wire.model_dump(mode="json")]}},
headers={rp.SESSION_HEADER: tok})
ids = r.json()["result"] if r.status_code == 200 else []
check("an uploaded file is added by the ordinary add_tracks",
len(ids) == 1 and r.json()["changed"][0]["title"] == "Kick Tune", r.text[:300])
if ids:
whole = c.get("/v1/audio", params={"track_id": ids[0]})
check("its audio streams", whole.status_code == 200 and whole.content == data
and int(whole.headers["X-Konduktor-Size"]) == len(data))
part = c.get("/v1/audio", params={"track_id": ids[0]}, headers={"Range": "bytes=10-19"})
check("…with Range", part.status_code == 206 and part.content == data[10:20])
facts = call("audio_facts", track_ids=ids).json()["result"]
check("its facts name the server's file", facts[ids[0]]["key"] == str(p1))
r = c.delete("/v1/upload", params={"path": str(p1)}, headers={rp.SESSION_HEADER: tok})
check("an upload the library now names is not deleted", r.status_code == 409 and p1.exists())
print("== export sets ==")
doc = {"sets": {"s1": {"name": "Gig", "targets": ["traktor"], "destination": "/Volumes/STICK",
"playlist_ids": [], "track_ids": []}}}
check("export sets need the session to change",
c.put("/v1/export-sets", json=doc).status_code == 423)
c.put("/v1/export-sets", json=doc, headers={rp.SESSION_HEADER: tok})
got = c.get("/v1/export-sets").json()
check("…and are kept by the server, keyed by its library id",
got["sets"]["s1"]["name"] == "Gig" and got["library_id"] == hello["library_id"], got)
c.post("/v1/session/release", headers={rp.SESSION_HEADER: tok})
check("release frees the session", c.get("/v1/hello").json()["holder"] is None)
check("the original collection beside the tests was never touched", REAL.exists())
print()
print("RESULT:", "FAILURES" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+235
View File
@@ -0,0 +1,235 @@
"""Convert to Stems on a REMOTE library, with a FAKE engine.
A Konduktor server runs in a thread on a temp copy of the real collection whose
playlisted tracks point at generated MP3s on "the server"; the app converts
through its own routes. The server never decodes audio, so this pins the split:
* the server plans (targets, skips) and this computer reports what it must
download and upload, and the room it needs here;
* a Replace batch separates HERE, uploads, and the SERVER publishes, parks
the original and swaps the entry — its saved collection untouched until
Save, which deletes the parked original there; Discard puts it back;
* Cancel deletes what the run uploaded, and nothing else;
* another computer taking over mid-batch loses no separation: the uploaded,
verified stem file stays on the server and the next run reuses it without
the engine.
"""
from __future__ import annotations
import os
import shutil
import sys
import tempfile
import threading
import time
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-remotestems-appdata-")
os.environ.pop("KONDUKTOR_NML", None)
import uvicorn # noqa: E402
from fastapi.testclient import TestClient # noqa: E402
import konduktor.main as main # noqa: E402
from konduktor.adapters.remote import config as remote_config # noqa: E402
from konduktor.adapters.remote.client import RemoteClient # noqa: E402
from konduktor.adapters.traktor.locations import os_path_to_location # noqa: E402
from konduktor.adapters.traktor.store import TraktorStore # noqa: E402
from konduktor.app_state import AppState # noqa: E402
from konduktor.core import stem_file as sf # noqa: E402
from konduktor.server.app import Server, create_app # noqa: E402
from konduktor.server.config import ServerConfig # noqa: E402
from konduktor.stems import convert as convert_mod # noqa: E402
from konduktor.stems import engine_manager as em # noqa: E402
from konduktor.stems import remote_convert # noqa: E402
from konduktor.stems.pending import parked_name, partial_name # noqa: E402
from stem_test_support import install_fake_engine, make_mp3 # noqa: E402
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
class MemoryKeychain(dict):
def get(self, account): # noqa: D401
return dict.get(self, account)
def set(self, account, password):
self[account] = password
def delete(self, account):
self.pop(account, None)
remote_config.use_password_store(MemoryKeychain())
ROOT = Path(tempfile.mkdtemp(prefix="konduktor-remotestems-"))
em._DEFAULT = install_fake_engine(ROOT / "engine")
# ---- a server library: playlisted tracks pointed at generated MP3s -------------------
music = (ROOT / "server" / "Music").resolve()
music.mkdir(parents=True)
work = ROOT / "server" / "collection.nml"
shutil.copy2(REAL, work)
st = TraktorStore(work)
in_pl = {k for n in st._iter_nodes(st._root()) if n.playlist for k in st._entry_keys_of(n.playlist)}
entries = [e for e in st._nml.collection.entry if e.location and st._key_of(e) in in_pl and e.stems is None][:5]
ids = []
for n, e in enumerate(entries):
path = make_mp3(music / f"Track {n}.mp3", seed=n + 1)
old = st._key_of(e)
e.location.volume, e.location.dir, e.location.file = os_path_to_location(path)
new = st._key_of(e)
for node in st._iter_nodes(st._root()):
for pe in (node.playlist.entry if node.playlist else None) or []:
if pe.primarykey and pe.primarykey.key == old:
pe.primarykey.key = new
st._entry_by_key = {st._key_of(x): x for x in st._nml.collection.entry if x.location}
e.cue_v2 = []
st.set_hotcue(new, 1, 1.0, 0, name="Drop")
st.replace_grid(new, [(0.5, 120.0)])
ids.append(new)
st.save()
del st
cfg = ServerConfig(platform="traktor", library=work, content=music, username="dj", password="pw", name="NAS")
srv = Server(cfg, state=AppState())
srv.open()
uv = uvicorn.Server(uvicorn.Config(create_app(srv), host="127.0.0.1", port=0, log_level="warning"))
threading.Thread(target=uv.run, daemon=True).start()
while not uv.started:
time.sleep(0.05)
port = uv.servers[0].sockets[0].getsockname()[1]
def wait(c, jid, timeout=120):
end = time.time() + timeout
while time.time() < end:
j = c.get(f"/api/jobs/{jid}").json()
if j["state"] != "running":
return j
time.sleep(0.05)
raise AssertionError("job did not finish")
with TestClient(main.app) as c:
remote_id = c.post("/api/remotes", json={"name": "NAS", "host": f"127.0.0.1:{port}",
"username": "dj", "password": "pw"}).json()["remote"]["id"]
r = c.post("/api/library/open-remote", json={"remote_id": remote_id})
assert r.status_code == 200, r.text
server_adapter = srv.state.adapter
print("== the plan: the server's, plus this computer's ==")
p = c.post("/api/tracks/stems/preview", json={"track_ids": ids[:1], "mode": "replace"}).json()
check("one track to convert, its target beside it on the server",
len(p["convert"]) == 1 and p["convert"][0]["target"] == str(music / "Track 0.stem.m4a"), p)
check("…and what must cross the network", p["transfer"]["download"] > 0 and p["transfer"]["upload"] > 0,
p.get("transfer"))
check("…and the room needed on BOTH machines",
any(s["volume"] == "this computer" for s in p["space"])
and any(s["volume"].startswith("the server") for s in p["space"]), p["space"])
print("== a Replace batch ==")
saved_bytes = work.read_bytes()
r = c.post("/api/tracks/stems/convert", json={"track_ids": ids[:1], "mode": "replace"})
job = wait(c, r.json()["id"])
res = job.get("result") or {}
target = music / "Track 0.stem.m4a"
check("the job converts the track", job["state"] == "done" and len(res.get("converted", [])) == 1,
job.get("error") or res)
check("the stem file is on the server, the original parked beside it",
target.is_file() and sf.is_stem_file(target) and parked_name(music / "Track 0.mp3").is_file())
new_id = res.get("renamed", {}).get(ids[0])
check("the server's entry now names the stem file", new_id and server_adapter.track(new_id) is not None)
check("…and the mirror here follows", main.require_adapter().track(new_id) is not None)
check("the SAVED collection is untouched until Save", work.read_bytes() == saved_bytes)
st_ = c.get("/api/state").json()
check("the state reports the conversion awaiting Save (from the server's ledger)",
st_["pending_stems"] and st_["pending_stems"]["tracks"] == 1, st_.get("pending_stems"))
check("…and blocks what would save or drop it", c.post("/api/reload").status_code == 409)
c.post("/api/save")
check("Save deletes the parked original on the server",
not parked_name(music / "Track 0.mp3").exists() and target.is_file())
check("…and the ledger is clear", not (c.get("/api/state").json()["pending_stems"] or {}).get("tracks"))
print("== playing a remote stem file ==")
layout = c.get("/api/tracks/stems", params={"track_id": new_id})
stems = layout.json().get("stems") if layout.status_code == 200 else None
check("the deck is offered the stem file's four stems",
isinstance(stems, list) and len(stems) == 4, layout.text[:200])
one = c.get("/api/tracks/audio", params={"track_id": new_id, "stem": 1})
check("…and each streams, extracted HERE from the downloaded file",
one.status_code == 200 and len(one.content) > 1000, one.status_code)
print("== Discard puts it back ==")
r = c.post("/api/tracks/stems/convert", json={"track_ids": [ids[1]], "mode": "replace"})
job = wait(c, r.json()["id"])
check("(setup) a second conversion", job["state"] == "done" and (music / "Track 1.stem.m4a").is_file(),
job.get("error"))
c.post("/api/discard")
check("Discard restores the original and removes the stem file, on the server",
(music / "Track 1.mp3").is_file() and not (music / "Track 1.stem.m4a").exists()
and not parked_name(music / "Track 1.mp3").exists())
print("== Cancel deletes what the run uploaded ==")
adapter = main.require_adapter()
opts = convert_mod.Options(mode="replace")
planned = remote_convert.plan(adapter, [ids[2], ids[3]], opts)
class Handle:
cancelled = False
def progress(self, **kw):
pass
h = Handle()
real_stage = adapter.stage_stem
def stage_then_cancel(*a, **k):
out = real_stage(*a, **k)
h.cancelled = True
return out
adapter.stage_stem = stage_then_cancel
out = remote_convert.run(h, adapter, planned, opts, still_current=lambda: True)
adapter.stage_stem = real_stage
check("a cancel after one upload stops the batch", out["cancelled"])
check("…and the uploaded stem file is deleted on the server",
not partial_name(music / "Track 2.stem.m4a").exists() and not srv.state.pending.leftovers,
srv.state.pending.leftovers)
check("…nothing else changed", (music / "Track 2.mp3").is_file() and not server_adapter.dirty)
print("== a takeover mid-batch loses no separation ==")
planned = remote_convert.plan(adapter, [ids[4]], opts)
item = planned.items[0]
local = adapter.audio_path(ids[4])
staged = ROOT / "staged.stem.m4a"
written = sf.build(local, staged, lambda pcm: [pcm * g for g in (0.5, 0.25, -0.2, 0.1)])
adapter.stage_stem(ids[4], item["target"], staged, bit_rate=written.bit_rate, duration=written.duration)
other = RemoteClient(remote_config.Remote(id="o", name="NAS", host=f"127.0.0.1:{port}", username="dj"), "pw")
other.acquire("other", "Studio iMac", takeover=True)
other.release()
check("the uploaded file stays on the server as a verified leftover",
partial_name(music / "Track 4.stem.m4a").is_file() and len(srv.state.pending.leftovers) == 1)
r = c.post("/api/library/open-remote", json={"remote_id": remote_id})
p = c.post("/api/tracks/stems/preview", json={"track_ids": [ids[4]], "mode": "replace"}).json()
check("the next plan reuses it", p["convert"] and p["convert"][0]["reuse"] and p["seconds"] == 0, p)
em._DEFAULT = em.EngineManager(ROOT / "no-engine") # an engine call would now fail
r = c.post("/api/tracks/stems/convert", json={"track_ids": [ids[4]], "mode": "replace"})
job = wait(c, r.json()["id"]) if r.status_code == 200 else {"state": "refused", "error": r.text}
check("…and converts without the engine", job["state"] == "done"
and len((job.get("result") or {}).get("converted", [])) == 1, job.get("error") or job.get("result"))
c.post("/api/save")
check("…to a stem file on the server", sf.is_stem_file(music / "Track 4.stem.m4a"))
uv.should_exit = True
print()
print("RESULT:", "FAILURES" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+39 -1
View File
@@ -646,7 +646,44 @@ export default function App() {
notify(n ? 'success' : 'error', text, details) notify(n ? 'success' : 'error', text, details)
} }
// A conversion keeps running if the page reloads; find it again. // A conversion keeps running if the page reloads; find it again.
const editState = useQuery({ queryKey: ['state'], queryFn: api.state, enabled: loaded, retry: false }) const isRemote = !!collection.data?.library?.remote
const editState = useQuery({
queryKey: ['state'],
queryFn: api.state,
enabled: loaded,
retry: false,
// A remote library's connection changes on its own (another computer
// takes over, the server drops off the network), so it is polled; a local
// library's state changes only when this app changes it.
refetchInterval: isRemote ? 5000 : false,
})
const remoteState = editState.data?.remote?.state ?? null
const remoteShown = useRef<string | null>(null)
useEffect(() => {
const previous = remoteShown.current
remoteShown.current = remoteState
if (!remoteState || previous === remoteState || previous === null) return
// What the library will accept changed with it: re-read, so the UI gates
// itself (read-only while taken over or offline) — never offers an edit.
qc.invalidateQueries({ queryKey: ['capabilities'] })
const who = editState.data?.remote?.machine
if (remoteState === 'taken_over')
notify('warning', `${who || 'Another computer'} took over this library — it is read-only here now`)
else if (remoteState === 'offline') notify('warning', 'The server cannot be reached — read-only until it is back')
else if (remoteState === 'connected' && previous !== 'reconnecting') notify('success', 'Reconnected to the server')
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [remoteState])
const remoteNotices = editState.data?.remote?.notices ?? 0
const noticesShown = useRef(0)
useEffect(() => {
if (remoteNotices <= noticesShown.current) return
noticesShown.current = remoteNotices
const text = editState.data?.remote?.notice
if (text) notify('warning', text)
// Re-read: the server's library is what it is now, not what this tab holds.
qc.invalidateQueries()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [remoteNotices])
useEffect(() => { useEffect(() => {
const id = editState.data?.stem_job const id = editState.data?.stem_job
if (id && !batchJob) setBatchJob({ id, kind: 'stems' }) if (id && !batchJob) setBatchJob({ id, kind: 'stems' })
@@ -1510,6 +1547,7 @@ export default function App() {
: null : null
} }
loading={loading} loading={loading}
connection={editState.data?.remote ?? null}
collectionName={capabilities.data ? libraryName : null} collectionName={capabilities.data ? libraryName : null}
onChangeCollection={() => { onChangeCollection={() => {
// The same question the sidebar header asks: this button used to // The same question the sidebar header asks: this button used to
+124 -5
View File
@@ -227,7 +227,10 @@ export interface SaveCapabilities {
} }
/** Why a library cannot be edited. A fact — lib/platformCopy.ts words it. */ /** Why a library cannot be edited. A fact — lib/platformCopy.ts words it. */
export type ReadonlyCause = 'platform_incomplete' | 'cloud_synced' | 'not_in_library' | 'browsing' export type ReadonlyCause =
| 'platform_incomplete' | 'cloud_synced' | 'not_in_library' | 'browsing'
/** A library held by a server: another computer took it over / the server is unreachable. */
| 'taken_over' | 'offline'
export interface Capabilities { export interface Capabilities {
platform: Platform platform: Platform
@@ -261,8 +264,15 @@ export interface Capabilities {
audio_formats: string[] audio_formats: string[]
artwork: boolean artwork: boolean
artwork_note: string | null artwork_note: string | null
/** Whose filesystem an import destination is on: this computer's ('host'),
* or the machine holding the library ('library' — audio is uploaded). */
audio_destination: 'host' | 'library'
/** Added files can be left where they are rather than copied. */
reference: boolean
} }
playlists: { folders: boolean; smart: 'none' | 'read_only'; reorder: boolean } playlists: { folders: boolean; smart: 'none' | 'read_only'; reorder: boolean }
/** Path mapping / rewriting / the missing-files check apply to this library. */
paths: { remappable: boolean }
save: SaveCapabilities save: SaveCapabilities
} }
@@ -273,6 +283,8 @@ export interface LibraryInfo {
path: string path: string
display_name: string display_name: string
version: string | null version: string | null
/** Set when the library is held by a server (a saved remote). */
remote: { id: string; name: string; via: string | null } | null
} }
export interface PlatformOption { export interface PlatformOption {
@@ -280,7 +292,7 @@ export interface PlatformOption {
name: string name: string
library_label: string library_label: string
/** Whether picking this platform's library means picking a file or a folder. */ /** Whether picking this platform's library means picking a file or a folder. */
selects: 'file' | 'directory' selects: 'file' | 'directory' | 'remote'
installed: boolean installed: boolean
/** How many libraries this platform has right now; `installed` is `found > 0`. */ /** How many libraries this platform has right now; `installed` is `found > 0`. */
found: number found: number
@@ -302,6 +314,22 @@ export interface EditState {
stem_job: string | null stem_job: string | null
/** What this open's crash recovery did about an interrupted conversion. */ /** What this open's crash recovery did about an interrupted conversion. */
stem_recovery: { committed: number; restored: number; kept: number } | null stem_recovery: { committed: number; restored: number; kept: number } | null
/** A remote library's connection, null for a local one. */
remote: RemoteConnection | null
}
/** How this computer stands with a remote library's server. `taken_over`:
* another computer holds the session, so this one is read-only. */
export interface RemoteConnection {
state: 'connected' | 'reconnecting' | 'offline' | 'taken_over'
/** The address in use ('primary' / 'fallback'), when connected. */
via: 'primary' | 'fallback' | null
/** Who took it over, when `taken_over`. */
machine: string | null
/** Something to tell the user once ("the server restarted"), with a counter
* that changes each time there is a new one. */
notice: string | null
notices: number
} }
export interface CollectionStatus { export interface CollectionStatus {
@@ -310,6 +338,61 @@ export interface CollectionStatus {
library: LibraryInfo | null library: LibraryInfo | null
tracks: number | null tracks: number | null
playlists: number | null playlists: number | null
/** Opening a remote: the unsaved edits another computer left there. */
pending_edits?: PendingEdits | null
}
/** Unsaved edits a remote library holds that another computer made. */
export interface PendingEdits {
machine: string | null
summary: string
}
/** A saved remote — a Konduktor server this computer knows how to reach. The
* password is in the OS keychain, never here. */
export interface RemoteSettings {
id: string
name: string
host: string
port: number | null
fallback_host: string | null
fallback_port: number | null
username: string
has_password: boolean
}
export interface RemoteForm {
name: string
/** `host` or `host:port`. */
host: string
fallback_host?: string | null
username: string
/** Omitted on an edit: keep the saved one. */
password?: string
}
/** One address's answer to a handshake. */
export interface HandshakeResult {
address: 'primary' | 'fallback'
url: string
ok: boolean
error: string | null
kind: 'ok' | 'unreachable' | 'auth' | 'version' | 'other'
}
/** Someone else holds a remote's session (409 from open-remote). */
export interface RemoteInUse {
code: 'in_use'
machine: string
since: string
batch: string | null
}
export interface RemoteCacheUsage {
bytes: number
files: number
cap: number
free: number
} }
export interface CollectionCandidate { export interface CollectionCandidate {
@@ -515,6 +598,9 @@ export interface StemPlan {
bytes: number bytes: number
/** The originals' size — what Save deletes in Replace mode. */ /** The originals' size — what Save deletes in Replace mode. */
original_bytes: number original_bytes: number
/** A remote library: what must cross the network (bytes; `speed` in
* bytes/s, `measured` false while it is still a default). */
transfer?: { download: number; upload: number; speed: number; measured: boolean }
} }
/** A stem conversion job's `result`. */ /** A stem conversion job's `result`. */
@@ -743,6 +829,19 @@ async function getJSON<T>(url: string): Promise<T> {
return res.json() as Promise<T> return res.json() as Promise<T>
} }
/** A refusal from the backend. `message` is always a sentence; `detail` keeps
* a structured answer (e.g. `{code: 'in_use', machine, since}`) for the few
* callers that act on it rather than just showing it. */
export class ApiError extends Error {
status: number
detail: unknown
constructor(status: number, message: string, detail: unknown) {
super(message)
this.status = status
this.detail = detail
}
}
async function send<T>(method: string, url: string, body?: unknown): Promise<T> { async function send<T>(method: string, url: string, body?: unknown): Promise<T> {
const res = await fetch(API_BASE + url, { const res = await fetch(API_BASE + url, {
method, method,
@@ -750,14 +849,19 @@ async function send<T>(method: string, url: string, body?: unknown): Promise<T>
body: body ? JSON.stringify(body) : undefined, body: body ? JSON.stringify(body) : undefined,
}) })
if (!res.ok) { if (!res.ok) {
let detail = `${res.status} ${res.statusText}` let message = `${res.status} ${res.statusText}`
let detail: unknown = null
try { try {
const j = await res.json() const j = await res.json()
if (j.detail) detail = j.detail if (j.detail) {
detail = j.detail
if (typeof j.detail === 'string') message = j.detail
else if (typeof j.detail?.message === 'string') message = j.detail.message
}
} catch { } catch {
/* ignore */ /* ignore */
} }
throw new Error(detail) throw new ApiError(res.status, message, detail)
} }
return res.json() as Promise<T> return res.json() as Promise<T>
} }
@@ -782,6 +886,21 @@ export const api = {
getJSON<CollectionOptions>(`/api/library/options${qs({ platform })}`), getJSON<CollectionOptions>(`/api/library/options${qs({ platform })}`),
listDir: (path?: string, platform?: string) => listDir: (path?: string, platform?: string) =>
getJSON<FsListing>(`/api/fs/list${qs({ path, platform })}`), getJSON<FsListing>(`/api/fs/list${qs({ path, platform })}`),
/** Folders on the machine that HOLDS the library (a remote's server),
* confined to its content folder — `home` is that folder. */
libraryListDir: (path?: string) => getJSON<FsListing>(`/api/library/fs/list${qs({ path })}`),
// ---- remote libraries ----
remotes: () => getJSON<RemoteSettings[]>('/api/remotes'),
addRemote: (form: RemoteForm) =>
send<{ remote: RemoteSettings; results: HandshakeResult[] }>('POST', '/api/remotes', form),
editRemote: (id: string, form: RemoteForm) =>
send<{ remote: RemoteSettings; results: HandshakeResult[] }>('PATCH', `/api/remotes/${id}`, form),
deleteRemote: (id: string) => send<{ status: string }>('DELETE', `/api/remotes/${id}`),
openRemote: (id: string, takeover = false) =>
send<CollectionStatus>('POST', '/api/library/open-remote', { remote_id: id, takeover }),
remoteCache: () => getJSON<RemoteCacheUsage>('/api/remote-cache'),
clearRemoteCache: () => send<{ freed: number }>('DELETE', '/api/remote-cache'),
// Re-asked rather than cached: drives come and go while a dialog is open. // Re-asked rather than cached: drives come and go while a dialog is open.
places: (platform?: string) => getJSON<FsPlace[]>(`/api/fs/places${qs({ platform })}`), places: (platform?: string) => getJSON<FsPlace[]>(`/api/fs/places${qs({ platform })}`),
+63 -6
View File
@@ -18,6 +18,10 @@ import { FolderPicker } from './FolderPicker'
* how the DJ keeps their music, and a remembered default would quietly apply * how the DJ keeps their music, and a remembered default would quietly apply
* last week's answer to a different drive. * last week's answer to a different drive.
* *
* A library held by a server (`tracks.audio_destination === 'library'`) is the
* other exception: it cannot see this computer's files, so the only choice is
* which folder ON THE SERVER they are uploaded into.
*
* A playlist or export target still needs the files in the collection first — * A playlist or export target still needs the files in the collection first —
* both hold collection track ids — so the dialog says so rather than doing it * both hold collection track ids — so the dialog says so rather than doing it
* silently. Files the collection already holds are not added again, but still * silently. Files the collection already holds are not added again, but still
@@ -53,8 +57,11 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
// decides copy vs in place itself, so there is nothing to ask. // decides copy vs in place itself, so there is nothing to ask.
const caps = useCaps() const caps = useCaps()
const places = caps.tracks.places_audio const places = caps.tracks.places_audio
const [mode, setMode] = useState<'copy' | 'reference' | null>(null) // Uploaded into a folder on the server: nothing to ask but where.
const uploads = !places && caps.tracks.audio_destination === 'library'
const [mode, setMode] = useState<'copy' | 'reference' | null>(uploads ? 'copy' : null)
const [folder, setFolder] = useState('') const [folder, setFolder] = useState('')
const remote = useServerImportFolder(uploads)
const [browsing, setBrowsing] = useState(false) const [browsing, setBrowsing] = useState(false)
const [job, setJob] = useState<JobStatus | null>(null) const [job, setJob] = useState<JobStatus | null>(null)
const [starting, setStarting] = useState(false) const [starting, setStarting] = useState(false)
@@ -65,9 +72,13 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
const prefsLoaded = prefs.isSuccess const prefsLoaded = prefs.isSuccess
useEffect(() => { useEffect(() => {
if (!prefsLoaded || folder) return if (!prefsLoaded || folder) return
if (uploads) {
if (remote.folder) setFolder(remote.folder)
return
}
const p = prefs.data as { importFolder?: string } const p = prefs.data as { importFolder?: string }
setFolder(p?.importFolder || '~/Music/Konduktor Imports') setFolder(p?.importFolder || '~/Music/Konduktor Imports')
}, [prefsLoaded, prefs.data, folder]) }, [prefsLoaded, prefs.data, folder, uploads, remote.folder])
const body: FolderAddRequest = { const body: FolderAddRequest = {
track_ids: trackIds, track_ids: trackIds,
@@ -192,9 +203,11 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
{browsing && ( {browsing && (
<FolderPicker <FolderPicker
value={folder} value={folder}
listing={uploads ? 'library' : 'host'}
onChange={(path) => { onChange={(path) => {
setFolder(path) setFolder(path)
api.patchPrefs({ importFolder: path }).catch(() => {}) if (uploads) remote.remember(path)
else api.patchPrefs({ importFolder: path }).catch(() => {})
}} }}
onClose={() => setBrowsing(false)} onClose={() => setBrowsing(false)}
/> />
@@ -224,7 +237,21 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
</div> </div>
)} )}
{!places && ( {uploads && (
<div className="rounded well px-3 py-2 text-xs text-muted">
<div>Uploaded to {remote.serverName} into</div>
<div className="mt-1 flex items-center gap-2">
<span className="min-w-0 truncate font-mono text-text" dir="rtl" title={folder}>
{folder ? `\u200E${folder}\u200E` : 'Loading…'}
</span>
<button onClick={() => setBrowsing(true)} className="shrink-0 text-accent hover:underline">
Change…
</button>
</div>
</div>
)}
{!places && !uploads && (
<div className="space-y-1"> <div className="space-y-1">
{option( {option(
'copy', 'copy',
@@ -270,12 +297,12 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
<div className="text-text"> <div className="text-text">
{newCount} new to {libraryName} {newCount} new to {libraryName}
{shown !== 'reference' && p.total_bytes > 0 && ( {shown !== 'reference' && p.total_bytes > 0 && (
<span className="text-muted"> · {gb(p.total_bytes)} to copy</span> <span className="text-muted"> · {gb(p.total_bytes)} to {uploads ? 'upload' : 'copy'}</span>
)} )}
</div> </div>
{shown !== 'reference' && p.free_bytes != null && ( {shown !== 'reference' && p.free_bytes != null && (
<div className={p.enough_space === false ? 'text-pink' : 'text-faint'}> <div className={p.enough_space === false ? 'text-pink' : 'text-faint'}>
{gb(p.free_bytes)} free {gb(p.free_bytes)} free{uploads ? ' on the server' : ''}
{p.enough_space === false && ' — not enough space'} {p.enough_space === false && ' — not enough space'}
</div> </div>
)} )}
@@ -369,3 +396,33 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
document.body, document.body,
) )
} }
/**
* A folder ON THE SERVER of a remote library — where uploads go, or where stem
* files are written: the one last chosen for THIS remote (remembered per remote
* under `key`, since each server has its own folders), else its content folder
* (plus `sub`). `serverName` names it in the dialog.
*/
export function useServerFolder(
enabled: boolean,
key: 'remoteImportFolders' | 'remoteStemFolders' = 'remoteImportFolders',
sub = '',
) {
const collection = useQuery({ queryKey: ['collection'], queryFn: api.collection, enabled })
const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs, enabled })
const root = useQuery({ queryKey: ['fs', 'library', '~', null], queryFn: () => api.libraryListDir(), enabled })
const remoteId = collection.data?.library?.remote?.id ?? null
const saved = (prefs.data as Record<string, Record<string, string> | undefined> | undefined)?.[key]
const home = root.data?.home
const folder = (remoteId && saved?.[remoteId]) || (home ? (sub ? `${home}/${sub}` : home) : '')
return {
folder,
serverName: collection.data?.library?.display_name ?? 'the server',
remember: (path: string) => {
if (!remoteId) return
api.patchPrefs({ [key]: { ...(saved ?? {}), [remoteId]: path } }).catch(() => {})
},
}
}
export const useServerImportFolder = (enabled: boolean) => useServerFolder(enabled)
+16 -47
View File
@@ -1,10 +1,12 @@
import { useState, type ReactNode } from 'react' import { useState } from 'react'
import { useMutation, useQuery } from '@tanstack/react-query' import { useMutation, useQuery } from '@tanstack/react-query'
import { api, type CollectionCandidate, type CollectionStatus, type PlatformOption } from '../api' import { api, type CollectionCandidate, type CollectionStatus, type PlatformOption } from '../api'
import { FileBrowser, useFsListing } from './FileBrowser' import { FileBrowser, useFsListing } from './FileBrowser'
import { browsePrompt, platformAvailability } from '../lib/platformCopy' import { browsePrompt, platformAvailability } from '../lib/platformCopy'
import { Icon } from '../lib/icons' import { Icon } from '../lib/icons'
import { PlatformIcon } from '../lib/platformIcons' import { PlatformIcon } from '../lib/platformIcons'
import { OptionCard } from './OptionCard'
import { RemotePicker } from './RemotePicker'
/** /**
* Choose a library to open, in two steps: WHICH PLATFORM, then which library. * Choose a library to open, in two steps: WHICH PLATFORM, then which library.
@@ -35,50 +37,6 @@ function formatWhen(sec: number | null): string {
}) })
} }
function OptionCard({
icon,
lit,
title,
subtitle,
disabled,
busy,
onClick,
}: {
icon: ReactNode
/** A small lit dot on the icon tile: "something is here". */
lit?: boolean
title: string
subtitle: string
disabled?: boolean
busy?: boolean
onClick: () => void
}) {
return (
<button
disabled={disabled || busy}
onClick={onClick}
className="btn-glass group flex w-full items-center gap-3.5 rounded-2xl px-3 py-3 text-left disabled:cursor-not-allowed disabled:opacity-40"
>
<span className="well relative flex h-11 w-11 shrink-0 items-center justify-center rounded-xl text-text">
{icon}
{lit && (
<span className="absolute -right-0.5 -top-0.5 h-2.5 w-2.5 rounded-full bg-mint shadow-[0_0_8px_var(--color-mint)] ring-2 ring-[rgb(12_14_24)]" />
)}
</span>
<div className="min-w-0 flex-1">
<div className="text-sm font-semibold text-text">{title}</div>
<div className="truncate text-xs text-faint">{subtitle}</div>
</div>
<Icon
name="chevronRight"
size={14}
strokeWidth={2.2}
className="text-faint transition-colors group-hover:text-text"
/>
</button>
)
}
export function CollectionPicker({ onOpened, onCancel }: Props) { export function CollectionPicker({ onOpened, onCancel }: Props) {
const [step, setStep] = useState<'platform' | 'library' | 'browse'>('platform') const [step, setStep] = useState<'platform' | 'library' | 'browse'>('platform')
const [platform, setPlatform] = useState<PlatformOption | null>(null) const [platform, setPlatform] = useState<PlatformOption | null>(null)
@@ -89,10 +47,12 @@ export function CollectionPicker({ onOpened, onCancel }: Props) {
// /api/platforms is the pre-load equivalent, and it is the whole of step one. // /api/platforms is the pre-load equivalent, and it is the whole of step one.
const platforms = useQuery({ queryKey: ['platforms'], queryFn: api.platforms }) const platforms = useQuery({ queryKey: ['platforms'], queryFn: api.platforms })
// A remote is not found on this computer; its step lists saved servers.
const remote = platform?.selects === 'remote'
const options = useQuery({ const options = useQuery({
queryKey: ['collectionOptions', platform?.platform], queryKey: ['collectionOptions', platform?.platform],
queryFn: () => api.collectionOptions(platform!.platform), queryFn: () => api.collectionOptions(platform!.platform),
enabled: !!platform, enabled: !!platform && !remote,
}) })
// Shares FileBrowser's query, so the confirm row below cannot disagree with // Shares FileBrowser's query, so the confirm row below cannot disagree with
@@ -126,6 +86,8 @@ export function CollectionPicker({ onOpened, onCancel }: Props) {
const subtitle = const subtitle =
step === 'platform' step === 'platform'
? 'Konduktor opens libraries from each of these.' ? 'Konduktor opens libraries from each of these.'
: step === 'library' && remote
? 'A library held by a Konduktor server, played and prepared from here.'
: step === 'library' : step === 'library'
? 'Open automatically, resume your last one, or browse.' ? 'Open automatically, resume your last one, or browse.'
: platform : platform
@@ -146,7 +108,11 @@ export function CollectionPicker({ onOpened, onCancel }: Props) {
)} )}
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<div className="text-[15px] font-semibold tracking-tight"> <div className="text-[15px] font-semibold tracking-tight">
{platform ? `Select your ${platform.name} library` : 'Select your DJ platform'} {remote
? 'Open a remote library'
: platform
? `Select your ${platform.name} library`
: 'Select your DJ platform'}
</div> </div>
<div className="truncate text-xs text-muted">{subtitle}</div> <div className="truncate text-xs text-muted">{subtitle}</div>
</div> </div>
@@ -199,6 +165,9 @@ export function CollectionPicker({ onOpened, onCancel }: Props) {
/> />
))} ))}
</div> </div>
) : step === 'library' && remote ? (
/* ---- Step 2, remote: which server ---- */
<RemotePicker onOpened={onOpened} />
) : step === 'library' ? ( ) : step === 'library' ? (
/* ---- Step 2: which library of that platform ---- */ /* ---- Step 2: which library of that platform ---- */
<div className="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto p-5"> <div className="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto p-5">
+43 -4
View File
@@ -10,6 +10,8 @@ import {
type StemTarget, type StemTarget,
} from '../api' } from '../api'
import { FolderPicker } from './FolderPicker' import { FolderPicker } from './FolderPicker'
import { useServerFolder } from './AddFilesDialog'
import { useCaps } from '../lib/capabilities'
/** /**
* Convert to Stems — one dialog (decided, see the stem-conversion discussion * Convert to Stems — one dialog (decided, see the stem-conversion discussion
@@ -89,6 +91,12 @@ export function ConvertStemsDialog({ trackIds, onClose, onStarted, onDownloading
const [showSkipped, setShowSkipped] = useState(false) const [showSkipped, setShowSkipped] = useState(false)
const [starting, setStarting] = useState(false) const [starting, setStarting] = useState(false)
const [target, setTarget] = useState<StemTarget | null>(null) const [target, setTarget] = useState<StemTarget | null>(null)
// A remote library: its stem files are written ON THE SERVER, so the
// destination is one of its folders (remembered per remote), never the
// local one `stemConvert` remembers for this computer's libraries.
const remote = useCaps().tracks.audio_destination === 'library'
const server = useServerFolder(remote, 'remoteStemFolders', 'Stems')
const [serverDest, setServerDest] = useState<string | null>(null)
useEffect(() => { useEffect(() => {
if (opts || !prefs.isSuccess) return if (opts || !prefs.isSuccess) return
@@ -114,9 +122,10 @@ export function ConvertStemsDialog({ trackIds, onClose, onStarted, onDownloading
const playlists = useQuery({ queryKey: ['playlists'], queryFn: api.playlists }) const playlists = useQuery({ queryKey: ['playlists'], queryFn: api.playlists })
const choices = useMemo(() => flatten(playlists.data ?? []), [playlists.data]) const choices = useMemo(() => flatten(playlists.data ?? []), [playlists.data])
const destination = remote ? (serverDest ?? server.folder) : (opts?.destination ?? '')
const body: StemConvertOptions | null = opts && { const body: StemConvertOptions | null = opts && {
mode: opts.mode, mode: opts.mode,
destination: opts.mode === 'destination' ? opts.destination : null, destination: opts.mode === 'destination' ? destination : null,
collection: opts.mode === 'replace' ? 'repoint' : opts.collection, collection: opts.mode === 'replace' ? 'repoint' : opts.collection,
playlist_id: playlist_id:
opts.mode === 'destination' && opts.collection === 'add' && opts.playlist === 'existing' opts.mode === 'destination' && opts.collection === 'add' && opts.playlist === 'existing'
@@ -218,7 +227,17 @@ export function ConvertStemsDialog({ trackIds, onClose, onStarted, onDownloading
return createPortal( return createPortal(
<> <>
{browsing && opts && ( {browsing && opts && (
<FolderPicker value={opts.destination} onChange={(path) => set({ destination: path })} onClose={() => setBrowsing(false)} /> <FolderPicker
value={destination}
listing={remote ? 'library' : 'host'}
onChange={(path) => {
if (remote) {
setServerDest(path)
server.remember(path)
} else set({ destination: path })
}}
onClose={() => setBrowsing(false)}
/>
)} )}
<div <div
aria-modal="true" aria-modal="true"
@@ -260,8 +279,8 @@ export function ConvertStemsDialog({ trackIds, onClose, onStarted, onDownloading
() => set({ mode: 'destination' }), () => set({ mode: 'destination' }),
'Save to a folder', 'Save to a folder',
<span className="flex items-center gap-2"> <span className="flex items-center gap-2">
<span className="min-w-0 truncate font-mono" dir="rtl" title={opts.destination}> <span className="min-w-0 truncate font-mono" dir="rtl" title={destination}>
{`‎${opts.destination}‎`} {`‎${destination}‎`}
</span> </span>
<button <button
onClick={(e) => { onClick={(e) => {
@@ -414,6 +433,26 @@ export function ConvertStemsDialog({ trackIds, onClose, onStarted, onDownloading
{size(plan.bytes)} of stem files {size(plan.bytes)} of stem files
</div> </div>
)} )}
{/* A remote library: the sources come down and the stem
files go up — said, with the time it adds. */}
{n > 0 && plan.transfer && plan.transfer.download + plan.transfer.upload > 0 && (
<div className="text-faint">
{size(plan.transfer.download)} to download and {size(plan.transfer.upload)} to upload
{' · about '}
{duration((plan.transfer.download + plan.transfer.upload) / plan.transfer.speed)}
{plan.transfer.measured ? '' : ' (estimated)'} more
</div>
)}
{n > 0 && plan.transfer && (
<ul className="space-y-0.5 text-faint">
{plan.space.map((sp) => (
<li key={`${sp.volume}-${sp.folder}`}>
{sp.volume}: {size(sp.bytes)} needed
{sp.free != null ? `, ${size(sp.free)} free` : ''}
</li>
))}
</ul>
)}
{plan.blocked && <div className="text-pink">{plan.blocked}</div>} {plan.blocked && <div className="text-pink">{plan.blocked}</div>}
</section> </section>
)} )}
+19 -6
View File
@@ -26,13 +26,17 @@ import { Icon, type IconName } from '../lib/icons'
* the cache key. Passing it back up through a callback would mean an effect * the cache key. Passing it back up through a callback would mean an effect
* firing on every navigation to tell the parent what it already asked for. * firing on every navigation to tell the parent what it already asked for.
*/ */
export function useFsListing(path: string | undefined, platform?: string) { export function useFsListing(path: string | undefined, platform?: string, listing: Listing = 'host') {
return useQuery({ return useQuery({
queryKey: ['fs', path ?? '~', platform ?? null], queryKey: ['fs', listing, path ?? '~', platform ?? null],
queryFn: () => api.listDir(path, platform), queryFn: () => (listing === 'library' ? api.libraryListDir(path) : api.listDir(path, platform)),
}) })
} }
/** Whose folders: this computer's (`host`), or those of the machine holding the
* library — a remote's server, confined to its content folder (`library`). */
export type Listing = 'host' | 'library'
// Volumes come and go while a dialog is open, so the rail polls. Slower than // Volumes come and go while a dialog is open, so the rail polls. Slower than
// the sidebar's device poll: this is a shortcut list, not the thing you came for. // the sidebar's device poll: this is a shortcut list, not the thing you came for.
const PLACES_POLL_MS = 5000 const PLACES_POLL_MS = 5000
@@ -59,19 +63,28 @@ interface Props {
onPickFile?: (path: string) => void onPickFile?: (path: string) => void
/** The caller's confirm row, pinned under the listing. */ /** The caller's confirm row, pinned under the listing. */
footer?: ReactNode footer?: ReactNode
/** Whose folders are browsed (see `Listing`). Default: this computer's. */
listing?: Listing
} }
export function FileBrowser({ mode, platform, path, onNavigate, onPickFile, footer }: Props) { export function FileBrowser({ mode, platform, path, onNavigate, onPickFile, footer, listing: whose = 'host' }: Props) {
const listing = useFsListing(path, platform) const listing = useFsListing(path, platform, whose)
const places = useQuery({ const places = useQuery({
queryKey: ['fs-places', platform ?? null], queryKey: ['fs-places', platform ?? null],
queryFn: () => api.places(platform), queryFn: () => api.places(platform),
refetchInterval: PLACES_POLL_MS, refetchInterval: PLACES_POLL_MS,
// A server's folders have one place worth a shortcut: its content folder.
enabled: whose === 'host',
}) })
const data: FsListing | undefined = listing.data const data: FsListing | undefined = listing.data
const here = data?.path ?? '' const here = data?.path ?? ''
const rows = places.data ?? [] const rows: FsPlace[] =
whose === 'library'
? data
? [{ name: 'Library folder', path: data.home, kind: 'library' } as FsPlace]
: []
: (places.data ?? [])
// Volatile section LAST: a drive appearing or vanishing must not shift the // Volatile section LAST: a drive appearing or vanishing must not shift the
// rows above it under a cursor that is already moving towards one. // rows above it under a cursor that is already moving towards one.
+6 -3
View File
@@ -1,6 +1,6 @@
import { createPortal } from 'react-dom' import { createPortal } from 'react-dom'
import { useState } from 'react' import { useState } from 'react'
import { FileBrowser, useFsListing } from './FileBrowser' import { FileBrowser, useFsListing, type Listing } from './FileBrowser'
/** /**
* Pick a FOLDER, by browsing. * Pick a FOLDER, by browsing.
@@ -15,16 +15,18 @@ interface Props {
value: string value: string
onChange: (path: string) => void onChange: (path: string) => void
onClose: () => void onClose: () => void
/** Whose folders: this computer's, or the server's holding a remote library. */
listing?: Listing
} }
export function FolderPicker({ value, onChange, onClose }: Props) { export function FolderPicker({ value, onChange, onClose, listing = 'host' }: Props) {
// `undefined` means "wherever the server thinks home is" — the picker does not // `undefined` means "wherever the server thinks home is" — the picker does not
// need to know that path to open on it. // need to know that path to open on it.
const [dir, setDir] = useState<string | undefined>(value || undefined) const [dir, setDir] = useState<string | undefined>(value || undefined)
const [newFolder, setNewFolder] = useState('') const [newFolder, setNewFolder] = useState('')
// Shares FileBrowser's query, so "where am I" cannot disagree with what is // Shares FileBrowser's query, so "where am I" cannot disagree with what is
// on screen — and the confirm row below needs it to name its target. // on screen — and the confirm row below needs it to name its target.
const here = useFsListing(dir).data?.path ?? '' const here = useFsListing(dir, undefined, listing).data?.path ?? ''
const confirm = () => { const confirm = () => {
onChange(newFolder.trim() ? `${here}/${newFolder.trim()}` : here) onChange(newFolder.trim() ? `${here}/${newFolder.trim()}` : here)
@@ -40,6 +42,7 @@ export function FolderPicker({ value, onChange, onClose }: Props) {
<FileBrowser <FileBrowser
mode="directory" mode="directory"
listing={listing}
path={dir} path={dir}
onNavigate={setDir} onNavigate={setDir}
footer={ footer={
+15 -3
View File
@@ -5,6 +5,7 @@ import { api, type ImportPreview, type JobStatus } from '../api'
import { useCaps } from '../lib/capabilities' import { useCaps } from '../lib/capabilities'
import { placedAudioSummary } from '../lib/platformCopy' import { placedAudioSummary } from '../lib/platformCopy'
import { FolderPicker } from './FolderPicker' import { FolderPicker } from './FolderPicker'
import { useServerImportFolder } from './AddFilesDialog'
/** /**
* Import a browsed device into the loaded collection. * Import a browsed device into the loaded collection.
@@ -45,6 +46,9 @@ export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError
// One that places its own audio — a stick — needs no destination. // One that places its own audio — a stick — needs no destination.
const caps = useCaps() const caps = useCaps()
const places = caps.tracks.places_audio const places = caps.tracks.places_audio
// A library held by a server: the audio is uploaded into one of ITS folders.
const uploads = !places && caps.tracks.audio_destination === 'library'
const remote = useServerImportFolder(uploads)
const [baseFolder, setBaseFolder] = useState('') const [baseFolder, setBaseFolder] = useState('')
const [useSubfolder, setUseSubfolder] = useState(true) const [useSubfolder, setUseSubfolder] = useState(true)
const [browsing, setBrowsing] = useState(false) const [browsing, setBrowsing] = useState(false)
@@ -59,9 +63,13 @@ export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError
useEffect(() => { useEffect(() => {
if (!prefsLoaded || baseFolder) return if (!prefsLoaded || baseFolder) return
const p = prefs.data as { importFolder?: string; importSubfolder?: boolean } const p = prefs.data as { importFolder?: string; importSubfolder?: boolean }
if (uploads) {
if (remote.folder) setBaseFolder(remote.folder)
} else {
setBaseFolder(p?.importFolder || '~/Music/Konduktor Imports') setBaseFolder(p?.importFolder || '~/Music/Konduktor Imports')
}
if (typeof p?.importSubfolder === 'boolean') setUseSubfolder(p.importSubfolder) if (typeof p?.importSubfolder === 'boolean') setUseSubfolder(p.importSubfolder)
}, [prefsLoaded, prefs.data, baseFolder]) }, [prefsLoaded, prefs.data, baseFolder, uploads, remote.folder])
const remember = (patch: Record<string, unknown>) => { const remember = (patch: Record<string, unknown>) => {
api.patchPrefs(patch).catch(() => { api.patchPrefs(patch).catch(() => {
@@ -153,9 +161,11 @@ export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError
{browsing && ( {browsing && (
<FolderPicker <FolderPicker
value={baseFolder} value={baseFolder}
listing={uploads ? 'library' : 'host'}
onChange={(path) => { onChange={(path) => {
setBaseFolder(path) setBaseFolder(path)
remember({ importFolder: path }) if (uploads) remote.remember(path)
else remember({ importFolder: path })
}} }}
onClose={() => setBrowsing(false)} onClose={() => setBrowsing(false)}
/> />
@@ -179,7 +189,9 @@ export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError
)} )}
{!places && ( {!places && (
<div> <div>
<span className="mb-1 block text-xs text-muted">Copy audio into</span> <span className="mb-1 block text-xs text-muted">
{uploads ? `Upload audio to ${remote.serverName}, into` : 'Copy audio into'}
</span>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<span <span
title={baseFolder} title={baseFolder}
+47
View File
@@ -0,0 +1,47 @@
import type { ReactNode } from 'react'
import { Icon } from '../lib/icons'
/** One choice in the library picker: an icon tile, a title, one line of facts. */
export function OptionCard({
icon,
lit,
title,
subtitle,
disabled,
busy,
onClick,
}: {
icon: ReactNode
/** A small lit dot on the icon tile: "something is here". */
lit?: boolean
title: string
subtitle: string
disabled?: boolean
busy?: boolean
onClick: () => void
}) {
return (
<button
disabled={disabled || busy}
onClick={onClick}
className="btn-glass group flex w-full items-center gap-3.5 rounded-2xl px-3 py-3 text-left disabled:cursor-not-allowed disabled:opacity-40"
>
<span className="well relative flex h-11 w-11 shrink-0 items-center justify-center rounded-xl text-text">
{icon}
{lit && (
<span className="absolute -right-0.5 -top-0.5 h-2.5 w-2.5 rounded-full bg-mint shadow-[0_0_8px_var(--color-mint)] ring-2 ring-[rgb(12_14_24)]" />
)}
</span>
<div className="min-w-0 flex-1">
<div className="text-sm font-semibold text-text">{title}</div>
<div className="truncate text-xs text-faint">{subtitle}</div>
</div>
<Icon
name="chevronRight"
size={14}
strokeWidth={2.2}
className="text-faint transition-colors group-hover:text-text"
/>
</button>
)
}
@@ -0,0 +1,113 @@
import { createPortal } from 'react-dom'
import { useEffect, useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { api } from '../api'
import { size } from './ConvertStemsDialog'
/**
* Settings → Remote audio: this computer's copies of a remote library's audio.
*
* Everything that needs a track as a FILE — the deck, analysis, stem
* separation, an export's copy onto a stick — runs here on a downloaded copy,
* kept in one cache so a track is fetched once. Least recently used goes first
* once the cap is reached; clearing it only costs a download the next time.
*/
const CAPS_GB = [2, 5, 10, 20, 50, 100]
export function RemoteCacheSettings({ onClose }: { onClose: () => void }) {
const qc = useQueryClient()
const usage = useQuery({ queryKey: ['remote-cache'], queryFn: api.remoteCache })
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string | null>(null)
useEffect(() => {
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [onClose])
const u = usage.data
const capGb = u ? Math.round(u.cap / 1024 ** 3) : null
const setCap = async (gb: number) => {
setError(null)
try {
const p = await api.patchPrefs({ remoteCacheBytes: gb * 1024 ** 3 })
qc.setQueryData(['prefs'], p)
qc.invalidateQueries({ queryKey: ['remote-cache'] })
} catch (e) {
setError((e as Error).message)
}
}
const clear = async () => {
setBusy(true)
setError(null)
try {
await api.clearRemoteCache()
qc.invalidateQueries({ queryKey: ['remote-cache'] })
} catch (e) {
setError((e as Error).message)
} finally {
setBusy(false)
}
}
return createPortal(
<div
aria-modal="true"
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-6 backdrop-blur-[3px]"
onClick={onClose}
>
<div className="flex w-full max-w-md flex-col overflow-hidden glass-overlay" onClick={(e) => e.stopPropagation()}>
<div className="flex items-center justify-between border-b border-line px-5 py-3">
<h2 className="text-sm font-semibold text-text">Remote audio</h2>
<button onClick={onClose} className="rounded px-1.5 text-faint hover:text-text" aria-label="Close">
×
</button>
</div>
<div className="space-y-4 px-5 py-4 text-sm">
<p className="text-muted">
Tracks from a remote library are downloaded to this computer to be played, analysed,
converted or exported, and kept so each is fetched only once.
</p>
<div className="text-text">
{u ? `${size(u.bytes)} in ${u.files} file${u.files === 1 ? '' : 's'}` : 'Loading…'}
{u && <span className="text-faint"> · {size(u.free)} free on this disk</span>}
</div>
<label className="flex items-center gap-3">
<span className="text-muted">Keep up to</span>
<select
value={capGb ?? ''}
onChange={(e) => void setCap(Number(e.target.value))}
className="rounded-lg well px-2 py-1 text-sm text-text outline-none"
>
{capGb !== null && !CAPS_GB.includes(capGb) && <option value={capGb}>{capGb} GB</option>}
{CAPS_GB.map((gb) => (
<option key={gb} value={gb}>
{gb} GB
</option>
))}
</select>
<span className="text-faint">— the least recently used go first</span>
</label>
{error && <div className="text-xs text-pink">{error}</div>}
</div>
<div className="flex justify-end gap-2 border-t border-line px-5 py-3">
<button
disabled={busy || !u || u.files === 0}
onClick={() => void clear()}
className="btn-glass rounded-full px-4 py-1.5 text-sm text-muted hover:text-text disabled:opacity-40"
>
{busy ? 'Clearing…' : 'Clear'}
</button>
<button onClick={onClose} className="rounded-full btn-primary px-4 py-1.5 text-sm font-semibold">
Done
</button>
</div>
</div>
</div>,
document.body,
)
}
+375
View File
@@ -0,0 +1,375 @@
import { useState, type ReactNode } from 'react'
import { createPortal } from 'react-dom'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import {
api,
ApiError,
type CollectionStatus,
type HandshakeResult,
type PendingEdits,
type RemoteForm,
type RemoteInUse,
type RemoteSettings,
} from '../api'
import { askConfirm } from '../lib/confirm'
import { Icon } from '../lib/icons'
import { remoteHolder } from '../lib/platformCopy'
import { OptionCard } from './OptionCard'
/**
* The picker's "Remote" step: the Konduktor servers this computer knows, and
* a form to add one.
*
* A remote is saved only once the server has answered — the backend handshakes
* every address and refuses a wrong password or a version that cannot talk, so
* a saved remote is one that worked. Connecting can meet two things the user
* has to decide, and both are asked here, before the library is shown:
*
* * another computer holds the library — take over (its edits stay with the
* library), or leave it;
* * the library holds edits another computer left unsaved — save them,
* discard them, or decide later (they stay unsaved, and Save shows them).
*/
interface Props {
onOpened: (status: CollectionStatus) => void
}
const input =
'w-full rounded-lg well px-3 py-2 text-sm text-text outline-none placeholder:text-faint focus:ring-1 focus:ring-accent'
function addressLine(r: RemoteSettings): string {
const main = r.port ? `${r.host}:${r.port}` : r.host
if (!r.fallback_host) return main
const fb = r.fallback_port ? `${r.fallback_host}:${r.fallback_port}` : r.fallback_host
return `${main} · fallback ${fb}`
}
export function RemotePicker({ onOpened }: Props) {
const qc = useQueryClient()
const remotes = useQuery({ queryKey: ['remotes'], queryFn: api.remotes })
const [editing, setEditing] = useState<RemoteSettings | 'new' | null>(null)
const [connecting, setConnecting] = useState<string | null>(null)
const [error, setError] = useState<string | null>(null)
const [pending, setPending] = useState<{ status: CollectionStatus; edits: PendingEdits } | null>(null)
const connect = async (r: RemoteSettings, takeover = false): Promise<void> => {
setConnecting(r.id)
setError(null)
try {
const status = await api.openRemote(r.id, takeover)
if (status.pending_edits) setPending({ status, edits: status.pending_edits })
else onOpened(status)
} catch (e) {
const inUse = e instanceof ApiError && e.status === 409 ? (e.detail as RemoteInUse | null) : null
if (inUse?.code === 'in_use') {
const ok = await askConfirm({
title: `${r.name} is open on another computer`,
body: (
<>
<p>{remoteHolder(inUse.machine, inUse.since, inUse.batch)}</p>
<p>
Taking over makes it read-only there. Any edits it has not saved stay with the library,
and you are asked what to do with them.
</p>
</>
),
confirmLabel: 'Take over',
tone: 'primary',
})
if (ok) return connect(r, true)
} else {
setError((e as Error).message)
}
} finally {
setConnecting(null)
}
}
const remove = async (r: RemoteSettings) => {
const ok = await askConfirm({
title: `Forget ${r.name}?`,
body: 'Konduktor forgets this server and its saved password. Nothing on the server changes.',
confirmLabel: 'Forget',
})
if (!ok) return
try {
await api.deleteRemote(r.id)
qc.invalidateQueries({ queryKey: ['remotes'] })
qc.invalidateQueries({ queryKey: ['platforms'] })
} catch (e) {
setError((e as Error).message)
}
}
if (editing) {
return (
<RemoteFormView
initial={editing === 'new' ? null : editing}
onCancel={() => setEditing(null)}
onSaved={() => {
setEditing(null)
qc.invalidateQueries({ queryKey: ['remotes'] })
qc.invalidateQueries({ queryKey: ['platforms'] })
}}
/>
)
}
const list = remotes.data ?? []
return (
<div className="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto p-5">
{remotes.isLoading && <div className="text-sm text-faint">Loading…</div>}
{list.map((r) => (
<div key={r.id} className="flex items-center gap-2">
<div className="min-w-0 flex-1">
<OptionCard
icon={<Icon name="server" size={20} />}
title={r.name}
subtitle={connecting === r.id ? 'Connecting…' : addressLine(r)}
busy={connecting !== null}
onClick={() => void connect(r)}
/>
</div>
<button
title="Edit"
onClick={() => setEditing(r)}
className="btn-glass flex h-9 w-9 shrink-0 items-center justify-center rounded-full text-muted hover:text-text"
>
<Icon name="pencil" size={14} />
</button>
<button
title="Forget"
onClick={() => void remove(r)}
className="btn-glass flex h-9 w-9 shrink-0 items-center justify-center rounded-full text-muted hover:text-pink"
>
<Icon name="trash" size={14} />
</button>
</div>
))}
<OptionCard
icon={<Icon name="plus" size={20} />}
title="Add a remote library"
subtitle="The address of a Konduktor server, and the account it was set up with"
onClick={() => setEditing('new')}
/>
{error && (
<div className="rounded-xl bg-pink/10 px-3 py-2 text-xs text-pink shadow-[inset_0_0_0_1px_rgb(255_122_154/0.35)]">
{error}
</div>
)}
{pending && (
<PendingEditsDialog
edits={pending.edits}
onChoose={async (choice) => {
if (choice === 'save') await api.save()
if (choice === 'discard') await api.discard()
onOpened(pending.status)
}}
onError={(msg) => setError(msg)}
/>
)}
</div>
)
}
function RemoteFormView({
initial,
onCancel,
onSaved,
}: {
initial: RemoteSettings | null
onCancel: () => void
onSaved: () => void
}) {
const [name, setName] = useState(initial?.name ?? '')
const [host, setHost] = useState(initial ? (initial.port ? `${initial.host}:${initial.port}` : initial.host) : '')
const [fallback, setFallback] = useState(
initial?.fallback_host
? initial.fallback_port
? `${initial.fallback_host}:${initial.fallback_port}`
: initial.fallback_host
: '',
)
const [username, setUsername] = useState(initial?.username ?? '')
const [password, setPassword] = useState('')
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string | null>(null)
const [results, setResults] = useState<HandshakeResult[] | null>(null)
const ready = name.trim() && host.trim() && username.trim() && (password || initial?.has_password)
const save = async () => {
setBusy(true)
setError(null)
setResults(null)
const form: RemoteForm = {
name: name.trim(),
host: host.trim(),
fallback_host: fallback.trim() || null,
username: username.trim(),
...(password ? { password } : {}),
}
try {
const r = initial ? await api.editRemote(initial.id, form) : await api.addRemote(form)
setResults(r.results)
if (r.results.every((x) => x.ok)) onSaved()
// A fallback that did not answer is saved anyway — a VPN address is often
// unreachable at home — but the user is shown it before going back.
} catch (e) {
setError((e as Error).message)
const detail = e instanceof ApiError ? (e.detail as { results?: HandshakeResult[] } | null) : null
if (detail?.results) setResults(detail.results)
} finally {
setBusy(false)
}
}
const saved = results !== null && error === null
const field = (label: string, el: ReactNode, hint?: string) => (
<label className="block space-y-1">
<span className="text-xs font-medium text-muted">{label}</span>
{el}
{hint && <span className="block text-[11px] text-faint">{hint}</span>}
</label>
)
return (
<div className="flex min-h-0 flex-1 flex-col">
<div className="min-h-0 flex-1 space-y-3 overflow-y-auto p-5">
{field('Name', <input className={input} value={name} onChange={(e) => setName(e.target.value)} placeholder="NAS" autoFocus />)}
{field(
'Address',
<input className={`${input} font-mono`} value={host} onChange={(e) => setHost(e.target.value)} placeholder="192.168.1.20 or nas.local:8765" />,
'The server’s address on your network. Add :port if it is not 8765.',
)}
{field(
'Fallback address',
<input className={`${input} font-mono`} value={fallback} onChange={(e) => setFallback(e.target.value)} placeholder="Optional — e.g. its Tailscale address" />,
'Tried when the first one does not answer — away from home, for instance.',
)}
{field('Username', <input className={input} value={username} onChange={(e) => setUsername(e.target.value)} autoComplete="username" />)}
{field(
'Password',
<input
type="password"
className={input}
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder={initial?.has_password ? 'Unchanged' : ''}
autoComplete="current-password"
/>,
'Kept in this computer’s keychain.',
)}
{results && (
<div className="space-y-1 rounded-xl well px-3 py-2 text-xs">
{results.map((r) => (
<div key={r.address} className="flex items-start gap-2">
<span className={r.ok ? 'text-mint' : r.kind === 'unreachable' ? 'text-gold' : 'text-pink'}>
<Icon name={r.ok ? 'check' : r.kind === 'unreachable' ? 'warning' : 'close'} size={13} />
</span>
<span className="min-w-0 flex-1">
<span className="text-muted">{r.address === 'primary' ? 'Address' : 'Fallback'}</span>{' '}
<span className="font-mono text-faint">{r.url}</span>
{!r.ok && <span className="block text-faint">{r.error}</span>}
</span>
</div>
))}
</div>
)}
{error && (
<div className="rounded-xl bg-pink/10 px-3 py-2 text-xs text-pink shadow-[inset_0_0_0_1px_rgb(255_122_154/0.35)]">
{error}
</div>
)}
</div>
<div className="flex items-center justify-end gap-2 border-t border-line px-5 py-3">
{saved ? (
<button onClick={onSaved} className="rounded-full btn-primary px-4 py-1.5 text-sm font-semibold">
Done
</button>
) : (
<>
<button onClick={onCancel} className="btn-glass rounded-full px-4 py-1.5 text-sm text-muted hover:text-text">
Cancel
</button>
<button
disabled={!ready || busy}
onClick={() => void save()}
className="rounded-full btn-primary px-4 py-1.5 text-sm font-semibold disabled:cursor-not-allowed disabled:opacity-40"
>
{busy ? 'Checking…' : initial ? 'Save' : 'Add'}
</button>
</>
)}
</div>
</div>
)
}
/** The edits another computer left unsaved in the library: save, discard, or
* decide later. Esc is "later" — never a discard. */
function PendingEditsDialog({
edits,
onChoose,
onError,
}: {
edits: PendingEdits
onChoose: (choice: 'save' | 'discard' | 'later') => Promise<void>
onError: (msg: string) => void
}) {
const [busy, setBusy] = useState(false)
const choose = async (choice: 'save' | 'discard' | 'later') => {
setBusy(true)
try {
await onChoose(choice)
} catch (e) {
onError((e as Error).message)
setBusy(false)
}
}
return createPortal(
<div
aria-modal="true"
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-6 backdrop-blur-[3px]"
onKeyDown={(e) => e.key === 'Escape' && !busy && void choose('later')}
>
<div className="w-full max-w-sm overflow-hidden glass-overlay">
<div className="border-b border-line px-5 py-4 text-[15px] font-semibold tracking-tight">
Unsaved edits from {edits.machine || 'another computer'}
</div>
<div className="space-y-2 px-5 py-4 text-sm text-muted">
<p>This library has edits that were never saved: {edits.summary}.</p>
<p>Save them, or discard them to start from the library as it was last saved.</p>
</div>
<div className="flex items-center gap-2 border-t border-line px-5 py-3">
<button
disabled={busy}
onClick={() => void choose('later')}
className="rounded-full px-3 py-1.5 text-sm text-faint hover:text-text disabled:opacity-40"
>
Decide later
</button>
<span className="flex-1" />
<button
disabled={busy}
onClick={() => void choose('discard')}
className="rounded-full bg-pink/15 px-4 py-1.5 text-sm font-semibold text-[#ffd0da] shadow-[inset_0_0_0_1px_rgb(255_122_154/0.55)] hover:bg-pink/25 disabled:opacity-50"
>
Discard
</button>
<button
autoFocus
disabled={busy}
onClick={() => void choose('save')}
className="rounded-full btn-primary px-4 py-1.5 text-sm font-semibold disabled:opacity-50"
>
Save
</button>
</div>
</div>
</div>,
document.body,
)
}
+25
View File
@@ -1,4 +1,8 @@
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { api } from '../api'
import { useCaps } from '../lib/capabilities'
import { RemoteCacheSettings } from './RemoteCacheSettings'
import { ShortcutsDialog } from './ShortcutsDialog' import { ShortcutsDialog } from './ShortcutsDialog'
import { StemsSettings } from './StemsSettings' import { StemsSettings } from './StemsSettings'
@@ -15,7 +19,13 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
const [open, setOpen] = useState(false) const [open, setOpen] = useState(false)
const [showShortcuts, setShowShortcuts] = useState(false) const [showShortcuts, setShowShortcuts] = useState(false)
const [showStems, setShowStems] = useState(false) const [showStems, setShowStems] = useState(false)
const [showCache, setShowCache] = useState(false)
const ref = useRef<HTMLDivElement>(null) const ref = useRef<HTMLDivElement>(null)
// Path remapping is a library on THIS computer's business; a remote's
// mapping is its server's configuration.
const remappable = useCaps().paths.remappable
const collection = useQuery({ queryKey: ['collection'], queryFn: api.collection })
const remote = !!collection.data?.library?.remote
useEffect(() => { useEffect(() => {
if (!open) return if (!open) return
@@ -56,6 +66,7 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
up ? 'bottom-full mb-1' : 'mt-1' up ? 'bottom-full mb-1' : 'mt-1'
}`} }`}
> >
{remappable && (
<button <button
onClick={() => { onClick={() => {
onOpenPathMapping() onOpenPathMapping()
@@ -68,6 +79,19 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
Point the collection at moved or relocated files Point the collection at moved or relocated files
</span> </span>
</button> </button>
)}
{remote && (
<button
onClick={() => {
setShowCache(true)
setOpen(false)
}}
className={item}
>
<span className="text-sm text-text">Remote audio…</span>
<span className="text-[11px] text-faint">This computer's copies of the server's tracks</span>
</button>
)}
<button <button
onClick={() => { onClick={() => {
setShowStems(true) setShowStems(true)
@@ -92,6 +116,7 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
)} )}
{showShortcuts && <ShortcutsDialog onClose={() => setShowShortcuts(false)} />} {showShortcuts && <ShortcutsDialog onClose={() => setShowShortcuts(false)} />}
{showStems && <StemsSettings onClose={() => setShowStems(false)} />} {showStems && <StemsSettings onClose={() => setShowStems(false)} />}
{showCache && <RemoteCacheSettings onClose={() => setShowCache(false)} />}
</div> </div>
) )
} }
+31 -1
View File
@@ -1,4 +1,5 @@
import { Icon } from '../lib/icons' import { Icon } from '../lib/icons'
import type { RemoteConnection } from '../api'
/** A background job's progress, shown at the right of the bar. */ /** A background job's progress, shown at the right of the bar. */
export interface StatusJob { export interface StatusJob {
label: string label: string
@@ -29,6 +30,8 @@ interface Props {
loading?: boolean loading?: boolean
collectionName?: string | null collectionName?: string | null
onChangeCollection?: () => void onChangeCollection?: () => void
/** A remote library's connection; null for a library on this computer. */
connection?: RemoteConnection | null
} }
export function StatusBar({ export function StatusBar({
@@ -40,6 +43,7 @@ export function StatusBar({
loading, loading,
collectionName, collectionName,
onChangeCollection, onChangeCollection,
connection,
}: Props) { }: Props) {
return ( return (
<div className="glass flex h-7 shrink-0 items-center gap-3 !rounded-full px-4 text-[11px] text-muted"> <div className="glass flex h-7 shrink-0 items-center gap-3 !rounded-full px-4 text-[11px] text-muted">
@@ -145,10 +149,11 @@ export function StatusBar({
</button> </button>
</div> </div>
)} )}
{connection && <ConnectionDot connection={connection} pushRight={!job} />}
{collectionName && ( {collectionName && (
<button <button
onClick={onChangeCollection} onClick={onChangeCollection}
className={`${job ? '' : 'ml-auto '}flex items-center gap-1.5 rounded px-2 py-0.5 text-faint hover:bg-ink-800 hover:text-text`} className={`${job || connection ? '' : 'ml-auto '}flex items-center gap-1.5 rounded px-2 py-0.5 text-faint hover:bg-ink-800 hover:text-text`}
title="Change collection" title="Change collection"
> >
<Icon name="link" size={12} /> <Icon name="link" size={12} />
@@ -158,3 +163,28 @@ export function StatusBar({
</div> </div>
) )
} }
/** How this computer stands with a remote library's server, in a word. */
function ConnectionDot({ connection, pushRight }: { connection: RemoteConnection; pushRight: boolean }) {
const { state, via, machine } = connection
const look = {
connected: { dot: 'bg-mint shadow-[0_0_6px_var(--color-mint)]', text: via === 'fallback' ? 'Connected · fallback' : 'Connected' },
reconnecting: { dot: 'bg-gold animate-pulse', text: 'Reconnecting…' },
offline: { dot: 'bg-pink', text: 'Offline' },
taken_over: { dot: 'bg-pink', text: `Taken over${machine ? ` by ${machine}` : ''}` },
}[state]
const title =
state === 'connected'
? `Connected to the server through its ${via === 'fallback' ? 'fallback' : 'main'} address`
: state === 'taken_over'
? 'Another computer holds this library; it is read-only here'
: state === 'offline'
? 'The server cannot be reached; the library is read-only until it is back'
: 'Trying to reach the server again'
return (
<span className={`${pushRight ? 'ml-auto ' : ''}flex shrink-0 items-center gap-1.5 text-faint`} title={title}>
<span className={`h-1.5 w-1.5 rounded-full ${look.dot}`} />
<span>{look.text}</span>
</span>
)
}
+7
View File
@@ -43,6 +43,13 @@ const PATHS = {
</> </>
), ),
export: <path d="M12 3v12M7 8l5-5 5 5M5 15v4a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-4" />, export: <path d="M12 3v12M7 8l5-5 5 5M5 15v4a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-4" />,
server: (
<>
<rect x="3" y="4" width="18" height="7" rx="2" />
<rect x="3" y="13" width="18" height="7" rx="2" />
<path d="M7 7.5h.01M7 16.5h.01M11 7.5h6M11 16.5h6" />
</>
),
download: <path d="M12 3v12M7 10l5 5 5-5M5 19h14" />, download: <path d="M12 3v12M7 10l5 5 5-5M5 19h14" />,
settings: ( settings: (
<> <>
+28
View File
@@ -57,6 +57,10 @@ export function readOnlyNotice(caps: Capabilities): string | null {
return 'This file is not in your collection yet — add it to edit its tags, cues or beatgrid.' return 'This file is not in your collection yet — add it to edit its tags, cues or beatgrid.'
case 'browsing': case 'browsing':
return `This ${caps.save.app_name} drive is open for browsing. Open it for editing to change it.` return `This ${caps.save.app_name} drive is open for browsing. Open it for editing to change it.`
case 'taken_over':
return 'Another computer has taken over this remote library, so it is read-only here. Open it again to take it back.'
case 'offline':
return 'The server holding this library cannot be reached. It is read-only until the connection comes back.'
case 'platform_incomplete': case 'platform_incomplete':
default: default:
return `Konduktor can read ${caps.save.app_name} libraries but cannot save changes to them yet.` return `Konduktor can read ${caps.save.app_name} libraries but cannot save changes to them yet.`
@@ -67,6 +71,8 @@ export function readOnlyNotice(caps: Capabilities): string | null {
export function readOnlyShort(caps: Capabilities): string | null { export function readOnlyShort(caps: Capabilities): string | null {
if (caps.writable) return null if (caps.writable) return null
if (caps.readonly_cause === 'not_in_library') return 'Not in collection' if (caps.readonly_cause === 'not_in_library') return 'Not in collection'
if (caps.readonly_cause === 'taken_over') return 'Read-only · taken over'
if (caps.readonly_cause === 'offline') return 'Read-only · offline'
return caps.readonly_cause === 'cloud_synced' ? 'Read-only · cloud-synced' : 'Read-only' return caps.readonly_cause === 'cloud_synced' ? 'Read-only · cloud-synced' : 'Read-only'
} }
@@ -85,6 +91,11 @@ export function readOnlyShort(caps: Capabilities): string | null {
* Someone told "not found" about OneLibrary would go hunting for a missing app. * Someone told "not found" about OneLibrary would go hunting for a missing app.
*/ */
export function platformAvailability(p: PlatformOption): string { export function platformAvailability(p: PlatformOption): string {
// A remote is reached, not found: `found` counts the saved ones.
if (p.selects === 'remote') {
if (p.found > 1) return `${p.found} saved servers`
return p.found === 1 ? '1 saved server' : 'A library on a Konduktor server'
}
if (p.found > 1) return p.removable ? `${p.found} drives connected` : `${p.found} found` if (p.found > 1) return p.removable ? `${p.found} drives connected` : `${p.found} found`
if (p.found === 1) return p.removable ? '1 drive connected' : `${p.library_label} found` if (p.found === 1) return p.removable ? '1 drive connected' : `${p.library_label} found`
return p.removable ? 'No drive connected' : `No ${p.library_label} in the usual place` return p.removable ? 'No drive connected' : `No ${p.library_label} in the usual place`
@@ -127,3 +138,20 @@ export function removalNote(caps: Capabilities, count: number): string {
? ', and a save can be rolled back from version history.' ? ', and a save can be rolled back from version history.'
: ', and that save cannot be undone.'}` : ', and that save cannot be undone.'}`
} }
// ---- a remote library -----------------------------------------------------------
/** "Studio iMac (since 14:02) — a stem conversion is running there". */
export function remoteHolder(machine: string | null, since: string | null, batch: string | null): string {
const who = machine || 'another computer'
const when = since ? new Date(since).toLocaleString(undefined, { timeStyle: 'short', dateStyle: 'medium' }) : null
const what: Record<string, string> = {
'grid-analysis': 'a beatgrid analysis',
'auto-hotcues': 'an Auto Hotcues run',
'stem-conversion': 'a stem conversion',
import: 'an import',
export: 'an export',
}
const running = batch ? ` — ${what[batch] ?? 'a batch'} is running there, and taking over cancels it` : ''
return `${who}${when ? ` has had it open since ${when}` : ' has it open'}${running}.`
}
+2
View File
@@ -70,6 +70,8 @@ export function PlatformIcon({
// Masks are addressed by id, and one page can show the same mark twice. // Masks are addressed by id, and one page can show the same mark twice.
const mask = `pm-${useId().replace(/:/g, '')}` const mask = `pm-${useId().replace(/:/g, '')}`
const Mark = MARKS[platform] ?? MARKS[ALIASES[platform]] const Mark = MARKS[platform] ?? MARKS[ALIASES[platform]]
// A remote is a way to reach a library, not a platform with a mark of its own.
if (platform === 'remote') return <Icon name="server" size={size} className={className} />
if (!Mark) return <Icon name="music" size={size} className={className} /> if (!Mark) return <Icon name="music" size={size} className={className} />
return ( return (
<svg <svg
+29
View File
@@ -0,0 +1,29 @@
# The Konduktor server: one library (Traktor or Rekordbox), held where its audio
# lives, opened from the desktop app as a "Remote" library.
#
# Build from the REPOSITORY ROOT (the version is read from frontend/package.json):
# docker build -f server/Dockerfile -t konduktor-server .
#
# Configuration is the environment — see server/.env.example.
FROM python:3.12-slim AS build
RUN apt-get update \
&& apt-get install -y --no-install-recommends git \
&& rm -rf /var/lib/apt/lists/*
COPY backend/requirements-server.txt /tmp/requirements-server.txt
RUN pip install --no-cache-dir --prefix=/install -r /tmp/requirements-server.txt
FROM python:3.12-slim
ENV PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1 \
KONDUKTOR_DATA_DIR=/data \
KONDUKTOR_PORT=8765
COPY --from=build /install /usr/local
# `konduktor/__init__.py` reads the app version from <repo>/frontend/package.json,
# two levels above the package.
COPY frontend/package.json /app/frontend/package.json
COPY backend/konduktor /app/backend/konduktor
WORKDIR /app/backend
# History, export sets and the stems ledger.
VOLUME ["/data"]
EXPOSE 8765
CMD ["python", "-m", "konduktor.server"]
+18
View File
@@ -0,0 +1,18 @@
# Konduktor server — e.g. as a TrueNAS SCALE custom app (Apps → Discover Apps →
# ⋮ → Install via YAML), or `docker compose up -d` anywhere with Docker.
#
# Mount your datasets on the left-hand side; the right-hand paths are what
# .env refers to.
services:
konduktor:
image: ghcr.io/mrpatben8/konduktor-server:latest
env_file: .env
ports:
- "8765:8765"
volumes:
- /mnt/tank/music:/music # the audio (KONDUKTOR_CONTENT)
- /mnt/tank/konduktor/library:/library # collection.nml / master.db
- /mnt/tank/konduktor/data:/data # history, export sets, ledger
# TrueNAS's "apps" user, so files written on the datasets keep its ownership.
user: "568:568"
restart: unless-stopped