diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 7440c95..99a1b08 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -114,6 +114,50 @@ jobs: if-no-files-found: error 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. # Runs once, after both builds succeed, so the two matrix jobs never race to # create the same tag/release. diff --git a/CLAUDE.md b/CLAUDE.md index 25e5941..f52243a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -114,6 +114,43 @@ Two independent apps that talk over HTTP: `backend/bench_grid_detect.py` scores it against any library's single-marker grids and reports that constant separately from detection error (29 Rekordbox references: old 1/29 BPMs, new 27/29). + Either half can be HELD — the Analyze dialog's BPM / Grid ticks: + `bpm=` keeps that tempo (no search, no round snap, no re-octave) and + finds only the phase; `anchor=` detects the tempo and returns the anchor + untouched, `drift_ms` then measuring how well the kept anchor fits. + `bench_grid_detect.py --hold bpm|anchor` scores each alone (2026-10-04, + 15 local refs: phase given the right BPM 15/15; tempo given the right + anchor 14/15, the same miss as full analysis). + - `grid_plan.py` — **what an analysis does to one track's grid**, as one + pure function (`plan_grid` → `GridStep`) so the batch, the dialog's + counts and the tests agree. BPM+Grid = full, an existing grid replaced + only with Replace ticked; BPM alone keeps the first marker's anchor; Grid + alone keeps its BPM (else the track's TEMPO). With ONE tick, Replace does + not apply (adjusting is the point) and a track with nothing to keep is + analysed in full; a flexible grid is skipped, never flattened; locked is + always skipped. `main._analyse_grid` writes each through the hand-edit + command for the same thing — `set_grid_marker_bpm(0)` / `move_grid_marker(0)` + — so companions, marker names and time bases behave as for a hand edit. + - `key_detect.py` + `key_model.npz` — **musical key detection**: a small + CNN (Korzeniowski & Widmer 2017 — five 5x5 convs, a per-frame dense layer + over the WHOLE pitch axis, since a key is not pitch-invariant, logits + averaged over time), an ensemble of three, run in NUMPY — torch only + trains it (`backend/train_key_model.py`, engine venv), the backend never + imports it. Input is a 7-octave CQT at 36 bins/octave (C1–C8); the net + sees C2–C7, the spare octaves are for pitch-shift augmentation. Trained + on GiantSteps MTG, scored on the separate GiantSteps key set + (`bench_key_detect.py`): **69.4% exact, 83.4% harmonically mixable**; + key templates (Krumhansl/Temperley/KeyFinder/EDM) topped out at 49.5% on + the same features. ~0.6 s per track beside the decode. Always returns a + key for music (confidence tracks accuracy, but even the lowest band is + ~10x chance); None only for silence / under 5 s. The datasets are NOT on + the machine by default — fetch steps are in the training script. + - `musical_key.py` — the generic key (Camelot wheel 1-12 + mode) and the + three notations libraries STORE: `camelot` (8A), `open_key` (1m — Traktor's + default, Open Key n = Camelot n+7) and `musical` (Am, spelt as rekordbox + spells its own rows: flats for Db/Eb/Ab/Bb, F#). `parse` accepts all + three (and "Amin", "F# minor"), because a library holds what imported + tags said: a rekordbox stick's key table had "12A" beside "Abm". - `stem_file.py` + `tag_copy.py` — **writing a native-instruments STEM file** (Convert to Stems). An `ipod` MP4 with five AAC stereo 44.1 kHz streams (mix, drums, bass, synths, vox), streams 1-4 `disposition` 0, @@ -487,6 +524,105 @@ Two independent apps that talk over HTTP: 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, 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:` 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 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 @@ -533,7 +669,13 @@ Two independent apps that talk over HTTP: "Map by hand…" link to `PathMappingDialog`; no backdrop-click dismiss. - `prefs.py` — persisted user prefs (`userprefs.json` in the per-OS app-data dir). Last-opened collection (global AND per-platform), library column - layout, prep-deck zoom, import destination. Best-effort. + layout, prep-deck zoom, import destination. Best-effort, but **every + read-modify-write holds `_LOCK` and every write is atomic** + (`paths.write_json`): the UI sends several PATCHes at once on launch, and + unlocked, with a truncating write, a reader caught the file empty and wrote + back only its own key — wiping every pref, the column layout included. A + file that will not parse is moved to `userprefs.json.corrupt`, never + silently overwritten. New helpers that read then write must take the lock. - `schemas.py` — HTTP request bodies + envelopes; re-exports `core.model`. - `main.py` — thin FastAPI routes (all under `/api`), talking only to the adapter. Starts **unloaded**; the library is chosen at runtime via @@ -719,6 +861,18 @@ Two independent apps that talk over HTTP: original files" while conversions are pending (decided: the consequence is shown where Save is pressed). `Toast` takes an optional `action`; `StatusJob.unit: 'bytes'` shows a download in MB. Every background job's status-bar entry reads label + count · a bar SPLIT horizontally when the job reports per-item progress (top = the current item's `fraction`, 0-100 %; bottom = the whole job, (done + fraction) / total, so 99 % into the first of two tracks reads ~50 %) — a single bar otherwise; two colours in one bar was tried and read as confusing · its `status` ("separating 41 %") at its natural width · the item's name LAST (the only part that truncates; full name on hover). The section is a FIXED width (560 px; the view name on the left gives way instead) and everything BEFORE the bar is fixed (count sized for its largest value, "cancelling…" as a status, not a label), so neither a long name nor a phase change moves the bar. The status deliberately has no fixed slot: it is after the bar, and a slot left a gap before the name. `Job.fraction`/`status` come from `JobHandle.progress(fraction=, status=)` and reset whenever `done` advances; a stem conversion maps decode / separate / encode onto a track's 0-1 by measured shares. + `AnalyzeDialog` (the context menu's **Analyze…**, decided 2026-10-04: + BPM / Grid / Key ticks, remembered as `analyzeWhat`, each disabled with a + reason where the library cannot store it — offered when EITHER grids or + keys are writable; the Replace questions are inside the dialog, never a + second popup, and never remembered: the grid's only when BPM AND Grid are + ticked, since with one tick adjusting the grid is the point. Every count + and the "Analyze N" button come from `/api/tracks/analyze/preview`, i.e. + the backend's own `plan_grid`. The finished job's toast says what was + written and skipped, by reason. The deck's one-click Analyze writes the + key too, and App hands the deck the fresh copy of its track whenever the + view it came from refetches — the deck otherwise held a load-time + snapshot, so neither an analysed key nor an Edit Tags change reached it), `AutoCueDialog` (the Auto Hotcues slot template: event + beat offset per slot, a per-slot Replace tick for occupied slots — never remembered, since overwriting is a decision about THIS track — and the template itself @@ -842,7 +996,11 @@ Two independent apps that talk over HTTP: via `GET`/`PATCH /api/prefs` (debounced; hydrated on launch, merged against defaults so newly-added columns still appear). The prep deck's main-waveform zoom persists the same way (`mainZoomSec`, hydrated in `PrepStrip` from the - shared `['prefs']` query). + shared `['prefs']` query). Continuously-changing prefs (columns, zoom, + `beatSize`) are written through ONE debounced writer, `lib/prefs.ts` + (`usePrefsWriter` / `queuePrefs`): changes merge into one PATCH, sent in + order, and the queue outlives unmounts; `QuitGuard` calls `flushPrefs()` + before quitting. Do not give a new pref its own timer. ## Commands @@ -854,6 +1012,13 @@ cd backend && source .venv/bin/activate uvicorn konduktor.main:app --reload --port 8000 # 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 cd frontend npm run dev # dev server (proxies /api -> :8000) @@ -881,7 +1046,12 @@ serialization path.** It enforces: — onto a staying track's path, or two differently-keyed entries for one file — which the preview reports first, while a chain (A onto B's old path, B onward) and a pre-existing duplicate are allowed, each track's staged art - and edits following the TRACK (H4). + and edits following the TRACK (H4). And **`set_key`** (N): on a keyed + entry only its INFO and MUSICAL_KEY lines change; an unkeyed one gains the + KEY attribute and one `` between LOUDNESS and CUE_V2 in + Traktor's layout; the encoding matches the real collection; a Camelot + collection gets Camelot; an ADDED Pioneer key ("Abm") lands as "6m"; and the + key tag reaches TKEY / `initialkey` in MP3, FLAC and M4A. The guard that catches serialization regressions like the lxml reformatting bug. - `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays Traktor-valid, backup-first, COLLECTION byte-identical, original untouched. @@ -970,6 +1140,11 @@ serialization path.** It enforces: (pad, colour), loop and memory cue cross as themselves; and removing it deletes its analysis files. `test_folders.py` drives the same through `/api/folder/add` on a Rekordbox copy, and a non-addable library 422s. + And **`set_key`** (K): a key the library has changes exactly the track row + and the counter, pointing at its OWN row (found by meaning, not name); a + missing key adds one `djmdKey` row as rekordbox creates its own — its + spelling, `Seq` NULL, its own USN (so through the ORM; a raw insert is + left unstamped) — which the next `set_key` reuses. - `test_onelibrary_adapter.py` — the third adapter against the same contract. Unlike the Rekordbox tests it needs **nothing installed and nothing plugged in**: it runs against `fixtures/onelibrary/`, a real rekordbox 7 export trimmed @@ -988,7 +1163,10 @@ serialization path.** It enforces: `nameForSearch` NULL, a new playlist on top with siblings shifted, entries from 1; and the stick hazards — another app's write refused, an unplugged drive keeps the edits, stale `-shm` deleted, the backup holds the old rows, - the drive never held open, file tags written (title yes, rating no). + the drive never held open, file tags written (title yes, rating no). And + `set_key`: an existing key changes only `content.key_id` and reaches TKEY as + the stick names it; a missing one adds a key row in rekordbox's spelling; + on Goober, "12A" projects a key and setting 12A reuses that row. - `test_onelibrary_anlz.py` — cue and grid edits in the ANLZ files. First against **rekordbox's own edit** of the same thing (`fixtures/onelibrary-goober/after/`): a recolour's `PCO2` and a grid edit's @@ -1024,8 +1202,17 @@ serialization path.** It enforces: tempo and first beat are known rather than borrowed from another analyser: exact integer and non-integer BPMs, the 125 BPM the old detector could not return, octave choice, and the loud off-beat hat and syncopated bassline that - each fooled one band on real music. Accuracy on REAL music is + each fooled one band on real music. Holding either half: a held BPM comes + back untouched (never snapped or re-octaved, a wrong one reports drift) with + the phase still found through the hat/bass traps; a held anchor comes back + untouched with the tempo detected, an off-beat one reported as drift. And + `plan_grid`'s every rule. Accuracy on REAL music is `bench_grid_detect.py`'s job (not in `run_tests.sh`: it needs audio). +- `test_key_detect.py` — key detection on SYNTHETIC cadences in all 24 keys + (I-IV-V-I / i-iv-V-i — a pop I-V-vi-IV is fairly called minor by an EDM + model), loudness / sample-rate invariance, None for silence, and the numpy + convolution against a direct implementation. Accuracy on real music is + `bench_key_detect.py`'s job (GiantSteps + any folder of key-tagged files). - `test_auto_hotcues.py` — Auto Hotcues in three layers: `structure.analyse` on SYNTHETIC audio with known sections (the intro with a kick is not a drop; no breakdown after the last drop), `plan`'s outcomes and beat-counted offsets @@ -1033,7 +1220,7 @@ serialization path.** It enforces: collection — the previous implementation's route returned 500 on every call for a week while its helper's tests passed. - `test_grid_batch.py` — **batch analysis** from the context menu, both - `jobs.py` jobs shown in the status bar: Analyze Grid & BPM + `jobs.py` jobs shown in the status bar: Analyze… (BPM / Grid / Key) (`POST /api/tracks/grid/auto-batch`) and Auto Hotcues… (`POST /api/tracks/cue/auto-batch`, one template for every track). Pins the batch-only decisions: locked grids are skipped always, existing grids unless @@ -1045,6 +1232,20 @@ serialization path.** It enforces: returns its result; opening another library cancels the run. Each shares its helper (`_analyse_grid`, `_place_auto_cues`) with the deck's single-track button. + Also BPM alone / Grid alone through `_analyse_grid` on a real Traktor copy: + the detector is asked to hold the right half, BPM alone retempos the marker + in place with its beat-1 cue untouched, Grid alone moves it (cue dragged + along) at the same tempo, and a TEMPO-only track gets one marker at it. + And **Analyze** (`POST /api/tracks/analyze` + `/analyze/preview`, the + dialog's BPM / Grid / Key; `grid/auto-batch` is now an alias of it with + BPM+Grid): nothing ticked 400s; Key alone sets keyless tracks, skips keyed + ones unless `replace_key`, never touches a grid; the preview's counts match + the run's (BPM alone: single grids adjusted, flexible skipped, bare in + full); a skipped track is never decoded and grid+key share ONE decode; a + grid that cannot be fitted still gets its key; the deck's Analyze writes + the key too and never fails on it. The decode is `main._decode_for_analysis` + (the seam the fakes replace); `test_key_detect.py` runs the route once with + the REAL decode and detectors on a generated F-minor 124 BPM WAV. - `test_bulk_remove.py` — the context menu's **Remove ▸** routes (`/api/tracks/grid/clear`, `/api/tracks/cue/clear`, `/api/tracks/remove`): locked grids are kept, clearing hotcues empties the whole bank (loops and the @@ -1071,6 +1272,11 @@ serialization path.** It enforces: as a drive, and that the adapter and the browser share ONE mount scanner. Needs nothing installed: every assertion is about the SHAPE of the answer, and prefs are redirected to a temp file so a test can never rewrite the user's last-opened library. +- `test_prefs.py` — `userprefs.json` under concurrent writes: 200 bursts of + simultaneous patches (plus a reader) keep every key and every patch; the + last-collection and path-mapping helpers lose nothing either; an unreadable + file is moved aside, not overwritten. Against the old unlocked code it fails + on the first trial. - `test_exports.py` — export sets against a temp copy of the real collection. Pins the things that would fail SILENTLY: a live reference picks up a playlist edited AFTER curation; contents dedupe across playlists and loose tracks; a @@ -1123,11 +1329,35 @@ serialization path.** It enforces: 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 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 `` 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 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 **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 frontend at `http://localhost:5173`. @@ -1160,7 +1390,15 @@ frontend at `http://localhost:5173`. e.g. `Macintosh HD/:Music/:one.mp3`. This is how playlist entries (`PRIMARYKEY.KEY`) join to collection tracks. `Track.id` uses this. - **Rating** = `RANKING / 51`, giving 0–5 stars (`_rating_stars`). -- **Key** is Traktor's display key string, e.g. `"10m"` (Open Key notation). +- **Key** = two fields. `INFO@KEY` is the display text Traktor shows and tags + files with, in the user's notation (Open Key `"10m"` in the real + collection); `` is the analysed key, pitch class + 12 for + minor (`12` = C minor = `10m`; 6,628 of 6,641 entries carrying both agree). + 1,354 entries have ONLY `MUSICAL_KEY` — analysed, never given text — so + `projection.entry_key` falls back to it (rendered Open Key). `set_key` and + `add_entry` write BOTH, the text in the collection's majority notation + (`TraktorStore.key_notation()`; an empty collection — an export — takes a + Traktor-native source's own, so Traktor→Traktor keeps the user's). - **Beatgrid = an ORDERED LIST of markers**, never a single BPM + anchor. Traktor stores each as a `CUE_V2 TYPE="4"` with its own `` child (flexible beatgrids, 3.4+); `` mirrors the **first marker by @@ -1353,7 +1591,8 @@ that number and nothing else — everything derives from it: (`waveform.decode` → `analyse_samples` + `grid_detect`), in a first phase that may be cancelled through `checkpoint` before the library is touched; a file with no grid of its own gets Konduktor's (decided: arrive ready to - prep). Then `RekordboxStore.add_track` writes the row the way Rekordbox's + prep), and one with no key of its own a detected key + (`key_detect.with_detected_key`, from the same decode; OneLibrary too). Then `RekordboxStore.add_track` writes the row the way Rekordbox's own add was MEASURED to (file facts, `DateCreated` from the file's birth time, this library's device) and the grid/cues replay through `replace_grid`/`set_cue`/`add_memory_cue` — memory cues and colours cross @@ -1585,7 +1824,12 @@ that number and nothing else — everything derives from it: **Key notation crosses via the wheel**, never by copying the string: `projection.render_key()` is the inverse of `parse_key`, shared by both Pioneer targets, so Traktor's `"10m"` becomes `"Cm"` rather than a literal `"10m"` in a - Pioneer library. **Caveat**: `djmdContent.FolderPath` is an ABSOLUTE host path, + Pioneer library. Both are now `core/musical_key`; until 2026-10-04 + `render_key` spelt with SHARPS ("G#m", "D#", "C#m") where rekordbox's own rows + say "Abm", "Eb", "Dbm" — measured from the key rows rekordbox 7 created in + the local library. In-place writes (`set_key`, adds) find a key row by + MEANING, so a library's existing "12A" or "G#m" row is reused, never + duplicated. **Caveat**: `djmdContent.FolderPath` is an ABSOLUTE host path, so unlike Traktor and OneLibrary a Rekordbox export is not portable by copying the folder. Still unwritten and documented as unknown: OneLibrary's waveform tags and the `cue` table's MPEG seek columns. @@ -1651,6 +1895,13 @@ that number and nothing else — everything derives from it: yet**, since nothing can be written. Note the OneLibrary work already demonstrated creating an `exportLibrary.db` from nothing, and `fixtures/onelibrary/schema.sql` 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 - ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging diff --git a/README.md b/README.md index 1d117d4..a15304b 100644 --- a/README.md +++ b/README.md @@ -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 - Konduktor is built on [`traktor-nml-utils`](https://github.com/MrPatben8/traktor-nml-utils) diff --git a/backend/bench_grid_detect.py b/backend/bench_grid_detect.py index aa8f4a6..73a71e7 100644 --- a/backend/bench_grid_detect.py +++ b/backend/bench_grid_detect.py @@ -6,6 +6,8 @@ compare rather than a pass/fail. Every open is read-only — nothing is saved. python bench_grid_detect.py # the local Rekordbox library python bench_grid_detect.py path/to/collection.nml path/to/master.db python bench_grid_detect.py --legacy # score the old librosa beat_track + python bench_grid_detect.py --hold bpm # Grid alone: phase, given the right BPM + python bench_grid_detect.py --hold anchor # BPM alone: tempo, given the right anchor The reference is each track's own grid, and only single-marker grids are used: a multi-marker grid is either a real tempo change (which a constant-tempo @@ -102,6 +104,9 @@ def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("libraries", nargs="*", type=Path) ap.add_argument("--legacy", action="store_true", help="score the old librosa beat_track detector") + ap.add_argument("--hold", choices=("bpm", "anchor"), + help="score one half alone: hold the REFERENCE's BPM (the Analyze dialog's " + "'Grid' tick — phase is all that is scored) or its anchor ('BPM')") args = ap.parse_args() libs = args.libraries or [Path.home() / "Library/Pioneer/rekordbox/master.db"] @@ -119,7 +124,8 @@ def main() -> int: for name, audio, r0, rb in refs: t0 = time.perf_counter() try: - res = detect(str(audio)) + hold = {"bpm": {"bpm": rb}, "anchor": {"anchor": r0}}.get(args.hold, {}) + res = detect(str(audio), **hold) except Exception as ex: # a failure is a data point, not a crash print(f" FAIL {name[:48]:48} {ex}") rows.append(None) diff --git a/backend/bench_key_detect.py b/backend/bench_key_detect.py new file mode 100644 index 0000000..bd7ef35 --- /dev/null +++ b/backend/bench_key_detect.py @@ -0,0 +1,172 @@ +"""Benchmark key detection (`core/key_detect.py`). + +NOT part of `run_tests.sh`: it needs real audio, and the answer is a score to +compare rather than a pass/fail. + + python bench_key_detect.py --giantsteps DATA/gs # hand-annotated EDM + python bench_key_detect.py ~/Music # files with a key TAG + +GiantSteps (604 Beatport previews, keys corrected by hand) is ground truth +and the number to quote; the model never trained on it (see +`train_key_model.py`). A folder's key tags were written by some other +analyser — usually Traktor, sometimes Mixed In Key or a store — so that score +is AGREEMENT with it, not accuracy. Copies of one song (a stem file beside its +source) count once, by title. + +Errors are classed the MIREX way, because they are not equally wrong for a +DJ: a FIFTH (one step round the Camelot wheel) or the RELATIVE key (same +number, other letter) still mixes harmonically; PARALLEL (same tonic, other +mode) and OTHER do not. MIREX's weighted score is 1 / 0.5 / 0.3 / 0.2 / 0. +""" +from __future__ import annotations + +import argparse +import os +import re +import sys +import warnings +from collections import Counter +from concurrent.futures import ProcessPoolExecutor +from pathlib import Path + +warnings.filterwarnings("ignore") + +from konduktor.core import key_detect, musical_key # noqa: E402 + +WEIGHT = {"exact": 1.0, "fifth": 0.5, "relative": 0.3, "parallel": 0.2, "other": 0.0} +AUDIO = {".mp3", ".m4a", ".mp4", ".flac", ".aif", ".aiff", ".wav", ".ogg"} + + +def relation(det: tuple[int, str], ref: tuple[int, str]) -> str: + """How a detected (wheel, mode) relates to the reference.""" + (dw, dm), (rw, rm) = det, ref + if (dw, dm) == (rw, rm): + return "exact" + if dw == rw: + return "relative" + if dm == rm and (dw - rw) % 12 in (1, 11): + return "fifth" + if dm != rm: + major, minor = (dw, rw) if dm == "major" else (rw, dw) + if (major - minor) % 12 == 3: # C major 8B vs C minor 5A + return "parallel" + return "other" + + +def parse_any(text: str) -> tuple[int, str] | None: + """Open Key, Camelot or a named key ("Abm", "F# minor", "Gmin").""" + w, m = musical_key.parse(text) + return (w, m) if w else None + + +def _tag_key(path: Path) -> tuple[str, str] | None: + import mutagen + + try: + f = mutagen.File(path) + except Exception: + return None + if not f or not f.tags: + return None + t = f.tags + + def has(name: str) -> bool: + try: + return name in t + except ValueError: # a Vorbis comment refuses an MP4-style atom name + return False + + key = title = None + for name in ("TKEY", "----:com.apple.iTunes:initialkey", "initialkey", "INITIALKEY"): + if has(name): + v = t[name] + v = v.text[0] if hasattr(v, "text") else v[0] + key = v.decode() if isinstance(v, bytes) else str(v) + break + for name in ("TIT2", "\xa9nam", "title", "TITLE"): + if has(name): + v = t[name] + title = str(v.text[0] if hasattr(v, "text") else v[0]) + break + return (key, title or path.stem) if key else None + + +def folder_refs(roots: list[Path]) -> list[tuple[Path, tuple[int, str], str]]: + seen, out = set(), [] + for root in roots: + for dp, dirs, files in os.walk(root): + dirs[:] = sorted(d for d in dirs if not d.startswith(".")) + for name in sorted(files): + p = Path(dp) / name + if p.suffix.lower() not in AUDIO or name.startswith("."): + continue + tagged = _tag_key(p) + if not tagged or not (ref := parse_any(tagged[0])): + continue + title = re.sub(r"\.stem$", "", tagged[1].strip().lower()) + if title not in seen: + seen.add(title) + out.append((p, ref, tagged[1])) + return out + + +def giantsteps_refs(gs: Path) -> list[tuple[Path, tuple[int, str], str]]: + out = [] + for f in sorted((gs / "annotations/key").glob("*.key")): + audio = gs / "audio" / f"{f.stem}.mp3" + ref = parse_any(f.read_text()) # "C minor" + if audio.exists() and ref: + out.append((audio, ref, f.stem)) + return out + + +def _detect(path: Path): + warnings.filterwarnings("ignore") + try: + r = key_detect.detect_key(str(path)) + except Exception as ex: # an undecodable file is reported, not fatal + return None, str(ex) + return (r.wheel, r.mode, r.name, r.confidence) if r else None, None + + +def run(refs, label: str, verbose: bool) -> None: + with ProcessPoolExecutor() as ex: + results = list(ex.map(_detect, [p for p, _, _ in refs], chunksize=2)) + rels, misses = [], [] + for (path, ref, title), (det, err) in zip(refs, results): + if det is None: + print(f" could not analyse {title}: {err or 'silent / too short'}") + continue + rel = relation(det[:2], ref) + rels.append(rel) + if rel != "exact": + misses.append((title, ref, det, rel)) + n = len(rels) + if not n: + print(f"{label}: nothing to score") + return + c = Counter(rels) + print(f"\n{label}: {n} tracks") + for k in WEIGHT: + print(f" {k:9s} {c[k]:4d} {100 * c[k] / n:5.1f}%") + print(f" MIREX weighted score {sum(WEIGHT[r] for r in rels) / n:.3f}") + print(f" harmonically mixable (exact + fifth + relative) {100 * (c['exact'] + c['fifth'] + c['relative']) / n:.1f}%") + if verbose: + for title, ref, det, rel in misses: + print(f" {rel:9s} ref {ref[0]}{'A' if ref[1] == 'minor' else 'B'} " + f"got {det[0]}{'A' if det[1] == 'minor' else 'B'} ({det[2]}, p={det[3]:.2f}) {title[:60]}") + + +if __name__ == "__main__": + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("folders", nargs="*", type=Path, help="folders of audio files carrying a key tag") + ap.add_argument("--giantsteps", type=Path, help="a downloaded giantsteps-key-dataset clone") + ap.add_argument("-v", "--verbose", action="store_true", help="list every miss") + a = ap.parse_args() + if not a.folders and not a.giantsteps: + ap.error("give --giantsteps and/or folders") + if a.giantsteps: + run(giantsteps_refs(a.giantsteps), "GiantSteps key (hand-annotated)", a.verbose) + if a.folders: + run(folder_refs(a.folders), "Key tags (agreement with another analyser)", a.verbose) + sys.exit(0) diff --git a/backend/konduktor-sidecar.spec b/backend/konduktor-sidecar.spec index ca2490b..fb2f436 100644 --- a/backend/konduktor-sidecar.spec +++ b/backend/konduktor-sidecar.spec @@ -10,7 +10,7 @@ # - python-multipart is imported as `multipart` by starlette → hidden import # - dulwich (version-history backups) imports git backends dynamically → # collect_submodules('dulwich') -from PyInstaller.utils.hooks import collect_submodules, collect_all +from PyInstaller.utils.hooks import collect_all, collect_submodules, copy_metadata hiddenimports = [] datas = [] @@ -31,6 +31,12 @@ for pkg in ("uvloop", "httptools", "websockets", "av"): # Imported by name, not statically discoverable. hiddenimports += ["multipart", "anyio"] +# A remote library's password lives in the OS keychain through `keyring`, which +# finds its backends (macOS Keychain, Windows Credential Manager) by entry point +# — so both the modules AND the package metadata that names them must ship. +hiddenimports += collect_submodules("keyring") +datas += copy_metadata("keyring") + # Bundle the canonical version file so konduktor.__version__ can read it at # runtime from sys._MEIPASS (frontend/package.json is the single source of the # app version — see konduktor/__init__.py). Path is relative to this spec. @@ -54,6 +60,8 @@ datas += [ ("konduktor/stems/engine.json", "konduktor/stems"), ("konduktor/stems/weights.json", "konduktor/stems"), ] +# The key-detection network's weights (konduktor/core/key_detect.py). +datas += [("konduktor/core/key_model.npz", "konduktor/core")] a = Analysis( ["sidecar.py"], diff --git a/backend/konduktor/adapters/onelibrary/adapter.py b/backend/konduktor/adapters/onelibrary/adapter.py index e89f131..002fdea 100644 --- a/backend/konduktor/adapters/onelibrary/adapter.py +++ b/backend/konduktor/adapters/onelibrary/adapter.py @@ -21,7 +21,7 @@ from __future__ import annotations from pathlib import Path -from ...core.adapter import InvalidCommand, Unsupported +from ...core.adapter import InvalidCommand, Unsupported, local_audio_facts from ...core.capabilities import Capabilities from ...core.model import GridMarker, HotcueChip, PlaylistNode, Track, TrackCues from ...core.pathmap import PathMapping, common_dir_prefix @@ -223,6 +223,9 @@ class OneLibraryAdapter: def audio_path(self, track_id: str): return self._store.audio_path(track_id) + def audio_facts(self, track_ids: list[str]): + return local_audio_facts(self, track_ids) + def set_path_mapping(self, mapping: PathMapping) -> None: """Ignored: a drive's paths are relative to wherever it is mounted. @@ -312,7 +315,7 @@ class OneLibraryAdapter: `audio_path` is where `place_audio` said to copy it (or the file itself, already on the stick); Save moves copies into place. """ - from ...core import audio_tags, grid_detect, waveform + from ...core import audio_tags, grid_detect, key_detect, waveform from ...core.export import ExportTrack from ..rekordbox import artwork, timebase from .export import OneLibraryExporter @@ -348,21 +351,23 @@ class OneLibraryAdapter: taken.add(cue.slot) else: memory.append(cue.model_copy(update={"role": "memory", "slot": None})) - export_track = ExportTrack(track=item.track, destination=audio, + # A file with no key of its own gets one, as it gets a grid. + track = key_detect.with_detected_key(item.track, samples, waveform.SR) + export_track = ExportTrack(track=track, destination=audio, cues=TrackCues(grid_markers=markers, cues=memory)) # Decoded once above; the writer must not decode it again. export_track.waveform = lambda *, lead=0.0, m=measured: m art = item.art or audio_tags.read_cover(audio) jpegs = artwork.pioneer_jpegs(art[0]) if art else None - length = item.track.length or (int(measured.duration) if measured else None) - prepared.append((item, audio, rel, exporter.anlz_files(export_track, rel), jpegs, + length = track.length or (int(measured.duration) if measured else None) + prepared.append((item, track, audio, rel, exporter.anlz_files(export_track, rel), jpegs, markers, hot, length)) added: list[str] = [] - for item, audio, rel, anlz, jpegs, markers, hot, length in prepared: + for item, track, audio, rel, anlz, jpegs, markers, hot, length in prepared: track_id = self._store.add_track( - audio, item.track, rel=rel, anlz_rel=self._store._anlz_rel(rel), anlz=anlz, - jpegs=jpegs, bpm=markers[0].bpm if markers else item.track.bpm, length=length) + audio, track, rel=rel, anlz_rel=self._store._anlz_rel(rel), anlz=anlz, + jpegs=jpegs, bpm=markers[0].bpm if markers else track.bpm, length=length) for cue in hot: self._store.set_cue(track_id, slot=cue.slot, start_sec=cue.start, cue_type="loop" if cue.length else "cue", @@ -392,6 +397,12 @@ class OneLibraryAdapter: self._refresh(track_id) return self._index.get(track_id) + def set_key(self, track_id: str, wheel: int, mode: str) -> Track | None: + self._require_writable("Setting the key") + self._store.set_key(track_id, wheel, mode) + self._refresh(track_id) + return self._index.get(track_id) + def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None: self._refuse("Editing cover art") diff --git a/backend/konduktor/adapters/onelibrary/capabilities.py b/backend/konduktor/adapters/onelibrary/capabilities.py index 3f241ef..b524361 100644 --- a/backend/konduktor/adapters/onelibrary/capabilities.py +++ b/backend/konduktor/adapters/onelibrary/capabilities.py @@ -84,6 +84,7 @@ def capabilities_for( # with it, at Save — so the library, not the user, places the audio. addable=not read_only, removable=not read_only, + key_writable=not read_only, places_audio=True, # `artwork` gates EDITING, which Rekordbox does not do yet either # (parity). Reading works: `store.cover_art` follows diff --git a/backend/konduktor/adapters/onelibrary/store.py b/backend/konduktor/adapters/onelibrary/store.py index ad47643..5923390 100644 --- a/backend/konduktor/adapters/onelibrary/store.py +++ b/backend/konduktor/adapters/onelibrary/store.py @@ -133,8 +133,8 @@ class OneLibraryStore(ReplaceGridCommands): EDITABLE_FIELDS = set(_DIRECT_FIELDS) | set(_LOOKUP_FIELDS) | {"rating", "release_date"} # Written into the audio file's own tags at Save, as rekordbox does when it # edits a stick (measured: the title reached the MP3's TIT2, the rating did - # not). Everything editable except the rating. - FILE_TAG_FIELDS = EDITABLE_FIELDS - {"rating"} + # not). Everything editable except the rating, plus the key `set_key` sets. + FILE_TAG_FIELDS = (EDITABLE_FIELDS - {"rating"}) | {"key"} def __init__(self, path: Path, *, read_only: bool = False): layout = DriveLayout.locate(Path(path)) @@ -490,6 +490,34 @@ class OneLibraryStore(ReplaceGridCommands): pass raise InvalidCommand(f"Release date must be a year or YYYY-MM-DD, got {text!r}") + def _key_id(self, wheel: int | None, mode: str | None) -> int | None: + """The `key` row for a key, found by what it MEANS: a stick's table holds + rekordbox's names ("Abm") beside imported tag text ("12A" — the goober + fixture has both), so a rendered-name match would duplicate a key the + stick already has. A new key gets rekordbox's own spelling.""" + if wheel is None or mode is None: + return None + from pyrekordbox.devicelib_plus import models + + from ..rekordbox.projection import parse_key, render_key + + for k in self._require_db().query(models.Key).all(): + if parse_key(k.name) == (wheel, mode): + return int(k.key_id) + return self._lookup_id("Key", render_key(wheel, mode)) + + def set_key(self, track_id: str, wheel: int, mode: str) -> None: + if not (isinstance(wheel, int) and 1 <= wheel <= 12) or mode not in ("major", "minor"): + raise InvalidCommand(f"Not a key: wheel {wheel!r}, mode {mode!r}") + db = self._require_db() + row = self.content(track_id) + before = row.key_id + row.key_id = self._key_id(wheel, mode) + self._journal.record("track", "set", track_id, "key", before, row.key_id) + # A foreign key: flush + expire, or re-projecting reads the old name. + db.flush() + db.session.expire(row) + def set_track_metadata(self, track_id: str, fields: dict) -> None: from sqlalchemy import text @@ -1026,7 +1054,6 @@ class OneLibraryStore(ReplaceGridCommands): """ from sqlalchemy import text - from ..rekordbox.projection import render_key from .export import ANALYSED_BITS, CONTENT_LINK, _audio_format, _file_type, _kbps, art_files if rel in (self._by_id or {}) or any(self.track_id(r) == rel for r in self.iter_content()): @@ -1070,7 +1097,7 @@ class OneLibraryStore(ReplaceGridCommands): "album": lookup("Album", track.album), "genre": lookup("Genre", track.genre), "label": lookup("Label", track.label), # Rendered from the parsed wheel: a source's "10m" means nothing here. - "key": lookup("Key", render_key(track.key_wheel, track.key_mode)), + "key": self._key_id(track.key_wheel, track.key_mode), "image": image_id, "comment": track.comment or "", "rating": max(0, min(5, int(track.rating or 0))), "year": year, "released": released, "added": datetime.now().strftime("%Y-%m-%d"), "created": created, "path": rel, @@ -1375,7 +1402,7 @@ class OneLibraryStore(ReplaceGridCommands): t = projection.to_track(self.content(track_id)) return {"title": t.title, "artist": t.artist, "album": t.album, "genre": t.genre, "label": t.label, "remixer": t.remixer, "comment": t.comment, - "release_date": t.release_date} + "release_date": t.release_date, "key": t.key} def _prune_empty(folder: Path, *, stop: Path) -> None: diff --git a/backend/konduktor/adapters/rekordbox/adapter.py b/backend/konduktor/adapters/rekordbox/adapter.py index f9abf01..df988c3 100644 --- a/backend/konduktor/adapters/rekordbox/adapter.py +++ b/backend/konduktor/adapters/rekordbox/adapter.py @@ -21,13 +21,14 @@ from __future__ import annotations from pathlib import Path -from ...core.adapter import InvalidCommand, Unsupported +from ...core.adapter import InvalidCommand, Unsupported, local_audio_facts from ...core.capabilities import Capabilities from ...core.model import GridMarker, PlaylistNode, Track, TrackCues from ...core.pathmap import PathMapping, common_dir_prefix from ...core.query import TrackIndex from . import capabilities as caps from . import palette, projection, timebase +from ...core import add_analysis from .store import RekordboxStore @@ -202,6 +203,9 @@ class RekordboxAdapter: def audio_path(self, track_id: str): return self._store.audio_path(track_id) + def audio_facts(self, track_ids: list[str]): + return local_audio_facts(self, track_ids) + def set_path_mapping(self, mapping: PathMapping) -> None: self._store.set_path_mapping(mapping) # The FILE decides a track's media kind, and the mapping moves files. @@ -215,6 +219,10 @@ class RekordboxAdapter: def set_session_mappings(self, mappings: list[PathMapping]) -> None: return None + def set_write_stored_paths(self, enabled: bool) -> None: + """OPTIONAL: see `TraktorAdapter.set_write_stored_paths`.""" + self._store.set_write_stored_paths(enabled) + def path_prefix_suggestions(self) -> dict: paths = self._store.all_audio_paths() primary = common_dir_prefix(paths) @@ -245,6 +253,12 @@ class RekordboxAdapter: self._refresh(track_id) return self._index.get(track_id) + def set_key(self, track_id: str, wheel: int, mode: str) -> Track | None: + self._require_writable("Setting the key") + self._store.set_key(track_id, wheel, mode) + self._refresh(track_id) + return self._index.get(track_id) + # ---- commands: playlists ---------------------------------------------- def create_playlist(self, name: str, parent_id: str | None = None) -> str: self._require_writable("Creating playlists") @@ -382,6 +396,12 @@ class RekordboxAdapter: def dirty(self) -> bool: return self._store.dirty + def edit_summary(self) -> str: + """OPTIONAL: this session's unsaved edits in one line ("edited 3 + tracks; added 6 hotcues") — what a server tells the next computer to + open the library about the edits it is inheriting.""" + return self._store._journal.summary() + def save(self): self._require_writable("Saving") return self._store.save() @@ -416,6 +436,14 @@ class RekordboxAdapter: if self._cloud_synced: raise Unsupported(self._readonly_reason(what)) + def analysis_lead(self, audio: Path) -> float: + """The time-base lead `add_tracks` measures a file's waveform with — + rekordbox's clock against the decoded audio, read from the file's + header (`timebase.py`). OPTIONAL on the protocol: a platform that does + not analyse what it adds has none, and whoever prepares an analysis + for this one (a client of a server-held library) asks for it.""" + return timebase.offset(Path(audio)) + def add_tracks(self, items: list, *, checkpoint=None) -> list[str]: """Add tracks that came from somewhere else, with their prep. @@ -437,7 +465,7 @@ class RekordboxAdapter: bank or already taken becomes a memory cue at the same position rather than being dropped. """ - from ...core import audio_tags, grid_detect, waveform + from ...core import audio_tags self._require_writable("Adding tracks") held = set(self._store.all_audio_paths()) @@ -453,22 +481,29 @@ class RekordboxAdapter: if str(audio) in held: raise InvalidCommand(f"The library already holds {audio}") held.add(str(audio)) - samples = waveform.decode(audio) - measured = waveform.analyse_samples(samples, lead=timebase.offset(audio)) markers = list(item.cues.grid_markers) if item.cues else [] - if not markers and samples is not None: - try: - found = grid_detect.detect_grid(str(audio), y=samples, sr=waveform.SR) - markers = [GridMarker(start=found.anchor, bpm=found.bpm)] - except ValueError: - pass # no pulse to fit (a one-shot, silence): no grid + if item.analysis is not None: + # Measured by whoever added it — a library held by a server is + # never asked to decode audio (see `PreparedAnalysis`). + analysed = item.analysis + if not markers: + markers = list(analysed.markers) + else: + analysed = add_analysis.prepare(audio, lead=self.analysis_lead(audio), + detect=not markers, + detect_key=item.track.key_wheel is None) + markers = markers or list(analysed.markers) + measured = analysed.measured + # A file with no key of its own gets one, as it gets a grid + # (decided: arrive ready to prep). Rekordbox's own add analyses one. + track = add_analysis.with_key(item.track, analysed.key) art = item.art or audio_tags.read_cover(audio) - prepared.append((item, audio, measured, markers, art[0] if art else None)) + prepared.append((item, track, audio, measured, markers, art[0] if art else None)) added: list[str] = [] - for item, audio, measured, markers, art in prepared: + for item, track, audio, measured, markers, art in prepared: track_id = self._store.add_track( - audio, item.track, measured=measured, with_grid=bool(markers), art=art) + audio, track, measured=measured, with_grid=bool(markers), art=art) self._index.add(projection.to_track(self._store.content(track_id), (), stem=self._store.is_stem(track_id))) if markers: diff --git a/backend/konduktor/adapters/rekordbox/capabilities.py b/backend/konduktor/adapters/rekordbox/capabilities.py index 8c0e85e..da130e1 100644 --- a/backend/konduktor/adapters/rekordbox/capabilities.py +++ b/backend/konduktor/adapters/rekordbox/capabilities.py @@ -91,6 +91,7 @@ def capabilities_for( media_kinds=["audio", "stem"], removable=True, addable=True, + key_writable=True, artwork=False, artwork_note=None, ), diff --git a/backend/konduktor/adapters/rekordbox/projection.py b/backend/konduktor/adapters/rekordbox/projection.py index f53db7a..cbb558f 100644 --- a/backend/konduktor/adapters/rekordbox/projection.py +++ b/backend/konduktor/adapters/rekordbox/projection.py @@ -5,65 +5,32 @@ The only place a ``pyrekordbox`` ORM object becomes a generic `Track` / """ from __future__ import annotations -import re - +from ...core import musical_key from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues from . import beatgrid, palette, timebase from .cue_types import cue_type, role_and_slot -# Rekordbox names keys musically ("Abm", "F", "Ebm") rather than in Camelot or -# Open Key notation. Parsing that is platform knowledge and belongs here. -_KEY_RE = re.compile(r"^([A-G])([#b]?)(m?)$", re.I) - -# Camelot wheel position for each pitch class, per mode. -_CAMELOT_MINOR = { - "A": 8, "E": 9, "B": 10, "F#": 11, "Gb": 11, "C#": 12, "Db": 12, - "G#": 1, "Ab": 1, "D#": 2, "Eb": 2, "A#": 3, "Bb": 3, - "F": 4, "C": 5, "G": 6, "D": 7, -} -_CAMELOT_MAJOR = { - "C": 8, "G": 9, "D": 10, "A": 11, "E": 12, "B": 1, "F#": 2, "Gb": 2, - "C#": 3, "Db": 3, "G#": 4, "Ab": 4, "D#": 5, "Eb": 5, "A#": 6, "Bb": 6, - "F": 7, -} - - +# Rekordbox names keys musically ("Abm", "F", "Ebm") — but its key table also +# holds whatever text a track's key TAG carried when it was imported, so a real +# stick has "12A" beside "Abm". Parsing therefore accepts every notation. def parse_key(key: str | None) -> tuple[int | None, str | None]: - """(Camelot wheel position 1-12, mode) for a Rekordbox key name.""" - if not key: - return None, None - m = _KEY_RE.match(key.strip()) - if not m: - return None, None - letter, accidental, minor = m.group(1).upper(), m.group(2), m.group(3) - pitch = letter + (accidental.replace("B", "b") if accidental else "") - table = _CAMELOT_MINOR if minor else _CAMELOT_MAJOR - n = table.get(pitch) - return (n, "minor" if minor else "major") if n else (None, None) + """(Camelot wheel position 1-12, mode) for a key name in any notation.""" + return musical_key.parse(key) -# The inverse, for EXPORT. A track arriving from Traktor carries `key` as +# The inverse, for writing. A track arriving from Traktor carries `key` as # Traktor's own display string ("10m") and `key_wheel`/`key_mode` as the parsed # position — so writing the string verbatim into a Pioneer library would show -# "10m" where the deck expects "Abm". Rendering from the wheel is the only -# correct crossing. Shared with the OneLibrary exporter: same vendor, same -# notation, and two tables would drift. -_MINOR_NAMES = {v: k for k, v in reversed(list(_CAMELOT_MINOR.items()))} -_MAJOR_NAMES = {v: k for k, v in reversed(list(_CAMELOT_MAJOR.items()))} - - +# "10m" where the deck expects "Cm". Rendering from the wheel is the only +# correct crossing. Shared by the adapter and both Pioneer exporters. def render_key(wheel: int | None, mode: str | None) -> str | None: - """A Pioneer-style key name ("Abm", "F") for a Camelot position + mode. + """A Pioneer key name ("Abm", "F") for a Camelot position + mode, spelt as + rekordbox spells its own (flats; see `core/musical_key`). Returns None when the position is unknown, which is honest: a made-up key is worse than a blank one, and Pioneer software shows blanks without complaint. """ - if not wheel or not (1 <= wheel <= 12): - return None - if mode == "minor": - name = _MINOR_NAMES.get(wheel) - return f"{name}m" if name else None - return _MAJOR_NAMES.get(wheel) + return musical_key.render(wheel, mode, "musical") def _iso_date(value) -> str | None: diff --git a/backend/konduktor/adapters/rekordbox/store.py b/backend/konduktor/adapters/rekordbox/store.py index 25677f9..e676638 100644 --- a/backend/konduktor/adapters/rekordbox/store.py +++ b/backend/konduktor/adapters/rekordbox/store.py @@ -46,7 +46,7 @@ from ...core.adapter import ( ) from ...core.edit_journal import EditJournal from ...core.grid_edit import ReplaceGridCommands -from ...core.pathmap import PathMapping +from ...core.pathmap import PathMapping, stored_form from . import timebase from .cue_types import beat_loop_size, kind_for, role_and_slot @@ -117,6 +117,8 @@ class RekordboxStore(ReplaceGridCommands): def __init__(self, path: Path): self.path = Path(path) self._mapping = PathMapping() + # Write an added file in the library's STORED form (`pathmap.stored_form`). + self._write_stored_paths = False self._grid_cache: dict[str, tuple[list[float], list[float], list[int]] | None] = {} self._journal = EditJournal() # Grid edits buffered until save(): ANLZ files are written to disk, so @@ -375,6 +377,14 @@ class RekordboxStore(ReplaceGridCommands): def set_path_mapping(self, mapping: PathMapping) -> None: self._mapping = mapping or PathMapping() + def set_write_stored_paths(self, enabled: bool) -> None: + self._write_stored_paths = bool(enabled) + + def _stored(self, audio: Path) -> Path: + if not self._write_stored_paths: + return Path(audio) + return stored_form(Path(audio), [self._mapping]) + def is_stem(self, track_id: str) -> bool: """Whether the track's FILE is a native-instruments stem file — read from its contents (only `.m4a`/`.mp4` are opened, ~0.7 ms each), and @@ -506,6 +516,46 @@ class RekordboxStore(ReplaceGridCommands): self._db.flush() self._db.session.expire(row) + # ---- writes: musical key --------------------------------------------- + def _key_id(self, wheel: int | None, mode: str | None) -> str | None: + """The `djmdKey` row for a key, found by what it MEANS, not its text. + + A library's key table holds rekordbox's own names ("Abm") and whatever + key tags imported ("12A"), so matching on a rendered name would add a + second row for a key the library already has. Only a key it has never + seen gets a row — created as rekordbox creates its own (measured on the + local library, which rekordbox fills lazily as it analyses): named in + its spelling, `Seq` NULL, and through the ORM so `commit()` stamps the + row's `rb_local_usn` like any other change. (The exporters' raw insert + would leave it unstamped.)""" + from .projection import parse_key, render_key + + if wheel is None or mode is None: + return None + for k in self._db.query(self._tables.DjmdKey).all(): + if parse_key(k.ScaleName) == (wheel, mode): + return str(k.ID) + row = self._tables.DjmdKey( + ID=str(uuid.uuid4().int % 2_147_483_647), + ScaleName=render_key(wheel, mode), + UUID=str(uuid.uuid4()), + ) + self._db.add(row) + self._db.flush() + return str(row.ID) + + def set_key(self, track_id: str, wheel: int, mode: str) -> None: + if not (isinstance(wheel, int) and 1 <= wheel <= 12) or mode not in ("major", "minor"): + raise InvalidCommand(f"Not a key: wheel {wheel!r}, mode {mode!r}") + row = self.content(track_id) + before = row.KeyID + row.KeyID = self._key_id(wheel, mode) + self._journal.record("track", "set", track_id, "key", before, row.KeyID) + # A foreign key, like artist: flush + expire, or the re-projection + # reads the old key back through the cached relationship. + self._db.flush() + self._db.session.expire(row) + # ---- writes: playlists ------------------------------------------------ def _playlist(self, node_id: str): t = self._tables @@ -604,14 +654,15 @@ class RekordboxStore(ReplaceGridCommands): through the ordinary commands. `with_grid` reserves an empty `PQTZ` in the `.DAT` for `replace_grid` to fill.""" from . import new_content - from .projection import render_key audio = Path(audio) if not audio.is_file(): raise InvalidCommand(f"No audio file at {audio}") t = self._tables - if self._db.session.query(t.DjmdContent).filter_by(FolderPath=str(audio)).count(): - raise InvalidCommand(f"The library already holds {audio}") + stored = self._stored(audio) + for form in {str(audio), str(stored)}: + if self._db.session.query(t.DjmdContent).filter_by(FolderPath=form).count(): + raise InvalidCommand(f"The library already holds {audio}") facts = _file_facts(audio) content = self._db.add_content( str(audio), @@ -633,11 +684,14 @@ class RekordboxStore(ReplaceGridCommands): content.AlbumID = new_content.lookup(self._db, "album", track.album) content.GenreID = new_content.lookup(self._db, "genre", track.genre) content.LabelID = new_content.lookup(self._db, "label", track.label) - # Rendered from the wheel, never copied: the source's notation is not - # Rekordbox's ("10m" is "Cm" here). - content.KeyID = new_content.lookup( - self._db, "key", render_key(track.key_wheel, track.key_mode)) + # From the wheel, never the source's text: its notation is not + # Rekordbox's ("10m" is "Cm" here), and a row it already has is reused. + content.KeyID = self._key_id(track.key_wheel, track.key_mode) content.ContentLink = new_content.CONTENT_LINK + if stored != audio: + # pyrekordbox reads the file where it IS; the row names it as the + # library stores every other path (the server's mapping, inverted). + content.FolderPath = str(stored) track_uuid = str(content.UUID) rel = new_content.anlz_rel(track_uuid) diff --git a/backend/konduktor/adapters/remote/__init__.py b/backend/konduktor/adapters/remote/__init__.py new file mode 100644 index 0000000..cca00fe --- /dev/null +++ b/backend/konduktor/adapters/remote/__init__.py @@ -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 diff --git a/backend/konduktor/adapters/remote/adapter.py b/backend/konduktor/adapters/remote/adapter.py new file mode 100644 index 0000000..4619309 --- /dev/null +++ b/backend/konduktor/adapters/remote/adapter.py @@ -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 diff --git a/backend/konduktor/adapters/remote/cache.py b/backend/konduktor/adapters/remote/cache.py new file mode 100644 index 0000000..848227d --- /dev/null +++ b/backend/konduktor/adapters/remote/cache.py @@ -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 diff --git a/backend/konduktor/adapters/remote/client.py b/backend/konduktor/adapters/remote/client.py new file mode 100644 index 0000000..2291bad --- /dev/null +++ b/backend/konduktor/adapters/remote/client.py @@ -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) diff --git a/backend/konduktor/adapters/remote/config.py b/backend/konduktor/adapters/remote/config.py new file mode 100644 index 0000000..489ab2e --- /dev/null +++ b/backend/konduktor/adapters/remote/config.py @@ -0,0 +1,199 @@ +"""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. + + Each address keeps its OWN port. The fallback once borrowed the + primary's, so a reverse-proxied fallback (`konduktor.example.net`, + served on 443) was tried at `:8765` because the LAN address named it. + """ + out = [("primary", _base(self.host, self.port))] + if self.fallback_host: + out.append(("fallback", _base(self.fallback_host, self.fallback_port))) + return out + + def public(self) -> dict: + return asdict(self) + + +def _base(host: str, port: int | None) -> str: + """An address as typed → a base URL. A full URL (`https://…`, the way to + reach a server behind the user's own reverse proxy) is taken exactly as + given, port and all; anything else is plain HTTP on its port, else 8765.""" + host = host.strip() + if host.startswith("http://") or host.startswith("https://"): + 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 diff --git a/backend/konduktor/adapters/remote/services.py b/backend/konduktor/adapters/remote/services.py new file mode 100644 index 0000000..df96bc1 --- /dev/null +++ b/backend/konduktor/adapters/remote/services.py @@ -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 {} diff --git a/backend/konduktor/adapters/remote/session.py b/backend/konduktor/adapters/remote/session.py new file mode 100644 index 0000000..b607fc7 --- /dev/null +++ b/backend/konduktor/adapters/remote/session.py @@ -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") diff --git a/backend/konduktor/adapters/traktor/adapter.py b/backend/konduktor/adapters/traktor/adapter.py index 6576cf7..6f74b1b 100644 --- a/backend/konduktor/adapters/traktor/adapter.py +++ b/backend/konduktor/adapters/traktor/adapter.py @@ -15,7 +15,7 @@ from contextlib import contextmanager from pathlib import Path from types import SimpleNamespace -from ...core.adapter import InvalidCommand, NotFound, Unsupported +from ...core.adapter import InvalidCommand, NotFound, Unsupported, local_audio_facts from ...core.capabilities import Capabilities from ...core.model import PlaylistNode, Track, TrackCues from ...core.pathmap import PathMapping @@ -146,6 +146,12 @@ class TraktorAdapter: self._refresh(track_id) return self._index.get(track_id) + def set_key(self, track_id: str, wheel: int, mode: str) -> Track | None: + with _translate(): + self._store.set_key(track_id, wheel, mode) + self._refresh(track_id) + return self._index.get(track_id) + def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None: with _translate(): self._store.set_track_art(track_id, data, mime) @@ -377,12 +383,22 @@ class TraktorAdapter: def audio_path(self, track_id: str): return self._store.audio_path(track_id) + def audio_facts(self, track_ids: list[str]): + return local_audio_facts(self, track_ids) + def set_path_mapping(self, mapping: PathMapping) -> None: self._store.set_path_mapping(mapping) def set_session_mappings(self, mappings: list[PathMapping]) -> None: self._store.set_session_mappings(mappings) + def set_write_stored_paths(self, enabled: bool) -> None: + """OPTIONAL: write a file added through the path mapping in the + library's STORED form (see `pathmap.stored_form`). A Konduktor server + holding a collection made on another computer turns this on, so a + track uploaded there is stored as that computer would have stored it.""" + self._store.set_write_stored_paths(enabled) + def unresolved_path_groups(self) -> list[PathGroup]: return self._store.unresolved_path_groups() @@ -405,6 +421,12 @@ class TraktorAdapter: def dirty(self) -> bool: return self._store.dirty + def edit_summary(self) -> str: + """OPTIONAL: this session's unsaved edits in one line ("edited 3 + tracks; added 6 hotcues") — what a server tells the next computer to + open the library about the edits it is inheriting.""" + return self._store._edit_summary() + def save(self): outcome = self._store.save() self._rebuild() # save() re-parses, so every object identity changed diff --git a/backend/konduktor/adapters/traktor/capabilities.py b/backend/konduktor/adapters/traktor/capabilities.py index 59dd4b0..e967265 100644 --- a/backend/konduktor/adapters/traktor/capabilities.py +++ b/backend/konduktor/adapters/traktor/capabilities.py @@ -64,6 +64,7 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities: removable=True, addable=True, stem_convertible=True, + key_writable=True, # `.mp4` covers stem files (`.stem.mp4`). Traktor also reads WMA, # but only on Windows, and a file added on one OS must play on both. audio_formats=[".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a", ".mp4", ".ogg"], diff --git a/backend/konduktor/adapters/traktor/projection.py b/backend/konduktor/adapters/traktor/projection.py index d33a8ac..ef07f80 100644 --- a/backend/konduktor/adapters/traktor/projection.py +++ b/backend/konduktor/adapters/traktor/projection.py @@ -7,15 +7,14 @@ from __future__ import annotations import re +from ...core import musical_key from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues from . import beatgrid, timebase from .cue_types import NATIVE_TO_CUE_TYPE # Traktor displays keys in Open Key ("10m" / "8d") or Camelot ("8A" / "8B"), -# depending on a user preference — so the library can contain either. Parsing -# notation is platform knowledge and belongs here, not in the UI. -_OPEN_KEY = re.compile(r"^(\d{1,2})\s*([md])$", re.I) -_CAMELOT = re.compile(r"^(\d{1,2})\s*([ab])$", re.I) +# depending on a user preference, and INFO@KEY also holds whatever a file's key +# tag said ("Gm", "Amin") — so every notation is parsed (`core/musical_key`). _DATE = re.compile(r"^(\d{4})/(\d{1,2})/(\d{1,2})$") # "YYYY", "YYYY-MM" or "YYYY-MM-DD", optionally followed by a time (a # timestamp's date part is the date). @@ -23,23 +22,42 @@ _ISO_DATE = re.compile(r"^(\d{4})(?:-(\d{1,2})(?:-(\d{1,2}))?)?(?:[T ].*)?$") def parse_key(key: str | None) -> tuple[int | None, str | None]: - """(Camelot wheel position 1-12, mode) for a Traktor display key. + """(Camelot wheel position 1-12, mode) for a Traktor key string.""" + return musical_key.parse(key) - Open Key numbers the wheel seven semitones round from Camelot, so - Open Key 1 == Camelot 8 (both are C major / A minor). - """ - if not key: + +def musical_key_value(wheel: int, mode: str) -> int: + """``: the tonic's pitch class (C = 0), plus 12 for minor + — read off the real collection, where 12 pairs with "10m" (C minor) and 21 + with "1m" (A minor) on every entry carrying both.""" + return musical_key.pitch_class_of(wheel, mode) + (12 if mode == "minor" else 0) + + +def _from_musical_key(value: int | None) -> tuple[int | None, str | None]: + if value is None or not 0 <= value <= 23: return None, None - k = key.strip() - if m := _CAMELOT.match(k): - n = int(m.group(1)) - if 1 <= n <= 12: - return n, "minor" if m.group(2).lower() == "a" else "major" - if m := _OPEN_KEY.match(k): - n = int(m.group(1)) - if 1 <= n <= 12: - return ((n + 6) % 12) + 1, "minor" if m.group(2).lower() == "m" else "major" - return None, None + mode = "minor" if value >= 12 else "major" + return musical_key.wheel_of(value % 12, mode), mode + + +def entry_key(e) -> tuple[str | None, int | None, str | None]: + """(display string, wheel, mode) for an ENTRY. + + INFO@KEY is the text Traktor shows and writes to the file's tag; the + analysed key itself is ``. 1,354 of the real collection's + 8,485 entries carry only the latter — analysed, with every value 0-23 + present, just never given a text — and Traktor shows a key for them, so + they fall back to it, rendered in Open Key (Traktor's own default). + """ + info = e.info + text = info.key if info else None + wheel, mode = parse_key(text) + if wheel is None: + mk = e.musical_key.value_attribute if e.musical_key is not None else None + wheel, mode = _from_musical_key(mk) + if wheel is not None and not text: + text = musical_key.render(wheel, mode, "open_key") + return text, wheel, mode def iso_date(value: str | None) -> str | None: @@ -122,7 +140,7 @@ def to_track(e) -> Track: ), key=lambda chip: chip.slot, ) - wheel, mode = parse_key(info.key if info else None) + key_text, wheel, mode = entry_key(e) return Track( id=primary_key(loc) if loc else (e.title or ""), artist=e.artist, @@ -137,7 +155,7 @@ def to_track(e) -> Track: # Traktor's "Comment 2" is stored in INFO@RATING (stars are RANKING). comment2=info.rating if info else None, bpm=beatgrid.effective_bpm(e), - key=info.key if info else None, + key=key_text, key_wheel=wheel, key_mode=mode, rating=_rating_stars(info.ranking if info else None), diff --git a/backend/konduktor/adapters/traktor/store.py b/backend/konduktor/adapters/traktor/store.py index ab33fb8..670acc5 100644 --- a/backend/konduktor/adapters/traktor/store.py +++ b/backend/konduktor/adapters/traktor/store.py @@ -35,6 +35,7 @@ from traktor_nml_utils.models.collection import ( Entrytype, GridType, Infotype, + MusicalKeytype, Locationtype, Nodetype, Playlisttype, @@ -48,13 +49,14 @@ from xsdata.formats.dataclass.serializers import XmlSerializer from ...core.adapter import FileTagResult, InvalidCommand, SaveOutcome, StemSwapResult from ...core.edit_journal import EditJournal from ...core.pathmap import common_dir_prefix -from ...core.pathmap import PathMapping +from ...core.pathmap import PathMapping, stored_form from ...core.relocate import PathGroup from ...core.stem_file import NML_STEMS_JSON, nml_stems_for from ...schemas import PlaylistNode from . import beatgrid, timebase from .locations import os_path_to_location, resolve_path -from .projection import iso_date, traktor_date +from ...core import musical_key +from .projection import iso_date, musical_key_value, traktor_date # Traktor's POPM frame owner: an ID3 rating is per-owner, so writing under # this email is what makes the stars show up in Traktor itself. @@ -77,6 +79,9 @@ class TraktorStore: self.dirty = False # Active OS-path prefix remapping (empty = identity). Survives _load(). self._path_mapping = PathMapping() + # Write a file added through a mapping in the library's STORED form + # (`pathmap.stored_form`) — a Konduktor server sets this. + self._write_stored_paths = False # Mappings the user confirmed in the open-time missing-files check. # Session-only: never saved, re-derived on every open. self._session_mappings: list[PathMapping] = [] @@ -99,6 +104,7 @@ class TraktorStore: self._journal = EditJournal() # track_id -> (image_bytes, mime) of staged replacement cover art self._track_art: dict[str, tuple[bytes, str]] = {} + self._notation: str | None = None self.dirty = False def _note( @@ -399,6 +405,69 @@ class TraktorStore: self._journal.record("track", "set", track_id, k) self.dirty = True + # ---- musical key ---------------------------------------------------- + def _collection_notation(self) -> str | None: + """The notation this collection's INFO@KEY values are written in — a + Traktor preference (Open Key / Camelot / musical) the NML does not + record, so it is read off the keys themselves; the majority wins. None + when the collection holds no keys — never cached, since adding entries + to an empty collection (an export) is exactly when it changes. Once + known it is kept for the session: every key Konduktor writes is in it, + so it can only move if one could out-vote thousands.""" + from collections import Counter + + if self._notation is not None: + return self._notation + seen = Counter( + musical_key.notation_of(e.info.key) + for e in self._nml.collection.entry + if e.info is not None and e.info.key + ) + seen.pop(None, None) + self._notation = seen.most_common(1)[0][0] if seen else None + return self._notation + + def key_notation(self) -> str: + """`_collection_notation`, or Open Key (Traktor's default) when there + are no keys to go by. A key in another notation would display fine but + read as foreign beside its neighbours.""" + return self._collection_notation() or "open_key" + + def _added_key_text(self, track) -> str | None: + """INFO@KEY for an entry `add_entry` creates: rendered from the wheel in + this collection's notation, never copied — a Pioneer source says "Abm", + which reads as foreign beside "9m". A collection with no keys yet (an + export's fresh skeleton) takes a Traktor-native source's own notation, + so Traktor -> Traktor keeps the user's (the export decision). Text that + names no key is kept as it was: dropping it would lose information.""" + text = getattr(track, "key", None) or None + wheel, mode = getattr(track, "key_wheel", None), getattr(track, "key_mode", None) + if not (wheel and mode): + return text + notation = self._collection_notation() + if notation is None: + own = musical_key.notation_of(text) + notation = own if own in ("open_key", "camelot") else "open_key" + return musical_key.render(wheel, mode, notation) + + def set_key(self, track_id: str, wheel: int, mode: str) -> None: + """Set a track's key as Traktor's analysis writes one: the display + text in INFO@KEY (in the collection's notation; also what reaches the + file's tag at Save) AND the analysed value in ``.""" + if not (isinstance(wheel, int) and 1 <= wheel <= 12) or mode not in ("major", "minor"): + raise InvalidCommand(f"Not a key: wheel {wheel!r}, mode {mode!r}") + with self._lock: + entry = self._entry_by_key.get(track_id) + if entry is None: + raise PlaylistError(f"Track not found: {track_id}") + if entry.info is None: + entry.info = Infotype() + before = entry.info.key + entry.info.key = musical_key.render(wheel, mode, self.key_notation()) + entry.musical_key = MusicalKeytype(value_attribute=musical_key_value(wheel, mode)) + self._journal.record("track", "set", track_id, "key", before, entry.info.key) + self.dirty = True + # ---- adding tracks -------------------------------------------------- def add_entry(self, track, audio_path: Path) -> str: """Append a brand-new ENTRY for `audio_path` and return its track id. @@ -428,7 +497,7 @@ class TraktorStore: # Read before the lock: it opens the file. stems = nml_stems_for(audio_path) with self._lock: - volume, dir_, file = os_path_to_location(Path(audio_path)) + volume, dir_, file = os_path_to_location(self._stored(Path(audio_path))) key = f"{volume}{dir_}{file}" if key in self._entry_by_key: raise PlaylistError( @@ -443,7 +512,7 @@ class TraktorStore: remixer=getattr(track, "remixer", None) or None, producer=getattr(track, "producer", None) or None, mix=getattr(track, "mix", None) or None, - key=getattr(track, "key", None) or None, + key=self._added_key_text(track), bitrate=getattr(track, "bitrate", None) or None, playcount=getattr(track, "playcount", None) or None, # The generic model carries ISO dates; Traktor writes "YYYY/M/D". @@ -469,6 +538,12 @@ class TraktorStore: # projected BPM so a track with no grid still shows a tempo; # `replace_grid` overwrites it from the markers when they land. tempo=Tempotype(bpm=float(bpm)) if bpm else None, + # The analysed key, as Traktor's own analysis stores it. + musical_key=( + MusicalKeytype(value_attribute=musical_key_value(track.key_wheel, track.key_mode)) + if getattr(track, "key_wheel", None) and getattr(track, "key_mode", None) + else None + ), cue_v2=[], stems=Stemstype(stems=stems) if stems else None, ) @@ -988,6 +1063,15 @@ class TraktorStore: with self._lock: self._path_mapping = mapping + def set_write_stored_paths(self, enabled: bool) -> None: + self._write_stored_paths = bool(enabled) + + def _stored(self, os_path: Path) -> Path: + """Where a NEW entry points, as the collection stores paths.""" + if not self._write_stored_paths: + return Path(os_path) + return stored_form(Path(os_path), [self._path_mapping, *self._session_mappings]) + def set_session_mappings(self, mappings: list[PathMapping]) -> None: """Set the mappings confirmed for this session (applied at resolve time).""" with self._lock: @@ -1283,7 +1367,7 @@ class TraktorStore: if swap.mode not in ("repoint", "add"): raise PlaylistError(f"Unknown stem swap mode: {swap.mode}") seen_ids.add(swap.track_id) - loc = os_path_to_location(Path(swap.stem_path)) + loc = os_path_to_location(self._stored(Path(swap.stem_path))) new_key = "".join(x or "" for x in loc) if new_key in self._entry_by_key or new_key in new_keys: raise PlaylistError( diff --git a/backend/konduktor/app_state.py b/backend/konduktor/app_state.py index 1661b2d..1220921 100644 --- a/backend/konduktor/app_state.py +++ b/backend/konduktor/app_state.py @@ -28,11 +28,12 @@ import os import threading from pathlib import Path -from . import __version__, adapters, history, library_id, prefs # noqa: F401 — registers adapters +from . import adapters, library_id, prefs # noqa: F401 — registers adapters from .core import registry from .core.adapter import LibraryAdapter from .core.pathmap import PathMapping from .relocation import RelocationCheck +from .services import LibraryServices, LocalServices class AppState: @@ -61,6 +62,18 @@ class AppState: # and what the last open's crash recovery did about any left over. self.pending = None self.recovery: dict | None = None + # Where this library's history (and, for a remote, its export sets and + # ledger) are kept — see `services.py`. + self.services: LibraryServices | None = None + # The open remote's connection (`adapters/remote/session.py`), or None + # for a library on this computer. + self.remote = None + # …and the saved remote it was opened through (`adapters/remote/config.py`). + self.remote_config = None + # Called with the adapter at the end of every open (and so after a + # restore, which reopens): how a Konduktor SERVER re-applies the path + # mapping its configuration names, which lives in no prefs file. + self.open_hooks: list = [] @property def loaded(self) -> bool: @@ -120,16 +133,7 @@ class AppState: # write-ahead log beside a file another process replaces is how a SQLite # library gets corrupted. Only close once the new one has parsed, so a # failed open leaves the current library intact. - previous = self.adapter - # Leaving a library discards its unsaved edits (the UI has confirmed), so - # a stem conversion's parked originals go back under their own names. - if self.pending is not None and self.pending.items: - self.pending.restore() - if previous is not None and hasattr(previous, "close"): - try: - previous.close() - except Exception: # noqa: BLE001 — a failed close must not block the open - pass + self._release_previous() # Apply this library's saved OS-path remapping (per-machine, keyed by the # library's local path) so runtime translation is live on open. saved = prefs.get_path_mapping(str(path)) @@ -161,9 +165,55 @@ class AppState: # Started after the saved mapping is applied, so a volume that mapping # already fixes is not asked about. self.relocation = RelocationCheck(adapter) - # Version history: record an "as I found it" baseline (deduped, so - # re-opening an unchanged library is a no-op). Best-effort. - history.ensure_baseline(path) + self.services = LocalServices(path) + self.services.baseline() + for hook in self.open_hooks: + hook(adapter) + + def _release_previous(self) -> None: + previous = self.adapter + # Leaving a library discards its unsaved edits (the UI has confirmed), so + # a stem conversion's parked originals go back under their own names. + if self.pending is not None and self.pending.items: + self.pending.restore() + if previous is not None and hasattr(previous, "close"): + try: + previous.close() + except Exception: # noqa: BLE001 — a failed close must not block the open + pass + if self.remote is not None and self.library_id: + # A remote library's export sets were the server's; stop asking it. + from . import exports + + exports.use_store(self.library_id, None) + self.adapter = None + self.remote = None + self.remote_config = None + + def open_remote(self, opened) -> None: + """Make an already-connected remote library THE library. + + `opened` is what `adapters.remote.open_remote` returns: the adapter, its + services and session, and the server's identity for the library. The + connection (handshake, version check, session) is made BEFORE this, so + a refusal leaves the current library intact, as a failed parse does. + """ + with self.mutation: + self._release_previous() + self.path = opened.path + self.adapter = opened.adapter + self.services = opened.services + self.remote = opened.session + self.remote_config = opened.remote + # The server's id for the library: export sets are keyed by it, and + # they live on the server too, so every computer sees the same ones. + self.library_id = opened.library_id + # The server keeps its own ledger of converted tracks; nothing of a + # remote library's lives in this computer's. + self.pending = opened.pending + self.recovery = None + # A remote library's files are not on this computer's drives. + self.relocation = None def save(self): """Write the library, then record the saved bytes in version history. @@ -178,15 +228,7 @@ class AppState: def _save(self): outcome = self.adapter.save() - # Not every platform is versioned. A library that is more than one file - # has no single blob that IS the library, and it says so through its - # capabilities rather than this module knowing which platforms those are. - versioned = self.adapter.capabilities().save.history - commit = None - if versioned and outcome.snapshot is not None: - commit = history.commit( - self.path, outcome.snapshot, outcome.summary, __version__ - ) + commit = self.services.commit_save(self.adapter, outcome) # The swap is now on disk: what it replaced can go. After the library # write, so a failed save deletes nothing; here rather than in the save # route, because import and path remap save too. @@ -209,8 +251,25 @@ class AppState: with self.mutation: if self.pending is not None and self.pending.items: self.pending.restore() + if self.services is not None and self.services.remote: + # The server holds the edits; it is what drops them. + self.services.discard() self.adapter.reload() + def restore_version(self, commit_id: str) -> bool: + """Write a past version back as a new save and re-read the library. + False when the version is unknown.""" + assert self.adapter is not None and self.services is not None + with self.mutation: + if not self.services.restore(commit_id): + return False + if self.services.remote: + # The server reopened its own library; follow it. + self.adapter.reload() + else: + self._open(self.path) # rebuild read + edit models from the restored file + return True + STATE = AppState() diff --git a/backend/konduktor/core/adapter.py b/backend/konduktor/core/adapter.py index 3a4e988..2c24fda 100644 --- a/backend/konduktor/core/adapter.py +++ b/backend/konduktor/core/adapter.py @@ -65,6 +65,60 @@ class SaveOutcome: tag_results: list = field(default_factory=list) +@dataclass(frozen=True) +class AudioFacts: + """One track's audio file as its library's host sees it — WITHOUT reading it. + + `key` is the file's path on the machine that holds it (a string, because on + a remote library that is not this machine), `size` and `mtime_ns` its stat. + Together they name one version of one file: what an export's manifest + records, what the analysis cache keys on, and how a downloaded copy is + recognised. Callers that only need a file's IDENTITY ask for these rather + than `audio_path`, which on a remote library means downloading it. + """ + + key: str + size: int + mtime_ns: int + + +def local_audio_facts(adapter, track_ids) -> dict[str, AudioFacts]: + """`audio_facts` for a library whose files are on this machine: stat each + `audio_path`. A track whose file is missing is left out.""" + out: dict[str, AudioFacts] = {} + for track_id in track_ids: + try: + path = adapter.audio_path(track_id) + if path is None: + continue + st = Path(path).stat() + except (OSError, AdapterError): + continue + if not Path(path).is_file(): + continue + out[track_id] = AudioFacts(key=str(path), size=st.st_size, mtime_ns=st.st_mtime_ns) + return out + + +@dataclass +class PreparedAnalysis: + """What adding a track would otherwise decode the file to learn. + + A platform that must ANALYSE what it adds (Rekordbox: the waveform and grid + live in its ANLZ files) decodes each file in `add_tracks`. When the library + lives on a server that never decodes audio, the client does that work on + its own copy and the result travels with the track. `measured` is a + `core.waveform.Analysis` measured with the file's own time-base lead, + `markers` the detected grid (empty: none found) and `key` the detected + `core.key_detect.KeyResult` (None: not asked for, or none found). Absent, + the adapter decodes as before. + """ + + measured: object + markers: list = field(default_factory=list) + key: object | None = None + + @dataclass class NewTrack: """A track to ADD to a library, described generically. @@ -93,6 +147,9 @@ class NewTrack: # For a platform that keeps its own copy of the art (Rekordbox); one that # reads the file's tags (Traktor) ignores it. art: tuple[bytes, str] | None = None + # Precomputed analysis for a platform that would otherwise decode the file + # (see `PreparedAnalysis`); ignored by one that does not analyse. + analysis: PreparedAnalysis | None = None @dataclass(frozen=True) @@ -153,6 +210,11 @@ class Unsupported(AdapterError): """The platform cannot represent this edit at all.""" +class Unavailable(AdapterError): + """The library's host cannot be reached, or no longer lets this computer + write (a library held by a server, taken over by another computer).""" + + @runtime_checkable class LibraryAdapter(Protocol): """One open library. Stateful; exactly one is loaded at a time.""" @@ -172,6 +234,7 @@ class LibraryAdapter(Protocol): def facets(self) -> Facets: ... def stats(self, playlist_count: int) -> Stats: ... def playlist_tree(self) -> list[PlaylistNode]: ... + def playlist_count(self) -> int: ... def playlist_entries(self, node_id: str) -> list[str] | None: ... def playlist_tracks(self, node_id: str) -> list[Track] | None: ... def track_cues(self, track_id: str) -> TrackCues | None: ... @@ -223,6 +286,10 @@ class LibraryAdapter(Protocol): # ---- commands: track metadata / art --------------------------------- def set_track_metadata(self, track_id: str, fields: dict) -> Track | None: ... + # The musical key, as a Camelot wheel position (1-12) + mode — what key + # analysis writes. Each platform renders it in its own notation (and its own + # analysed-key field, where it has one). Gated on `tracks.key_writable`. + def set_key(self, track_id: str, wheel: int, mode: str) -> Track | None: ... def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None: ... def cover_art(self, track_id: str) -> tuple[bytes, str] | None: ... @@ -256,7 +323,12 @@ class LibraryAdapter(Protocol): def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues: ... # ---- audio / paths --------------------------------------------------- + # A READABLE file on this machine — which, for a library held by a server, + # means downloading it. Anything that only needs to know WHICH file a track + # is (an export plan, "is this already in the library?") asks `audio_facts` + # instead, which never reads the file and never downloads. def audio_path(self, track_id: str) -> Path | None: ... + def audio_facts(self, track_ids: list[str]) -> dict[str, AudioFacts]: ... def set_path_mapping(self, mapping: PathMapping) -> None: ... # The open-time missing-files check (`core/relocate.py`): the stored volumes # in which NO track resolves, and the mappings the user confirmed for them — diff --git a/backend/konduktor/core/add_analysis.py b/backend/konduktor/core/add_analysis.py new file mode 100644 index 0000000..b9f5589 --- /dev/null +++ b/backend/konduktor/core/add_analysis.py @@ -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}) diff --git a/backend/konduktor/core/audio_tags.py b/backend/konduktor/core/audio_tags.py index bee8dc5..75de1f8 100644 --- a/backend/konduktor/core/audio_tags.py +++ b/backend/konduktor/core/audio_tags.py @@ -22,7 +22,10 @@ DEFAULT_POPM_EMAIL = "no@email" # The safe, editable metadata we sync to files (the adapter's editable field set). # rating is 0–5 stars. TagMeta = dict # keys: title, artist, album, genre, label, remixer, producer, -# comment, mix, release_date, rating +# comment, mix, release_date, rating, key +# `key` is written as the library holds it ("9m", "Abm") into the frame DJ +# software reads: ID3 TKEY, MP4/FLAC `initialkey` — where Traktor writes its +# own (every key-tagged file on the dev machine has it there). @dataclass @@ -170,6 +173,7 @@ def _apply_id3(id3, meta: TagMeta, popm_email: str = DEFAULT_POPM_EMAIL) -> None TDRC, TIT2, TIT3, + TKEY, TPE1, TPE4, TPUB, @@ -185,6 +189,7 @@ def _apply_id3(id3, meta: TagMeta, popm_email: str = DEFAULT_POPM_EMAIL) -> None "remixer": TPE4, "mix": TIT3, "release_date": TDRC, + "key": TKEY, } for field, frame in simple.items(): if field in meta: @@ -262,7 +267,8 @@ def _write_mp4(path: Path, meta: TagMeta) -> None: else: t[atom] = [val] # No standard MP4 atoms for these — use iTunes-style freeform atoms. - freeform = {"label": "LABEL", "remixer": "REMIXER", "producer": "PRODUCER", "mix": "MIX"} + freeform = {"label": "LABEL", "remixer": "REMIXER", "producer": "PRODUCER", "mix": "MIX", + "key": "initialkey"} for field, name in freeform.items(): if field in meta: key = f"----:com.apple.iTunes:{name}" @@ -297,6 +303,7 @@ def _write_flac(path: Path, meta: TagMeta) -> None: "comment": "comment", "mix": "mixname", "release_date": "date", + "key": "initialkey", } for field, vc in mapping.items(): if field in meta: diff --git a/backend/konduktor/core/capabilities.py b/backend/konduktor/core/capabilities.py index e920835..1c5d22b 100644 --- a/backend/konduktor/core/capabilities.py +++ b/backend/konduktor/core/capabilities.py @@ -25,7 +25,12 @@ from pydantic import BaseModel # `browsing` is an editable library opened only to READ alongside the loaded one # (a OneLibrary stick in the sidebar's Devices): the way to edit it is to open it # as THE library, which one SaveBar and one dirty state can then follow. -ReadonlyCause = Literal["platform_incomplete", "cloud_synced", "not_in_library", "browsing"] +# `taken_over` is a library held by a server that another computer has taken +# over; `offline` one whose server cannot be reached. Both are temporary, and +# both mean "nothing you do here can be saved" until the session is back. +ReadonlyCause = Literal[ + "platform_incomplete", "cloud_synced", "not_in_library", "browsing", "taken_over", "offline", +] CueType = Literal["cue", "fade_in", "fade_out", "load", "loop"] CueRole = Literal["hotcue", "memory"] @@ -78,12 +83,23 @@ class TrackCapabilities(BaseModel): # Tracks can be converted to native-instruments STEM files, which this # platform plays as stems (`apply_stem_swaps`). stem_convertible: bool = False + # The musical key can be set (`set_key`) — what key analysis writes. Not + # in `editable_fields`: a key is a wheel position, not free text. + key_writable: bool = False # The audio files this library can hold, as lower-case suffixes. What a # browsed folder offers to add — a file the library would refuse, or that # the DJ app cannot play, is not worth listing as addable. audio_formats: list[str] = [".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a"] artwork: bool = False artwork_note: str | None = None + # Whose filesystem an import destination is on. "host": this computer's, + # browsed with the ordinary file browser. "library": the machine that holds + # the library (a server), whose folders are listed through the library — + # added audio is UPLOADED there. + audio_destination: Literal["host", "library"] = "host" + # Whether added files can be left where they are ("reference") rather than + # copied. False where the library cannot see this computer's files at all. + reference: bool = True class PlaylistCapabilities(BaseModel): @@ -92,6 +108,13 @@ class PlaylistCapabilities(BaseModel): reorder: bool = False +class PathCapabilities(BaseModel): + # Path mapping, path rewriting and the open-time missing-files check apply. + # False for a library held by a server: its mapping is the server's own + # configuration, and this computer's drives are not where its files are. + remappable: bool = True + + class SaveCapabilities(BaseModel): """Structured facts, never finished sentences. @@ -126,4 +149,5 @@ class Capabilities(BaseModel): grid: GridCapabilities = GridCapabilities() tracks: TrackCapabilities = TrackCapabilities() playlists: PlaylistCapabilities = PlaylistCapabilities() + paths: PathCapabilities = PathCapabilities() save: SaveCapabilities diff --git a/backend/konduktor/core/folder.py b/backend/konduktor/core/folder.py index 8be62fc..5f04ce0 100644 --- a/backend/konduktor/core/folder.py +++ b/backend/konduktor/core/folder.py @@ -150,6 +150,11 @@ class FolderSource: def audio_path(self, track_id: str) -> Path | None: return Path(track_id) if track_id in self._by_id else None + def audio_facts(self, track_ids: list[str]): + from .adapter import local_audio_facts + + return local_audio_facts(self, track_ids) + def playlist_tree(self) -> list[PlaylistNode]: return [] diff --git a/backend/konduktor/core/grid_detect.py b/backend/konduktor/core/grid_detect.py index 040e973..7c852f7 100644 --- a/backend/konduktor/core/grid_detect.py +++ b/backend/konduktor/core/grid_detect.py @@ -213,12 +213,27 @@ def detect_grid( *, y: np.ndarray | None = None, sr: int = _SR, + bpm: float | None = None, + anchor: float | None = None, ) -> GridResult: """Detect a track's constant tempo and first beat. ``y``/``sr`` let a caller (or a test) pass decoded mono audio directly. Raises ``ValueError`` when there is no pulse to fit (silence, a one-shot). + + Either half can be held fixed — the Analyze dialog's BPM and Grid ticks: + - ``bpm`` given ("Grid" alone): that tempo is KEPT — no search, no + round-BPM snap — and only where its beats fall is found. For a BPM the + user trusts (typed, or a store's) and a grid that sits off the beat. + - ``anchor`` given ("BPM" alone): the tempo is detected and the anchor + returned as given, so the grid's downbeat stays where the user put it. + ``drift_ms`` is then measured against THAT anchor: large means the kept + anchor does not sit on the detected beat. """ + if bpm is not None and anchor is not None: + raise ValueError("Hold the BPM or the anchor, not both — there would be nothing to detect") + if bpm is not None and not (20.0 <= bpm <= 400.0): + raise ValueError(f"Not a usable BPM: {bpm}") if y is None: import librosa y, sr = librosa.load(audio_path, sr=sr, mono=True) @@ -227,10 +242,42 @@ def detect_grid( if duration < 1.5: raise ValueError("Track is too short to detect a tempo") - lo, hi = bpm_range low = _onset(_band_env(y, sr, 30.0, 150.0)) - mid = _onset(_band_env(y, sr, 150.0, 4000.0, smooth_ms=3)) attack = _onset(_band_env(y, sr, _ATTACK_LO_HZ, _ATTACK_HI_HZ, smooth_ms=3)) + + if bpm is not None: + period = 60.0 / bpm + if not np.isfinite(attack).all() or attack.max() <= 0: + raise ValueError("No onsets found") + phase = _phase(low, attack, period) + return GridResult( + bpm=float(bpm), + anchor=round(_first_beat(low + attack, phase, period), 4), + duration=duration, + drift_ms=round(_drift(attack, bpm, phase) * 1000.0, 1), + ) + + found_bpm, phase, drift = _detect_tempo(y, sr, low, attack, bpm_range, duration) + period = 60.0 / found_bpm + if anchor is not None: + return GridResult( + bpm=round(found_bpm, 4), + anchor=float(anchor), + duration=duration, + drift_ms=round(_drift(attack, found_bpm, float(anchor) % period) * 1000.0, 1), + ) + return GridResult( + bpm=round(found_bpm, 4), + anchor=round(_first_beat(low + attack, phase, period), 4), + duration=duration, + drift_ms=round(drift * 1000.0, 1), + ) + + +def _detect_tempo(y, sr, low, attack, bpm_range, duration) -> tuple[float, float, float]: + """(bpm, phase, drift) — the tempo search, octave rule and round snap.""" + lo, hi = bpm_range + mid = _onset(_band_env(y, sr, 150.0, 4000.0, smooth_ms=3)) full = _onset(_band_env(y, sr, None, None, smooth_ms=3)) o_tempo = low + mid + 0.5 * full if not np.isfinite(o_tempo).all() or o_tempo.max() <= 0: @@ -260,15 +307,7 @@ def detect_grid( bpm, _ = _refine(o_t, bpm, 0.02, 0.001) phase = _phase(low, attack, 60.0 / bpm) drift = _drift(attack, bpm, phase) - bpm, phase, drift = _snap_round(low, attack, bpm, phase, drift, duration) - - period = 60.0 / bpm - return GridResult( - bpm=round(bpm, 4), - anchor=round(_first_beat(low + attack, phase, period), 4), - duration=duration, - drift_ms=round(drift * 1000.0, 1), - ) + return _snap_round(low, attack, bpm, phase, drift, duration) def _peaks(f: np.ndarray, k: int, min_sep: int) -> list[int]: diff --git a/backend/konduktor/core/grid_plan.py b/backend/konduktor/core/grid_plan.py new file mode 100644 index 0000000..16951af --- /dev/null +++ b/backend/konduktor/core/grid_plan.py @@ -0,0 +1,63 @@ +"""What an analysis does to one track's grid, given the BPM / Grid ticks. + +One pure function, so the batch, the dialog's counts and the tests cannot come +to mean different things. Decided with the user (2026-10-04, see +`.claude/discussions/discuss-key-analysis-2026-10-04.md`): + + - BPM + Grid: a full analysis. A track that already has a grid is replaced + only when the user ticked "Replace" — a grid may hold hand edits. + - BPM alone: re-detect the tempo, KEEP the anchor (the first marker). + - Grid alone: KEEP the BPM, find only where the beats fall. + - With one tick, adjusting the existing grid is the point, so "Replace" does + not apply; a track with nothing to keep (no grid / no BPM) is analysed in + full rather than skipped — one tick never leaves a track worse off. + - A multi-marker (flexible) grid is skipped by BPM alone and Grid alone: its + tempo changes are exactly what one constant tempo would flatten. + - A locked grid is skipped whatever is ticked. +""" +from __future__ import annotations + +from dataclasses import dataclass +from typing import Literal, Sequence + +Action = Literal["none", "full", "bpm", "phase", "skip"] +SkipReason = Literal["locked", "existing", "flexible"] + + +@dataclass(frozen=True) +class GridStep: + action: Action + reason: SkipReason | None = None + hold_bpm: float | None = None # "phase": the tempo kept + hold_anchor: float | None = None # "bpm": the anchor kept (seconds) + + +def plan_grid( + *, + bpm: bool, + grid: bool, + markers: Sequence, # the track's grid markers (`.start`, `.bpm`), any order + track_bpm: float | None, + locked: bool, + replace_existing: bool, +) -> GridStep: + if not (bpm or grid): + return GridStep("none") + if locked: + return GridStep("skip", "locked") + ordered = sorted(markers, key=lambda m: m.start) + if bpm and grid: + if ordered and not replace_existing: + return GridStep("skip", "existing") + return GridStep("full") + if len(ordered) > 1: + return GridStep("skip", "flexible") + if bpm: # BPM alone + if not ordered: + return GridStep("full") + return GridStep("bpm", hold_anchor=float(ordered[0].start)) + # Grid alone + held = float(ordered[0].bpm) if ordered else (float(track_bpm) if track_bpm else None) + if not held or held <= 0: + return GridStep("full") + return GridStep("phase", hold_bpm=held) diff --git a/backend/konduktor/core/key_detect.py b/backend/konduktor/core/key_detect.py new file mode 100644 index 0000000..02173a8 --- /dev/null +++ b/backend/konduktor/core/key_detect.py @@ -0,0 +1,184 @@ +"""Musical key detection: a small convolutional network, run in numpy. + +Why a network and not key profiles. The classic method — fold the spectrum +into a 12-bin chroma vector and correlate it with a major / minor template — +was benchmarked first on GiantSteps (604 Beatport previews, keys corrected by +hand), over Krumhansl, Temperley, Sha'ath (KeyFinder) and Faraldo's EDM +templates and every combination of octave range, compression and harmonic +filtering tried: the best got 49.5% exactly right. A template sees only how +much of each pitch class there is; a network also sees WHERE in pitch it is +(the bass line, the pad, the lead) and learns from data what states a key. + +The model follows Korzeniowski & Widmer, "End-to-end musical key estimation +using a convolutional neural network" (EUSIPCO 2017): five 5x5 convolutions, +then a per-frame dense layer over the whole pitch axis — a key is NOT +pitch-invariant, so nothing pools over frequency — then 24 logits averaged +over the track. ~76 k weights per network; `key_model.npz` holds an ensemble +of three (logits averaged), trained by `backend/train_key_model.py` on the +SEPARATE GiantSteps MTG dataset. torch is used only to train: the backend +never imports it. + +Measured (`bench_key_detect.py`, 2026-10-04): GiantSteps 69.4% exact, 83.4% +harmonically mixable (exact, a fifth, or the relative key), MIREX 0.758 — +about the published figure for this design. Against the key tags of 47 local +files (Traktor's analysis, not ground truth) it agrees on 62%, 77% mixable. +`confidence` tracks correctness (82% exact above 0.7, ~40% below 0.4) but even +a low one is ten times better than chance, so a key is always returned for +music; only silence and clips under 5 s get None. + +Cost on a 6.7-minute track: CQT 0.1 s, the three networks 0.5 s — beside the +decode, which the grid analysis shares. +""" +from __future__ import annotations + +from dataclasses import dataclass +from functools import lru_cache +from pathlib import Path +from typing import Literal + +import numpy as np + +from . import musical_key + +SR = 22050 +HOP = 4096 # ~5.4 frames/s: key is a slow property +BINS_PER_OCTAVE = 36 # three per semitone, so a detuned track still lands in one +FMIN_NOTE = "C1" +OCTAVES = 7 # C1..C8: the input window plus room to pitch-shift it +# The network's input: C2..C7 (65 Hz - 2.1 kHz), where bass lines, pads and +# leads state the key. The octave either side is only there so training can +# shift the window by up to six semitones. +WINDOW = (36, 216) + +_MODEL = Path(__file__).with_name("key_model.npz") +_TIME_CHUNK = 256 # frames per im2col block: bounds memory to tens of MB + +PITCH_NAMES = musical_key.SPELLING + + +@dataclass(frozen=True) +class KeyResult: + pitch_class: int # tonic, 0 = C + mode: Literal["major", "minor"] + wheel: int # Camelot position 1-12, the generic model's key + confidence: float # the network's probability for this key, 0-1 + + @property + def name(self) -> str: + return PITCH_NAMES[self.pitch_class] + ("m" if self.mode == "minor" else "") + + +def camelot_wheel(pitch_class: int, mode: str) -> int: + """Camelot position: C major = 8B, A minor = 8A; one step = a fifth.""" + return musical_key.wheel_of(pitch_class, mode) + + +def features(y: np.ndarray, sr: int = SR) -> np.ndarray: + """Log-magnitude constant-Q spectrogram, (OCTAVES * 36, frames), float32. + + Normalised to the track's own loudest bin, so a quiet master and a loud + one give the same picture. Training calls this same function.""" + import librosa + + if sr != SR: + y = librosa.resample(y, orig_sr=sr, target_sr=SR) + C = np.abs(librosa.cqt( + y, sr=SR, hop_length=HOP, fmin=librosa.note_to_hz(FMIN_NOTE), + n_bins=OCTAVES * BINS_PER_OCTAVE, bins_per_octave=BINS_PER_OCTAVE, tuning=0.0, + )) + peak = float(C.max()) or 1.0 + return np.log1p(1000.0 * C / peak).astype(np.float32) + + +@lru_cache(maxsize=1) +def _members() -> list[dict[str, np.ndarray]]: + """The ensemble: `key_model.npz` holds N networks as `m.`, plus + `pool` (frequency bins averaged before the dense layer; 1 = none).""" + with np.load(_MODEL) as z: + flat = {k: z[k] for k in z.files} + pool = int(flat.pop("pool")) + members: dict[int, dict[str, np.ndarray]] = {} + for k, v in flat.items(): + i, name = k.split(".", 1) + members.setdefault(int(i[1:]), {})[name] = v.astype(np.float32) + for m in members.values(): + m["pool"] = np.array(pool) + return [members[i] for i in sorted(members)] + + +def _elu(x: np.ndarray) -> np.ndarray: + return np.where(x > 0, x, np.expm1(np.minimum(x, 0))) + + +def _conv5(x: np.ndarray, w: np.ndarray, b: np.ndarray) -> np.ndarray: + """'same' 5x5 convolution (cross-correlation, as torch's Conv2d). + x: (cin, F, T), w: (cout, cin, 5, 5) -> (cout, F, T).""" + cin, f, t = x.shape + xp = np.pad(x, ((0, 0), (2, 2), (2, 2))) + out = np.empty((w.shape[0], f, t), np.float32) + for t0 in range(0, t, _TIME_CHUNK): + t1 = min(t, t0 + _TIME_CHUNK) + view = np.lib.stride_tricks.sliding_window_view(xp[:, :, t0:t1 + 4], (5, 5), axis=(1, 2)) + out[:, :, t0:t1] = np.tensordot(w, view, axes=([1, 2, 3], [0, 3, 4])) + return out + b[:, None, None] + + +def _network(x: np.ndarray, w: dict[str, np.ndarray]) -> np.ndarray: + """One member's 24 logits, averaged over time. x: (1, F, T).""" + n = sum(1 for k in w if k.startswith("conv") and k.endswith(".weight")) + for i in range(n): + x = _elu(_conv5(x, w[f"conv{i}.weight"], w[f"conv{i}.bias"])) + pool = int(w["pool"]) # average within a semitone + if pool > 1: + f = x.shape[1] // pool * pool + x = x[:, :f].reshape(x.shape[0], f // pool, pool, -1).mean(axis=2) + dw = w["dense.weight"][..., 0] # (hid, ch, F) + h = _elu(np.tensordot(dw, x, axes=([1, 2], [0, 1])) + w["dense.bias"][:, None]) + out = w["out.weight"][:, :, 0, 0] @ h + w["out.bias"][:, None] # (24, T) + return out.mean(axis=1) + + +def logits(spec: np.ndarray) -> np.ndarray: + """The ensemble's 24 logits — major C..B, then minor C..B — for a + `features()` spectrogram: each member's, averaged.""" + x = spec[WINDOW[0]:WINDOW[1]][None] + return np.mean([_network(x, w) for w in _members()], axis=0) + + +def detect_key_samples(y: np.ndarray, sr: int) -> KeyResult | None: + """The key of decoded mono audio, or None for silence / too short to say.""" + if y.size < sr * 5 or not np.any(y): + return None + z = logits(features(y, sr)).astype(np.float64) + p = np.exp(z - z.max()) + p /= p.sum() + k = int(np.argmax(p)) + pc, mode = k % 12, ("minor" if k >= 12 else "major") + return KeyResult(pc, mode, camelot_wheel(pc, mode), float(p[k])) + + +def with_detected_key(track, y: np.ndarray | None, sr: int): + """`track` (a generic `Track`) with a detected key if it has none of its + own — for a file being ADDED, which is decoded anyway. A key the track + already carries (its tags, its source library) is never second-guessed, + and a detection failure leaves the track as it was: a missing key is not + worth failing an add over.""" + if getattr(track, "key_wheel", None) is not None or y is None: + return track + try: + found = detect_key_samples(y, sr) + except Exception: # noqa: BLE001 + import logging + + logging.getLogger(__name__).warning("key detection failed", exc_info=True) + return track + if found is None: + return track + return track.model_copy(update={"key": found.name, "key_wheel": found.wheel, "key_mode": found.mode}) + + +def detect_key(audio_path: str) -> KeyResult | None: + import librosa + + y, sr = librosa.load(audio_path, sr=SR, mono=True) + return detect_key_samples(y, sr) diff --git a/backend/konduktor/core/key_model.npz b/backend/konduktor/core/key_model.npz new file mode 100644 index 0000000..2bc7c08 Binary files /dev/null and b/backend/konduktor/core/key_model.npz differ diff --git a/backend/konduktor/core/model.py b/backend/konduktor/core/model.py index a12abd9..4dd720d 100644 --- a/backend/konduktor/core/model.py +++ b/backend/konduktor/core/model.py @@ -194,6 +194,9 @@ class LibraryInfo(BaseModel): path: str display_name: str # short label for the status bar version: str | None = None + # Set when the library is held by a server: {id, name, via} of the saved + # remote it was opened through. None for a library on this computer. + remote: dict | None = None class PlatformOption(BaseModel): @@ -208,7 +211,7 @@ class PlatformOption(BaseModel): platform: str name: str library_label: str - selects: Literal["file", "directory"] = "file" + selects: Literal["file", "directory", "remote"] = "file" installed: bool = False #: How many libraries this platform has right now; `installed` is `found > 0`. found: int = 0 diff --git a/backend/konduktor/core/musical_key.py b/backend/konduktor/core/musical_key.py new file mode 100644 index 0000000..955dac6 --- /dev/null +++ b/backend/konduktor/core/musical_key.py @@ -0,0 +1,95 @@ +"""Musical keys: the generic form and the notations DJ software writes. + +The generic model carries a key as a Camelot wheel position (1-12) plus a mode +(`Track.key_wheel` / `key_mode`); one step round the wheel is a fifth, and the +minor key on a number is the relative of the major one. Each platform STORES a +key in its own notation, and a library also holds whatever another tool put +there — a rekordbox stick's key table carries "12A" beside "Abm" when tracks +arrived with Camelot tags. So parsing accepts every notation, and rendering is +always explicit about which one it writes. + +Notations: + - "camelot": 8A / 8B (Mixed In Key's wheel; A = minor) + - "open_key": 1m / 1d (Traktor's default; Open Key 1 = Camelot 8) + - "musical": Am / C, with rekordbox's spelling: flats for Db Eb Ab Bb, and + F# — measured from the key rows rekordbox 7 itself created (Abm, Dbm, Ebm, + Eb; the six-sharp key was not among them). +""" +from __future__ import annotations + +import re +from typing import Literal + +Mode = Literal["major", "minor"] +Notation = Literal["camelot", "open_key", "musical"] + +_CAMELOT = re.compile(r"^(\d{1,2})\s*([ab])$", re.I) +_OPEN_KEY = re.compile(r"^(\d{1,2})\s*([md])$", re.I) +_MUSICAL = re.compile(r"^([A-G])\s*([#b♯♭]?)\s*(m|min|minor|maj|major)?$", re.I) + +_PITCH = {"C": 0, "D": 2, "E": 4, "F": 5, "G": 7, "A": 9, "B": 11} +SPELLING = ("C", "Db", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B") + + +def wheel_of(pitch_class: int, mode: Mode) -> int: + """Camelot position of a tonic: C major = 8B, A minor = 8A.""" + return (((7 * pitch_class) % 12 + (7 if mode == "major" else 4)) % 12) + 1 + + +def pitch_class_of(wheel: int, mode: Mode) -> int: + """The tonic (0 = C) at a Camelot position — `wheel_of`'s inverse.""" + return (7 * ((wheel - 1) - (7 if mode == "major" else 4))) % 12 + + +def parse(text: str | None) -> tuple[int | None, Mode | None]: + """(wheel, mode) for a key in any notation; (None, None) if unreadable. + + A bare number-and-letter is ambiguous only in principle: Camelot uses A/B + and Open Key m/d, so the letter says which.""" + if not text: + return None, None + s = text.strip() + if m := _CAMELOT.match(s): + n = int(m.group(1)) + if 1 <= n <= 12: + return n, "minor" if m.group(2).lower() == "a" else "major" + return None, None + if m := _OPEN_KEY.match(s): + n = int(m.group(1)) + if 1 <= n <= 12: + return ((n + 6) % 12) + 1, "minor" if m.group(2).lower() == "m" else "major" + return None, None + if m := _MUSICAL.match(s): + letter, accidental, quality = m.group(1).upper(), m.group(2), (m.group(3) or "") + pc = _PITCH[letter] + {"#": 1, "♯": 1, "b": -1, "♭": -1}.get(accidental, 0) + # "m" alone is minor; "maj"/"major" major; "min"/"minor" minor. + q = quality.lower() + mode: Mode = "minor" if q in ("m", "min", "minor") else "major" + return wheel_of(pc % 12, mode), mode + return None, None + + +def render(wheel: int | None, mode: str | None, notation: Notation) -> str | None: + """A key in `notation`, or None when the position is unknown — a made-up + key is worse than a blank one.""" + if not wheel or not (1 <= wheel <= 12) or mode not in ("major", "minor"): + return None + if notation == "camelot": + return f"{wheel}{'A' if mode == 'minor' else 'B'}" + if notation == "open_key": + return f"{((wheel + 4) % 12) + 1}{'m' if mode == 'minor' else 'd'}" + return SPELLING[pitch_class_of(wheel, mode)] + ("m" if mode == "minor" else "") + + +def notation_of(text: str | None) -> Notation | None: + """Which notation a stored key string is written in.""" + if not text: + return None + s = text.strip() + if _CAMELOT.match(s): + return "camelot" + if _OPEN_KEY.match(s): + return "open_key" + if _MUSICAL.match(s): + return "musical" + return None diff --git a/backend/konduktor/core/pathmap.py b/backend/konduktor/core/pathmap.py index e440b1b..39ea382 100644 --- a/backend/konduktor/core/pathmap.py +++ b/backend/konduktor/core/pathmap.py @@ -54,6 +54,10 @@ class PathMapping: return True return s.startswith(self.from_prefix + os.sep) or s.startswith(self.from_prefix + "/") + def inverted(self) -> "PathMapping": + """The mapping back: a path HERE → the form the library stores.""" + return PathMapping(self.to_prefix, self.from_prefix) + def apply(self, os_path: Path) -> Path: """Rebase ``os_path`` from ``from_prefix`` onto ``to_prefix``. Returns the path unchanged when it doesn't match (non-matching tracks untouched).""" @@ -81,3 +85,21 @@ def common_dir_prefix(paths: list[str]) -> str: else: break return "/".join(common) + + +def stored_form(os_path: Path, mappings) -> Path: + """`os_path` as the library STORES its paths, when it sits under where one + of `mappings` points (the first that does). + + A library opened through a mapping (a server holding a collection made on + another computer) stores every path in the other computer's form. A file + added through that mapping is written in the same form, so the library + keeps ONE convention — and still opens, mapping and all, where it was made. + """ + for mapping in mappings: + if mapping is None or mapping.empty: + continue + back = mapping.inverted() + if back.matches(os_path): + return back.apply(os_path) + return os_path diff --git a/backend/konduktor/core/stem_file.py b/backend/konduktor/core/stem_file.py index fa57913..a044c4c 100644 --- a/backend/konduktor/core/stem_file.py +++ b/backend/konduktor/core/stem_file.py @@ -356,17 +356,14 @@ def stem_layout(path: Path | str) -> list[dict] | None: MP3 entries in the real collection carry that element.""" import json - import av - path = Path(path) try: raw = read_stem_box(path) if raw is None: - return None + return None # not a stem file: nothing to count, no decoder needed stems = json.loads(raw).get("stems") or [] - with av.open(str(path), metadata_errors="ignore") as c: - streams = len(c.streams.audio) - except (OSError, ValueError, av.FFmpegError): + streams = _audio_stream_count(path) + except (OSError, ValueError): return None if not stems or streams < 1 + len(stems): return None @@ -374,6 +371,39 @@ def stem_layout(path: Path | str) -> list[dict] | None: for i, s in enumerate(stems)] +def _audio_stream_count(path: Path) -> int: + """How many audio streams an MP4 holds. Through PyAV where it is installed; + otherwise (the Konduktor SERVER ships without it — it never decodes) by + counting the `trak`s whose handler is `soun`, which is what PyAV counts.""" + try: + import av + except ImportError: + av = None + if av is not None: + try: + with av.open(str(path), metadata_errors="ignore") as c: + return len(c.streams.audio) + except av.FFmpegError as ex: + raise ValueError(str(ex)) + size = path.stat().st_size + count = 0 + with open(path, "rb") as f: + moov = _find(f, 0, size, b"moov") + if moov is None: + return 0 + for kind, body, end in mp4_edit._boxes(f, moov[1], moov[2]): + if kind != b"trak": + continue + mdia = _find(f, body, end, b"mdia") + hdlr = _find(f, mdia[1], mdia[2], b"hdlr") if mdia else None + if hdlr is None: + continue + f.seek(hdlr[1] + 8) # version/flags (4) + pre_defined (4), then the type + if f.read(4) == b"soun": + count += 1 + return count + + def _traktor_json(v) -> str: if isinstance(v, bool): return "true" if v else "false" diff --git a/backend/konduktor/exporter.py b/backend/konduktor/exporter.py index 5af777f..424b371 100644 --- a/backend/konduktor/exporter.py +++ b/backend/konduktor/exporter.py @@ -341,11 +341,15 @@ def plan(adapter, export_set) -> ExportPlan: resolved = exports.resolve(adapter, export_set) tracks = [t for t in (adapter.track(i) for i in resolved.track_ids) if t is not None] - # The source is the adapter's `audio_path`, never `Track.filepath`: that is - # a DISPLAY path, which on Traktor omits the volume and ignores the active + # The source is the adapter's file, never `Track.filepath`: that is a + # DISPLAY path, which on Traktor omits the volume and ignores the active # path mapping — so every track off the boot volume (or on a remapped - # Windows drive) read as missing and the export was "empty". - sources = {t.id: adapter.audio_path(t.id) for t in tracks} + # Windows drive) read as missing and the export was "empty". Its FACTS, + # not `audio_path`: planning must not read a file, and on a library held + # by a server reading one means downloading it. `run` fetches each file + # only when it copies it. + facts = adapter.audio_facts([t.id for t in tracks]) + sources = {tid: Path(f.key) for tid, f in facts.items()} # Mirror relative to the deepest shared folder, so the export carries the # user's structure without carrying their home directory. @@ -355,16 +359,10 @@ def plan(adapter, export_set) -> ExportPlan: previous = _previous_copies(destination) claimed: set[Path] = set() for track in tracks: - source = sources[track.id] - exists = False - size = mtime_ns = 0 - try: - exists = bool(source and source.is_file()) - if exists: - st = source.stat() - size, mtime_ns = st.st_size, st.st_mtime_ns - except OSError: - exists = False + source = sources.get(track.id) + fact = facts.get(track.id) + exists = fact is not None + size, mtime_ns = (fact.size, fact.mtime_ns) if fact else (0, 0) planned = PlannedTrack( track_id=track.id, title=track.title or (source.name if source else track.id), @@ -519,7 +517,10 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict: done += n handle.progress(done=done) - copy_file(planned.source_path, partial, handle, advance) + # The file to READ: on this machine that is the source itself; + # on a library held by a server, a downloaded copy of it. + local = adapter.audio_path(planned.track_id) or planned.source_path + copy_file(local, partial, handle, advance) os.replace(partial, target) payload_tracks.append( ExportTrack( diff --git a/backend/konduktor/exports.py b/backend/konduktor/exports.py index 5b82101..2ae40fb 100644 --- a/backend/konduktor/exports.py +++ b/backend/konduktor/exports.py @@ -123,8 +123,39 @@ def _store_path(library_id: str) -> Path: return paths.app_data_dir() / "exports" / f"{library_id}.json" +# A library whose sets are kept somewhere other than this computer's app-data — +# a library held by a server keeps them beside itself, so every computer that +# opens it sees the same sets. Each store reads and writes the WHOLE document +# (`{"library_id", "sets"}`); everything else here is unchanged by where it is. +_STORES: dict[str, object] = {} + + +def use_store(library_id: str, store) -> None: + """Keep `library_id`'s sets in `store` (`read() -> dict`, `write(dict)`); + None returns them to this computer's app-data.""" + if store is None: + _STORES.pop(library_id, None) + else: + _STORES[library_id] = store + + +def _read_doc(library_id: str) -> dict: + store = _STORES.get(library_id) + if store is not None: + return store.read() + return paths.read_json(_store_path(library_id), {}) + + +def _write_doc(library_id: str, doc: dict) -> None: + store = _STORES.get(library_id) + if store is not None: + store.write(doc) + else: + paths.write_json(_store_path(library_id), doc) + + def _load(library_id: str) -> dict[str, ExportSet]: - data = paths.read_json(_store_path(library_id), {}) + data = _read_doc(library_id) raw = data.get("sets") if isinstance(data, dict) else None out: dict[str, ExportSet] = {} if isinstance(raw, dict): @@ -158,8 +189,8 @@ def _targets(values: dict) -> list[str]: def _save(library_id: str, sets: dict[str, ExportSet]) -> None: - paths.write_json( - _store_path(library_id), + _write_doc( + library_id, {"library_id": library_id, "sets": {k: v.as_dict() for k, v in sets.items()}}, ) diff --git a/backend/konduktor/importer.py b/backend/konduktor/importer.py index ab2456e..e0e0e58 100644 --- a/backend/konduktor/importer.py +++ b/backend/konduktor/importer.py @@ -112,18 +112,19 @@ def _key(path: Path) -> str: def _existing_files(dest) -> dict[str, str]: """Every audio file the destination points at → its track id. - Resolved through the adapter's own `audio_path`, which is the only answer + Resolved through the adapter's own `audio_facts`, which is the only answer that includes the volume and the active path mapping; the projected - `filepath` is a display string and is not good enough to match on. + `filepath` is a display string and is not good enough to match on. Facts, + not `audio_path`: on a library held by a server that would download every + file it has. """ out: dict[str, str] = {} - for track in dest.tracks: - try: - path = dest.audio_path(track.id) - except Exception: # noqa: BLE001 - path = None - if path is not None: - out.setdefault(_key(path), track.id) + try: + facts = dest.audio_facts([t.id for t in dest.tracks]) + except Exception: # noqa: BLE001 + return out + for track_id, fact in facts.items(): + out.setdefault(_key(Path(fact.key)), track_id) return out @@ -216,7 +217,16 @@ def _all_playlists(source) -> list[tuple[str, str]]: return out -def free_bytes(path: Path) -> int | None: +def free_bytes(path: Path, dest=None) -> int | None: + """Free space where the audio will land. On the DESTINATION's machine: a + library held by a server reports its own disk (`free_space`), since the + path names a folder there, not here.""" + remote_free = getattr(dest, "free_space", None) if dest is not None and uploads_audio(dest) else None + if remote_free is not None: + try: + return remote_free(str(path)) + except Exception: # noqa: BLE001 — unknown is not "full" + return None try: target = path if path.exists() else path.parent return shutil.disk_usage(target).free @@ -224,6 +234,15 @@ def free_bytes(path: Path) -> int | None: return None +def uploads_audio(dest) -> bool: + """Whether added audio is SENT to the machine holding the library (a + server) rather than copied on this one — `tracks.audio_destination`.""" + try: + return dest.capabilities().tracks.audio_destination == "library" and hasattr(dest, "upload_audio") + except Exception: # noqa: BLE001 + return False + + def _unique_target(folder: Path, name: str, taken: set[str]) -> Path: """A free filename in `folder`, suffixing on collision. @@ -298,7 +317,13 @@ def run( """ destination = plan.destination places = places_audio(dest) - if not reference and not places: + # A library held by a server: each file is UPLOADED into `destination`, + # a folder on the server, instead of copied here. Nothing can be left in + # place — the server cannot see this computer's files. + uploads = not places and uploads_audio(dest) + if uploads and reference: + raise ValueError("A remote library cannot reference files on this computer") + if not reference and not places and not uploads: assert destination is not None destination.mkdir(parents=True, exist_ok=True) @@ -312,6 +337,8 @@ def run( # from it leaves the half-written file behind — which then makes the next # attempt suffix around a file that is not really there. created: list[Path] = [] + # Files sent to the server, which a failure asks it to delete again. + uploaded: list[Path] = [] taken: set[str] = set() moved = 0 @@ -333,6 +360,19 @@ def run( elif reference: copied.append((planned, planned.source_path)) continue + elif uploads: + handle.progress(message=f"Uploading {planned.title}") + + def sent(n: int) -> None: + handle.raise_if_cancelled() # mid-file: the server drops the partial + bump(n) + + # The server never overwrites: a taken name comes back `-2`… + target = dest.upload_audio(planned.source_path, str(destination), + planned.source_path.name, progress=sent) + uploaded.append(target) + copied.append((planned, target)) + continue else: target = _unique_target(destination, planned.source_path.name, taken) handle.progress(message=f"Copying {planned.title}") @@ -409,6 +449,11 @@ def run( target.unlink(missing_ok=True) except OSError: log.debug("could not clean up %s", target, exc_info=True) + for target in uploaded: + try: + dest.delete_upload(target) # refused once the library names it + except Exception: # noqa: BLE001 + log.debug("could not clean up upload %s", target, exc_info=True) raise diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index c2ff9a1..016be99 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -9,15 +9,17 @@ from __future__ import annotations import logging import os from pathlib import Path +from types import SimpleNamespace from fastapi import FastAPI, File, Form, HTTPException, Query, Response, UploadFile from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse, JSONResponse -from . import __version__, exporter, exports, history, prefs +from . import __version__, exporter, exports, prefs from .app_state import STATE from .core import auto_hotcues as ah -from .core import grid_detect, structure +from .core import grid_detect, key_detect, structure +from .core.grid_plan import GridStep, plan_grid from . import importer from .core import export as core_export from .core import places, registry @@ -28,6 +30,7 @@ from .core.adapter import ( LibraryAdapter, LibraryNotSupported, NotFound, + Unavailable, Unsupported, ) from .core.capabilities import Capabilities @@ -39,6 +42,8 @@ from .schemas import ( RelocationApply, RelocationCandidate, RelocationVolume, + AnalyzePreview, + AnalyzeRequest, AutoGridBatchRequest, AutoGridRequest, AutoCueOutcome, @@ -77,7 +82,9 @@ from .schemas import ( ImportRequest, JobStatus, OpenCollection, + OpenRemote, OpenSource, + RemoteIn, PathMappingInfo, PlaylistNode, PrefixSuggestions, @@ -137,7 +144,7 @@ def _adapter_error(_request, exc: AdapterError): InvalidCommand: 400, Unsupported: 422, LibraryNotSupported: 400, - }.get(type(exc), 400) + }.get(type(exc), 503 if isinstance(exc, Unavailable) else 400) return JSONResponse(status_code=status, content={"detail": str(exc)}) @@ -203,6 +210,171 @@ def collection_options(platform: str | None = None) -> CollectionOptions: ) +# ---- remote libraries ---------------------------------------------------------- +# A library held by a Konduktor server (a container on the user's NAS), opened +# from the picker's "Remote" step. The saved remotes are this computer's; the +# password is in the OS keychain (`adapters/remote/config.py`). + + +def _remote_out(remote) -> dict: + out = remote.public() + out["has_password"] = bool(remote_cfg().password(remote.id)) + return out + + +def remote_cfg(): + from .adapters.remote import config + + return config + + +def _checked_remote(body: RemoteIn, remote_id: str | None): + """Build the remote from the form and handshake every address. Refuses — + nothing saved — when an address answers but refuses (wrong password, a + version that cannot talk), or when none answers at all; an unreachable + FALLBACK alone is fine (a VPN address is often unreachable at home).""" + from .adapters import remote as remote_lib + + config = remote_cfg() + host, port = config.split_host(body.host) + fallback, fallback_port = config.split_host(body.fallback_host or "") + previous = config.get(remote_id) if remote_id else None + password = body.password if body.password else (config.password(remote_id) if remote_id else None) + if not body.name.strip() or not host or not body.username.strip(): + raise HTTPException(400, "A name, an address and a username are all needed") + if not password: + raise HTTPException(400, "Enter the server's password") + remote = config.Remote( + id=previous.id if previous else config.new_id(), name=body.name.strip(), host=host, + port=body.port or port, fallback_host=fallback or None, + fallback_port=(body.fallback_port or fallback_port) if fallback else None, + username=body.username.strip(), + ) + results = remote_lib.handshake(remote, password) + refused = [r for r in results if r["kind"] in ("auth", "version", "other")] + if refused: + raise HTTPException(400, {"message": refused[0]["error"], "results": results}) + if not any(r["ok"] for r in results): + raise HTTPException(400, {"message": results[0]["error"], "results": results}) + return remote, password, results + + +@app.get("/api/remotes") +def list_remotes() -> list[dict]: + return [_remote_out(r) for r in remote_cfg().remotes()] + + +@app.post("/api/remotes") +def add_remote(body: RemoteIn) -> dict: + remote, password, results = _checked_remote(body, None) + config = remote_cfg() + config.set_password(remote.id, password) + config.save(remote) + return {"remote": _remote_out(remote), "results": results} + + +@app.patch("/api/remotes/{remote_id}") +def edit_remote(remote_id: str, body: RemoteIn) -> dict: + config = remote_cfg() + if config.get(remote_id) is None: + raise HTTPException(404, "No such remote") + remote, password, results = _checked_remote(body, remote_id) + config.set_password(remote.id, password) + config.save(remote) + return {"remote": _remote_out(remote), "results": results} + + +@app.delete("/api/remotes/{remote_id}") +def delete_remote(remote_id: str) -> dict: + if STATE.remote_config is not None and STATE.remote_config.id == remote_id: + raise HTTPException(409, "That remote is open — open another library first") + if not remote_cfg().delete(remote_id): + raise HTTPException(404, "No such remote") + return {"status": "deleted"} + + +def _running_batch() -> str | None: + """The kind of batch running here, for the heartbeat: another computer + asking to take over is told what it would cancel.""" + for kind in BATCH_JOBS + ("import", "export"): + if JOBS.active(kind): + return kind + return None + + +def _on_remote_change(state: str) -> None: + # Taken over: whatever batch is running here is now writing into a library + # this computer no longer holds — cancel it, as Cancel does (finished + # tracks stay as the edits the new holder inherits). + if state == "taken_over": + import threading + + threading.Thread(target=_stop_batches, name="konduktor-takeover-stop", daemon=True).start() + + +@app.post("/api/library/open-remote", response_model=CollectionStatus) +def open_remote(body: OpenRemote) -> CollectionStatus: + """Connect to a saved remote and make its library THE library. + + 409 `{code: "in_use", machine, since, batch}` when another computer holds + it — the picker asks, and retries with `takeover`. On success, the edits + another computer left unsaved are reported (`pending_edits`) for the user + to save or discard. + """ + from .adapters import remote as remote_lib + + remote = remote_cfg().get(body.remote_id) + if remote is None: + raise HTTPException(404, "No such remote") + _stop_batches() + try: + opened = remote_lib.open_remote(remote, takeover=body.takeover, batch_probe=_running_batch) + except remote_lib.InUse as ex: + raise HTTPException(409, {"code": "in_use", **ex.holder}) + except AdapterError as ex: + raise HTTPException(400, str(ex)) + STATE.open_remote(opened) + opened.session.on_change(_on_remote_change) + status = collection_status() + status.pending_edits = opened.pending_edits + return status + + +def _require_remote(): + adapter = require_adapter() + if STATE.remote is None: + raise HTTPException(409, "The open library is not a remote one") + return adapter + + +@app.get("/api/library/fs/list", response_model=FsListing) +def library_fs_list(path: str | None = None) -> FsListing: + """Folders on the machine that HOLDS the library — where an import into a + remote library lands (`tracks.audio_destination == "library"`). Confined by + the server to its content folder; `home` is that folder.""" + adapter = _require_remote() + listing = adapter.client.fs_list(path) + return FsListing( + path=listing["path"], parent=listing["parent"], home=listing["root"], + dirs=[FsEntry(name=e["name"], path=e["path"]) for e in listing["entries"] if e["is_dir"]], + files=[], + ) + + +@app.get("/api/remote-cache") +def remote_cache_status() -> dict: + from .adapters.remote import cache + + return cache.shared().usage() + + +@app.delete("/api/remote-cache") +def clear_remote_cache() -> dict: + from .adapters.remote import cache + + return {"freed": cache.shared().clear()} + + @app.get("/api/library/path-mapping", response_model=PathMappingInfo) def get_path_mapping() -> PathMappingInfo: """The current collection's saved OS-path remapping (blank if none).""" @@ -683,9 +855,15 @@ def _library_info() -> LibraryInfo: driver = next((d for d in registry.drivers() if d.platform == caps.platform), None) namer = getattr(driver, "display_name_for", None) try: - display_name = namer(path) if namer else path.name + display_name = namer(path) if namer and STATE.remote_config is None else path.name except OSError: display_name = path.name + remote = None + if STATE.remote_config is not None: + # A remote is called what the user called it, not its file's name. + display_name = STATE.remote_config.name + remote = {"id": STATE.remote_config.id, "name": STATE.remote_config.name, + "via": STATE.remote.client.via if STATE.remote else None} return LibraryInfo( platform=caps.platform, name=caps.save.app_name, @@ -693,6 +871,7 @@ def _library_info() -> LibraryInfo: path=str(STATE.path), display_name=display_name, version=caps.version, + remote=remote, ) @@ -723,6 +902,14 @@ def platforms() -> list[PlatformOption]: # that keep a library in a known place come before the ones that are a # plugged-in drive, which is the real distinction a chooser is making. out.sort(key=lambda o: (o.removable, o.name.lower())) + # A library held by a Konduktor server — not a platform of its own (the + # server says which it holds), but a way to reach one, so it is offered + # last, after every platform on this computer. + from .adapters.remote import config as remote_config + + saved = len(remote_config.remotes()) + out.append(PlatformOption(platform="remote", name="Remote", library_label="remote library", + selects="remote", installed=saved > 0, found=saved)) return out @@ -739,7 +926,8 @@ def state() -> EditState: return EditState(dirty=require_adapter().dirty, library=_library_info(), pending_stems=pending if pending and pending["tracks"] else None, stem_job=stem_job[0].id if stem_job else None, - stem_recovery=STATE.recovery) + stem_recovery=STATE.recovery, + remote=STATE.remote.describe() if STATE.remote is not None else None) # ---- stem engine (download / side-load / remove) -------------------------- @@ -818,26 +1006,46 @@ def _require_no_pending_stems(what: str) -> None: def _stem_options(body): from .stems import convert + # A remote library's destination is a folder ON THE SERVER: not expanded + # here, where `~` is this computer's home. + remote = STATE.remote is not None + destination = None + if body.destination: + destination = Path(body.destination) if remote else Path(body.destination).expanduser() return convert.Options( - mode=body.mode, destination=Path(body.destination).expanduser() if body.destination else None, + mode=body.mode, destination=destination, collection=body.collection, playlist_id=body.playlist_id, new_playlist=body.new_playlist, device=prefs.load_prefs().get("stemDevice", "auto"), ) def _stem_plan(body): - from .stems import convert + from .stems import convert, remote_convert adapter = require_adapter() caps = adapter.capabilities() if not (caps.writable and caps.tracks.stem_convertible): raise HTTPException(422, "This library cannot hold stem files") try: + if _remote_stems(adapter): + return adapter, remote_convert.plan(adapter, body.track_ids, _stem_options(body)) return adapter, convert.plan(adapter, body.track_ids, _stem_options(body), STATE.pending) except convert.ConvertError as ex: raise HTTPException(400, str(ex)) +def _remote_stems(adapter) -> bool: + """A library held by a server: it plans and swaps, this computer separates + (`stems/remote_convert.py`).""" + return hasattr(adapter, "publish_stems") + + +def _needs_engine(planned) -> bool: + if hasattr(planned, "server"): + return any(i.get("reuse") is None for i in planned.items) + return any(p.reuse is None for p in planned.items) + + @app.post("/api/tracks/stems/preview") def preview_stem_conversion(body: StemConvert) -> dict: """What a conversion would do — converted, skipped (and why), disk space.""" @@ -859,11 +1067,16 @@ def convert_to_stems(body: StemConvert) -> JobStatus: raise HTTPException(409, planned.blocked) if not planned.items: raise HTTPException(400, "None of these tracks can be converted") - if any(p.reuse is None for p in planned.items) and not em.default_manager().ready(): + if _needs_engine(planned) and not em.default_manager().ready(): raise HTTPException(409, "The stem engine is not installed") opts = _stem_options(body) def run(handle): + if _remote_stems(adapter): + from .stems import remote_convert + + return remote_convert.run(handle, adapter, planned, opts, + still_current=lambda: STATE.adapter is adapter) return convert.run(handle, adapter, planned, opts, STATE.pending, mutation=STATE.mutation, still_current=lambda: STATE.adapter is adapter) @@ -926,10 +1139,25 @@ def reload_collection() -> dict: _require_no_pending_stems("Reloading") if not STATE.loaded: raise HTTPException(409, "No collection loaded") - STATE.open(STATE.path) # re-parse current file from disk + if STATE.remote is not None: + STATE.adapter.refresh() # a remote library is re-read from its server + else: + STATE.open(STATE.path) # re-parse current file from disk return {"status": "reloaded", "tracks": len(require_adapter().tracks)} +@app.on_event("shutdown") +def _release_remote_session() -> None: + """A graceful stop hands a remote library's session back (see sidecar.py + for the abrupt one).""" + if STATE.remote is not None: + try: + STATE.remote.stop() + STATE.remote.client.release(timeout=2.0) + except Exception: # noqa: BLE001 + pass + + # ---- read: stats / facets / tracks ------------------------------------ @@ -1229,18 +1457,36 @@ def _place_auto_cues(a, track_id: str, cues: TrackCues, slots: list) -> AutoHotc @app.post("/api/tracks/grid/auto", response_model=TrackCues) def auto_grid(body: AutoGridRequest) -> TrackCues: - """Detect tempo + first beat and build a beatgrid (see `core/grid_detect`). + """The deck's one-click Analyze: BPM + grid (see `core/grid_detect`) and, + where the library can store one, the KEY — from one decode. One constant-tempo marker, written the way the platform's own analyser would (on Traktor that also sets hotcue 1 to the first beat). Octave (half/double) - ambiguity in halftime genres is left for the ×2 / ÷2 controls.""" + ambiguity in halftime genres is left for the ×2 / ÷2 controls. The key + always follows the analysis (a click on Analyze is a request for it), and + a key that cannot be found never fails the grid.""" a = require_adapter() if a.track(body.track_id) is None: raise HTTPException(404, "Track not found") + path = a.audio_path(body.track_id) + if path is None or not path.exists(): + raise HTTPException(400, "Audio file not found (is the drive mounted?)") try: - return _analyse_grid(a, body.track_id) + y, sr = _decode_for_analysis(path) + except Exception as ex: # noqa: BLE001 + raise HTTPException(400, f"Could not decode: {ex}") + try: + cues = _analyse_grid(a, body.track_id, y=y, sr=sr) except _AnalysisError as ex: raise HTTPException(400, str(ex)) + if a.capabilities().tracks.key_writable: + try: + found = key_detect.detect_key_samples(y, sr) + if found is not None: + a.set_key(body.track_id, found.wheel, found.mode) + except Exception: # noqa: BLE001 — the grid is written; a key is a bonus + log.warning("key detection failed for %s", body.track_id, exc_info=True) + return cues class _AnalysisError(Exception): @@ -1285,25 +1531,196 @@ def _submit_batch(kind: str, run) -> "Job": raise HTTPException(409, "A batch analysis is already running") -def _analyse_grid(a, track_id: str) -> TrackCues: +def _analyse_grid(a, track_id: str, step: GridStep = GridStep("full"), *, + y=None, sr: int | None = None) -> TrackCues: """Detect and write one track's grid — shared by the deck's Analyze and the - batch job, so the two cannot come to mean different things.""" - path = a.audio_path(track_id) - if path is None or not path.exists(): - raise _AnalysisError("Audio file not found (is the drive mounted?)") + batch job, so the two cannot come to mean different things. + + `step` is `core/grid_plan`'s decision. Each kind is written through the + command a hand edit of the same thing uses, so it inherits that command's + handling (Traktor's beat-1 companion cue, the time base, the BPM column): + - "full": `set_analysed_grid` — one marker, written as the platform's + own analyser would (on Traktor also hotcue 1 on the first beat); + - "bpm": `set_grid_marker_bpm` on the first marker — the anchor, the + marker's name and its companion stay exactly where they are; + - "phase": `move_grid_marker` on the first marker (dragging its + companion), or a fresh marker at the kept BPM when there was + only a TEMPO and no grid. + `y`/`sr` let a caller that already decoded the file share it.""" + if step.action in ("none", "skip"): + raise ValueError(f"nothing to write for a {step.action!r} step") + if y is None: + path = a.audio_path(track_id) + if path is None or not path.exists(): + raise _AnalysisError("Audio file not found (is the drive mounted?)") try: - found = grid_detect.detect_grid(str(path)) + kw = {"y": y, "sr": sr} if y is not None else {} + found = grid_detect.detect_grid( + "" if y is not None else str(path), + bpm=step.hold_bpm if step.action == "phase" else None, + anchor=step.hold_anchor if step.action == "bpm" else None, + **kw, + ) except Exception as ex: # analysis is best-effort; never 500 the UI raise _AnalysisError(f"Analysis failed: {ex}") from ex + if step.action == "bpm": + return a.set_grid_marker_bpm(track_id, 0, found.bpm) + if step.action == "phase": + cues = a.track_cues(track_id) + if cues is not None and cues.grid_markers: + return a.move_grid_marker(track_id, 0, found.anchor) # "Analysed", not "replace": each platform writes an analysis result in its # own shape (Traktor pairs the first marker with a beat-1 cue). return a.set_analysed_grid(track_id, [(found.anchor, found.bpm)]) -@app.post("/api/tracks/grid/auto-batch", response_model=JobStatus) -def auto_grid_batch(body: AutoGridBatchRequest) -> JobStatus: - """Analyse many tracks' grids as a JOB; poll `/api/jobs/{id}`. +# ---- Analyze (the context menu's "Analyze…": BPM / Grid / Key) ------------- + + +def _require_analysable(a, body: AnalyzeRequest) -> None: + caps = a.capabilities() + if not (body.bpm or body.grid or body.key): + raise HTTPException(400, "Nothing to analyse: tick BPM, Grid or Key") + if (body.bpm or body.grid) and not caps.grid.editable: + raise HTTPException(422, "This library's beatgrids cannot be edited") + if body.key and not caps.tracks.key_writable: + raise HTTPException(422, "This library's keys cannot be written") + + +def _grid_step(a, track, body: AnalyzeRequest, *, exact: bool) -> GridStep: + """`plan_grid` for one track. `exact` reads the real markers (a lazy + platform's projected count is only "has a grid"); the preview does not, + so it cannot see a flexible grid there — the run does.""" + if not (body.bpm or body.grid): + return GridStep("none") + if track.grid_marker_count and exact: + markers = list((a.track_cues(track.id) or TrackCues()).grid_markers) + else: + markers = [SimpleNamespace(start=0.0, bpm=track.bpm or 0.0)] * (track.grid_marker_count or 0) + return plan_grid(bpm=body.bpm, grid=body.grid, markers=markers, track_bpm=track.bpm, + locked=bool(track.grid_locked), replace_existing=body.replace_grid) + + +def _wants_key(track, body: AnalyzeRequest) -> bool: + return body.key and (track.key_wheel is None or body.replace_key) + + +@app.post("/api/tracks/analyze/preview", response_model=AnalyzePreview) +def analyze_preview(body: AnalyzeRequest) -> AnalyzePreview: + """Counts for the Analyze dialog, from the same `plan_grid` the run uses.""" + a = require_adapter() + out = AnalyzePreview(total=0) + for tid in dict.fromkeys(body.track_ids): + track = a.track(tid) + if track is None: + continue + out.total += 1 + if track.grid_marker_count and not track.grid_locked: + out.with_grid += 1 + step = _grid_step(a, track, body, exact=False) + if step.action in ("full", "bpm", "phase") or _wants_key(track, body): + out.tracks_to_analyze += 1 + if step.action in ("full", "bpm", "phase"): + setattr(out, f"grid_{step.action}", getattr(out, f"grid_{step.action}") + 1) + elif step.action == "skip": + setattr(out, f"grid_{step.reason}", getattr(out, f"grid_{step.reason}") + 1) + if track.key_wheel is not None: + out.with_key += 1 + if body.key: + if _wants_key(track, body): + out.key_set += 1 + else: + out.key_existing += 1 + return out + + +def _decode_for_analysis(path: Path): + """Mono samples at the rate BOTH detectors work at (they share one decode).""" + import librosa + + assert grid_detect._SR == key_detect.SR, "grid and key detection must share a sample rate" + return librosa.load(str(path), sr=key_detect.SR, mono=True) + + +def _analyse_one(a, track_id: str, body: AnalyzeRequest, result: dict) -> None: + """Analyse one track as `body` asks, folding the outcome into `result`. + + The file is decoded ONCE and shared by grid and key. A failing half is + reported and does not stop the other: a track whose grid cannot be fitted + (a one-shot) can still have a key, and the reverse.""" + track = a.track(track_id) + title = (track.title or track_id) if track else track_id + if track is None: + result["failed"].append({"title": title, "reason": "Track not found"}) + return + step = _grid_step(a, track, body, exact=True) + if step.action == "skip": + result["grid"][step.reason] += 1 + want_key = _wants_key(track, body) + if body.key and not want_key: + result["key"]["existing"] += 1 + if step.action not in ("full", "bpm", "phase") and not want_key: + return + path = a.audio_path(track_id) + if path is None or not path.exists(): + result["failed"].append({"title": title, "reason": "Audio file not found (is the drive mounted?)"}) + return + try: + y, sr = _decode_for_analysis(path) + except Exception as ex: # noqa: BLE001 — an undecodable file is one failure + result["failed"].append({"title": title, "reason": f"Could not decode: {ex}"}) + return + wrote = False + if step.action in ("full", "bpm", "phase"): + try: + _analyse_grid(a, track_id, step, y=y, sr=sr) + result["grid"][step.action] += 1 + wrote = True + except (_AnalysisError, AdapterError) as ex: + result["failed"].append({"title": title, "reason": f"Grid: {ex}"}) + if want_key: + try: + found = key_detect.detect_key_samples(y, sr) + if found is None: + result["key"]["none"] += 1 + else: + a.set_key(track_id, found.wheel, found.mode) + result["key"]["set"] += 1 + wrote = True + except (AdapterError, ValueError) as ex: + result["failed"].append({"title": title, "reason": f"Key: {ex}"}) + if wrote: + result["analysed"].append(track_id) + + +def _analyze_job(a, body: AnalyzeRequest): + ids = list(dict.fromkeys(body.track_ids)) + + def run(handle) -> dict: + result = { + "analysed": [], "failed": [], + "grid": {"full": 0, "bpm": 0, "phase": 0, "locked": 0, "existing": 0, "flexible": 0}, + "key": {"set": 0, "existing": 0, "none": 0}, + } + handle.progress(done=0, total=len(ids)) + for i, track_id in enumerate(ids): + if handle.cancelled: + break # keep what is done; return it rather than raise + track = a.track(track_id) + handle.progress(message=(track.title or track_id) if track else track_id) + _analyse_one(a, track_id, body, result) + handle.progress(done=i + 1) + # The names the context menu's toast read before the dialog existed. + result["locked"], result["existing"] = result["grid"]["locked"], result["grid"]["existing"] + return result + + return run + + +@app.post("/api/tracks/analyze", response_model=JobStatus) +def analyze_batch(body: AnalyzeRequest) -> JobStatus: + """Analyse many tracks' BPM / grid / key as a JOB; poll `/api/jobs/{id}`. Each track is written as it finishes, into the in-memory model like any other edit — so a cancel keeps what is done (it is all unsaved until Save), @@ -1311,39 +1728,20 @@ def auto_grid_batch(body: AutoGridBatchRequest) -> JobStatus: reported and skipped, never fatal: one unmounted drive must not stop 400 other tracks.""" a = require_adapter() - if not a.capabilities().grid.editable: - raise HTTPException(422, "This library's beatgrids cannot be edited") + _require_analysable(a, body) _require_no_batch() - ids = list(dict.fromkeys(body.track_ids)) - - def run(handle) -> dict: - result = {"analysed": [], "locked": 0, "existing": 0, "failed": []} - handle.progress(done=0, total=len(ids)) - for i, track_id in enumerate(ids): - if handle.cancelled: - break # keep what is done; return it rather than raise - track = a.track(track_id) - title = (track.title or track_id) if track else track_id - handle.progress(message=title) - if track is None: - result["failed"].append({"title": title, "reason": "Track not found"}) - elif track.grid_locked: - result["locked"] += 1 - elif track.grid_marker_count > 0 and not body.replace_existing: - result["existing"] += 1 - else: - try: - _analyse_grid(a, track_id) - result["analysed"].append(track_id) - except (_AnalysisError, AdapterError) as ex: - result["failed"].append({"title": title, "reason": str(ex)}) - handle.progress(done=i + 1) - return result - - job = _submit_batch(GRID_JOB, run) + job = _submit_batch(GRID_JOB, _analyze_job(a, body)) return JobStatus(**job.as_dict()) +@app.post("/api/tracks/grid/auto-batch", response_model=JobStatus) +def auto_grid_batch(body: AutoGridBatchRequest) -> JobStatus: + """The pre-dialog route: BPM + Grid, no key. Kept as an alias of + `/api/tracks/analyze` so the two cannot drift.""" + return analyze_batch(AnalyzeRequest(track_ids=body.track_ids, bpm=True, grid=True, + key=False, replace_grid=body.replace_existing)) + + @app.post("/api/tracks/cue/auto-batch", response_model=JobStatus) def auto_hotcues_batch(body: AutoHotcuesBatchRequest) -> JobStatus: """Place one Auto Hotcues template on many tracks, as a JOB. @@ -1561,7 +1959,7 @@ def save() -> SaveResult: def get_history() -> list[HistoryEntry]: """All saved versions of the current collection, newest first.""" require_adapter() - return [HistoryEntry(**e.__dict__) for e in history.list_history(STATE.path)] + return [HistoryEntry(**e.__dict__) for e in STATE.services.history()] @app.post("/api/history/{commit_id}/restore", response_model=CollectionStatus) @@ -1571,14 +1969,8 @@ def restore_version(commit_id: str) -> CollectionStatus: reloads. The user should close Traktor first (it overwrites on exit).""" _require_no_pending_stems("Restoring a version") require_adapter() - data = history.read_version(STATE.path, commit_id) - if data is None: + if not STATE.restore_version(commit_id): raise HTTPException(404, f"Version not found: {commit_id}") - path = STATE.path - # The adapter's driver owns writing its own format back, even for a restore. - registry.driver_for(path).restore(path, data) - history.commit(path, data, f"Restored version {commit_id[:8]}", __version__) - STATE.open(path) # rebuild read + edit models from the restored file return collection_status() @@ -1586,7 +1978,7 @@ def restore_version(commit_id: str) -> CollectionStatus: def clear_history() -> dict: """Permanently delete ALL version history for the current collection.""" require_adapter() - history.clear_history(STATE.path) + STATE.services.clear_history() return {"status": "cleared"} @@ -1914,7 +2306,7 @@ def _folder_add_plan(body: FolderAddRequest): @app.post("/api/folder/add/preview") def folder_add_preview(body: FolderAddRequest) -> dict: _source, dest, destination, plan = _folder_add_plan(body) - out = plan.as_dict(free_bytes=importer.free_bytes(destination) if destination else None) + out = plan.as_dict(free_bytes=importer.free_bytes(destination, dest) if destination else None) if importer.places_audio(dest): _placed_space(out, dest, plan, destination) elif body.mode == "reference": @@ -1933,7 +2325,7 @@ def folder_add(body: FolderAddRequest) -> JobStatus: if not plan.importable and not plan.existing: raise HTTPException(400, "Nothing to add (none of those files exist)") if body.mode == "copy" or importer.places_audio(dest): - free = importer.free_bytes(destination) + free = importer.free_bytes(destination, dest) needed = importer.placed_bytes(dest, plan) if importer.places_audio(dest) else plan.total_bytes if free is not None and free < needed + importer.SPACE_HEADROOM: raise HTTPException( @@ -2002,7 +2394,7 @@ def import_preview(body: ImportRequest) -> dict: between the preview and the import, and a stale preview is worse than none. """ _source, dest, destination, plan = _import_plan(body) - out = plan.as_dict(free_bytes=importer.free_bytes(destination)) + out = plan.as_dict(free_bytes=importer.free_bytes(destination, dest)) if importer.places_audio(dest): _placed_space(out, dest, plan, destination) return out @@ -2015,7 +2407,7 @@ def start_import(body: ImportRequest) -> JobStatus: source, dest, destination, plan = _import_plan(body) if not plan.importable: raise HTTPException(400, "Nothing to import (no tracks, or none of their files exist)") - free = importer.free_bytes(destination) + free = importer.free_bytes(destination, dest) needed = importer.placed_bytes(dest, plan) if importer.places_audio(dest) else plan.total_bytes if free is not None and free < needed + importer.SPACE_HEADROOM: raise HTTPException( diff --git a/backend/konduktor/prefs.py b/backend/konduktor/prefs.py index f7d70aa..fb4cd6b 100644 --- a/backend/konduktor/prefs.py +++ b/backend/konduktor/prefs.py @@ -3,10 +3,19 @@ A self-contained JSON file in the app's per-OS user-writable data dir (see ``paths.app_data_dir``) so it survives a frozen/packaged build and works the same on every platform. Best-effort: any I/O error degrades to "no prefs". + +**Every read-modify-write holds ``_LOCK`` and every write is atomic.** FastAPI +runs ``PATCH /api/prefs`` on a thread pool, and the UI sends several at once on +launch. Unlocked, with ``write_text`` truncating before it wrote, a reader could +catch the file empty, take it for "no prefs" and write back only its own key — +wiping everything else (measured: 249 of 300 trials of three concurrent patches). +A file that exists but will not parse is moved aside before it is replaced, so +it is never silently overwritten. """ from __future__ import annotations import json +import threading from pathlib import Path from . import paths @@ -16,6 +25,9 @@ from . import paths _PREFS_PATH = paths.app_data_dir() / "userprefs.json" _LEGACY_PREFS_PATH = Path(__file__).resolve().parent.parent / "userprefs.json" +# Reentrant: the helpers below read and write inside one critical section. +_LOCK = threading.RLock() + def _migrate_legacy() -> None: """One-time: if the new file is absent but a legacy package-relative one @@ -27,29 +39,52 @@ def _migrate_legacy() -> None: pass -def load_prefs() -> dict: +def _read(*, for_write: bool) -> dict: + """The stored prefs, or {} if there are none or they cannot be read. + + With ``for_write``, a file that exists but is not a JSON object is renamed + to ``userprefs.json.corrupt`` first, since the caller is about to replace it. + """ try: _migrate_legacy() - data = json.loads(_PREFS_PATH.read_text()) - return data if isinstance(data, dict) else {} - except (OSError, ValueError): + text = _PREFS_PATH.read_text() + except OSError: return {} + try: + data = json.loads(text) + if isinstance(data, dict): + return data + except ValueError: + pass + if for_write: + try: + _PREFS_PATH.replace(_PREFS_PATH.with_name(_PREFS_PATH.name + ".corrupt")) + except OSError: + pass + return {} + + +def load_prefs() -> dict: + with _LOCK: + return _read(for_write=False) def save_prefs(prefs: dict) -> None: - try: - _PREFS_PATH.write_text(json.dumps(prefs, indent=2)) - except OSError: - pass # non-fatal — prefs are a convenience, not a requirement + with _LOCK: + try: + paths.write_json(_PREFS_PATH, prefs) + except OSError: + pass # non-fatal — prefs are a convenience, not a requirement def update_prefs(patch: dict) -> dict: """Shallow-merge `patch` into the stored prefs and persist. Returns the full updated prefs dict.""" - prefs = load_prefs() - prefs.update(patch) - save_prefs(prefs) - return prefs + with _LOCK: + prefs = _read(for_write=True) + prefs.update(patch) + save_prefs(prefs) + return prefs def get_path_mapping(collection_path: str) -> dict | None: @@ -69,16 +104,17 @@ def set_path_mapping( collection_path: str, from_prefix: str | None, to_prefix: str | None ) -> None: """Persist (or, when either prefix is blank, clear) a collection's mapping.""" - prefs = load_prefs() - mappings = prefs.get("path_mappings") - if not isinstance(mappings, dict): - mappings = {} - if from_prefix and to_prefix: - mappings[collection_path] = {"from": from_prefix, "to": to_prefix} - else: - mappings.pop(collection_path, None) - prefs["path_mappings"] = mappings - save_prefs(prefs) + with _LOCK: + prefs = _read(for_write=True) + mappings = prefs.get("path_mappings") + if not isinstance(mappings, dict): + mappings = {} + if from_prefix and to_prefix: + mappings[collection_path] = {"from": from_prefix, "to": to_prefix} + else: + mappings.pop(collection_path, None) + prefs["path_mappings"] = mappings + save_prefs(prefs) def get_last_collection(platform: str | None = None) -> str | None: @@ -105,12 +141,13 @@ def get_last_collection(platform: str | None = None) -> str | None: def set_last_collection(path: str, platform: str | None = None) -> None: """Record a library as the last opened, globally and for its platform.""" - prefs = load_prefs() - prefs["last_collection"] = path - if platform: - by_platform = prefs.get("last_collection_by_platform") - if not isinstance(by_platform, dict): - by_platform = {} - by_platform[platform] = path - prefs["last_collection_by_platform"] = by_platform - save_prefs(prefs) + with _LOCK: + prefs = _read(for_write=True) + prefs["last_collection"] = path + if platform: + by_platform = prefs.get("last_collection_by_platform") + if not isinstance(by_platform, dict): + by_platform = {} + by_platform[platform] = path + prefs["last_collection_by_platform"] = by_platform + save_prefs(prefs) diff --git a/backend/konduktor/remote_protocol.py b/backend/konduktor/remote_protocol.py new file mode 100644 index 0000000..30de27e --- /dev/null +++ b/backend/konduktor/remote_protocol.py @@ -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) diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index a3151fb..6f9b55c 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -133,6 +133,40 @@ class AutoGridRequest(BaseModel): track_id: str +class AnalyzeRequest(BaseModel): + """The Analyze dialog's choices. BPM and Grid are independent halves of a + beatgrid (`core/grid_plan`); `replace_grid` only guards a FULL re-analysis + (both ticked), since with one tick adjusting the grid is the point. + `replace_key` lets detection overwrite a key the track already has.""" + track_ids: list[str] + bpm: bool = True + grid: bool = True + key: bool = False + replace_grid: bool = False + replace_key: bool = False + + +class AnalyzePreview(BaseModel): + """What an Analyze run WOULD do, for the dialog. Counted from the + projection, so on a platform whose marker counts are lazy (Rekordbox, + OneLibrary: 1 for any track with a BPM) a flexible grid is only found when + the run reads the real grid — it is then skipped and reported.""" + total: int + tracks_to_analyze: int = 0 # tracks with anything to do (grid and key overlap) + # Grid: what `plan_grid` decides per track — full / bpm / phase / skipped. + grid_full: int = 0 + grid_bpm: int = 0 + grid_phase: int = 0 + grid_locked: int = 0 + grid_existing: int = 0 # skipped: has a grid, Replace not ticked + grid_flexible: int = 0 + with_grid: int = 0 # unlocked tracks that have a grid (the Replace tick's count) + # Key. + key_set: int = 0 + key_existing: int = 0 # skipped: has a key, Replace not ticked + with_key: int = 0 # tracks that have a key (the Replace tick's count) + + class AutoGridBatchRequest(BaseModel): track_ids: list[str] # False skips tracks that already have a grid. Locked grids are skipped @@ -187,6 +221,8 @@ class EditState(BaseModel): stem_job: str | None = None # What this open's crash recovery did about an interrupted conversion. stem_recovery: dict | None = None + # A remote library's connection: {state, via, machine}. None when local. + remote: dict | None = None # ---- collection selection ---- @@ -200,12 +236,34 @@ class CollectionStatus(BaseModel): # Identity of the loaded library, so the UI can name it without parsing the # path (a Serato library is a directory, not a file). library: LibraryInfo | None = None + # Opening a remote library: the unsaved edits another computer left there, + # {machine, summary} — the user chooses to save or discard them. + pending_edits: dict | None = None class OpenCollection(BaseModel): path: str +class RemoteIn(BaseModel): + """A remote's settings as the picker's form sends them. `password` may be + omitted on an edit, which keeps the saved one.""" + + name: str + host: str + port: int | None = None + fallback_host: str | None = None + fallback_port: int | None = None + username: str + password: str | None = None + + +class OpenRemote(BaseModel): + remote_id: str + # Take the session from the computer holding it (the user confirmed). + takeover: bool = False + + class CollectionCandidate(BaseModel): path: str label: str # folder name, e.g. "Traktor 4.5.0" diff --git a/backend/konduktor/server/__init__.py b/backend/konduktor/server/__init__.py new file mode 100644 index 0000000..9d63660 --- /dev/null +++ b/backend/konduktor/server/__init__.py @@ -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`.""" diff --git a/backend/konduktor/server/__main__.py b/backend/konduktor/server/__main__.py new file mode 100644 index 0000000..5a7a89b --- /dev/null +++ b/backend/konduktor/server/__main__.py @@ -0,0 +1,37 @@ +"""`python -m konduktor.server` — what the container runs. + +Configuration is the environment (see `config.py`); a bad setting stops here +with one clear line instead of serving a library that half-works. +""" +from __future__ import annotations + +import logging +import sys + +import uvicorn + +from .config import ConfigError, from_env + + +def main() -> int: + logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s") + try: + config = from_env() + except ConfigError as ex: + print(f"konduktor-server: {ex}", file=sys.stderr) + return 2 + from .app import Server, create_app + + server = Server(config) + try: + server.open() + except ConfigError as ex: + print(f"konduktor-server: {ex}", file=sys.stderr) + return 2 + uvicorn.run(create_app(server), host=config.host, port=config.port, + log_level="info", proxy_headers=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/backend/konduktor/server/app.py b/backend/konduktor/server/app.py new file mode 100644 index 0000000..f2f6741 --- /dev/null +++ b/backend/konduktor/server/app.py @@ -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) diff --git a/backend/konduktor/server/config.py b/backend/konduktor/server/config.py new file mode 100644 index 0000000..c5eff74 --- /dev/null +++ b/backend/konduktor/server/config.py @@ -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, + ) diff --git a/backend/konduktor/server/session.py b/backend/konduktor/server/session.py new file mode 100644 index 0000000..a15e8ad --- /dev/null +++ b/backend/konduktor/server/session.py @@ -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 diff --git a/backend/konduktor/services.py b/backend/konduktor/services.py new file mode 100644 index 0000000..e87ce88 --- /dev/null +++ b/backend/konduktor/services.py @@ -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) diff --git a/backend/konduktor/stems/remote_convert.py b/backend/konduktor/stems/remote_convert.py new file mode 100644 index 0000000..14b120c --- /dev/null +++ b/backend/konduktor/stems/remote_convert.py @@ -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 diff --git a/backend/requirements-server.txt b/backend/requirements-server.txt new file mode 100644 index 0000000..e546af3 --- /dev/null +++ b/backend/requirements-server.txt @@ -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 diff --git a/backend/requirements.txt b/backend/requirements.txt index 2391f45..43f8fc3 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -34,3 +34,8 @@ pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git # The stem engine and its weights are downloaded over HTTPS by the sidecar; a # frozen Python on macOS has no system CA bundle of its own. certifi>=2024.7 +# Remote libraries (a Konduktor server on the user's NAS): the HTTP client the +# remote adapter speaks to it with, and the OS keychain (macOS Keychain / +# Windows Credential Manager) its password is kept in — never userprefs.json. +httpx>=0.27 +keyring>=25 diff --git a/backend/run_tests.sh b/backend/run_tests.sh index b2da4bb..8515917 100755 --- a/backend/run_tests.sh +++ b/backend/run_tests.sh @@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")" source .venv/bin/activate fail=0 -for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py test_discard.py; do +for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_key_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_prefs.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py test_discard.py test_remote_protocol.py test_remote_server.py test_remote_adapter.py test_remote_stems.py; do echo "──────────────────────────────────────────" echo "▶ $t" echo "──────────────────────────────────────────" diff --git a/backend/sidecar.py b/backend/sidecar.py index bd3a6ef..49fb2cf 100644 --- a/backend/sidecar.py +++ b/backend/sidecar.py @@ -34,9 +34,24 @@ def _watch_parent_and_exit() -> None: pass except Exception: pass + _release_remote() os._exit(0) +def _release_remote() -> None: + """Hand back a remote library's session on the way out, so the next + computer opens it at once instead of waiting out the lease (or being asked + to take over a laptop that has already quit). Best-effort and brief.""" + try: + from konduktor.app_state import STATE + + if STATE.remote is not None: + STATE.remote.stop() + STATE.remote.client.release(timeout=2.0) + except Exception: + pass + + def _free_port() -> int: """Grab an unused loopback port. There's a tiny bind→close→rebind race, but it's harmless on 127.0.0.1 for a single local sidecar.""" diff --git a/backend/test_grid_batch.py b/backend/test_grid_batch.py index f7ccee5..f79f0c4 100644 --- a/backend/test_grid_batch.py +++ b/backend/test_grid_batch.py @@ -57,6 +57,9 @@ with tempfile.TemporaryDirectory() as d: return SimpleNamespace(anchor=0.123, bpm=127.5) main.grid_detect.detect_grid = fake_detect + # The batch decodes once for grid AND key; the detector above is fake, so + # the decode is too (audio_path points at this .py file). + main._decode_for_analysis = lambda path: (detected.append(str(path)) or np.zeros(22050 * 8, np.float32), 22050) with TestClient(main.app, raise_server_exceptions=False) as c: a = main.require_adapter() @@ -239,6 +242,161 @@ with tempfile.TemporaryDirectory() as d: jid = main.JOBS.submit("unit-probe", lambda h: h.progress(done=1, total=2, unit="bytes")).id check("a job's unit reaches the client", wait(c, jid).get("unit") == "bytes") +print("== Analyze: BPM / Grid / Key through the routes ==") +with tempfile.TemporaryDirectory() as d: + from konduktor.core.key_detect import KeyResult + + work = Path(d) / "collection.nml" + shutil.copy2(REAL, work) + os.environ["KONDUKTOR_NML"] = str(work) + decodes: list[str] = [] + main._decode_for_analysis = lambda path: (decodes.append(str(path)) or np.ones(22050 * 8, np.float32), 22050) + main.grid_detect.detect_grid = lambda path, *a, **k: SimpleNamespace( + anchor=k.get("anchor") or 0.5, bpm=k.get("bpm") or 133.0) + main.key_detect.detect_key_samples = lambda y, sr: KeyResult(5, "minor", 4, 0.9) # F minor, 4A + + with TestClient(main.app, raise_server_exceptions=False) as c: + a = main.require_adapter() + a.audio_path = lambda tid: Path(__file__) + keyed = [t.id for t in a.tracks if t.key_wheel is not None][:3] + unkeyed = [t.id for t in a.tracks if t.key_wheel is None][:3] + single = [t.id for t in a.tracks if t.grid_marker_count == 1 and not t.grid_locked][:3] + # Every flexible grid in the real collection is locked: make one. + flexible = single.pop() + a.add_grid_marker(flexible, a.track_cues(flexible).grid_markers[0].start + 60.0, 126.0) + bare = [t.id for t in a.tracks if t.grid_marker_count == 0][:2] + + def run(**body): + r = c.post("/api/tracks/analyze", json=body) + assert r.status_code == 200, r.text + return wait(c, r.json()["id"])["result"] + + r = c.post("/api/tracks/analyze", json={"track_ids": keyed, "bpm": False, "grid": False, "key": False}) + check("nothing ticked is refused", r.status_code == 400, r.text) + + # Key alone: an existing key is skipped unless Replace; the grid untouched. + before_grid = {t: a.track_cues(t).grid_markers for t in keyed} + before_keys = {t: a.track(t).key for t in keyed} + res = run(track_ids=keyed + unkeyed, bpm=False, grid=False, key=True) + check("Key alone sets the keyless tracks' keys", res["key"]["set"] == len(unkeyed) + and all(a.track(t).key_wheel == 4 for t in unkeyed), str(res["key"])) + check("…and skips tracks that have one", res["key"]["existing"] == len(keyed) + and {t: a.track(t).key for t in keyed} == before_keys) + check("…leaving every grid alone", {t: a.track_cues(t).grid_markers for t in keyed} == before_grid) + res = run(track_ids=keyed, bpm=False, grid=False, key=True, replace_key=True) + check("Replace keys overwrites them", res["key"]["set"] == len(keyed) + and all(a.track(t).key_wheel == 4 for t in keyed), str(res["key"])) + + # The preview counts what the run does. + ids = single + [flexible] + bare + pv = c.post("/api/tracks/analyze/preview", json={"track_ids": ids, "bpm": True, "grid": False}).json() + check("preview: BPM alone adjusts single grids, skips flexible, analyses bare in full", + (pv["grid_bpm"], pv["grid_flexible"], pv["grid_full"]) == (len(single), 1, len(bare)), str(pv)) + pv = c.post("/api/tracks/analyze/preview", json={"track_ids": ids, "bpm": True, "grid": True}).json() + check("preview: BPM+Grid without Replace skips every gridded track", + (pv["grid_existing"], pv["grid_full"], pv["with_grid"]) == (len(single) + 1, len(bare), len(single) + 1), + str(pv)) + pv = c.post("/api/tracks/analyze/preview", + json={"track_ids": ids, "bpm": True, "grid": True, "key": True, "replace_key": True}).json() + check("preview: tracks_to_analyze counts a track once for grid AND key", + pv["tracks_to_analyze"] == len(ids), str(pv)) + + # BPM alone, through the run. + anchors = {t: a.track_cues(t).grid_markers[0].start for t in single} + flex_before = a.track_cues(flexible).grid_markers + decodes.clear() + res = run(track_ids=ids, bpm=True, grid=False, key=False) + check("BPM alone: the run's counts match the preview", + (res["grid"]["bpm"], res["grid"]["flexible"], res["grid"]["full"]) == (len(single), 1, len(bare)), + str(res["grid"])) + check("…single grids keep their anchor, take the new tempo", + all(abs(a.track_cues(t).grid_markers[0].start - anchors[t]) < 1e-6 + and a.track_cues(t).grid_markers[0].bpm == 133.0 for t in single)) + check("…a flexible grid is untouched", a.track_cues(flexible).grid_markers == flex_before) + check("…and is never decoded (nothing to do)", len(decodes) == len(single) + len(bare), str(len(decodes))) + + # Grid + Key together: ONE decode per track. + decodes.clear() + res = run(track_ids=bare, bpm=True, grid=True, key=True, replace_grid=True, replace_key=True) + check("BPM+Grid+Key decodes each track once", len(decodes) == len(bare), str(decodes)) + check("…and writes both", res["grid"]["full"] == len(bare) and res["key"]["set"] == len(bare), str(res)) + + # A grid that cannot be fitted still gets its key. + def no_pulse(*a, **k): + raise ValueError("No onsets found") + main.grid_detect.detect_grid = no_pulse + res = run(track_ids=unkeyed[:1], bpm=True, grid=True, key=True, replace_grid=True, replace_key=True) + check("a failed grid is reported and the key still written", + res["key"]["set"] == 1 and any(f["reason"].startswith("Grid:") for f in res["failed"]), str(res)) + + # The deck's Analyze sets the key too. + main.grid_detect.detect_grid = lambda path, *a, **k: SimpleNamespace(anchor=0.5, bpm=133.0) + main.key_detect.detect_key_samples = lambda y, sr: KeyResult(9, "minor", 8, 0.9) # A minor, 8A + r = c.post("/api/tracks/grid/auto", json={"track_id": bare[0]}) + check("the deck's Analyze writes the grid AND the key", + r.status_code == 200 and a.track(bare[0]).key_wheel == 8, r.text[:200]) + main.key_detect.detect_key_samples = lambda y, sr: (_ for _ in ()).throw(RuntimeError("boom")) + r = c.post("/api/tracks/grid/auto", json={"track_id": bare[1]}) + check("…and a failing key never fails the grid", r.status_code == 200, r.text[:200]) + check("nothing reached disk", work.read_bytes() == REAL.read_bytes()) + +print("== BPM alone / Grid alone write through the hand-edit commands ==") +with tempfile.TemporaryDirectory() as d: + from konduktor.adapters.traktor.adapter import TraktorAdapter + from konduktor.core.grid_plan import GridStep + + work = Path(d) / "collection.nml" + shutil.copy2(REAL, work) + a = TraktorAdapter(work) + a.audio_path = lambda tid: Path(__file__) + asked: list[dict] = [] + + def fake_detect(path, *args, **k): + asked.append({key: k.get(key) for key in ("bpm", "anchor")}) + return SimpleNamespace(anchor=k.get("anchor") or 0.777, bpm=k.get("bpm") or 131.0) + + main.grid_detect.detect_grid = fake_detect + + def single_with_companion(): + for t in a.tracks: + cues = a.track_cues(t.id) + if t.grid_locked or not cues or len(cues.grid_markers) != 1: + continue + m = cues.grid_markers[0] + comp = [c for c in cues.cues if c.slot is not None and abs(c.start - m.start) < 0.002] + if comp: + yield t.id, m, comp[0] + + picks = single_with_companion() + tid, m, comp = next(picks) + out = main._analyse_grid(a, tid, GridStep("bpm", hold_anchor=m.start)) + g = out.grid_markers + check("BPM alone asks the detector to hold the anchor", asked[-1] == {"bpm": None, "anchor": m.start}, str(asked[-1])) + check("…and retempos the marker in place", + len(g) == 1 and abs(g[0].bpm - 131.0) < 1e-6 and abs(g[0].start - m.start) < 1e-6, str(g)) + check("…leaving its beat-1 cue where it was", + any(c.slot == comp.slot and abs(c.start - comp.start) < 1e-6 for c in out.cues)) + check("the track's BPM follows", abs(a.track(tid).bpm - 131.0) < 0.01, str(a.track(tid).bpm)) + + tid, m, comp = next(picks) + out = main._analyse_grid(a, tid, GridStep("phase", hold_bpm=m.bpm)) + g = out.grid_markers + check("Grid alone asks the detector to hold the BPM", asked[-1] == {"bpm": m.bpm, "anchor": None}, str(asked[-1])) + check("…and moves the marker, keeping its tempo", + len(g) == 1 and abs(g[0].start - 0.777) < 0.002 and abs(g[0].bpm - m.bpm) < 1e-6, str(g)) + check("…dragging its beat-1 cue along", + any(c.slot == comp.slot and abs(c.start - 0.777) < 0.002 for c in out.cues)) + + bare = next(t for t in a.tracks if t.grid_marker_count == 0 and not t.grid_locked) + out = main._analyse_grid(a, bare.id, GridStep("phase", hold_bpm=128.0)) + check("Grid alone with a BPM but no grid creates one marker at that BPM", + [(round(x.start, 3), x.bpm) for x in out.grid_markers] == [(0.777, 128.0)], str(out.grid_markers)) + try: + main._analyse_grid(a, bare.id, GridStep("skip", "locked")) + check("a skip step is never written", False) + except ValueError: + check("a skip step is never written", True) + print() print("FAILED" if failed else "RESULT: ALL PASSED") raise SystemExit(1 if failed else 0) diff --git a/backend/test_grid_detect.py b/backend/test_grid_detect.py index 36c6db4..d50f355 100644 --- a/backend/test_grid_detect.py +++ b/backend/test_grid_detect.py @@ -136,6 +136,38 @@ print("== a wandering tempo is reported, not hidden ==") r = detect(track(124, tempo_b=124.15)) check("drift is reported when one grid cannot fit", r.drift_ms is not None and r.drift_ms >= 12, f"{r.drift_ms}") +print("== Grid alone: the BPM is held, only the phase is found ==") +r = detect(track(124, first=0.3), bpm=124.0) +check("the given BPM comes back untouched", r.bpm == 124.0, f"got {r.bpm}") +check("the anchor is found on the first kick (±3 ms)", abs(r.anchor - 0.3) <= 0.003, f"got {r.anchor}") +r = detect(track(123.37, first=0.2), bpm=123.37) +check("a non-round held BPM is not snapped to 123", r.bpm == 123.37, f"got {r.bpm}") +check("…and its grid is on the beat at the end (±5 ms)", abs(beat_error_ms(r, 123.37, 0.2, 175)) <= 5) +r = detect(track(124, first=0.4, hat=1.5, bass=1.2), bpm=124.0) +check("the phase traps still hold with a held BPM", + abs(beat_error_ms(r, 124, 0.4, 60)) <= 3, f"{beat_error_ms(r, 124, 0.4, 60):+.1f} ms") +r = detect(track(87, first=0.3), bpm=174.0) +check("a held double-time BPM is kept (the octave is the user's call)", + r.bpm == 174.0 and abs(beat_error_ms(r, 87, 0.3, 60)) <= 3, f"{r.bpm} {beat_error_ms(r, 87, 0.3, 60):+.1f}") +r = detect(track(124, first=0.3), bpm=124.2) +check("a WRONG held BPM is kept, and its drift reported", r.bpm == 124.2 and r.drift_ms >= 20, f"{r.drift_ms}") + +print("== BPM alone: the tempo is found, the anchor is held ==") +r = detect(track(125, first=0.3), anchor=0.3 + 2 * 60 / 125) # a downbeat two beats in +check("the tempo is detected", r.bpm == 125.0, f"got {r.bpm}") +check("the given anchor comes back untouched", r.anchor == 0.3 + 2 * 60 / 125, f"got {r.anchor}") +check("an anchor on the beat reports little drift", r.drift_ms <= 5, f"{r.drift_ms}") +r = detect(track(125, first=0.3), anchor=0.33) +check("an anchor 30 ms off the beat is kept, and the drift says so", + r.anchor == 0.33 and 25 <= r.drift_ms <= 35, f"{r.anchor} {r.drift_ms}") + +print("== holding both is refused ==") +try: + detect(track(124), bpm=124.0, anchor=0.3) + check("bpm + anchor raises ValueError", False) +except ValueError: + check("bpm + anchor raises ValueError", True) + print("== nothing to fit ==") for label, y in (("silence", np.zeros(SR * 20, dtype=np.float32)), ("too short", np.zeros(SR, dtype=np.float32))): try: @@ -144,6 +176,39 @@ for label, y in (("silence", np.zeros(SR * 20, dtype=np.float32)), ("too short", except ValueError: check(f"{label} raises ValueError", True) +print("== the BPM / Grid plan (core/grid_plan) ==") +from types import SimpleNamespace as M # noqa: E402 + +from konduktor.core.grid_plan import plan_grid # noqa: E402 + +one = [M(start=0.5, bpm=124.0)] +two = [M(start=60.0, bpm=126.0), M(start=0.5, bpm=124.0)] # unsorted on purpose + + +def plan(bpm, grid, markers=(), track_bpm=None, locked=False, replace=False): + return plan_grid(bpm=bpm, grid=grid, markers=list(markers), track_bpm=track_bpm, + locked=locked, replace_existing=replace) + + +check("nothing ticked does nothing", plan(False, False, one).action == "none") +check("locked is skipped whatever is ticked", + all(plan(b, g, one, locked=True).reason == "locked" for b, g in ((1, 1), (1, 0), (0, 1)))) +check("BPM+Grid on an ungridded track: full", plan(True, True).action == "full") +check("BPM+Grid on a gridded track, no Replace: skipped as existing", + plan(True, True, one).reason == "existing") +check("BPM+Grid with Replace replaces even a flexible grid", plan(True, True, two, replace=True).action == "full") +s_ = plan(True, False, one) +check("BPM alone keeps the anchor", s_.action == "bpm" and s_.hold_anchor == 0.5) +check("BPM alone ignores Replace (adjusting IS the point)", plan(True, False, one, replace=False).action == "bpm") +check("BPM alone, no grid: analysed in full", plan(True, False, track_bpm=124).action == "full") +s_ = plan(False, True, one, track_bpm=999) +check("Grid alone keeps the MARKER's BPM", s_.action == "phase" and s_.hold_bpm == 124.0) +s_ = plan(False, True, track_bpm=128.0) +check("Grid alone, no grid but a BPM: keeps that BPM", s_.action == "phase" and s_.hold_bpm == 128.0) +check("Grid alone, no BPM at all: analysed in full", plan(False, True).action == "full") +check("one tick on a flexible grid: skipped, never flattened", + plan(True, False, two).reason == "flexible" and plan(False, True, two).reason == "flexible") + print() print("FAILED" if failed else "OK") raise SystemExit(1 if failed else 0) diff --git a/backend/test_key_detect.py b/backend/test_key_detect.py new file mode 100644 index 0000000..97b4d69 --- /dev/null +++ b/backend/test_key_detect.py @@ -0,0 +1,168 @@ +"""Tests for key detection (`core/key_detect.py`) on synthetic audio. + +Needs no audio files: every track is generated, so its key is KNOWN. These +pin what `bench_key_detect.py` (real music) cannot: that all 24 keys come out +— a wrong label order or wheel mapping would get exactly some of them wrong — +that loudness and sample rate do not change the answer, that silence gives no +key rather than a made-up one, and that the numpy network computes what was +trained (the convolution against a direct reference implementation). + +The progressions are cadences that state their key unambiguously (I-IV-V-I; +i-iv-V-i with the raised leading tone). A pop I-V-vi-IV is deliberately NOT +used: it spends a quarter of its time on the relative minor, and a model +trained on dance music — 85% minor — fairly calls some of those minor. +""" +import warnings + +import numpy as np + +warnings.filterwarnings("ignore") + +from konduktor.core import key_detect # noqa: E402 + +SR = 22050 +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 + + +def tone(midi: int, dur: float, amp: float, harmonics: int = 6, sr: int = SR) -> np.ndarray: + t = np.arange(int(dur * sr)) / sr + f = 440.0 * 2 ** ((midi - 69) / 12) + x = sum(np.sin(2 * np.pi * f * h * t) / h for h in range(1, harmonics + 1) if f * h < sr / 2) + env = np.minimum(1, t / 0.01) * np.minimum(1, (dur - t) / 0.05) + return amp * x * env + + +MAJOR = [(0, "M"), (5, "M"), (7, "M"), (0, "M")] # I IV V I +MINOR = [(0, "m"), (5, "m"), (7, "M"), (0, "m")] # i iv V i + + +def song(tonic: int, mode: str, bars: int = 16, bpm: float = 124.0, sr: int = SR) -> np.ndarray: + beat = 60.0 / bpm + prog = MAJOR if mode == "major" else MINOR + out = [] + for b in range(bars): + root, q = prog[b % len(prog)] + r = 48 + (tonic + root) % 12 + chord = sum(tone(r + 12 + i, 4 * beat, 0.12, sr=sr) for i in (0, 4 if q == "M" else 3, 7)) + bass = np.concatenate([tone(r - 12, beat, 0.3, 3, sr=sr) for _ in range(4)]) + n = min(len(chord), len(bass)) + out.append(chord[:n] + bass[:n]) + y = np.concatenate(out) + return (y / np.abs(y).max() * 0.8).astype(np.float32) + + +def name(pc: int, mode: str) -> str: + return key_detect.PITCH_NAMES[pc] + ("m" if mode == "minor" else "") + + +print("all 24 keys") +for mode in ("major", "minor"): + for pc in range(12): + r = key_detect.detect_key_samples(song(pc, mode), SR) + check(f"{name(pc, mode):4s} -> {r.name if r else None}", + r is not None and (r.pitch_class, r.mode) == (pc, mode)) + if r: + check(f"{name(pc, mode):4s} wheel {r.wheel}", r.wheel == key_detect.camelot_wheel(pc, mode)) + +print("the Camelot mapping") +check("C major = 8B", key_detect.camelot_wheel(0, "major") == 8) +check("A minor = 8A", key_detect.camelot_wheel(9, "minor") == 8) +check("G major = 9B (a fifth up = one step)", key_detect.camelot_wheel(7, "major") == 9) +check("F minor = 4A", key_detect.camelot_wheel(5, "minor") == 4) + +print("invariance") +y = song(2, "minor") +base = key_detect.detect_key_samples(y, SR) +quiet = key_detect.detect_key_samples(y * 0.05, SR) +check("a quiet master gives the same key", quiet and quiet.name == base.name) +check("...and the same confidence", quiet and abs(quiet.confidence - base.confidence) < 0.02, + f"{base.confidence:.3f} vs {quiet and quiet.confidence:.3f}") +hi = key_detect.detect_key_samples(song(2, "minor", sr=44100), 44100) +check("44.1 kHz input gives the same key", hi and hi.name == base.name) +check("confidence is a probability", 0.0 < base.confidence <= 1.0) + +print("nothing to say") +check("silence -> None", key_detect.detect_key_samples(np.zeros(SR * 30, np.float32), SR) is None) +check("under 5 s -> None", key_detect.detect_key_samples(song(0, "major")[: SR * 3], SR) is None) + +print("the numpy network") +rng = np.random.default_rng(1) +x = rng.standard_normal((3, 20, 300)).astype(np.float32) # > one time chunk, odd sizes +w = rng.standard_normal((4, 3, 5, 5)).astype(np.float32) +b = rng.standard_normal(4).astype(np.float32) +got = key_detect._conv5(x, w, b) +xp = np.pad(x, ((0, 0), (2, 2), (2, 2))) +ref = np.zeros_like(got) +for o in range(4): + for i in range(3): + for di in range(5): + for dj in range(5): + ref[o] += w[o, i, di, dj] * xp[i, di:di + 20, dj:dj + 300] + ref[o] += b[o] +check("5x5 'same' conv == direct cross-correlation", np.allclose(got, ref, atol=1e-3), + f"max diff {np.abs(got - ref).max():.2e}") +members = key_detect._members() +check("the shipped model is an ensemble of >= 1 network", len(members) >= 1) +spec = key_detect.features(y, SR) +check("24 logits", key_detect.logits(spec).shape == (24,)) + +print("end to end: the Analyze route with the REAL decode and detectors") +# Every other route test fakes the detectors. A route can still be broken +# around working helpers (Auto Hotcues' once 500'd for a week), so one real +# run: a generated F minor track at 124 BPM, written to a WAV, analysed for +# BPM + Grid + Key through `/api/tracks/analyze` on a temp copy of the collection. +import os # noqa: E402 +import shutil # noqa: E402 +import tempfile # noqa: E402 +import time # noqa: E402 +from pathlib import Path # noqa: E402 + +import soundfile # noqa: E402 + +REAL = Path(__file__).resolve().parents[1] / "collection.nml" +with tempfile.TemporaryDirectory() as d: + os.environ["KONDUKTOR_DATA_DIR"] = str(Path(d) / "appdata") + work = Path(d) / "collection.nml" + shutil.copy2(REAL, work) + os.environ["KONDUKTOR_NML"] = str(work) + music = song(5, "minor", bars=24, bpm=124.0) + kick = np.zeros_like(music) + beat = int(round(SR * 60 / 124.0)) + t = np.arange(int(0.12 * SR)) / SR + hit = (np.sin(2 * np.pi * 55 * t) * np.exp(-t / 0.05)).astype(np.float32) + for i in range(0, len(kick) - len(hit), beat): + kick[i:i + len(hit)] += hit + wav = Path(d) / "f-minor.wav" + soundfile.write(wav, 0.6 * music + 0.4 * kick, SR) + + from fastapi.testclient import TestClient + + import konduktor.main as main + + with TestClient(main.app) as c: + a = main.require_adapter() + tid = next(t.id for t in a.tracks if t.grid_marker_count == 0 and t.key_wheel is None) + a.audio_path = lambda track_id: wav + r = c.post("/api/tracks/analyze", json={"track_ids": [tid], "bpm": True, "grid": True, "key": True}) + job = r.json() + while job["state"] == "running": + time.sleep(0.05) + job = c.get(f"/api/jobs/{job['id']}").json() + res = job.get("result") or {} + check("the run finishes without failures", job["state"] == "done" and not res.get("failed"), str(job)[:300]) + track = a.track(tid) + check("the key is F minor (4A), written in the collection's Open Key (9m)", + (track.key_wheel, track.key_mode, track.key) == (4, "minor", "9m"), + f"{track.key} {track.key_wheel} {track.key_mode}") + g = a.track_cues(tid).grid_markers + check("the grid is 124 BPM", len(g) == 1 and abs(g[0].bpm - 124.0) < 0.05, str(g)) + +print("\nFAILED" if failed else "\nall key-detection tests passed") +raise SystemExit(1 if failed else 0) diff --git a/backend/test_layering.py b/backend/test_layering.py index 1835ffd..a1e9113 100644 --- a/backend/test_layering.py +++ b/backend/test_layering.py @@ -95,5 +95,40 @@ for platform, module in NATIVE.items(): ] check(f"the {platform} adapter does import {module} somewhere", bool(own), "nowhere") +print("== remote libraries ==") +# The remote adapter speaks a PROTOCOL; which platform the server holds is the +# server's business. Importing a platform's adapter (or its library) here would +# make a remote library quietly platform-shaped again. +remote_pkg = CORE.parent / "adapters" / "remote" +strays = [] +for src in sorted(remote_pkg.rglob("*.py")): + tree = ast.parse(src.read_text()) + for node in ast.walk(tree): + if isinstance(node, ast.ImportFrom): + mod = node.module or "" + if node.level and any(mod == p or mod.startswith(p + ".") for p in NATIVE): + strays.append(f"{src.name}: ..{mod}") + if not node.level and any(mod.startswith(m) for m in set(NATIVE.values())): + strays.append(f"{src.name}: {mod}") + elif isinstance(node, ast.Import): + for a in node.names: + if any(a.name.startswith(m) for m in set(NATIVE.values())): + strays.append(f"{src.name}: {a.name}") +check("the remote adapter imports no platform adapter or library", not strays, "; ".join(strays)) + +# The server is lightweight by decision: it never decodes audio, so importing +# it must not pull in the analysis stack (and its image ships without it). +import subprocess + +probe = subprocess.run( + [sys.executable, "-c", + "import sys, konduktor.server.app; " + "print(','.join(m for m in ('librosa', 'sklearn', 'torch', 'numba', 'av') if m in sys.modules))"], + capture_output=True, text=True, cwd=str(CORE.parents[1]), +) +heavy = probe.stdout.strip() +check("the server imports no audio-analysis library", probe.returncode == 0 and not heavy, + heavy or probe.stderr[-300:]) + print("\nRESULT:", "FAILED" if failed else "ALL PASSED") sys.exit(1 if failed else 0) diff --git a/backend/test_onelibrary_fidelity.py b/backend/test_onelibrary_fidelity.py index 0133739..4a8eccf 100644 --- a/backend/test_onelibrary_fidelity.py +++ b/backend/test_onelibrary_fidelity.py @@ -349,6 +349,61 @@ check("a missing audio file is reported, not fatal", and dump(db_of(drive))["content"]["2"]["title"] == "Missing", str(outcome.tag_results)) a.close() +# ---- the key: found by meaning, created in rekordbox's spelling, tagged ------- +print("== set_key ==") +from konduktor.adapters.rekordbox.projection import parse_key, render_key # noqa: E402 + +drive = fresh_drive() +audio = drive / TRACK_1.lstrip("/") +make_mp3(audio) +before = dump(db_of(drive)) +keys = {parse_key(r["name"]): pk for pk, r in before["key"].items()} +a = OneLibraryAdapter(drive) +check("the key can be written on an editable stick", a.capabilities().tracks.key_writable is True) +have = next(iter(keys)) +t = a.set_key(TRACK_1, *have) +check("the projection shows it at once", (t.key_wheel, t.key_mode) == have, str(t)) +a.save() +changes = diff(before, dump(db_of(drive))) +check("an existing key: exactly content.key_id changes, pointing at the stick's own row", + len(changes) == 1 and set(changes[0][3]) == {"key_id"} + and str(changes[0][3]["key_id"][1]) == keys[have], str(changes)) +check("and reaches the file's TKEY as the stick names it", + str(mutagen.File(str(audio)).tags.get("TKEY")) == before["key"][keys[have]]["name"], + str(mutagen.File(str(audio)).tags.get("TKEY"))) +before = dump(db_of(drive)) +lack = next((w, m) for w in range(1, 13) for m in ("major", "minor") if (w, m) not in keys) +a.set_key(TRACK_2, *lack) +a.save() +changes = diff(before, dump(db_of(drive))) +added = [c for c in changes if c[0] == "key"] +check("a missing key adds one key row, in rekordbox's spelling", + len(added) == 1 and added[0][2] == "INSERT" and added[0][3]["name"] == render_key(*lack), + describe(changes)) +check("a read-only stick may not", OneLibraryAdapter(drive, read_only=True).capabilities().tracks.key_writable is False) +a.close() + +print("== imported key names (a rekordbox stick holds '12A' beside 'Abm') ==") +goober = Path(tempfile.mkdtemp(prefix="konduktor-olfid-goober-")) / "Goober" +shutil.copytree(FIXTURE.parent / "onelibrary-goober", goober, ignore=shutil.ignore_patterns("after")) +before = dump(db_of(goober)) +names = {r["name"]: pk for pk, r in before["key"].items()} +g = OneLibraryAdapter(goober) +camelot_keyed = [t for t in g.tracks if t.key in ("12A", "11A", "10A")] +check("a track keyed '12A' projects its wheel (it read as no key before)", + camelot_keyed and all(t.key_wheel is not None for t in camelot_keyed), + str([(t.key, t.key_wheel) for t in camelot_keyed])) +target = next(t for t in g.tracks if t.key != "12A") +g.set_key(target.id, 12, "minor") +g.save() +after = dump(db_of(goober)) +check("setting 12A reuses the stick's '12A' row instead of adding 'Dbm'", + len(after["key"]) == len(before["key"]) + and str(next(r for r in after["content"].values() + if r["content_id"] == next(r2["content_id"] for r2 in before["content"].values() + if r2["title"] == target.title))["key_id"]) == names["12A"]) +g.close() + print() print("RESULT:", "FAILED" if failed else "ALL PASSED") sys.exit(1 if failed else 0) diff --git a/backend/test_onelibrary_tracks.py b/backend/test_onelibrary_tracks.py index 67b3c99..e5c6c18 100644 --- a/backend/test_onelibrary_tracks.py +++ b/backend/test_onelibrary_tracks.py @@ -237,6 +237,8 @@ target.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(ONE, target) [pending] = a.add_tracks([NewTrack(track=Track(id="x", title="Kick"), audio_path=target)]) check("an unsaved add plays from its incoming copy", a.track(pending).filepath == str(target)) +check("a file with no key of its own arrives with one detected", a.track(pending).key_wheel is not None, + str(a.track(pending).key)) a.reload() check("Discard deletes the copy and leaves the stick as it was", not target.exists() and fingerprint(drive) == before and a.track(pending) is None) diff --git a/backend/test_picker.py b/backend/test_picker.py index dd520fb..ceb96ce 100644 --- a/backend/test_picker.py +++ b/backend/test_picker.py @@ -36,13 +36,19 @@ def check(label, cond, detail=""): failed = True -opts = platforms() +everything = platforms() +# A remote library is offered LAST, after every platform on this computer: it is +# a way to reach a library (held by a Konduktor server), not a driver here. +opts = [p for p in everything if p.platform != "remote"] by_name = {p.platform: p for p in opts} print("== /api/platforms reports the facts the platform step needs ==") check("every registered driver is offered", len(opts) == len(registry.drivers()), f"{len(opts)} of {len(registry.drivers())}") check("all three platforms present", {"traktor", "rekordbox", "onelibrary"} <= set(by_name)) +check("Remote is offered once, after them, as a remote", + [p.platform for p in everything].count("remote") == 1 and everything[-1].platform == "remote" + and everything[-1].selects == "remote") check("selects is per-platform, not assumed", by_name["traktor"].selects == "file" and by_name["rekordbox"].selects == "file" @@ -61,7 +67,7 @@ check("ordered fixed-location first, then by name", [p.platform for p in opts] == [p.platform for p in sorted(opts, key=lambda o: (o.removable, o.name.lower()))], [p.platform for p in opts]) -check("a second call gives the same order", [p.platform for p in platforms()] == [p.platform for p in opts]) +check("a second call gives the same order", [p.platform for p in platforms()] == [p.platform for p in everything]) print("== /api/library/options is scoped to ONE platform ==") for plat in ("traktor", "rekordbox", "onelibrary"): diff --git a/backend/test_prefs.py b/backend/test_prefs.py new file mode 100644 index 0000000..b80c757 --- /dev/null +++ b/backend/test_prefs.py @@ -0,0 +1,104 @@ +"""userprefs.json under concurrent writes. + +The UI sends several `PATCH /api/prefs` at once on launch (column layout, deck +zoom, loop size), and FastAPI runs them on a thread pool. Before the lock and +the atomic write, a reader could catch the file truncated mid-write, take it for +"no prefs" and write back only its own key — the column layout, and with it +every other pref, vanished between sessions (249 of 300 trials of the burst +below lost the other keys). Nothing failed; the app just forgot. + +Prefs are redirected to a temp file — a test must never rewrite the user's own. +""" +import tempfile +import threading +from pathlib import Path + +from konduktor import prefs + +_TMP = tempfile.TemporaryDirectory() +prefs._PREFS_PATH = Path(_TMP.name) / "userprefs.json" +prefs._LEGACY_PREFS_PATH = Path(_TMP.name) / "absent.json" + +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 + + +BASE = {"columns": {"order": ["a", "b"]}, "autoCueTemplate": [1, 2, 3], "beatSize": 4} +PATCHES = [ + {"columns": {"order": ["b", "a"]}}, + {"mainZoomSec": 16}, + {"beatSize": 8}, + {"stemDevice": "cpu"}, +] + +# The launch burst, many times over: every patch lands and nothing else is lost. +TRIALS = 200 +bad = [] +for i in range(TRIALS): + prefs.save_prefs(BASE) + go = threading.Barrier(len(PATCHES) + 1) + + def write(p): + go.wait() + prefs.update_prefs(p) + + def read(): + go.wait() + for _ in range(20): + if "autoCueTemplate" not in prefs.load_prefs(): + bad.append(f"trial {i}: a reader saw no prefs") + return + + threads = [threading.Thread(target=write, args=(p,)) for p in PATCHES] + threads.append(threading.Thread(target=read)) + for t in threads: + t.start() + for t in threads: + t.join() + got = prefs.load_prefs() + want = {**BASE, **{k: v for p in PATCHES for k, v in p.items()}} + if got != want: + bad.append(f"trial {i}: {got}") +check(f"{TRIALS} concurrent bursts keep every key and every patch", not bad, + bad[0] if bad else "") + +# The path-specific helpers share the lock: a burst of them loses nothing either. +prefs.save_prefs({"autoCueTemplate": [1]}) +threads = [threading.Thread(target=prefs.set_last_collection, args=(f"/lib/{p}", p)) + for p in ("traktor", "rekordbox", "onelibrary")] +threads += [threading.Thread(target=prefs.set_path_mapping, args=(f"/c{n}", "X:", "/Volumes/X")) + for n in range(3)] +for t in threads: + t.start() +for t in threads: + t.join() +got = prefs.load_prefs() +check("concurrent last-collection writes keep every platform", + set(got.get("last_collection_by_platform", {})) == {"traktor", "rekordbox", "onelibrary"}, + str(got)) +check("concurrent path mappings keep every collection", + set(got.get("path_mappings", {})) == {"/c0", "/c1", "/c2"}, str(got)) +check("and the unrelated key survives", got.get("autoCueTemplate") == [1]) + +# A file that will not parse is moved aside, never silently overwritten. +prefs._PREFS_PATH.write_text('{"columns": {"order": ["a"') +check("an unreadable file reads as no prefs", prefs.load_prefs() == {}) +check("reading leaves it in place", prefs._PREFS_PATH.read_text().startswith('{"columns"')) +prefs.update_prefs({"beatSize": 2}) +corrupt = prefs._PREFS_PATH.with_name("userprefs.json.corrupt") +check("writing over it keeps the old bytes beside it", + corrupt.exists() and corrupt.read_text() == '{"columns": {"order": ["a"') +check("and the new file holds the patch", prefs.load_prefs() == {"beatSize": 2}) + +check("no temp file is left behind", + not [p for p in Path(_TMP.name).iterdir() if ".tmp" in p.name]) + +print("\n" + ("❌ FAILED" if failed else "✅ PASSED")) +_TMP.cleanup() +raise SystemExit(1 if failed else 0) diff --git a/backend/test_rekordbox_fidelity.py b/backend/test_rekordbox_fidelity.py index 3348bca..3518f4e 100644 --- a/backend/test_rekordbox_fidelity.py +++ b/backend/test_rekordbox_fidelity.py @@ -684,6 +684,13 @@ with tempfile.TemporaryDirectory() as d: plain_row["DeviceID"] == next(iter(before["djmdContent"].values()))["DeviceID"]) check("the release year is kept", plain_row["ReleaseYear"] == 2021) check("the key is rendered, not copied", prepped_row["KeyID"] is not None) + from konduktor.adapters.rekordbox.projection import parse_key as _pk + key_rows = dump(work)["djmdKey"] + check("a source's own key is kept, not re-detected", + _pk(key_rows[str(prepped_row["KeyID"])]["ScaleName"]) == (10, "minor"), + str(key_rows.get(str(prepped_row["KeyID"])))) + check("a file with no key of its own gets one detected", + plain_row["KeyID"] is not None and str(plain_row["KeyID"]) in key_rows, str(plain_row["KeyID"])) files: dict[str, list] = {} for r in after["contentFile"].values(): files.setdefault(str(r["ContentID"]), []).append(r) @@ -736,5 +743,53 @@ with tempfile.TemporaryDirectory() as d: check("removing it again deletes its analysis files", not dat.exists()) reopened.close() + # ---- K: setting the key ------------------------------------------------ + # Rekordbox fills djmdKey lazily, one row per key it has met, named "Abm" — + # and an imported tag can add "12A". So the key is found by MEANING, a row + # is only ever added for a key the library lacks, and that row looks like + # rekordbox's own: Seq NULL, its own USN. + print("== K: set_key reuses the library's key rows and creates missing ones as rekordbox does ==") + from konduktor.adapters.rekordbox.projection import parse_key as rb_parse_key, render_key + + clean_copy(REAL, work) + before = dump(work) + by_meaning = {rb_parse_key(r["ScaleName"]): pk for pk, r in before["djmdKey"].items()} + adapter = RekordboxAdapter(work) + have = next(((w, m) for (w, m) in by_meaning if w), None) + lack = next(((w, m) for w in range(1, 13) for m in ("major", "minor") if (w, m) not in by_meaning)) + t1, t2 = adapter.tracks[0], adapter.tracks[1] + if have is None: + print(" (skipped the reuse half: this library has no key rows)") + else: + got = adapter.set_key(t1.id, *have) + check("the projection updates immediately", (got.key_wheel, got.key_mode) == have, str(got)) + adapter.save() + changes = diff(before, dump(work)) + check("an existing key: exactly the track row and the counter change", + {t for t, _, _, _ in changes} == {"djmdContent", "agentRegistry"} and len(changes) == 2, + describe(changes)) + content = [c for c in changes if c[0] == "djmdContent"] + check("…pointing at the library's own row for that key", + content and content[0][3].get("KeyID", (None, None))[1] == by_meaning[have], + str(content and content[0][3])) + before = dump(work) + got = adapter.set_key(t2.id, *lack) + adapter.save() + after = dump(work) + changes = diff(before, after) + new_keys = [c for c in changes if c[0] == "djmdKey"] + check("a missing key adds exactly one key row", len(new_keys) == 1 and new_keys[0][2] == "INSERT", + describe(changes)) + if new_keys: + row = new_keys[0][3] + check("named in rekordbox's spelling, Seq NULL, stamped with a USN", + rb_parse_key(row["ScaleName"]) == lack and row["ScaleName"] == render_key(*lack) + and row["Seq"] is None and row["rb_local_usn"] is not None, str(row)) + adapter.set_key(t1.id, *lack) + adapter.save() + check("setting that key again reuses the new row", + len(dump(work)["djmdKey"]) == len(after["djmdKey"])) + adapter.close() + print("\nRESULT:", "FAILED" if failed else "ALL PASSED") sys.exit(1 if failed else 0) diff --git a/backend/test_remote_adapter.py b/backend/test_remote_adapter.py new file mode 100644 index 0000000..67cd0cf --- /dev/null +++ b/backend/test_remote_adapter.py @@ -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"", i) + len(b"") + + +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) diff --git a/backend/test_remote_protocol.py b/backend/test_remote_protocol.py new file mode 100644 index 0000000..be0dada --- /dev/null +++ b/backend/test_remote_protocol.py @@ -0,0 +1,151 @@ +"""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("== remote addresses ==") +from konduktor.adapters.remote.config import Remote + +r = Remote(id="r", name="NAS", host="192.168.1.20", port=8765, fallback_host="konduktor.example.net") +check("each address is built from its own parts", + r.addresses() == [("primary", "http://192.168.1.20:8765"), ("fallback", "http://konduktor.example.net:8765")], + r.addresses()) +r = Remote(id="r", name="NAS", host="192.168.1.20", port=9000, fallback_host="konduktor.example.net") +check("…so a bare fallback gets the default port, not the primary's 9000", + r.addresses()[1] == ("fallback", "http://konduktor.example.net:8765"), r.addresses()) +r = Remote(id="r", name="NAS", host="192.168.1.20", port=9000, fallback_host="https://konduktor.example.net/") +check("a full URL is used exactly as typed (a reverse proxy's port)", + r.addresses()[1] == ("fallback", "https://konduktor.example.net"), r.addresses()) +r = Remote(id="r", name="NAS", host="http://nas.lan:8080") +check("…a URL with its own port keeps it", r.addresses() == [("primary", "http://nas.lan:8080")]) +check("host:port typed inline is split", Remote(id="r", name="N", host="nas.local:9001").addresses()[0][1] + == "http://nas.local:9001") + +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) diff --git a/backend/test_remote_server.py b/backend/test_remote_server.py new file mode 100644 index 0000000..23410ae --- /dev/null +++ b/backend/test_remote_server.py @@ -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) diff --git a/backend/test_remote_stems.py b/backend/test_remote_stems.py new file mode 100644 index 0000000..732bfbd --- /dev/null +++ b/backend/test_remote_stems.py @@ -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) diff --git a/backend/test_save_fidelity.py b/backend/test_save_fidelity.py index 448b02e..b21d6c1 100644 --- a/backend/test_save_fidelity.py +++ b/backend/test_save_fidelity.py @@ -940,5 +940,151 @@ with tempfile.TemporaryDirectory() as d: f"{info.release_date!r} {info.import_date!r}") +# ---- Invariant N: setting a key is localized, in Traktor's two fields ------- +# Traktor keeps the analysed key in (pitch class, +12 for +# minor) and the text it shows / tags files with in INFO@KEY. `set_key` writes +# both, as Traktor's analysis does, in the collection's own notation. +print("== N. set_key writes INFO@KEY + MUSICAL_KEY, localized, in the collection's notation ==") +import re # noqa: E402 + +from konduktor.adapters.traktor.projection import entry_key, musical_key_value, parse_key # noqa: E402 +from konduktor.core.adapter import InvalidCommand # noqa: E402 + +real = TraktorCollection(path=REAL).nml.collection.entry +both = [e for e in real if e.info and e.info.key and e.musical_key is not None + and parse_key(e.info.key)[0] is not None] +agree = sum(musical_key_value(*parse_key(e.info.key)) == e.musical_key.value_attribute for e in both) +check(f"N: MUSICAL_KEY encoding matches INFO@KEY on the real collection ({agree}/{len(both)})", + agree >= 0.995 * len(both), f"{len(both) - agree} disagree") +mk_only = [e for e in real if e.musical_key is not None and not (e.info and e.info.key)] +check(f"N: the {len(mk_only)} MUSICAL_KEY-only entries project a key", + mk_only and all(entry_key(e)[1] is not None for e in mk_only)) + +with tempfile.TemporaryDirectory() as d: + work = Path(d) / "collection.nml" + shutil.copy2(REAL, work) + store = TraktorStore(work) + check("N: the real collection's notation is Open Key", store.key_notation() == "open_key", + store.key_notation()) + + def changed_lines(before: bytes, after: bytes) -> list[str]: + return [dl for dl in difflib.unified_diff(tag_lines(before), tag_lines(after), n=0) + if dl[:1] in "+-" and dl[:3] not in ("+++", "---")] + + # A track that has both: the two existing lines change, nothing else. + keyed = next(e for e in store._nml.collection.entry + if e.location and e.info and e.info.key == "10m" and e.musical_key is not None) + original = store._render() + store.set_key(store._key_of(keyed), 1, "minor") # Camelot 1A = Ab minor = Open Key 6m + changed = changed_lines(original, store._render()) + check("N: a keyed track: only its INFO and MUSICAL_KEY lines change", + len(changed) == 4 and 'KEY="6m"' in changed[1] and changed[3] == '+', + "\n".join(changed)) + + # A track that has neither: MUSICAL_KEY appears where Traktor puts it. + bare = next(e for e in store._nml.collection.entry + if e.location and e.info and not e.info.key and e.musical_key is None + and e.loudness is not None and e.cue_v2) + bare_id = store._key_of(bare) + original = store._render() + store.set_key(bare_id, 8, "major") # C major + after = store._render() + changed = changed_lines(original, after) + check("N: an unkeyed track gains KEY on INFO plus one MUSICAL_KEY element", + len(changed) == 4 and 'KEY="1d"' in changed[1] + and changed[2] == '+' and changed[3] == "+", + "\n".join(changed)) + i = after.find(f'FILE="{bare.location.file}"'.encode()) + span = after[after.rfind(b"", i)].decode() + check("N: …between LOUDNESS and the first CUE_V2, as Traktor writes it", + span.index("\n\n', span) is not None) + + check("N: the file tag is given the INFO text", store._entry_field_value(bare, "key") == "1d") + try: + store.set_key(bare_id, 13, "minor") + check("N: an impossible key is refused", False) + except InvalidCommand: + check("N: an impossible key is refused", True) + + store.save() + e = TraktorCollection(path=work).nml.collection.entry + saved = next(x for x in e if x.location and x.location.file == bare.location.file + and x.location.dir == bare.location.dir) + check("N: survives a save + re-parse", + saved.info.key == "1d" and saved.musical_key.value_attribute == 0 + and entry_key(saved)[1:] == (8, "major")) + +with tempfile.TemporaryDirectory() as d: + # An ADDED entry's key is rendered too: a Pioneer source's "Abm" is not + # copied into an Open Key collection, and MUSICAL_KEY is written. + from konduktor.adapters.traktor.export import SKELETON # noqa: E402 + + work = Path(d) / "collection.nml" + shutil.copy2(REAL, work) + store = TraktorStore(work) + pioneer = SimpleNamespace(title="N add", key="Abm", key_wheel=1, key_mode="minor") + added = store._entry_by_key[store.add_entry(pioneer, Path("/Volumes/KONDUKTOR_TEST_N/a.mp3"))] + check("N: an added Pioneer key is rendered in the collection's notation, with MUSICAL_KEY", + added.info.key == "6m" and added.musical_key.value_attribute == 20, + f"{added.info.key} {added.musical_key}") + odd = SimpleNamespace(title="N odd", key="DANCEDJ.CLUB", key_wheel=None, key_mode=None) + kept = store._entry_by_key[store.add_entry(odd, Path("/Volumes/KONDUKTOR_TEST_N/b.mp3"))] + check("N: text that names no key is kept, with no MUSICAL_KEY", + kept.info.key == "DANCEDJ.CLUB" and kept.musical_key is None) + + empty = Path(d) / "export.nml" + empty.write_text(SKELETON, encoding="utf-8") + fresh = TraktorStore(empty) + camelot = SimpleNamespace(title="N cam", key="8A", key_wheel=8, key_mode="minor") + first = fresh._entry_by_key[fresh.add_entry(camelot, Path("/Volumes/KONDUKTOR_TEST_N/c.mp3"))] + check("N: an empty collection (an export) keeps a Traktor-native source's notation", + first.info.key == "8A", first.info.key) + nxt = fresh._entry_by_key[fresh.add_entry(pioneer, Path("/Volumes/KONDUKTOR_TEST_N/d.mp3"))] + check("N: …and follows it from then on", nxt.info.key == "1A", nxt.info.key) + +with tempfile.TemporaryDirectory() as d: + # The key reaches the frame DJ software reads, in every container written. + import av # noqa: E402 + import mutagen # noqa: E402 + import numpy as np # noqa: E402 + import soundfile # noqa: E402 + + from konduktor.core import audio_tags # noqa: E402 + from stem_test_support import make_mp3 # noqa: E402 + + mp3 = make_mp3(Path(d) / "k.mp3", seconds=1) + flac = Path(d) / "k.flac" + soundfile.write(flac, np.zeros((44100, 2), np.float32), 44100) + m4a = Path(d) / "k.m4a" + with av.open(str(m4a), "w", format="ipod") as c: + st = c.add_stream("aac", rate=44100, layout="stereo") + fr = av.AudioFrame.from_ndarray(np.zeros((2, 1024), np.float32), format="fltp", layout="stereo") + fr.sample_rate = 44100 + for pkt in list(st.encode(fr)) + list(st.encode(None)): + c.mux(pkt) + for path, frame in ((mp3, "TKEY"), (flac, "initialkey"), (m4a, "----:com.apple.iTunes:initialkey")): + r = audio_tags.write_tags(path, {"key": "9m"}) + tags = mutagen.File(str(path)).tags + v = tags.get(frame) + v = v.text[0] if hasattr(v, "text") else (v[0] if v else None) + v = v.decode() if isinstance(v, bytes) else v + check(f"N: {path.suffix} key tag lands in {frame}", r.ok and v == "9m", f"{r} {v!r}") + +with tempfile.TemporaryDirectory() as d: + # A collection keyed in Camelot gets Camelot. + work = Path(d) / "collection.nml" + data = REAL.read_text(encoding="utf-8") + data = re.sub(r'KEY="(\d{1,2})([md])"', + lambda m: f'KEY="{((int(m.group(1)) + 6) % 12) + 1}{"A" if m.group(2) == "m" else "B"}"', data) + work.write_text(data, encoding="utf-8") + store = TraktorStore(work) + check("N: a Camelot collection is detected as one", store.key_notation() == "camelot", store.key_notation()) + target = next(e for e in store._nml.collection.entry if e.location and e.info) + store.set_key(store._key_of(target), 1, "minor") + check("N: …and written in Camelot", target.info.key == "1A", target.info.key) + + print("\nRESULT:", "FAILED" if failed else "ALL PASSED") sys.exit(1 if failed else 0) diff --git a/backend/test_traktor_adapter.py b/backend/test_traktor_adapter.py index 149977e..b05cd2d 100644 --- a/backend/test_traktor_adapter.py +++ b/backend/test_traktor_adapter.py @@ -90,6 +90,7 @@ with tempfile.TemporaryDirectory() as d: check("no cue colours to pick", caps.cues.color == "none" and caps.cues.palette == []) check("flexible beatgrids supported", caps.grid.flexible is True) check("grid is lockable", caps.grid.lockable is True) + check("the key can be written", caps.tracks.key_writable is True) check("save facts present for the UI to compose copy from", caps.save.app_name == "Traktor" and caps.save.overwrite_risk == "on_exit") @@ -106,6 +107,14 @@ with tempfile.TemporaryDirectory() as d: check("metadata edit is visible in the projection", adapter.track(tid).genre == "Konduktor Test Genre") + # key — the projection's wheel, mode AND display text all follow + t = adapter.set_key(tid, 4, "minor") # 4A = F minor = Open Key 9m + check("set_key returns the refreshed track", + t is not None and (t.key, t.key_wheel, t.key_mode) == ("9m", 4, "minor"), + f"{t and (t.key, t.key_wheel, t.key_mode)}") + check("…and the index holds it (the key filter finds it)", + any(x.id == tid for x in adapter.query_tracks(key="9m", limit=20000).items)) + # cues — a free slot on a track with a grid, so the companion guard is clear tid2 = next( t.id for t in adapter.tracks diff --git a/backend/train_key_model.py b/backend/train_key_model.py new file mode 100644 index 0000000..8392a7c --- /dev/null +++ b/backend/train_key_model.py @@ -0,0 +1,209 @@ +"""Train the key-detection network shipped as `konduktor/core/key_model.npz`. + +NOT part of the app or of `run_tests.sh`: a dev tool, run when the model +changes. Two steps in two environments, because the backend never imports +torch and torch is only installed in the stem engine's venv: + + # 0. the data (Beatport EDM previews, hand-annotated keys — ~2.9 GB): + git clone https://github.com/GiantSteps/giantsteps-mtg-key-dataset DATA/mtg + git clone https://github.com/GiantSteps/giantsteps-key-dataset DATA/gs + (cd DATA/mtg && bash audio_dl.sh); (cd DATA/gs && bash audio_dl.sh) + + # 1. features, with the app's own `key_detect.features` (backend venv) + python train_key_model.py features DATA + + # 2. train + export (engine venv: torch) + ../engine/.venv/bin/python train_key_model.py train DATA + +The protocol is the literature's (Korzeniowski & Widmer 2017): TRAIN on +GiantSteps MTG (1,159 tracks with one confident key), TEST on the separate +GiantSteps key dataset (604) — `bench_key_detect.py` scores it. Choices made +on a held-out 20% of MTG, three seeds each (2026-10-04): + - the per-frame dense layer over the full pitch axis beat averaging each + semitone's three bins before it (68.1% vs 66.9% on GiantSteps, val equal); + - a fixed 30-epoch cosine schedule, keeping the LAST epoch: validation on + ~230 tracks is too noisy to pick an epoch from; + - weight decay made no difference and is off. +The shipped file is an ENSEMBLE of three seeds trained on all of MTG, their +logits averaged — each costs ~0.2 s per six-minute track. + +Augmentation: the input window (C2..C7) is shifted by up to six semitones +inside the 7-octave spectrogram, and the label rotated with it, so every +tonic is seen in every position; plus random 128-frame (~24 s) crops. +""" +from __future__ import annotations + +import argparse +import hashlib +import re +import sys +from pathlib import Path + +PC = {"C": 0, "C#": 1, "Db": 1, "D": 2, "D#": 3, "Eb": 3, "E": 4, "F": 5, "F#": 6, + "Gb": 6, "G": 7, "G#": 8, "Ab": 8, "A": 9, "A#": 10, "Bb": 10, "B": 11} +LO, HI, MAX_SHIFT = 36, 216, 6 # must match key_detect.WINDOW +CROP, BATCH, EPOCHS, LR = 128, 16, 30, 1e-3 +SEEDS = (11, 12, 13) +OUT = Path(__file__).parent / "konduktor" / "core" / "key_model.npz" + + +def label(name: str, mode: str) -> int: + """Class index: major C..B = 0..11, minor C..B = 12..23 (key_detect's order).""" + return PC[name] + (12 if mode == "minor" else 0) + + +def mtg_labels(data: Path) -> dict[str, int]: + """MTG ids with ONE key annotated at the dataset's top confidence (2).""" + out = {} + for line in (data / "mtg/annotations/annotations.txt").read_text().splitlines()[1:]: + parts = line.split("\t") + if len(parts) < 3: + continue + m = re.fullmatch(r"([A-G][#b]?) (major|minor)", parts[1].strip()) + if m and parts[2].strip() == "2": + out[f"{parts[0]}.LOFI"] = label(*m.groups()) + return out + + +def gs_labels(data: Path) -> dict[str, int]: + out = {} + for f in (data / "gs/annotations/key").glob("*.key"): + name, mode = f.read_text().split() + out[f.stem] = label(name, mode) + return out + + +# ---- step 1: features (backend venv) --------------------------------------- + + +def _feature_job(args): + import warnings + + warnings.filterwarnings("ignore") + import librosa + import numpy as np + from konduktor.core import key_detect + + src, dst, md5 = args + if dst.exists(): + return "cached" + if not src.exists(): + return "missing" + if hashlib.md5(src.read_bytes()).hexdigest() != md5: + return "bad md5" + y, sr = librosa.load(str(src), sr=key_detect.SR, mono=True) + np.save(dst, key_detect.features(y, sr)) + return "ok" + + +def features(data: Path) -> None: + from collections import Counter + from concurrent.futures import ProcessPoolExecutor + + for which in ("mtg", "gs"): + out = data / "features" / which + out.mkdir(parents=True, exist_ok=True) + jobs = [ + (data / which / "audio" / f"{m.stem}.mp3", out / f"{m.stem}.npy", m.read_text().split()[0]) + for m in sorted((data / which / "md5").iterdir()) + ] + with ProcessPoolExecutor() as ex: + print(which, dict(Counter(ex.map(_feature_job, jobs, chunksize=4))), flush=True) + + +# ---- step 2: train + export (engine venv) ---------------------------------- + + +def _net(torch): + nn, F = torch.nn, torch.nn.functional + + class Net(nn.Module): + """Five 5x5 convs (8 ch, ELU), a dense layer per frame over the whole + pitch axis (48, ELU, dropout), 24 logits averaged over time. + `key_detect._network` is this, in numpy.""" + + def __init__(self, ch=8, layers=5, hid=48): + super().__init__() + self.convs = nn.ModuleList( + [nn.Conv2d(1 if i == 0 else ch, ch, 5, padding=2) for i in range(layers)]) + self.dense = nn.Conv2d(ch, hid, (HI - LO, 1)) + self.out = nn.Conv2d(hid, 24, 1) + self.drop = nn.Dropout(0.3) + + def forward(self, x): # (B, 1, F, T) + for c in self.convs: + x = F.elu(c(x)) + x = self.drop(F.elu(self.dense(x))) + return self.out(x).mean((2, 3)) + + return Net + + +def train(data: Path, seeds=SEEDS, out: Path = OUT) -> None: + import random + + import numpy as np + import torch + import torch.nn.functional as F + + Net = _net(torch) + labels = mtg_labels(data) + X, Y = [], [] + for stem, y in sorted(labels.items()): + f = data / "features/mtg" / f"{stem}.npy" + if f.exists(): + X.append(np.load(f)) + Y.append(y) + print(f"training on {len(X)} tracks", flush=True) + dev = "mps" if torch.backends.mps.is_available() else "cuda" if torch.cuda.is_available() else "cpu" + + arrays: dict[str, np.ndarray] = {"pool": np.array(1)} + for m, seed in enumerate(seeds): + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + net = Net().to(dev) + opt = torch.optim.Adam(net.parameters(), LR) + sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, EPOCHS) + order = list(range(len(X))) + for ep in range(EPOCHS): + net.train() + random.shuffle(order) + total = 0.0 + for i in range(0, len(order), BATCH): + xb, yb = [], [] + for j in order[i:i + BATCH]: + s = random.randint(-MAX_SHIFT, MAX_SHIFT) + x = X[j][LO + 3 * s:HI + 3 * s] + if x.shape[1] > CROP: + o = random.randint(0, x.shape[1] - CROP) + x = x[:, o:o + CROP] + else: + x = np.pad(x, ((0, 0), (0, CROP - x.shape[1]))) + xb.append(x) + # The window moved UP s semitones, so the music moved DOWN. + yb.append((Y[j] % 12 - s) % 12 + Y[j] // 12 * 12) + xt = torch.from_numpy(np.stack(xb))[:, None].to(dev) + loss = F.cross_entropy(net(xt), torch.tensor(yb).to(dev)) + opt.zero_grad() + loss.backward() + opt.step() + total += loss.item() + sched.step() + print(f" seed {seed} epoch {ep + 1}/{EPOCHS} loss {total / (len(order) / BATCH):.3f}", flush=True) + for k, v in net.state_dict().items(): + arrays[f"m{m}." + k.replace("convs.", "conv")] = v.detach().cpu().numpy().astype(np.float32) + np.savez_compressed(out, **arrays) + print(f"wrote {out} ({out.stat().st_size // 1024} KB, {len(seeds)} members)") + + +if __name__ == "__main__": + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("step", choices=("features", "train")) + ap.add_argument("data", type=Path) + a = ap.parse_args() + if a.step == "features": + sys.path.insert(0, str(Path(__file__).parent)) + features(a.data) + else: + train(a.data) diff --git a/frontend/package.json b/frontend/package.json index be94b78..34352af 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "frontend", "private": true, - "version": "0.2.1", + "version": "0.2.3", "type": "module", "scripts": { "dev": "vite", diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 591e923..0ee54a1 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -4,7 +4,7 @@ import type { ColumnSizingState, SortingState, VisibilityState } from '@tanstack import { CapabilitiesContext, slotLabeller } from './lib/capabilities' import { removalNote, writeHint } from './lib/platformCopy' import { invalidateTrackLists } from './lib/trackQueries' -import { api, type CueBatchResult, type GridBatchResult, type AutoCueSlot, type PlaylistNode, type StemBatchResult, type Track, type TrackOrigin } from './api' +import { api, type AnalyzeOptions, type AnalyzeResult, type CueBatchResult, type AutoCueSlot, type PlaylistNode, type StemBatchResult, type Track, type TrackOrigin } from './api' import { confirmDiscardUnsaved } from './lib/unsaved' import { COLUMN_MENU, @@ -19,7 +19,7 @@ import { Toast, type ToastMsg } from './components/Toast' import { CollectionPicker } from './components/CollectionPicker' import { ContextMenu, type MenuItem } from './components/ContextMenu' import { EditTagsDialog } from './components/EditTagsDialog' -import { AnalyzeGridDialog } from './components/AnalyzeGridDialog' +import { AnalyzeDialog } from './components/AnalyzeDialog' import { AutoCueDialog } from './components/AutoCueDialog' import { ConfirmDialog, type ConfirmRequest } from './components/ConfirmDialog' import { PathMappingDialog } from './components/PathMappingDialog' @@ -31,6 +31,7 @@ import { AddFilesDialog, type AddTarget } from './components/AddFilesDialog' import { ConvertStemsDialog } from './components/ConvertStemsDialog' import { StemReportDialog } from './components/StemReportDialog' import { Icon } from './lib/icons' +import { usePrefsWriter } from './lib/prefs' function applyFilters(tracks: Track[], f: Filters): Track[] { const q = f.search.trim().toLowerCase() @@ -84,9 +85,7 @@ export default function App() { // job, polled into the status bar. ONE at a time across both kinds — the // backend refuses a second, since a grid run would move the beats a hotcue // run is placing cues on. - const [gridConfirm, setGridConfirm] = useState< - { ids: string[]; existing: number; locked: number } | null - >(null) + const [analyzing, setAnalyzing] = useState(null) // the Analyze dialog's selection const [cueBatch, setCueBatch] = useState<{ ids: string[]; withoutGrid: number } | null>(null) const [batchJob, setBatchJob] = useState<{ id: string; kind: 'grid' | 'cues' | 'stems' } | null>(null) // Convert to Stems: the dialog's selection, a finished run's Details, and a @@ -117,7 +116,7 @@ export default function App() { const [columnSizing, setColumnSizing] = useState({}) const prefsQuery = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs }) const hydratedRef = useRef(false) - const saveTimer = useRef(null) + const writePrefs = usePrefsWriter() const resetColumns = useCallback(() => { setColumnVisibility(DEFAULT_COLUMN_VISIBILITY) @@ -148,22 +147,14 @@ export default function App() { } }, [prefsQuery.data]) - // Persist layout changes (debounced), but not before hydration so we never - // clobber saved prefs with the initial defaults. + // Persist layout changes (debounced, via the shared prefs writer), but not + // before hydration so we never clobber saved prefs with the initial defaults. useEffect(() => { if (!hydratedRef.current) return - if (saveTimer.current) window.clearTimeout(saveTimer.current) - saveTimer.current = window.setTimeout(() => { - api - .patchPrefs({ - columns: { visibility: columnVisibility, order: columnOrder, sizing: columnSizing }, - }) - .catch(() => {}) - }, 500) - return () => { - if (saveTimer.current) window.clearTimeout(saveTimer.current) - } - }, [columnVisibility, columnOrder, columnSizing]) + writePrefs({ + columns: { visibility: columnVisibility, order: columnOrder, sizing: columnSizing }, + }) + }, [columnVisibility, columnOrder, columnSizing, writePrefs]) const collection = useQuery({ queryKey: ['collection'], queryFn: api.collection }) const loaded = collection.data?.loaded ?? false @@ -422,6 +413,19 @@ export default function App() { : isAll ? (allTracks.data?.items ?? []) : (playlistTracks.data ?? []) + // The deck holds a SNAPSHOT of its track, taken when it was loaded. When the + // view it came from refetches (Analyze wrote its key, Edit Tags its title), + // follow the fresh copy so the deck's KEY readout and header are current. + // PrepStrip keys its audio on the id, so a new object for the same id + // reloads nothing. + useEffect(() => { + if (!prepTrack || viewOriginRef.current !== prepOrigin) return + const fresh = tracks.find((t) => t.id === prepTrack.id) + if (fresh && JSON.stringify(fresh) !== JSON.stringify(prepTrack)) setPrepTrack(fresh) + // Only a refetch of the list matters; prepTrack is read, not tracked. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [tracks]) + const loading = viewingFolder ? folderView.isLoading : viewingDevice @@ -525,7 +529,7 @@ export default function App() { return } if (job.state === 'failed') { - const what = kind === 'grid' ? 'Grid analysis' : 'Auto Hotcues' + const what = kind === 'grid' ? 'Analysis' : 'Auto Hotcues' onError(`${what} failed: ${job.error ?? 'unknown error'}`) return } @@ -538,13 +542,27 @@ export default function App() { let parts: string[] let failures: CueBatchResult['failed'] if (kind === 'grid') { - const r = job.result as unknown as GridBatchResult + const r = job.result as unknown as AnalyzeResult touched = r.analysed failures = r.failed + const g = r.grid + const wrote = [ + g.full ? plural(g.full, 'grid') : '', + g.bpm ? `${plural(g.bpm, 'BPM')} (downbeat kept)` : '', + g.phase ? `${plural(g.phase, 'grid')} at its BPM` : '', + r.key.set ? plural(r.key.set, 'key') : '', + ].filter(Boolean) + const skipped = [ + g.existing ? `${g.existing} with a grid` : '', + g.locked ? `${g.locked} locked` : '', + g.flexible ? `${g.flexible} multi-tempo` : '', + r.key.existing ? `${r.key.existing} with a key` : '', + ].filter(Boolean) parts = [ - `${cancelled ? 'Cancelled — analyzed' : 'Analyzed'} ${plural(r.analysed.length, 'track')}`, - r.existing ? `skipped ${r.existing} with a grid` : '', - r.locked ? `${r.locked} locked` : '', + `${cancelled ? 'Cancelled — analyzed' : 'Analyzed'} ${plural(r.analysed.length, 'track')}` + + (wrote.length ? `: ${wrote.join(', ')}` : ''), + skipped.length ? `skipped ${skipped.join(', ')}` : '', + r.key.none ? `no key found in ${r.key.none}` : '', ] } else { const r = job.result as unknown as CueBatchResult @@ -628,7 +646,44 @@ export default function App() { notify(n ? 'success' : 'error', text, details) } // 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(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(() => { const id = editState.data?.stem_job if (id && !batchJob) setBatchJob({ id, kind: 'stems' }) @@ -699,32 +754,17 @@ export default function App() { y, }) - const runGridAnalysis = async (ids: string[], replaceExisting: boolean) => { - setGridConfirm(null) - try { - const job = await api.autoGridBatch(ids, replaceExisting) - setBatchCancelling(false) - setBatchJob({ id: job.id, kind: 'grid' }) - } catch (e) { - onError((e as Error).message) - } + const runAnalysis = async (ids: string[], opts: AnalyzeOptions) => { + const job = await api.analyze(ids, opts) + setAnalyzing(null) + setBatchCancelling(false) + setBatchJob({ id: job.id, kind: 'grid' }) } - // Confirm only when the run would meet existing grids. Counted from the - // view's tracks, which is where the selection came from. - const startGridAnalysis = (ids: string[]) => { - const byId = new Map(tracks.map((t) => [t.id, t])) - const sel = ids.map((id) => byId.get(id)).filter((t): t is Track => !!t) - const locked = sel.filter((t) => t.grid_locked).length - const existing = sel.filter((t) => !t.grid_locked && t.grid_marker_count > 0).length - if (locked === ids.length) { - notify('error', `${locked === 1 ? 'That grid is' : `All ${locked} grids are`} locked — nothing to analyze`) - } else if (existing > 0) { - setGridConfirm({ ids, existing, locked }) - } else { - void runGridAnalysis(ids, false) - } - } - const canAnalyzeGrid = canEdit && !viewForeign && !!capabilities.data?.grid.editable + // Offered where ANY of BPM / Grid / Key can be stored; the dialog disables + // the rest with a reason. + const canAnalyzeGrid = !!capabilities.data?.grid.editable + const canAnalyzeKey = !!capabilities.data?.tracks.key_writable + const canAnalyze = canEdit && !viewForeign && (canAnalyzeGrid || canAnalyzeKey) const startCueBatch = (ids: string[]) => { const byId = new Map(tracks.map((t) => [t.id, t])) @@ -962,13 +1002,13 @@ export default function App() { ...(canEdit && !viewForeign && menu.ids.length === 1 ? [{ label: 'Edit Tags…', onClick: () => setEditing(menu.track) }] : []), - ...(canAnalyzeGrid + ...(canAnalyze ? [ { - label: 'Analyze Grid & BPM', + label: 'Analyze…', hint: batchJob ? 'busy' : menu.ids.length > 1 ? String(menu.ids.length) : undefined, disabled: !!batchJob, - onClick: () => startGridAnalysis(menu.ids), + onClick: () => setAnalyzing(menu.ids), }, ] : []), @@ -1082,13 +1122,14 @@ export default function App() { onError={onError} /> )} - {gridConfirm && ( - runGridAnalysis(gridConfirm.ids, replace)} - onClose={() => setGridConfirm(null)} + {analyzing && ( + runAnalysis(analyzing, opts)} + onClose={() => setAnalyzing(null)} + onError={onError} /> )} {!!relocation.data?.volumes.length && ( @@ -1480,7 +1521,7 @@ export default function App() { job={ batchJob ? { - label: batchJob.kind === 'grid' ? 'Analyzing grids' : batchJob.kind === 'stems' ? 'Converting to stems' : 'Placing hotcues', + label: batchJob.kind === 'grid' ? 'Analyzing' : batchJob.kind === 'stems' ? 'Converting to stems' : 'Placing hotcues', done: batchJobStatus.data?.done ?? 0, total: batchJobStatus.data?.total ?? 0, detail: batchJobStatus.data?.message, @@ -1506,6 +1547,7 @@ export default function App() { : null } loading={loading} + connection={editState.data?.remote ?? null} collectionName={capabilities.data ? libraryName : null} onChangeCollection={() => { // The same question the sidebar header asks: this button used to diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 1f8b6d7..c967082 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -227,7 +227,10 @@ export interface SaveCapabilities { } /** 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 { platform: Platform @@ -255,12 +258,21 @@ export interface Capabilities { places_audio: boolean /** Tracks can be converted to native-instruments STEM files. */ stem_convertible: boolean + /** The musical key can be set — what key analysis writes. */ + key_writable: boolean /** Lower-case suffixes this library can hold — what a browsed folder lists. */ audio_formats: string[] artwork: boolean 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 } + /** Path mapping / rewriting / the missing-files check apply to this library. */ + paths: { remappable: boolean } save: SaveCapabilities } @@ -271,6 +283,8 @@ export interface LibraryInfo { path: string display_name: string 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 { @@ -278,7 +292,7 @@ export interface PlatformOption { name: string library_label: string /** Whether picking this platform's library means picking a file or a folder. */ - selects: 'file' | 'directory' + selects: 'file' | 'directory' | 'remote' installed: boolean /** How many libraries this platform has right now; `installed` is `found > 0`. */ found: number @@ -300,6 +314,22 @@ export interface EditState { stem_job: string | null /** What this open's crash recovery did about an interrupted conversion. */ 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 { @@ -308,6 +338,61 @@ export interface CollectionStatus { library: LibraryInfo | null tracks: 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 { @@ -434,11 +519,41 @@ export interface JobStatus { } /** What a batch grid analysis did, per track outcome. */ -export interface GridBatchResult { +/** What the Analyze dialog asks for. BPM and Grid are independent halves of + * a beatgrid: BPM alone keeps the downbeat, Grid alone keeps the tempo. + * `replace_grid` only guards a FULL re-analysis (both ticked). */ +export interface AnalyzeOptions { + bpm: boolean + grid: boolean + key: boolean + replace_grid: boolean + replace_key: boolean +} + +/** What an Analyze run WOULD do — the backend's `plan_grid`, per track. */ +export interface AnalyzePreview { + total: number + tracks_to_analyze: number + grid_full: number + grid_bpm: number + grid_phase: number + grid_locked: number + grid_existing: number + grid_flexible: number + /** Unlocked tracks with a grid — the grid Replace tick's count. */ + with_grid: number + key_set: number + key_existing: number + /** Tracks with a key — the key Replace tick's count. */ + with_key: number +} + +/** What an Analyze run did. */ +export interface AnalyzeResult { analysed: string[] - locked: number - existing: number failed: { title: string; reason: string }[] + grid: { full: number; bpm: number; phase: number; locked: number; existing: number; flexible: number } + key: { set: number; existing: number; none: number } } /** What a batch Auto Hotcues run did. `tracks` got the template (whatever it @@ -483,6 +598,9 @@ export interface StemPlan { bytes: number /** The originals' size — what Save deletes in Replace mode. */ 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`. */ @@ -711,6 +829,19 @@ async function getJSON(url: string): Promise { return res.json() as Promise } +/** 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(method: string, url: string, body?: unknown): Promise { const res = await fetch(API_BASE + url, { method, @@ -718,14 +849,19 @@ async function send(method: string, url: string, body?: unknown): Promise body: body ? JSON.stringify(body) : undefined, }) if (!res.ok) { - let detail = `${res.status} ${res.statusText}` + let message = `${res.status} ${res.statusText}` + let detail: unknown = null try { 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 { /* ignore */ } - throw new Error(detail) + throw new ApiError(res.status, message, detail) } return res.json() as Promise } @@ -750,6 +886,21 @@ export const api = { getJSON(`/api/library/options${qs({ platform })}`), listDir: (path?: string, platform?: string) => getJSON(`/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(`/api/library/fs/list${qs({ path })}`), + + // ---- remote libraries ---- + remotes: () => getJSON('/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('POST', '/api/library/open-remote', { remote_id: id, takeover }), + remoteCache: () => getJSON('/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. places: (platform?: string) => getJSON(`/api/fs/places${qs({ platform })}`), @@ -887,12 +1038,11 @@ export const api = { track_id: trackId, slots, }), - // Backend detects tempo + first beat: sets BPM, hotcue 1, and grid anchor. + /** The deck's Analyze: BPM + grid (on Traktor also hotcue 1) and, where the + * library stores one, the key — from one decode. Returns the cues; the key + * lands on the track, so refetch the track lists. */ autoGrid: (trackId: string) => send('POST', '/api/tracks/grid/auto', { track_id: trackId }), - /** Many tracks at once, as a job — poll `job()`. Locked grids are always - * skipped; existing ones unless `replaceExisting`. The finished job's - * `result` is a `GridBatchResult`. */ /** Auto Hotcues over many tracks, one template for all, as a job. A track * without a grid gets one analysed first. The finished job's `result` is a * `CueBatchResult`. */ @@ -921,11 +1071,11 @@ export const api = { stemSideload: (path: string, kind: 'engine' | 'weights') => send('POST', '/api/stems/engine/sideload', { path, kind }), stemEngineRemove: () => send('DELETE', '/api/stems/engine'), - autoGridBatch: (trackIds: string[], replaceExisting: boolean) => - send('POST', '/api/tracks/grid/auto-batch', { - track_ids: trackIds, - replace_existing: replaceExisting, - }), + analyzePreview: (trackIds: string[], opts: AnalyzeOptions) => + send('POST', '/api/tracks/analyze/preview', { track_ids: trackIds, ...opts }), + /** Starts an analysis job; its `result` is an `AnalyzeResult`. */ + analyze: (trackIds: string[], opts: AnalyzeOptions) => + send('POST', '/api/tracks/analyze', { track_ids: trackIds, ...opts }), setCueType: (trackId: string, slot: number, type: CueType) => send('PATCH', '/api/tracks/cue', { track_id: trackId, slot, type }), /** Recolour a cue from `capabilities.cues.palette`; null = uncoloured. */ diff --git a/frontend/src/components/AddFilesDialog.tsx b/frontend/src/components/AddFilesDialog.tsx index d808468..0c2a4eb 100644 --- a/frontend/src/components/AddFilesDialog.tsx +++ b/frontend/src/components/AddFilesDialog.tsx @@ -18,6 +18,10 @@ import { FolderPicker } from './FolderPicker' * how the DJ keeps their music, and a remembered default would quietly apply * 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 — * 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 @@ -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. const caps = useCaps() 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 remote = useServerImportFolder(uploads) const [browsing, setBrowsing] = useState(false) const [job, setJob] = useState(null) const [starting, setStarting] = useState(false) @@ -65,9 +72,13 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P const prefsLoaded = prefs.isSuccess useEffect(() => { if (!prefsLoaded || folder) return + if (uploads) { + if (remote.folder) setFolder(remote.folder) + return + } const p = prefs.data as { importFolder?: string } setFolder(p?.importFolder || '~/Music/Konduktor Imports') - }, [prefsLoaded, prefs.data, folder]) + }, [prefsLoaded, prefs.data, folder, uploads, remote.folder]) const body: FolderAddRequest = { track_ids: trackIds, @@ -192,9 +203,11 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P {browsing && ( { setFolder(path) - api.patchPrefs({ importFolder: path }).catch(() => {}) + if (uploads) remote.remember(path) + else api.patchPrefs({ importFolder: path }).catch(() => {}) }} onClose={() => setBrowsing(false)} /> @@ -224,7 +237,21 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P )} - {!places && ( + {uploads && ( +
+
Uploaded to {remote.serverName} into
+
+ + {folder ? `\u200E${folder}\u200E` : 'Loading…'} + + +
+
+ )} + + {!places && !uploads && (
{option( 'copy', @@ -270,12 +297,12 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
{newCount} new to {libraryName} {shown !== 'reference' && p.total_bytes > 0 && ( - · {gb(p.total_bytes)} to copy + · {gb(p.total_bytes)} to {uploads ? 'upload' : 'copy'} )}
{shown !== 'reference' && p.free_bytes != null && (
- {gb(p.free_bytes)} free + {gb(p.free_bytes)} free{uploads ? ' on the server' : ''} {p.enough_space === false && ' — not enough space'}
)} @@ -369,3 +396,33 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P 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 | 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) diff --git a/frontend/src/components/AnalyzeDialog.tsx b/frontend/src/components/AnalyzeDialog.tsx new file mode 100644 index 0000000..beed3eb --- /dev/null +++ b/frontend/src/components/AnalyzeDialog.tsx @@ -0,0 +1,199 @@ +import { createPortal } from 'react-dom' +import { useEffect, useState, type ReactNode } from 'react' +import { keepPreviousData, useQuery, useQueryClient } from '@tanstack/react-query' +import { api, type AnalyzeOptions, type AnalyzePreview } from '../api' + +interface Props { + /** The selected tracks. */ + ids: string[] + /** The library can write beatgrids (BPM and Grid). */ + gridEditable: boolean + /** The library can store a key. */ + keyWritable: boolean + onRun: (opts: AnalyzeOptions) => Promise + onClose: () => void + onError: (msg: string) => void +} + +type What = Pick +const PREF_KEY = 'analyzeWhat' +const DEFAULT_WHAT: What = { bpm: true, grid: true, key: true } + +/** The remembered ticks; anything malformed falls back to the default. */ +function loadWhat(prefs: Record | undefined): What { + const saved = prefs?.[PREF_KEY] as Partial | undefined + if (!saved || typeof saved !== 'object') return DEFAULT_WHAT + const pick = (k: keyof What) => (typeof saved[k] === 'boolean' ? (saved[k] as boolean) : DEFAULT_WHAT[k]) + return { bpm: pick('bpm'), grid: pick('grid'), key: pick('key') } +} + +const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}` + +/** + * The context menu's "Analyze…" (decided 2026-10-04): which of BPM / Grid / + * Key to analyse, with the "already has one — replace?" questions folded in so + * there is never a second popup. BPM and Grid are independent halves of a + * beatgrid — BPM alone keeps the downbeat, Grid alone keeps the tempo — and + * the grid Replace tick only guards a FULL re-analysis (both ticked). The + * ticks are remembered; the Replace ticks never are — overwriting is a + * decision about THESE tracks. + */ +export function AnalyzeDialog({ ids, gridEditable, keyWritable, onRun, onClose, onError }: Props) { + const qc = useQueryClient() + const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs }) + const [what, setWhat] = useState(null) + const [replaceGrid, setReplaceGrid] = useState(false) + const [replaceKey, setReplaceKey] = useState(false) + const [busy, setBusy] = useState(false) + + // Hydrate once from prefs, masked by what this library can store. + useEffect(() => { + if (what || prefs.isPending) return + const w = loadWhat(prefs.data as Record | undefined) + setWhat({ bpm: w.bpm && gridEditable, grid: w.grid && gridEditable, key: w.key && keyWritable }) + }, [what, prefs.isPending, prefs.data, gridEditable, keyWritable]) + + const opts: AnalyzeOptions | null = what && { + ...what, + replace_grid: what.bpm && what.grid && replaceGrid, + replace_key: what.key && replaceKey, + } + const preview = useQuery({ + queryKey: ['analyze-preview', ids, opts], + queryFn: () => api.analyzePreview(ids, opts!), + enabled: !!opts && (opts.bpm || opts.grid || opts.key), + placeholderData: keepPreviousData, + }) + const p: AnalyzePreview | undefined = preview.data + const nothingTicked = !!what && !(what.bpm || what.grid || what.key) + const count = nothingTicked ? 0 : (p?.tracks_to_analyze ?? 0) + + useEffect(() => { + const onKey = (e: KeyboardEvent) => e.key === 'Escape' && !busy && onClose() + window.addEventListener('keydown', onKey) + return () => window.removeEventListener('keydown', onKey) + }, [busy, onClose]) + + const run = async () => { + if (!opts || busy || count === 0) return + setBusy(true) + api + .patchPrefs({ [PREF_KEY]: { bpm: opts.bpm, grid: opts.grid, key: opts.key } }) + .then((x) => qc.setQueryData(['prefs'], x)) + .catch(() => {}) + try { + await onRun(opts) + } catch (e) { + onError((e as Error).message) + setBusy(false) + } + } + + const toggle = (k: keyof What, label: string, help: string, enabled: boolean, why: string) => ( + + ) + + // What the grid ticks will do, in the dialog's own words. + const gridLines: ReactNode[] = [] + if (p && what && (what.bpm || what.grid)) { + if (what.bpm && what.grid) { + if (p.with_grid > 0) + gridLines.push( +
+ + {p.with_grid}{' '} + {p.with_grid === 1 ? 'already has a grid' : 'already have a grid'} + + +
, + ) + } else if (what.bpm) { + if (p.grid_bpm) gridLines.push(
{plural(p.grid_bpm, 'grid')}: tempo re-detected, downbeat kept
) + if (p.grid_full) gridLines.push(
{plural(p.grid_full, 'track')} without a grid: analyzed in full
) + } else { + if (p.grid_phase) gridLines.push(
{plural(p.grid_phase, 'track')}: downbeats found at the current BPM
) + if (p.grid_full) gridLines.push(
{plural(p.grid_full, 'track')} without a BPM: analyzed in full
) + } + if (p.grid_flexible) + gridLines.push( +
+ {plural(p.grid_flexible, 'multi-tempo grid')} — skipped +
, + ) + if (p.grid_locked) gridLines.push(
{plural(p.grid_locked, 'locked grid')} — skipped
) + } + + return createPortal( +
!busy && onClose()} + > +
e.stopPropagation()}> +
+
Analyze
+
{plural(ids.length, 'track')} selected
+
+ +
+ {toggle('bpm', 'BPM', 'Detect the tempo', gridEditable, "This library's beatgrids cannot be edited")} + {toggle('grid', 'Grid', 'Find where the downbeats fall', gridEditable, "This library's beatgrids cannot be edited")} + {toggle('key', 'Key', 'Detect the musical key', keyWritable, "This library cannot store a key")} +
+ +
+ {gridLines} + {p && what?.key && p.with_key > 0 && ( +
+ + {p.with_key}{' '} + {p.with_key === 1 ? 'already has a key' : 'already have a key'} + + +
+ )} + {nothingTicked &&
Tick what to analyze.
} +
+ +
+ + +
+
+
, + document.body, + ) +} diff --git a/frontend/src/components/AnalyzeGridDialog.tsx b/frontend/src/components/AnalyzeGridDialog.tsx deleted file mode 100644 index 03c4ff4..0000000 --- a/frontend/src/components/AnalyzeGridDialog.tsx +++ /dev/null @@ -1,85 +0,0 @@ -import { createPortal } from 'react-dom' -import { useEffect } from 'react' - -interface Props { - /** Tracks the user selected. */ - total: number - /** Unlocked tracks that already have a beatgrid. */ - existing: number - /** Tracks whose grid is locked — skipped whatever is chosen here. */ - locked: number - onChoose: (replaceExisting: boolean) => void - onClose: () => void -} - -/** Asked only when a batch analysis would meet existing grids: re-analysing a - * grid someone may have hand-fixed is a decision, not a default. */ -export function AnalyzeGridDialog({ total, existing, locked, onChoose, onClose }: Props) { - // "Skip them" would leave nothing to do when every unlocked track has a grid. - const canSkip = existing < total - locked - - useEffect(() => { - const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose() - window.addEventListener('keydown', onKey) - return () => window.removeEventListener('keydown', onKey) - }, [onClose]) - - return createPortal( -
-
e.stopPropagation()} - > -
-
Analyze Grid & BPM
-
- {total} track{total === 1 ? '' : 's'} selected -
-
-
-

- {existing}{' '} - {existing === 1 ? 'already has a beatgrid' : 'already have a beatgrid'}. Replacing - discards any hand edits to {existing === 1 ? 'it' : 'them'}. -

- {locked > 0 && ( -

- {locked} {locked === 1 ? 'is' : 'are'} locked and will be skipped either way. -

- )} -
-
- - - {canSkip && ( - - )} -
-
-
, - document.body, - ) -} diff --git a/frontend/src/components/CollectionPicker.tsx b/frontend/src/components/CollectionPicker.tsx index 4a28015..099b2ba 100644 --- a/frontend/src/components/CollectionPicker.tsx +++ b/frontend/src/components/CollectionPicker.tsx @@ -1,10 +1,12 @@ -import { useState, type ReactNode } from 'react' +import { useState } from 'react' import { useMutation, useQuery } from '@tanstack/react-query' import { api, type CollectionCandidate, type CollectionStatus, type PlatformOption } from '../api' import { FileBrowser, useFsListing } from './FileBrowser' import { browsePrompt, platformAvailability } from '../lib/platformCopy' import { Icon } from '../lib/icons' 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. @@ -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 ( - - ) -} - export function CollectionPicker({ onOpened, onCancel }: Props) { const [step, setStep] = useState<'platform' | 'library' | 'browse'>('platform') const [platform, setPlatform] = useState(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. 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({ queryKey: ['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 @@ -126,7 +86,9 @@ export function CollectionPicker({ onOpened, onCancel }: Props) { const subtitle = step === 'platform' ? 'Konduktor opens libraries from each of these.' - : step === 'library' + : step === 'library' && remote + ? 'A library held by a Konduktor server, played and prepared from here.' + : step === 'library' ? 'Open automatically, resume your last one, or browse.' : platform ? browsePrompt(platform) @@ -146,7 +108,11 @@ export function CollectionPicker({ onOpened, onCancel }: Props) { )}
- {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'}
{subtitle}
@@ -199,6 +165,9 @@ export function CollectionPicker({ onOpened, onCancel }: Props) { /> ))}
+ ) : step === 'library' && remote ? ( + /* ---- Step 2, remote: which server ---- */ + ) : step === 'library' ? ( /* ---- Step 2: which library of that platform ---- */
diff --git a/frontend/src/components/ConvertStemsDialog.tsx b/frontend/src/components/ConvertStemsDialog.tsx index 8dcda10..f14a676 100644 --- a/frontend/src/components/ConvertStemsDialog.tsx +++ b/frontend/src/components/ConvertStemsDialog.tsx @@ -10,6 +10,8 @@ import { type StemTarget, } from '../api' import { FolderPicker } from './FolderPicker' +import { useServerFolder } from './AddFilesDialog' +import { useCaps } from '../lib/capabilities' /** * 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 [starting, setStarting] = useState(false) const [target, setTarget] = useState(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(null) useEffect(() => { 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 choices = useMemo(() => flatten(playlists.data ?? []), [playlists.data]) + const destination = remote ? (serverDest ?? server.folder) : (opts?.destination ?? '') const body: StemConvertOptions | null = opts && { mode: opts.mode, - destination: opts.mode === 'destination' ? opts.destination : null, + destination: opts.mode === 'destination' ? destination : null, collection: opts.mode === 'replace' ? 'repoint' : opts.collection, playlist_id: opts.mode === 'destination' && opts.collection === 'add' && opts.playlist === 'existing' @@ -218,7 +227,17 @@ export function ConvertStemsDialog({ trackIds, onClose, onStarted, onDownloading return createPortal( <> {browsing && opts && ( - set({ destination: path })} onClose={() => setBrowsing(false)} /> + { + if (remote) { + setServerDest(path) + server.remember(path) + } else set({ destination: path }) + }} + onClose={() => setBrowsing(false)} + /> )}
set({ mode: 'destination' }), 'Save to a folder', - - {`‎${opts.destination}‎`} + + {`‎${destination}‎`}
)} + {/* 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 && ( +
+ {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 +
+ )} + {n > 0 && plan.transfer && ( +
    + {plan.space.map((sp) => ( +
  • + {sp.volume}: {size(sp.bytes)} needed + {sp.free != null ? `, ${size(sp.free)} free` : ''} +
  • + ))} +
+ )} {plan.blocked &&
{plan.blocked}
} )} diff --git a/frontend/src/components/FileBrowser.tsx b/frontend/src/components/FileBrowser.tsx index 0bc8466..84f63b8 100644 --- a/frontend/src/components/FileBrowser.tsx +++ b/frontend/src/components/FileBrowser.tsx @@ -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 * 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({ - queryKey: ['fs', path ?? '~', platform ?? null], - queryFn: () => api.listDir(path, platform), + queryKey: ['fs', listing, path ?? '~', platform ?? null], + 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 // the sidebar's device poll: this is a shortcut list, not the thing you came for. const PLACES_POLL_MS = 5000 @@ -59,19 +63,28 @@ interface Props { onPickFile?: (path: string) => void /** The caller's confirm row, pinned under the listing. */ footer?: ReactNode + /** Whose folders are browsed (see `Listing`). Default: this computer's. */ + listing?: Listing } -export function FileBrowser({ mode, platform, path, onNavigate, onPickFile, footer }: Props) { - const listing = useFsListing(path, platform) +export function FileBrowser({ mode, platform, path, onNavigate, onPickFile, footer, listing: whose = 'host' }: Props) { + const listing = useFsListing(path, platform, whose) const places = useQuery({ queryKey: ['fs-places', platform ?? null], queryFn: () => api.places(platform), 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 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 // rows above it under a cursor that is already moving towards one. diff --git a/frontend/src/components/FolderPicker.tsx b/frontend/src/components/FolderPicker.tsx index 8c65818..d9db68d 100644 --- a/frontend/src/components/FolderPicker.tsx +++ b/frontend/src/components/FolderPicker.tsx @@ -1,6 +1,6 @@ import { createPortal } from 'react-dom' import { useState } from 'react' -import { FileBrowser, useFsListing } from './FileBrowser' +import { FileBrowser, useFsListing, type Listing } from './FileBrowser' /** * Pick a FOLDER, by browsing. @@ -15,16 +15,18 @@ interface Props { value: string onChange: (path: string) => 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 // need to know that path to open on it. const [dir, setDir] = useState(value || undefined) const [newFolder, setNewFolder] = useState('') // 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. - const here = useFsListing(dir).data?.path ?? '' + const here = useFsListing(dir, undefined, listing).data?.path ?? '' const confirm = () => { onChange(newFolder.trim() ? `${here}/${newFolder.trim()}` : here) @@ -40,6 +42,7 @@ export function FolderPicker({ value, onChange, onClose }: Props) { { if (!prefsLoaded || baseFolder) return const p = prefs.data as { importFolder?: string; importSubfolder?: boolean } - setBaseFolder(p?.importFolder || '~/Music/Konduktor Imports') + if (uploads) { + if (remote.folder) setBaseFolder(remote.folder) + } else { + setBaseFolder(p?.importFolder || '~/Music/Konduktor Imports') + } if (typeof p?.importSubfolder === 'boolean') setUseSubfolder(p.importSubfolder) - }, [prefsLoaded, prefs.data, baseFolder]) + }, [prefsLoaded, prefs.data, baseFolder, uploads, remote.folder]) const remember = (patch: Record) => { api.patchPrefs(patch).catch(() => { @@ -153,9 +161,11 @@ export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError {browsing && ( { setBaseFolder(path) - remember({ importFolder: path }) + if (uploads) remote.remember(path) + else remember({ importFolder: path }) }} onClose={() => setBrowsing(false)} /> @@ -179,7 +189,9 @@ export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError )} {!places && (
- Copy audio into + + {uploads ? `Upload audio to ${remote.serverName}, into` : 'Copy audio into'} +
void +}) { + return ( + + ) +} diff --git a/frontend/src/components/PrepStrip.tsx b/frontend/src/components/PrepStrip.tsx index 4871ece..4c26503 100644 --- a/frontend/src/components/PrepStrip.tsx +++ b/frontend/src/components/PrepStrip.tsx @@ -33,6 +33,7 @@ import { HotcueBar } from './HotcueBar' import { LoopControls, LOOP_SIZES, type LoopMode } from './LoopControls' import { MainWaveform, MIN_SEC, MAX_SEC, DEFAULT_SEC, type StemLane } from './MainWaveform' import { OverviewWaveform } from './OverviewWaveform' +import { usePrefsWriter } from '../lib/prefs' /** Keys that mute stems 1-4 (Shift = solo), by `KeyboardEvent.code`. */ const STEM_KEYS = ['KeyQ', 'KeyW', 'KeyE', 'KeyR'] @@ -165,11 +166,11 @@ export function PrepStrip({ // Main-waveform zoom persists to userprefs.json so it survives track switches // (MainWaveform unmounts during each load) and app restarts. Hydrate once from - // the shared ['prefs'] query, then persist changes debounced (mirrors the - // column-layout prefs flow in App). + // the shared ['prefs'] query, then persist changes through the shared, + // debounced prefs writer (as App's column layout does). const prefsQuery = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs }) const zoomHydratedRef = useRef(false) - const zoomSaveTimer = useRef(null) + const writePrefs = usePrefsWriter() useEffect(() => { if (zoomHydratedRef.current || !prefsQuery.data) return zoomHydratedRef.current = true @@ -180,20 +181,13 @@ export function PrepStrip({ }, [prefsQuery.data]) useEffect(() => { if (!zoomHydratedRef.current) return // don't clobber saved prefs pre-hydration - if (zoomSaveTimer.current) window.clearTimeout(zoomSaveTimer.current) - zoomSaveTimer.current = window.setTimeout(() => { - api.patchPrefs({ mainZoomSec: secPerView }).catch(() => {}) - }, 500) - return () => { - if (zoomSaveTimer.current) window.clearTimeout(zoomSaveTimer.current) - } - }, [secPerView]) + writePrefs({ mainZoomSec: secPerView }) + }, [secPerView, writePrefs]) // The loop/jump size persists the same way (survives track switches + // restarts). `beatJumpBeats` is its name from when only beat jump had a size; // it is read once so an upgrade keeps the user's choice. const sizeHydratedRef = useRef(false) - const sizeSaveTimer = useRef(null) useEffect(() => { if (sizeHydratedRef.current || !prefsQuery.data) return sizeHydratedRef.current = true @@ -203,14 +197,8 @@ export function PrepStrip({ }, [prefsQuery.data]) useEffect(() => { if (!sizeHydratedRef.current) return // don't clobber saved prefs pre-hydration - if (sizeSaveTimer.current) window.clearTimeout(sizeSaveTimer.current) - sizeSaveTimer.current = window.setTimeout(() => { - api.patchPrefs({ beatSize }).catch(() => {}) - }, 500) - return () => { - if (sizeSaveTimer.current) window.clearTimeout(sizeSaveTimer.current) - } - }, [beatSize]) + writePrefs({ beatSize }) + }, [beatSize, writePrefs]) const getCtx = (): AudioContext => { if (!audioCtxRef.current) { @@ -1055,14 +1043,17 @@ export function PrepStrip({ onError?.((e as Error).message) } } - // Analyze: backend detects BPM + first beat, sets the grid anchor and hotcue 1. + // Analyze: the backend detects BPM + first beat (setting the grid anchor and, + // on Traktor, hotcue 1) and the key where the library stores one. The key + // lands on the track: `applyCueEdit` refetches the lists, and App hands the + // deck the fresh copy. const runAnalyzeGrid = async () => { if (!track || gridBusy) return if (refuseGridEdit()) return setGridBusy(true) try { applyCueEdit(await api.autoGrid(track.id)) - onNotify?.('success', 'Analyzed — set BPM, grid, and hotcue 1') + onNotify?.('success', caps.tracks.key_writable ? 'Analyzed — set BPM, grid and key' : 'Analyzed — set BPM and grid') } catch (e) { onError?.((e as Error).message) } finally { diff --git a/frontend/src/components/QuitGuard.tsx b/frontend/src/components/QuitGuard.tsx index 6ccd5d9..982b6c2 100644 --- a/frontend/src/components/QuitGuard.tsx +++ b/frontend/src/components/QuitGuard.tsx @@ -2,6 +2,7 @@ import { createPortal } from 'react-dom' import { useEffect, useRef, useState } from 'react' import { useQuery } from '@tanstack/react-query' import { api } from '../api' +import { flushPrefs } from '../lib/prefs' /** * Ask before quitting with unsaved changes: Save · Discard · Cancel. @@ -46,6 +47,7 @@ export function QuitGuard() { .then((s) => s.dirty) .catch(() => false) // no library loaded: nothing to lose if (!unsaved) { + await flushPrefs(1000) await invoke('quit_now') return } @@ -73,6 +75,7 @@ export function QuitGuard() { }, [dirty]) const quit = async () => { + await flushPrefs(1000) // a layout change made just before quitting still lands const { invoke } = await import('@tauri-apps/api/core') await invoke('quit_now') } diff --git a/frontend/src/components/RemoteCacheSettings.tsx b/frontend/src/components/RemoteCacheSettings.tsx new file mode 100644 index 0000000..ce8d8b1 --- /dev/null +++ b/frontend/src/components/RemoteCacheSettings.tsx @@ -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(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( +
+
e.stopPropagation()}> +
+

Remote audio

+ +
+
+

+ 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. +

+
+ {u ? `${size(u.bytes)} in ${u.files} file${u.files === 1 ? '' : 's'}` : 'Loading…'} + {u && · {size(u.free)} free on this disk} +
+ + {error &&
{error}
} +
+
+ + +
+
+
, + document.body, + ) +} diff --git a/frontend/src/components/RemotePicker.tsx b/frontend/src/components/RemotePicker.tsx new file mode 100644 index 0000000..b1d8762 --- /dev/null +++ b/frontend/src/components/RemotePicker.tsx @@ -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(null) + const [connecting, setConnecting] = useState(null) + const [error, setError] = useState(null) + const [pending, setPending] = useState<{ status: CollectionStatus; edits: PendingEdits } | null>(null) + + const connect = async (r: RemoteSettings, takeover = false): Promise => { + 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: ( + <> +

{remoteHolder(inUse.machine, inUse.since, inUse.batch)}

+

+ 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. +

+ + ), + 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 ( + setEditing(null)} + onSaved={() => { + setEditing(null) + qc.invalidateQueries({ queryKey: ['remotes'] }) + qc.invalidateQueries({ queryKey: ['platforms'] }) + }} + /> + ) + } + + const list = remotes.data ?? [] + return ( +
+ {remotes.isLoading &&
Loading…
} + {list.map((r) => ( +
+
+ } + title={r.name} + subtitle={connecting === r.id ? 'Connecting…' : addressLine(r)} + busy={connecting !== null} + onClick={() => void connect(r)} + /> +
+ + +
+ ))} + } + title="Add a remote library" + subtitle="The address of a Konduktor server, and the account it was set up with" + onClick={() => setEditing('new')} + /> + {error && ( +
+ {error} +
+ )} + {pending && ( + { + if (choice === 'save') await api.save() + if (choice === 'discard') await api.discard() + onOpened(pending.status) + }} + onError={(msg) => setError(msg)} + /> + )} +
+ ) +} + +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(null) + const [results, setResults] = useState(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) => ( + + ) + + return ( +
+
+ {field('Name', setName(e.target.value)} placeholder="NAS" autoFocus />)} + {field( + 'Address', + 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, or enter a full https://… address if it sits behind a reverse proxy.', + )} + {field( + 'Fallback address', + setFallback(e.target.value)} placeholder="Optional — e.g. https://konduktor.example.net" />, + 'Tried when the first one does not answer — away from home, for instance. Same rules: host[:port] for the server itself (8765 if no port), or a full https://… address used exactly as typed.', + )} + {field('Username', setUsername(e.target.value)} autoComplete="username" />)} + {field( + 'Password', + setPassword(e.target.value)} + placeholder={initial?.has_password ? 'Unchanged' : ''} + autoComplete="current-password" + />, + 'Kept in this computer’s keychain.', + )} + + {results && ( +
+ {results.map((r) => ( +
+ + + + + {r.address === 'primary' ? 'Address' : 'Fallback'}{' '} + {r.url} + {!r.ok && {r.error}} + +
+ ))} +
+ )} + {error && ( +
+ {error} +
+ )} +
+
+ {saved ? ( + + ) : ( + <> + + + + )} +
+
+ ) +} + +/** 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 + 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( +
e.key === 'Escape' && !busy && void choose('later')} + > +
+
+ Unsaved edits from {edits.machine || 'another computer'} +
+
+

This library has edits that were never saved: {edits.summary}.

+

Save them, or discard them to start from the library as it was last saved.

+
+
+ + + + +
+
+
, + document.body, + ) +} diff --git a/frontend/src/components/SettingsMenu.tsx b/frontend/src/components/SettingsMenu.tsx index b2539c0..34b857a 100644 --- a/frontend/src/components/SettingsMenu.tsx +++ b/frontend/src/components/SettingsMenu.tsx @@ -1,4 +1,8 @@ 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 { StemsSettings } from './StemsSettings' @@ -15,7 +19,13 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) { const [open, setOpen] = useState(false) const [showShortcuts, setShowShortcuts] = useState(false) const [showStems, setShowStems] = useState(false) + const [showCache, setShowCache] = useState(false) const ref = useRef(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(() => { if (!open) return @@ -56,6 +66,7 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) { up ? 'bottom-full mb-1' : 'mt-1' }`} > + {remappable && ( + )} + {remote && ( + + )}
) } diff --git a/frontend/src/components/StatusBar.tsx b/frontend/src/components/StatusBar.tsx index 262b55c..e984766 100644 --- a/frontend/src/components/StatusBar.tsx +++ b/frontend/src/components/StatusBar.tsx @@ -1,4 +1,5 @@ import { Icon } from '../lib/icons' +import type { RemoteConnection } from '../api' /** A background job's progress, shown at the right of the bar. */ export interface StatusJob { label: string @@ -29,6 +30,8 @@ interface Props { loading?: boolean collectionName?: string | null onChangeCollection?: () => void + /** A remote library's connection; null for a library on this computer. */ + connection?: RemoteConnection | null } export function StatusBar({ @@ -40,6 +43,7 @@ export function StatusBar({ loading, collectionName, onChangeCollection, + connection, }: Props) { return (
@@ -145,10 +149,11 @@ export function StatusBar({
)} + {connection && } {collectionName && (
) } + +/** 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 ( + + + {look.text} + + ) +} diff --git a/frontend/src/lib/icons.tsx b/frontend/src/lib/icons.tsx index cb77220..de3cf5c 100644 --- a/frontend/src/lib/icons.tsx +++ b/frontend/src/lib/icons.tsx @@ -43,6 +43,13 @@ const PATHS = { ), export: , + server: ( + <> + + + + + ), download: , settings: ( <> diff --git a/frontend/src/lib/platformCopy.ts b/frontend/src/lib/platformCopy.ts index 0ceb3d5..54cd348 100644 --- a/frontend/src/lib/platformCopy.ts +++ b/frontend/src/lib/platformCopy.ts @@ -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.' case 'browsing': 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': default: 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 { if (caps.writable) return null 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' } @@ -85,6 +91,11 @@ export function readOnlyShort(caps: Capabilities): string | null { * Someone told "not found" about OneLibrary would go hunting for a missing app. */ 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 ? '1 drive connected' : `${p.library_label} found` 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 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 = { + '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}.` +} diff --git a/frontend/src/lib/platformIcons.tsx b/frontend/src/lib/platformIcons.tsx index d3ea9b9..39a97eb 100644 --- a/frontend/src/lib/platformIcons.tsx +++ b/frontend/src/lib/platformIcons.tsx @@ -70,6 +70,8 @@ export function PlatformIcon({ // Masks are addressed by id, and one page can show the same mark twice. const mask = `pm-${useId().replace(/:/g, '')}` 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 if (!Mark) return return ( = {} +let timer: number | null = null +let client: QueryClient | null = null +let chain: Promise = Promise.resolve() + +export function queuePrefs(qc: QueryClient, patch: Record): void { + client = qc + Object.assign(pending, patch) + if (timer !== null) window.clearTimeout(timer) + timer = window.setTimeout(() => void flushPrefs(), DEBOUNCE_MS) +} + +/** + * Send anything queued now. Resolves once every write so far has landed, or + * after `timeoutMs` if given — quitting must not wait on a hung backend. + */ +export function flushPrefs(timeoutMs?: number): Promise { + if (timer !== null) { + window.clearTimeout(timer) + timer = null + } + if (Object.keys(pending).length) { + const patch = pending + pending = {} + chain = chain.then(() => + api + .patchPrefs(patch) + .then((p) => { + client?.setQueryData(['prefs'], p) + }) + .catch(() => {}), + ) + } + if (timeoutMs === undefined) return chain + return Promise.race([chain, new Promise((r) => window.setTimeout(r, timeoutMs))]) +} + +/** `queuePrefs` bound to this tree's QueryClient. */ +export function usePrefsWriter(): (patch: Record) => void { + const qc = useQueryClient() + return useCallback((patch) => queuePrefs(qc, patch), [qc]) +} diff --git a/server/Dockerfile b/server/Dockerfile new file mode 100644 index 0000000..16c5998 --- /dev/null +++ b/server/Dockerfile @@ -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 /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"] diff --git a/server/compose.yaml b/server/compose.yaml new file mode 100644 index 0000000..a43dfcb --- /dev/null +++ b/server/compose.yaml @@ -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