mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-28 10:32:51 +01:00
Compare commits
27
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
966f3fe8c5 | ||
|
|
a03b9056a9 | ||
|
|
26b556d975 | ||
|
|
c87444bda5 | ||
|
|
7ba71981c8 | ||
|
|
89c7dade25 | ||
|
|
b154df430a | ||
|
|
e5c7b67626 | ||
|
|
9f79f5a849 | ||
|
|
c8b86100f0 | ||
|
|
0fac84cb73 | ||
|
|
71ee877784 | ||
|
|
920146f2c0 | ||
|
|
ba7b662b93 | ||
|
|
e5fb0f0dbb | ||
|
|
e8a53eee07 | ||
|
|
36a6df4d3b | ||
|
|
72a52d3291 | ||
|
|
c3571fd054 | ||
|
|
b5b3dd04c3 | ||
|
|
4e9472c14a | ||
|
|
957525393b | ||
|
|
bdc62f2c1b | ||
|
|
7960a5a68f | ||
|
|
c5280a95f2 | ||
|
|
e73fa05e1f | ||
|
|
775e94168c |
No files matched your search
@@ -114,6 +114,52 @@ 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
|
||||
env:
|
||||
DOCKER_BUILD_RECORD_UPLOAD: false # no .dockerbuild artifact in the run
|
||||
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.
|
||||
@@ -136,6 +182,9 @@ jobs:
|
||||
- name: Download installers from both builds
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
# Only the installers: the run also holds server-image's Docker build
|
||||
# record, which is not a release asset (and once failed to download).
|
||||
pattern: konduktor-*
|
||||
path: artifacts # → artifacts/konduktor-macOS/…, artifacts/konduktor-Windows/…
|
||||
|
||||
- name: Publish release
|
||||
|
||||
@@ -35,6 +35,21 @@ Two independent apps that talk over HTTP:
|
||||
- `adapter.py` — the `LibraryAdapter` / `LibraryDriver` protocols and the
|
||||
error tree (`NotFound` → 404, `InvalidCommand` → 400, `Unsupported` → 422),
|
||||
mapped to status codes once in `main.py` rather than per route.
|
||||
**`move_playlist(node_id, parent_id, index)`** (sidebar drag and drop,
|
||||
`POST /api/playlists/move`) moves any tree node; `index` counts the new
|
||||
parent's children WITHOUT the node, and it returns the node's id AFTER
|
||||
the move — a Traktor folder's / smart playlist's id is its path, so it
|
||||
changes (playlists keep their UUID, so export sets never need
|
||||
retargeting). Gated per node on `PlaylistNode.can_move`. Traktor refuses a
|
||||
folder or smart playlist landing beside a namesake (as rename does);
|
||||
Rekordbox renumbers `Seq` itself (pyrekordbox's version cannot move to the
|
||||
top level) and keeps `masterPlaylists6.xml`'s `ParentId` in step;
|
||||
OneLibrary renumbers `sequenceNo` from 0, and the pdb follows at Save.
|
||||
`POST /api/playlists/{id}/add` takes `duplicates`: `skip` / `add` / `ask`
|
||||
(nothing changes, the count comes back so the UI can ask and resend);
|
||||
`add` only where `capabilities.playlists.duplicates` — Traktor only, since
|
||||
OneLibrary's `playlist_content` is keyed on (playlist, content) and
|
||||
rekordbox's tolerance of a repeat is unmeasured.
|
||||
- `capabilities.py` — `Capabilities`: what the loaded library can persist, so
|
||||
the UI can gate controls instead of branching on the platform.
|
||||
- `query.py` (`TrackIndex`) — all query/filter/sort/facet/stats logic, over
|
||||
@@ -47,6 +62,10 @@ Two independent apps that talk over HTTP:
|
||||
- `registry.py` — adapter selection by **`can_open()` probe**, not extension
|
||||
(Rekordbox is a `.db`, Serato is a directory).
|
||||
- `audio_tags.py`, `pathmap.py` — format-agnostic helpers.
|
||||
- `grid_edit.py` (`ReplaceGridCommands`) — the marker-level grid commands
|
||||
(add / move-with-clamp / retempo / delete) for a store whose one primitive
|
||||
is `replace_grid`: Rekordbox's and OneLibrary's, whose grids are per-beat
|
||||
lists. Traktor keeps its own, companion-aware versions.
|
||||
- `relocate.py` — **auto path remapping's search** (see `relocation.py`).
|
||||
Fixes ONE thing: a stored prefix changed and the layout under it did not
|
||||
(a collection built on Windows with the SSD as `X:`, opened on a Mac where
|
||||
@@ -110,6 +129,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,
|
||||
@@ -255,8 +311,9 @@ Two independent apps that talk over HTTP:
|
||||
**Memory cues stay preserved-but-uneditable** (Rekordbox is the only
|
||||
platform with them — the two-platform promotion rule).
|
||||
**Hot cue colour is writable** (`set_cue_color`, `PATCH
|
||||
/api/tracks/cue/color`) from `palette.SWATCHES` — the 15 MEASURED swatches
|
||||
of rekordbox's 16 (the teal-green is left out, not guessed); a pick must
|
||||
/api/tracks/cue/color`) from `palette.SWATCHES` — all 16 of rekordbox's
|
||||
swatches, MEASURED (the teal-green, 0x13 #00FF30, came last: rekordbox
|
||||
wrote it as its default for a hot cue added on a stick); a pick must
|
||||
be an exact swatch (`swatch_code`), unlike the exporter's nearest-hue
|
||||
`code_for`. Not a breach of the promotion rule: Rekordbox, OneLibrary and
|
||||
Serato all colour cues — Traktor is the odd one out, by type only, so it
|
||||
@@ -295,9 +352,73 @@ Two independent apps that talk over HTTP:
|
||||
`close()` disposes the SQLAlchemy engine, not just the session — otherwise
|
||||
the OS file handle stays open and `master.db` cannot be replaced. `AppState`
|
||||
closes the previous adapter when opening a new library.
|
||||
- `adapters/onelibrary/` — **read-only.** The cross-vendor USB export format
|
||||
(AlphaTheta + Algoriddim + Native Instruments), read by CDJ-class hardware.
|
||||
Built as the source half of a future "import a stick into Traktor" feature.
|
||||
- `adapters/onelibrary/` — **editable when opened as THE library; read-only
|
||||
when browsed from the sidebar's Devices** (`read_only=True`, cause `browsing`).
|
||||
The cross-vendor USB export format (AlphaTheta + Algoriddim + Native
|
||||
Instruments), read by CDJ-class hardware. Editing is landing in steps toward
|
||||
parity with the Rekordbox adapter — track metadata, playlists, hot cues and
|
||||
the beatgrid, and the `export.pdb` rebuild done and VERIFIED in rekordbox 7
|
||||
(both library views matched); adding/removing tracks done (checked
|
||||
in rekordbox too) and the UI ("Open for editing…" on a Devices row) — all
|
||||
VERIFIED in rekordbox 7 on a real stick (2026-10-01) — decided in
|
||||
[the editing discussion](.claude/discussions/discuss-onelibrary-editing-2026-10-01.md),
|
||||
which also holds what rekordbox 7 was MEASURED writing when it edits a stick
|
||||
(no update counter moves, the `cue` table stays empty, a new playlist goes on
|
||||
top). **The store never opens the database ON the drive**: it works on a copy
|
||||
in app-data and Save writes it back whole — fingerprint check (refuses if
|
||||
another app wrote the stick since open), backup to app-data, temp file beside
|
||||
the database, stale `-wal`/`-shm` deleted, rename — then writes edited text
|
||||
fields into the audio files' tags as rekordbox does (not the rating). Cue tags
|
||||
are read by Konduktor's own `rekordbox/anlz_file.py`, NOT pyrekordbox: rekordbox
|
||||
writes COMPACT cue entries when it edits (48 / 44 bytes, export: 88), and
|
||||
pyrekordbox's parser raised on the 44-byte one and lost the whole `.EXT`.
|
||||
**Cue and grid edits rewrite only the cue LISTS they touch, and inside them
|
||||
only the entries they touch** (`anlz_file.raw_entries` keeps the rest as
|
||||
rekordbox wrote them), held as edited in-memory copies of the `.DAT`/`.EXT`
|
||||
that every read serves, written at Save BEFORE the database (temp + rename,
|
||||
fingerprinted, backed up). Each rule reproduces rekordbox's own measured edit
|
||||
byte for byte: a recolour changes only the `PCP2` colour bytes (palette code
|
||||
+ RGB — rekordbox draws the CODE, so `cues.color` is `palette`, like
|
||||
master.db); a new pad is APPENDED to its lists; a grid edit rewrites `PQTZ`,
|
||||
BLANKS `.EXT`'s `PQT2` (`anlz_writer.blank_pqt2`), clears every loop's beat
|
||||
length to 0/0, leaves `.2EX` alone, and sets `bpmx100` from the first marker.
|
||||
A pad keeps its colour and (unless given one) its name through a move or
|
||||
retype. An `.EXT` without `PCO2` gets both lists seeded from its `PCOB`s on
|
||||
the first edit — readers prefer `PCO2`, so a one-pad list would hide the rest.
|
||||
A track with no analysis files refuses cue/grid edits. Memory cues stay
|
||||
preserved-but-uneditable.
|
||||
**`device_library.py` keeps the stick's legacy `export.pdb` in step** at
|
||||
every Save (rekordbox's own edits let its playlists drift — measured). The
|
||||
stick's own pdb is EDITED (`pdb.PdbEditor`), not regenerated: ids are
|
||||
mirrored from OneLibrary (rekordbox exports both from the same ids), only the
|
||||
tracks / lookup / playlist tables are candidates, a table is rewritten only if
|
||||
a row changed, an unchanged row keeps rekordbox's bytes, and a changed track
|
||||
row is the old row with the edited fields overwritten — so phrase strings,
|
||||
`masterDbId` halves and play counts survive. A track row ends at its last
|
||||
string (`pdb.track_extent`), NOT at the next row: rekordbox's heap holds stale
|
||||
tails between rows. Keys and artwork are mirrored too (pdb artwork row =
|
||||
`a<n>.jpg` beside OneLibrary's `b<n>`); history and `exportExt.pdb` are
|
||||
untouched.
|
||||
**Adding and removing tracks** (`tracks.places_audio`: the LIBRARY places
|
||||
added audio, so the importer asks `place_audio` instead of the user, and the
|
||||
routes check space at `audio_home()`): a file already on the stick is used in
|
||||
place, anything else is copied to `Contents/<Artist>/<Album>/` (rekordbox's
|
||||
layout: `UnknownArtist`/`UnknownAlbum`, file names cut to 48 characters) via
|
||||
`<stick>/.konduktor-incoming/`, playable from there until Save moves it into
|
||||
place; Discard deletes it, and a crashed session's incoming folder is cleared
|
||||
on the next EDITABLE open (never a browsing one). Each added track is decoded
|
||||
once and gets the OneLibrary exporter's own `.DAT`/`.EXT`/`.2EX`
|
||||
(`OneLibraryExporter.anlz_files` builds bytes rather than writing) and art
|
||||
(`art_files`), held in memory and written at Save; hot cues replay through
|
||||
`set_cue`, memory cues (and a hot cue with no free pad) cross as memory cues.
|
||||
The row copies a rekordbox stick row column for column (search columns NULL,
|
||||
no counters) and `property.numberOfContents` follows. Removing deletes every
|
||||
row naming the track (playlist entries renumbered from 1) and, AFTER the
|
||||
database is saved, its audio, analysis files and unshared artwork, pruning
|
||||
emptied folders. The adapter re-projects after every save, since Save moves
|
||||
files. `save.managed_by_export` is set when the drive's root carries an
|
||||
export set's `.konduktor-export.json`, and SaveBar warns that the next export
|
||||
run replaces edits made in place.
|
||||
Full research, incl. the schema, is in
|
||||
[.claude/handoffs/onelibrary-adapter.md](.claude/handoffs/onelibrary-adapter.md);
|
||||
the four things that make it unlike the Rekordbox adapter:
|
||||
@@ -418,6 +539,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:<server id>` so nothing on
|
||||
this computer is mistaken for the server's) and the stems ledger
|
||||
(`RemotePending`) all on the server. Imports UPLOAD
|
||||
(`importer.uploads_audio` → `upload_audio`, cleaned up on failure; free
|
||||
space from the server) into a folder the user picks on the server;
|
||||
Rekordbox's add analysis — waveform, grid AND key — is computed HERE
|
||||
(`core/add_analysis.prepare` with the lead the upload reports, sent as
|
||||
`NewTrack.analysis`).
|
||||
**Convert to Stems** (`stems/remote_convert.py`): the server plans
|
||||
(`/v1/stems/plan`, its `convert.plan`), this computer downloads,
|
||||
separates and encodes, uploads each verified file (`/v1/stems/stage`,
|
||||
sha-256 checked, kept on the server as a LEFTOVER), and the server runs
|
||||
the ordinary `convert._end_step` under its mutation lock with its own
|
||||
ledger (`/v1/stems/publish`). Cancel abandons this run's uploads; a
|
||||
takeover cannot, so they stay and the next run reuses them. The preview
|
||||
adds `transfer` (download / upload / measured speed) and space lines for
|
||||
both machines.
|
||||
UI: the picker's platform list ends with **Remote** (`selects:
|
||||
"remote"`) → `RemotePicker` (saved remotes; the form saves only after
|
||||
`handshake` — a wrong password or version refuses, an unreachable
|
||||
fallback alone does not; the in-use → Take over and the leftover-edits
|
||||
Save / Discard / Decide-later prompts happen before the library shows).
|
||||
`App` polls `['state']` every 5 s for a remote (`remote` in `EditState`),
|
||||
re-reads capabilities on a change and toasts it; `StatusBar` shows the
|
||||
connection. `FileBrowser`/`FolderPicker` take `listing="library"` for the
|
||||
server's folders; Import / Add Files / Convert to Stems use it when
|
||||
`tracks.audio_destination === 'library'` (folders remembered per remote:
|
||||
`remoteImportFolders`, `remoteStemFolders`). Settings → Remote audio is
|
||||
the cache. Path remapping hides on `paths.remappable === false`.
|
||||
- `library_id.py` — a **stable identity for a library that survives it being
|
||||
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
|
||||
@@ -464,7 +684,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
|
||||
@@ -567,12 +793,20 @@ Two independent apps that talk over HTTP:
|
||||
clicking a folder is the `folder` source kind — its audio in the ordinary
|
||||
table, read-only via `readonly_cause: 'not_in_library'`, with files the
|
||||
collection already holds checked off in the # column (`TrackTable`'s
|
||||
`marked`). Capped at 40% of the sidebar and self-scrolling so a deep tree
|
||||
`marked`). A browsed device is read-only (cause `browsing`); **"Open for
|
||||
editing…"** — the drive row's right-click menu, and a button while browsing
|
||||
a device whose caps say `browsing` — opens it as THE library via App's
|
||||
`openForEditing` (unsaved-edits confirm, source closed, library opened).
|
||||
Capped at 40% of the sidebar and self-scrolling so a deep tree
|
||||
gives way before the playlists do) + `AddFilesDialog` (copy vs. leave in
|
||||
place is **asked every time with nothing preselected** — the answer depends
|
||||
on the drive — and warns that a referenced file on an external drive goes
|
||||
missing on unplug. A playlist/export target adds to the collection first
|
||||
and says so; it runs through `importer.run(reference=…, into_playlist=…)`),
|
||||
and says so; it runs through `importer.run(reference=…, into_playlist=…)`.
|
||||
A library with `tracks.places_audio` (a stick) is the exception: no
|
||||
question and no destination — the dialog STATES how many files are copied
|
||||
and how many stay in place (`platformCopy.placedAudioSummary`), and
|
||||
`ImportDialog` drops its destination folder the same way),
|
||||
`CollectionPicker` (**two steps: which PLATFORM, then which
|
||||
library** — Automatic / Open last / Find manually, the last revealing a file
|
||||
browser. The platform comes first because every later answer depends on it:
|
||||
@@ -592,6 +826,21 @@ Two independent apps that talk over HTTP:
|
||||
space below the rows creates at the top level, and the new node is named
|
||||
in place (Esc or an empty name creates nothing). Rename/Delete are on the
|
||||
same menu and the row's hover buttons, which share one set of actions.
|
||||
**Drag and drop** (lib/drag.tsx, below): a row is a drag source and a drop
|
||||
target with ZONES — a playlist's upper/lower half is before/after; a
|
||||
folder's top/bottom quarter before/after and its middle INTO (appended),
|
||||
except the bottom quarter of an OPEN folder, which is "first inside"; the
|
||||
empty space below the rows is "end of the top level". Never into the
|
||||
dragged node's own subtree, and a drop that would change nothing shows no
|
||||
indicator. Holding over a collapsed folder opens it after 0.6 s (tracks
|
||||
too, so nested playlists are reachable). Tracks dropped on a playlist go
|
||||
through `lib/addTracks.ts` — shared with the context menu's "Add to" —
|
||||
which ASKS about duplicates where the platform can hold them (decided:
|
||||
ask each time), and Option/Alt moves them out of the editable playlist
|
||||
they came from. A device's or Files folder's tracks open `ImportDialog`
|
||||
(`trackIds` + `target`) / `AddFilesDialog` with the target filled in
|
||||
(`onAddForeign`), so copy-vs-reference is still asked. Export rows take the
|
||||
collection's tracks and any playlist/folder (as "Add to export" does).
|
||||
A Traktor folder's id is its PATH of names, so the `PATCH`/`DELETE`
|
||||
playlist routes take a `:path` param, a folder name may not contain `/`,
|
||||
and renaming onto a sibling folder's name is refused), `QuitGuard` (mounted in `main.tsx`: the desktop shell PREVENTS window close /
|
||||
@@ -619,7 +868,28 @@ Two independent apps that talk over HTTP:
|
||||
not dnd-kit sortable**: a SortableContext around the virtualizer loops on its
|
||||
flushSync-driven measurement — which is why playlists were once a separate,
|
||||
non-virtualized `PlaylistTable`. Fixed 44 px rows make the drop index just
|
||||
pointer-y / ROW_HEIGHT. dnd-kit still reorders the header's columns.)
|
||||
pointer-y / ROW_HEIGHT. dnd-kit still reorders the header's columns.
|
||||
Every table's rows are a DRAG SOURCE through `lib/drag.tsx` (a selected row
|
||||
carries the selection, the payload's `lead` is the row grabbed, `dragFrom`
|
||||
says whose ids they are and which editable playlist an Option-drag leaves);
|
||||
the in-table reorder is just the table's own drop target.)
|
||||
**`lib/drag.tsx` — drag and drop across the window** (decided 2026-10-06,
|
||||
[the discussion](.claude/discussions/discuss-drag-and-drop-2026-10-06.md)):
|
||||
ONE gesture, the TARGET decides what it means. Pointer events, NOT HTML5
|
||||
DnD — Tauri's webview captures native drag events for file drops on
|
||||
Windows. A source calls `beginDrag` past a 6 px threshold (`usePressToDrag`
|
||||
for plain elements); targets register with `useDropTarget({ hint, label,
|
||||
onDrop })` and are found by `elementFromPoint` then up the ancestors, the
|
||||
innermost whose `hint` is non-null winning, so a target declines a spot by
|
||||
returning null. A module-level store read through narrow
|
||||
`useSyncExternalStore` selectors: a move re-renders only the target under
|
||||
the pointer and the ghost (`DragLayer`, mounted in main.tsx), never the
|
||||
table. Esc cancels (before every other Esc handler); the click after a drop
|
||||
is swallowed; `data-drag-scroll="<top inset>"` makes an element scroll at a
|
||||
20 px edge after a 250 ms dwell — any less and the first/last visible row
|
||||
could not be dropped on. Targets: playlist + export rows (Sidebar,
|
||||
ExportsSection), the tree's zones, the table's reorder, and the DECK
|
||||
(App), which loads the grabbed row paused, in its own origin.
|
||||
`ConvertStemsDialog` (**Convert to Stems**, one dialog — decided: Where =
|
||||
Replace the originals (its option STATES that Save deletes them, since
|
||||
the choice is remembered and may be preselected) or Save to a folder; In
|
||||
@@ -642,6 +912,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
|
||||
@@ -653,7 +935,11 @@ Two independent apps that talk over HTTP:
|
||||
`ContextMenu` (supports `▸` submenus, section headings, separators and
|
||||
checkbox items that toggle without closing — the header row's right-click
|
||||
column chooser uses those; "Add to" lists
|
||||
playlists + exports and acts on the whole selection; "Remove ▸" holds
|
||||
playlists + exports and acts on the whole selection; in an editable
|
||||
playlist "Set Position…" (`SetPositionDialog`, `lib/playlistOrder.ts`)
|
||||
moves the selection as ONE block in playlist order so its first track
|
||||
lands at #N — allowed while sorted/filtered, unlike drag, because it
|
||||
reorders the FULL entry list; "Remove ▸" holds
|
||||
From this playlist / From this export / Grids / Hotcues / From collection,
|
||||
each behind a `ConfirmDialog` — as is the playlist Delete key. Enter
|
||||
confirms unless a button has focus, so Tab-to-Cancel + Enter cancels) + `EditTagsDialog`
|
||||
@@ -765,7 +1051,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
|
||||
|
||||
@@ -777,6 +1067,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)
|
||||
@@ -804,10 +1101,22 @@ 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 `<MUSICAL_KEY>` 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. And
|
||||
**`move_playlist`** (O): the COLLECTION is untouched, a move round-trips and
|
||||
moving back is byte-identical; a folder moves with its subtree and answers
|
||||
its new path id; into its own descendant / beside a namesake is refused with
|
||||
nothing changed; a smart playlist moves by its path id; a no-op is not dirty.
|
||||
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.
|
||||
Traktor-valid, backup-first, COLLECTION byte-identical, original untouched;
|
||||
plus the drag-and-drop routes: `/add`'s three `duplicates` modes (`ask`
|
||||
changes nothing and counts) and `/api/playlists/move` (path id answered,
|
||||
400 into itself, 404 unknown).
|
||||
- `test_timebase.py` — Traktor's MP3 time base: `mp3_gapless` on generated
|
||||
MP3s (header found after a 1 MB ID3 tag; header-less has none), the offset
|
||||
in samples (2257 at 44.1 and 48 kHz, 0 header-less / WAV / missing), every
|
||||
@@ -875,7 +1184,9 @@ serialization path.** It enforces:
|
||||
against SQLite). Asserts a no-op save changes zero rows; a one-field edit
|
||||
changes exactly two — the track and `agentRegistry.localUpdateCount` — with the
|
||||
counter up by one and the edited row stamped with it; edits are invisible on
|
||||
disk until save; and playlist create/fill/rename/delete round-trip. And
|
||||
disk until save; and playlist create/fill/rename/delete round-trip, and
|
||||
`move_playlist` (E2) changes only `djmdPlaylist` rows + the counter with
|
||||
`Seq` 1..n in both parents. And
|
||||
**removing a track** deletes exactly the rows Rekordbox 7 deletes (measured
|
||||
2026-10-01 by diffing a removal made in Rekordbox itself: `djmdContent`,
|
||||
`djmdCue`, `contentCue`, `contentFile`, `djmdMixerParam`, `djmdSongPlaylist`
|
||||
@@ -893,6 +1204,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
|
||||
@@ -901,18 +1217,70 @@ serialization path.** It enforces:
|
||||
Konduktor wrote. Pins the drive-relative path resolution, the `PCOB`/`PCO2`
|
||||
merge, and — cross-checked against the same cues in `master.db` — the dense
|
||||
ANLZ slot numbering, which is the thing most likely to be silently wrong.
|
||||
Also reads `fixtures/onelibrary/rekordbox-edited/` (a stick after rekordbox
|
||||
itself edited it: compact cue entries) and pins browsing vs editable mode. It
|
||||
opens a temp COPY of the fixture — a stray save once rewrote the checked-in one.
|
||||
- `test_onelibrary_fidelity.py` — the row-level diff for OneLibrary writes, on a
|
||||
temp copy of the fixture: nothing reaches the drive before Save, a no-op save
|
||||
changes zero rows, a title edit exactly `content.title` (no counter, as
|
||||
rekordbox), dates as `YYYY-MM-DD` text, lookups found-or-created with
|
||||
`nameForSearch` NULL, a new playlist on top with siblings shifted, entries
|
||||
from 1, a move changing only parent + `sequenceNo` (0..n-1 in both
|
||||
parents); 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). 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
|
||||
blanked `PQT2` and cleared loop beats are rekordbox's bytes exactly, and the
|
||||
new `PQTZ` keeps the marker where it was (rekordbox's own halving moved its
|
||||
anchor 6 ms; within 10 ms). Then fidelity on the demo drive: nothing on the
|
||||
drive before Save, only the touched tags change (in place, order kept), a
|
||||
moved pad keeps colour and name, memory cues refused, swatches only, a
|
||||
same-tempo marker collapses (a per-beat grid has no markers), another app's
|
||||
ANLZ write refused, an `.EXT` with no `PCO2` keeps every pad, a track with no
|
||||
analysis files refuses.
|
||||
- `test_onelibrary_pdb.py` — the Device Library rebuild on Goober's own
|
||||
`export.pdb`: every track row reads (rows end at their last string; stale
|
||||
heap tails ignored), a no-op rebuild returns None and a no-op save leaves the
|
||||
file byte-identical (ids are mirrored), an edit changes only the edited
|
||||
fields, a new playlist and a reorder reach it, every untouched table and
|
||||
`exportExt.pdb` stay byte-identical, another app's pdb write is refused, and a
|
||||
stick without one never gets one.
|
||||
- `test_onelibrary_tracks.py` — adding and removing through `importer.run` on
|
||||
Goober: placement (in place on the stick, else `Contents/<Artist>/<Album>/`,
|
||||
Unknown*, FAT-safe names, 48 chars, suffixed on collision), the prep crossing
|
||||
(pad + colour + name, memory cues, a taken pad -> memory, a detected grid),
|
||||
the row's shape, art as a/b pairs, the Device Library rows; a cancel
|
||||
mid-copy, a Discard and a crash leave nothing; removal deletes rows at once
|
||||
and files only at Save, renumbers playlists and prunes empty folders.
|
||||
- `test_import.py` — the import feature end to end: a drive's tracks into a temp
|
||||
copy of the real collection. Asserts the prep survives (hot cues keep their
|
||||
PAD, memory cues fill spare ones, the flexible grid crosses intact, no
|
||||
companion cue is invented), that the existing 8,485 entries render
|
||||
byte-identically, that the job registry runs/fails/cancels, and that a
|
||||
cancelled import leaves **no orphaned audio and an untouched collection**.
|
||||
And the route with chosen `track_ids` + `into_playlist` + `export_id` (a
|
||||
device drop): only that track, into the playlist and the export, no drive
|
||||
folder made.
|
||||
- `test_grid_detect.py` — beatgrid detection on **synthetic** audio, so the
|
||||
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
|
||||
@@ -920,7 +1288,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
|
||||
@@ -932,6 +1300,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
|
||||
@@ -958,6 +1340,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
|
||||
@@ -1010,11 +1397,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 `<ENTRY>` THROUGH the trip, one download per file, Analyze
|
||||
on the cached copy, export (and a re-export copying nothing), an upload
|
||||
stored in the mapping's stored form, takeover → read-only at once,
|
||||
reopening names the holder and the edits left, leaving releases.
|
||||
- `test_remote_stems.py` — Convert to Stems on a remote with the FAKE engine:
|
||||
the plan's transfer and two-machine space, Replace parks and swaps ON THE
|
||||
SERVER (saved file untouched until Save, which deletes the parked
|
||||
original), Discard restores, Cancel deletes only this run's uploads, a
|
||||
takeover's uploads are reused without the engine.
|
||||
- `test_layering.py` — `core/` imports nothing platform-specific, and no adapter
|
||||
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`.
|
||||
@@ -1047,7 +1458,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); `<MUSICAL_KEY VALUE>` 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 `<GRID BPM>` child
|
||||
(flexible beatgrids, 3.4+); `<TEMPO BPM>` mirrors the **first marker by
|
||||
@@ -1240,7 +1659,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
|
||||
@@ -1268,15 +1688,17 @@ that number and nothing else — everything derives from it:
|
||||
library. Lossiness follows the settled rule: memory cues become hot cues in
|
||||
spare pads (earliest first), cue colour is dropped (Traktor derives it from
|
||||
type).
|
||||
- 🟡 OneLibrary adapter — **read-only, done**. A OneLibrary USB drive opens,
|
||||
projects, browses and searches: tracks, playlists, hot cues, memory cues, loops
|
||||
and flexible beatgrids. Built as the readable SOURCE half of a future
|
||||
**"import a OneLibrary stick into a Traktor library"** feature, which is the
|
||||
motivating use case. Everything unknown about the format is on the write side
|
||||
(the `cue` table's MPEG seek columns, the waveform tags a CDJ draws from, the
|
||||
update counters), so read-only is a deliberate boundary rather than an
|
||||
unfinished one. All research — including the schema, which has no public spec —
|
||||
is in [.claude/handoffs/onelibrary-adapter.md](.claude/handoffs/onelibrary-adapter.md).
|
||||
- ✅ OneLibrary adapter — **reading and editing done**, at parity with the
|
||||
Rekordbox adapter (2026-10-01, [decisions](.claude/discussions/discuss-onelibrary-editing-2026-10-01.md)).
|
||||
A OneLibrary USB drive opens, projects, browses and searches: tracks,
|
||||
playlists, hot cues, memory cues, loops and flexible beatgrids. Done: track
|
||||
metadata (+ file tags), playlists, hot cues and the beatgrid (in the ANLZ
|
||||
files, each rule matching rekordbox's measured edit), the `export.pdb` rebuild
|
||||
on save, adding/removing tracks (the library places the audio), Save via a
|
||||
working copy, and "Open for editing…" on a Devices row — all verified in
|
||||
rekordbox 7. Same gaps as Rekordbox: cover-art writing, memory-cue editing,
|
||||
stem conversion. All format research — including the schema, which has no
|
||||
public spec — is in [.claude/handoffs/onelibrary-adapter.md](.claude/handoffs/onelibrary-adapter.md).
|
||||
- 🟡 **Export/conversion** — **in progress.** Both the design AND the user flow
|
||||
are settled; see
|
||||
[the export discussion doc](.claude/discussions/discuss-export-implementation-2026-09-22.md),
|
||||
@@ -1408,8 +1830,8 @@ that number and nothing else — everything derives from it:
|
||||
rekordbox draw its own defaults (green/orange). **rekordbox draws a hot cue
|
||||
from its palette CODE** (`PCP2` byte 44, before the RGB; `djmdCue.ColorTableIndex`
|
||||
in master.db), not the RGB — `adapters/rekordbox/palette.py` holds the 16-swatch
|
||||
table MEASURED from a rekordbox 7 export (one swatch, ~0x12 teal-green, still
|
||||
unmeasured). Type colours map by intent (cue -> light blue 0x05, loop -> green
|
||||
table MEASURED from a rekordbox 7 export (the teal-green, 0x13 #00FF30, measured
|
||||
later from a rekordbox-edited stick). Type colours map by intent (cue -> light blue 0x05, loop -> green
|
||||
0x16), anything else to the nearest hue; the palette has NO white, so a grid
|
||||
companion is code 0 + RGB white (what rekordbox draws for it: unverified). The
|
||||
**Artwork** (`adapters/rekordbox/artwork.py`, Pillow), measured on a rekordbox 7
|
||||
@@ -1470,7 +1892,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.
|
||||
@@ -1536,6 +1963,16 @@ 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.
|
||||
- ✅ **Drag and drop** (2026-10-06) — tracks onto playlists / exports / the
|
||||
deck, playlists around the tree and onto exports; see `lib/drag.tsx` and
|
||||
the Sidebar under Architecture.
|
||||
- ✅ **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
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,32 @@
|
||||
# Goober: a rekordbox-written stick, before and after rekordbox edited it
|
||||
|
||||
The stick Ben keeps for measuring the Pioneer formats, as rekordbox 7 left it:
|
||||
11 tracks, 2 playlists, **both** libraries (`exportLibrary.db` and the legacy
|
||||
`export.pdb` + `exportExt.pdb`). `test_onelibrary_anlz.py`,
|
||||
`test_onelibrary_pdb.py` and `test_onelibrary_tracks.py` run against copies of it.
|
||||
|
||||
## What is here
|
||||
|
||||
- `PIONEER/rekordbox/` holds the three databases, **untouched**: bytes rekordbox
|
||||
wrote (snapshot `s0`, 2026-10-01).
|
||||
- `PIONEER/USBANLZ/` holds every track's `.DAT` and `.EXT`, trimmed by dropping
|
||||
whole tags: only `PPTH`, `PQTZ`, `PCOB`, `PCO2` and `PQT2` are kept, byte for
|
||||
byte. The waveforms are gone, and so are the `.2EX` files.
|
||||
- `after/` holds the same tags after **rekordbox 7 itself** edited the stick
|
||||
(snapshot `s1`, one edit per track):
|
||||
- `black-bloc-recoloured.EXT`: pad C recoloured to `0x2D` `#FF0045`.
|
||||
- `wtf-87bpm.DAT` / `.EXT`: "Result – WTF" changed from 174 to 87 BPM.
|
||||
- `demo2-pad-e-added.EXT`: a hot cue added on pad E of "Demo Track 2".
|
||||
|
||||
There is no audio. The adapter resolves paths and never needs the files, so the
|
||||
time base falls back to rekordbox's MP3 default, the same offset for reading and
|
||||
writing.
|
||||
|
||||
## Why
|
||||
|
||||
Konduktor's edits are pinned against what rekordbox wrote for the SAME edit, not
|
||||
against Konduktor's own reader. A recolour and a grid edit must reproduce
|
||||
rekordbox's bytes exactly (colour bytes, the blanked `PQT2`, loop beats cleared).
|
||||
The pdb tests prove that an in-place edit of a rekordbox-written `export.pdb`
|
||||
leaves everything else as rekordbox wrote it. The full diff of the measurement is
|
||||
in `.claude/discussions/discuss-onelibrary-editing-2026-10-01.md`.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -56,3 +56,16 @@ implementation — open and write to it.
|
||||
|
||||
Not loaded by the tests; kept as documentation, and as the starting point if
|
||||
Konduktor ever needs to create a drive from nothing.
|
||||
|
||||
## rekordbox-edited/
|
||||
|
||||
Analysis files from a SECOND stick (Goober), after rekordbox 7 itself edited it
|
||||
(2026-10-01): a hot cue added on pad E of `demo-track-2`, and a memory cue added on
|
||||
the start of `nemean`'s memory loop. Trimmed the same way as above, by dropping
|
||||
whole tags: only `PPTH`, `PCOB` and `PCO2` are kept, byte for byte.
|
||||
|
||||
They exist for one property: rekordbox writes **compact** cue entries when it
|
||||
edits (48 bytes for that hot cue, 44 with no colour for the memory cue; an export
|
||||
writes 88). pyrekordbox's parser raises on the 44-byte form, which once made the
|
||||
reader drop the whole `.EXT`, losing pads D-H and every colour. See
|
||||
`adapters/rekordbox/anlz_file.py`.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -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"],
|
||||
|
||||
@@ -5,28 +5,30 @@ Mirrors `adapters.rekordbox.adapter`. It holds:
|
||||
* a ``OneLibraryStore`` — the retained NATIVE model (the open drive),
|
||||
* a ``TrackIndex`` — the generic READ projection built from it.
|
||||
|
||||
**Read-only.** Every command is refused and `capabilities.writable` is False with
|
||||
cause `platform_incomplete`, so the UI never offers an edit in the first place;
|
||||
the raises here are the backstop, not the mechanism.
|
||||
**Editable when opened as THE library**, with parity with the Rekordbox adapter
|
||||
as the goal (decisions: `.claude/discussions/discuss-onelibrary-editing-2026-10-01.md`).
|
||||
Opened `read_only` — as the sidebar's Devices do, beside the loaded library — it
|
||||
reports `writable=False` with cause `browsing`, and every command is refused.
|
||||
|
||||
That scope is deliberate rather than provisional. The purpose of this adapter is
|
||||
to make a OneLibrary drive a readable SOURCE — the half an import into another
|
||||
library needs — and every genuinely unknown part of the format sits on the write
|
||||
side: the `cue` table's eight MPEG frame/offset columns, whose values a player
|
||||
needs to seek accurately in a VBR file; the waveform tags a CDJ draws from; and
|
||||
the update counters a drive uses to reconcile edits made on hardware. None of
|
||||
those has to be guessed at to read a drive, and none of them should be guessed at
|
||||
at all.
|
||||
What a write must look like was MEASURED by diffing a stick before and after
|
||||
rekordbox 7 edited it, rather than guessed: the update counters a drive carries
|
||||
do NOT move, and the `cue` table stays empty. Landing in steps — track metadata,
|
||||
playlists, hot cues and the beatgrid so far; adding and removing tracks next —
|
||||
and every command not written yet is refused, with its capability flag False so
|
||||
the UI never offers it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from ...core.adapter import Unsupported
|
||||
from ...core.adapter import InvalidCommand, Unsupported, local_audio_facts
|
||||
from ...core.capabilities import Capabilities
|
||||
from ...core.model import HotcueChip, PlaylistNode, Track, TrackCues
|
||||
from ...core.model import GridMarker, HotcueChip, PlaylistNode, Track, TrackCues
|
||||
from ...core.pathmap import PathMapping, common_dir_prefix
|
||||
from ...core.query import TrackIndex
|
||||
from ..rekordbox import palette
|
||||
from ..rekordbox.cue_types import WRITABLE_CUE_TYPES
|
||||
from ...exporter import MANIFEST_NAME
|
||||
from . import capabilities as caps
|
||||
from . import projection
|
||||
from .store import OneLibraryStore
|
||||
@@ -42,9 +44,10 @@ ATTRIBUTE_SMART = 4
|
||||
class OneLibraryAdapter:
|
||||
platform = "onelibrary"
|
||||
|
||||
def __init__(self, path: Path):
|
||||
def __init__(self, path: Path, *, read_only: bool = False):
|
||||
self.path = Path(path)
|
||||
self._store = OneLibraryStore(self.path)
|
||||
self.read_only = read_only
|
||||
self._store = OneLibraryStore(self.path, read_only=read_only)
|
||||
self._index = TrackIndex()
|
||||
self._rebuild()
|
||||
|
||||
@@ -60,7 +63,9 @@ class OneLibraryAdapter:
|
||||
self._index.rebuild(tracks)
|
||||
|
||||
def _drive_path(self, row) -> str | None:
|
||||
resolved = self._store.layout.resolve(getattr(row, "path", None))
|
||||
# Through the store: an added track plays from its incoming copy until
|
||||
# Save puts it in place.
|
||||
resolved = self._store.resolve_audio(getattr(row, "path", None))
|
||||
return str(resolved) if resolved is not None else None
|
||||
|
||||
def close(self) -> None:
|
||||
@@ -72,14 +77,27 @@ class OneLibraryAdapter:
|
||||
self._store.close()
|
||||
|
||||
def reload(self) -> None:
|
||||
self._store._load()
|
||||
"""Re-read the drive, DISCARDING unsaved edits."""
|
||||
self._store.discard()
|
||||
self._rebuild()
|
||||
|
||||
def _refresh(self, track_id: str) -> None:
|
||||
"""Re-project one track after a command, so the UI cannot go stale."""
|
||||
from ...core.stem_file import is_stem_file
|
||||
|
||||
row = self._store.content(track_id)
|
||||
path = self._drive_path(row)
|
||||
self._index.replace(projection.to_track(row, path, stem=bool(path) and is_stem_file(path)))
|
||||
|
||||
# ---- identity --------------------------------------------------------
|
||||
def capabilities(self) -> Capabilities:
|
||||
return caps.capabilities_for(
|
||||
device_name=self._store.device_name,
|
||||
version=self._store.db_version,
|
||||
read_only=self.read_only,
|
||||
editable_fields=sorted(OneLibraryStore.EDITABLE_FIELDS),
|
||||
# A drive an export set wrote carries the export's manifest at its root.
|
||||
managed_by_export=(self._store.layout.root / MANIFEST_NAME).is_file(),
|
||||
)
|
||||
|
||||
# ---- read ------------------------------------------------------------
|
||||
@@ -146,7 +164,9 @@ class OneLibraryAdapter:
|
||||
rather than an absence, and treating 0 as a real id would orphan every
|
||||
top-level playlist.
|
||||
"""
|
||||
rows = self._store.playlists()
|
||||
rows = sorted(self._store.playlists(),
|
||||
key=lambda r: (int(getattr(r, "sequenceNo", 0) or 0), int(r.playlist_id)))
|
||||
writable = not self.read_only
|
||||
nodes: dict[str, PlaylistNode] = {}
|
||||
parents: dict[str, str] = {}
|
||||
|
||||
@@ -166,13 +186,14 @@ class OneLibraryAdapter:
|
||||
count=(0 if kind == "folder" else len(self._store.playlist_song_ids(node_id))),
|
||||
children=[],
|
||||
selectable=kind == "playlist",
|
||||
# Read-only: every per-node flag is False, and
|
||||
# Opened read-only, every flag is False and
|
||||
# `capabilities.writable` tells the UI why, once.
|
||||
can_add_tracks=False,
|
||||
can_reorder=False,
|
||||
can_rename=False,
|
||||
can_delete=False,
|
||||
can_add_tracks=writable and kind == "playlist",
|
||||
can_reorder=writable and kind == "playlist",
|
||||
can_rename=writable,
|
||||
can_delete=writable,
|
||||
can_contain_children=kind == "folder",
|
||||
can_move=writable,
|
||||
)
|
||||
parent = str(getattr(r, "playlist_id_parent", 0) or 0)
|
||||
parents[node_id] = "root" if parent in ("0", "", "None") else parent
|
||||
@@ -203,6 +224,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.
|
||||
|
||||
@@ -238,32 +262,147 @@ class OneLibraryAdapter:
|
||||
# ---- save -------------------------------------------------------------
|
||||
@property
|
||||
def dirty(self) -> bool:
|
||||
return False
|
||||
return self._store.dirty
|
||||
|
||||
def save(self):
|
||||
raise Unsupported(self._readonly_reason("Saving"))
|
||||
self._require_writable("Saving")
|
||||
outcome = self._store.save()
|
||||
# Save MOVES files (an added track's audio leaves its incoming copy), so
|
||||
# the projection is rebuilt from what is now on the drive.
|
||||
self._rebuild()
|
||||
return outcome
|
||||
|
||||
def snapshot(self) -> bytes:
|
||||
raise Unsupported("OneLibrary drives are not versioned by Konduktor")
|
||||
|
||||
# ---- commands: all refused -------------------------------------------
|
||||
# ---- commands -----------------------------------------------------------
|
||||
def _readonly_reason(self, what: str) -> str:
|
||||
if self.read_only:
|
||||
return (f"{what} is not possible while the drive is open for browsing. "
|
||||
"Open it for editing to change it.")
|
||||
return f"{what} is not supported yet for OneLibrary drives."
|
||||
|
||||
def _refuse(self, what: str):
|
||||
raise Unsupported(self._readonly_reason(what))
|
||||
|
||||
def _require_writable(self, what: str) -> None:
|
||||
"""Every write passes through here, so a command added later cannot
|
||||
forget that a browsing drive is read-only."""
|
||||
if self.read_only:
|
||||
self._refuse(what)
|
||||
|
||||
# ---- audio placement (`tracks.places_audio`) ----------------------------
|
||||
def audio_home(self) -> Path:
|
||||
return self._store.audio_home()
|
||||
|
||||
def place_audio(self, source: Path, track) -> Path | None:
|
||||
self._require_writable("Adding tracks")
|
||||
return self._store.place_audio(source, track)
|
||||
|
||||
def add_tracks(self, items: list, *, checkpoint=None) -> list[str]:
|
||||
self._refuse("Adding tracks")
|
||||
"""Add tracks, each arriving ready to prep — as the Rekordbox adapter does.
|
||||
|
||||
A drive keeps the beatgrid, cues and waveforms in per-track analysis
|
||||
files, and rekordbox shows neither grid nor cues without them, so every
|
||||
file is decoded ONCE here and its `.DAT`/`.EXT`/`.2EX` built by the
|
||||
OneLibrary exporter's own writer — the files rekordbox 7 was verified
|
||||
to read. A file with no grid of its own gets Konduktor's.
|
||||
|
||||
Two phases, as in Rekordbox: FIRST the slow, cancellable part (decoding,
|
||||
grid detection, building the analysis and artwork bytes) before the
|
||||
library is touched; THEN the rows, with hot cues replayed through the
|
||||
ordinary `set_cue` so they keep its conventions. Memory cues — and a hot
|
||||
cue with no free pad — cross as memory cues, written with the files.
|
||||
`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, key_detect, waveform
|
||||
from ...core.export import ExportTrack
|
||||
from ..rekordbox import artwork, timebase
|
||||
from .export import OneLibraryExporter
|
||||
|
||||
self._require_writable("Adding tracks")
|
||||
exporter = OneLibraryExporter()
|
||||
prepared = []
|
||||
total = len(items)
|
||||
for n, item in enumerate(items, start=1):
|
||||
audio = Path(item.audio_path)
|
||||
if checkpoint is not None:
|
||||
checkpoint(f"Analysing {item.track.title or audio.name} ({n}/{total})", step=n, of=total)
|
||||
if not audio.is_file():
|
||||
raise InvalidCommand(f"No audio file at {audio}")
|
||||
try:
|
||||
rel = self._store.drive_relative(self._store.final_of(audio))
|
||||
except ValueError:
|
||||
raise InvalidCommand(f"{audio} is not on this drive") from None
|
||||
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
|
||||
hot, memory, taken = [], [], set()
|
||||
for cue in sorted((item.cues.cues if item.cues else []), key=lambda c: c.start):
|
||||
if (cue.role == "hotcue" and cue.slot is not None
|
||||
and 0 <= cue.slot < caps.HOTCUE_SLOTS and cue.slot not in taken):
|
||||
hot.append(cue)
|
||||
taken.add(cue.slot)
|
||||
else:
|
||||
memory.append(cue.model_copy(update={"role": "memory", "slot": None}))
|
||||
# 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 = 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, track, audio, rel, anlz, jpegs, markers, hot, length in prepared:
|
||||
track_id = self._store.add_track(
|
||||
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",
|
||||
length_sec=cue.length or 0.0, name=cue.name)
|
||||
code, _rgb = palette.code_for(cue.color)
|
||||
if cue.color and code:
|
||||
self._store.set_cue_color(track_id, cue.slot, code)
|
||||
added.append(track_id)
|
||||
self._rebuild()
|
||||
return added
|
||||
|
||||
def remove_tracks(self, track_ids: list[str]) -> int:
|
||||
self._refuse("Removing tracks")
|
||||
"""Remove tracks — and, on a stick, their audio and analysis files at Save
|
||||
(decision 3: a stick's audio belongs to its library)."""
|
||||
self._require_writable("Removing tracks")
|
||||
n = self._store.remove_tracks(track_ids)
|
||||
if n:
|
||||
self._rebuild()
|
||||
return n
|
||||
|
||||
def apply_stem_swaps(self, swaps, *, add_to_playlist=None):
|
||||
self._refuse("Converting tracks to stems")
|
||||
|
||||
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None:
|
||||
self._refuse("Editing track metadata")
|
||||
self._require_writable("Editing track metadata")
|
||||
self._store.set_track_metadata(track_id, fields)
|
||||
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")
|
||||
@@ -272,55 +411,130 @@ class OneLibraryAdapter:
|
||||
return self._store.cover_art(track_id)
|
||||
|
||||
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
|
||||
self._refuse("Creating playlists")
|
||||
self._require_writable("Creating playlists")
|
||||
return self._store.create_playlist(name, parent_id)
|
||||
|
||||
def create_folder(self, name: str, parent_id: str | None = None) -> str:
|
||||
self._refuse("Creating playlist folders")
|
||||
self._require_writable("Creating playlist folders")
|
||||
return self._store.create_folder(name, parent_id)
|
||||
|
||||
def rename_playlist(self, node_id: str, name: str) -> None:
|
||||
self._refuse("Renaming playlists")
|
||||
self._require_writable("Renaming playlists")
|
||||
self._store.rename_playlist(node_id, name)
|
||||
|
||||
def delete_playlist(self, node_id: str) -> None:
|
||||
self._refuse("Deleting playlists")
|
||||
self._require_writable("Deleting playlists")
|
||||
self._store.delete_playlist(node_id)
|
||||
|
||||
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
|
||||
self._require_writable("Moving playlists")
|
||||
return self._store.move_playlist(node_id, parent_id, index)
|
||||
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
|
||||
self._refuse("Editing playlists")
|
||||
self._require_writable("Editing playlists")
|
||||
return self._store.set_playlist_entries(node_id, track_ids)
|
||||
|
||||
def set_cue(self, track_id: str, **kw) -> TrackCues:
|
||||
self._refuse("Editing cues")
|
||||
def _refresh_cues(self, track_id: str) -> TrackCues:
|
||||
"""Re-project a track AND return its fresh cues — every cue/grid command
|
||||
ends here, so a route can never serve a stale projection."""
|
||||
self._refresh(track_id)
|
||||
return self.track_cues(track_id) or TrackCues()
|
||||
|
||||
def _check_cue_type(self, cue_type: str) -> None:
|
||||
if cue_type not in WRITABLE_CUE_TYPES:
|
||||
raise Unsupported(f"OneLibrary has no cue type {cue_type!r}")
|
||||
|
||||
def set_cue(
|
||||
self,
|
||||
track_id: str,
|
||||
*,
|
||||
slot: int,
|
||||
start_sec: float,
|
||||
cue_type: str,
|
||||
length_sec: float = 0.0,
|
||||
role: str = "hotcue",
|
||||
name: str | None = None,
|
||||
) -> TrackCues:
|
||||
self._require_writable("Editing cues")
|
||||
if role != "hotcue":
|
||||
# Preserved-but-uneditable, exactly as in the Rekordbox adapter.
|
||||
raise Unsupported(
|
||||
"Memory cues are shown but cannot be edited — only hot cues are writable"
|
||||
)
|
||||
self._check_cue_type(cue_type)
|
||||
self._store.set_cue(track_id, slot=slot, start_sec=start_sec, cue_type=cue_type,
|
||||
length_sec=length_sec, name=name)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> TrackCues:
|
||||
self._refuse("Editing cues")
|
||||
self._require_writable("Editing cues")
|
||||
self._check_cue_type(cue_type)
|
||||
self._store.set_cue_type(track_id, slot, cue_type)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def set_cue_color(self, track_id: str, slot: int, color: str | None) -> TrackCues:
|
||||
self._refuse("Editing cues")
|
||||
self._require_writable("Editing cues")
|
||||
code = None
|
||||
if color is not None:
|
||||
code = palette.swatch_code(color)
|
||||
if code is None:
|
||||
raise InvalidCommand(f"{color!r} is not one of rekordbox's hot cue colours")
|
||||
self._store.set_cue_color(track_id, slot, code)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def delete_cue(self, track_id: str, slot: int) -> TrackCues:
|
||||
self._refuse("Deleting cues")
|
||||
self._require_writable("Deleting cues")
|
||||
self._store.delete_cue(track_id, slot)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues:
|
||||
self._refuse("Placing cues")
|
||||
self._require_writable("Placing cues")
|
||||
for cue in cues:
|
||||
self._check_cue_type(getattr(cue, "type", "cue"))
|
||||
self._store.place_cues(track_id, cues, overwrite=overwrite)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
# ---- commands: beatgrid -----------------------------------------------
|
||||
@staticmethod
|
||||
def _markers_from(markers: list) -> list:
|
||||
"""Accept either GridMarkers or the (start, bpm) tuples routes send."""
|
||||
return [m if isinstance(m, GridMarker) else GridMarker(start=float(m[0]), bpm=float(m[1]))
|
||||
for m in markers]
|
||||
|
||||
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> TrackCues:
|
||||
self._refuse("Editing the beatgrid")
|
||||
self._require_writable("Editing the beatgrid")
|
||||
self._store.add_grid_marker(track_id, start_sec, bpm)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> TrackCues:
|
||||
self._refuse("Editing the beatgrid")
|
||||
self._require_writable("Editing the beatgrid")
|
||||
self._store.move_grid_marker(track_id, index, start_sec)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> TrackCues:
|
||||
self._refuse("Editing the beatgrid")
|
||||
self._require_writable("Editing the beatgrid")
|
||||
self._store.set_grid_marker_bpm(track_id, index, bpm)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def delete_grid_marker(self, track_id: str, index: int) -> TrackCues:
|
||||
self._refuse("Editing the beatgrid")
|
||||
self._require_writable("Editing the beatgrid")
|
||||
self._store.delete_grid_marker(track_id, index)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def replace_grid(self, track_id: str, markers: list) -> TrackCues:
|
||||
self._refuse("Editing the beatgrid")
|
||||
self._require_writable("Editing the beatgrid")
|
||||
self._store.replace_grid(track_id, self._markers_from(markers))
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def set_analysed_grid(self, track_id: str, markers: list) -> TrackCues:
|
||||
self._refuse("Editing the beatgrid")
|
||||
"""An analysis result, as rekordbox's analyser would write it: nothing is
|
||||
paired with a marker (the companion cue is Traktor's), so a replace."""
|
||||
return self.replace_grid(track_id, markers)
|
||||
|
||||
def delete_grid(self, track_id: str) -> TrackCues:
|
||||
self._refuse("Deleting the beatgrid")
|
||||
self._require_writable("Deleting the beatgrid")
|
||||
self._store.delete_grid(track_id)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues:
|
||||
raise Unsupported("OneLibrary has no beatgrid lock")
|
||||
@@ -28,7 +28,8 @@ __all__ = ["BPM_EPSILON", "markers_from_beats", "beats_from_pqtz", "markers_from
|
||||
|
||||
|
||||
def beats_from_pqtz(anlz) -> tuple[list[float], list[float], list[int]] | None:
|
||||
"""Per-beat ``(times_sec, bpms, beat_in_bar)`` from a parsed ANLZ file's `PQTZ` tag.
|
||||
"""Per-beat ``(times_sec, bpms, beat_in_bar)`` from a parsed ANLZ file's `PQTZ` tag
|
||||
(an `anlz_file.AnlzFile`).
|
||||
|
||||
Returns None when the file has no `PQTZ` — which is a real state, not an
|
||||
error: rekordbox analyses one-shot samples too, and gives them an analysis
|
||||
@@ -39,7 +40,7 @@ def beats_from_pqtz(anlz) -> tuple[list[float], list[float], list[int]] | None:
|
||||
for tag in getattr(anlz, "tags", []):
|
||||
if tag.type != "PQTZ":
|
||||
continue
|
||||
entries = getattr(getattr(tag.struct, "content", None), "entries", None)
|
||||
entries = tag.entries
|
||||
if not entries:
|
||||
return None
|
||||
times: list[float] = []
|
||||
|
||||
@@ -1,25 +1,27 @@
|
||||
"""What a OneLibrary drive can persist: nothing, for now.
|
||||
"""What a OneLibrary drive can persist.
|
||||
|
||||
`writable` is False with cause `platform_incomplete`. That is the distinction the
|
||||
capability system exists to draw — this is a ROADMAP GAP, not a refusal. A
|
||||
cloud-synced Rekordbox library is refused permanently to protect the user's other
|
||||
machines; a OneLibrary drive simply has no write path yet, and the UI must word
|
||||
those two very differently.
|
||||
Opened as THE library, a drive is writable, and the per-feature flags say which
|
||||
edits have landed: track metadata, playlists, hot cues, the grid, and adding
|
||||
and removing tracks, so the UI never offers an edit the adapter
|
||||
would refuse. Opened `read_only` — the sidebar's Devices, browsing beside the
|
||||
loaded library — `writable` is False with cause `browsing`, which the UI words
|
||||
as "open it for editing", not as a missing feature.
|
||||
|
||||
The per-feature flags below still report what the FORMAT supports rather than
|
||||
being blanked to false, because that is what `writable=False` is for: the UI can
|
||||
show a drive's cues and grid honestly, and say once, in one place, that the whole
|
||||
library is read-only. Blanking them would claim OneLibrary has no hot cues.
|
||||
With `writable=False` the per-feature flags still report what the FORMAT
|
||||
supports rather than being blanked, because that is what the library-level flag
|
||||
is for: the UI can show a drive's cues and grid honestly and say once, in one
|
||||
place, that the library is read-only. Blanking them would claim OneLibrary has no
|
||||
hot cues.
|
||||
|
||||
Two answers are worth recording now, while the evidence is in front of us, since
|
||||
getting them wrong later would be a silent data bug rather than a missing
|
||||
feature:
|
||||
|
||||
* cue colour is **free RGB**, not a palette index. The `PCO2` tag stores three
|
||||
bytes per cue, and the reference drive held #4D00FF, #33FF00, #00C4FF and
|
||||
#FF8C00. This differs from the desktop Rekordbox adapter, which reports
|
||||
"palette" because `djmdCue` stores an index into a built-in table — the same
|
||||
vendor, two genuinely different representations.
|
||||
* cue colour is a **palette**, like master.db's. `PCO2` stores a palette CODE
|
||||
and an RGB per cue, and rekordbox DRAWS from the code (an export writing only
|
||||
RGB had every cue in rekordbox's defaults) — so a pick is one of rekordbox's
|
||||
16 swatches and both are written. (This was first read as "free RGB" off the
|
||||
RGB bytes alone; the code byte beside them is what decides.)
|
||||
* a loop is a cue with an out-point, so ``loops="cue_type"`` — the same answer
|
||||
as Traktor and Rekordbox, and NOT the `separate_bank` the original
|
||||
multi-platform plan assumed.
|
||||
@@ -34,44 +36,59 @@ from ...core.capabilities import (
|
||||
SaveCapabilities,
|
||||
TrackCapabilities,
|
||||
)
|
||||
from ..rekordbox import palette
|
||||
from ..rekordbox.cue_types import WRITABLE_CUE_TYPES
|
||||
|
||||
# Pads A-H. Unlike `djmdCue.Kind`, the ANLZ slot number is a dense 1-based index,
|
||||
# so the bank really is 1..8 (see `cues.py`).
|
||||
HOTCUE_SLOTS = 8
|
||||
|
||||
|
||||
def capabilities_for(device_name: str | None = None, version: str | None = None) -> Capabilities:
|
||||
def capabilities_for(
|
||||
device_name: str | None = None,
|
||||
version: str | None = None,
|
||||
*,
|
||||
read_only: bool = False,
|
||||
editable_fields: list[str] | None = None,
|
||||
managed_by_export: bool = False,
|
||||
) -> Capabilities:
|
||||
return Capabilities(
|
||||
platform="onelibrary",
|
||||
version=version,
|
||||
# A roadmap gap, not a protective refusal — the UI words the two
|
||||
# differently, which is the whole reason `readonly_cause` exists.
|
||||
writable=False,
|
||||
readonly_cause="platform_incomplete",
|
||||
writable=not read_only,
|
||||
readonly_cause="browsing" if read_only else None,
|
||||
cues=CueCapabilities(
|
||||
editable=False,
|
||||
editable=True,
|
||||
hotcue_slots=HOTCUE_SLOTS,
|
||||
slot_labels="letter",
|
||||
# OneLibrary carries memory cues, as Rekordbox does. They are
|
||||
# projected and preserved; nothing here is editable anyway.
|
||||
# OneLibrary carries memory cues, as Rekordbox does: projected and
|
||||
# preserved, NOT editable (the two-platform rule, as in Rekordbox).
|
||||
memory_cues=True,
|
||||
max_memory_cues=None,
|
||||
types=["cue", "loop"],
|
||||
color="free", # PCO2 stores RGB per cue, not a palette index
|
||||
palette=[],
|
||||
types=WRITABLE_CUE_TYPES,
|
||||
color="palette",
|
||||
palette=[palette.hex_for(code) for code in palette.SWATCHES],
|
||||
named=True, # PCO2 carries a per-cue comment
|
||||
loops="cue_type",
|
||||
),
|
||||
# The grid is the ANLZ `PQTZ` tag, per beat, and multi-tempo grids do
|
||||
# survive an export — so the format is flexible even though Konduktor
|
||||
# does not write it here.
|
||||
grid=GridCapabilities(editable=False, flexible=True, lockable=False),
|
||||
# The grid is the ANLZ `PQTZ` tag, per beat; multi-tempo grids survive.
|
||||
# No per-track grid lock exists in the format.
|
||||
grid=GridCapabilities(editable=True, flexible=True, lockable=False),
|
||||
tracks=TrackCapabilities(
|
||||
rating_max=5, # stored 0-5 directly, as in master.db
|
||||
editable_fields=[],
|
||||
# The Rekordbox adapter's set: `producer`/`mix` have no column.
|
||||
editable_fields=sorted(editable_fields or []),
|
||||
media_kinds=["audio", "stem"],
|
||||
# `artwork` gates EDITING, and a drive is read-only here. Reading
|
||||
# works: `store.cover_art` follows `content.image_id` -> `image.path`.
|
||||
# A stick's audio belongs to its library: added files are copied onto
|
||||
# it (laid out as rekordbox does) and a removed track's file goes
|
||||
# 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
|
||||
# `content.image_id` -> `image.path`.
|
||||
artwork=False,
|
||||
artwork_note=None,
|
||||
),
|
||||
@@ -80,13 +97,18 @@ def capabilities_for(device_name: str | None = None, version: str | None = None)
|
||||
# A drive carries no smart playlists: rekordbox resolves them to
|
||||
# static lists on export, because a CDJ cannot evaluate rules.
|
||||
smart="none",
|
||||
reorder=False,
|
||||
reorder=True,
|
||||
),
|
||||
save=SaveCapabilities(
|
||||
app_name="OneLibrary",
|
||||
library_label=device_name or "exportLibrary.db",
|
||||
# Nothing is written, so nothing can be overwritten by another app.
|
||||
# Named for the DRIVE ("Save to Goober"): a person has several
|
||||
# sticks, and "Save to OneLibrary" would not say which.
|
||||
app_name=device_name or "OneLibrary",
|
||||
library_label="exportLibrary.db",
|
||||
# Another app writing the drive between open and save is CAUGHT,
|
||||
# not risked: the store fingerprints the database at open and
|
||||
# refuses to save over a change it did not make.
|
||||
overwrite_risk="none",
|
||||
managed_by_export=managed_by_export,
|
||||
# A drive is a database plus N analysis files plus the audio itself,
|
||||
# so there is no single blob that IS the library — the same reason
|
||||
# Rekordbox libraries are not versioned.
|
||||
|
||||
@@ -37,6 +37,7 @@ from __future__ import annotations
|
||||
import logging
|
||||
|
||||
from ...core.model import CuePoint
|
||||
from ..rekordbox import palette
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
@@ -47,14 +48,13 @@ NO_LOOP = 0xFFFFFFFF
|
||||
# `hot_cue` for a cue that sits in no pad bank, i.e. a memory cue.
|
||||
MEMORY_SLOT = 0
|
||||
|
||||
# PCO2/PCOB entry kinds. The value is the same in both tags; PCOB exposes it as
|
||||
# a construct enum and PCO2 as a plain int, so both are normalised to an int.
|
||||
# PCO2/PCOB entry kinds. The value is the same in both tags.
|
||||
ENTRY_CUE = 1
|
||||
ENTRY_LOOP = 2
|
||||
|
||||
|
||||
def _entry_kind(value) -> int:
|
||||
"""PCOB gives an enum, PCO2 an int — one number out of either."""
|
||||
"""An entry's kind as an int, defaulting to a point cue if unreadable."""
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
@@ -68,8 +68,17 @@ def _color(entry) -> str | None:
|
||||
real black in principle, but rekordbox uses it as "unset" and shows such a
|
||||
cue in the default colour, so it is reported as no colour rather than as
|
||||
black. Memory cues in the reference export are exactly this case.
|
||||
|
||||
rekordbox DRAWS a cue from its palette CODE (`rekordbox.palette`), so a known
|
||||
code is reported as that swatch; a cue with code 0 and an RGB (older
|
||||
exports, the reference fixture) is reported by its RGB.
|
||||
"""
|
||||
swatch = palette.hex_for(getattr(entry, "color_code", None))
|
||||
if swatch is not None:
|
||||
return swatch
|
||||
try:
|
||||
# None on an entry too short to carry a colour: every PCPT, and the
|
||||
# compact 44-byte PCP2 rekordbox writes for a memory cue it added.
|
||||
r, g, b = int(entry.color_red), int(entry.color_green), int(entry.color_blue)
|
||||
except (AttributeError, TypeError, ValueError):
|
||||
return None
|
||||
@@ -78,7 +87,7 @@ def _color(entry) -> str | None:
|
||||
return f"#{r:02X}{g:02X}{b:02X}"
|
||||
|
||||
|
||||
def _to_cue(entry, *, with_color: bool) -> CuePoint | None:
|
||||
def _to_cue(entry, *, with_color: bool, editable: bool = False) -> CuePoint | None:
|
||||
"""One ANLZ cue entry as a generic `CuePoint`, or None if unreadable."""
|
||||
try:
|
||||
hot_cue = int(entry.hot_cue)
|
||||
@@ -111,11 +120,11 @@ def _to_cue(entry, *, with_color: bool) -> CuePoint | None:
|
||||
length=length,
|
||||
slot=slot,
|
||||
color=_color(entry) if with_color else None,
|
||||
# A OneLibrary drive is read-only in Konduktor, so no cue accepts a
|
||||
# command. `capabilities.writable` is what the UI actually gates on;
|
||||
# this keeps the per-cue answer consistent with it.
|
||||
editable=False,
|
||||
readonly_reason="platform_managed",
|
||||
# Hot cues are editable on a drive opened for editing (the caller says
|
||||
# so). MEMORY cues never are — preserved-but-uneditable, as in the
|
||||
# Rekordbox adapter (the two-platform rule).
|
||||
editable=editable and role == "hotcue",
|
||||
readonly_reason=None if editable and role == "hotcue" else "platform_managed",
|
||||
grid_marker=None,
|
||||
)
|
||||
|
||||
@@ -130,15 +139,14 @@ def _entries(anlz, tag_type: str) -> list:
|
||||
"""
|
||||
out: list = []
|
||||
for tag in getattr(anlz, "tags", []):
|
||||
if tag.type != tag_type:
|
||||
continue
|
||||
content = getattr(tag.struct, "content", None)
|
||||
out.extend(getattr(content, "entries", None) or [])
|
||||
if tag.type == tag_type:
|
||||
out.extend(tag.entries)
|
||||
return out
|
||||
|
||||
|
||||
def cues_from_anlz(dat, ext) -> list[CuePoint]:
|
||||
"""The track's complete cue list, from its parsed `.DAT` and `.EXT`.
|
||||
def cues_from_anlz(dat, ext, *, editable: bool = False) -> list[CuePoint]:
|
||||
"""The track's complete cue list, from its parsed `.DAT` and `.EXT`
|
||||
(`rekordbox.anlz_file.AnlzFile`s).
|
||||
|
||||
Either may be None — a drive can carry a `.DAT` with no `.EXT` — and a track
|
||||
with no cues at all yields an empty list rather than an error.
|
||||
@@ -153,14 +161,14 @@ def cues_from_anlz(dat, ext) -> list[CuePoint]:
|
||||
for f in files:
|
||||
pco2.extend(_entries(f, "PCO2"))
|
||||
if pco2:
|
||||
cues = [c for e in pco2 if (c := _to_cue(e, with_color=True)) is not None]
|
||||
cues = [c for e in pco2 if (c := _to_cue(e, with_color=True, editable=editable)) is not None]
|
||||
else:
|
||||
# Fallback: merge PCOB across BOTH files. The .DAT holds pads 1-3 and the
|
||||
# .EXT the rest, so either alone is an incomplete bank.
|
||||
pcob: list = []
|
||||
for f in files:
|
||||
pcob.extend(_entries(f, "PCOB"))
|
||||
cues = [c for e in pcob if (c := _to_cue(e, with_color=False)) is not None]
|
||||
cues = [c for e in pcob if (c := _to_cue(e, with_color=False, editable=editable)) is not None]
|
||||
|
||||
return _dedupe(cues)
|
||||
|
||||
@@ -168,18 +176,23 @@ def cues_from_anlz(dat, ext) -> list[CuePoint]:
|
||||
def _dedupe(cues: list[CuePoint]) -> list[CuePoint]:
|
||||
"""Collapse the same cue appearing in more than one tag or file.
|
||||
|
||||
Identity is (role, slot, start) rather than the whole cue: the same pad can
|
||||
be described by both `PCOB` and `PCO2`, and by both files, and those copies
|
||||
agree on position while differing in how much detail they carry. The first
|
||||
one wins, which — given PCO2 is read first — is the richest.
|
||||
Identity is (role, slot, start, type, length) rather than the whole cue:
|
||||
the same pad can be described by both `PCOB` and `PCO2`, and by both files,
|
||||
and those copies agree on all five while differing in how much detail they
|
||||
carry (colour, comment). The first one wins, which — given PCO2 is read
|
||||
first — is the richest.
|
||||
|
||||
Type and length are part of it because two MEMORY cues may share a position:
|
||||
rekordbox happily stores a memory cue on the start of a memory loop (seen on
|
||||
Goober), and keying on position alone silently dropped the loop.
|
||||
|
||||
Ordered by position, then by slot, so the projection is stable across reads
|
||||
regardless of the order the tags happened to store.
|
||||
"""
|
||||
seen: set[tuple[str, int | None, int]] = set()
|
||||
seen: set[tuple] = set()
|
||||
out: list[CuePoint] = []
|
||||
for c in cues:
|
||||
key = (c.role, c.slot, round(c.start * 1000))
|
||||
key = (c.role, c.slot, round(c.start * 1000), c.type, round(c.length * 1000))
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
"""Keeping a stick's legacy Device Library (`export.pdb`) in step with its OneLibrary.
|
||||
|
||||
Most rekordbox sticks carry BOTH: `exportLibrary.db` (OneLibrary, newer players)
|
||||
and `export.pdb` (the Device Library, older players and rekordbox's own "Device
|
||||
Library" view). Cues and the grid live in the analysis files both share, so they
|
||||
follow an edit by themselves; titles and playlists live in each database
|
||||
separately. **rekordbox itself lets them drift**: measured on Goober
|
||||
(2026-10-01), its edits updated the pdb's track metadata but not a new playlist
|
||||
or a reorder. Konduktor rebuilds the pdb at Save instead (decision 2 of the
|
||||
editing discussion), so a stick never shows different playlists depending on
|
||||
which player reads it.
|
||||
|
||||
**Ids are mirrored, not assigned.** rekordbox exports both libraries from the
|
||||
same ids — pdb track id = `content_id`, the artist/album/genre/label/key ids, the
|
||||
playlist ids, playlist `sort` = `sequenceNo`, entries `(sequenceNo, content_id,
|
||||
playlist_id)`, artwork id = `image_id` — all checked on Goober. So the OneLibrary
|
||||
database IS the answer for every row the pdb shares with it.
|
||||
|
||||
**An edit, not a regeneration.** The stick's own `export.pdb` is edited in place
|
||||
(`pdb.PdbEditor`): only the tracks, the lookup tables (artist, album, genre,
|
||||
label, key), artwork and the playlist tree and entries are candidates, a table is rewritten only if one of its rows changed,
|
||||
and an unchanged row keeps rekordbox's bytes. A changed TRACK row is the old row
|
||||
with the edited fields overwritten, so everything the pdb holds that OneLibrary
|
||||
does not — the phrase-analysis strings, the `masterDbId` halves, play counts,
|
||||
dates — survives. History, colours, menus and `exportExt.pdb` are never touched.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import struct
|
||||
from pathlib import Path
|
||||
|
||||
from ..rekordbox import pdb
|
||||
|
||||
#: Tables this rebuild owns. Everything else in the file is left as it is.
|
||||
_OWNED = (pdb.TRACKS, pdb.ARTISTS, pdb.ALBUMS, pdb.GENRES, pdb.LABELS, pdb.KEYS,
|
||||
pdb.ARTWORK, pdb.PLAYLIST_TREE, pdb.PLAYLIST_ENTRIES)
|
||||
|
||||
|
||||
def _lookup_name(table: int, row: bytes) -> str:
|
||||
if table == pdb.ARTISTS:
|
||||
sub, _shift, _rid, _b, ofs = struct.unpack_from("<HHIBB", row, 0)
|
||||
if sub == 0x64:
|
||||
ofs = struct.unpack_from("<H", row, 10)[0]
|
||||
return pdb.read_dsql(row, ofs)
|
||||
if table == pdb.ALBUMS:
|
||||
sub, _shift, _u, _artist, _rid, _u3, _b, ofs = struct.unpack_from("<HHIIIIBB", row, 0)
|
||||
return pdb.read_dsql(row, ofs)
|
||||
if table == pdb.KEYS:
|
||||
return pdb.read_dsql(row, 8)
|
||||
return pdb.read_dsql(row, 4)
|
||||
|
||||
|
||||
def _pdb_art_path(path: str | None) -> str:
|
||||
"""OneLibrary's `image.path` names the `b<n>` file; export.pdb's artwork row
|
||||
the byte-identical `a<n>` beside it (as on Goober, and as rekordbox writes)."""
|
||||
return re.sub(r"/b(\d+)(\.jpg)$", r"/a\1\2", path or "")
|
||||
|
||||
|
||||
def _tree_value(row: bytes) -> tuple:
|
||||
parent, _u, sort, rid, folder = struct.unpack_from("<5I", row, 0)
|
||||
return parent, sort, rid, bool(folder), pdb.read_dsql(row, 20)
|
||||
|
||||
|
||||
def _merge(old: list[bytes], new: dict, table: int, same) -> list[bytes] | None:
|
||||
"""The table's rows: old ORDER kept, an unchanged row's old BYTES kept, new
|
||||
rows appended by id. None when nothing changed (the table is not rewritten).
|
||||
|
||||
`new` maps row id -> (value, encode()); `same(old_row, value)` says whether
|
||||
an old row already says `value`.
|
||||
"""
|
||||
out, changed, seen = [], False, set()
|
||||
for row in old:
|
||||
rid = pdb.row_id(table, row)
|
||||
if rid not in new:
|
||||
changed = True # removed
|
||||
continue
|
||||
seen.add(rid)
|
||||
value, encode = new[rid]
|
||||
if same(row, value):
|
||||
out.append(row)
|
||||
else:
|
||||
out.append(encode())
|
||||
changed = True
|
||||
for rid in sorted((r for r in new if r not in seen), key=str):
|
||||
out.append(new[rid][1]())
|
||||
changed = True
|
||||
return out if changed else None
|
||||
|
||||
|
||||
def rebuild(existing: bytes, session) -> bytes | None:
|
||||
"""`export.pdb` edited to match the OneLibrary database open in `session`
|
||||
(the working copy, edits committed); None if it already matches."""
|
||||
from sqlalchemy import text
|
||||
|
||||
tables: dict[int, list[bytes]] = {}
|
||||
|
||||
# ---- lookups ----------------------------------------------------------------
|
||||
for table, sql, build in (
|
||||
(pdb.ARTISTS, "SELECT artist_id, name FROM artist", pdb.artist_row),
|
||||
# rekordbox's export leaves an album's artist 0 (see `pdb.album_row`).
|
||||
(pdb.ALBUMS, "SELECT album_id, name FROM album", pdb.album_row),
|
||||
(pdb.GENRES, "SELECT genre_id, name FROM genre", pdb.id_string_row),
|
||||
(pdb.LABELS, "SELECT label_id, name FROM label", pdb.id_string_row),
|
||||
(pdb.KEYS, "SELECT key_id, name FROM key", pdb.key_row),
|
||||
):
|
||||
want = {int(i): (name or "", (lambda i=i, n=name, b=build: b(int(i), n or "")))
|
||||
for i, name in session.execute(text(sql))}
|
||||
merged = _merge(pdb.table_rows(existing, table), want, table,
|
||||
lambda row, value, t=table: _lookup_name(t, row) == value)
|
||||
if merged is not None:
|
||||
tables[table] = merged
|
||||
|
||||
want = {int(i): (_pdb_art_path(path), (lambda i=i, p=path: pdb.id_string_row(int(i), _pdb_art_path(p))))
|
||||
for i, path in session.execute(text("SELECT image_id, path FROM image"))}
|
||||
merged = _merge(pdb.table_rows(existing, pdb.ARTWORK), want, pdb.ARTWORK,
|
||||
lambda row, value: pdb.read_dsql(row, 4) == value)
|
||||
if merged is not None:
|
||||
tables[pdb.ARTWORK] = merged
|
||||
|
||||
# ---- tracks -----------------------------------------------------------------
|
||||
old_tracks = {pdb.row_id(pdb.TRACKS, r): r for r in pdb.table_rows(existing, pdb.TRACKS)}
|
||||
want = {}
|
||||
for (cid, title, artist, remixer, album, genre, label, rating, bpm, year, released,
|
||||
comment, *fresh) in session.execute(text(
|
||||
"SELECT content_id, title, artist_id_artist, artist_id_remixer, album_id, genre_id, "
|
||||
"label_id, rating, bpmx100, releaseYear, releaseDate, djComment, "
|
||||
"path, fileName, fileSize, fileType, bitrate, bitDepth, samplingRate, length, "
|
||||
"analysisDataFilePath, dateAdded, key_id, image_id FROM content")):
|
||||
cid = int(cid)
|
||||
if cid in old_tracks:
|
||||
fields, strings = pdb.track_fields(old_tracks[cid])
|
||||
else:
|
||||
fields, strings = _fresh_track(cid, *fresh)
|
||||
fields = {**fields, "artist_id": artist or 0, "remixer_id": remixer or 0,
|
||||
"album_id": album or 0, "genre_id": genre or 0, "label_id": label or 0,
|
||||
"rating": max(0, min(5, int(rating or 0))), "tempo": int(bpm or 0),
|
||||
"year": int(year or 0)}
|
||||
strings = {**strings, "title": title or "", "comment": comment or "",
|
||||
"release_date": released or ""}
|
||||
want[cid] = ((fields, strings),
|
||||
(lambda f=fields, s=strings: pdb.track_row(f, s)))
|
||||
merged = _merge(list(old_tracks.values()), want, pdb.TRACKS,
|
||||
lambda row, value: _same_track(pdb.track_fields(row), value))
|
||||
if merged is not None:
|
||||
tables[pdb.TRACKS] = merged
|
||||
|
||||
# ---- playlists ----------------------------------------------------------------
|
||||
want = {int(pid): ((int(parent or 0), int(seq or 0), int(pid), int(attr or 0) == 1, name or ""),
|
||||
(lambda p=pid, par=parent, s=seq, n=name, a=attr:
|
||||
pdb.playlist_tree_row(int(p), int(par or 0), int(s or 0), n or "",
|
||||
folder=int(a or 0) == 1)))
|
||||
for pid, parent, seq, name, attr in session.execute(text(
|
||||
"SELECT playlist_id, playlist_id_parent, sequenceNo, name, attribute FROM playlist"))}
|
||||
merged = _merge(pdb.table_rows(existing, pdb.PLAYLIST_TREE), want, pdb.PLAYLIST_TREE,
|
||||
lambda row, value: _tree_value(row) == value)
|
||||
if merged is not None:
|
||||
tables[pdb.PLAYLIST_TREE] = merged
|
||||
|
||||
want = {}
|
||||
for pid, cid, seq in session.execute(text(
|
||||
"SELECT playlist_id, content_id, sequenceNo FROM playlist_content "
|
||||
"ORDER BY playlist_id, sequenceNo")):
|
||||
key = (int(seq), int(cid), int(pid))
|
||||
want[key] = (key, (lambda k=key: pdb.playlist_entry_row(*k)))
|
||||
merged = _merge(pdb.table_rows(existing, pdb.PLAYLIST_ENTRIES), want, pdb.PLAYLIST_ENTRIES,
|
||||
lambda row, value: True)
|
||||
if merged is not None:
|
||||
tables[pdb.PLAYLIST_ENTRIES] = merged
|
||||
|
||||
if not tables:
|
||||
return None
|
||||
editor = pdb.PdbEditor(existing)
|
||||
for table in _OWNED:
|
||||
if table in tables:
|
||||
editor.refill(table, tables[table])
|
||||
return editor.render()
|
||||
|
||||
|
||||
def _same_track(old: tuple[dict, dict], new: tuple[dict, dict]) -> bool:
|
||||
"""Equal in every field that means something: `index_shift` is the row's slot
|
||||
in its page, re-stamped whenever a page is written."""
|
||||
(of, os_), (nf, ns) = old, new
|
||||
return ({k: v for k, v in of.items() if k != "index_shift"}
|
||||
== {k: v for k, v in nf.items() if k != "index_shift"} and os_ == ns)
|
||||
|
||||
|
||||
def _fresh_track(cid: int, path, file_name, file_size, file_type, bitrate, bit_depth,
|
||||
sample_rate, length, analysis, date_added, key_id, image_id) -> tuple[dict, dict]:
|
||||
"""A track the pdb has never listed (one added to the stick by Konduktor), in
|
||||
the shape `device_export` writes one — the values a rekordbox device export
|
||||
was measured to carry (see that module)."""
|
||||
from ..rekordbox.device_export import ANALYSED, BITMASK
|
||||
|
||||
added = str(date_added or "")[:10]
|
||||
fields = {
|
||||
"subtype": 0x24, "bitmask": BITMASK, "sample_rate": int(sample_rate or 0),
|
||||
"file_size": int(file_size or 0), "u2": cid + 0x600, "artwork_id": int(image_id or 0),
|
||||
"key_id": int(key_id or 0), "bitrate": int(bitrate or 0), "id": cid,
|
||||
"sample_depth": int(bit_depth or 0), "duration": min(int(length or 0), 0xFFFF),
|
||||
"u5": ANALYSED, "u6": int(file_type or 0), "u7": 3,
|
||||
}
|
||||
strings = {
|
||||
"kuvo_public": "ON", "autoload_hotcues": "ON", "date_added": added,
|
||||
"analyze_path": analysis or "", "analyze_date": added,
|
||||
"filename": file_name or Path(str(path or "")).name, "file_path": path or "",
|
||||
}
|
||||
return fields, strings
|
||||
@@ -73,8 +73,8 @@ class OneLibraryDriver:
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
def open(self, path: Path) -> OneLibraryAdapter:
|
||||
return OneLibraryAdapter(path)
|
||||
def open(self, path: Path, *, read_only: bool = False) -> OneLibraryAdapter:
|
||||
return OneLibraryAdapter(path, read_only=read_only)
|
||||
|
||||
def detect(self) -> list[dict]:
|
||||
return discovery.detect_libraries()
|
||||
|
||||
@@ -265,21 +265,21 @@ class OneLibraryExporter:
|
||||
n = counter["next"]
|
||||
folder = root / "PIONEER" / "Artwork" / "00001"
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
small, medium = jpegs
|
||||
files = []
|
||||
for letter in ("a", "b"):
|
||||
for suffix, data in (("", small), ("_m", medium)):
|
||||
path = folder / f"{letter}{n}{suffix}.jpg"
|
||||
path.write_bytes(data)
|
||||
files.append(path)
|
||||
for rel, data in art_files(n, jpegs):
|
||||
path = root / rel.lstrip("/")
|
||||
path.write_bytes(data)
|
||||
files.append(path)
|
||||
con.execute("INSERT INTO image (image_id, path) VALUES (?, ?)",
|
||||
(n, f"/PIONEER/Artwork/00001/b{n}.jpg"))
|
||||
return n, files
|
||||
|
||||
# ---- the analysis files --------------------------------------------------
|
||||
|
||||
def _write_anlz(self, item: ExportTrack, rel: str, dat: Path) -> list[Path]:
|
||||
"""The `.DAT`, `.EXT` and `.2EX`, as rekordbox 7 writes them.
|
||||
def anlz_files(self, item: ExportTrack, rel: str) -> list[tuple[str, bytes]]:
|
||||
"""The `.DAT`, `.EXT` and `.2EX` as `(suffix, bytes)`, as rekordbox 7 writes
|
||||
them — built, not written, so a library adding a track to a stick can hold
|
||||
them until Save (`OneLibraryStore.add_track`).
|
||||
|
||||
All three, and every cue list, even for a track with no cues: rekordbox
|
||||
never produces a track without them, and `PCO2` — the complete list,
|
||||
@@ -318,9 +318,18 @@ class OneLibraryExporter:
|
||||
tags += previews
|
||||
tags += W.cue_tags(cues, extended=False)
|
||||
ext = [W.path_tag(rel), *ext_waves[:1], *W.cue_tags(cues, extended=True), *ext_waves[1:]]
|
||||
written = [W.write_anlz(dat, tags), W.write_anlz(dat.with_suffix(".EXT"), ext)]
|
||||
files = [(".DAT", W.anlz_bytes(tags)), (".EXT", W.anlz_bytes(ext))]
|
||||
if two_ex:
|
||||
written.append(W.write_anlz(dat.with_suffix(".2EX"), [W.path_tag(rel), *two_ex]))
|
||||
files.append((".2EX", W.anlz_bytes([W.path_tag(rel), *two_ex])))
|
||||
return files
|
||||
|
||||
def _write_anlz(self, item: ExportTrack, rel: str, dat: Path) -> list[Path]:
|
||||
written = []
|
||||
for suffix, data in self.anlz_files(item, rel):
|
||||
path = dat.with_suffix(suffix)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(data)
|
||||
written.append(path)
|
||||
return written
|
||||
|
||||
@staticmethod
|
||||
@@ -424,6 +433,15 @@ _FILE_TYPES = {".mp3": 1, ".m4a": 4, ".mp4": 4, ".aac": 4, ".flac": 5, ".wav": 1
|
||||
".aif": 12, ".aiff": 12}
|
||||
|
||||
|
||||
def art_files(n: int, jpegs: tuple[bytes, bytes]) -> list[tuple[str, bytes]]:
|
||||
"""Image `n`'s four files as `(drive-relative path, bytes)`: `a<n>`/`b<n>`
|
||||
and their `_m`, byte-identical pairs, in `Artwork/00001/` (see `_write_art`).
|
||||
`image.path` names the `b` file; `export.pdb`'s artwork table the `a` one."""
|
||||
small, medium = jpegs
|
||||
return [(f"/PIONEER/Artwork/00001/{letter}{n}{suffix}.jpg", data)
|
||||
for letter in ("a", "b") for suffix, data in (("", small), ("_m", medium))]
|
||||
|
||||
|
||||
def _file_type(path: Path) -> int:
|
||||
return _FILE_TYPES.get(path.suffix.lower(), 1)
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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
|
||||
|
||||
|
||||
@@ -171,6 +172,7 @@ class RekordboxAdapter:
|
||||
can_rename=writable,
|
||||
can_delete=writable,
|
||||
can_contain_children=kind == "folder",
|
||||
can_move=writable,
|
||||
)
|
||||
parent = str(r.ParentID or "root")
|
||||
parents[node_id] = "root" if parent in ("0", "", "root", "None") else parent
|
||||
@@ -202,6 +204,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 +220,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 +254,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")
|
||||
@@ -262,6 +277,10 @@ class RekordboxAdapter:
|
||||
self._require_writable("Deleting playlists")
|
||||
self._store.delete_playlist(node_id)
|
||||
|
||||
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
|
||||
self._require_writable("Moving playlists")
|
||||
return self._store.move_playlist(node_id, parent_id, index)
|
||||
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
|
||||
self._require_writable("Editing playlists")
|
||||
return self._store.set_playlist_entries(node_id, track_ids)
|
||||
@@ -382,6 +401,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 +441,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 +470,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 +486,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:
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
"""Reading an ANLZ analysis file at the TAG level, by hand.
|
||||
|
||||
The writer half is `anlz_writer`; this is its reader. Like the writer it lives
|
||||
here because the format is Pioneer's, not one product's.
|
||||
|
||||
**Why not `pyrekordbox`'s parser.** It decodes a cue entry with a FIXED layout,
|
||||
and rekordbox does not write one. An exported entry is 88 bytes, but when
|
||||
rekordbox 7 EDITS a stick it writes compact ones (measured on Goober,
|
||||
2026-10-01): a hot cue added in rekordbox was a 48-byte `PCP2` (colour, no
|
||||
padding), and a memory cue a 44-byte one (no colour bytes at all). pyrekordbox
|
||||
raises `PaddingError` on the 44-byte form, the whole `.EXT` fails to parse, and
|
||||
a reader that falls back to the `.DAT` silently loses pads D-H and every colour.
|
||||
So every entry here is read at its own `len_entry`, and a field the entry is too
|
||||
short to hold is simply absent.
|
||||
|
||||
A file is also split into its RAW tags, kept byte for byte. Editing a stick
|
||||
replaces one or two tags of a file rekordbox wrote; everything else (the
|
||||
waveforms, `PVBR`, tags nobody has decoded) must go back exactly as it was, and
|
||||
re-serialising through a parser is how bytes get lost.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import struct
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
#: `PMAI` · len_header · len_file · …
|
||||
FILE_MAGIC = b"PMAI"
|
||||
NO_LOOP = 0xFFFFFFFF
|
||||
|
||||
#: The cue-list kinds in `PCOB`/`PCO2`'s own header.
|
||||
LIST_MEMORY = 0
|
||||
LIST_HOT = 1
|
||||
|
||||
|
||||
@dataclass
|
||||
class Tag:
|
||||
"""One tag, raw. `data` is the WHOLE tag: magic, both lengths, and body."""
|
||||
|
||||
type: str
|
||||
data: bytes
|
||||
_entries: list | None = field(default=None, repr=False, compare=False)
|
||||
|
||||
@property
|
||||
def len_header(self) -> int:
|
||||
return struct.unpack_from(">I", self.data, 4)[0]
|
||||
|
||||
@property
|
||||
def list_kind(self) -> int | None:
|
||||
"""`PCOB`/`PCO2`: whether this is the hot cue or the memory list."""
|
||||
if self.type in ("PCOB", "PCO2") and len(self.data) >= 16:
|
||||
return struct.unpack_from(">I", self.data, 12)[0]
|
||||
return None
|
||||
|
||||
@property
|
||||
def entries(self) -> list:
|
||||
"""The tag's decoded entries (cues, or beats for `PQTZ`); [] otherwise."""
|
||||
if self._entries is None:
|
||||
decode = _DECODERS.get(self.type)
|
||||
self._entries = decode(self.data) if decode else []
|
||||
return self._entries
|
||||
|
||||
|
||||
@dataclass
|
||||
class AnlzFile:
|
||||
"""An analysis file split into its header and raw tags."""
|
||||
|
||||
header: bytes
|
||||
tags: list[Tag]
|
||||
|
||||
def to_bytes(self) -> bytes:
|
||||
"""Reassemble, fixing only the header's file length."""
|
||||
body = b"".join(t.data for t in self.tags)
|
||||
head = bytearray(self.header)
|
||||
struct.pack_into(">I", head, 8, len(head) + len(body))
|
||||
return bytes(head) + body
|
||||
|
||||
def copy(self) -> "AnlzFile":
|
||||
return AnlzFile(self.header, [Tag(t.type, t.data) for t in self.tags])
|
||||
|
||||
def find(self, kind: str, list_kind: int | None = None) -> int | None:
|
||||
"""Index of the first `kind` tag (of that cue-list kind, if given)."""
|
||||
for i, t in enumerate(self.tags):
|
||||
if t.type == kind and (list_kind is None or t.list_kind == list_kind):
|
||||
return i
|
||||
return None
|
||||
|
||||
def put(self, kind: str, data: bytes, *, list_kind: int | None = None,
|
||||
after: tuple[str, ...] = ()) -> None:
|
||||
"""Replace the `kind` tag IN PLACE, keeping every other tag where it is.
|
||||
|
||||
A file without one gets it inserted after the last tag named in
|
||||
`after` (rekordbox's order), else at the end.
|
||||
"""
|
||||
tag = Tag(kind, data)
|
||||
i = self.find(kind, list_kind)
|
||||
if i is not None:
|
||||
self.tags[i] = tag
|
||||
return
|
||||
at = max((j for j, t in enumerate(self.tags) if t.type in after), default=len(self.tags) - 1)
|
||||
self.tags.insert(at + 1, tag)
|
||||
|
||||
|
||||
class AnlzError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def parse(data: bytes) -> AnlzFile:
|
||||
"""Split a file into its tags. Raises `AnlzError` on a malformed file.
|
||||
|
||||
Lengths are trusted only as far as the file reaches: a tag claiming more
|
||||
bytes than remain ends the walk with an error rather than a short read.
|
||||
"""
|
||||
if len(data) < 12 or data[:4] != FILE_MAGIC:
|
||||
raise AnlzError("not an ANLZ file")
|
||||
len_header = struct.unpack_from(">I", data, 4)[0]
|
||||
if not 12 <= len_header <= len(data):
|
||||
raise AnlzError(f"bad file header length {len_header}")
|
||||
tags: list[Tag] = []
|
||||
off = len_header
|
||||
while off < len(data):
|
||||
if off + 12 > len(data):
|
||||
raise AnlzError(f"truncated tag at {off}")
|
||||
kind = data[off:off + 4].decode("latin-1")
|
||||
len_tag = struct.unpack_from(">I", data, off + 8)[0]
|
||||
if len_tag < 12 or off + len_tag > len(data):
|
||||
raise AnlzError(f"bad length {len_tag} for {kind} at {off}")
|
||||
tags.append(Tag(kind, data[off:off + len_tag]))
|
||||
off += len_tag
|
||||
return AnlzFile(header=data[:len_header], tags=tags)
|
||||
|
||||
|
||||
def parse_file(path) -> AnlzFile:
|
||||
with open(path, "rb") as f:
|
||||
return parse(f.read())
|
||||
|
||||
|
||||
# ---- cue entries ------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass
|
||||
class CueEntry:
|
||||
"""One `PCPT` or `PCP2` entry. Attribute names follow pyrekordbox's, which
|
||||
is what `onelibrary.cues` was written against.
|
||||
|
||||
`color_code` / RGB are None when the entry is too short to carry them (every
|
||||
`PCPT`, and rekordbox's compact 44-byte `PCP2`).
|
||||
"""
|
||||
|
||||
hot_cue: int
|
||||
type: int
|
||||
time: int
|
||||
loop_time: int
|
||||
comment: str = ""
|
||||
loop_numerator: int = 0
|
||||
loop_denominator: int = 0
|
||||
color_code: int | None = None
|
||||
color_red: int | None = None
|
||||
color_green: int | None = None
|
||||
color_blue: int | None = None
|
||||
len_entry: int = 0
|
||||
|
||||
|
||||
def raw_entries(tag: Tag) -> list[bytes]:
|
||||
"""A `PCOB`/`PCO2` tag's entries as their own bytes, each at its own length —
|
||||
so an entry Konduktor does not change goes back exactly as rekordbox wrote it."""
|
||||
if tag.type == "PCOB":
|
||||
count, first, magic = struct.unpack_from(">H", tag.data, 18)[0], 24, b"PCPT"
|
||||
elif tag.type == "PCO2":
|
||||
count, first, magic = struct.unpack_from(">H", tag.data, 16)[0], 20, b"PCP2"
|
||||
else:
|
||||
return []
|
||||
return [tag.data[off:off + n] for off, n in _walk(tag.data, first, magic, count)]
|
||||
|
||||
|
||||
def decode_entry(entry: bytes) -> CueEntry:
|
||||
"""One raw `PCPT` or `PCP2` entry, decoded."""
|
||||
if entry[:4] == b"PCPT":
|
||||
return _pcob(struct.pack(">4sIIIHHi", b"PCOB", 24, 24 + len(entry), 0, 0, 1, -1) + entry)[0]
|
||||
return _pco2(struct.pack(">4sIIIHH", b"PCO2", 20, 20 + len(entry), 0, 1, 0) + entry)[0]
|
||||
|
||||
|
||||
def entry_hot_cue(entry: bytes) -> int:
|
||||
"""A PCPT/PCP2 entry's `hot_cue`: its pad, 1-based; 0 for a memory cue."""
|
||||
return struct.unpack_from(">I", entry, 12)[0]
|
||||
|
||||
|
||||
def entry_with_colour(entry: bytes, code: int, rgb: tuple[int, int, int]) -> bytes | None:
|
||||
"""A `PCP2` entry with ONLY its colour bytes changed — what rekordbox itself
|
||||
does to recolour a cue (measured: those 4 bytes and nothing else). None if
|
||||
the entry is too short to carry a colour (rekordbox's 44-byte form)."""
|
||||
if len(entry) < 44:
|
||||
return None
|
||||
len_comment = struct.unpack_from(">I", entry, 40)[0]
|
||||
at = 44 + len_comment
|
||||
if at + 4 > len(entry):
|
||||
return None
|
||||
return entry[:at] + bytes([code & 0xFF, *rgb]) + entry[at + 4:]
|
||||
|
||||
|
||||
def entry_without_loop_beats(entry: bytes) -> bytes:
|
||||
"""A `PCP2` entry with its loop length in beats cleared to 0/0 — what
|
||||
rekordbox does to every loop when the grid changes (measured: 32/1 -> 0/0),
|
||||
rather than recomputing it."""
|
||||
if len(entry) < 40 or entry[36:40] == b"\0\0\0\0":
|
||||
return entry
|
||||
return entry[:36] + bytes(4) + entry[40:]
|
||||
|
||||
|
||||
def _walk(data: bytes, first: int, magic: bytes, count: int):
|
||||
"""(offset, len_entry) for each entry, trusting each entry's own length."""
|
||||
off = first
|
||||
for _ in range(count):
|
||||
if off + 12 > len(data) or data[off:off + 4] != magic:
|
||||
return
|
||||
len_entry = struct.unpack_from(">I", data, off + 8)[0]
|
||||
if len_entry < 12 or off + len_entry > len(data):
|
||||
return
|
||||
yield off, len_entry
|
||||
off += len_entry
|
||||
|
||||
|
||||
def _pcob(data: bytes) -> list[CueEntry]:
|
||||
# tag prefix(12) · I list kind · H 0 · H count · i last
|
||||
count = struct.unpack_from(">H", data, 18)[0]
|
||||
out = []
|
||||
for off, n in _walk(data, 24, b"PCPT", count):
|
||||
if n < 44:
|
||||
continue
|
||||
# 4s · I len_header · I len_entry · I hot_cue · I status · I 0x10000 ·
|
||||
# H order_first · H order_last · B kind · x · H 1000 · I time · I loop
|
||||
hot_cue, = struct.unpack_from(">I", data, off + 12)
|
||||
kind = data[off + 28]
|
||||
time, loop = struct.unpack_from(">II", data, off + 32)
|
||||
out.append(CueEntry(hot_cue=hot_cue, type=kind, time=time, loop_time=loop, len_entry=n))
|
||||
return out
|
||||
|
||||
|
||||
def _pco2(data: bytes) -> list[CueEntry]:
|
||||
# tag prefix(12) · I list kind · H count · H 0
|
||||
count = struct.unpack_from(">H", data, 16)[0]
|
||||
out = []
|
||||
for off, n in _walk(data, 20, b"PCP2", count):
|
||||
if n < 28:
|
||||
continue
|
||||
hot_cue, = struct.unpack_from(">I", data, off + 12)
|
||||
kind = data[off + 16]
|
||||
time, loop = struct.unpack_from(">II", data, off + 20)
|
||||
e = CueEntry(hot_cue=hot_cue, type=kind, time=time, loop_time=loop, len_entry=n)
|
||||
if n >= 44:
|
||||
e.loop_numerator, e.loop_denominator, len_comment = struct.unpack_from(">HHI", data, off + 36)
|
||||
colour_at = off + 44 + len_comment
|
||||
if len_comment and colour_at <= off + n:
|
||||
e.comment = data[off + 44:colour_at].decode("utf-16-be", "replace").rstrip("\x00")
|
||||
if colour_at + 4 <= off + n:
|
||||
e.color_code, e.color_red, e.color_green, e.color_blue = data[colour_at:colour_at + 4]
|
||||
out.append(e)
|
||||
return out
|
||||
|
||||
|
||||
# ---- the beatgrid -----------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass
|
||||
class Beat:
|
||||
beat: int # 1-4, position in the bar
|
||||
tempo: int # BPM x 100
|
||||
time: int # ms
|
||||
|
||||
|
||||
def _pqtz(data: bytes) -> list[Beat]:
|
||||
# tag prefix(12) · I 0 · I 0x80000 · I count, then 8-byte entries
|
||||
count = struct.unpack_from(">I", data, 20)[0]
|
||||
first = struct.unpack_from(">I", data, 4)[0]
|
||||
out = []
|
||||
for i in range(count):
|
||||
off = first + 8 * i
|
||||
if off + 8 > len(data):
|
||||
break
|
||||
beat, tempo, time = struct.unpack_from(">HHI", data, off)
|
||||
out.append(Beat(beat=beat, tempo=tempo, time=time))
|
||||
return out
|
||||
|
||||
|
||||
_DECODERS = {"PCOB": _pcob, "PCO2": _pco2, "PQTZ": _pqtz}
|
||||
|
||||
|
||||
__all__ = [
|
||||
"AnlzError", "AnlzFile", "Beat", "CueEntry", "LIST_HOT", "LIST_MEMORY",
|
||||
"NO_LOOP", "Tag", "decode_entry", "entry_hot_cue", "entry_with_colour", "entry_without_loop_beats",
|
||||
"parse", "parse_file", "raw_entries",
|
||||
]
|
||||
@@ -313,30 +313,38 @@ def flat_preview_tags() -> list[bytes]:
|
||||
return preview_tags([0.0] * 400, [0.0] * 400)
|
||||
|
||||
|
||||
def _pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
|
||||
rgb: tuple[int, int, int] | None, beats: int | None, code: int = 0) -> bytes:
|
||||
def pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
|
||||
rgb: tuple[int, int, int] | None, beats: int | None, code: int = 0,
|
||||
comment: str | None = None) -> bytes:
|
||||
"""One `PCP2` entry, byte-for-byte as rekordbox 7 writes it.
|
||||
|
||||
Two constants in here are rekordbox's, not the documented struct's: the
|
||||
`1000` after the kind (the struct calls it padding) and the `1` after the
|
||||
colour id. Both appear in every entry of a real export; zeros there were a
|
||||
guess, and pyrekordbox's parser would never notice one.
|
||||
|
||||
A `comment` (the cue's name) is UTF-16BE with a terminating NUL, and
|
||||
`len_comment` counts the terminator — crate-digger's layout, which both
|
||||
Konduktor's reader and pyrekordbox's agree with. No reference cue carries
|
||||
one, so that detail is documented rather than measured. The entry stays the
|
||||
exported 88 bytes unless the name needs more.
|
||||
"""
|
||||
comment = b""
|
||||
comment_bytes = (comment.encode("utf-16-be") + b"\0\0") if comment else b""
|
||||
red, green, blue = rgb or (0, 0, 0)
|
||||
length = max(PCP2_ENTRY_LEN, 48 + len(comment_bytes))
|
||||
return struct.pack(
|
||||
">4sIIIBxHIIBB6xHHI",
|
||||
b"PCP2", 16, PCP2_ENTRY_LEN, hot_cue, kind, 1000,
|
||||
b"PCP2", 16, length, hot_cue, kind, 1000,
|
||||
int(time_ms), NO_LOOP if loop_ms is None else int(loop_ms),
|
||||
0, 1, beats or 0, 1 if beats else 0, len(comment),
|
||||
0, 1, beats or 0, 1 if beats else 0, len(comment_bytes),
|
||||
# The colour is the palette CODE, then RGB: rekordbox draws from the code
|
||||
# (`palette`); a code of 0 draws its default colour whatever the RGB says.
|
||||
) + comment + struct.pack(">4B", code & 0xFF, red, green, blue) + bytes(
|
||||
PCP2_ENTRY_LEN - 48 - len(comment)
|
||||
) + comment_bytes + struct.pack(">4B", code & 0xFF, red, green, blue) + bytes(
|
||||
length - 48 - len(comment_bytes)
|
||||
)
|
||||
|
||||
|
||||
def _pcpt_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None) -> bytes:
|
||||
def pcpt_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None) -> bytes:
|
||||
"""One `PCPT` entry, byte-for-byte as rekordbox 7 writes it.
|
||||
|
||||
`len_header` is **28**, not 12: a reader that trusts it finds the body 16
|
||||
@@ -353,28 +361,54 @@ def _pcpt_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None) -
|
||||
) + bytes(16)
|
||||
|
||||
|
||||
def _pcob(cue_type: int, chosen: list[dict]) -> bytes:
|
||||
blob = b"".join(
|
||||
_pcpt_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
|
||||
loop_ms=c["loop_ms"])
|
||||
for c in chosen
|
||||
)
|
||||
def pcob_tag(cue_type: int, entries: list[bytes]) -> bytes:
|
||||
"""A `PCOB` around already-built `PCPT` entries (rekordbox's own, untouched,
|
||||
or new ones from `pcpt_entry`)."""
|
||||
# cue_type is Int32ub (an Enum over it), NOT Int16 — getting this wrong
|
||||
# shifts every following field and the reader sees garbage. The last field
|
||||
# is -1 on a hot-cue list and (count - 1) on a memory list, as rekordbox
|
||||
# writes it.
|
||||
last = -1 if cue_type == 1 else len(chosen) - 1
|
||||
return _wrap("PCOB", struct.pack(">IHHi", cue_type, 0, len(chosen), last) + blob)
|
||||
# writes it (an export, and rekordbox's own edits, alike).
|
||||
last = -1 if cue_type == 1 else len(entries) - 1
|
||||
return _wrap("PCOB", struct.pack(">IHHi", cue_type, 0, len(entries), last) + b"".join(entries))
|
||||
|
||||
|
||||
def pco2_tag(cue_type: int, entries: list[bytes]) -> bytes:
|
||||
"""A `PCO2` around already-built `PCP2` entries."""
|
||||
return _wrap("PCO2", struct.pack(">IHH", cue_type, len(entries), 0) + b"".join(entries))
|
||||
|
||||
|
||||
def _pcob(cue_type: int, chosen: list[dict]) -> bytes:
|
||||
return pcob_tag(cue_type, [
|
||||
pcpt_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
|
||||
loop_ms=c["loop_ms"])
|
||||
for c in chosen
|
||||
])
|
||||
|
||||
|
||||
def _pco2(cue_type: int, chosen: list[dict]) -> bytes:
|
||||
blob = b"".join(
|
||||
_pcp2_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
|
||||
loop_ms=c["loop_ms"], rgb=c.get("rgb"), beats=c.get("beats"),
|
||||
code=c.get("code", 0))
|
||||
return pco2_tag(cue_type, [
|
||||
pcp2_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
|
||||
loop_ms=c["loop_ms"], rgb=c.get("rgb"), beats=c.get("beats"),
|
||||
code=c.get("code", 0), comment=c.get("comment"))
|
||||
for c in chosen
|
||||
)
|
||||
return _wrap("PCO2", struct.pack(">IHH", cue_type, len(chosen), 0) + blob)
|
||||
])
|
||||
|
||||
|
||||
#: `PQT2` as rekordbox 7 leaves it after a grid edit: header kept, every count
|
||||
#: and the beat list gone (56 bytes, the `len_header`). MEASURED on Goober
|
||||
#: (2026-10-01): rekordbox does not recompute this "extended" grid when the grid
|
||||
#: changes, it blanks it, and a CDJ then works from `PQTZ`.
|
||||
_PQT2_HEADER = 56
|
||||
|
||||
|
||||
def blank_pqt2(tag: bytes) -> bytes:
|
||||
"""The blanked form of an existing `PQT2` tag, exactly as rekordbox writes it.
|
||||
|
||||
Bytes 12-24 (rekordbox's constants, `00000000 01000002 00000000` on every
|
||||
file seen) are KEPT; the counts and first/last-beat fields after them are
|
||||
zeroed, and the beat entries dropped.
|
||||
"""
|
||||
return tag[:8] + struct.pack(">I", _PQT2_HEADER) + tag[12:24] + bytes(_PQT2_HEADER - 24)
|
||||
|
||||
|
||||
def cue_tags(cues: list[dict], *, extended: bool) -> list[bytes]:
|
||||
|
||||
@@ -69,8 +69,8 @@ def capabilities_for(
|
||||
max_memory_cues=None, # unlimited
|
||||
# Both cue types write; Rekordbox has no fade/load types.
|
||||
types=WRITABLE_CUE_TYPES,
|
||||
# A hot cue's colour is one of rekordbox's swatches (the 15 that
|
||||
# were measured, see `palette`), offered in rekordbox's own order.
|
||||
# A hot cue's colour is one of rekordbox's 16 swatches (all
|
||||
# measured, see `palette`), offered in rekordbox's own order.
|
||||
color="palette",
|
||||
palette=[palette.hex_for(code) for code in palette.SWATCHES],
|
||||
named=True, # djmdCue.Comment
|
||||
@@ -91,6 +91,7 @@ def capabilities_for(
|
||||
media_kinds=["audio", "stem"],
|
||||
removable=True,
|
||||
addable=True,
|
||||
key_writable=True,
|
||||
artwork=False,
|
||||
artwork_note=None,
|
||||
),
|
||||
|
||||
@@ -63,7 +63,7 @@ class RekordboxDriver:
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
def open(self, path: Path) -> RekordboxAdapter:
|
||||
def open(self, path: Path, *, read_only: bool = False) -> RekordboxAdapter:
|
||||
return RekordboxAdapter(path)
|
||||
|
||||
def detect(self) -> list[dict]:
|
||||
|
||||
@@ -9,8 +9,9 @@ The table was MEASURED, not recalled: 16 hot cues coloured through rekordbox 7's
|
||||
own palette, one colour per pad, exported to a stick, and read back. Rekordbox
|
||||
writes the palette's exact RGB beside each code.
|
||||
|
||||
* One palette colour went unmeasured — the teal-green between 0x0E and 0x16
|
||||
(probably code 0x12); a cue that should be it maps to its nearest neighbour.
|
||||
* The teal-green between 0x0E and 0x16 was missed by that measurement, and
|
||||
found later: it is **0x13 = #00FF30**, which rekordbox 7 wrote itself as the
|
||||
DEFAULT colour of a hot cue added on a stick (Goober, 2026-10-01).
|
||||
* 0x2B (#FF0017) was observed on a real export though it is not one of the 16
|
||||
swatches; it is kept so such a colour survives a round trip exactly.
|
||||
* **The palette has no white or grey.** A colourless (white/grey) cue — above
|
||||
@@ -32,6 +33,7 @@ PALETTE: dict[int, tuple[int, int, int]] = {
|
||||
0x05: (0x00, 0x70, 0xFF), # light blue
|
||||
0x09: (0x00, 0xE0, 0xFF), # cyan
|
||||
0x0E: (0x00, 0xFF, 0xA3), # teal
|
||||
0x13: (0x00, 0xFF, 0x30), # teal-green (rekordbox's default for a new hot cue)
|
||||
0x16: (0x1A, 0xFF, 0x00), # green
|
||||
0x1A: (0x80, 0xFF, 0x00), # lime
|
||||
0x1E: (0xE6, 0xFF, 0x00), # yellow-lime
|
||||
@@ -94,18 +96,17 @@ def code_for(color: str | None) -> tuple[int, tuple[int, int, int]]:
|
||||
|
||||
|
||||
#: The swatches a user can pick, in rekordbox's own order — what
|
||||
#: `capabilities.cues.palette` offers. 15 of rekordbox's 16: the unmeasured
|
||||
#: teal-green is left out rather than offered with a guessed RGB, and 0x2B is
|
||||
#: not a swatch at all (see the module note).
|
||||
#: `capabilities.cues.palette` offers: all 16. 0x2B is not a swatch at all (see
|
||||
#: the module note).
|
||||
SWATCHES: list[int] = [code for code in PALETTE if code != 0x2B]
|
||||
|
||||
|
||||
def hex_for(code: int | None) -> str | None:
|
||||
"""`#RRGGBB` for a stored palette code; None for uncoloured or unknown.
|
||||
|
||||
An unknown code (the unmeasured teal-green) projects as no colour rather
|
||||
than a guessed one; it is still kept on the row, since editing a cue's
|
||||
position, type or name never rewrites its colour.
|
||||
An unknown code projects as no colour rather than a guessed one; it is
|
||||
still kept on the row, since editing a cue's position, type or name never
|
||||
rewrites its colour.
|
||||
"""
|
||||
rgb = PALETTE.get(code) if code else None
|
||||
return None if rgb is None else f"#{rgb[0]:02X}{rgb[1]:02X}{rgb[2]:02X}"
|
||||
|
||||
@@ -430,3 +430,166 @@ __all__ = [
|
||||
"album_row", "artist_row", "dsql", "id_string_row", "key_row", "playlist_entry_row",
|
||||
"playlist_tree_row", "read", "read_dsql", "template", "track_row",
|
||||
]
|
||||
|
||||
|
||||
# ---- editing an existing library -----------------------------------------------
|
||||
#
|
||||
# Editing a stick rekordbox wrote, rather than writing one from the template:
|
||||
# only the tables whose rows change are rewritten, and inside them a row that
|
||||
# does not change keeps rekordbox's own bytes. Every other table — history,
|
||||
# colours, menus, artwork — stays byte-identical, and so does exportExt.pdb.
|
||||
|
||||
|
||||
def _chain(buf: bytes, first: int, last: int) -> list[int]:
|
||||
"""A table's page chain, header page first."""
|
||||
pages, p = [first], first
|
||||
while p != last and len(pages) < 100000:
|
||||
p = struct.unpack_from("<I", buf, p * PAGE + 12)[0]
|
||||
pages.append(p)
|
||||
return pages
|
||||
|
||||
|
||||
def table_rows(buf: bytes, table: int) -> list[bytes]:
|
||||
"""Every present row of `table`, in page order, as its own bytes (padding
|
||||
included) — a row's extent is up to the next row's heap offset, or the end
|
||||
of the page's used heap."""
|
||||
n_tables = struct.unpack_from("<I", buf, 8)[0]
|
||||
for i in range(n_tables):
|
||||
t, _empty, first, last = struct.unpack_from("<4I", buf, 28 + 16 * i)
|
||||
if t != table:
|
||||
continue
|
||||
out = []
|
||||
for p in _chain(buf, first, last)[1:]:
|
||||
o = p * PAGE
|
||||
if buf[o + 0x1B] & _HEADER_PAGE:
|
||||
continue
|
||||
n = (buf[o + 0x19] >> 5) | (buf[o + 0x1A] << 3)
|
||||
used = struct.unpack_from("<H", buf, o + 0x1E)[0]
|
||||
offs, present = [], []
|
||||
# As `_rows` reads them: every bit of every group, since a page
|
||||
# rekordbox has edited holds more row slots than its small count.
|
||||
for g in range((n + 15) // 16):
|
||||
base = o + PAGE - g * _GROUP
|
||||
mask = struct.unpack_from("<H", buf, base - 4)[0]
|
||||
for r in range(16):
|
||||
if mask & (1 << r):
|
||||
offs.append(struct.unpack_from("<H", buf, base - 6 - 2 * r)[0])
|
||||
present.append(True)
|
||||
ends = sorted(set(offs)) + [used]
|
||||
for off, ok in zip(offs, present):
|
||||
if ok:
|
||||
end = next(e for e in ends if e > off)
|
||||
row = bytes(buf[o + _HEADER + off:o + _HEADER + end])
|
||||
if table == TRACKS:
|
||||
row = row[:track_extent(row)]
|
||||
out.append(row)
|
||||
return out
|
||||
return []
|
||||
|
||||
|
||||
def _dsql_len(buf: bytes, off: int) -> int:
|
||||
head = buf[off]
|
||||
return (head >> 1) if head & 1 else struct.unpack_from("<H", buf, off + 1)[0]
|
||||
|
||||
|
||||
def track_extent(row: bytes) -> int:
|
||||
"""Where a track row really ends: past its last string, 4-aligned.
|
||||
|
||||
NOT the next row's offset: rekordbox reuses its heap, and the bytes between
|
||||
a row and the next can be a stale tail of an older, longer string (seen on
|
||||
Goober: `...mp3` followed by `ing.stem.m4a`)."""
|
||||
offs = struct.unpack_from(f"<{len(TRACK_STRINGS)}H", row, _TRACK_FIXED)
|
||||
end = max(o + _dsql_len(row, o) for o in offs)
|
||||
return end + (-end % 4)
|
||||
|
||||
|
||||
def track_fields(row: bytes) -> tuple[dict, dict]:
|
||||
"""A raw track row as (`fields`, `strings`) — what `track_row` takes back."""
|
||||
fields = dict(zip([n for n, _ in _TRACK_FIELDS], struct.unpack_from(_TRACK_FMT, row, 0)))
|
||||
offs = struct.unpack_from(f"<{len(TRACK_STRINGS)}H", row, _TRACK_FIXED)
|
||||
return fields, {name: read_dsql(row, o) for name, o in zip(TRACK_STRINGS, offs)}
|
||||
|
||||
|
||||
def row_id(table: int, row: bytes) -> int | tuple:
|
||||
"""A row's identity within its table (the triple, for playlist entries)."""
|
||||
if table == TRACKS:
|
||||
return track_fields(row)[0]["id"]
|
||||
if table == ARTISTS:
|
||||
return struct.unpack_from("<I", row, 4)[0]
|
||||
if table == ALBUMS:
|
||||
return struct.unpack_from("<I", row, 12)[0]
|
||||
if table == PLAYLIST_TREE:
|
||||
return struct.unpack_from("<I", row, 12)[0]
|
||||
if table == PLAYLIST_ENTRIES:
|
||||
return struct.unpack_from("<3I", row, 0)
|
||||
return struct.unpack_from("<I", row, 0)[0]
|
||||
|
||||
|
||||
class PdbEditor(PdbWriter):
|
||||
"""`PdbWriter` over an EXISTING library: `refill` replaces one table's rows.
|
||||
|
||||
The table keeps its pages — overwritten in place, more taken from the
|
||||
next-unused counter if needed, any left over unlinked and blanked (a blank
|
||||
reserved page inside the file is a state rekordbox's own template has) —
|
||||
and keeps its empty candidate. `render` leaves the header's
|
||||
pages-with-room field as it was: rekordbox did not touch it when it edited
|
||||
Goober, and it is the least understood field in the file.
|
||||
"""
|
||||
|
||||
def __init__(self, existing: bytes):
|
||||
super().__init__(existing)
|
||||
self._room_field = struct.unpack_from("<I", self.buf, 16)[0]
|
||||
self._blank: set[int] = set()
|
||||
|
||||
def refill(self, table: int, rows: list[bytes]) -> None:
|
||||
slot, candidate, first, last = self.tables[table]
|
||||
old = _chain(bytes(self.buf), first, last)[1:]
|
||||
if candidate in old:
|
||||
old.remove(candidate)
|
||||
chunks = _chunk(rows) if rows else []
|
||||
indices = old[:len(chunks)] + [self._alloc() for _ in chunks[len(old):]]
|
||||
for p in old[len(chunks):]:
|
||||
self._blank.add(p)
|
||||
shift_at = _INDEX_SHIFT_AT if table in (TRACKS, ARTISTS, ALBUMS) else None
|
||||
indexed = table in _INDEXED
|
||||
for i, chunk in enumerate(chunks):
|
||||
nxt = indices[i + 1] if i + 1 < len(indices) else candidate
|
||||
fill = None
|
||||
if indexed:
|
||||
fill = (len(chunk) + 1, 0) if i + 1 == len(chunks) else (_NONE, _NONE)
|
||||
self.sequence += 1
|
||||
self.pages[indices[i]] = _data_page(indices[i], table, nxt, chunk, self.sequence,
|
||||
shift_at=shift_at, fill=fill)
|
||||
self._reindex(first, indices, indexed=indexed)
|
||||
self.tables[table] = [slot, candidate, first, indices[-1] if indices else first]
|
||||
if not indices:
|
||||
# No rows: the header page points straight at the candidate again.
|
||||
struct.pack_into("<I", self.buf, first * PAGE + 12, candidate)
|
||||
|
||||
def _reindex(self, header_page: int, data_pages: list[int], *, indexed: bool) -> None:
|
||||
o = header_page * PAGE
|
||||
struct.pack_into("<I", self.buf, o + 12, data_pages[0] if data_pages else
|
||||
struct.unpack_from("<I", self.buf, o + 12)[0])
|
||||
if indexed:
|
||||
# Clear the old entries first: a table that shrank must not keep
|
||||
# listing pages it no longer has.
|
||||
count = struct.unpack_from("<H", self.buf, o + _HEADER + 16)[0]
|
||||
for k in range(max(count, len(data_pages))):
|
||||
struct.pack_into("<I", self.buf, o + _HEADER + 20 + 4 * k, 0x1FFFFFF8)
|
||||
if data_pages:
|
||||
pages_with_room = self.pages_with_room
|
||||
self._index(header_page, data_pages, indexed=indexed)
|
||||
self.pages_with_room = pages_with_room
|
||||
else:
|
||||
struct.pack_into("<I", self.buf, o + _HEADER + 4, 0x03FFFFFF)
|
||||
if indexed:
|
||||
struct.pack_into("<HH", self.buf, o + _HEADER + 16, 0, 0x1FFF)
|
||||
struct.pack_into("<HH", self.buf, o + 0x20, _NONE, _NONE)
|
||||
struct.pack_into("<H", self.buf, o + 0x26, 0)
|
||||
|
||||
def render(self) -> bytes:
|
||||
out = bytearray(super().render())
|
||||
struct.pack_into("<I", out, 16, self._room_field)
|
||||
for p in self._blank - set(self.pages):
|
||||
out[p * PAGE:(p + 1) * PAGE] = bytes(PAGE)
|
||||
return bytes(out)
|
||||
@@ -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:
|
||||
|
||||
@@ -45,7 +45,8 @@ from ...core.adapter import (
|
||||
Unsupported,
|
||||
)
|
||||
from ...core.edit_journal import EditJournal
|
||||
from ...core.pathmap import PathMapping
|
||||
from ...core.grid_edit import ReplaceGridCommands
|
||||
from ...core.pathmap import PathMapping, stored_form
|
||||
from . import timebase
|
||||
from .cue_types import beat_loop_size, kind_for, role_and_slot
|
||||
|
||||
@@ -110,12 +111,14 @@ def _iso_stamp(value) -> str:
|
||||
return str(value)
|
||||
|
||||
|
||||
class RekordboxStore:
|
||||
class RekordboxStore(ReplaceGridCommands):
|
||||
"""One open Rekordbox library."""
|
||||
|
||||
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
|
||||
@@ -374,6 +377,14 @@ class RekordboxStore:
|
||||
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
|
||||
@@ -505,6 +516,46 @@ class RekordboxStore:
|
||||
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
|
||||
@@ -557,6 +608,79 @@ class RekordboxStore:
|
||||
self._db.delete_playlist(row)
|
||||
self._journal.record("playlist", "delete", name)
|
||||
|
||||
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
|
||||
"""Move a node to `index` among `parent_id`'s visible children.
|
||||
|
||||
Not pyrekordbox's `move_playlist`: its `parent=None` means "keep the
|
||||
parent", so nothing can be moved to the top level with it. The same
|
||||
writes are made here — `ParentID`, the moved row's `updated_at`, and
|
||||
`Seq` renumbered from 1 in both parents (only rows whose `Seq` changes
|
||||
are touched) — plus `masterPlaylists6.xml`'s `ParentId`, which
|
||||
pyrekordbox's version leaves stale. Rekordbox's hidden working lists
|
||||
share the table and the numbering, so `index` is placed relative to
|
||||
the VISIBLE siblings and the hidden ones keep their order around it."""
|
||||
import datetime
|
||||
|
||||
from pyrekordbox.masterdb.database import SPECIAL_PLAYLIST_IDS
|
||||
|
||||
t = self._tables
|
||||
row = self._playlist(node_id)
|
||||
dest = self._playlist(parent_id) if parent_id else None
|
||||
if dest is not None and int(dest.Attribute or 0) != int(t.PlaylistType.FOLDER):
|
||||
raise InvalidCommand("A playlist can only be moved into a folder")
|
||||
ancestor = dest
|
||||
while ancestor is not None:
|
||||
if str(ancestor.ID) == str(row.ID):
|
||||
raise InvalidCommand("A folder cannot be moved into itself")
|
||||
up = str(ancestor.ParentID or "root")
|
||||
ancestor = None if up in ("root", "0", "") else self._playlist(up)
|
||||
|
||||
def children(key: str) -> list:
|
||||
return (
|
||||
self._db.session.query(t.DjmdPlaylist)
|
||||
.filter(t.DjmdPlaylist.ParentID == key)
|
||||
.filter(t.DjmdPlaylist.rb_local_deleted == 0)
|
||||
.order_by(t.DjmdPlaylist.Seq)
|
||||
.all()
|
||||
)
|
||||
|
||||
old_key = str(row.ParentID or "root")
|
||||
new_key = str(dest.ID) if dest is not None else "root"
|
||||
siblings = [c for c in children(new_key) if str(c.ID) != str(row.ID)]
|
||||
visible = [c for c in siblings if str(c.ID) not in SPECIAL_PLAYLIST_IDS]
|
||||
index = max(0, min(int(index), len(visible)))
|
||||
if index < len(visible):
|
||||
at = siblings.index(visible[index])
|
||||
else:
|
||||
at = siblings.index(visible[-1]) + 1 if visible else len(siblings)
|
||||
order = siblings[:at] + [row] + siblings[at:]
|
||||
if old_key == new_key and [str(c.ID) for c in order] == [
|
||||
str(c.ID) for c in children(new_key)
|
||||
]:
|
||||
return str(row.ID)
|
||||
|
||||
row.ParentID = new_key
|
||||
with self._db.registry.disabled():
|
||||
row.updated_at = datetime.datetime.now()
|
||||
for n, c in enumerate(order, start=1):
|
||||
if c.Seq != n:
|
||||
c.Seq = n
|
||||
if old_key != new_key:
|
||||
for n, c in enumerate(
|
||||
(c for c in children(old_key) if str(c.ID) != str(row.ID)), start=1
|
||||
):
|
||||
if c.Seq != n:
|
||||
c.Seq = n
|
||||
xml = getattr(self._db, "playlist_xml", None)
|
||||
if xml is not None:
|
||||
try:
|
||||
xml.update(row.ID, parent_id=new_key)
|
||||
except ValueError:
|
||||
pass # a playlist the XML never listed: nothing to keep in step
|
||||
self._db.flush()
|
||||
self._journal.record("playlist", "move", row.Name)
|
||||
return str(row.ID)
|
||||
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
|
||||
"""Replace a playlist's contents, in the given order.
|
||||
|
||||
@@ -603,14 +727,15 @@ class RekordboxStore:
|
||||
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),
|
||||
@@ -632,11 +757,14 @@ class RekordboxStore:
|
||||
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)
|
||||
@@ -1285,53 +1413,6 @@ class RekordboxStore:
|
||||
row.BPM = int(round(ordered[0].bpm * 100)) if ordered else 0
|
||||
self._journal.record("grid", "replace" if ordered else "delete", track_id)
|
||||
|
||||
def delete_grid(self, track_id: str) -> None:
|
||||
self.replace_grid(track_id, [])
|
||||
|
||||
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> None:
|
||||
from ...core.model import GridMarker
|
||||
|
||||
markers = self.current_markers(track_id)
|
||||
if bpm is None:
|
||||
# Inherit the tempo governing this point, like Traktor's add does.
|
||||
governing = [m for m in markers if m.start <= start_sec]
|
||||
bpm = governing[-1].bpm if governing else (markers[0].bpm if markers else None)
|
||||
if not bpm:
|
||||
raise InvalidCommand("The first marker on an ungridded track needs a tempo")
|
||||
if any(abs(m.start - start_sec) < 0.001 for m in markers):
|
||||
raise InvalidCommand("There is already a marker here")
|
||||
markers.append(GridMarker(start=float(start_sec), bpm=float(bpm)))
|
||||
self.replace_grid(track_id, markers)
|
||||
|
||||
def _marker_at(self, track_id: str, index: int) -> tuple[list, int]:
|
||||
markers = self.current_markers(track_id)
|
||||
if not 0 <= index < len(markers):
|
||||
raise NotFound(f"No grid marker {index}")
|
||||
return markers, index
|
||||
|
||||
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> None:
|
||||
markers, i = self._marker_at(track_id, index)
|
||||
# Clamp between neighbours so the list cannot reorder under the caller.
|
||||
low = markers[i - 1].start + 0.001 if i > 0 else 0.0
|
||||
high = markers[i + 1].start - 0.001 if i + 1 < len(markers) else None
|
||||
target = max(low, float(start_sec))
|
||||
if high is not None:
|
||||
target = min(target, high)
|
||||
markers[i] = markers[i].model_copy(update={"start": target})
|
||||
self.replace_grid(track_id, markers)
|
||||
|
||||
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> None:
|
||||
markers, i = self._marker_at(track_id, index)
|
||||
if bpm <= 0:
|
||||
raise InvalidCommand(f"A tempo must be positive, got {bpm}")
|
||||
markers[i] = markers[i].model_copy(update={"bpm": float(bpm)})
|
||||
self.replace_grid(track_id, markers)
|
||||
|
||||
def delete_grid_marker(self, track_id: str, index: int) -> None:
|
||||
markers, i = self._marker_at(track_id, index)
|
||||
del markers[i]
|
||||
self.replace_grid(track_id, markers)
|
||||
|
||||
def _flush_grids(self) -> None:
|
||||
"""Write buffered grids into their ANLZ files. Called by save().
|
||||
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Remote libraries: a library held by a Konduktor server, opened from here.
|
||||
|
||||
NOT a registered driver: a remote is not a file `can_open` could probe, and it
|
||||
is chosen from the picker's own "Remote" step, by the saved remote's id. What
|
||||
opening one returns is everything `AppState.open_remote` installs — the
|
||||
adapter, the services that keep history and export sets on the server, and the
|
||||
session that keeps this computer's hold on it.
|
||||
|
||||
Imports no platform adapter (`test_layering.py`): what platform the server
|
||||
holds is the server's business, and reaches this side only as capabilities.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from ... import exports
|
||||
from . import config
|
||||
from .adapter import RemoteAdapter
|
||||
from .client import AuthFailed, InUse, RemoteClient, SessionLost, Unreachable, VersionMismatch
|
||||
from .services import RemotePending, RemoteServices, RemoteSetStore
|
||||
from .session import RemoteSession
|
||||
|
||||
__all__ = [
|
||||
"AuthFailed", "InUse", "Opened", "RemoteAdapter", "SessionLost", "Unreachable",
|
||||
"VersionMismatch", "handshake", "open_remote",
|
||||
]
|
||||
|
||||
|
||||
@dataclass
|
||||
class Opened:
|
||||
remote: config.Remote
|
||||
path: Path
|
||||
adapter: RemoteAdapter
|
||||
services: RemoteServices
|
||||
session: RemoteSession
|
||||
library_id: str
|
||||
pending: object | None
|
||||
#: Edits another computer left unsaved: {machine, summary}, or None.
|
||||
pending_edits: dict | None
|
||||
|
||||
|
||||
def open_remote(remote: config.Remote, *, takeover: bool = False, batch_probe=None,
|
||||
password: str | None = None, cache=None) -> Opened:
|
||||
"""Connect, take the session, and mirror the library. Raises `InUse` when
|
||||
another computer holds it (and `takeover` is not set), `AuthFailed`,
|
||||
`VersionMismatch` or `Unreachable` — all before anything is installed."""
|
||||
secret = password if password is not None else config.password(remote.id)
|
||||
if not secret:
|
||||
raise AuthFailed("No password is saved for this remote — edit it to enter one")
|
||||
client = RemoteClient(remote, secret)
|
||||
try:
|
||||
client_id = config.client_id()
|
||||
hello = client.hello(client_id)
|
||||
machine = config.machine_name()
|
||||
acquired = client.acquire(client_id, machine, takeover=takeover)
|
||||
session = RemoteSession(client, batch_probe=batch_probe, identity=(client_id, machine))
|
||||
adapter = RemoteAdapter(client, session, hello, cache=cache)
|
||||
session.on_reacquired = adapter.refresh
|
||||
except Exception:
|
||||
client.release()
|
||||
client.close()
|
||||
raise
|
||||
# The server's id for the library, namespaced: this computer's export-set
|
||||
# store for it is the SERVER (`RemoteSetStore`), and nothing this computer
|
||||
# keeps under the server's own id may be mistaken for it.
|
||||
library_id = f"remote:{hello['library_id']}"
|
||||
exports.use_store(library_id, RemoteSetStore(client))
|
||||
session.start()
|
||||
return Opened(
|
||||
remote=remote, path=Path(hello.get("path") or remote.name), adapter=adapter,
|
||||
services=RemoteServices(client), session=session, library_id=library_id,
|
||||
pending=RemotePending(client), pending_edits=acquired.get("pending_edits"),
|
||||
)
|
||||
|
||||
|
||||
def handshake(remote: config.Remote, password: str) -> list[dict]:
|
||||
"""Try each of the remote's addresses on its own: what a Save of the
|
||||
remote's settings reports. Each result is {address, url, ok, error, kind},
|
||||
`kind` one of ok / unreachable / auth / version / other."""
|
||||
results = []
|
||||
for label, url in remote.addresses():
|
||||
single = config.Remote(id=remote.id, name=remote.name, host=url, username=remote.username)
|
||||
client = RemoteClient(single, password, timeout=8.0)
|
||||
try:
|
||||
info = client.hello()
|
||||
results.append({"address": label, "url": url, "ok": True, "error": None, "kind": "ok",
|
||||
"name": info.get("name"), "platform": info.get("platform")})
|
||||
except Unreachable as ex:
|
||||
results.append({"address": label, "url": url, "ok": False, "error": str(ex), "kind": "unreachable"})
|
||||
except AuthFailed as ex:
|
||||
results.append({"address": label, "url": url, "ok": False, "error": str(ex), "kind": "auth"})
|
||||
except VersionMismatch as ex:
|
||||
results.append({"address": label, "url": url, "ok": False, "error": str(ex), "kind": "version"})
|
||||
except Exception as ex: # noqa: BLE001 — anything else is that address's answer
|
||||
results.append({"address": label, "url": url, "ok": False, "error": str(ex), "kind": "other"})
|
||||
finally:
|
||||
client.close()
|
||||
return results
|
||||
@@ -0,0 +1,449 @@
|
||||
"""`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 move_playlist(self, node_id, parent_id, index):
|
||||
return self._call("move_playlist", node_id=node_id, parent_id=parent_id, index=index)
|
||||
|
||||
def set_playlist_entries(self, node_id, track_ids):
|
||||
return self._call("set_playlist_entries", node_id=node_id, track_ids=list(track_ids))
|
||||
|
||||
def remove_tracks(self, track_ids):
|
||||
return self._call("remove_tracks", track_ids=list(track_ids))
|
||||
|
||||
def set_track_metadata(self, track_id, fields):
|
||||
return self._call("set_track_metadata", track_id=track_id, fields=fields)
|
||||
|
||||
def set_key(self, track_id, wheel, mode):
|
||||
return self._call("set_key", track_id=track_id, wheel=wheel, mode=mode)
|
||||
|
||||
def set_cue(self, track_id, *, slot, start_sec, cue_type, length_sec=0.0, role="hotcue", name=None):
|
||||
return self._call("set_cue", track_id=track_id, slot=slot, start_sec=start_sec,
|
||||
cue_type=cue_type, length_sec=length_sec, role=role, name=name)
|
||||
|
||||
def set_cue_type(self, track_id, slot, cue_type):
|
||||
return self._call("set_cue_type", track_id=track_id, slot=slot, cue_type=cue_type)
|
||||
|
||||
def set_cue_color(self, track_id, slot, color):
|
||||
return self._call("set_cue_color", track_id=track_id, slot=slot, color=color)
|
||||
|
||||
def delete_cue(self, track_id, slot):
|
||||
return self._call("delete_cue", track_id=track_id, slot=slot)
|
||||
|
||||
def place_cues(self, track_id, cues, *, overwrite=False):
|
||||
return self._call("place_cues", track_id=track_id, cues=list(cues), overwrite=overwrite)
|
||||
|
||||
def add_grid_marker(self, track_id, start_sec, bpm=None):
|
||||
return self._call("add_grid_marker", track_id=track_id, start_sec=start_sec, bpm=bpm)
|
||||
|
||||
def move_grid_marker(self, track_id, index, start_sec):
|
||||
return self._call("move_grid_marker", track_id=track_id, index=index, start_sec=start_sec)
|
||||
|
||||
def set_grid_marker_bpm(self, track_id, index, bpm):
|
||||
return self._call("set_grid_marker_bpm", track_id=track_id, index=index, bpm=bpm)
|
||||
|
||||
def delete_grid_marker(self, track_id, index):
|
||||
return self._call("delete_grid_marker", track_id=track_id, index=index)
|
||||
|
||||
def replace_grid(self, track_id, markers):
|
||||
return self._call("replace_grid", track_id=track_id, markers=_pairs(markers))
|
||||
|
||||
def set_analysed_grid(self, track_id, markers):
|
||||
return self._call("set_analysed_grid", track_id=track_id, markers=_pairs(markers))
|
||||
|
||||
def delete_grid(self, track_id):
|
||||
return self._call("delete_grid", track_id=track_id)
|
||||
|
||||
def set_grid_lock(self, track_id, locked):
|
||||
return self._call("set_grid_lock", track_id=track_id, locked=locked)
|
||||
|
||||
# ---- adding tracks ------------------------------------------------------------------
|
||||
def upload_audio(self, source: Path, folder: str, name: str, *, progress=None) -> Path:
|
||||
"""Send `source` into `folder` on the server; the path it landed at (a
|
||||
taken name gets `-2`…, as a local copy does). What a local import's
|
||||
file copy becomes when the library's destination is the server's."""
|
||||
try:
|
||||
landed = self.client.upload(Path(source), folder, name, progress=progress)
|
||||
except SessionLost as ex:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
self._uploads[landed["path"]] = (Path(source), landed.get("analysis_lead"))
|
||||
return Path(landed["path"])
|
||||
|
||||
def free_space(self, path: str) -> int:
|
||||
"""Free space on the SERVER's disk at `path` (an import's destination)."""
|
||||
return self.client.fs_space(path)
|
||||
|
||||
def delete_upload(self, path) -> None:
|
||||
"""Undo `upload_audio` (a cancelled or failed import)."""
|
||||
self._uploads.pop(str(path), None)
|
||||
self.client.delete_upload(str(path))
|
||||
|
||||
def add_tracks(self, items, *, checkpoint=None):
|
||||
"""Add uploaded files. Where the platform analyses what it adds (the
|
||||
server said so with an analysis lead), the analysis is done HERE, on
|
||||
the copy this computer uploaded — the server never decodes audio."""
|
||||
from ...core import add_analysis
|
||||
|
||||
wire = []
|
||||
total = len(items)
|
||||
for n, item in enumerate(items, start=1):
|
||||
key = str(item.audio_path)
|
||||
source, lead = self._uploads.get(key, (None, None))
|
||||
analysis = item.analysis
|
||||
if analysis is None and lead is not None and source is not None:
|
||||
if checkpoint is not None:
|
||||
checkpoint(f"Analysing {item.track.title or source.name} ({n}/{total})", step=n, of=total)
|
||||
has_grid = bool(item.cues and item.cues.grid_markers)
|
||||
analysis = add_analysis.prepare(source, lead=lead, detect=not has_grid,
|
||||
detect_key=item.track.key_wheel is None)
|
||||
art = rp.WireArt(data=base64.b64encode(item.art[0]).decode("ascii"), mime=item.art[1]) \
|
||||
if item.art else None
|
||||
wire.append(rp.WireNewTrack(track=item.track, audio_path=key, cues=item.cues, art=art,
|
||||
analysis=rp.pack_analysis(analysis)))
|
||||
if checkpoint is not None:
|
||||
checkpoint(f"Adding {total} track{'' if total == 1 else 's'} on the server",
|
||||
step=total, of=total)
|
||||
try:
|
||||
envelope = self.client.rpc("add_tracks", items=wire, timeout=None)
|
||||
except SessionLost as ex:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
self._apply(envelope)
|
||||
for item in items:
|
||||
self._uploads.pop(str(item.audio_path), None)
|
||||
return envelope["result"]
|
||||
|
||||
def apply_stem_swaps(self, swaps, *, add_to_playlist=None):
|
||||
raise Unsupported("A remote library's stem files are swapped in on the server")
|
||||
|
||||
# ---- Convert to Stems (the library side lives on the server) ---------------------
|
||||
# `stems/remote_convert.py` drives these: the server plans and swaps, this
|
||||
# computer separates. See the server's stem routes for why.
|
||||
def stems_plan(self, body: dict) -> dict:
|
||||
return self.client.stems_plan(body)
|
||||
|
||||
def stage_stem(self, track_id: str, target: str, local: Path, *, bit_rate: int,
|
||||
duration: float, progress=None) -> dict:
|
||||
import hashlib
|
||||
|
||||
digest = hashlib.sha256()
|
||||
with open(local, "rb") as f:
|
||||
while chunk := f.read(1 << 20):
|
||||
digest.update(chunk)
|
||||
try:
|
||||
return self.client.stems_stage(track_id, target, local, sha256=digest.hexdigest(),
|
||||
bit_rate=bit_rate, duration=duration, progress=progress)
|
||||
except SessionLost as ex:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
|
||||
def abandon_stems(self, targets: list[str]) -> None:
|
||||
self.client.stems_abandon(targets)
|
||||
|
||||
def publish_stems(self, items: list[dict], options: dict) -> dict:
|
||||
try:
|
||||
result = self.client.stems_publish(items, options)
|
||||
except SessionLost as ex:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
self._load() # ids changed (repoint) or entries were added
|
||||
return result
|
||||
|
||||
# ---- metadata / art ------------------------------------------------------------------
|
||||
def set_cover_art(self, track_id, data, mime):
|
||||
try:
|
||||
envelope = self.client.put_art(track_id, data, mime)
|
||||
except SessionLost as ex:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
self._apply({**envelope, "removed": [], "reset": False})
|
||||
|
||||
def cover_art(self, track_id):
|
||||
return self.client.art(track_id)
|
||||
|
||||
# ---- audio ------------------------------------------------------------------------------
|
||||
def audio_facts(self, track_ids):
|
||||
wanted = list(dict.fromkeys(track_ids))
|
||||
with self._lock:
|
||||
missing = [t for t in wanted if t not in self._facts]
|
||||
if missing:
|
||||
found = {}
|
||||
for start in range(0, len(missing), 2000):
|
||||
found.update(self._call("audio_facts", track_ids=missing[start:start + 2000]))
|
||||
with self._lock:
|
||||
self._facts.update(found)
|
||||
with self._lock:
|
||||
return {t: self._facts[t] for t in wanted if t in self._facts}
|
||||
|
||||
def audio_path(self, track_id, *, progress=None):
|
||||
"""A local copy of the track's audio, downloaded if this computer has
|
||||
none of this version. None when the server has no file for it."""
|
||||
for attempt in range(2):
|
||||
facts = self.audio_facts([track_id]).get(track_id)
|
||||
if facts is None:
|
||||
return None
|
||||
cached = self.cache.get(facts)
|
||||
if cached is not None:
|
||||
return cached
|
||||
try:
|
||||
return self.cache.fetch(
|
||||
facts, lambda partial: self.client.download(track_id, partial, progress=progress))
|
||||
except StaleFacts:
|
||||
with self._lock:
|
||||
self._facts.pop(track_id, None)
|
||||
if attempt:
|
||||
raise
|
||||
return None
|
||||
|
||||
def cached_audio(self, track_id) -> Path | None:
|
||||
"""The local copy if there already is one — never downloads."""
|
||||
facts = self.audio_facts([track_id]).get(track_id)
|
||||
return self.cache.get(facts) if facts else None
|
||||
|
||||
# ---- paths: the server's business ------------------------------------------------
|
||||
def set_path_mapping(self, mapping):
|
||||
raise Unsupported(_NOT_HERE)
|
||||
|
||||
def set_session_mappings(self, mappings):
|
||||
raise Unsupported(_NOT_HERE)
|
||||
|
||||
def unresolved_path_groups(self):
|
||||
return []
|
||||
|
||||
def path_prefix_suggestions(self):
|
||||
raise Unsupported(_NOT_HERE)
|
||||
|
||||
def remap_preview(self, mapping):
|
||||
raise Unsupported(_NOT_HERE)
|
||||
|
||||
def remap_locations(self, mapping):
|
||||
raise Unsupported(_NOT_HERE)
|
||||
|
||||
# ---- save ----------------------------------------------------------------------------
|
||||
def save(self):
|
||||
try:
|
||||
result = self.client.save()
|
||||
except SessionLost as ex:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
outcome = SaveOutcome(
|
||||
summary=result.get("summary") or "",
|
||||
snapshot=None,
|
||||
tag_results=[FileTagResult(**r) for r in result.get("tag_results") or []],
|
||||
)
|
||||
# Versioned on the server; `RemoteServices.commit_save` hands it on.
|
||||
outcome.commit = result.get("commit")
|
||||
self._load()
|
||||
return outcome
|
||||
|
||||
def snapshot(self) -> bytes:
|
||||
raise Unsupported("A remote library's version history is kept on the server")
|
||||
|
||||
def close(self) -> None:
|
||||
self.session.stop()
|
||||
self.client.release()
|
||||
self.client.close()
|
||||
|
||||
|
||||
def _pairs(markers) -> list[tuple[float, float]]:
|
||||
out = []
|
||||
for m in markers:
|
||||
if hasattr(m, "start"):
|
||||
out.append((float(m.start), float(m.bpm)))
|
||||
else:
|
||||
start, bpm = m
|
||||
out.append((float(start), float(bpm)))
|
||||
return out
|
||||
@@ -0,0 +1,194 @@
|
||||
"""This computer's copies of a remote library's audio.
|
||||
|
||||
Everything that needs a track's audio as a FILE runs here, not on the server —
|
||||
the deck's decode, grid and cue analysis, stem separation and extraction, an
|
||||
export's copy onto a stick. One cache serves them all, so a track analysed and
|
||||
then exported downloads once.
|
||||
|
||||
* **Keyed by what the server says the file IS** — its path there, size and
|
||||
mtime (`AudioFacts`) — never by when it was fetched: an edited file (Save
|
||||
writes tags into it) is a new entry, and the same file fetched again after
|
||||
an eviction, or by another computer exporting the same set, is recognised.
|
||||
* **A partial, renamed into place**, so a cut connection never leaves a
|
||||
truncated file under a real entry's name, and a download whose size does
|
||||
not match the facts is refused rather than kept.
|
||||
* **Least recently used, under a cap** (`remoteCacheBytes` in prefs). The
|
||||
entry just written and anything touched in the last few minutes are never
|
||||
the ones evicted: they are being played or copied right now.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import shutil
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from ... import paths, prefs
|
||||
from ...core.adapter import AudioFacts, Unavailable
|
||||
|
||||
DEFAULT_CAP = 10 * 1024 ** 3
|
||||
_RECENT = 300.0 # seconds: an entry touched this recently is in use
|
||||
_PART = ".part"
|
||||
|
||||
|
||||
class StaleFacts(Unavailable):
|
||||
"""The server's file changed between asking about it and downloading it."""
|
||||
|
||||
|
||||
def cache_root() -> Path:
|
||||
return paths.app_data_dir() / "remote-cache"
|
||||
|
||||
|
||||
def cap_bytes() -> int:
|
||||
try:
|
||||
value = int(prefs.load_prefs().get("remoteCacheBytes") or DEFAULT_CAP)
|
||||
except (TypeError, ValueError):
|
||||
value = DEFAULT_CAP
|
||||
return max(value, 256 * 1024 ** 2)
|
||||
|
||||
|
||||
class RemoteAudioCache:
|
||||
def __init__(self, root: Path | None = None, *, cap=None, clock=time.time):
|
||||
self.root = Path(root) if root is not None else cache_root()
|
||||
self._cap = cap if cap is not None else cap_bytes
|
||||
self._clock = clock
|
||||
self._locks: dict[str, threading.Lock] = {}
|
||||
self._guard = threading.Lock()
|
||||
#: Recent download speeds (bytes/s), newest last — for time estimates.
|
||||
self._speeds: list[float] = []
|
||||
|
||||
# ---- naming ----------------------------------------------------------------
|
||||
@staticmethod
|
||||
def key(facts: AudioFacts) -> str:
|
||||
text = f"{facts.key}|{facts.size}|{facts.mtime_ns}"
|
||||
return hashlib.sha256(text.encode("utf-8")).hexdigest()[:32]
|
||||
|
||||
def path_for(self, facts: AudioFacts) -> Path:
|
||||
# The original's suffix, so a MIME type and a decoder's guess still work.
|
||||
suffix = Path(facts.key.replace("\\", "/")).suffix.lower()
|
||||
return self.root / f"{self.key(facts)}{suffix}"
|
||||
|
||||
def _lock_for(self, key: str) -> threading.Lock:
|
||||
with self._guard:
|
||||
return self._locks.setdefault(key, threading.Lock())
|
||||
|
||||
# ---- use -------------------------------------------------------------------
|
||||
def get(self, facts: AudioFacts) -> Path | None:
|
||||
path = self.path_for(facts)
|
||||
if path.is_file():
|
||||
self._touch(path)
|
||||
return path
|
||||
return None
|
||||
|
||||
def fetch(self, facts: AudioFacts, download) -> Path:
|
||||
"""The cached copy, downloading it first if needed. `download(partial)`
|
||||
writes the file and returns the server's `{size, mtime_ns}` for it."""
|
||||
path = self.path_for(facts)
|
||||
with self._lock_for(path.name):
|
||||
if path.is_file():
|
||||
self._touch(path)
|
||||
return path
|
||||
self.root.mkdir(parents=True, exist_ok=True)
|
||||
partial = path.with_name(f"{path.name}.{os.getpid()}.{threading.get_ident()}{_PART}")
|
||||
started = time.monotonic()
|
||||
try:
|
||||
meta = download(partial) or {}
|
||||
got = partial.stat().st_size
|
||||
if got != facts.size or (meta.get("size") and meta["size"] != facts.size):
|
||||
raise StaleFacts(f"{Path(facts.key).name} changed on the server while downloading")
|
||||
os.replace(partial, path)
|
||||
finally:
|
||||
partial.unlink(missing_ok=True)
|
||||
elapsed = max(time.monotonic() - started, 1e-3)
|
||||
if facts.size > 1 << 20:
|
||||
self._speeds = (self._speeds + [facts.size / elapsed])[-8:]
|
||||
self._touch(path)
|
||||
self.prune(keep={path})
|
||||
return path
|
||||
|
||||
def speed(self) -> float | None:
|
||||
"""A recent download speed in bytes/s, or None before the first."""
|
||||
if not self._speeds:
|
||||
return None
|
||||
ordered = sorted(self._speeds)
|
||||
return ordered[len(ordered) // 2]
|
||||
|
||||
def _touch(self, path: Path) -> None:
|
||||
now = self._clock()
|
||||
try:
|
||||
os.utime(path, (now, now))
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# ---- housekeeping ------------------------------------------------------------
|
||||
def _entries(self) -> list[tuple[float, int, Path]]:
|
||||
out = []
|
||||
if not self.root.is_dir():
|
||||
return out
|
||||
for p in self.root.iterdir():
|
||||
if p.name.endswith(_PART) or not p.is_file():
|
||||
continue
|
||||
try:
|
||||
st = p.stat()
|
||||
except OSError:
|
||||
continue
|
||||
out.append((st.st_mtime, st.st_size, p))
|
||||
return out
|
||||
|
||||
def prune(self, keep: set[Path] | None = None) -> int:
|
||||
"""Evict least-recently-used entries until under the cap. Returns bytes freed."""
|
||||
cap = self._cap() if callable(self._cap) else self._cap
|
||||
entries = sorted(self._entries())
|
||||
total = sum(size for _, size, _ in entries)
|
||||
freed = 0
|
||||
now = self._clock()
|
||||
for used, size, p in entries:
|
||||
if total <= cap:
|
||||
break
|
||||
if (keep and p in keep) or now - used < _RECENT:
|
||||
continue
|
||||
try:
|
||||
p.unlink()
|
||||
except OSError:
|
||||
continue # held open (Windows): next time
|
||||
total -= size
|
||||
freed += size
|
||||
return freed
|
||||
|
||||
def usage(self) -> dict:
|
||||
entries = self._entries()
|
||||
cap = self._cap() if callable(self._cap) else self._cap
|
||||
return {"bytes": sum(s for _, s, _ in entries), "files": len(entries), "cap": cap,
|
||||
"free": _free(self.root)}
|
||||
|
||||
def clear(self) -> int:
|
||||
freed = 0
|
||||
for _, size, p in self._entries():
|
||||
try:
|
||||
p.unlink()
|
||||
freed += size
|
||||
except OSError:
|
||||
pass
|
||||
return freed
|
||||
|
||||
|
||||
def _free(folder: Path) -> int:
|
||||
probe = folder
|
||||
while not probe.exists() and probe != probe.parent:
|
||||
probe = probe.parent
|
||||
try:
|
||||
return shutil.disk_usage(probe).free
|
||||
except OSError:
|
||||
return 0
|
||||
|
||||
|
||||
_shared: RemoteAudioCache | None = None
|
||||
|
||||
|
||||
def shared() -> RemoteAudioCache:
|
||||
global _shared
|
||||
if _shared is None:
|
||||
_shared = RemoteAudioCache()
|
||||
return _shared
|
||||
@@ -0,0 +1,302 @@
|
||||
"""Talking to a Konduktor server: addresses, sign-in, and the error vocabulary.
|
||||
|
||||
Every request tries the address that last worked, then the others in the
|
||||
remote's order (primary, then fallback) — so a laptop that leaves the house
|
||||
moves from the LAN address to the VPN one without being asked, and back again.
|
||||
Only a CONNECT failure moves on: the request never reached that server, so
|
||||
sending it to the other one cannot apply it twice. A request that reached a
|
||||
server and then failed is that server's answer.
|
||||
|
||||
The server's refusals come back as the adapter's own error classes (the same
|
||||
status codes `main.py` maps them from), so a route on this computer reports a
|
||||
remote library's refusal exactly as it would a local one's.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
|
||||
from ... import remote_protocol as rp
|
||||
from ...core.adapter import (
|
||||
AdapterError,
|
||||
InvalidCommand,
|
||||
LibraryNotSupported,
|
||||
NotFound,
|
||||
Unavailable,
|
||||
Unsupported,
|
||||
)
|
||||
from .config import Remote
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
_CONNECT_ERRORS = (httpx.ConnectError, httpx.ConnectTimeout)
|
||||
|
||||
|
||||
class Unreachable(Unavailable):
|
||||
"""No address of the remote answered."""
|
||||
|
||||
|
||||
class AuthFailed(LibraryNotSupported):
|
||||
"""The server refused the username or password."""
|
||||
|
||||
|
||||
class VersionMismatch(LibraryNotSupported):
|
||||
def __init__(self, update: str, server_version: str):
|
||||
side = "Konduktor on this computer" if update == "app" else "the Konduktor server"
|
||||
super().__init__(
|
||||
f"This server speaks a different version of Konduktor's protocol "
|
||||
f"(server {server_version}): update {side}."
|
||||
)
|
||||
self.update = update
|
||||
|
||||
|
||||
class InUse(AdapterError):
|
||||
"""Another computer holds the session: `holder` = {machine, since, batch}."""
|
||||
|
||||
def __init__(self, holder: dict):
|
||||
super().__init__(f"In use by {holder.get('machine') or 'another computer'}")
|
||||
self.holder = holder
|
||||
|
||||
|
||||
class SessionLost(Unavailable):
|
||||
"""This computer no longer holds the session (another one took over)."""
|
||||
|
||||
def __init__(self, holder: dict | None):
|
||||
who = (holder or {}).get("machine")
|
||||
super().__init__(
|
||||
f"{who} has taken over this library — it is read-only here" if who
|
||||
else "This computer no longer holds the library's session"
|
||||
)
|
||||
self.holder = holder
|
||||
|
||||
|
||||
def _detail(response: httpx.Response):
|
||||
try:
|
||||
return response.json().get("detail")
|
||||
except Exception: # noqa: BLE001
|
||||
return response.text[:300]
|
||||
|
||||
|
||||
class RemoteClient:
|
||||
def __init__(self, remote: Remote, password: str, *, timeout: float = 30.0):
|
||||
self.remote = remote
|
||||
self._addresses = remote.addresses()
|
||||
self._active: int | None = None
|
||||
self.token: str | None = None
|
||||
self._lock = threading.Lock()
|
||||
self._http = httpx.Client(
|
||||
auth=(remote.username, password),
|
||||
timeout=httpx.Timeout(timeout, connect=4.0),
|
||||
follow_redirects=False,
|
||||
)
|
||||
|
||||
def close(self) -> None:
|
||||
self._http.close()
|
||||
|
||||
@property
|
||||
def via(self) -> str | None:
|
||||
"""Which address is in use: "primary" / "fallback" (None until one answers)."""
|
||||
return None if self._active is None else self._addresses[self._active][0]
|
||||
|
||||
# ---- transport ----------------------------------------------------------------
|
||||
def _order(self) -> list[int]:
|
||||
everything = list(range(len(self._addresses)))
|
||||
if self._active is None:
|
||||
return everything
|
||||
return [self._active] + [i for i in everything if i != self._active]
|
||||
|
||||
def request(self, method: str, path: str, *, retry: bool = True, session: bool = True,
|
||||
**kw) -> httpx.Response:
|
||||
headers = dict(kw.pop("headers", None) or {})
|
||||
if session and self.token:
|
||||
headers[rp.SESSION_HEADER] = self.token
|
||||
order = self._order() if retry else ([self._active] if self._active is not None else [0])
|
||||
last: Exception | None = None
|
||||
for i in order:
|
||||
base = self._addresses[i][1]
|
||||
try:
|
||||
response = self._http.request(method, base + path, headers=headers, **kw)
|
||||
except _CONNECT_ERRORS as ex:
|
||||
last = ex
|
||||
continue
|
||||
except httpx.TimeoutException as ex:
|
||||
self._active = i
|
||||
raise Unreachable(f"The server at {base} stopped answering") from ex
|
||||
except httpx.TransportError as ex:
|
||||
last = ex
|
||||
continue
|
||||
self._active = i
|
||||
return self.check(response)
|
||||
names = " or ".join(b for _, b in (self._addresses[i] for i in order))
|
||||
raise Unreachable(f"Cannot reach the server at {names}") from last
|
||||
|
||||
def stream(self, method: str, path: str, **kw):
|
||||
"""A streaming request on the address in use (a download)."""
|
||||
headers = dict(kw.pop("headers", None) or {})
|
||||
if self.token:
|
||||
headers[rp.SESSION_HEADER] = self.token
|
||||
# Pick the address first with a cheap call, so the stream itself is not
|
||||
# the request that discovers the primary is gone.
|
||||
if self._active is None:
|
||||
self.request("GET", "/v1/hello", session=False)
|
||||
base = self._addresses[self._active][1]
|
||||
return self._http.stream(method, base + path, headers=headers, **kw)
|
||||
|
||||
@staticmethod
|
||||
def check(response: httpx.Response) -> httpx.Response:
|
||||
status = response.status_code
|
||||
if status < 400:
|
||||
return response
|
||||
detail = _detail(response)
|
||||
if status == 401:
|
||||
raise AuthFailed("The server refused the username or password")
|
||||
if status == 423:
|
||||
raise SessionLost((detail or {}).get("holder") if isinstance(detail, dict) else None)
|
||||
if status == 409 and isinstance(detail, dict) and detail.get("code") == "in_use":
|
||||
raise InUse(detail)
|
||||
text = detail if isinstance(detail, str) else (detail or {}).get("message", str(detail))
|
||||
cls = {404: NotFound, 400: InvalidCommand, 422: Unsupported, 503: Unavailable}.get(status)
|
||||
if cls is not None:
|
||||
raise cls(text)
|
||||
raise AdapterError(f"The server answered {status}: {text}")
|
||||
|
||||
# ---- handshake + session ----------------------------------------------------------
|
||||
def hello(self, client_id: str | None = None) -> dict:
|
||||
info = self.request("GET", "/v1/hello", params={"client_id": client_id} if client_id else None,
|
||||
session=False).json()
|
||||
server_version = tuple(info.get("api_version") or (0, 0))
|
||||
update = rp.compatible(rp.API_VERSION, (int(server_version[0]), int(server_version[1])))
|
||||
if update:
|
||||
raise VersionMismatch(update, info.get("app_version") or ".".join(map(str, server_version)))
|
||||
return info
|
||||
|
||||
def acquire(self, client_id: str, machine: str, *, takeover: bool = False) -> dict:
|
||||
body = self.request("POST", "/v1/session/acquire", session=False,
|
||||
json={"client_id": client_id, "machine": machine, "takeover": takeover}).json()
|
||||
self.token = body["token"]
|
||||
return body
|
||||
|
||||
def heartbeat(self, batch: str | None) -> dict:
|
||||
return self.request("POST", "/v1/session/heartbeat", json={"batch": batch}).json()
|
||||
|
||||
def release(self, *, timeout: float | None = None) -> None:
|
||||
if not self.token:
|
||||
return
|
||||
try:
|
||||
kw = {"timeout": timeout} if timeout is not None else {}
|
||||
self.request("POST", "/v1/session/release", retry=False, **kw)
|
||||
except AdapterError:
|
||||
pass
|
||||
self.token = None
|
||||
|
||||
# ---- the protocol -------------------------------------------------------------------
|
||||
def rpc(self, method: str, /, *, timeout=..., **args) -> dict:
|
||||
"""Call one protocol method; the envelope `{result, rev, changed, removed, reset}`
|
||||
with `result` already deserialised."""
|
||||
kw = {} if timeout is ... else {"timeout": timeout}
|
||||
body = self.request("POST", f"/v1/rpc/{method}", json={"args": rp.dump_args(method, args)}, **kw).json()
|
||||
body["result"] = rp.load_result(method, body.get("result"))
|
||||
return body
|
||||
|
||||
# ---- bytes -----------------------------------------------------------------------------
|
||||
def download(self, track_id: str, target: Path, *, progress=None) -> dict:
|
||||
"""Stream a track's audio into `target`; its server-side size and mtime."""
|
||||
with self.stream("GET", "/v1/audio", params={"track_id": track_id}, timeout=None) as response:
|
||||
if response.status_code >= 400:
|
||||
response.read()
|
||||
self.check(response)
|
||||
with open(target, "wb") as out:
|
||||
for chunk in response.iter_bytes(1 << 20):
|
||||
out.write(chunk)
|
||||
if progress is not None:
|
||||
progress(len(chunk))
|
||||
return {
|
||||
"size": int(response.headers.get("X-Konduktor-Size") or 0),
|
||||
"mtime_ns": int(response.headers.get("X-Konduktor-Mtime-Ns") or 0),
|
||||
}
|
||||
|
||||
def upload(self, source: Path, folder: str, name: str, *, progress=None) -> dict:
|
||||
def body():
|
||||
with open(source, "rb") as f:
|
||||
while chunk := f.read(1 << 20):
|
||||
if progress is not None:
|
||||
progress(len(chunk))
|
||||
yield chunk
|
||||
|
||||
return self.request("POST", "/v1/upload", params={"dir": folder, "name": name},
|
||||
content=body(), retry=False, timeout=None).json()
|
||||
|
||||
def delete_upload(self, path: str) -> None:
|
||||
self.request("DELETE", "/v1/upload", params={"path": path})
|
||||
|
||||
def art(self, track_id: str) -> tuple[bytes, str] | None:
|
||||
try:
|
||||
r = self.request("GET", "/v1/art", params={"track_id": track_id})
|
||||
except NotFound:
|
||||
return None
|
||||
return r.content, r.headers.get("content-type", "image/jpeg").split(";")[0]
|
||||
|
||||
def put_art(self, track_id: str, data: bytes, mime: str) -> dict:
|
||||
return self.request("PUT", "/v1/art", params={"track_id": track_id, "mime": mime},
|
||||
content=data).json()
|
||||
|
||||
def fs_list(self, path: str | None) -> dict:
|
||||
return self.request("GET", "/v1/fs/list", params={"path": path} if path else None).json()
|
||||
|
||||
def fs_space(self, path: str | None) -> int:
|
||||
return int(self.request("GET", "/v1/fs/space", params={"path": path} if path else None).json()["free"])
|
||||
|
||||
# ---- Convert to Stems ----------------------------------------------------------------
|
||||
def stems_plan(self, body: dict) -> dict:
|
||||
return self.request("POST", "/v1/stems/plan", json=body, timeout=None).json()
|
||||
|
||||
def stems_stage(self, track_id: str, target: str, source: Path, *, sha256: str,
|
||||
bit_rate: int, duration: float, progress=None) -> dict:
|
||||
def body():
|
||||
with open(source, "rb") as f:
|
||||
while chunk := f.read(1 << 20):
|
||||
if progress is not None:
|
||||
progress(len(chunk))
|
||||
yield chunk
|
||||
|
||||
return self.request(
|
||||
"PUT", "/v1/stems/stage",
|
||||
params={"track_id": track_id, "target": target, "sha256": sha256,
|
||||
"bit_rate": bit_rate, "duration": duration},
|
||||
content=body(), retry=False, timeout=None,
|
||||
).json()
|
||||
|
||||
def stems_abandon(self, targets: list[str]) -> None:
|
||||
self.request("POST", "/v1/stems/abandon", json={"targets": targets})
|
||||
|
||||
def stems_publish(self, items: list[dict], options: dict) -> dict:
|
||||
return self.request("POST", "/v1/stems/publish", json={"items": items, "options": options},
|
||||
timeout=None).json()
|
||||
|
||||
def stems_pending(self) -> dict:
|
||||
return self.request("GET", "/v1/stems/pending").json()
|
||||
|
||||
# ---- save / history / export sets -------------------------------------------------
|
||||
def save(self) -> dict:
|
||||
return self.request("POST", "/v1/save", timeout=None).json()
|
||||
|
||||
def discard(self) -> dict:
|
||||
return self.request("POST", "/v1/discard", timeout=None).json()
|
||||
|
||||
def history(self) -> list[dict]:
|
||||
return self.request("GET", "/v1/history").json()
|
||||
|
||||
def restore(self, commit_id: str) -> dict:
|
||||
return self.request("POST", f"/v1/history/{commit_id}/restore", timeout=None).json()
|
||||
|
||||
def clear_history(self) -> None:
|
||||
self.request("DELETE", "/v1/history")
|
||||
|
||||
def export_sets(self) -> dict:
|
||||
return self.request("GET", "/v1/export-sets").json()
|
||||
|
||||
def put_export_sets(self, doc: dict) -> None:
|
||||
self.request("PUT", "/v1/export-sets", json=doc)
|
||||
@@ -0,0 +1,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
|
||||
@@ -0,0 +1,85 @@
|
||||
"""A remote library's app-level bookkeeping — kept on the server, beside it.
|
||||
|
||||
Version history, export sets and the stems ledger belong with the library, not
|
||||
with whichever computer opened it: they are what every computer that opens it
|
||||
should see. So for a remote library these are calls to the server, and this
|
||||
computer's app-data holds none of them (`services.py` is the local half).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from ...core.adapter import NotFound
|
||||
from ...history import HistoryEntry
|
||||
from .client import RemoteClient
|
||||
|
||||
|
||||
class RemoteServices:
|
||||
remote = True
|
||||
|
||||
def __init__(self, client: RemoteClient):
|
||||
self.client = client
|
||||
|
||||
def baseline(self) -> None:
|
||||
pass # the server records its own "as I found it" version when it opens
|
||||
|
||||
def commit_save(self, adapter, outcome) -> str | None:
|
||||
# The server versioned the save itself; its commit rides on the outcome.
|
||||
return getattr(outcome, "commit", None)
|
||||
|
||||
def history(self) -> list[HistoryEntry]:
|
||||
return [HistoryEntry(**e) for e in self.client.history()]
|
||||
|
||||
def restore(self, commit_id: str) -> bool:
|
||||
try:
|
||||
self.client.restore(commit_id)
|
||||
except NotFound:
|
||||
return False
|
||||
return True
|
||||
|
||||
def clear_history(self) -> None:
|
||||
self.client.clear_history()
|
||||
|
||||
def discard(self) -> None:
|
||||
self.client.discard()
|
||||
|
||||
|
||||
class RemoteSetStore:
|
||||
"""`exports.use_store`'s store for a remote library: its sets, on the server."""
|
||||
|
||||
def __init__(self, client: RemoteClient):
|
||||
self.client = client
|
||||
|
||||
def read(self) -> dict:
|
||||
return self.client.export_sets()
|
||||
|
||||
def write(self, doc: dict) -> None:
|
||||
self.client.put_export_sets(doc)
|
||||
|
||||
|
||||
class RemotePending:
|
||||
"""`AppState.pending` for a remote library: the SERVER keeps the ledger of
|
||||
converted tracks awaiting Save (and commits, restores and recovers it
|
||||
itself), so on this computer there is nothing to commit or restore — only
|
||||
the server's summary to report, and its "blocking" to honour."""
|
||||
|
||||
items: list = []
|
||||
|
||||
def __init__(self, client: RemoteClient):
|
||||
self.client = client
|
||||
|
||||
def summary(self) -> dict:
|
||||
try:
|
||||
return self.client.stems_pending()
|
||||
except Exception: # noqa: BLE001 — out of reach: nothing known to be pending
|
||||
return {"tracks": 0, "parked": 0, "bytes": 0}
|
||||
|
||||
def blocking(self) -> bool:
|
||||
return bool(self.summary().get("tracks"))
|
||||
|
||||
def swapped(self) -> list:
|
||||
return []
|
||||
|
||||
def restore(self) -> int:
|
||||
return 0
|
||||
|
||||
def commit(self) -> dict:
|
||||
return {}
|
||||
@@ -0,0 +1,159 @@
|
||||
"""This computer's hold on a remote library's session.
|
||||
|
||||
The server lets ONE computer edit at a time (`server/session.py`); this keeps
|
||||
this computer's hold alive with a heartbeat every `HEARTBEAT_SECONDS`, and is
|
||||
the one place that knows how this computer stands:
|
||||
|
||||
connected — holding the session; edits go through
|
||||
reconnecting — a heartbeat failed to reach the server; edits still try
|
||||
(each request walks the addresses again)
|
||||
offline — several in a row failed; read-only until one gets through
|
||||
taken_over — another computer took the session; read-only, for good
|
||||
|
||||
Coming back from `reconnecting` or `offline` needs no new sign-in: the server
|
||||
renews a lapsed lease for the computer that held it, as long as nobody else
|
||||
has taken it meanwhile — and says so (423) if somebody has.
|
||||
|
||||
The heartbeat names the batch running here, so a computer asking to take over
|
||||
is told what it would cancel. Being taken over cancels it (`on_change`).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
|
||||
from ...core.adapter import Unavailable
|
||||
from ...remote_protocol import HEARTBEAT_SECONDS
|
||||
from .client import RemoteClient, SessionLost
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
#: Missed heartbeats in a row before `reconnecting` becomes `offline`.
|
||||
OFFLINE_AFTER = 3
|
||||
|
||||
|
||||
class RemoteSession:
|
||||
def __init__(self, client: RemoteClient, *, batch_probe=None, interval: float = HEARTBEAT_SECONDS,
|
||||
identity: tuple[str, str] | None = None):
|
||||
self.client = client
|
||||
self.interval = interval
|
||||
self._batch_probe = batch_probe or (lambda: None)
|
||||
#: (client_id, machine) — to take the session back when the server has
|
||||
#: forgotten it (a restart) and nobody else holds it.
|
||||
self.identity = identity
|
||||
self.state = "connected"
|
||||
self.machine: str | None = None # who took it over
|
||||
#: The last thing worth telling the user that is not a state ("the
|
||||
#: server restarted"), with a counter so the UI shows each once.
|
||||
self.notice: str | None = None
|
||||
self.notices = 0
|
||||
#: Called after the session was taken back: the library must be re-read.
|
||||
self.on_reacquired = None
|
||||
self._failures = 0
|
||||
self._listeners: list = []
|
||||
self._stop = threading.Event()
|
||||
self._thread: threading.Thread | None = None
|
||||
self._lock = threading.Lock()
|
||||
|
||||
# ---- facts ---------------------------------------------------------------------
|
||||
@property
|
||||
def writable(self) -> bool:
|
||||
return self.state in ("connected", "reconnecting")
|
||||
|
||||
@property
|
||||
def readonly_cause(self) -> str | None:
|
||||
return {"taken_over": "taken_over", "offline": "offline"}.get(self.state)
|
||||
|
||||
def describe(self) -> dict:
|
||||
return {"state": self.state, "via": self.client.via if self.state != "offline" else None,
|
||||
"machine": self.machine, "notice": self.notice, "notices": self.notices}
|
||||
|
||||
def on_change(self, listener) -> None:
|
||||
"""`listener(state)` after every change of state (from the heartbeat thread)."""
|
||||
self._listeners.append(listener)
|
||||
|
||||
# ---- running -------------------------------------------------------------------
|
||||
def start(self) -> None:
|
||||
if self._thread is None:
|
||||
self._thread = threading.Thread(target=self._run, name="konduktor-remote-heartbeat",
|
||||
daemon=True)
|
||||
self._thread.start()
|
||||
|
||||
def stop(self) -> None:
|
||||
self._stop.set()
|
||||
|
||||
def _run(self) -> None:
|
||||
while not self._stop.wait(self.interval):
|
||||
if self.state == "taken_over":
|
||||
return
|
||||
self.beat()
|
||||
|
||||
def beat(self) -> None:
|
||||
try:
|
||||
self.client.heartbeat(self._batch_probe())
|
||||
except SessionLost as ex:
|
||||
self.lost(ex.holder)
|
||||
return
|
||||
except Unavailable:
|
||||
self._failures += 1
|
||||
self._set("offline" if self._failures >= OFFLINE_AFTER else "reconnecting")
|
||||
return
|
||||
except Exception: # noqa: BLE001 — a bad answer is a missed beat, not a crash
|
||||
log.exception("heartbeat failed")
|
||||
self._failures += 1
|
||||
self._set("offline" if self._failures >= OFFLINE_AFTER else "reconnecting")
|
||||
return
|
||||
self._failures = 0
|
||||
self._set("connected")
|
||||
|
||||
def _take_back(self) -> bool:
|
||||
"""The server no longer knows this computer's token and nobody holds the
|
||||
session — it restarted (unsaved edits went with it, an accepted loss).
|
||||
Take the session back without asking, unless the library now holds
|
||||
someone ELSE's unsaved edits: those deserve the Save / Discard question
|
||||
that reopening asks, so then this stays read-only."""
|
||||
if self.identity is None:
|
||||
return False
|
||||
try:
|
||||
got = self.client.acquire(*self.identity)
|
||||
except Exception: # noqa: BLE001 — someone got there first, or no server
|
||||
return False
|
||||
if got.get("pending_edits"):
|
||||
self.client.release()
|
||||
return False
|
||||
if self.on_reacquired is not None:
|
||||
try:
|
||||
self.on_reacquired()
|
||||
except Exception: # noqa: BLE001
|
||||
log.exception("re-reading the library after a reconnect failed")
|
||||
self.notice = "The server restarted — any edits not yet saved there were lost"
|
||||
self.notices += 1
|
||||
self._failures = 0
|
||||
self._set("connected")
|
||||
return True
|
||||
|
||||
def lost(self, holder: dict | None) -> None:
|
||||
"""Another computer holds the session — from a heartbeat, or a command
|
||||
the server refused with 423. Nobody holding it means the server forgot
|
||||
this computer's token (a restart): take it back if that is safe."""
|
||||
if holder is None and self.state != "taken_over" and self._take_back():
|
||||
return
|
||||
self.machine = (holder or {}).get("machine")
|
||||
self._set("taken_over")
|
||||
|
||||
def reached(self) -> None:
|
||||
"""A request got through: whatever the heartbeat last saw, the server is there."""
|
||||
if self.state in ("reconnecting", "offline"):
|
||||
self._failures = 0
|
||||
self._set("connected")
|
||||
|
||||
def _set(self, state: str) -> None:
|
||||
with self._lock:
|
||||
if state == self.state:
|
||||
return
|
||||
self.state = state
|
||||
for listener in list(self._listeners):
|
||||
try:
|
||||
listener(state)
|
||||
except Exception: # noqa: BLE001
|
||||
log.exception("remote session listener failed")
|
||||
@@ -15,7 +15,7 @@ from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
from ...core.adapter import InvalidCommand, NotFound, Unsupported
|
||||
from ...core.adapter import InvalidCommand, NotFound, Unsupported, local_audio_facts
|
||||
from ...core.capabilities import Capabilities
|
||||
from ...core.model import PlaylistNode, Track, TrackCues
|
||||
from ...core.pathmap import PathMapping
|
||||
@@ -131,6 +131,10 @@ class TraktorAdapter:
|
||||
with _translate():
|
||||
self._store.delete_playlist(node_id)
|
||||
|
||||
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
|
||||
with _translate():
|
||||
return self._store.move_playlist(node_id, parent_id, index)
|
||||
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
|
||||
"""Replace a playlist's contents. The adapter resolves each id to its
|
||||
native entry kind, so callers never see Traktor's STEM/TRACK split."""
|
||||
@@ -146,6 +150,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 +387,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 +425,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
|
||||
|
||||
@@ -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"],
|
||||
@@ -73,7 +74,12 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
|
||||
"need a manual Import Cover Art to show up."
|
||||
),
|
||||
),
|
||||
playlists=PlaylistCapabilities(folders=True, smart="read_only", reorder=True),
|
||||
playlists=PlaylistCapabilities(
|
||||
folders=True, smart="read_only", reorder=True,
|
||||
# A playlist's entries are a plain list of PRIMARYKEYs, and Traktor
|
||||
# itself adds a track twice when asked.
|
||||
duplicates=True,
|
||||
),
|
||||
save=SaveCapabilities(
|
||||
app_name="Traktor",
|
||||
library_label="collection.nml",
|
||||
|
||||
@@ -25,7 +25,7 @@ class TraktorDriver:
|
||||
return False
|
||||
return b"<NML" in head and b"VERSION=" in head
|
||||
|
||||
def open(self, path: Path) -> TraktorAdapter:
|
||||
def open(self, path: Path, *, read_only: bool = False) -> TraktorAdapter:
|
||||
return TraktorAdapter(path)
|
||||
|
||||
def detect(self) -> list[dict]:
|
||||
|
||||
@@ -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:
|
||||
"""`<MUSICAL_KEY VALUE>`: 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 `<MUSICAL_KEY>`. 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),
|
||||
|
||||
@@ -22,7 +22,6 @@ import copy
|
||||
import math
|
||||
import threading
|
||||
import uuid as uuidlib
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from traktor_nml_utils import (
|
||||
@@ -36,6 +35,7 @@ from traktor_nml_utils.models.collection import (
|
||||
Entrytype,
|
||||
GridType,
|
||||
Infotype,
|
||||
MusicalKeytype,
|
||||
Locationtype,
|
||||
Nodetype,
|
||||
Playlisttype,
|
||||
@@ -46,16 +46,17 @@ from traktor_nml_utils.models.collection import (
|
||||
)
|
||||
from xsdata.formats.dataclass.serializers import XmlSerializer
|
||||
|
||||
from ...core.adapter import InvalidCommand, SaveOutcome, StemSwapResult
|
||||
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.
|
||||
@@ -71,15 +72,6 @@ class PlaylistError(InvalidCommand):
|
||||
"""
|
||||
|
||||
|
||||
@dataclass
|
||||
class FileTagResult:
|
||||
track_id: str
|
||||
file: str
|
||||
ok: bool
|
||||
status: str # "written" | "file-not-found" | "unsupported-format" | "error"
|
||||
detail: str = ""
|
||||
|
||||
|
||||
class TraktorStore:
|
||||
def __init__(self, nml_path: Path):
|
||||
self.nml_path = Path(nml_path)
|
||||
@@ -87,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] = []
|
||||
@@ -109,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(
|
||||
@@ -164,11 +160,13 @@ class TraktorStore:
|
||||
can_reorder=True,
|
||||
can_rename=True,
|
||||
can_delete=True,
|
||||
can_move=True,
|
||||
)
|
||||
if ntype == "SMARTLIST" or node.smartplaylist is not None:
|
||||
# Rule-based, so it has no static entry list to show or edit.
|
||||
return PlaylistNode(
|
||||
id="sl:" + "/".join(parent_path + [name]), name=name, kind="smart"
|
||||
id="sl:" + "/".join(parent_path + [name]), name=name, kind="smart",
|
||||
can_move=True,
|
||||
)
|
||||
path = parent_path + [name]
|
||||
return PlaylistNode(
|
||||
@@ -179,6 +177,7 @@ class TraktorStore:
|
||||
can_contain_children=True,
|
||||
can_rename=True,
|
||||
can_delete=True,
|
||||
can_move=True,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
@@ -352,6 +351,79 @@ class TraktorStore:
|
||||
self._note("playlist-delete", node.name)
|
||||
self.dirty = True
|
||||
|
||||
def _find_node(self, node_id: str) -> Nodetype:
|
||||
"""Any node by its id: a playlist's UUID, a folder's `fld:` path or a
|
||||
smart playlist's `sl:` path (its folder path plus its own name)."""
|
||||
if node_id.startswith("fld:"):
|
||||
return self._find_folder(node_id)
|
||||
if node_id.startswith("sl:"):
|
||||
*folders, name = node_id[len("sl:"):].split("/")
|
||||
parent = self._find_folder("fld:" + "/".join(folders) if folders else None)
|
||||
match = next(
|
||||
(c for c in self._children(parent)
|
||||
if (c.type == "SMARTLIST" or c.smartplaylist is not None) and c.name == name),
|
||||
None,
|
||||
)
|
||||
if match is None:
|
||||
raise PlaylistError(f"Smart playlist not found: {node_id}")
|
||||
return match
|
||||
node = self._find_playlist_node(node_id)
|
||||
if node is None:
|
||||
raise PlaylistError(f"Playlist not found: {node_id}")
|
||||
return node
|
||||
|
||||
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
|
||||
"""Move a node to `index` among `parent_id`'s children (counted without
|
||||
it) and return its id afterwards — a folder's and a smart playlist's id
|
||||
is their path of names, so moving one changes it (and its subtree's).
|
||||
|
||||
A folder or smart playlist landing beside a namesake of its own kind is
|
||||
refused, as rename refuses it: the two paths would be one, and one of
|
||||
them unaddressable. Playlists are UUIDs, so their names may repeat."""
|
||||
with self._lock:
|
||||
node = self._find_node(node_id)
|
||||
if node is self._root():
|
||||
raise PlaylistError("Cannot move the root folder")
|
||||
dest = self._find_folder(parent_id)
|
||||
if dest is node or any(n is dest for n in self._iter_nodes(node)):
|
||||
raise PlaylistError("A folder cannot be moved into itself")
|
||||
is_folder = node.playlist is None and node.smartplaylist is None and (
|
||||
node.type or "FOLDER") == "FOLDER"
|
||||
is_smart = node.type == "SMARTLIST" or node.smartplaylist is not None
|
||||
if is_folder or is_smart:
|
||||
kind = "folder" if is_folder else "smart playlist"
|
||||
for c in self._children(dest):
|
||||
same_kind = (
|
||||
(c.type or "FOLDER") == "FOLDER" and c.playlist is None
|
||||
and c.smartplaylist is None
|
||||
) if is_folder else (c.type == "SMARTLIST" or c.smartplaylist is not None)
|
||||
if c is not node and same_kind and c.name == node.name:
|
||||
raise PlaylistError(f'There is already a {kind} called "{node.name}" there')
|
||||
source = self._find_parent_of(node)
|
||||
if source is None:
|
||||
raise PlaylistError("Cannot move a top-level node")
|
||||
siblings = [c for c in self._children(dest) if c is not node]
|
||||
index = max(0, min(int(index), len(siblings)))
|
||||
if source is dest and self._children(dest).index(node) == index:
|
||||
return self._node_id(node, parent_id) # already there
|
||||
source.subnodes.node.remove(node)
|
||||
source.subnodes.count = len(source.subnodes.node)
|
||||
if dest.subnodes is None:
|
||||
dest.subnodes = Subnodestype(node=[], count=0)
|
||||
dest.subnodes.node.insert(index, node)
|
||||
dest.subnodes.count = len(dest.subnodes.node)
|
||||
self._note("playlist-move", node.name)
|
||||
self.dirty = True
|
||||
return self._node_id(node, parent_id)
|
||||
|
||||
def _node_id(self, node: Nodetype, parent_id: str | None) -> str:
|
||||
"""The id `_to_model` gives `node` inside the folder `parent_id`."""
|
||||
if node.playlist is not None:
|
||||
return node.playlist.uuid
|
||||
prefix = parent_id[len("fld:"):] if parent_id and parent_id.startswith("fld:") else ""
|
||||
tag = "sl:" if (node.type == "SMARTLIST" or node.smartplaylist is not None) else "fld:"
|
||||
return tag + "/".join(p for p in (prefix, node.name or "(unnamed)") if p)
|
||||
|
||||
def set_entries(self, playlist_uuid: str, entries: list[tuple[str, str]]) -> None:
|
||||
with self._lock:
|
||||
node = self._find_playlist_node(playlist_uuid)
|
||||
@@ -409,6 +481,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 `<MUSICAL_KEY>`."""
|
||||
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.
|
||||
@@ -438,7 +573,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(
|
||||
@@ -453,7 +588,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".
|
||||
@@ -479,6 +614,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,
|
||||
)
|
||||
@@ -998,6 +1139,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:
|
||||
@@ -1293,7 +1443,7 @@ class TraktorStore:
|
||||
if swap.mode not in ("repoint", "add"):
|
||||
raise PlaylistError(f"Unknown stem swap mode: {swap.mode}")
|
||||
seen_ids.add(swap.track_id)
|
||||
loc = os_path_to_location(Path(swap.stem_path))
|
||||
loc = os_path_to_location(self._stored(Path(swap.stem_path)))
|
||||
new_key = "".join(x or "" for x in loc)
|
||||
if new_key in self._entry_by_key or new_key in new_keys:
|
||||
raise PlaylistError(
|
||||
|
||||
@@ -28,11 +28,12 @@ import os
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from . import __version__, adapters, history, library_id, prefs # noqa: F401 — registers adapters
|
||||
from . import adapters, library_id, prefs # noqa: F401 — registers adapters
|
||||
from .core import registry
|
||||
from .core.adapter import LibraryAdapter
|
||||
from .core.pathmap import PathMapping
|
||||
from .relocation import RelocationCheck
|
||||
from .services import LibraryServices, LocalServices
|
||||
|
||||
|
||||
class AppState:
|
||||
@@ -61,6 +62,18 @@ class AppState:
|
||||
# and what the last open's crash recovery did about any left over.
|
||||
self.pending = None
|
||||
self.recovery: dict | None = None
|
||||
# Where this library's history (and, for a remote, its export sets and
|
||||
# ledger) are kept — see `services.py`.
|
||||
self.services: LibraryServices | None = None
|
||||
# The open remote's connection (`adapters/remote/session.py`), or None
|
||||
# for a library on this computer.
|
||||
self.remote = None
|
||||
# …and the saved remote it was opened through (`adapters/remote/config.py`).
|
||||
self.remote_config = None
|
||||
# Called with the adapter at the end of every open (and so after a
|
||||
# restore, which reopens): how a Konduktor SERVER re-applies the path
|
||||
# mapping its configuration names, which lives in no prefs file.
|
||||
self.open_hooks: list = []
|
||||
|
||||
@property
|
||||
def loaded(self) -> bool:
|
||||
@@ -79,7 +92,7 @@ class AppState:
|
||||
rests on, and an adapter is the thing that knows whether it is true —
|
||||
so it is asserted here rather than assumed everywhere else.
|
||||
"""
|
||||
adapter = registry.open_library(path)
|
||||
adapter = registry.open_library(path, read_only=True)
|
||||
if adapter.capabilities().writable:
|
||||
if hasattr(adapter, "close"):
|
||||
try:
|
||||
@@ -87,7 +100,7 @@ class AppState:
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
raise ValueError(
|
||||
f"{path} is a writable library; only read-only sources "
|
||||
f"{path} cannot be opened read-only; only a library that can "
|
||||
"(such as a OneLibrary drive) can be opened as a source"
|
||||
)
|
||||
self.close_source()
|
||||
@@ -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()
|
||||
|
||||
|
||||
@@ -28,6 +28,21 @@ from .pathmap import PathMapping
|
||||
from .relocate import PathGroup
|
||||
|
||||
|
||||
@dataclass
|
||||
class FileTagResult:
|
||||
"""One audio-file tag write a save made — the `SaveOutcome.tag_results` item.
|
||||
|
||||
Promoted from the Traktor store when OneLibrary became the second platform
|
||||
that writes edited fields into the audio files themselves.
|
||||
"""
|
||||
|
||||
track_id: str
|
||||
file: str
|
||||
ok: bool
|
||||
status: str # "written" | "file-not-found" | "unsupported-format" | "error"
|
||||
detail: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class SaveOutcome:
|
||||
"""What a save produced, in terms every platform can answer.
|
||||
@@ -50,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.
|
||||
@@ -78,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)
|
||||
@@ -138,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."""
|
||||
@@ -157,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: ...
|
||||
@@ -169,6 +247,12 @@ class LibraryAdapter(Protocol):
|
||||
def create_folder(self, name: str, parent_id: str | None = None) -> str: ...
|
||||
def rename_playlist(self, node_id: str, name: str) -> None: ...
|
||||
def delete_playlist(self, node_id: str) -> None: ...
|
||||
# Move a node (playlist, folder or smart playlist) to `index` among
|
||||
# `parent_id`'s children (None = the top level), counted with the moved
|
||||
# node left out. Returns the node's id AFTER the move: an id is opaque, and
|
||||
# on a platform that addresses a folder by its path it changes. A folder
|
||||
# cannot go into itself or a descendant (InvalidCommand).
|
||||
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str: ...
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: ...
|
||||
|
||||
# ---- commands: adding tracks ----------------------------------------
|
||||
@@ -185,11 +269,18 @@ class LibraryAdapter(Protocol):
|
||||
# is touched, so a cancel leaves it as it was. Gated on
|
||||
# `capabilities().tracks.addable`.
|
||||
def add_tracks(self, items: list["NewTrack"], *, checkpoint=None) -> list[str]: ...
|
||||
# OPTIONAL, where `capabilities().tracks.places_audio`: the library decides
|
||||
# where added audio goes. `place_audio(source, track)` returns the path the
|
||||
# importer must COPY `source` to (which becomes `NewTrack.audio_path`), or
|
||||
# None when the file is already where the library can use it in place;
|
||||
# `audio_home()` is where that audio lands, for the free-space check.
|
||||
# (A protocol member would make every adapter implement them.)
|
||||
|
||||
# Remove tracks from the library — and so from every playlist, since an
|
||||
# entry naming a track the library no longer has is a dangling reference.
|
||||
# Never touches audio files. Returns how many were removed; gated on
|
||||
# `capabilities().tracks.removable`.
|
||||
# Never touches audio files, except where `tracks.places_audio` (a stick's
|
||||
# audio belongs to its library): there the file goes too, at Save. Returns
|
||||
# how many were removed; gated on `capabilities().tracks.removable`.
|
||||
def remove_tracks(self, track_ids: list[str]) -> int: ...
|
||||
|
||||
# Swap converted stem files into the library (see `StemSwap`), all at once:
|
||||
@@ -201,6 +292,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: ...
|
||||
|
||||
@@ -234,7 +329,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 —
|
||||
@@ -274,7 +374,11 @@ class LibraryDriver(Protocol):
|
||||
selects: str
|
||||
|
||||
def can_open(self, path: Path) -> bool: ...
|
||||
def open(self, path: Path) -> LibraryAdapter: ...
|
||||
# `read_only` opens a library only to READ it, alongside the loaded one (the
|
||||
# sidebar's Devices). An adapter that honours it reports `writable=False`
|
||||
# with cause `browsing`; one that ignores it still reports writable, and the
|
||||
# caller — `AppState.open_source` — refuses it, so ignoring is safe.
|
||||
def open(self, path: Path, *, read_only: bool = False) -> LibraryAdapter: ...
|
||||
# OPTIONAL. What to call an opened library on screen. Only the adapter can
|
||||
# answer for a platform where one library has more than one valid path —
|
||||
# the filename is otherwise assumed, and that assumption is wrong for a
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
"""The analysis a platform that ANALYSES what it adds needs for one new track.
|
||||
|
||||
Rekordbox draws a new track's waveform and grid from its ANLZ files, so adding a
|
||||
track means decoding it once: the waveform measured on the platform's own clock
|
||||
(`lead`, read from the file's header by that platform) plus a detected grid and
|
||||
key when the track brings none. One definition, used both by the adapter (a library on
|
||||
this computer) and by the client of a library held by a server — which never
|
||||
decodes audio, so the client measures its own copy and sends the result
|
||||
(`PreparedAnalysis`) with the track.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
from .adapter import PreparedAnalysis
|
||||
from .model import GridMarker
|
||||
|
||||
|
||||
def prepare(path: Path, *, lead: float, detect: bool = True,
|
||||
detect_key: bool = False) -> PreparedAnalysis:
|
||||
"""Decode `path` once: its waveform at `lead`, and (with `detect`) a grid,
|
||||
(with `detect_key`) a key."""
|
||||
from . import grid_detect, waveform
|
||||
|
||||
samples = waveform.decode(Path(path))
|
||||
measured = waveform.analyse_samples(samples, lead=lead)
|
||||
markers: list[GridMarker] = []
|
||||
if detect and samples is not None:
|
||||
try:
|
||||
found = grid_detect.detect_grid(str(path), y=samples, sr=waveform.SR)
|
||||
markers = [GridMarker(start=found.anchor, bpm=found.bpm)]
|
||||
except ValueError:
|
||||
pass # no pulse to fit (a one-shot, silence): no grid
|
||||
key = None
|
||||
if detect_key and samples is not None:
|
||||
from . import key_detect
|
||||
|
||||
try:
|
||||
key = key_detect.detect_key_samples(samples, waveform.SR)
|
||||
except Exception: # noqa: BLE001 - a missing key is not worth failing an add over
|
||||
logging.getLogger(__name__).warning("key detection failed", exc_info=True)
|
||||
return PreparedAnalysis(measured=measured, markers=markers, key=key)
|
||||
|
||||
|
||||
def with_key(track, key):
|
||||
"""`track` (a generic `Track`) with the detected `key` if it has none of its
|
||||
own. A key the track already carries (its tags, its source library) is
|
||||
never second-guessed."""
|
||||
if key is None or getattr(track, "key_wheel", None) is not None:
|
||||
return track
|
||||
return track.model_copy(update={"key": key.name, "key_wheel": key.wheel, "key_mode": key.mode})
|
||||
@@ -22,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:
|
||||
|
||||
@@ -22,7 +22,15 @@ from pydantic import BaseModel
|
||||
# permanent refusal protecting their other machines.
|
||||
# `not_in_library` is a folder of loose files being browsed: nothing there is a
|
||||
# library to write to, and the way to edit one is to add it to the collection.
|
||||
ReadonlyCause = Literal["platform_incomplete", "cloud_synced", "not_in_library"]
|
||||
# `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.
|
||||
# `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"]
|
||||
@@ -61,26 +69,53 @@ class TrackCapabilities(BaseModel):
|
||||
editable_fields: list[str] = []
|
||||
media_kinds: list[MediaKind] = ["audio"]
|
||||
# Tracks can be removed from the library (and so from its playlists). The
|
||||
# audio file is never touched either way.
|
||||
# audio file is never touched — except where `places_audio`: a library that
|
||||
# owns where its audio lives (a stick) deletes it with the track, at Save.
|
||||
removable: bool = False
|
||||
# Tracks can be added to the library (`add_tracks`): an import from a
|
||||
# device, or browsed files added to the collection.
|
||||
addable: bool = False
|
||||
# The LIBRARY decides where added audio goes (`place_audio`), so the user is
|
||||
# neither asked "copy or leave in place?" nor for a destination: a OneLibrary
|
||||
# stick can only point at files on itself, and lays them out as rekordbox
|
||||
# does. False: the user chooses, as for a desktop collection.
|
||||
places_audio: bool = False
|
||||
# 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):
|
||||
folders: bool = False
|
||||
smart: Literal["none", "read_only"] = "none"
|
||||
reorder: bool = False
|
||||
# A playlist can hold the same track more than once. Where it cannot, a
|
||||
# drop of tracks already there skips them rather than asking.
|
||||
duplicates: 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):
|
||||
@@ -95,6 +130,9 @@ class SaveCapabilities(BaseModel):
|
||||
library_label: str
|
||||
overwrite_risk: Literal["none", "on_exit", "while_running"] = "none"
|
||||
history: bool = True
|
||||
# The library was written by one of Konduktor's EXPORT sets, whose next run
|
||||
# replaces it — so an edit made here directly is undone by the next export.
|
||||
managed_by_export: bool = False
|
||||
|
||||
|
||||
class Capabilities(BaseModel):
|
||||
@@ -114,4 +152,5 @@ class Capabilities(BaseModel):
|
||||
grid: GridCapabilities = GridCapabilities()
|
||||
tracks: TrackCapabilities = TrackCapabilities()
|
||||
playlists: PlaylistCapabilities = PlaylistCapabilities()
|
||||
paths: PathCapabilities = PathCapabilities()
|
||||
save: SaveCapabilities
|
||||
@@ -150,6 +150,11 @@ class FolderSource:
|
||||
def audio_path(self, track_id: str) -> Path | None:
|
||||
return Path(track_id) if track_id in self._by_id else None
|
||||
|
||||
def audio_facts(self, track_ids: list[str]):
|
||||
from .adapter import local_audio_facts
|
||||
|
||||
return local_audio_facts(self, track_ids)
|
||||
|
||||
def playlist_tree(self) -> list[PlaylistNode]:
|
||||
return []
|
||||
|
||||
|
||||
@@ -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]:
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Marker-level beatgrid commands, for a store whose one primitive is "replace".
|
||||
|
||||
A platform that stores the grid as a flat list of beats (Rekordbox's `PQTZ`, and
|
||||
so OneLibrary's) has no native "move this marker": every marker-level command is
|
||||
a read-modify-replace of the generic marker list. Promoted here when OneLibrary
|
||||
became the second store needing exactly that, so "where does a moved marker
|
||||
clamp" cannot mean two things. (Traktor's store has markers natively and keeps
|
||||
its own, companion-cue-aware versions.)
|
||||
|
||||
A store using it provides `current_markers(track_id)` and
|
||||
`replace_grid(track_id, markers)`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .adapter import InvalidCommand, NotFound
|
||||
from .model import GridMarker
|
||||
|
||||
|
||||
class ReplaceGridCommands:
|
||||
def current_markers(self, track_id: str) -> list[GridMarker]: # pragma: no cover
|
||||
raise NotImplementedError
|
||||
|
||||
def replace_grid(self, track_id: str, markers: list[GridMarker]) -> None: # pragma: no cover
|
||||
raise NotImplementedError
|
||||
|
||||
def delete_grid(self, track_id: str) -> None:
|
||||
self.replace_grid(track_id, [])
|
||||
|
||||
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> None:
|
||||
markers = self.current_markers(track_id)
|
||||
if bpm is None:
|
||||
# Inherit the tempo governing this point, like Traktor's add does.
|
||||
governing = [m for m in markers if m.start <= start_sec]
|
||||
bpm = governing[-1].bpm if governing else (markers[0].bpm if markers else None)
|
||||
if not bpm:
|
||||
raise InvalidCommand("The first marker on an ungridded track needs a tempo")
|
||||
if any(abs(m.start - start_sec) < 0.001 for m in markers):
|
||||
raise InvalidCommand("There is already a marker here")
|
||||
markers.append(GridMarker(start=float(start_sec), bpm=float(bpm)))
|
||||
self.replace_grid(track_id, markers)
|
||||
|
||||
def _marker_at(self, track_id: str, index: int) -> tuple[list, int]:
|
||||
markers = self.current_markers(track_id)
|
||||
if not 0 <= index < len(markers):
|
||||
raise NotFound(f"No grid marker {index}")
|
||||
return markers, index
|
||||
|
||||
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> None:
|
||||
markers, i = self._marker_at(track_id, index)
|
||||
# Clamp between neighbours so the list cannot reorder under the caller.
|
||||
low = markers[i - 1].start + 0.001 if i > 0 else 0.0
|
||||
high = markers[i + 1].start - 0.001 if i + 1 < len(markers) else None
|
||||
target = max(low, float(start_sec))
|
||||
if high is not None:
|
||||
target = min(target, high)
|
||||
markers[i] = markers[i].model_copy(update={"start": target})
|
||||
self.replace_grid(track_id, markers)
|
||||
|
||||
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> None:
|
||||
markers, i = self._marker_at(track_id, index)
|
||||
if bpm <= 0:
|
||||
raise InvalidCommand(f"A tempo must be positive, got {bpm}")
|
||||
markers[i] = markers[i].model_copy(update={"bpm": float(bpm)})
|
||||
self.replace_grid(track_id, markers)
|
||||
|
||||
def delete_grid_marker(self, track_id: str, index: int) -> None:
|
||||
markers, i = self._marker_at(track_id, index)
|
||||
del markers[i]
|
||||
self.replace_grid(track_id, markers)
|
||||
@@ -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)
|
||||
@@ -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<i>.<param>`, 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)
|
||||
Binary file not shown.
@@ -130,6 +130,9 @@ class PlaylistNode(BaseModel):
|
||||
can_rename: bool = False
|
||||
can_delete: bool = False
|
||||
can_contain_children: bool = False # a valid parent for a new playlist
|
||||
# Can be dragged elsewhere in the tree (`move_playlist`): reordered among
|
||||
# its siblings or moved into another folder.
|
||||
can_move: bool = False
|
||||
|
||||
|
||||
PlaylistNode.model_rebuild()
|
||||
@@ -194,6 +197,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 +214,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
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -105,6 +105,8 @@ class TrackIndex:
|
||||
if (t.artist and ql in t.artist.lower())
|
||||
or (t.title and ql in t.title.lower())
|
||||
or (t.album and ql in t.album.lower())
|
||||
or (t.comment and ql in t.comment.lower())
|
||||
or (t.comment2 and ql in t.comment2.lower())
|
||||
]
|
||||
if genre:
|
||||
items = [t for t in items if t.genre == genre]
|
||||
|
||||
@@ -44,8 +44,8 @@ def driver_for(path: Path) -> LibraryDriver:
|
||||
raise LibraryNotSupported(f"No DJ library Konduktor recognises at {path}")
|
||||
|
||||
|
||||
def open_library(path: Path):
|
||||
return driver_for(path).open(path)
|
||||
def open_library(path: Path, *, read_only: bool = False):
|
||||
return driver_for(path).open(path, read_only=read_only)
|
||||
|
||||
|
||||
def describe(path: Path) -> dict:
|
||||
|
||||
@@ -356,17 +356,14 @@ def stem_layout(path: Path | str) -> list[dict] | None:
|
||||
MP3 entries in the real collection carry that element."""
|
||||
import json
|
||||
|
||||
import av
|
||||
|
||||
path = Path(path)
|
||||
try:
|
||||
raw = read_stem_box(path)
|
||||
if raw is None:
|
||||
return None
|
||||
return None # not a stem file: nothing to count, no decoder needed
|
||||
stems = json.loads(raw).get("stems") or []
|
||||
with av.open(str(path), metadata_errors="ignore") as c:
|
||||
streams = len(c.streams.audio)
|
||||
except (OSError, ValueError, av.FFmpegError):
|
||||
streams = _audio_stream_count(path)
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
if not stems or streams < 1 + len(stems):
|
||||
return None
|
||||
@@ -374,6 +371,39 @@ def stem_layout(path: Path | str) -> list[dict] | None:
|
||||
for i, s in enumerate(stems)]
|
||||
|
||||
|
||||
def _audio_stream_count(path: Path) -> int:
|
||||
"""How many audio streams an MP4 holds. Through PyAV where it is installed;
|
||||
otherwise (the Konduktor SERVER ships without it — it never decodes) by
|
||||
counting the `trak`s whose handler is `soun`, which is what PyAV counts."""
|
||||
try:
|
||||
import av
|
||||
except ImportError:
|
||||
av = None
|
||||
if av is not None:
|
||||
try:
|
||||
with av.open(str(path), metadata_errors="ignore") as c:
|
||||
return len(c.streams.audio)
|
||||
except av.FFmpegError as ex:
|
||||
raise ValueError(str(ex))
|
||||
size = path.stat().st_size
|
||||
count = 0
|
||||
with open(path, "rb") as f:
|
||||
moov = _find(f, 0, size, b"moov")
|
||||
if moov is None:
|
||||
return 0
|
||||
for kind, body, end in mp4_edit._boxes(f, moov[1], moov[2]):
|
||||
if kind != b"trak":
|
||||
continue
|
||||
mdia = _find(f, body, end, b"mdia")
|
||||
hdlr = _find(f, mdia[1], mdia[2], b"hdlr") if mdia else None
|
||||
if hdlr is None:
|
||||
continue
|
||||
f.seek(hdlr[1] + 8) # version/flags (4) + pre_defined (4), then the type
|
||||
if f.read(4) == b"soun":
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
def _traktor_json(v) -> str:
|
||||
if isinstance(v, bool):
|
||||
return "true" if v else "false"
|
||||
|
||||
@@ -341,11 +341,15 @@ def plan(adapter, export_set) -> ExportPlan:
|
||||
resolved = exports.resolve(adapter, export_set)
|
||||
tracks = [t for t in (adapter.track(i) for i in resolved.track_ids) if t is not None]
|
||||
|
||||
# The source is the adapter's `audio_path`, never `Track.filepath`: that is
|
||||
# a DISPLAY path, which on Traktor omits the volume and ignores the active
|
||||
# The source is the adapter's file, never `Track.filepath`: that is a
|
||||
# DISPLAY path, which on Traktor omits the volume and ignores the active
|
||||
# path mapping — so every track off the boot volume (or on a remapped
|
||||
# Windows drive) read as missing and the export was "empty".
|
||||
sources = {t.id: adapter.audio_path(t.id) for t in tracks}
|
||||
# Windows drive) read as missing and the export was "empty". Its FACTS,
|
||||
# not `audio_path`: planning must not read a file, and on a library held
|
||||
# by a server reading one means downloading it. `run` fetches each file
|
||||
# only when it copies it.
|
||||
facts = adapter.audio_facts([t.id for t in tracks])
|
||||
sources = {tid: Path(f.key) for tid, f in facts.items()}
|
||||
|
||||
# Mirror relative to the deepest shared folder, so the export carries the
|
||||
# user's structure without carrying their home directory.
|
||||
@@ -355,16 +359,10 @@ def plan(adapter, export_set) -> ExportPlan:
|
||||
previous = _previous_copies(destination)
|
||||
claimed: set[Path] = set()
|
||||
for track in tracks:
|
||||
source = sources[track.id]
|
||||
exists = False
|
||||
size = mtime_ns = 0
|
||||
try:
|
||||
exists = bool(source and source.is_file())
|
||||
if exists:
|
||||
st = source.stat()
|
||||
size, mtime_ns = st.st_size, st.st_mtime_ns
|
||||
except OSError:
|
||||
exists = False
|
||||
source = sources.get(track.id)
|
||||
fact = facts.get(track.id)
|
||||
exists = fact is not None
|
||||
size, mtime_ns = (fact.size, fact.mtime_ns) if fact else (0, 0)
|
||||
planned = PlannedTrack(
|
||||
track_id=track.id,
|
||||
title=track.title or (source.name if source else track.id),
|
||||
@@ -519,7 +517,10 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict:
|
||||
done += n
|
||||
handle.progress(done=done)
|
||||
|
||||
copy_file(planned.source_path, partial, handle, advance)
|
||||
# The file to READ: on this machine that is the source itself;
|
||||
# on a library held by a server, a downloaded copy of it.
|
||||
local = adapter.audio_path(planned.track_id) or planned.source_path
|
||||
copy_file(local, partial, handle, advance)
|
||||
os.replace(partial, target)
|
||||
payload_tracks.append(
|
||||
ExportTrack(
|
||||
|
||||
@@ -123,8 +123,39 @@ def _store_path(library_id: str) -> Path:
|
||||
return paths.app_data_dir() / "exports" / f"{library_id}.json"
|
||||
|
||||
|
||||
# A library whose sets are kept somewhere other than this computer's app-data —
|
||||
# a library held by a server keeps them beside itself, so every computer that
|
||||
# opens it sees the same sets. Each store reads and writes the WHOLE document
|
||||
# (`{"library_id", "sets"}`); everything else here is unchanged by where it is.
|
||||
_STORES: dict[str, object] = {}
|
||||
|
||||
|
||||
def use_store(library_id: str, store) -> None:
|
||||
"""Keep `library_id`'s sets in `store` (`read() -> dict`, `write(dict)`);
|
||||
None returns them to this computer's app-data."""
|
||||
if store is None:
|
||||
_STORES.pop(library_id, None)
|
||||
else:
|
||||
_STORES[library_id] = store
|
||||
|
||||
|
||||
def _read_doc(library_id: str) -> dict:
|
||||
store = _STORES.get(library_id)
|
||||
if store is not None:
|
||||
return store.read()
|
||||
return paths.read_json(_store_path(library_id), {})
|
||||
|
||||
|
||||
def _write_doc(library_id: str, doc: dict) -> None:
|
||||
store = _STORES.get(library_id)
|
||||
if store is not None:
|
||||
store.write(doc)
|
||||
else:
|
||||
paths.write_json(_store_path(library_id), doc)
|
||||
|
||||
|
||||
def _load(library_id: str) -> dict[str, ExportSet]:
|
||||
data = paths.read_json(_store_path(library_id), {})
|
||||
data = _read_doc(library_id)
|
||||
raw = data.get("sets") if isinstance(data, dict) else None
|
||||
out: dict[str, ExportSet] = {}
|
||||
if isinstance(raw, dict):
|
||||
@@ -158,8 +189,8 @@ def _targets(values: dict) -> list[str]:
|
||||
|
||||
|
||||
def _save(library_id: str, sets: dict[str, ExportSet]) -> None:
|
||||
paths.write_json(
|
||||
_store_path(library_id),
|
||||
_write_doc(
|
||||
library_id,
|
||||
{"library_id": library_id, "sets": {k: v.as_dict() for k, v in sets.items()}},
|
||||
)
|
||||
|
||||
|
||||
@@ -112,18 +112,19 @@ def _key(path: Path) -> str:
|
||||
def _existing_files(dest) -> dict[str, str]:
|
||||
"""Every audio file the destination points at → its track id.
|
||||
|
||||
Resolved through the adapter's own `audio_path`, which is the only answer
|
||||
Resolved through the adapter's own `audio_facts`, which is the only answer
|
||||
that includes the volume and the active path mapping; the projected
|
||||
`filepath` is a display string and is not good enough to match on.
|
||||
`filepath` is a display string and is not good enough to match on. Facts,
|
||||
not `audio_path`: on a library held by a server that would download every
|
||||
file it has.
|
||||
"""
|
||||
out: dict[str, str] = {}
|
||||
for track in dest.tracks:
|
||||
try:
|
||||
path = dest.audio_path(track.id)
|
||||
except Exception: # noqa: BLE001
|
||||
path = None
|
||||
if path is not None:
|
||||
out.setdefault(_key(path), track.id)
|
||||
try:
|
||||
facts = dest.audio_facts([t.id for t in dest.tracks])
|
||||
except Exception: # noqa: BLE001
|
||||
return out
|
||||
for track_id, fact in facts.items():
|
||||
out.setdefault(_key(Path(fact.key)), track_id)
|
||||
return out
|
||||
|
||||
|
||||
@@ -216,7 +217,16 @@ def _all_playlists(source) -> list[tuple[str, str]]:
|
||||
return out
|
||||
|
||||
|
||||
def free_bytes(path: Path) -> int | None:
|
||||
def free_bytes(path: Path, dest=None) -> int | None:
|
||||
"""Free space where the audio will land. On the DESTINATION's machine: a
|
||||
library held by a server reports its own disk (`free_space`), since the
|
||||
path names a folder there, not here."""
|
||||
remote_free = getattr(dest, "free_space", None) if dest is not None and uploads_audio(dest) else None
|
||||
if remote_free is not None:
|
||||
try:
|
||||
return remote_free(str(path))
|
||||
except Exception: # noqa: BLE001 — unknown is not "full"
|
||||
return None
|
||||
try:
|
||||
target = path if path.exists() else path.parent
|
||||
return shutil.disk_usage(target).free
|
||||
@@ -224,6 +234,15 @@ def free_bytes(path: Path) -> int | None:
|
||||
return None
|
||||
|
||||
|
||||
def uploads_audio(dest) -> bool:
|
||||
"""Whether added audio is SENT to the machine holding the library (a
|
||||
server) rather than copied on this one — `tracks.audio_destination`."""
|
||||
try:
|
||||
return dest.capabilities().tracks.audio_destination == "library" and hasattr(dest, "upload_audio")
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
|
||||
|
||||
def _unique_target(folder: Path, name: str, taken: set[str]) -> Path:
|
||||
"""A free filename in `folder`, suffixing on collision.
|
||||
|
||||
@@ -290,9 +309,21 @@ def run(
|
||||
destination and nothing to roll back. `into_playlist` appends every planned
|
||||
track — the new ones and those the destination already held — to one of the
|
||||
destination's playlists before the save, so both land in one commit.
|
||||
|
||||
A destination that PLACES ITS OWN AUDIO (`tracks.places_audio`: a OneLibrary
|
||||
stick) overrides both: `dest.place_audio` names each copy's target, or says
|
||||
the file can be used where it is, and `reference`/`plan.destination` are
|
||||
ignored.
|
||||
"""
|
||||
destination = plan.destination
|
||||
if not reference:
|
||||
places = places_audio(dest)
|
||||
# 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)
|
||||
|
||||
@@ -306,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
|
||||
|
||||
@@ -318,11 +351,31 @@ def run(
|
||||
for planned in importable:
|
||||
handle.raise_if_cancelled()
|
||||
assert planned.source_path is not None
|
||||
if reference:
|
||||
if places:
|
||||
target = dest.place_audio(planned.source_path, source.track(planned.track_id))
|
||||
if target is None:
|
||||
copied.append((planned, planned.source_path))
|
||||
continue
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
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}")
|
||||
target = _unique_target(destination, planned.source_path.name, taken)
|
||||
created.append(target) # registered BEFORE the write, so a cancel
|
||||
copy_file(planned.source_path, target, handle, bump) # mid-file is cleaned
|
||||
copied.append((planned, target))
|
||||
@@ -396,9 +449,34 @@ 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
|
||||
|
||||
|
||||
def places_audio(dest) -> bool:
|
||||
"""Whether the destination decides where added audio goes (a stick)."""
|
||||
try:
|
||||
return bool(dest.capabilities().tracks.places_audio) and hasattr(dest, "place_audio")
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
|
||||
|
||||
def placed_bytes(dest, plan: ImportPlan) -> int:
|
||||
"""What an import into a self-placing library will COPY: a file already under
|
||||
its `audio_home()` is used in place and costs nothing."""
|
||||
home = dest.audio_home()
|
||||
total = 0
|
||||
for planned in plan.importable:
|
||||
path = planned.source_path
|
||||
if path is not None and not path.resolve().is_relative_to(home.resolve()):
|
||||
total += planned.size
|
||||
return total
|
||||
|
||||
|
||||
def _save(dest):
|
||||
"""Save through AppState so the version-history commit is not skipped."""
|
||||
from .app_state import STATE
|
||||
|
||||
+526
-82
@@ -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,
|
||||
@@ -85,6 +92,8 @@ from .schemas import (
|
||||
RemapResult,
|
||||
RenamePlaylist,
|
||||
SaveResult,
|
||||
AddEntries,
|
||||
MovePlaylist,
|
||||
SetEntries,
|
||||
SourceCandidate,
|
||||
SourceStatus,
|
||||
@@ -137,7 +146,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 +212,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 +857,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 +873,7 @@ def _library_info() -> LibraryInfo:
|
||||
path=str(STATE.path),
|
||||
display_name=display_name,
|
||||
version=caps.version,
|
||||
remote=remote,
|
||||
)
|
||||
|
||||
|
||||
@@ -723,6 +904,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 +928,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 +1008,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 +1069,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 +1141,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 ------------------------------------
|
||||
|
||||
|
||||
@@ -999,6 +1229,7 @@ def create_playlist(body: CreatePlaylist) -> PlaylistNode:
|
||||
can_reorder=True,
|
||||
can_rename=True,
|
||||
can_delete=True,
|
||||
can_move=True,
|
||||
)
|
||||
|
||||
|
||||
@@ -1013,6 +1244,7 @@ def create_folder(body: CreatePlaylist) -> PlaylistNode:
|
||||
can_contain_children=True,
|
||||
can_rename=True,
|
||||
can_delete=True,
|
||||
can_move=True,
|
||||
)
|
||||
|
||||
|
||||
@@ -1037,17 +1269,35 @@ def set_entries(playlist_uuid: str, body: SetEntries) -> dict:
|
||||
return {"status": "updated", "id": playlist_uuid, "count": n}
|
||||
|
||||
|
||||
@app.post("/api/playlists/move")
|
||||
def move_playlist(body: MovePlaylist) -> dict:
|
||||
"""Move a playlist, folder or smart playlist in the tree. Answers the
|
||||
node's id AFTER the move, which on some platforms is not the one sent."""
|
||||
new_id = require_adapter().move_playlist(body.node_id, body.parent_id, body.index)
|
||||
return {"status": "moved", "id": new_id}
|
||||
|
||||
|
||||
@app.post("/api/playlists/{playlist_uuid}/add")
|
||||
def add_entries(playlist_uuid: str, body: SetEntries) -> dict:
|
||||
"""Append tracks to a playlist (skips ids already present)."""
|
||||
def add_entries(playlist_uuid: str, body: AddEntries) -> dict:
|
||||
"""Append tracks to a playlist. Tracks already there are skipped, added
|
||||
again, or — `duplicates="ask"` — counted with nothing changed (see
|
||||
`AddEntries`). `duplicates` in the answer is how many there were."""
|
||||
a = require_adapter()
|
||||
current = a.playlist_entries(playlist_uuid)
|
||||
if current is None:
|
||||
raise HTTPException(404, f"Playlist not found: {playlist_uuid}")
|
||||
have = set(current)
|
||||
added = [tid for tid in body.track_ids if tid not in have]
|
||||
n = a.set_playlist_entries(playlist_uuid, current + added)
|
||||
return {"status": "added", "id": playlist_uuid, "added": len(added), "count": n}
|
||||
dupes = [tid for tid in body.track_ids if tid in have]
|
||||
mode = body.duplicates
|
||||
if mode != "skip" and not a.capabilities().playlists.duplicates:
|
||||
mode = "skip"
|
||||
if mode == "ask" and dupes:
|
||||
return {"status": "duplicates", "id": playlist_uuid, "added": 0,
|
||||
"duplicates": len(dupes), "count": len(current)}
|
||||
added = list(body.track_ids) if mode == "add" else [t for t in body.track_ids if t not in have]
|
||||
n = a.set_playlist_entries(playlist_uuid, current + added) if added else len(current)
|
||||
return {"status": "added", "id": playlist_uuid, "added": len(added),
|
||||
"duplicates": len(dupes), "count": n}
|
||||
|
||||
|
||||
@app.patch("/api/tracks")
|
||||
@@ -1229,18 +1479,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 +1553,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 +1750,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 +1981,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 +1991,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 +2000,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"}
|
||||
|
||||
|
||||
@@ -1894,7 +2308,10 @@ def _folder_add_plan(body: FolderAddRequest):
|
||||
# One source across however many folders the ids came from.
|
||||
source = FolderSource(Path(tracks[0].id).parent, tracks)
|
||||
destination = None
|
||||
if body.mode == "copy":
|
||||
if importer.places_audio(dest):
|
||||
# The library decides (a stick): no mode, no destination to ask for.
|
||||
destination = dest.audio_home()
|
||||
elif body.mode == "copy":
|
||||
if not body.destination:
|
||||
raise HTTPException(400, "Copying needs a destination folder")
|
||||
destination = Path(body.destination).expanduser()
|
||||
@@ -1910,9 +2327,11 @@ 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)
|
||||
if body.mode == "reference":
|
||||
_source, dest, destination, plan = _folder_add_plan(body)
|
||||
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":
|
||||
# Nothing is copied, so there is no size to fit anywhere.
|
||||
out.update(total_bytes=0, free_bytes=None, enough_space=None)
|
||||
drive = _drive_of(Path(body.track_ids[0]), places.drives()) if body.track_ids else None
|
||||
@@ -1927,12 +2346,13 @@ def folder_add(body: FolderAddRequest) -> JobStatus:
|
||||
source, dest, destination, plan = _folder_add_plan(body)
|
||||
if not plan.importable and not plan.existing:
|
||||
raise HTTPException(400, "Nothing to add (none of those files exist)")
|
||||
if body.mode == "copy":
|
||||
free = importer.free_bytes(destination)
|
||||
if free is not None and free < plan.total_bytes + importer.SPACE_HEADROOM:
|
||||
if body.mode == "copy" or importer.places_audio(dest):
|
||||
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(
|
||||
400,
|
||||
f"Not enough space: {plan.total_bytes / 1e9:.1f} GB needed, "
|
||||
f"Not enough space: {needed / 1e9:.1f} GB needed, "
|
||||
f"{free / 1e9:.1f} GB free at {destination}",
|
||||
)
|
||||
if JOBS.active("import"):
|
||||
@@ -1962,10 +2382,23 @@ def folder_add(body: FolderAddRequest) -> JobStatus:
|
||||
# threads rather than something fancier.
|
||||
|
||||
|
||||
def _placed_space(out: dict, dest, plan, destination: Path) -> None:
|
||||
"""A self-placing library's preview: only what is really COPIED needs room,
|
||||
and the preview says how many files will be copied vs used in place."""
|
||||
needed = importer.placed_bytes(dest, plan)
|
||||
free = importer.free_bytes(destination)
|
||||
in_place = sum(1 for t in plan.importable if t.source_path is not None
|
||||
and t.source_path.resolve().is_relative_to(destination.resolve()))
|
||||
out.update(total_bytes=needed, free_bytes=free,
|
||||
enough_space=None if free is None else free >= needed + importer.SPACE_HEADROOM,
|
||||
places_audio=True, in_place=in_place, copied=len(plan.importable) - in_place)
|
||||
|
||||
|
||||
def _import_plan(body: ImportRequest):
|
||||
source, dest = require_source(), require_adapter()
|
||||
_require_addable(dest)
|
||||
destination = Path(body.destination).expanduser()
|
||||
destination = (dest.audio_home() if importer.places_audio(dest)
|
||||
else Path(body.destination).expanduser())
|
||||
return source, dest, destination, importer.plan(
|
||||
source,
|
||||
dest,
|
||||
@@ -1982,8 +2415,11 @@ def import_preview(body: ImportRequest) -> dict:
|
||||
Computed fresh on every call and never stored — a stick can be re-exported
|
||||
between the preview and the import, and a stale preview is worse than none.
|
||||
"""
|
||||
_source, _dest, destination, plan = _import_plan(body)
|
||||
return plan.as_dict(free_bytes=importer.free_bytes(destination))
|
||||
_source, dest, destination, plan = _import_plan(body)
|
||||
out = plan.as_dict(free_bytes=importer.free_bytes(destination, dest))
|
||||
if importer.places_audio(dest):
|
||||
_placed_space(out, dest, plan, destination)
|
||||
return out
|
||||
|
||||
|
||||
@app.post("/api/import", response_model=JobStatus)
|
||||
@@ -1993,11 +2429,12 @@ 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)
|
||||
if free is not None and free < plan.total_bytes + importer.SPACE_HEADROOM:
|
||||
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(
|
||||
400,
|
||||
f"Not enough space: {plan.total_bytes / 1e9:.1f} GB needed, "
|
||||
f"Not enough space: {needed / 1e9:.1f} GB needed, "
|
||||
f"{free / 1e9:.1f} GB free at {destination}",
|
||||
)
|
||||
# One at a time: two concurrent imports would race on filename collisions and
|
||||
@@ -2008,11 +2445,18 @@ def start_import(body: ImportRequest) -> JobStatus:
|
||||
folder_name = body.folder_name
|
||||
if folder_name is None and STATE.source is not None:
|
||||
folder_name = STATE.source.capabilities().save.library_label
|
||||
library = STATE.library_id
|
||||
|
||||
job = JOBS.submit(
|
||||
"import",
|
||||
lambda handle: importer.run(source, dest, plan, handle, folder_name=folder_name),
|
||||
)
|
||||
def work(handle):
|
||||
result = importer.run(
|
||||
source, dest, plan, handle, folder_name=folder_name, into_playlist=body.into_playlist,
|
||||
)
|
||||
# As folder add: an export set is Konduktor's data, updated afterwards.
|
||||
if body.export_id is not None and library is not None:
|
||||
exports.add(library, body.export_id, track_ids=result["track_ids"])
|
||||
return result
|
||||
|
||||
job = JOBS.submit("import", work)
|
||||
return JobStatus(**job.as_dict())
|
||||
|
||||
|
||||
|
||||
+68
-31
@@ -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)
|
||||
@@ -0,0 +1,271 @@
|
||||
"""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.
|
||||
#: 1.1 — `move_playlist` (sidebar drag and drop).
|
||||
API_VERSION: tuple[int, int] = (1, 1)
|
||||
|
||||
#: 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",
|
||||
"move_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)
|
||||
@@ -21,6 +21,20 @@ class SetEntries(BaseModel):
|
||||
track_ids: list[str] # ordered; full desired contents of the playlist
|
||||
|
||||
|
||||
class AddEntries(BaseModel):
|
||||
track_ids: list[str]
|
||||
# Tracks the playlist already holds: "skip" them, "add" them again (only
|
||||
# where `playlists.duplicates`, else skipped), or "ask" — change nothing and
|
||||
# report how many, so the UI can ask and send again with skip/add.
|
||||
duplicates: Literal["skip", "add", "ask"] = "skip"
|
||||
|
||||
|
||||
class MovePlaylist(BaseModel):
|
||||
node_id: str
|
||||
parent_id: str | None = None # None = the top level
|
||||
index: int # among the new parent's children, not counting the node
|
||||
|
||||
|
||||
class EditTrack(BaseModel):
|
||||
track_id: str
|
||||
fields: dict[str, str | int | None]
|
||||
@@ -133,6 +147,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 +235,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 +250,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"
|
||||
@@ -435,6 +507,11 @@ class ImportRequest(BaseModel):
|
||||
# Playlists land in a folder named after the drive. Null keeps them at the
|
||||
# root; the default is filled in from the source's label.
|
||||
folder_name: str | None = None
|
||||
# Device tracks dropped on a collection playlist / an export (drag and
|
||||
# drop): every imported track — and every one the collection already
|
||||
# holds — goes into it, as folder add does.
|
||||
into_playlist: str | None = None
|
||||
export_id: str | None = None
|
||||
|
||||
|
||||
class Drive(BaseModel):
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
"""Konduktor's server: one library, held on the machine where its audio lives,
|
||||
opened from the desktop app as a "Remote" library. See `app.py`."""
|
||||
@@ -0,0 +1,37 @@
|
||||
"""`python -m konduktor.server` — what the container runs.
|
||||
|
||||
Configuration is the environment (see `config.py`); a bad setting stops here
|
||||
with one clear line instead of serving a library that half-works.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import sys
|
||||
|
||||
import uvicorn
|
||||
|
||||
from .config import ConfigError, from_env
|
||||
|
||||
|
||||
def main() -> int:
|
||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
|
||||
try:
|
||||
config = from_env()
|
||||
except ConfigError as ex:
|
||||
print(f"konduktor-server: {ex}", file=sys.stderr)
|
||||
return 2
|
||||
from .app import Server, create_app
|
||||
|
||||
server = Server(config)
|
||||
try:
|
||||
server.open()
|
||||
except ConfigError as ex:
|
||||
print(f"konduktor-server: {ex}", file=sys.stderr)
|
||||
return 2
|
||||
uvicorn.run(create_app(server), host=config.host, port=config.port,
|
||||
log_level="info", proxy_headers=True)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,657 @@
|
||||
"""The Konduktor SERVER: one library, held where its audio lives.
|
||||
|
||||
Runs in a container on the user's NAS (`server/Dockerfile`) and is opened from
|
||||
the desktop app as a "Remote" library. It is deliberately NOT `main.py` behind a
|
||||
password: the UI's routes would become a public contract, and half of them are
|
||||
about THIS computer (its drives, its stem engine, its sticks). What it serves is
|
||||
the `LibraryAdapter` protocol itself (`remote_protocol.py`), plus the few things
|
||||
that are bytes — audio, art, uploads — and the app-level bookkeeping that lives
|
||||
beside the library: save + backups + version history, export sets, the stems
|
||||
ledger.
|
||||
|
||||
Lightweight by decision: the server never DECODES audio. Analysis, waveforms and
|
||||
stem separation all run on the computer that opened the library; what arrives
|
||||
here are the results, as ordinary commands. Its work is file IO, the native
|
||||
model, tags, and header reads.
|
||||
|
||||
One computer at a time (`session.py`): every command carries the session token,
|
||||
and anything that changes the library without it is answered 423 with who holds
|
||||
it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import mimetypes
|
||||
import os
|
||||
import secrets
|
||||
import shutil
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import Body, Depends, FastAPI, Header, HTTPException, Query, Request, Response
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
from fastapi.security import HTTPBasic, HTTPBasicCredentials
|
||||
|
||||
from .. import __version__, exports
|
||||
from .. import remote_protocol as rp
|
||||
from ..app_state import AppState
|
||||
from ..core import registry
|
||||
from ..core.adapter import (
|
||||
AdapterError,
|
||||
InvalidCommand,
|
||||
LibraryNotSupported,
|
||||
NewTrack,
|
||||
NotFound,
|
||||
Unsupported,
|
||||
)
|
||||
from ..core.places import is_os_housekeeping
|
||||
from .config import ConfigError, ServerConfig
|
||||
from .session import InUse, Lost, SessionLock
|
||||
|
||||
log = logging.getLogger("konduktor.server")
|
||||
|
||||
#: Upload partials, published by a rename that never overwrites.
|
||||
PARTIAL_SUFFIX = ".konduktor-upload"
|
||||
_CHUNK = 1 << 20
|
||||
|
||||
|
||||
class Server:
|
||||
"""The open library, its session, and the revision counter clients follow."""
|
||||
|
||||
def __init__(self, config: ServerConfig, *, state: AppState | None = None,
|
||||
lock: SessionLock | None = None):
|
||||
self.config = config
|
||||
self.state = state if state is not None else _default_state()
|
||||
self.lock = lock or SessionLock()
|
||||
self.rev = 0
|
||||
self._rev_lock = threading.Lock()
|
||||
|
||||
# ---- opening ---------------------------------------------------------------
|
||||
def open(self) -> None:
|
||||
cfg = self.config
|
||||
try:
|
||||
driver = registry.driver_for(cfg.library)
|
||||
except LibraryNotSupported as ex:
|
||||
raise ConfigError(f"KONDUKTOR_LIBRARY: {ex}")
|
||||
if driver.platform != cfg.platform:
|
||||
raise ConfigError(
|
||||
f"KONDUKTOR_PLATFORM is {cfg.platform!r} but {cfg.library} is a "
|
||||
f"{driver.display_name} library"
|
||||
)
|
||||
self.state.open_hooks.append(self._configure)
|
||||
self.state.open(cfg.library)
|
||||
|
||||
def _configure(self, adapter) -> None:
|
||||
"""After every (re)open: the configured path mapping, and no missing-files
|
||||
search of a container's empty drives."""
|
||||
maps = self.config.path_maps
|
||||
if maps:
|
||||
adapter.set_path_mapping(maps[0])
|
||||
adapter.set_session_mappings(list(maps[1:]))
|
||||
# A file uploaded here is stored as the library stores every other
|
||||
# path — so it still opens, mapping and all, where it was made.
|
||||
write_stored = getattr(adapter, "set_write_stored_paths", None)
|
||||
if write_stored is not None:
|
||||
write_stored(True)
|
||||
self.state.relocation = None
|
||||
|
||||
@property
|
||||
def adapter(self):
|
||||
if self.state.adapter is None:
|
||||
raise HTTPException(503, "The library is not open")
|
||||
return self.state.adapter
|
||||
|
||||
def bump(self) -> int:
|
||||
with self._rev_lock:
|
||||
self.rev += 1
|
||||
return self.rev
|
||||
|
||||
# ---- facts -------------------------------------------------------------------
|
||||
def capabilities(self):
|
||||
"""The adapter's own, plus what being held by a server changes."""
|
||||
caps = self.adapter.capabilities().model_copy(deep=True)
|
||||
caps.tracks.audio_destination = "library"
|
||||
caps.tracks.reference = False
|
||||
caps.paths.remappable = False
|
||||
# Nothing runs a DJ app against a library on a NAS while it is being
|
||||
# saved: the "close Traktor first" warning would only confuse.
|
||||
caps.save.overwrite_risk = "none"
|
||||
return caps
|
||||
|
||||
def name(self) -> str:
|
||||
return self.config.name or self.config.library.stem
|
||||
|
||||
def pending_edits(self, client_id: str | None = None) -> dict | None:
|
||||
"""The unsaved edits someone else left, for the computer arriving."""
|
||||
adapter = self.adapter
|
||||
if not adapter.dirty:
|
||||
return None
|
||||
editor = self.lock.last_editor or {}
|
||||
if client_id and editor.get("client_id") == client_id:
|
||||
return None
|
||||
summary = getattr(adapter, "edit_summary", None)
|
||||
return {
|
||||
"machine": editor.get("machine"),
|
||||
"summary": (summary() if summary else "") or "unsaved changes",
|
||||
}
|
||||
|
||||
def confine(self, raw: str | None) -> Path:
|
||||
"""A path inside the content folder, or 400. Resolved first, so neither
|
||||
`..` nor a symlink can lead out of it."""
|
||||
root = self.config.content
|
||||
candidate = Path(raw) if raw else root
|
||||
if not candidate.is_absolute():
|
||||
candidate = root / candidate
|
||||
resolved = candidate.resolve()
|
||||
if resolved != root and not resolved.is_relative_to(root):
|
||||
raise HTTPException(400, f"{raw} is outside the library's content folder")
|
||||
return resolved
|
||||
|
||||
|
||||
def _default_state() -> AppState:
|
||||
# The process-wide STATE: a server holds one library, and the stem end step
|
||||
# reaches for `app_state.STATE.mutation` like the desktop app's does.
|
||||
from ..app_state import STATE
|
||||
|
||||
return STATE
|
||||
|
||||
|
||||
def create_app(server: Server) -> FastAPI:
|
||||
cfg = server.config
|
||||
security = HTTPBasic(realm="Konduktor")
|
||||
|
||||
def auth(creds: HTTPBasicCredentials = Depends(security)) -> None:
|
||||
user_ok = secrets.compare_digest(creds.username.encode(), cfg.username.encode())
|
||||
pass_ok = secrets.compare_digest(creds.password.encode(), cfg.password.encode())
|
||||
if not (user_ok and pass_ok):
|
||||
raise HTTPException(401, "Wrong username or password",
|
||||
headers={"WWW-Authenticate": 'Basic realm="Konduktor"'})
|
||||
|
||||
app = FastAPI(title="Konduktor server", version=__version__, dependencies=[Depends(auth)])
|
||||
app.state.server = server
|
||||
|
||||
@app.exception_handler(AdapterError)
|
||||
def _adapter_error(_request, exc: AdapterError):
|
||||
status = {NotFound: 404, InvalidCommand: 400, Unsupported: 422,
|
||||
LibraryNotSupported: 400}.get(type(exc), 400)
|
||||
return JSONResponse(status_code=status, content={"detail": str(exc)})
|
||||
|
||||
def session(token: str | None = Header(None, alias=rp.SESSION_HEADER)):
|
||||
try:
|
||||
return server.lock.check(token)
|
||||
except Lost as ex:
|
||||
raise HTTPException(423, {
|
||||
"code": "taken_over", "message": str(ex), "holder": server.lock.describe(),
|
||||
})
|
||||
|
||||
# ---- handshake + session -----------------------------------------------------
|
||||
@app.get("/v1/hello")
|
||||
def hello(client_id: str | None = None) -> dict:
|
||||
state = server.state
|
||||
caps = server.capabilities()
|
||||
return {
|
||||
"api_version": list(rp.API_VERSION),
|
||||
"app_version": __version__,
|
||||
"platform": caps.platform,
|
||||
"app_name": caps.save.app_name,
|
||||
"library_label": caps.save.library_label,
|
||||
"name": server.name(),
|
||||
"path": str(state.path),
|
||||
"library_id": state.library_id,
|
||||
"holder": server.lock.describe(),
|
||||
"dirty": server.adapter.dirty,
|
||||
"pending_edits": server.pending_edits(client_id),
|
||||
"rev": server.rev,
|
||||
}
|
||||
|
||||
@app.post("/v1/session/acquire")
|
||||
def acquire(body: dict = Body(...)) -> dict:
|
||||
client_id = str(body.get("client_id") or "")
|
||||
machine = str(body.get("machine") or "another computer")
|
||||
if not client_id:
|
||||
raise HTTPException(400, "client_id is required")
|
||||
try:
|
||||
holder = server.lock.acquire(client_id, machine, takeover=bool(body.get("takeover")))
|
||||
except InUse as ex:
|
||||
h = ex.holder
|
||||
raise HTTPException(409, {"code": "in_use", "machine": h.machine,
|
||||
"since": h.since, "batch": h.batch})
|
||||
return {
|
||||
"token": holder.token,
|
||||
"lease": server.lock.lease,
|
||||
"heartbeat": rp.HEARTBEAT_SECONDS,
|
||||
"pending_edits": server.pending_edits(client_id),
|
||||
"rev": server.rev,
|
||||
}
|
||||
|
||||
@app.post("/v1/session/heartbeat")
|
||||
def heartbeat(body: dict = Body(default={}),
|
||||
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
try:
|
||||
server.lock.heartbeat(token, body.get("batch"))
|
||||
except Lost as ex:
|
||||
raise HTTPException(423, {"code": "taken_over", "message": str(ex),
|
||||
"holder": server.lock.describe()})
|
||||
return {"rev": server.rev, "dirty": server.adapter.dirty}
|
||||
|
||||
@app.post("/v1/session/release")
|
||||
def release(token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
server.lock.release(token)
|
||||
return {"status": "released"}
|
||||
|
||||
# ---- the protocol ------------------------------------------------------------
|
||||
@app.post("/v1/rpc/{name}")
|
||||
def rpc(name: str, body: dict = Body(default={}),
|
||||
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
method = rp.RPC.get(name)
|
||||
if method is None:
|
||||
raise HTTPException(404, f"No such method: {name}")
|
||||
holder = session(token) if method.mutating else None
|
||||
try:
|
||||
args = rp.load_args(name, body.get("args") or {})
|
||||
except ValueError as ex:
|
||||
raise HTTPException(400, str(ex))
|
||||
adapter = server.adapter
|
||||
changed: list = []
|
||||
removed: list[str] = []
|
||||
reset = False
|
||||
if name == "capabilities":
|
||||
value = server.capabilities()
|
||||
elif name == "add_tracks":
|
||||
with server.state.mutation:
|
||||
value = adapter.add_tracks([_new_track(server, w) for w in args["items"]])
|
||||
changed = [t for i in value if (t := adapter.track(i)) is not None]
|
||||
elif method.prop:
|
||||
value = getattr(adapter, name)
|
||||
else:
|
||||
value = getattr(adapter, name)(**args)
|
||||
if method.mutating:
|
||||
if name == "remove_tracks":
|
||||
removed = list(args["track_ids"])
|
||||
elif "track_id" in args:
|
||||
track = adapter.track(args["track_id"])
|
||||
if track is None:
|
||||
removed = [args["track_id"]]
|
||||
else:
|
||||
changed = [track]
|
||||
server.lock.touch(holder)
|
||||
rev = server.bump()
|
||||
else:
|
||||
rev = server.rev
|
||||
return {
|
||||
"result": rp.dump_result(name, value),
|
||||
"rev": rev,
|
||||
"changed": [t.model_dump(mode="json") for t in changed],
|
||||
"removed": removed,
|
||||
"reset": reset,
|
||||
}
|
||||
|
||||
# ---- bytes -------------------------------------------------------------------
|
||||
@app.get("/v1/audio")
|
||||
def audio(track_id: str):
|
||||
path = server.adapter.audio_path(track_id)
|
||||
if path is None or not Path(path).is_file():
|
||||
raise HTTPException(404, "The audio file is missing")
|
||||
st = Path(path).stat()
|
||||
media = mimetypes.guess_type(str(path))[0] or "application/octet-stream"
|
||||
return FileResponse(path, media_type=media, headers={
|
||||
"X-Konduktor-Size": str(st.st_size),
|
||||
"X-Konduktor-Mtime-Ns": str(st.st_mtime_ns),
|
||||
})
|
||||
|
||||
@app.get("/v1/art")
|
||||
def art(track_id: str):
|
||||
found = server.adapter.cover_art(track_id)
|
||||
if not found:
|
||||
raise HTTPException(404, "No cover art")
|
||||
data, mime = found
|
||||
return Response(content=data, media_type=mime)
|
||||
|
||||
@app.put("/v1/art")
|
||||
async def put_art(request: Request, track_id: str, mime: str,
|
||||
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
holder = session(token)
|
||||
data = await request.body()
|
||||
server.adapter.set_cover_art(track_id, data, mime)
|
||||
server.lock.touch(holder)
|
||||
track = server.adapter.track(track_id)
|
||||
return {"rev": server.bump(), "changed": [track.model_dump(mode="json")] if track else []}
|
||||
|
||||
@app.post("/v1/upload")
|
||||
async def upload(request: Request, dir: str, name: str,
|
||||
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
"""Receive one audio file into `dir` (created if needed) under the content
|
||||
folder. Never overwrites: a name already taken gets `-2`, `-3`, … as a
|
||||
local import's copy does. The partial is renamed in only when complete,
|
||||
so a cut connection leaves no half file under a real name."""
|
||||
holder = session(token)
|
||||
folder = server.confine(dir)
|
||||
clean = _safe_name(name)
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
partial = folder / f".{clean}.{secrets.token_hex(4)}{PARTIAL_SUFFIX}"
|
||||
try:
|
||||
with open(partial, "wb") as out:
|
||||
async for chunk in request.stream():
|
||||
out.write(chunk)
|
||||
target = _publish(partial, folder / clean)
|
||||
finally:
|
||||
partial.unlink(missing_ok=True)
|
||||
holder.uploads.add(str(target))
|
||||
st = target.stat()
|
||||
# A platform that analyses what it adds measures on its own clock, read
|
||||
# from the file's header — which only the server can read. The client
|
||||
# measures with this (`PreparedAnalysis`); None: nothing to measure.
|
||||
lead = getattr(server.adapter, "analysis_lead", None)
|
||||
return {"path": str(target), "size": st.st_size, "mtime_ns": st.st_mtime_ns,
|
||||
"analysis_lead": lead(target) if lead else None}
|
||||
|
||||
@app.delete("/v1/upload")
|
||||
def delete_upload(path: str, token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
"""Remove a file THIS session uploaded and the library does not name —
|
||||
how a cancelled or failed import cleans up after itself."""
|
||||
holder = session(token)
|
||||
target = server.confine(path)
|
||||
if str(target) not in holder.uploads:
|
||||
raise HTTPException(403, "Only a file this session uploaded can be removed")
|
||||
adapter = server.adapter
|
||||
named = {f.key for f in adapter.audio_facts([t.id for t in adapter.tracks]).values()}
|
||||
if str(target) in named:
|
||||
raise HTTPException(409, "The library names that file")
|
||||
target.unlink(missing_ok=True)
|
||||
holder.uploads.discard(str(target))
|
||||
return {"status": "deleted"}
|
||||
|
||||
# ---- the content folder ------------------------------------------------------
|
||||
@app.get("/v1/fs/list")
|
||||
def fs_list(path: str | None = None) -> dict:
|
||||
folder = server.confine(path)
|
||||
if not folder.is_dir():
|
||||
raise HTTPException(404, f"Not a folder: {folder}")
|
||||
entries = []
|
||||
try:
|
||||
children = sorted(folder.iterdir(), key=lambda p: p.name.lower())
|
||||
except OSError as ex:
|
||||
raise HTTPException(400, f"Cannot list {folder}: {ex}")
|
||||
for child in children:
|
||||
if child.name.startswith(".") or is_os_housekeeping(child.name):
|
||||
continue
|
||||
try:
|
||||
is_dir = child.is_dir()
|
||||
except OSError:
|
||||
continue
|
||||
entries.append({"name": child.name, "path": str(child), "is_dir": is_dir})
|
||||
root = server.config.content
|
||||
return {
|
||||
"path": str(folder),
|
||||
"parent": None if folder == root else str(folder.parent),
|
||||
"root": str(root),
|
||||
"entries": entries,
|
||||
}
|
||||
|
||||
@app.get("/v1/fs/space")
|
||||
def fs_space(path: str | None = None) -> dict:
|
||||
folder = server.confine(path)
|
||||
probe = folder
|
||||
while not probe.exists() and probe != server.config.content:
|
||||
probe = probe.parent
|
||||
return {"free": shutil.disk_usage(probe).free}
|
||||
|
||||
# ---- save / discard / history ------------------------------------------------
|
||||
@app.post("/v1/save")
|
||||
def save(token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
session(token)
|
||||
adapter = server.adapter
|
||||
if not adapter.dirty:
|
||||
return {"saved": False, "commit": None, "summary": "",
|
||||
"tag_results": [], "playlists": adapter.playlist_count(), "rev": server.rev}
|
||||
outcome, commit = server.state.save()
|
||||
server.lock.clear_editor()
|
||||
return {
|
||||
"saved": True,
|
||||
"commit": commit,
|
||||
"summary": outcome.summary,
|
||||
"tag_results": [r.__dict__ for r in outcome.tag_results],
|
||||
"playlists": adapter.playlist_count(),
|
||||
"rev": server.bump(),
|
||||
}
|
||||
|
||||
@app.post("/v1/discard")
|
||||
def discard(token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
session(token)
|
||||
server.state.discard()
|
||||
server._configure(server.adapter)
|
||||
server.lock.clear_editor()
|
||||
return {"rev": server.bump()}
|
||||
|
||||
@app.get("/v1/history")
|
||||
def history() -> list[dict]:
|
||||
return [e.__dict__ for e in server.state.services.history()]
|
||||
|
||||
@app.post("/v1/history/{commit_id}/restore")
|
||||
def restore(commit_id: str, token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
session(token)
|
||||
if not server.state.restore_version(commit_id):
|
||||
raise HTTPException(404, f"Version not found: {commit_id}")
|
||||
server.lock.clear_editor()
|
||||
return {"rev": server.bump()}
|
||||
|
||||
@app.delete("/v1/history")
|
||||
def clear_history(token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
session(token)
|
||||
server.state.services.clear_history()
|
||||
return {"status": "cleared"}
|
||||
|
||||
# ---- export sets -------------------------------------------------------------
|
||||
@app.get("/v1/export-sets")
|
||||
def get_export_sets() -> dict:
|
||||
return exports._read_doc(server.state.library_id)
|
||||
|
||||
@app.put("/v1/export-sets")
|
||||
def put_export_sets(doc: dict = Body(...),
|
||||
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
session(token)
|
||||
if not isinstance(doc.get("sets"), dict):
|
||||
raise HTTPException(400, "Expected {'sets': {...}}")
|
||||
exports._write_doc(server.state.library_id,
|
||||
{"library_id": server.state.library_id, "sets": doc["sets"]})
|
||||
return {"status": "saved"}
|
||||
|
||||
# ---- Convert to Stems: the library side ---------------------------------------
|
||||
# The SEPARATION runs on the computer that opened the library (the server
|
||||
# never decodes audio); what lives here is everything about the FILES and the
|
||||
# library: where each stem file goes, what is skipped and why, the verified
|
||||
# files it uploads (kept as leftovers until the batch's end step, so a
|
||||
# takeover mid-batch loses nothing — the next run reuses them), and the end
|
||||
# step itself, under the library's mutation lock, with the server's ledger.
|
||||
def stem_options(body: dict):
|
||||
from ..stems import convert
|
||||
|
||||
destination = body.get("destination")
|
||||
if body.get("mode") == "destination":
|
||||
if not destination:
|
||||
raise HTTPException(400, "Choose a destination folder")
|
||||
destination = server.confine(destination)
|
||||
return convert.Options(
|
||||
mode=body.get("mode") or "replace", destination=Path(destination) if destination else None,
|
||||
collection=body.get("collection") or "repoint", playlist_id=body.get("playlist_id"),
|
||||
new_playlist=body.get("new_playlist"),
|
||||
)
|
||||
|
||||
@app.post("/v1/stems/plan")
|
||||
def stems_plan(body: dict = Body(...)) -> dict:
|
||||
from ..stems import convert
|
||||
|
||||
adapter = server.adapter
|
||||
caps = adapter.capabilities()
|
||||
if not caps.tracks.stem_convertible:
|
||||
raise HTTPException(422, "This library cannot hold stem files")
|
||||
try:
|
||||
planned = convert.plan(adapter, list(body.get("track_ids") or []), stem_options(body),
|
||||
server.state.pending)
|
||||
except convert.ConvertError as ex:
|
||||
raise HTTPException(400, str(ex))
|
||||
out = planned.as_dict()
|
||||
out["items"] = [{
|
||||
"track_id": p.track_id, "title": p.title, "source": str(p.source), "target": str(p.target),
|
||||
"seconds": p.seconds, "source_size": p.source.stat().st_size if p.source.exists() else 0,
|
||||
"reuse": p.reuse["written"] if p.reuse else None,
|
||||
} for p in planned.items]
|
||||
return out
|
||||
|
||||
def stem_item(track_id: str, target: str) -> tuple[Path, Path]:
|
||||
"""The source and target a stem upload / publish names, checked against
|
||||
the library rather than trusted: a target outside the content folder, or
|
||||
one not named after its own track's file, is refused."""
|
||||
from ..core import stem_file as sf
|
||||
|
||||
source = server.adapter.audio_path(track_id)
|
||||
if source is None or not Path(source).is_file():
|
||||
raise HTTPException(404, "The track's audio file is missing")
|
||||
dest = server.confine(target)
|
||||
if dest.name != sf.stem_target_name(Path(source).name):
|
||||
raise HTTPException(400, f"{dest.name} is not the stem file of {Path(source).name}")
|
||||
return Path(source), dest
|
||||
|
||||
@app.put("/v1/stems/stage")
|
||||
async def stems_stage(request: Request, track_id: str, target: str, sha256: str,
|
||||
bit_rate: int, duration: float,
|
||||
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
import hashlib
|
||||
|
||||
from ..stems.pending import partial_name, source_facts
|
||||
|
||||
session(token)
|
||||
source, dest = stem_item(track_id, target)
|
||||
if dest.exists():
|
||||
raise HTTPException(409, f"A stem file already exists: {dest.name}")
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
partial = partial_name(dest)
|
||||
incoming = dest.with_name(f".{dest.name}.{secrets.token_hex(4)}{PARTIAL_SUFFIX}")
|
||||
digest = hashlib.sha256()
|
||||
size = 0
|
||||
try:
|
||||
with open(incoming, "wb") as out:
|
||||
async for chunk in request.stream():
|
||||
out.write(chunk)
|
||||
digest.update(chunk)
|
||||
size += len(chunk)
|
||||
if digest.hexdigest() != sha256.lower():
|
||||
raise HTTPException(400, "The stem file arrived damaged (checksum mismatch)")
|
||||
os.replace(incoming, partial)
|
||||
finally:
|
||||
incoming.unlink(missing_ok=True)
|
||||
pending = server.state.pending
|
||||
with pending._lock:
|
||||
pending.leftovers = [lo for lo in pending.leftovers if lo["partial"] != str(partial)]
|
||||
pending.leftovers.append({
|
||||
"source": str(source), "facts": source_facts(source), "partial": str(partial),
|
||||
"written": {"bit_rate": bit_rate, "duration": duration, "size": size},
|
||||
})
|
||||
pending._write()
|
||||
return {"partial": str(partial), "size": size}
|
||||
|
||||
@app.post("/v1/stems/abandon")
|
||||
def stems_abandon(body: dict = Body(...),
|
||||
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
"""A cancelled batch: delete the files it uploaded (a cancel deletes
|
||||
only new files, as on this computer)."""
|
||||
from ..stems.pending import partial_name
|
||||
|
||||
session(token)
|
||||
pending = server.state.pending
|
||||
wanted = {str(partial_name(server.confine(t))) for t in body.get("targets") or []}
|
||||
for lo in [lo for lo in pending.leftovers if lo["partial"] in wanted]:
|
||||
pending.forget_leftover(lo, delete=True)
|
||||
return {"status": "abandoned"}
|
||||
|
||||
@app.post("/v1/stems/publish")
|
||||
def stems_publish(body: dict = Body(...),
|
||||
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
"""The batch's END STEP, here where the files are: publish each staged
|
||||
stem file, park originals (Replace), swap every entry at once."""
|
||||
from ..core import stem_file as sf
|
||||
from ..stems import convert
|
||||
from ..stems.pending import partial_name
|
||||
|
||||
holder = session(token)
|
||||
opts = stem_options(body.get("options") or {})
|
||||
pending = server.state.pending
|
||||
result = {"converted": [], "renamed": {}, "added": {}, "failed": [], "clamped": {}}
|
||||
with server.state.mutation:
|
||||
finished = []
|
||||
for entry in body.get("items") or []:
|
||||
source, dest = stem_item(entry["track_id"], entry["target"])
|
||||
partial = partial_name(dest)
|
||||
lo = next((x for x in pending.leftovers if x["partial"] == str(partial)), None)
|
||||
track = server.adapter.track(entry["track_id"])
|
||||
title = convert._title(track)
|
||||
if lo is None or not partial.is_file():
|
||||
result["failed"].append({"track_id": entry["track_id"], "title": title,
|
||||
"reason": "the converted file never reached the server"})
|
||||
continue
|
||||
written = lo["written"]
|
||||
pitem = pending.add({"track_id": entry["track_id"], "mode": opts.collection,
|
||||
"source": str(source), "stem": str(dest), "state": "converted",
|
||||
"facts": lo.get("facts"), "written": written})
|
||||
pending.forget_leftover(lo, delete=False)
|
||||
planned = convert.Planned(entry["track_id"], title, source, dest, float(written["duration"]))
|
||||
finished.append((planned, pitem, sf.Written(path=partial, bit_rate=int(written["bit_rate"]),
|
||||
duration=float(written["duration"]),
|
||||
size=int(written["size"]), tags={})))
|
||||
convert._end_step(server.adapter, finished, opts, pending, result)
|
||||
server.lock.touch(holder)
|
||||
result["rev"] = server.bump()
|
||||
return result
|
||||
|
||||
@app.get("/v1/stems/pending")
|
||||
def stems_pending() -> dict:
|
||||
pending = server.state.pending
|
||||
return pending.summary() if pending is not None else {"tracks": 0, "parked": 0, "bytes": 0}
|
||||
|
||||
return app
|
||||
|
||||
|
||||
def _safe_name(name: str) -> str:
|
||||
clean = os.path.basename((name or "").replace("\\", "/")).strip()
|
||||
if not clean or clean in (".", "..") or clean.startswith("."):
|
||||
raise HTTPException(400, f"Not a usable file name: {name!r}")
|
||||
return clean
|
||||
|
||||
|
||||
def _publish(partial: Path, wanted: Path) -> Path:
|
||||
"""Rename `partial` to `wanted`, or `wanted-2`… — never over an existing file
|
||||
(a hard link fails rather than replaces)."""
|
||||
stem, suffix = wanted.stem, wanted.suffix
|
||||
# `.stem.m4a` keeps its double suffix together.
|
||||
if stem.endswith(".stem"):
|
||||
stem, suffix = stem[: -len(".stem")], ".stem" + suffix
|
||||
n = 1
|
||||
while True:
|
||||
target = wanted if n == 1 else wanted.with_name(f"{stem}-{n}{suffix}")
|
||||
try:
|
||||
os.link(partial, target)
|
||||
return target
|
||||
except FileExistsError:
|
||||
n += 1
|
||||
|
||||
|
||||
def _new_track(server: Server, wire: rp.WireNewTrack) -> NewTrack:
|
||||
import base64
|
||||
|
||||
path = server.confine(wire.audio_path)
|
||||
art = (base64.b64decode(wire.art.data), wire.art.mime) if wire.art else None
|
||||
return NewTrack(track=wire.track, audio_path=path, cues=wire.cues, art=art,
|
||||
analysis=rp.unpack_analysis(wire.analysis))
|
||||
|
||||
|
||||
# ---- entry points ------------------------------------------------------------------
|
||||
|
||||
|
||||
def create_from_env() -> FastAPI:
|
||||
"""`uvicorn --factory konduktor.server.app:create_from_env`."""
|
||||
from .config import from_env
|
||||
|
||||
server = Server(from_env())
|
||||
server.open()
|
||||
log.info("Serving %s (%s) to remote clients", server.config.library, server.config.platform)
|
||||
return create_app(server)
|
||||
@@ -0,0 +1,101 @@
|
||||
"""The server's configuration: the container's environment (its `.env`).
|
||||
|
||||
Everything is read once at start and checked before the library is opened, and
|
||||
a bad setting stops the container with ONE clear line rather than a library
|
||||
that half-works: a missing content folder would otherwise show up as every
|
||||
track "missing", and an empty password as an open door.
|
||||
|
||||
KONDUKTOR_PLATFORM traktor | rekordbox — checked against the library file
|
||||
KONDUKTOR_LIBRARY the library file (collection.nml / master.db)
|
||||
KONDUKTOR_CONTENT the folder holding the audio; uploads and the folder
|
||||
browser are confined to it
|
||||
KONDUKTOR_USERNAME the one account
|
||||
KONDUKTOR_PASSWORD
|
||||
KONDUKTOR_PATH_MAP optional: "stored => here", e.g.
|
||||
"/Users/ben/Music => /music"; several separated by ";".
|
||||
Applied for the session only — the library keeps its
|
||||
stored paths, so it still opens on the computer it
|
||||
was made on.
|
||||
KONDUKTOR_NAME optional: what the library is called on screen
|
||||
KONDUKTOR_DATA_DIR where history, export sets and the ledger live
|
||||
(read by `paths.app_data_dir`)
|
||||
KONDUKTOR_HOST / KONDUKTOR_PORT where to listen (0.0.0.0:8765)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from ..core.pathmap import PathMapping
|
||||
|
||||
PLATFORMS = ("traktor", "rekordbox")
|
||||
|
||||
|
||||
class ConfigError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ServerConfig:
|
||||
platform: str
|
||||
library: Path
|
||||
content: Path
|
||||
username: str
|
||||
password: str
|
||||
path_maps: tuple[PathMapping, ...] = field(default_factory=tuple)
|
||||
name: str = ""
|
||||
host: str = "0.0.0.0"
|
||||
port: int = 8765
|
||||
|
||||
|
||||
def parse_path_maps(text: str | None) -> tuple[PathMapping, ...]:
|
||||
"""`"a => b; c => d"` → mappings. Raises `ConfigError` on a malformed one."""
|
||||
out = []
|
||||
for part in (text or "").split(";"):
|
||||
part = part.strip()
|
||||
if not part:
|
||||
continue
|
||||
if "=>" not in part:
|
||||
raise ConfigError(f"KONDUKTOR_PATH_MAP: expected 'stored => here', got {part!r}")
|
||||
src, dst = (s.strip() for s in part.split("=>", 1))
|
||||
mapping = PathMapping.make(src, dst)
|
||||
if mapping.empty:
|
||||
raise ConfigError(f"KONDUKTOR_PATH_MAP: both sides are needed in {part!r}")
|
||||
out.append(mapping)
|
||||
return tuple(out)
|
||||
|
||||
|
||||
def from_env(env=None) -> ServerConfig:
|
||||
env = os.environ if env is None else env
|
||||
|
||||
def need(key: str) -> str:
|
||||
value = (env.get(key) or "").strip()
|
||||
if not value:
|
||||
raise ConfigError(f"{key} is not set")
|
||||
return value
|
||||
|
||||
platform = need("KONDUKTOR_PLATFORM").lower()
|
||||
if platform not in PLATFORMS:
|
||||
raise ConfigError(f"KONDUKTOR_PLATFORM must be one of {', '.join(PLATFORMS)}, not {platform!r}")
|
||||
library = Path(need("KONDUKTOR_LIBRARY"))
|
||||
if not library.exists():
|
||||
raise ConfigError(f"KONDUKTOR_LIBRARY: {library} does not exist")
|
||||
content = Path(need("KONDUKTOR_CONTENT"))
|
||||
if not content.is_dir():
|
||||
raise ConfigError(f"KONDUKTOR_CONTENT: {content} is not a folder")
|
||||
username = need("KONDUKTOR_USERNAME")
|
||||
password = env.get("KONDUKTOR_PASSWORD") or ""
|
||||
if not password:
|
||||
raise ConfigError("KONDUKTOR_PASSWORD is not set")
|
||||
try:
|
||||
port = int(env.get("KONDUKTOR_PORT") or 8765)
|
||||
except ValueError:
|
||||
raise ConfigError("KONDUKTOR_PORT must be a number")
|
||||
return ServerConfig(
|
||||
platform=platform, library=library, content=content.resolve(),
|
||||
username=username, password=password,
|
||||
path_maps=parse_path_maps(env.get("KONDUKTOR_PATH_MAP")),
|
||||
name=(env.get("KONDUKTOR_NAME") or "").strip(),
|
||||
host=(env.get("KONDUKTOR_HOST") or "0.0.0.0").strip(), port=port,
|
||||
)
|
||||
@@ -0,0 +1,133 @@
|
||||
"""One computer at a time: the server's session lock.
|
||||
|
||||
A library held by a server is edited by ONE computer at a time (decided: a
|
||||
shared or merged session was rejected). That computer holds the session; every
|
||||
command carries its token, and anything else is told who holds it.
|
||||
|
||||
* **A lease, renewed by heartbeat.** The holder's app sends one every
|
||||
`HEARTBEAT_SECONDS`; `LEASE_SECONDS` without one and the session is free.
|
||||
A crashed laptop or a closed lid therefore never locks the library for
|
||||
good, and a Wi-Fi blip does not lose it.
|
||||
* **Takeover** is how a second computer gets in before the lease runs out:
|
||||
it is told who holds the session (and what batch is running there) and may
|
||||
take it. The old token is refused from then on, which is how the displaced
|
||||
computer finds out.
|
||||
* **The same computer coming back** — after sleep, after a reconnect through
|
||||
its fallback address — renews its expired lease silently, as long as
|
||||
nobody else has taken the session meanwhile.
|
||||
|
||||
Unsaved edits are NOT the session's: they live in the one native model the
|
||||
server holds, so whoever holds the session next inherits them (and is asked to
|
||||
save or discard them — `last_editor` says whose they were).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from ..remote_protocol import LEASE_SECONDS
|
||||
|
||||
|
||||
@dataclass
|
||||
class Holder:
|
||||
token: str
|
||||
client_id: str
|
||||
machine: str
|
||||
since: str # ISO 8601, UTC
|
||||
last_seen: float # on the lock's clock
|
||||
batch: str | None = None # the kind of batch job running there, if any
|
||||
uploads: set[str] = field(default_factory=set)
|
||||
|
||||
|
||||
class InUse(Exception):
|
||||
"""Another computer holds the session."""
|
||||
|
||||
def __init__(self, holder: Holder):
|
||||
super().__init__(f"In use by {holder.machine}")
|
||||
self.holder = holder
|
||||
|
||||
|
||||
class Lost(Exception):
|
||||
"""This token no longer holds the session."""
|
||||
|
||||
def __init__(self, holder: Holder | None):
|
||||
super().__init__("Another computer has taken over this library" if holder
|
||||
else "This computer no longer holds the session")
|
||||
self.holder = holder
|
||||
|
||||
|
||||
def _now_iso() -> str:
|
||||
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
|
||||
|
||||
class SessionLock:
|
||||
def __init__(self, *, lease: float = LEASE_SECONDS, clock=time.monotonic):
|
||||
self.lease = lease
|
||||
self._clock = clock
|
||||
self._lock = threading.Lock()
|
||||
self._holder: Holder | None = None
|
||||
#: The machine whose commands made the unsaved edits (see `touch`).
|
||||
self.last_editor: dict | None = None
|
||||
|
||||
# ---- reading --------------------------------------------------------------
|
||||
def _live(self, holder: Holder | None) -> bool:
|
||||
return holder is not None and self._clock() - holder.last_seen < self.lease
|
||||
|
||||
def holder(self) -> Holder | None:
|
||||
"""Who holds the session right now (None: free, or the lease ran out)."""
|
||||
with self._lock:
|
||||
return self._holder if self._live(self._holder) else None
|
||||
|
||||
def describe(self) -> dict | None:
|
||||
h = self.holder()
|
||||
return None if h is None else {"machine": h.machine, "since": h.since, "batch": h.batch}
|
||||
|
||||
# ---- changing -------------------------------------------------------------
|
||||
def acquire(self, client_id: str, machine: str, *, takeover: bool = False) -> Holder:
|
||||
"""Hold the session. Raises `InUse` when another computer holds it and
|
||||
`takeover` is not set. The same client re-acquiring keeps its uploads."""
|
||||
with self._lock:
|
||||
current = self._holder
|
||||
live = self._live(current)
|
||||
if live and current.client_id != client_id and not takeover:
|
||||
raise InUse(current)
|
||||
uploads = current.uploads if current is not None and current.client_id == client_id else set()
|
||||
self._holder = Holder(
|
||||
token=secrets.token_urlsafe(24), client_id=client_id, machine=machine,
|
||||
since=_now_iso(), last_seen=self._clock(), uploads=uploads,
|
||||
)
|
||||
return self._holder
|
||||
|
||||
def check(self, token: str | None) -> Holder:
|
||||
"""The holder this token names, renewing its lease. Raises `Lost`.
|
||||
|
||||
A token whose lease ran out is still honoured when nobody else has
|
||||
taken the session since — the same computer back from sleep."""
|
||||
with self._lock:
|
||||
current = self._holder
|
||||
if current is None or not token or not secrets.compare_digest(current.token, token):
|
||||
raise Lost(current if self._live(current) else None)
|
||||
current.last_seen = self._clock()
|
||||
return current
|
||||
|
||||
def heartbeat(self, token: str | None, batch: str | None) -> Holder:
|
||||
holder = self.check(token)
|
||||
holder.batch = batch
|
||||
return holder
|
||||
|
||||
def release(self, token: str | None) -> None:
|
||||
with self._lock:
|
||||
current = self._holder
|
||||
if current is not None and token and secrets.compare_digest(current.token, token):
|
||||
self._holder = None
|
||||
|
||||
def touch(self, holder: Holder) -> None:
|
||||
"""Record that `holder` made an edit — whose the unsaved ones are."""
|
||||
self.last_editor = {"client_id": holder.client_id, "machine": holder.machine}
|
||||
|
||||
def clear_editor(self) -> None:
|
||||
"""After a save or discard, nobody's edits are pending."""
|
||||
self.last_editor = None
|
||||
@@ -0,0 +1,70 @@
|
||||
"""The app-level bookkeeping around ONE open library, wherever it is kept.
|
||||
|
||||
Version history belongs to the app, not the adapter (see `app_state.py`), and
|
||||
until a library could live on a server it could only mean one thing: a git repo
|
||||
in this computer's app-data, keyed by the library's local path. A library held
|
||||
by a server is versioned THERE, beside the file it describes — so the open
|
||||
library carries the services that know where its history lives, and the routes
|
||||
ask them rather than the history module directly.
|
||||
|
||||
`LocalServices` is the whole of what used to be inline: nothing about a library
|
||||
on this computer changes. The remote implementation lives with the remote
|
||||
adapter (`adapters/remote/services.py`).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Protocol
|
||||
|
||||
from . import __version__, history
|
||||
from .core import registry
|
||||
|
||||
|
||||
class LibraryServices(Protocol):
|
||||
#: Whether this library is held by a server (its history lives there).
|
||||
remote: bool
|
||||
|
||||
def baseline(self) -> None: ...
|
||||
def commit_save(self, adapter, outcome) -> str | None: ...
|
||||
def history(self) -> list[history.HistoryEntry]: ...
|
||||
def restore(self, commit_id: str) -> bool: ...
|
||||
def clear_history(self) -> None: ...
|
||||
|
||||
|
||||
class LocalServices:
|
||||
"""History in this computer's app-data, keyed by the library's path."""
|
||||
|
||||
remote = False
|
||||
|
||||
def __init__(self, path: Path):
|
||||
self.path = path
|
||||
|
||||
def baseline(self) -> None:
|
||||
# An "as I found it" version (deduped, so re-opening an unchanged
|
||||
# library is a no-op). Best-effort.
|
||||
history.ensure_baseline(self.path)
|
||||
|
||||
def commit_save(self, adapter, outcome) -> str | None:
|
||||
# Not every platform is versioned. A library that is more than one file
|
||||
# has no single blob that IS the library, and it says so through its
|
||||
# capabilities rather than this module knowing which platforms those are.
|
||||
if adapter.capabilities().save.history and outcome.snapshot is not None:
|
||||
return history.commit(self.path, outcome.snapshot, outcome.summary, __version__)
|
||||
return None
|
||||
|
||||
def history(self) -> list[history.HistoryEntry]:
|
||||
return history.list_history(self.path)
|
||||
|
||||
def restore(self, commit_id: str) -> bool:
|
||||
"""Write a past version back as a NEW forward save. False if unknown.
|
||||
The caller reopens the library afterwards."""
|
||||
data = history.read_version(self.path, commit_id)
|
||||
if data is None:
|
||||
return False
|
||||
# The adapter's driver owns writing its own format back, even for a restore.
|
||||
registry.driver_for(self.path).restore(self.path, data)
|
||||
history.commit(self.path, data, f"Restored version {commit_id[:8]}", __version__)
|
||||
return True
|
||||
|
||||
def clear_history(self) -> None:
|
||||
history.clear_history(self.path)
|
||||
Loaded 100 of 170 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user