Compare commits

...
Author SHA1 Message Date
patben8 1464b1e211 Merge pull request #9 from MrPatben8/dev
Fixed issues on Windows, Implemented drag & drop importing, Improved STEM encoding speed
2026-10-13 17:47:09 +02:00
patben8 10f175b206 Bumped version number 2026-10-13 17:43:20 +02:00
patben8 a65ef959b2 Implemented drag to import 2026-10-13 17:42:24 +02:00
patben8 87cbd3720e Fixed STEM analysis not working on Windows 2026-10-13 10:59:22 +02:00
patben8 591f2bc791 Pararellized STEM aac encoding 2026-10-13 10:45:52 +02:00
patben8 ebe30c1128 Fixed analysis not working on windows 2026-10-12 23:49:19 +02:00
patben8 cd1914216f Fixed library options not appearing in windows 2026-10-12 23:26:33 +02:00
patben8 d10b11f8eb Merge pull request #8 from MrPatben8/dev
Fixed Rekordbox exports
2026-10-12 19:12:41 +02:00
patben8 79a8a843c5 Bumped version number 2026-10-12 19:12:09 +02:00
patben8 0204a322ff Fixed and pinned rekordbox exports 2026-10-12 19:10:20 +02:00
patben8 05051e7056 Merge pull request #7 from MrPatben8/dev
Implemented remote file exploring, fixed STEM playback and improved startup time.
2026-10-12 15:04:40 +02:00
patben8 b5dabbc8a0 Updated the readme 2026-10-12 15:02:46 +02:00
patben8 86bbb7b961 Bumped version number 2026-10-12 13:51:23 +02:00
patben8 d474c662db Fixed slow build startup time and implemented loading screen 2026-10-12 13:20:00 +02:00
patben8 a0df683fee Fixed stem playback not working in build 2026-10-12 11:31:44 +02:00
patben8 3385b794e9 Added setting for export playlist root folder toggle 2026-10-12 10:56:32 +02:00
patben8 2c352b76a1 Added konduktor settings menu 2026-10-12 10:15:14 +02:00
patben8 40630ff78e Added support for remote file exploring 2026-10-12 09:23:34 +02:00
patben8 966f3fe8c5 Bumped version number 2026-10-10 17:42:17 +02:00
patben8 a03b9056a9 Merge pull request #6 from MrPatben8/dev
Implemented dragging engine
2026-10-10 17:40:06 +02:00
patben8 26b556d975 Updated remote protocol version 2026-10-06 23:17:21 +02:00
patben8 c87444bda5 Implemented drag and drop loading 2026-10-06 23:08:34 +02:00
patben8 7ba71981c8 Implemented library rearrangement 2026-10-06 22:51:34 +02:00
patben8 89c7dade25 Tracks can be added to playlists via drag 2026-10-06 22:41:29 +02:00
patben8 b154df430a Implemented drag core and song reorganizing 2026-10-06 22:32:31 +02:00
patben8 e5c7b67626 Implemented playlist reorganizing 2026-10-06 22:25:01 +02:00
patben8 9f79f5a849 Search now includes comments 2026-10-05 23:16:12 +02:00
patben8 c8b86100f0 Track position in playlist can now be typed 2026-10-05 21:01:25 +02:00
patben8 0fac84cb73 Fixed issue with release pipeline 2026-10-04 21:57:40 +02:00
patben8 71ee877784 Merge pull request #5 from MrPatben8/dev
Implemented Key Analysis & Remote Library Management
2026-10-04 18:35:08 +02:00
patben8 920146f2c0 Bumped version number 2026-10-04 18:33:33 +02:00
107 changed files with 4995 additions and 821 deletions

No files matched your search

+9 -3
View File
@@ -55,10 +55,11 @@ jobs:
with:
python-version: "3.12"
# --- Step 1: freeze the FastAPI backend into a single-file sidecar ---
# --- Step 1: freeze the FastAPI backend into a onedir sidecar folder ---
# build_sidecar.* stages it as
# frontend/src-tauri/binaries/konduktor-sidecar-<triple>[.exe]
# which tauri.conf.json's externalBin bundles into the app.
# frontend/src-tauri/binaries/konduktor-sidecar/
# which tauri.macos.conf.json (bundle.macOS.files, keeps its symlinks) /
# tauri.windows.conf.json (bundle.resources) put in the app as `sidecar/`.
- name: Install backend deps
working-directory: backend
run: |
@@ -145,6 +146,8 @@ jobs:
- 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
@@ -180,6 +183,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
+101 -29
View File
@@ -1,21 +1,27 @@
# Building Konduktor for Windows
The desktop app can't be cross-compiled — a Windows build must be produced **on
Windows** (Tauri needs the MSVC toolchain + WebView2; PyInstaller must freeze the
backend into a Windows `.exe`). The macOS `.dmg` is built separately on a Mac.
The desktop app can't be cross-compiled. A Windows build must be produced **on
Windows**: Tauri needs the MSVC toolchain and WebView2, and PyInstaller must
freeze the backend into a Windows `.exe`. The macOS `.dmg` is built separately
on a Mac (see [docs/BUILDING.md](docs/BUILDING.md)).
This mirrors the macOS build exactly; only the toolchain install and the
sidecar-build command differ.
The recipe is the same as on macOS. Only the toolchain install and the
sidecar-build command differ. CI does exactly this on `windows-latest`
([.github/workflows/build.yml](.github/workflows/build.yml)), so if a local build
disagrees with CI, check that workflow first.
## One-time setup
1. **Rust** — install via <https://rustup.rs> (gives the `x86_64-pc-windows-msvc`
1. **Rust**: install via <https://rustup.rs> (gives the `x86_64-pc-windows-msvc`
toolchain). You also need the **MSVC C++ build tools**: install "Desktop
development with C++" from the Visual Studio Build Tools installer.
2. **WebView2 Runtime** — preinstalled on current Windows 10/11. If missing, get
the Evergreen runtime from Microsoft (Tauri's installer can also bootstrap it).
3. **Python 3.11–3.14** — <https://python.org> (tick "Add to PATH").
4. **Node 18+** — <https://nodejs.org>.
2. **WebView2 Runtime**: preinstalled on current Windows 10/11. If it's missing,
get the Evergreen runtime from Microsoft (Tauri's installer can also
bootstrap it).
3. **Python 3.11–3.14**: <https://python.org> (tick "Add to PATH"). CI builds
with **3.12**, the safest choice.
4. **Node 20.19+ or 22.12+**: <https://nodejs.org>. Vite 8 refuses older
versions, so Node 18 no longer works. CI uses Node 20.
Then, from the repo root:
@@ -33,49 +39,115 @@ npm install
cd ..
```
## Build
If PowerShell refuses to run `Activate.ps1` or `dev.ps1` ("running scripts is
disabled on this system"), either allow local scripts once with
`Set-ExecutionPolicy -Scope CurrentUser RemoteSigned`, or run a script with
`powershell -ExecutionPolicy Bypass -File .\dev.ps1`.
## Develop (no build)
```powershell
.\dev.ps1 # backend on :8000 + Vite on :5173, both reloading; Ctrl-C stops both
```
Then open <http://localhost:5173> in a browser. `dev.ps1` is the Windows
counterpart of `dev.sh`. It needs the `backend\.venv` and `frontend\node_modules`
from the setup above. It runs the Python source, not the frozen sidecar, so it
can't show desktop-shell behaviour (startup screen, quit prompt, WebView2, file
drops from Explorer). For that, run `npx tauri dev` in `frontend`. Note that this
still spawns the **frozen** sidecar staged in `src-tauri\binaries\`, so backend
changes need `build_sidecar.ps1` first.
### Tests
`backend/run_tests.sh` expects a POSIX venv (`.venv/bin/activate`), so it won't
run as-is on Windows. Run a suite directly with the venv's Python instead:
```powershell
# 1) Freeze + stage the backend sidecar (from the activated backend venv)
cd backend
.\.venv\Scripts\Activate.ps1 # if not already active
.\build_sidecar.ps1 # → frontend\src-tauri\binaries\konduktor-sidecar-<triple>.exe
.\.venv\Scripts\python.exe test_save_fidelity.py
```
## Build
One command does both steps and lists the installers it produced:
```powershell
.\build.ps1 # sidecar + app
.\build.ps1 -SkipSidecar # frontend-only change: reuse the staged sidecar
.\build.ps1 --debug # any other argument is passed on to `tauri build`
```
By hand, that is:
```powershell
# 1) Freeze + stage the backend sidecar
cd backend
.\build_sidecar.ps1 # → frontend\src-tauri\binaries\konduktor-sidecar\ (a folder)
cd ..
# 2) Build the app
# 2) Build the app (its beforeBuildCommand runs the Vite build)
cd frontend
npx tauri build
```
`build_sidecar.ps1` uses `backend\.venv\Scripts\python.exe` when it exists (else
whatever `python` resolves to), so the venv doesn't need to be activated. It
replaces the whole staged folder, so no file from an older build survives.
The sidecar is a PyInstaller **onedir** folder (`konduktor-sidecar.exe` plus
`_internal\`), not a single `.exe`. Don't switch it back to onefile; see
gotcha 4 in [CLAUDE.md](CLAUDE.md).
## Output
Installers land in:
```
frontend\src-tauri\target\release\bundle\msi\Konduktor_0.1.0_x64_en-US.msi
frontend\src-tauri\target\release\bundle\nsis\Konduktor_0.1.0_x64-setup.exe
frontend\src-tauri\target\release\bundle\nsis\Konduktor_<version>_x64-setup.exe
frontend\src-tauri\target\release\bundle\msi\Konduktor_<version>_x64_en-US.msi
```
Either one installs the app (bundling the sidecar `.exe` alongside it).
`<version>` is the `version` in [frontend/package.json](frontend/package.json),
the app's only version source. Either installer works. Releases ship only the
NSIS `-setup.exe`. Both put the sidecar folder in the app's `sidecar\` resource
folder (`tauri.windows.conf.json` → `bundle.resources`), where `lib.rs` spawns
`sidecar\konduktor-sidecar.exe`.
## Rebuilding after changes
Same as macOS: if you changed **backend** Python, re-run `build_sidecar.ps1`
first; then `npx tauri build`. Frontend-only changes just need `npx tauri build`
(its `beforeBuildCommand` rebuilds the web app).
If you changed **backend** Python, run `.\build.ps1` (or `build_sidecar.ps1`,
then `npx tauri build`). Frontend-only changes just need
`.\build.ps1 -SkipSidecar` (or `npx tauri build`).
## Not part of this build: the stem engine
Convert to Stems uses a separate program, `engine/` (torch + demucs), built and
released on its own channel by
[.github/workflows/engine.yml](.github/workflows/engine.yml) (`windows-x64-cpu`
and `windows-x64-cuda`). The app downloads it at runtime into a short
`%LOCALAPPDATA%\Konduktor\engine` path to stay under Windows' 260-character path
limit. You don't need it to build or run the app.
## Known Windows caveats
- **Unsigned build → SmartScreen.** We don't code-sign yet, so the first launch
shows a "Windows protected your PC" prompt. Click **More info → Run anyway**.
(Signing is a future step.)
- **Unsigned build → SmartScreen.** Builds aren't code-signed yet, so the first
launch shows a "Windows protected your PC" prompt. Click **More info → Run
anyway**.
- **Mixed content is already handled.** The webview is forced to the `http`
custom-protocol scheme (`use_https_scheme(false)` in `src-tauri/src/lib.rs`) so
it can fetch the sidecar at `http://127.0.0.1:<port>` without being blocked.
Leave that setting as-is.
- **Sidecar console window.** The sidecar is frozen as a console app (needed for
the `KONDUKTOR_PORT` stdout handshake). Tauri's shell plugin normally spawns it
without a visible window; if a console flashes on launch, tell me and we'll add
the `CREATE_NO_WINDOW` spawn flag.
- **The sidecar must be frozen on Windows** — a macOS-built sidecar won't run.
- **The sidecar is a console app, but no console appears.** It's frozen with
`console=True` because the shell reads the `KONDUKTOR_PORT=<n>` line from its
stdout. Tauri's shell plugin spawns it with `CREATE_NO_WINDOW`, so no window
flashes.
- **The sidecar doesn't watch stdin on Windows.** On macOS it exits when its
stdin closes. On Windows a pending stdin read stalled loading scipy's OpenBLAS
DLL, which hung the first analysis, so it waits on the parent process instead
(`backend/sidecar.py`). Keep this in mind before touching that watcher.
- **Decode audio through `waveform.load`, never `librosa.load`.** librosa reads
AAC only through CoreAudio or a system ffmpeg, so on Windows every `.m4a` /
`.stem.m4a` failed with "Format not recognised". PyAV bundles FFmpeg.
- **The sidecar must be frozen on Windows.** A macOS-built sidecar won't run.
`build_sidecar.ps1` handles this; just don't copy binaries between OSes.
+197 -25
View File
@@ -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
@@ -155,7 +170,14 @@ Two independent apps that talk over HTTP:
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,
muxed IN LOCKSTEP, plus a `moov/udta/stem` JSON box appended in place
(moov is last, so only two sizes change). The separation is a CALLBACK —
(moov is last, so only two sizes change). **Each stream encodes on its
own thread** (PyAV releases the GIL in FFmpeg; ~3x faster with `aac`,
104 → 35 s for a 5-minute track's real stems) while ONE thread muxes in
the single-threaded order, so the file is byte-identical; every codec is
opened and the header written before a worker starts, since the first
`mux()` would otherwise open codecs a worker is using. `aac_coder=fast`
was measured and rejected: 3-4x faster per stream, but it drops whole
8-20 kHz bands for moments (twoloop: never). The separation is a CALLBACK —
the backend never imports torch; the engine (below) supplies it, the
tests a fake. Measured traps: FFmpeg's resampler upmixes mono at -3 dB,
so mono is duplicated by hand; resampling does not move time; both
@@ -553,7 +575,11 @@ Two independent apps that talk over HTTP:
/ `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`,
so a cancel deletes only its own), `fs/list|space`, `folder/tracks|audio|leads`
(the content folder as a Files tree: tags via the shared `FolderScanner`,
file facts, `held` = file → the library's id; audio only for a file a
listing returned, confined; `leads` = the analysis lead per file, None
unless the platform analyses), `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"`.
@@ -602,6 +628,21 @@ Two independent apps that talk over HTTP:
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`).
**The content folder browsed like a drive** (decided 2026-10-10,
`folder.py`): `/api/fs/drives` lists the server FIRST (`kind:
"server"`, path `server:`) while a remote is open, and the ordinary
Files routes (`/api/fs/folders`, `/api/folder/*`) take `server:` +
the path ON THE SERVER — so the folder view, deck and add dialog need no
second set of routes, and a server path is never taken for the same path
here. `RemoteAdapter.folder_listing` remembers what was listed
(`ServerFiles`, a read-only source); `folder_audio` downloads into the
shared cache by the same facts as a library track's. Adding one is IN
PLACE (`on_library_host` → `importer.plan_on_host` + `run(reference=True)`):
nothing uploaded, nothing asked; files the library holds map to their
ids; where the server reports a lead the file is fetched and analysed
here, as an upload is. Server paths go back to the server in its own
spelling (`_server_paths`), never `str(Path(…))`, which rewrites them on
Windows.
**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`,
@@ -776,9 +817,17 @@ Two independent apps that talk over HTTP:
expandable Local Storage. A drive carrying a OneLibrary library opens as a
device as before, and EVERY drive has a lazily-fetched **Files** tree;
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`). A browsed device is read-only (cause `browsing`); **"Open for
table, with files the collection already holds checked off in the #
column (`TrackTable`'s `marked`). **A held file's row IS the collection
track** (decided 2026-10-10: `main._folder_rows`; `FolderTracks.files` maps
its collection id back to the folder id that adding takes): it shows the
collection's key/rating/cues/plays, loads into the deck as origin
`collection` (`loadTrack`), edits inline and from the menu, and drops onto
a playlist directly. The table runs on the COLLECTION's capabilities; a
LOOSE row's edit — inline (`TableMeta.mayEdit`, asked before the editor
opens), rating, Edit Tags / Analyze / Auto Hotcues / Stems — asks to add
it first (`askToAdd`), and in the deck it stays read-only
(`not_in_library`). 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).
@@ -811,6 +860,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 /
@@ -818,8 +882,18 @@ Two independent apps that talk over HTTP:
shell quits anyway after ~2 s without one, so a hung page cannot trap the
user), quits (`quit_now`) when nothing is unsaved, else asks Save · Discard
· Cancel; the sidecar is killed only at `RunEvent::Exit`, after the answer;
browser dev gets `beforeunload`), `SaveBar` (+ "Discard changes…" when
dirty, and the settings gear beside it, whose menu opens `ShortcutsDialog` — the shortcut list is written out BY HAND, so a new or changed shortcut in `PrepStrip` / `TrackTable` must be added there too), `Toolbar` (search/filters; columns are chosen by right-clicking the table header),
browser dev gets `beforeunload`), `StartupGate` (mounted in `main.tsx`
around everything but `AmbientBackdrop`: the shell opens the window AT ONCE
and starts the sidecar beside it, so nothing that calls the API mounts
until `backend_status` / `konduktor://backend` says ready, which is when
`setApiBase` gets the sidecar's address. Meanwhile `StartupScreen` shows
the icon with a generated waveform scrolling under a fixed playhead, a
"first launch takes longer" note after 6 s, Quit / Keep waiting after 90 s,
and if the sidecar exits its last 30 output lines with Copy details / Quit
/ Try again (`backend_restart`). The shell has no timeout of its own. Before
ready it answers quit requests itself — nothing can be unsaved — and stops
at ready so it never races `QuitGuard`), `SaveBar` (+ "Discard changes…" when
dirty, and the settings gear beside it, whose menu opens `ShortcutsDialog` — the shortcut list is written out BY HAND, so a new or changed shortcut in `PrepStrip` / `TrackTable` must be added there too — and `AppSettings` ("Konduktor Settings…": app-level prefs, each with its default in `APP_SETTING_DEFAULTS` and read through `useAppSetting`; today `expandPlaylistFolders` and `exportRootFolder`, both default off — the latter read by the backend at `run_export` and passed down as `ExportPayload.root_folder`. The Sidebar holds folder open state as per-id overrides of that setting, reset on a new library or a change of the setting, and carried to the new ids when a rename/move changes a folder's path id)), `Toolbar` (search/filters; columns are chosen by right-clicking the table header),
`TrackTable` (**the one track list** — All Tracks, playlists, exports and
devices. TanStack Table + **virtualized** grid; per-row play button,
configurable columns, header sorting, inline double-click editing, and
@@ -838,7 +912,43 @@ 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.
**Files from Finder / Explorer** (decided 2026-10-13) ride the same store
as a `files` payload: `lib/fileDrop.ts` feeds Tauri's `onDragDropEvent`
(real paths; a plain browser has none, so no file drop there) through
`nativeDragStart`/`Move`/`End`, refused at enter while an `aria-modal`
dialog is open or no library is loaded. A playlist/export row opens
`AddFilesDialog` with its target, ONE audio file on the deck loads it to
listen to, anywhere else (App's root target, with a window overlay) adds
to the collection — or says why the library cannot. `POST
/api/folder/dropped` resolves the paths first (`FolderScanner.dropped`:
folders RECURSIVELY, capped at `MAX_DROPPED`; single files held apart
from the folder cache so a partial listing never hides a folder's other
files from the sidebar) and makes each file addable and playable through
the folder routes. Copy vs in place is asked as for a browsed folder; the
add preview counts external-drive files PER FILE (`removable_count` /
`removable_drives`, a drop can mix drives) and `in_destination`.
`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
@@ -884,7 +994,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`
@@ -1006,6 +1120,7 @@ Two independent apps that talk over HTTP:
```bash
./dev.sh # start both servers (see README for one-time setup)
.\dev.ps1 # the same on Windows (BUILDING-WINDOWS.md)
# Backend
cd backend && source .venv/bin/activate
@@ -1051,10 +1166,17 @@ serialization path.** It enforces:
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.
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
@@ -1071,7 +1193,10 @@ serialization path.** It enforces:
48 kHz resampling does not move time; MP3 and FLAC through both encoders give
five streams with only the mix enabled, no shift (cross-correlation), the
bitrate rule (256 floor, lossless 320), every tag + cover; `verify` refuses a
shifted, truncated or box-less file; a raising checkpoint cancels.
shifted, truncated or box-less file; a raising checkpoint cancels. The
threaded encode is byte-identical to a single-threaded reference (with each
encoder present), reports progress 0 → 1, and a cancel or a failing encoder
thread leaves no thread running.
- `test_stem_swap.py` — `apply_stem_swaps` on a temp copy of the real
collection with a generated MP3 (with header) and a real stem file: prep
reads back at the same decoded second while its START moves by the 2257-
@@ -1122,7 +1247,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`
@@ -1161,7 +1288,8 @@ serialization path.** It enforces:
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; and the stick hazards — another app's write refused, an unplugged
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
@@ -1198,6 +1326,9 @@ serialization path.** It enforces:
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
@@ -1262,7 +1393,11 @@ serialization path.** It enforces:
scan did not find; **a file the collection already points at is never added
twice** (on Traktor that would be two ENTRYs sharing a primary key — a corrupt
collection) but still reaches the playlist/export it was headed for; "copy"
points the entry at the copy and "reference" at the original.
points the entry at the copy and "reference" at the original. And a DROP
(`/api/folder/dropped`): folders recursively minus hidden ones, dropped
non-audio counted as skipped, only what was dropped becomes streamable, the
folder's own listing stays whole, the cap, held files as their collection
track, and the preview's per-file external-drive count and `in_destination`.
- `test_picker.py` — the picker's routes. Pins the scoping, because the bug it
replaced was invisible: `/api/library/options` flattened every driver's
detections and returned `[0]`, so a plugged-in USB stick could be offered as
@@ -1345,7 +1480,11 @@ serialization path.** It enforces:
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.
reopening names the holder and the edits left, leaving releases. And the
content folder as a drive: listed first, confined, held files ticked off,
auditioned with one download, an add IN PLACE (no upload, the held one not
added twice, both into the playlist, analysed here when the server reports
a lead).
- `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
@@ -1366,14 +1505,25 @@ frontend at `http://localhost:5173`.
1. **`traktor-nml-utils` MUST come from GitHub, not PyPI.** PyPI's `3.1.0` is
stale and **cannot parse Traktor Pro 4 (NML v20)** files — its strict parser
dies on the v4 `<GRID>` element inside `CUE_V2`. `requirements.txt` pins the
GitHub `master` (v4.0.0). Do not "simplify" this to a plain PyPI pin.
dies on the v4 `<GRID>` element inside `CUE_V2`. `requirements.txt` pins a
GitHub commit (v4.0.0). Do not "simplify" this to a plain PyPI pin.
**`pyrekordbox` is now the same situation**: PyPI's latest (0.4.4) has no
`devicelib_plus`, which is the OneLibrary (`exportLibrary.db`) reader, so
`requirements.txt` pins the GitHub master. That upgrade renamed `db6` →
`masterdb` and `tables` → `models` and moved `BLOB` out of `db6.database`;
the Rekordbox adapter uses the new names. `db6` still works as a deprecated
alias and is **removed in 0.6.0**.
`onelibrary` module, which is the OneLibrary (`exportLibrary.db`) reader
(`OneLibrary` class; `devicelib_plus` / `DeviceLibraryPlus` before upstream's
rename), nor `masterdb` (formerly `db6`, now removed upstream; `tables` →
`models`, `BLOB` in `masterdb.database`).
**Both GitHub deps are pinned to a COMMIT, never bare master**: the
`devicelib_plus` → `onelibrary` rename reached CI's fresh install while dev
venvs kept the old commit, and a release shipped that could not export or
read OneLibrary while every local test passed. Move a pin on purpose, with
`./run_tests.sh`.
**PyAV: open files for reading through `core/pyav.open_input`, never
`av.open` directly.** PyAV 18 refuses a file with non-UTF-8 tags unless
given `metadata_errors="ignore"`; PyAV 19 removed that keyword. CI installs
fresh (it got 19) while a dev venv keeps what it had (18), so code passing
the keyword passed every local test and shipped a release whose deck played
every stem track as the mix. `requirements.txt` caps `av<20`: check
`pyav.py` before raising it.
2. **The collection is real, irreplaceable data — protect it.** Every save
writes a timestamped `.bak` first (into a `backups/` folder next to the
collection). When testing writes, point `KONDUKTOR_NML` at a COPY. Warn the
@@ -1383,6 +1533,21 @@ frontend at `http://localhost:5173`.
render is the library's own pipeline (see "Write path"), which reproduces
Traktor's byte-exact layout so a no-op save is byte-identical and only edited
objects diff. `test_save_fidelity.py` enforces this.
4. **The desktop sidecar is a PyInstaller ONEDIR folder — never go back to
onefile.** A onefile binary unpacked ~390 native libraries into a NEW temp
folder on every launch, and macOS (XProtect / syspolicyd) checks each library
it has not seen before as it is dlopen()ed, keyed per FILE: the window
appeared only after ~10 s on every launch (measured 2026-10-12: 95 s to load
them all fresh, 1 s once seen). As a folder in the app they are checked
once; a launch is ~0.5 s. `build_sidecar.*` stages
`src-tauri/binaries/konduktor-sidecar/`; `lib.rs` spawns
`<resources>/sidecar/konduktor-sidecar[.exe]`. On macOS it is bundled by
`tauri.macos.conf.json`'s `bundle.macOS.files`, NOT `bundle.resources`:
the resource copier follows symlinks, turning PyInstaller's 37 library
aliases (`_internal/libavcodec… -> av/.dylibs/…`, `Python.framework`'s
`Versions/Current`) into second copies a library could be loaded twice
from. Windows has no such links and uses `resources`
(`tauri.windows.conf.json`).
## Data model notes
@@ -1648,7 +1813,11 @@ that number and nothing else — everything derives from it:
**volume-relative** `DIR`, never a host path — so a USB export is portable by
construction, and the `.nml` cannot be written until the destination is known.
Also settled: loose tracks land in an **"Other" playlist**, playlist folders
are preserved, and the export is a **standalone `collection.nml`** the user
are preserved — at the exported library's TOP LEVEL by default; the
`exportRootFolder` setting (`ExportPayload.root_folder`) nests the whole
tree, Other included, in one folder named after the export, in all four
writers (decided 2026-10-12: the export is a library of its own, so the
wrapper was one more click at the gig), and the export is a **standalone `collection.nml`** the user
swaps into a Traktor install — so it needs the full skeleton, verified from the
real file: `<NML VERSION="20">`, `<HEAD>`, `<COLLECTION ENTRIES>`,
`<SETS ENTRIES="0">`, `<PLAYLISTS>` wrapping a `$ROOT` FOLDER node with a
@@ -1679,7 +1848,7 @@ that number and nothing else — everything derives from it:
deliberately NOT in the fixture, since they carry the machine's name and
UUIDs; those are generated fresh per export.
- **The two Pioneer key blobs are different.** `masterdb`'s key and
`devicelib_plus`'s are not the same string; mixing them up yields a database
`onelibrary`'s are not the same string; mixing them up yields a database
Rekordbox cannot open.
`adapters/onelibrary/export.py` writes a whole drive (`PIONEER/rekordbox/
exportLibrary.db` from the checked-in DDL, plus ANLZ under `PIONEER/USBANLZ/`,
@@ -1895,6 +2064,9 @@ 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,
+125 -240
View File
@@ -1,256 +1,141 @@
# Konduktor
<p align="center">
<img src="design/konduktor-icon.svg" width="96" alt="Konduktor icon">
</p>
**A fast, modern home for your Traktor collection.**
<h1 align="center">Konduktor</h1>
Konduktor is a lightweight desktop-style app for DJs who run **Native
Instruments Traktor** (Pro 4 / NML v20). It opens your existing
`collection.nml`, gives you a beautiful dark library to explore, and lets you
build playlists and prep tracks — without launching the whole heavyweight
Traktor app just to tidy up your tags or drop a few cue points.
<p align="center">
<b>Prep your tracks and run your DJ libraries in one fast app.</b><br>
Traktor, Rekordbox, or the USB stick in your pocket.
</p>
Your collection stays exactly where it is. Konduktor reads and writes the same
file Traktor uses, so everything you do shows up next time you open Traktor.
<p align="center">
<a href="https://github.com/MrPatben8/konduktor/releases"><b>Download for macOS & Windows</b></a>
</p>
![Konduktor: the prep deck with a track loaded, above a playlist](docs/screenshots/library.png)
Konduktor opens the library you already have, in the format it already uses.
You can tidy tags, build playlists, set grids and cues, and pack a USB stick
for the gig without launching your full DJ software. When you open your DJ
software again, everything you changed is there.
---
## Why you'll like it
## One app for every library
- **Instant, searchable library.** Your whole collection loads into a snappy,
virtualized grid. Search, filter by genre / key / BPM / rating, and sort by
any column — all instant, no waiting.
- **Make it yours.** Show only the columns you care about, drag them into the
order you like, and resize them to fit. Your layout is remembered.
- **Edit tags without the ceremony.** Double-click any field to fix a title or
genre on the spot, click the stars to rate a track, or right-click for a full
tag + cover-art editor. Great for quick one-off fixes.
- **Playlists, the easy way.** Create, rename, and delete playlists, then
drag-and-drop to reorder or add tracks.
- **A real prep deck.** Load any track into the deck at the top and:
- play it with a **frequency-colored waveform** (Traktor-style Spectrum look),
scrolling under a fixed playhead with zoom in/out
- scratch it by dragging the waveform
- see and adjust the **beatgrid** and BPM
- set, jump to, and delete **hotcues** (with a color-coded 8-slot bar)
- build **loops** in fixed beat sizes, tied into the hotcue system
- use keyboard shortcuts: **Space** to play/pause, **1–8** to fire hotcues,
**Shift+1–8** to clear them
- **Your data is safe.** Every save makes a timestamped backup first, and only
ever touches the parts you changed — the rest of the file stays byte-for-byte
identical.
<img src="docs/screenshots/platforms.png" align="right" width="420" alt="Choosing a platform: Rekordbox, Traktor, OneLibrary or Remote">
- **Traktor** collections.
- **Rekordbox** libraries.
- **OneLibrary** USB sticks, the format CDJs read. Plug one in to browse it,
preview tracks off it, import them, or edit the stick directly.
- **Remote** libraries: keep your whole library and music on a home server and
open it from any laptop ([set up a server](docs/REMOTE-SERVER.md)).
- **Any folder or drive**: browse loose audio files, preview them, and add
them to your library.
Your library is never converted into a Konduktor database. Saves write back to
the original file and change only what you edited.
<br clear="right">
## A real prep deck
![The prep deck in beatgrid editing mode](docs/screenshots/deck.png)
- A scrolling waveform, coloured by frequency, with zoom, scratching and an
overview of the whole track.
- Eight hotcue pads with names, types and colours, plus beat loops, beat jump
and tap tempo.
- **Beatgrid editing**, including grids with tempo changes. Nudge, retempo,
halve or double without opening your DJ software.
- Keyboard shortcuts for the whole deck: Space to play, 1–8 for hotcues,
arrow keys to jump or move a loop.
## Stems, built in
![A stem file in the deck: drums, bass, synths and vocals each in their own lane](docs/screenshots/stems.png)
**Play stem files as stems.** Load a stem file and the deck splits into
drums, bass, synths and vocals, each drawn in its own lane. Click a lane's
button to mute it, Alt/Option-click to solo it, or use Q W E R.
**Convert to Stems.** In a Traktor collection, right-click any tracks and
choose Convert to Stems. They come back as standard Traktor stem files with their tags, cover art, cues and
beatgrid intact.
- The separation runs on your own computer, so your music isn't sent to an
online service.
- Replace the originals, or save the stems to a folder and add them as new
tracks.
- Convert a whole playlist in one go.
## Let it do the boring parts
| Auto Hotcues | Analyze |
|:---:|:---:|
| ![Auto Hotcues: choose an event for each pad](docs/screenshots/auto-hotcues.png) | ![Analyze: BPM, grid and key](docs/screenshots/analyze.png) |
| Pick an event for each pad (first beat, build, drop, breakdown, outro). Konduktor finds them in the track and places the cues. Run it on one track or a whole playlist. | Detects tempo, beatgrid and musical key, for one track or hundreds. |
## Export to USB for CDJs, or other platforms
<img src="docs/screenshots/export.png" align="right" width="380" alt="An export set for OneLibrary, Traktor and Rekordbox">
Make an **export** in the sidebar, drag playlists onto it, and press Export.
One stick can carry a Traktor collection, a OneLibrary library for current
CDJs and a Rekordbox Device Library for older players, all sharing **one copy
of the audio**.
- Hotcues, memory cues, loops, grids, keys and cover art are converted for
each platform.
- Playlists stay linked: edit a playlist, re-export, and the stick catches up.
- Re-exports copy only what changed, so updating a stick is quick.
- Konduktor only ever clears a folder that it wrote itself.
<br clear="right">
## Your library is safe
- **Saves are surgical.** A Traktor save changes only the entries you edited.
The rest of the file stays byte-for-byte identical.
- **Backups and history.** Every Traktor save makes a backup first and is kept
in a version history that you can restore from in the app.
- **Nothing is written until you press Save.** Discard changes throws away
everything you did since your last save.
- Tag edits are also written into the audio files themselves, so other apps
see them too.
## And also
- A fast library with search, filters, sorting and columns you can rearrange,
even with thousands of tracks.
- Edit tags inline or in a full tag and cover-art editor.
- Drag and drop tracks onto playlists, exports or the deck, and drag playlists
to reorganise them.
- If you open a Traktor collection on a different computer or drive,
Konduktor finds the missing files for you.
---
## Getting started
## Get Konduktor
Konduktor runs as two small local servers (a Python backend and a web
frontend). Do the one-time setup, then start them — the same steps work on
macOS, Linux, and Windows.
Download the latest build from
[**Releases**](https://github.com/MrPatben8/konduktor/releases):
a `.dmg` for macOS (Apple Silicon) and a `-setup.exe` for Windows.
### 1. Install (once)
> **First launch:** builds aren't notarised yet, so your OS will warn you the
> first time.
> **macOS:** right-click the app, choose **Open**, then **Open** again. If it
> still refuses, run `xattr -cr /Applications/Konduktor.app` once.
> **Windows:** click **More info → Run anyway**.
**Backend** — needs Python 3.11+. Create a virtual environment and install the
dependencies:
> **Using Traktor?** Close it before saving in Konduktor. Traktor rewrites
> `collection.nml` when it quits, which would overwrite your changes.
```bash
cd backend
python3 -m venv .venv # Windows: python -m venv .venv
```
Want to run it from source or build it yourself? See
[docs/BUILDING.md](docs/BUILDING.md).
Activate it, then install:
## License
```bash
source .venv/bin/activate # Windows (PowerShell): .\.venv\Scripts\Activate.ps1
pip install -r requirements.txt
cd ..
```
**Frontend** — needs Node 18+ (same on every platform):
```bash
cd frontend
npm install
cd ..
```
### 2. Run it (development)
Konduktor runs as two local servers (backend on `:8000`, frontend on `:5173`).
**macOS / Linux** — one command starts both:
```bash
./dev.sh
```
**Windows** — start each server in its own terminal:
```powershell
# Terminal 1 — backend
cd backend; .\.venv\Scripts\Activate.ps1; uvicorn konduktor.main:app --reload --port 8000
# Terminal 2 — frontend
cd frontend; npm run dev
```
Either way, open **http://localhost:5173** in your browser (`Ctrl-C` stops a
server). This is the fastest way to try Konduktor or hack on it — the frontend
hot-reloads as you edit. To package a real double-clickable app instead, see
[Build a standalone app](#build-a-standalone-app-production) below.
### 3. Open your collection
On launch, Konduktor offers to:
- **Automatically** open the collection from your latest installed Traktor,
- reopen the **last collection** you used, or
- **browse** for a `collection.nml` yourself.
That's it — you're in.
---
## Build a standalone app (production)
Prefer a real double-clickable app over running the dev servers? Konduktor
packages into a native desktop app (via **Tauri**) that bundles the Python
backend as a sidecar — no terminal, no servers to start by hand.
### Extra prerequisites
On top of the Python 3.11+ and Node 18+ from above:
- **Rust** — install from <https://rustup.rs> (the app shell is Tauri/Rust).
- **PyInstaller** — into the backend venv:
`pip install -r backend/requirements-build.txt`
- **Windows only:** also the MSVC C++ build tools and the WebView2 runtime — see
[BUILDING-WINDOWS.md](BUILDING-WINDOWS.md) for the one-time toolchain setup.
The build is a two-step recipe on both platforms: **freeze the backend into a
sidecar binary**, then **build the app**. The only difference is which sidecar
script you run — `.sh` on macOS/Linux, `.ps1` on Windows. Each build runs on its
own OS (the app can't be cross-compiled).
### macOS / Linux
```bash
# 1) Freeze the backend into a sidecar binary (from the activated backend venv)
cd backend && source .venv/bin/activate && ./build_sidecar.sh && cd ..
# 2) Build the app
cd frontend && npx tauri build
```
The installer lands at
`frontend/src-tauri/target/release/bundle/dmg/Konduktor_<version>_aarch64.dmg`
(with the `.app` beside it).
### Windows
```powershell
# 1) Freeze the backend into a sidecar binary (from the activated backend venv)
cd backend; .\.venv\Scripts\Activate.ps1; .\build_sidecar.ps1; cd ..
# 2) Build the app
cd frontend; npx tauri build
```
The installers land in `frontend\src-tauri\target\release\bundle\` (an `.msi` and
an NSIS `-setup.exe`). See [BUILDING-WINDOWS.md](BUILDING-WINDOWS.md) for the full
walkthrough and Windows-specific notes.
> **First launch — getting past the OS security prompt.** Builds are
> **ad-hoc signed, not notarized** (no paid Apple/Windows developer cert yet), so
> the OS flags them the first time. This is expected — the app isn't damaged.
>
> - **macOS:** right-click the app → **Open** → **Open** (or System Settings →
> Privacy & Security → **Open Anyway** after the first blocked attempt). If it
> still refuses — common for a `.dmg` downloaded via a browser, which macOS
> quarantines — clear the quarantine flag once from Terminal:
> ```bash
> xattr -cr /Applications/Konduktor.app
> ```
> - **Windows:** click **More info → Run anyway** past SmartScreen.
>
> The macOS `.dmg` is Apple-Silicon (`aarch64`) only.
> **Faster local builds:** `npx tauri build --debug --bundles app` skips the
> optimizer and the installer, giving you a runnable app in seconds — handy while
> iterating.
### Rebuilding after changes
Changed **backend** Python? Re-run the sidecar script for your OS
(`./build_sidecar.sh` or `.\build_sidecar.ps1`), then `npx tauri build`.
Frontend-only change? Just `npx tauri build` — it rebuilds the web app for you.
---
## Saving back to Traktor
Playlist edits, tag changes, and prep tweaks all apply live in the app. When
you're happy, hit **Save to Traktor** to write them to `collection.nml`.
> ⚠️ **Close Traktor before saving.** Traktor rewrites `collection.nml` when it
> quits, so if it's open it will overwrite your changes. Konduktor always writes
> a backup first (into a `backups/` folder next to your collection), but closing
> Traktor first is the safe habit.
Want to experiment risk-free? Point Konduktor at a *copy* of your collection and
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)
and speaks Traktor's real file format — no import/export, no separate database.
- Run it in your browser from source, or package it into a native desktop app
(macOS `.dmg` / Windows `.msi`) that bundles the backend — see
[Build a standalone app](#build-a-standalone-app-production). A mobile version
is on the horizon.
- Under the hood: **FastAPI** (Python) backend + **React / TypeScript / Vite**
frontend. Curious about internals or contributing? See
[CLAUDE.md](CLAUDE.md) for the architecture and conventions.
[AGPL-3.0](LICENSE)
+17 -10
View File
@@ -1,6 +1,7 @@
# Build the frozen backend sidecar on Windows (PyInstaller) and stage it for
# Tauri as binaries\konduktor-sidecar-<target-triple>.exe.
# Output: backend\dist\konduktor-sidecar.exe + frontend\src-tauri\binaries\...
# Build the frozen backend sidecar on Windows (a PyInstaller onedir folder) and
# stage it for Tauri as frontend\src-tauri\binaries\konduktor-sidecar\, which
# tauri.conf.json bundles as a resource folder (`sidecar\` in the app).
# Output: backend\dist\konduktor-sidecar\ + frontend\src-tauri\binaries\konduktor-sidecar\
#
# Run from a PowerShell prompt with the backend venv's Python on PATH, e.g.:
# cd backend
@@ -15,13 +16,19 @@ Set-Location $Root
$Py = Join-Path $Root ".venv\Scripts\python.exe"
if (-not (Test-Path $Py)) { $Py = "python" }
& $Py -m PyInstaller --noconfirm --clean konduktor-sidecar.spec
Write-Host "Built: $Root\dist\konduktor-sidecar.exe"
# PyInstaller logs to stderr. Windows PowerShell 5.1 (unlike pwsh 7) turns a
# native command's stderr into an error record, which "Stop" makes fatal on the
# first INFO line — so relax it for this call and judge by the exit code.
$ErrorActionPreference = "Continue"
& $Py -m PyInstaller --noconfirm --clean konduktor-sidecar.spec 2>&1 | ForEach-Object { "$_" }
$ErrorActionPreference = "Stop"
if ($LASTEXITCODE -ne 0) { throw "PyInstaller failed ($LASTEXITCODE)" }
Write-Host "Built: $Root\dist\konduktor-sidecar\"
# Stage for Tauri: name with the host target triple + .exe so the shell plugin
# resolves it. (rustc must be on PATH.)
$Triple = (& rustc -vV | Select-String '^host: ').ToString().Replace('host: ', '').Trim()
# Stage for Tauri, replacing the whole folder so no file from an older build survives.
$Dest = Join-Path $Root "..\frontend\src-tauri\binaries"
New-Item -ItemType Directory -Force -Path $Dest | Out-Null
Copy-Item "$Root\dist\konduktor-sidecar.exe" (Join-Path $Dest "konduktor-sidecar-$Triple.exe") -Force
Write-Host "Staged: $Dest\konduktor-sidecar-$Triple.exe"
$Staged = Join-Path $Dest "konduktor-sidecar"
if (Test-Path $Staged) { Remove-Item -Recurse -Force $Staged }
Copy-Item -Recurse "$Root\dist\konduktor-sidecar" $Staged
Write-Host "Staged: $Staged\"
+19 -23
View File
@@ -1,7 +1,8 @@
#!/usr/bin/env bash
# Build the frozen backend sidecar (single-file binary) with PyInstaller and
# stage it for Tauri as binaries/konduktor-sidecar-<target-triple>.
# Output: backend/dist/konduktor-sidecar + frontend/src-tauri/binaries/…
# Build the frozen backend sidecar (a onedir folder) with PyInstaller and stage
# it for Tauri as frontend/src-tauri/binaries/konduktor-sidecar/, which
# tauri.conf.json bundles as a resource folder (`sidecar/` in the app).
# Output: backend/dist/konduktor-sidecar/ + frontend/src-tauri/binaries/konduktor-sidecar/
#
# One-time: pip install -r requirements-build.txt (into the backend venv).
set -euo pipefail
@@ -9,25 +10,20 @@ ROOT="$(cd "$(dirname "$0")" && pwd)"
cd "$ROOT"
PY="${PY:-.venv/bin/python}"
"$PY" -m PyInstaller --noconfirm --clean konduktor-sidecar.spec
echo "Built: $ROOT/dist/konduktor-sidecar"
echo "Built: $ROOT/dist/konduktor-sidecar/"
# NOTE: do NOT re-codesign this binary. PyInstaller already ad-hoc signs the
# one-file bootloader AND its packed libraries (Python.framework, etc.) with a
# matching identity. Re-signing only the outer bootloader (e.g. `codesign -s -`)
# desyncs the Team IDs, so at runtime dlopen of the extracted Python framework
# fails with "different Team IDs" and the sidecar dies on launch (which makes
# the Tauri app panic: "backend sidecar did not report a port"). The app bundle
# is ad-hoc signed separately via tauri.conf.json `bundle.macOS.signingIdentity`,
# which seals this binary without re-signing it.
# NOTE: do NOT re-codesign anything in this folder. PyInstaller already ad-hoc
# signs the executable AND its collected libraries (Python, the .so/.dylib
# files) with a matching identity. Re-signing only some of them desyncs the
# Team IDs, so dlopen fails with "different Team IDs" and the sidecar dies on
# launch (the app then shows "Konduktor couldn't start"). The app bundle is
# ad-hoc signed separately via tauri.conf.json `bundle.macOS.signingIdentity`,
# which seals this folder as a resource without re-signing it.
# Stage for Tauri: the sidecar must be named with the host target triple so the
# shell plugin can resolve it in both dev and bundle. (rustc must be on PATH.)
if command -v rustc >/dev/null 2>&1; then
TRIPLE="$(rustc -vV | sed -n 's/host: //p')"
DEST="$ROOT/../frontend/src-tauri/binaries"
mkdir -p "$DEST"
cp "$ROOT/dist/konduktor-sidecar" "$DEST/konduktor-sidecar-$TRIPLE"
echo "Staged: $DEST/konduktor-sidecar-$TRIPLE"
else
echo "warning: rustc not found — skipped staging the Tauri sidecar binary" >&2
fi
# Stage for Tauri. Replace the whole folder so no file from an older build
# survives; `cp -R` keeps PyInstaller's symlinks as symlinks.
DEST="$ROOT/../frontend/src-tauri/binaries"
mkdir -p "$DEST"
rm -rf "$DEST/konduktor-sidecar"
cp -R "$ROOT/dist/konduktor-sidecar" "$DEST/konduktor-sidecar"
echo "Staged: $DEST/konduktor-sidecar/"
+20 -4
View File
@@ -1,6 +1,14 @@
# PyInstaller spec for the Konduktor backend sidecar (Step 1 of the standalone
# build). Produces a single-file binary that serves the FastAPI API on a free
# loopback port. Build with: pyinstaller konduktor-sidecar.spec (or build_sidecar.sh)
# build). Produces a ONEDIR build — dist/konduktor-sidecar/ holding the
# executable plus `_internal/` — that serves the FastAPI API on a free loopback
# port. Build with: pyinstaller konduktor-sidecar.spec (or build_sidecar.sh)
#
# Onedir, NOT onefile: a onefile binary unpacks ~300 MB (1,000+ files, ~390
# native libraries) into a NEW temp folder on every launch, and macOS checks
# every library it has not seen before (XProtect / syspolicyd) as it is
# dlopen()ed, keyed per file — so every launch paid ~10 s before the window
# appeared (measured 2026-10-12: the same libraries took 95 s fresh, 1 s once
# seen). Installed as a folder inside the app, they are checked once.
#
# The tricky bits this handles:
# - uvicorn imports its loop/protocol backends dynamically → collect_submodules
@@ -82,9 +90,8 @@ pyz = PYZ(a.pure)
exe = EXE(
pyz,
a.scripts,
a.binaries,
a.datas,
[],
exclude_binaries=True,
name="konduktor-sidecar",
debug=False,
bootloader_ignore_signals=False,
@@ -97,3 +104,12 @@ exe = EXE(
codesign_identity=None,
entitlements_file=None,
)
coll = COLLECT(
exe,
a.binaries,
a.datas,
strip=False,
upx=False,
name="konduktor-sidecar",
)
@@ -193,6 +193,7 @@ class OneLibraryAdapter:
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
@@ -425,6 +426,10 @@ class OneLibraryAdapter:
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)
@@ -49,7 +49,7 @@ class OneLibraryDriver:
def _has_onelibrary_schema(path: Path) -> bool:
try:
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.devicelib_plus.database import BLOB
from pyrekordbox.onelibrary.database import BLOB
from pyrekordbox.utils import deobfuscate
except ImportError: # pragma: no cover — dependency missing
return False
@@ -121,7 +121,7 @@ class OneLibraryExporter:
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.devicelib_plus.database import BLOB
from pyrekordbox.onelibrary.database import BLOB
from pyrekordbox.utils import deobfuscate
root = Path(destination)
@@ -381,7 +381,8 @@ class OneLibraryExporter:
# ---- playlists -----------------------------------------------------------
def _write_playlists(self, con, payload: ExportPayload, by_source: dict) -> None:
"""One folder named after the export, with the tree preserved under it.
"""The tree preserved — at the top level (parent NULL), or with
`payload.root_folder` under one folder named after the export.
`playlist` is a flat table with `playlist_id_parent`, so folders and
playlists are the same row kind told apart by `attribute` (1 = folder).
@@ -397,8 +398,8 @@ class OneLibraryExporter:
)
return next_id[0]
root = add(payload.name, None, folder=True)
folders: dict[tuple[str, ...], int] = {(): root}
root = add(payload.name, None, folder=True) if payload.root_folder else None
folders: dict[tuple[str, ...], int | None] = {(): root}
for playlist in payload.playlists:
parent = root
@@ -427,8 +428,10 @@ class OneLibraryExporter:
)
#: rekordbox's `fileType` codes, as `pyrekordbox.devicelib_plus.FileType` has them.
#: `.stem.m4a` (a Traktor STEM) is an M4A to a Pioneer player.
#: rekordbox's `fileType` codes. `.stem.m4a` (a Traktor STEM) is an M4A to a
#: Pioneer player. `pyrekordbox.onelibrary.FileType` now also lists MP4 = 3 (the
#: `.mp4` container) and ALAC = 6 (an ALAC `.m4a`); neither is measured here, so
#: both still write 4.
_FILE_TYPES = {".mp3": 1, ".m4a": 4, ".mp4": 4, ".aac": 4, ".flac": 5, ".wav": 11,
".aif": 12, ".aiff": 12}
@@ -1,6 +1,6 @@
"""OneLibrary rows -> the generic projection.
The only place a ``devicelib_plus`` ORM object becomes a generic `Track` /
The only place a ``pyrekordbox.onelibrary`` ORM object becomes a generic `Track` /
`TrackCues`. Everything above this file sees generic types exclusively.
Field conventions are read off a real rekordbox 7 export rather than guessed:
+54 -15
View File
@@ -1,7 +1,7 @@
"""The retained native model for a OneLibrary drive.
Owns the drive's ``exportLibrary.db`` and the layout around it, and is the only
place a ``pyrekordbox.devicelib_plus`` row or an ANLZ tag is touched.
place a ``pyrekordbox.onelibrary`` row or an ANLZ tag is touched.
The database is SQLCipher-encrypted SQLite, like Rekordbox's ``master.db``, but
with a **different and universal key**: every OneLibrary drive from every vendor
@@ -170,10 +170,10 @@ class OneLibraryStore(ReplaceGridCommands):
def _load(self) -> None:
"""Copy the drive's database into app-data and open the copy."""
try:
from pyrekordbox.devicelib_plus import DeviceLibraryPlus
from pyrekordbox.onelibrary import OneLibrary
except ImportError as ex: # pragma: no cover — dependency missing
raise LibraryNotSupported(
"Reading OneLibrary drives needs pyrekordbox with devicelib_plus"
"Reading OneLibrary drives needs pyrekordbox with its onelibrary module"
) from ex
_clear_stale_work()
work = Path(tempfile.mkdtemp(prefix="drive-", dir=_work_root()))
@@ -186,7 +186,7 @@ class OneLibraryStore(ReplaceGridCommands):
sidecar = self.path.with_name(self.path.name + suffix)
if sidecar.is_file() and sidecar.stat().st_size:
shutil.copyfile(sidecar, working.with_name(working.name + suffix))
db = DeviceLibraryPlus(str(working))
db = OneLibrary(str(working))
except Exception as ex: # noqa: BLE001 — surfaced as a clean 4xx
shutil.rmtree(work, ignore_errors=True)
raise LibraryNotSupported(f"Could not open OneLibrary database: {ex}") from ex
@@ -206,7 +206,7 @@ class OneLibraryStore(ReplaceGridCommands):
"""Release the working copy and delete it.
The drive itself is never held open (see the module docstring); the copy
is, and `DeviceLibraryPlus.close()` only unregisters events, so the
is, and `OneLibrary.close()` only unregisters events, so the
session and engine are closed here explicitly.
"""
db, self._db = self._db, None
@@ -316,7 +316,7 @@ class OneLibraryStore(ReplaceGridCommands):
image_id = getattr(self.content(track_id), "image_id", None)
if not image_id:
return None
from pyrekordbox.devicelib_plus import models
from pyrekordbox.onelibrary import models
row = self._require_db().query(models.Image).filter_by(image_id=image_id).one_or_none()
small = self.layout.resolve(getattr(row, "path", None)) if row is not None else None
@@ -456,7 +456,7 @@ class OneLibraryStore(ReplaceGridCommands):
"""
if not name:
return None
from pyrekordbox.devicelib_plus import models
from pyrekordbox.onelibrary import models
model = getattr(models, model_name)
pk = f"{model.__tablename__}_id"
@@ -497,7 +497,7 @@ class OneLibraryStore(ReplaceGridCommands):
stick already has. A new key gets rekordbox's own spelling."""
if wheel is None or mode is None:
return None
from pyrekordbox.devicelib_plus import models
from pyrekordbox.onelibrary import models
from ..rekordbox.projection import parse_key, render_key
@@ -567,7 +567,7 @@ class OneLibraryStore(ReplaceGridCommands):
# ---- writes: playlists --------------------------------------------------
def _playlist(self, node_id: str):
from pyrekordbox.devicelib_plus import models
from pyrekordbox.onelibrary import models
try:
pid = int(node_id)
@@ -579,14 +579,14 @@ class OneLibraryStore(ReplaceGridCommands):
return row
def _siblings(self, parent_id: int, *, excluding: int | None = None) -> list:
from pyrekordbox.devicelib_plus import models
from pyrekordbox.onelibrary import models
rows = self._require_db().query(models.Playlist).filter_by(playlist_id_parent=parent_id).all()
rows = [r for r in rows if r.playlist_id != excluding]
return sorted(rows, key=lambda r: (int(r.sequenceNo or 0), int(r.playlist_id)))
def _create_node(self, name: str, parent_id: str | None, attribute: int) -> str:
from pyrekordbox.devicelib_plus import models
from pyrekordbox.onelibrary import models
name = (name or "").strip()
noun = "folder" if attribute == ATTRIBUTE_FOLDER else "playlist"
@@ -631,7 +631,7 @@ class OneLibraryStore(ReplaceGridCommands):
def delete_playlist(self, node_id: str) -> None:
"""Delete a playlist, or a folder WITH everything in it, and close the gap
its `sequenceNo` leaves among its siblings."""
from pyrekordbox.devicelib_plus import models
from pyrekordbox.onelibrary import models
db = self._require_db()
row = self._playlist(node_id)
@@ -652,9 +652,48 @@ class OneLibraryStore(ReplaceGridCommands):
db.flush()
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 children, renumbering
`sequenceNo` from 0 in both parents as create and delete do. The
Device Library's playlist tree follows at Save (`device_library`
mirrors parent and sort from these rows)."""
db = self._require_db()
row = self._playlist(node_id)
dest = 0
if parent_id:
folder = self._playlist(parent_id)
if int(folder.attribute or 0) != ATTRIBUTE_FOLDER:
raise InvalidCommand("A playlist can only be moved into a folder")
dest = int(folder.playlist_id)
ancestor = folder
while ancestor is not None:
if int(ancestor.playlist_id) == int(row.playlist_id):
raise InvalidCommand("A folder cannot be moved into itself")
up = int(ancestor.playlist_id_parent or 0)
ancestor = self._playlist(str(up)) if up else None
source = int(row.playlist_id_parent or 0)
siblings = self._siblings(dest, excluding=row.playlist_id)
index = max(0, min(int(index), len(siblings)))
order = siblings[:index] + [row] + siblings[index:]
if source == dest and [r.playlist_id for r in order] == [
r.playlist_id for r in self._siblings(dest)
]:
return str(row.playlist_id)
row.playlist_id_parent = dest
for n, r in enumerate(order):
if int(r.sequenceNo or 0) != n:
r.sequenceNo = n
if source != dest:
for n, r in enumerate(self._siblings(source, excluding=row.playlist_id)):
if int(r.sequenceNo or 0) != n:
r.sequenceNo = n
db.flush()
self._journal.record("playlist", "move", row.name)
return str(row.playlist_id)
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
"""Replace a playlist's contents, in order, numbered from 1 (measured)."""
from pyrekordbox.devicelib_plus import models
from pyrekordbox.onelibrary import models
db = self._require_db()
playlist = self._playlist(node_id)
@@ -1339,9 +1378,9 @@ class OneLibraryStore(ReplaceGridCommands):
return SaveOutcome(summary=summary, snapshot=None, tag_results=tag_results)
def _reopen_working(self, work: Path) -> None:
from pyrekordbox.devicelib_plus import DeviceLibraryPlus
from pyrekordbox.onelibrary import OneLibrary
self._db, self._work = DeviceLibraryPlus(str(work / self.path.name)), work
self._db, self._work = OneLibrary(str(work / self.path.name)), work
self._content_cache = None
self._by_id = None
@@ -172,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
@@ -276,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)
@@ -198,8 +198,9 @@ class RekordboxDeviceExporter:
@staticmethod
def _playlists(payload: ExportPayload, by_source: dict) -> tuple[list[bytes], list[bytes]]:
"""The tree under one folder named after the export, as the other
targets build it. `sort_order` is a node's position among its siblings."""
"""The tree as the other targets build it — at the top level (parent
0), or with `payload.root_folder` under one folder named after the
export. `sort_order` is a node's position among its siblings."""
tree: list[bytes] = []
entries: list[bytes] = []
next_id = [0]
@@ -220,7 +221,7 @@ class RekordboxDeviceExporter:
index += 1
entries.append(pdb.playlist_entry_row(index, track_id, playlist_id))
root = add(payload.name, 0, folder=True)
root = add(payload.name, 0, folder=True) if payload.root_folder else 0
folders: dict[tuple[str, ...], int] = {(): root}
for playlist in payload.playlists:
parent = root
@@ -125,7 +125,7 @@ class RekordboxExporter:
)
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
# `masterdb`'s OWN key blob. `devicelib_plus` has a different one — a
# `masterdb`'s OWN key blob. `onelibrary` has a different one — a
# OneLibrary drive uses a universal key shared across vendors, and
# master.db does not. Mixing them up produces a database Rekordbox
# cannot open, and pyrekordbox rejects the wrong one outright.
@@ -383,9 +383,12 @@ class RekordboxExporter:
# ---- playlists ---------------------------------------------------------------
def _write_playlists(self, db, payload: ExportPayload, rows: dict) -> None:
"""The tree, under one folder named after the export."""
root = db.create_playlist_folder(payload.name)
db.flush()
"""The tree — at the top level, or with `payload.root_folder` under one
folder named after the export (None = the top level)."""
root = None
if payload.root_folder:
root = db.create_playlist_folder(payload.name)
db.flush()
folders: dict[tuple[str, ...], object] = {(): root}
for playlist in payload.playlists:
@@ -608,6 +608,79 @@ class RekordboxStore(ReplaceGridCommands):
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.
+74 -6
View File
@@ -30,6 +30,7 @@ from ... import remote_protocol as rp
from ...core.adapter import (
AudioFacts,
FileTagResult,
NotFound,
SaveOutcome,
Unavailable,
Unsupported,
@@ -39,6 +40,7 @@ from ...core.query import TrackIndex
from .cache import RemoteAudioCache, StaleFacts
from .cache import shared as shared_cache
from .client import RemoteClient, SessionLost
from .folder import ServerFile, ServerFiles
from .session import RemoteSession
_NOT_HERE = "A remote library's paths are the server's configuration"
@@ -60,6 +62,13 @@ class RemoteAdapter:
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]] = {}
#: Content-folder files a listing returned, by their server path.
self._listed: dict[str, ServerFile] = {}
#: `str(Path(p))` → `p` for every server path this side has turned into
#: a `Path` (an upload's target, a listed file): on Windows that
#: conversion rewrites the separators, and the server must get its own
#: spelling back.
self._server_paths: dict[str, str] = {}
self._dirty = bool(hello.get("dirty"))
self._load()
@@ -194,6 +203,9 @@ class RemoteAdapter:
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))
@@ -257,6 +269,7 @@ class RemoteAdapter:
self.session.lost(ex.holder)
raise
self._uploads[landed["path"]] = (Path(source), landed.get("analysis_lead"))
self._server_paths[str(Path(landed["path"]))] = landed["path"]
return Path(landed["path"])
def free_space(self, path: str) -> int:
@@ -265,8 +278,13 @@ class RemoteAdapter:
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))
key = self._server_key(path)
self._uploads.pop(key, None)
self.client.delete_upload(key)
def _server_key(self, path) -> str:
text = str(path)
return self._server_paths.get(text, text)
def add_tracks(self, items, *, checkpoint=None):
"""Add uploaded files. Where the platform analyses what it adds (the
@@ -276,10 +294,20 @@ class RemoteAdapter:
wire = []
total = len(items)
for n, item in enumerate(items, start=1):
key = str(item.audio_path)
keys = [self._server_key(item.audio_path) for item in items]
# Files already in the content folder (added in place): the server says
# whether the platform analyses, and only then is the file fetched.
in_place = [k for k, item in zip(keys, items)
if item.analysis is None and k not in self._uploads and k in self._listed]
leads = self.client.folder_leads(in_place) if in_place else {}
for n, (item, key) in enumerate(zip(items, keys), start=1):
source, lead = self._uploads.get(key, (None, None))
analysis = item.analysis
if analysis is None and source is None and leads.get(key) is not None:
lead = leads[key]
if checkpoint is not None:
checkpoint(f"Downloading {item.track.title or Path(key).name} ({n}/{total})", step=n, of=total)
source = self.folder_audio(key)
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)
@@ -299,8 +327,8 @@ class RemoteAdapter:
self.session.lost(ex.holder)
raise
self._apply(envelope)
for item in items:
self._uploads.pop(str(item.audio_path), None)
for key in keys:
self._uploads.pop(key, None)
return envelope["result"]
def apply_stem_swaps(self, swaps, *, add_to_playlist=None):
@@ -390,6 +418,46 @@ class RemoteAdapter:
facts = self.audio_facts([track_id]).get(track_id)
return self.cache.get(facts) if facts else None
# ---- the content folder, browsed --------------------------------------------------
def folder_listing(self, path: str | None) -> ServerFiles:
"""The audio directly inside a content folder (None: the folder itself),
as the server lists it — and remembered, so a file can then be played
or added by its path."""
listing = ServerFiles.from_wire(self, self.client.folder_tracks(path))
with self._lock:
self._listed = {k: f for k, f in self._listed.items() if f.folder != listing.path}
self._listed.update(listing.files)
self._server_paths.update({str(Path(k)): k for k in listing.files})
return listing
def listed_files(self, paths) -> ServerFiles | None:
"""The listed files among `paths` as one source (they may come from
several folders); None when none of them was listed."""
with self._lock:
found = [self._listed[p] for p in paths if p in self._listed]
return ServerFiles(self, found[0].folder, found) if found else None
def folder_audio(self, path: str, *, progress=None) -> Path:
"""A local copy of a listed file, downloaded into the shared cache —
keyed by the same facts as a library track's, so a file that is both
downloads once."""
for attempt in range(2):
with self._lock:
found = self._listed.get(path)
if found is None:
raise NotFound("File not found — browse to its folder first")
cached = self.cache.get(found.facts)
if cached is not None:
return cached
try:
return self.cache.fetch(
found.facts, lambda partial: self.client.folder_download(path, partial, progress=progress))
except StaleFacts:
if attempt:
raise
self.folder_listing(found.folder) # changed on the server: re-read it
raise NotFound(path)
# ---- paths: the server's business ------------------------------------------------
def set_path_mapping(self, mapping):
raise Unsupported(_NOT_HERE)
@@ -246,6 +246,29 @@ class RemoteClient:
def fs_list(self, path: str | None) -> dict:
return self.request("GET", "/v1/fs/list", params={"path": path} if path else None).json()
def folder_tracks(self, path: str | None) -> dict:
return self.request("GET", "/v1/folder/tracks", params={"path": path} if path else None,
timeout=None).json()
def folder_leads(self, paths: list[str]) -> dict[str, float | None]:
return self.request("POST", "/v1/folder/leads", json={"paths": paths}).json()["leads"]
def folder_download(self, path: str, target: Path, *, progress=None) -> dict:
"""Stream a listed content-folder file into `target` (as `download`)."""
with self.stream("GET", "/v1/folder/audio", params={"path": path}, 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 fs_space(self, path: str | None) -> int:
return int(self.request("GET", "/v1/fs/space", params={"path": path} if path else None).json()["free"])
+102
View File
@@ -0,0 +1,102 @@
"""The server's content folder, browsed from this computer like a drive.
The sidebar's Files trees read folders on THIS computer (`core/folder.py`). On a
remote library the music lives in the server's content folder, which this
computer cannot see — so the server lists it (`/v1/folder/tracks`: tags, file
facts, and which files the library already holds) and this module holds the
answer as a read-only SOURCE, the shape the table, the deck and the importer
already read.
Adding one of these files never uploads anything: it is already where the
library can reach it, so it is added IN PLACE (`on_library_host`), and the
importer skips both the copy and the copy-or-reference question.
Ids are the file's path ON THE SERVER — a string, never a `Path` on this side
until the importer needs one, because a server path is not a path here (on a
Windows laptop `Path("/music/x.mp3")` is `\\music\\x.mp3`).
"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from ...core.adapter import AudioFacts
from ...core.model import PlaylistNode, Track, TrackCues
@dataclass
class ServerFile:
folder: str
track: Track
facts: AudioFacts
#: The library's id for this file, when it already points at it.
held: str | None = None
class ServerFiles:
"""Files in the content folder, as the read half of a source."""
#: The importer's cue that these are already on the machine holding the
#: library: added where they are, neither copied nor uploaded.
on_library_host = True
def __init__(self, adapter, path: str, files: list[ServerFile]):
self.adapter = adapter
self.path = path
self._files = {f.track.id: f for f in files}
@classmethod
def from_wire(cls, adapter, body: dict) -> "ServerFiles":
folder = body["path"]
facts = body.get("files") or {}
held = body.get("held") or {}
files = []
for raw in body.get("tracks") or []:
track = Track.model_validate(raw)
fact = facts.get(track.id)
if fact is None:
continue
files.append(ServerFile(
folder=folder, track=track,
facts=AudioFacts(key=track.id, size=int(fact["size"]), mtime_ns=int(fact["mtime_ns"])),
held=held.get(track.id),
))
return cls(adapter, folder, files)
@property
def files(self) -> dict[str, ServerFile]:
return self._files
@property
def tracks(self) -> list[Track]:
return [f.track for f in self._files.values()]
def track(self, track_id: str) -> Track | None:
found = self._files.get(track_id)
return found.track if found else None
def held(self, track_id: str) -> str | None:
found = self._files.get(track_id)
return found.held if found else None
def size(self, track_id: str) -> int:
found = self._files.get(track_id)
return found.facts.size if found else 0
def track_cues(self, track_id: str) -> TrackCues | None:
return TrackCues(cues=[], grid_markers=[]) if track_id in self._files else None
def audio_facts(self, track_ids) -> dict[str, AudioFacts]:
return {t: self._files[t].facts for t in track_ids if t in self._files}
def audio_path(self, track_id: str, *, progress=None) -> Path | None:
"""A local copy (downloaded into the shared cache, like a library track)."""
if track_id not in self._files:
return None
return self.adapter.folder_audio(track_id, progress=progress)
def playlist_tree(self) -> list[PlaylistNode]:
return []
def playlist_tracks(self, node_id: str) -> list[Track] | None:
return None
@@ -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."""
@@ -74,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",
+5 -9
View File
@@ -106,14 +106,10 @@ class TraktorExporter:
return WrittenLibrary(library=library)
def _write_playlists(self, adapter, payload: ExportPayload, moved: dict) -> None:
"""Recreate the tree under one folder named after the export.
Nested under the export's own name for the same reason import nests a
drive's playlists under the drive's name: a collection swapped onto
another machine should say where its playlists came from.
"""
root = adapter.create_folder(payload.name)
folders: dict[tuple[str, ...], str] = {(): root}
"""Recreate the tree — at the top level, or with `payload.root_folder`
under one folder named after the export (None = the top level)."""
root = adapter.create_folder(payload.name) if payload.root_folder else None
folders: dict[tuple[str, ...], str | None] = {(): root}
for playlist in payload.playlists:
parent = self._folder_for(adapter, folders, tuple(playlist.folders), root)
@@ -128,7 +124,7 @@ class TraktorExporter:
adapter.set_playlist_entries(node_id, loose)
@staticmethod
def _folder_for(adapter, folders: dict, path: tuple[str, ...], root: str) -> str:
def _folder_for(adapter, folders: dict, path: tuple[str, ...], root: str | None) -> str | None:
"""Create (once) the folder chain a playlist sits under, and return it."""
for depth in range(1, len(path) + 1):
branch = path[:depth]
+77 -1
View File
@@ -160,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(
@@ -175,6 +177,7 @@ class TraktorStore:
can_contain_children=True,
can_rename=True,
can_delete=True,
can_move=True,
)
@staticmethod
@@ -348,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)
+6
View File
@@ -247,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 ----------------------------------------
+3
View File
@@ -106,6 +106,9 @@ 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):
+7 -1
View File
@@ -94,8 +94,14 @@ class ExportPayload:
tracks: list[ExportTrack] = field(default_factory=list)
playlists: list[ExportPlaylist] = field(default_factory=list)
#: The export's name, used for the folder its playlists are nested under.
#: The export's name, used for the folder its playlists are nested under
#: when `root_folder` is set.
name: str = "Export"
#: Nest the whole playlist tree (and "Other") in one folder named `name`.
#: Off — the default, a Konduktor setting — the playlists sit at the
#: library's top level: an export is a library of its own, so a folder
#: saying where it came from is one more click at the gig.
root_folder: bool = False
#: Called by a writer before each slow step (e.g. decoding a track for its
#: waveform) with a message for the status bar, and — for a per-track loop —
#: `step` of `of`, which drives the progress bar. RAISES when the user has
+102 -6
View File
@@ -14,7 +14,9 @@ This is opened by the folder routes and nothing else.
Three rules:
* **This folder only.** Subfolders are not scanned — the tree is how you get to
them — so a click on a drive root never walks the whole drive.
them — so a click on a drive root never walks the whole drive. A folder
DROPPED onto the window is the exception (`FolderScanner.dropped`): the user
asked for everything in it, so it recurses, capped at `MAX_DROPPED`.
* **A track id is the file's absolute path.** It is the one identity a loose
file has, and it is what the audio route checks a request against.
* **Tags are read once per folder state.** Reading tags opens every file, which
@@ -26,6 +28,7 @@ from __future__ import annotations
import logging
import os
import threading
from dataclasses import dataclass, field
from pathlib import Path
from .capabilities import Capabilities, SaveCapabilities, TrackCapabilities
@@ -165,17 +168,88 @@ class FolderSource:
return capabilities_for(self.path)
# A drop of a whole drive must not read tags for hours: past this many audio
# files the rest are left out and the answer says so.
MAX_DROPPED = 20_000
@dataclass
class Dropped:
"""What a drop onto the window resolved to."""
tracks: list[Track] = field(default_factory=list)
# Dropped FILES that are not audio this library can hold (or are gone).
# Non-audio inside a dropped folder is not counted: an album folder's
# cover and cue sheet are not something the user asked to add.
skipped: int = 0
# More than MAX_DROPPED audio files: the rest were left out.
truncated: bool = False
class FolderScanner:
"""Scans folders on request, caching each until its contents change.
Also the gatekeeper for streaming: `source_for_file` answers only for a file
found by a scan, so the audio route cannot be used to read an arbitrary path
off the disk — only audio the user has browsed to.
found by a scan — or dropped onto the window by the user — so the audio
route cannot be used to read an arbitrary path off the disk, only audio the
user has browsed to or handed over.
"""
def __init__(self) -> None:
self._lock = threading.Lock()
self._cache: dict[str, tuple[float, tuple[str, ...], FolderSource]] = {}
# Files dropped one by one: their folder was never scanned (and is not
# cached as if it had been — a partial listing would hide its other
# files from the sidebar), so each is held on its own.
self._files: dict[str, Track] = {}
def dropped(self, paths: list[str], formats: list[str], limit: int = MAX_DROPPED) -> Dropped:
"""Resolve paths dropped onto the window: folders RECURSIVELY (hidden
and OS-housekeeping folders left out, as the tree leaves them out),
files as themselves. Every audio file found becomes addable and
playable through the folder routes, exactly as if it had been browsed."""
wanted = {f.lower() for f in formats}
out = Dropped()
seen: set[str] = set()
def take(tracks: list[Track]) -> bool:
for t in tracks:
if t.id in seen:
continue
if len(out.tracks) >= limit:
out.truncated = True
return False
seen.add(t.id)
out.tracks.append(t)
return True
for raw in paths:
path = Path(raw).expanduser()
if path.is_dir():
for folder in _walk(path):
if not audio_files(folder, formats):
continue
if not take(self.scan(folder, formats).tracks):
return out
elif path.is_file() and path.suffix.lower() in wanted and not is_hidden(path):
track = self._file_track(path)
if not take([track]):
return out
else:
out.skipped += 1
return out
def _file_track(self, path: Path) -> Track:
key = str(path)
with self._lock:
hit = self._cache.get(str(path.parent))
known = hit[2].track(key) if hit is not None else None
if known is not None:
return known
track = read_track(path)
with self._lock:
self._files[key] = track
return track
def scan(self, folder: Path, formats: list[str]) -> FolderSource:
folder = Path(folder)
@@ -198,10 +272,32 @@ class FolderScanner:
folder = str(Path(track_id).parent)
with self._lock:
hit = self._cache.get(folder)
if hit is None or hit[2].track(track_id) is None:
return None
return hit[2]
loose = self._files.get(track_id)
if hit is not None and hit[2].track(track_id) is not None:
return hit[2]
if loose is not None:
return FolderSource(Path(folder), [loose])
return None
def clear(self) -> None:
with self._lock:
self._cache.clear()
self._files.clear()
def _walk(root: Path):
"""`root` and every visible folder under it, depth first, sorted by name."""
yield root
try:
with os.scandir(root) as it:
subs = []
for entry in it:
try:
if entry.is_dir(follow_symlinks=False) and not is_hidden(entry):
subs.append(Path(entry.path))
except OSError:
continue
except OSError:
return
for sub in sorted(subs, key=lambda p: p.name.lower()):
yield from _walk(sub)
+2 -2
View File
@@ -235,8 +235,8 @@ def detect_grid(
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)
from . import waveform
y, sr = waveform.load(audio_path, sr=sr)
y = np.asarray(y, dtype=np.float32)
duration = len(y) / sr
if duration < 1.5:
+2 -2
View File
@@ -178,7 +178,7 @@ def with_detected_key(track, y: np.ndarray | None, sr: int):
def detect_key(audio_path: str) -> KeyResult | None:
import librosa
from . import waveform
y, sr = librosa.load(audio_path, sr=SR, mono=True)
y, sr = waveform.load(audio_path, sr=SR)
return detect_key_samples(y, sr)
+3
View File
@@ -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()
+33
View File
@@ -0,0 +1,33 @@
"""Opening a file for reading with PyAV, on every PyAV version the app ships.
A file whose tags are not valid UTF-8 must still open: it is still audio.
PyAV 18 decodes tags strictly by default and raises UnicodeDecodeError at open
unless given `metadata_errors="ignore"`; PyAV 19 REMOVED that keyword (passing
it is a TypeError) and opens such a file as it is, the bad bytes as surrogates.
Measured on both with a generated M4A and MP3 whose title is invalid UTF-8.
The keyword once went straight into `av.open`, which worked on the dev venv's
18.1 while CI's fresh install took 19.0.1: every stem file then failed to open
in the released app, and the deck played stem tracks as the mix. Every read
goes through `open_input`, so the difference lives in one place.
"""
from __future__ import annotations
from functools import cache
from pathlib import Path
@cache
def _takes_metadata_errors() -> bool:
import av
return int(av.__version__.split(".")[0]) < 19
def open_input(path: Path | str):
"""`av.open(path)` for reading, tolerant of tags that are not UTF-8."""
import av
if _takes_metadata_errors():
return av.open(str(path), metadata_errors="ignore")
return av.open(str(path))
+2
View File
@@ -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]
+90 -23
View File
@@ -37,15 +37,17 @@ from __future__ import annotations
import fractions
import json
import queue
import struct
import sys
import threading
from dataclasses import dataclass
from pathlib import Path
from typing import Callable
import numpy as np
from . import mp4_edit, tag_copy
from . import mp4_edit, pyav, tag_copy
SR = 44100
FRAME = 1024 # AAC-LC frame size, for both encoders
@@ -132,7 +134,7 @@ def decode(path: Path | str) -> Source:
"""Decode the first audio stream to stereo float32 at 44.1 kHz."""
import av
with av.open(str(path), metadata_errors="ignore") as container:
with pyav.open_input(path) as container:
stream = container.streams.audio[0]
codec = stream.codec_context.name
bit_rate = stream.bit_rate or container.bit_rate or None
@@ -151,15 +153,36 @@ def decode(path: Path | str) -> Source:
return Source(pcm=np.ascontiguousarray(pcm), codec=codec, bit_rate=bit_rate)
#: Encoded frames each stream's thread may run ahead of the muxer.
_ENCODE_QUEUE = 64
#: Frames between `checkpoint()` / `progress()` calls (~6 s of audio).
_ENCODE_TICK = 256
def _encode(fp, tracks: list[np.ndarray], *, bit_rate: int, encoder: str,
checkpoint: Callable[[], None] | None) -> None:
"""Mux five AAC streams IN LOCKSTEP — one frame of each in turn — so the
muxer never buffers a whole stream (which it would if they came one after
another)."""
checkpoint: Callable[[], None] | None,
progress: Callable[[float], None] | None = None) -> None:
"""Encode the AAC streams on one thread EACH and mux them on this one, IN
LOCKSTEP — per frame stream 0..4, then each stream's flush — so the muxer
never buffers a whole stream (which it would if they came one after another).
The encoders are independent and PyAV releases the GIL inside FFmpeg, so
this is ~3x faster than one thread with FFmpeg's `aac` (a 5-minute track's
real stems: 104 s -> 35 s on a 6-core i7) — and since the mux order is the single-threaded
one, the file is byte-identical. Every codec is opened and the header written
HERE before any worker starts: the first `mux()` would otherwise open (and
read) codec contexts a worker may be opening or encoding with. After that
this thread never touches a codec, and a worker never touches the container.
`checkpoint()` and `progress(fraction)` are called from this thread only.
"""
import av
n = tracks[0].shape[1]
tb = fractions.Fraction(1, SR)
offsets = range(0, n, FRAME)
stop = threading.Event()
threads: list[threading.Thread] = []
container = av.open(fp, "w", format="ipod")
try:
streams = []
@@ -169,21 +192,63 @@ def _encode(fp, tracks: list[np.ndarray], *, bit_rate: int, encoder: str,
if k:
s.disposition = 0 # present, not enabled: a plain player plays the mix
streams.append(s)
for i, offset in enumerate(range(0, n, FRAME)):
if checkpoint is not None and i % 512 == 0:
checkpoint()
for s, x in zip(streams, tracks):
frame = av.AudioFrame.from_ndarray(
np.ascontiguousarray(x[:, offset:offset + FRAME], dtype=np.float32),
format="fltp", layout="stereo",
)
frame.sample_rate, frame.pts, frame.time_base = SR, offset, tb
for packet in s.encode(frame):
container.mux(packet)
for s in streams:
for packet in s.encode(None):
s.codec_context.open(strict=False)
container.start_encoding()
queues = [queue.Queue(maxsize=_ENCODE_QUEUE) for _ in tracks]
def put(q: queue.Queue, item) -> bool:
while not stop.is_set():
try:
q.put(item, timeout=0.1)
return True
except queue.Full:
pass
return False # the muxer gave up: stop encoding
def work(s, x: np.ndarray, q: queue.Queue) -> None:
try:
for offset in offsets:
frame = av.AudioFrame.from_ndarray(
np.ascontiguousarray(x[:, offset:offset + FRAME], dtype=np.float32),
format="fltp", layout="stereo",
)
frame.sample_rate, frame.pts, frame.time_base = SR, offset, tb
if not put(q, s.encode(frame)):
return
put(q, s.encode(None))
except BaseException as ex: # noqa: BLE001 — re-raised by the muxer
put(q, ex)
def mux(q: queue.Queue) -> None:
packets = q.get()
if isinstance(packets, BaseException):
raise packets
for packet in packets:
container.mux(packet)
threads = [threading.Thread(target=work, args=(s, x, q), daemon=True, name=f"stem-encode-{k}")
for k, (s, x, q) in enumerate(zip(streams, tracks, queues))]
for t in threads:
t.start()
for i in range(len(offsets)):
if i % _ENCODE_TICK == 0:
if checkpoint is not None:
checkpoint()
if progress is not None:
progress(i / len(offsets))
for q in queues:
mux(q)
for q in queues:
mux(q) # each stream's flush
if progress is not None:
progress(1.0)
finally:
# A cancel or a failure: the workers stop at their next frame, and must
# have stopped before the container (and their codecs) are freed.
stop.set()
for t in threads:
t.join()
container.close()
@@ -302,14 +367,16 @@ Separate = Callable[[np.ndarray], list[np.ndarray]]
def build(source_path: Path | str, target: Path | str, separate: Separate, *,
encoder: str | None = None, checkpoint: Callable[[], None] | None = None) -> Written:
encoder: str | None = None, checkpoint: Callable[[], None] | None = None,
on_encode: Callable[[float], None] | None = None) -> Written:
"""Convert `source_path` into a stem file at `target`.
`separate(pcm)` gets the stereo 44.1 kHz mix and must return the four stems
in `DEMUCS_ORDER`, each the mix's shape. `target` may be any name — the batch
writes a `*.konduktor-partial` and renames it once the batch commits — since
nothing here infers a format from the suffix. `checkpoint()` is called between
phases and during the encode, and may raise to cancel.
phases and during the encode, and may raise to cancel. `on_encode(fraction)`
reports the encode's progress, 0 to 1 (verifying after it takes ~1 s).
"""
target = Path(target)
tick = checkpoint or (lambda: None)
@@ -322,7 +389,7 @@ def build(source_path: Path | str, target: Path | str, separate: Separate, *,
bit_rate = choose_bitrate(source)
with open(target, "wb") as fp:
_encode(fp, [source.pcm, *stems], bit_rate=bit_rate,
encoder=encoder or default_encoder(), checkpoint=checkpoint)
encoder=encoder or default_encoder(), checkpoint=checkpoint, progress=on_encode)
add_stem_box(target)
tags = tag_copy.copy_tags(source_path, target)
verify(target, source)
@@ -381,7 +448,7 @@ def _audio_stream_count(path: Path) -> int:
av = None
if av is not None:
try:
with av.open(str(path), metadata_errors="ignore") as c:
with pyav.open_input(path) as c:
return len(c.streams.audio)
except av.FFmpegError as ex:
raise ValueError(str(ex))
@@ -453,7 +520,7 @@ def extract_stream(path: Path | str, stream: int, fp) -> None:
"""
import av
with av.open(str(path), metadata_errors="ignore") as inp:
with pyav.open_input(path) as inp:
if not 0 <= stream < len(inp.streams.audio):
raise StemFileError(f"The file has no audio stream {stream}")
ist = inp.streams.audio[stream]
+2 -2
View File
@@ -273,8 +273,8 @@ def analyse(
if not markers:
raise ValueError("Set a beatgrid first")
if y is None:
import librosa
y, _ = librosa.load(audio_path, sr=_SR, mono=True)
from . import waveform
y, _ = waveform.load(audio_path, sr=_SR)
y = np.asarray(y, dtype=np.float32)
duration = len(y) / _SR
beats, bar0 = grid_beats(markers, duration)
+20 -10
View File
@@ -84,8 +84,8 @@ class Analysis:
return self.columns.duration
def _decode_pyav(path: Path) -> np.ndarray:
"""Mono float32 at `SR`, via PyAV — FFmpeg's decoders, bundled in its wheel.
def _decode_pyav(path: Path, sr: int = SR) -> np.ndarray:
"""Mono float32 at `sr`, via PyAV — FFmpeg's decoders, bundled in its wheel.
The reason it is first: it decodes AAC (every Traktor `.stem.m4a`) on EVERY
OS, where librosa needs CoreAudio (macOS only) or a system ffmpeg. Measured
@@ -94,9 +94,11 @@ def _decode_pyav(path: Path) -> np.ndarray:
"""
import av
with av.open(str(path)) as container:
from . import pyav
with pyav.open_input(path) as container:
stream = container.streams.audio[0]
resampler = av.AudioResampler(format="flt", layout="mono", rate=SR)
resampler = av.AudioResampler(format="flt", layout="mono", rate=sr)
chunks = []
for frame in container.decode(stream):
for out in resampler.resample(frame):
@@ -120,16 +122,24 @@ def even_slices(n: int, k: int) -> list[slice]:
return [slice(int(a), int(max(b, a + 1)) if n else 0) for a, b in zip(edges[:-1], edges[1:])]
def _decode(path: Path) -> np.ndarray | None:
def load(path: Path | str, sr: int = SR) -> tuple[np.ndarray, int]:
"""Mono float32 at `sr` as `(y, sr)` — `librosa.load`'s shape, raising as it
does. EVERY analysis decode goes through here, never `librosa.load` itself:
librosa reads AAC only through CoreAudio or a system ffmpeg, so on Windows
a `.stem.m4a` failed with "Format not recognised"."""
try:
return _decode_pyav(path)
return _decode_pyav(Path(path), sr), sr
except Exception as ex: # PyAV missing, or a file FFmpeg cannot open
log.debug("PyAV could not decode %s (%s); trying librosa", path, ex)
try:
import librosa
import librosa
y, _ = librosa.load(str(path), sr=SR, mono=True)
return y
y, _ = librosa.load(str(path), sr=sr, mono=True)
return y, sr
def _decode(path: Path) -> np.ndarray | None:
try:
return load(path)[0]
except Exception as ex: # any decoder failure: no waveform, not a failed export
log.warning("could not decode %s for a waveform: %s", path, ex)
return None
+6 -1
View File
@@ -433,9 +433,13 @@ def _folder_paths(adapter) -> dict[str, list[str]]:
# ---- running -----------------------------------------------------------------
def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict:
def run(adapter, export_set, built: ExportPlan, handle: JobHandle, *,
root_folder: bool = False) -> dict:
"""Copy what changed, then write every target's library over the audio.
`root_folder` nests the playlists in a folder named after the export (the
"Put exported playlists in a folder" setting); otherwise they sit at the top.
Rolls back EVERYTHING this run wrote on cancel or on any failure —
including the libraries of targets that had already been written when a
later one failed. What it KEPT from the previous export stays, and the
@@ -545,6 +549,7 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict:
payload = ExportPayload(
name=export_set.name,
root_folder=root_folder,
tracks=payload_tracks,
playlists=built.playlists,
checkpoint=checkpoint,
+25 -1
View File
@@ -191,6 +191,30 @@ def plan(source, dest, destination: Path | None, *, track_ids=None, playlist_ids
return plan
def plan_on_host(source, track_ids) -> ImportPlan:
"""A plan for files that are already on the machine holding the library — a
remote library's content folder, browsed from this computer
(`source.on_library_host`). Nothing is checked on THIS disk, where those
paths mean nothing: the source says each file's size and which ones the
library already holds. Added in place (`run(reference=True)`), so there is
no destination and nothing to copy.
"""
plan = ImportPlan(destination=None)
for track_id in dict.fromkeys(track_ids):
track = source.track(track_id)
if track is None:
continue
name = track_id.replace("\\", "/").rsplit("/", 1)[-1]
plan.tracks.append(PlannedTrack(
track_id=track_id,
title=track.title or name,
source_path=Path(track_id),
size=source.size(track_id),
existing_id=source.held(track_id),
))
return plan
def _playlist_name(source, node_id: str) -> str | None:
for nid, name in _all_playlists(source):
if nid == node_id:
@@ -321,7 +345,7 @@ def run(
# 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:
if uploads and reference and not getattr(source, "on_library_host", False):
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
+209 -27
View File
@@ -69,6 +69,8 @@ from .schemas import (
ExportSetOut,
ExportPreview,
Drive,
DroppedFiles,
DroppedPaths,
FolderAddRequest,
FolderTracks,
FsEntry,
@@ -92,6 +94,8 @@ from .schemas import (
RemapResult,
RenamePlaylist,
SaveResult,
AddEntries,
MovePlaylist,
SetEntries,
SourceCandidate,
SourceStatus,
@@ -118,8 +122,12 @@ app.add_middleware(
"http://localhost:5173",
"http://127.0.0.1:5173",
# Packaged desktop app: the webview's origin when Tauri loads the built
# frontend (macOS uses tauri://, Windows/Linux use https://tauri.localhost).
# frontend. macOS uses tauri://; Windows/Linux default to
# https://tauri.localhost, but lib.rs forces the http scheme
# (use_https_scheme(false)) so the sidecar is not mixed content —
# without the http origin here, the Windows app reaches no API at all.
"tauri://localhost",
"http://tauri.localhost",
"https://tauri.localhost",
],
allow_methods=["*"],
@@ -763,7 +771,10 @@ def run_export(set_id: str) -> JobStatus:
built = exporter.plan(adapter, found)
if built.blocked:
raise HTTPException(409, built.blocked)
job = JOBS.submit("export", lambda handle: exporter.run(adapter, found, built, handle))
# A Konduktor setting, read when the export starts.
root_folder = bool(prefs.load_prefs().get("exportRootFolder", False))
job = JOBS.submit("export", lambda handle: exporter.run(
adapter, found, built, handle, root_folder=root_folder))
return JobStatus(**job.as_dict())
@@ -1227,6 +1238,7 @@ def create_playlist(body: CreatePlaylist) -> PlaylistNode:
can_reorder=True,
can_rename=True,
can_delete=True,
can_move=True,
)
@@ -1241,6 +1253,7 @@ def create_folder(body: CreatePlaylist) -> PlaylistNode:
can_contain_children=True,
can_rename=True,
can_delete=True,
can_move=True,
)
@@ -1265,17 +1278,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")
@@ -1637,10 +1668,10 @@ def analyze_preview(body: AnalyzeRequest) -> AnalyzePreview:
def _decode_for_analysis(path: Path):
"""Mono samples at the rate BOTH detectors work at (they share one decode)."""
import librosa
from .core import waveform
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)
return waveform.load(path, sr=key_detect.SR)
def _analyse_one(a, track_id: str, body: AnalyzeRequest, result: dict) -> None:
@@ -2161,6 +2192,50 @@ def source_track_stems(track_id: str) -> dict:
FOLDERS = FolderScanner()
# A remote library's content folder rides the same routes. Its paths carry this
# prefix, so a path on the server can never be taken for the same path on this
# computer — and the UI's folder view, deck and add dialog need no second set of
# routes. The prefix alone is the content folder itself.
SERVER_FOLDER = "server:"
def _on_server(path: str) -> str | None:
"""The server path behind a prefixed one ('' = the content folder), else None."""
return path[len(SERVER_FOLDER):] if path.startswith(SERVER_FOLDER) else None
def _server_track(track: Track) -> Track:
return track.model_copy(update={"id": SERVER_FOLDER + track.id})
def _folder_rows(dest, tracks: list[Track], held_of) -> tuple[list[Track], dict[str, str]]:
"""A folder's files as table rows. Where the library holds a file, the row
IS the library's track — its key, rating, comments, cues and plays, and
its id, so it plays, edits and drags as the collection track it is
(decided 2026-10-10) — else the file's own tags. Also returns library id →
the file's folder id, for the rows that are library tracks: adding still
speaks in folder ids."""
rows: list[Track] = []
files: dict[str, str] = {}
for track in tracks:
known = held_of(track)
held = dest.track(known) if known else None
if held is None or held.id in files:
rows.append(track)
continue
rows.append(held)
files[held.id] = track.id
return rows, files
def _server_file(track_id: str) -> tuple[object, str]:
"""The remote adapter and the server path of a listed content-folder file."""
adapter = _require_remote()
raw = _on_server(track_id) or ""
if adapter.listed_files([raw]) is None:
raise HTTPException(404, "Track not found — browse to its folder first")
return adapter, raw
def _drive_of(path: Path, drives: list[dict]) -> dict | None:
"""The drive `path` lives on: the longest drive root that contains it."""
@@ -2187,6 +2262,10 @@ def fs_drives() -> list[Drive]:
found = places.drives()
libraries = sources()
out = [Drive(**d) for d in found]
if STATE.remote is not None and STATE.remote_config is not None:
# The server holding the library, first: its content folder is where
# this library's music is, and this computer cannot see it otherwise.
out.insert(0, Drive(name=STATE.remote_config.name, path=SERVER_FOLDER, kind="server"))
externals = [d for d in found if d["path"] != "/"]
for lib in libraries:
home = _drive_of(Path(lib.path), externals)
@@ -2201,6 +2280,11 @@ def fs_drives() -> list[Drive]:
@app.get("/api/fs/folders", response_model=list[FsEntry])
def fs_folders(path: str) -> list[FsEntry]:
"""The visible folders directly inside `path` — one level of a Files tree."""
raw = _on_server(path)
if raw is not None:
listing = _require_remote().client.fs_list(raw or None)
return [FsEntry(name=e["name"], path=SERVER_FOLDER + e["path"])
for e in listing["entries"] if e["is_dir"]]
base = Path(path).expanduser()
if not base.is_dir():
raise HTTPException(404, f"Not a folder: {base}")
@@ -2214,20 +2298,43 @@ def _formats() -> list[str]:
@app.get("/api/folder/tracks", response_model=FolderTracks)
def folder_tracks(path: str) -> FolderTracks:
"""The audio files directly inside a folder, and which are already held."""
raw = _on_server(path)
if raw is not None:
adapter = _require_remote()
listing = adapter.folder_listing(raw or None)
rows, files = _folder_rows(adapter, [_server_track(t) for t in listing.tracks],
lambda t: listing.held(t.id[len(SERVER_FOLDER):]))
return FolderTracks(path=SERVER_FOLDER + listing.path, tracks=rows,
in_collection=list(files), files=files, removable=False)
base = Path(path).expanduser()
if not base.is_dir():
raise HTTPException(404, f"Not a folder: {base}")
source = FOLDERS.scan(base, _formats())
held = importer._existing_files(require_adapter())
dest = require_adapter()
held = importer._existing_files(dest)
rows, files = _folder_rows(dest, source.tracks, lambda t: held.get(importer._key(Path(t.id))))
drive = _drive_of(base, places.drives())
return FolderTracks(
path=str(base),
tracks=source.tracks,
in_collection=[t.id for t in source.tracks if importer._key(Path(t.id)) in held],
tracks=rows,
in_collection=list(files),
files=files,
removable=drive is None or drive["kind"] == "external",
)
@app.post("/api/folder/dropped", response_model=DroppedFiles)
def folder_dropped(body: DroppedPaths) -> DroppedFiles:
"""Files and folders dropped onto the window. Folders are searched all the
way down; every audio file found is then addable and playable through the
folder routes, as if it had been browsed to in the sidebar."""
dest = require_adapter()
dropped = FOLDERS.dropped(body.paths, _formats())
held = importer._existing_files(dest)
rows, files = _folder_rows(dest, dropped.tracks, lambda t: held.get(importer._key(Path(t.id))))
return DroppedFiles(tracks=rows, files=files, skipped=dropped.skipped, truncated=dropped.truncated)
def _folder_track(track_id: str) -> FolderSource:
# Only a file a scan found. This is what keeps the audio route from being a
# way to read any path on the disk.
@@ -2241,11 +2348,17 @@ def _folder_track(track_id: str) -> FolderSource:
def folder_capabilities(path: str) -> Capabilities:
from .core.folder import capabilities_for
raw = _on_server(path)
if raw is not None:
return capabilities_for(Path(raw) if raw else Path(STATE.remote_config.name if STATE.remote_config else "Server"))
return capabilities_for(Path(path))
@app.get("/api/folder/tracks/cues", response_model=TrackCues)
def folder_track_cues(track_id: str) -> TrackCues:
if _on_server(track_id) is not None:
_server_file(track_id)
return TrackCues(cues=[], grid_markers=[])
cues = _folder_track(track_id).track_cues(track_id)
assert cues is not None
return cues
@@ -2253,7 +2366,11 @@ def folder_track_cues(track_id: str) -> TrackCues:
@app.get("/api/folder/tracks/audio")
def folder_track_audio(track_id: str, stem: int | None = None) -> FileResponse:
path = _folder_track(track_id).audio_path(track_id)
if _on_server(track_id) is not None:
adapter, raw = _server_file(track_id)
path = adapter.folder_audio(raw) # this computer's copy, as for a library track
else:
path = _folder_track(track_id).audio_path(track_id)
if path is None or not path.is_file():
raise HTTPException(404, "Audio file not found")
if stem is not None:
@@ -2264,6 +2381,9 @@ def folder_track_audio(track_id: str, stem: int | None = None) -> FileResponse:
@app.get("/api/folder/tracks/stems")
def folder_track_stems(track_id: str) -> dict:
if _on_server(track_id) is not None:
adapter, raw = _server_file(track_id)
return _stem_layout_of(adapter.folder_audio(raw))
return _stem_layout_of(_folder_track(track_id).audio_path(track_id))
@@ -2273,6 +2393,34 @@ def _require_addable(dest) -> None:
raise HTTPException(422, "Tracks cannot be added to this library")
def _check_add_targets(dest, body: FolderAddRequest) -> None:
if body.playlist_id is not None and dest.playlist_entries(body.playlist_id) is None:
raise HTTPException(404, f"Playlist not found: {body.playlist_id}")
if body.export_id is not None:
if STATE.library_id is None or exports.get(STATE.library_id, body.export_id) is None:
raise HTTPException(404, f"Export not found: {body.export_id}")
def _is_server_add(body: FolderAddRequest) -> bool:
on_server = [_on_server(t) is not None for t in body.track_ids]
if any(on_server) and not all(on_server):
raise HTTPException(400, "Files on the server and on this computer are added separately")
return bool(on_server) and all(on_server)
def _server_add_plan(body: FolderAddRequest):
"""Files in the remote library's content folder: already where the library
can reach them, so they are added IN PLACE — nothing uploaded, nothing asked."""
dest = _require_remote()
_require_addable(dest)
paths = [_on_server(t) for t in body.track_ids]
source = dest.listed_files(paths)
if source is None:
raise HTTPException(400, "No tracks to add")
_check_add_targets(dest, body)
return source, dest, importer.plan_on_host(source, paths)
def _folder_add_plan(body: FolderAddRequest):
dest = require_adapter()
_require_addable(dest)
@@ -2293,11 +2441,7 @@ def _folder_add_plan(body: FolderAddRequest):
if not body.destination:
raise HTTPException(400, "Copying needs a destination folder")
destination = Path(body.destination).expanduser()
if body.playlist_id is not None and dest.playlist_entries(body.playlist_id) is None:
raise HTTPException(404, f"Playlist not found: {body.playlist_id}")
if body.export_id is not None:
if STATE.library_id is None or exports.get(STATE.library_id, body.export_id) is None:
raise HTTPException(404, f"Export not found: {body.export_id}")
_check_add_targets(dest, body)
return source, dest, destination, importer.plan(
source, dest, destination, track_ids=[t.id for t in tracks]
)
@@ -2305,6 +2449,11 @@ def _folder_add_plan(body: FolderAddRequest):
@app.post("/api/folder/add/preview")
def folder_add_preview(body: FolderAddRequest) -> dict:
if _is_server_add(body):
_source, _dest, plan = _server_add_plan(body)
out = plan.as_dict()
out.update(total_bytes=0, free_bytes=None, enough_space=None, removable=False)
return out
_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):
@@ -2312,8 +2461,28 @@ def folder_add_preview(body: FolderAddRequest) -> dict:
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
out["removable"] = drive is None or drive["kind"] == "external"
elif destination is not None:
# Copying a file that is already in the import folder makes a second
# copy beside it — legal, but rarely meant, so the dialog says so.
home = destination.resolve()
out["in_destination"] = sum(
1 for t in plan.importable
if t.source_path is not None and t.source_path.resolve().is_relative_to(home)
)
# Per FILE, not per request: a drop can mix the computer's own disk with a
# stick, and only the files on the stick go missing when it is unplugged.
drives = places.drives()
external: dict[str, int] = {}
for t in plan.importable:
if t.source_path is None:
continue
drive = _drive_of(t.source_path, drives)
if drive is None or drive["kind"] == "external":
name = drive["name"] if drive else str(t.source_path.anchor or t.source_path.parent)
external[name] = external.get(name, 0) + 1
out["removable"] = bool(external)
out["removable_count"] = sum(external.values())
out["removable_drives"] = sorted(external)
return out
@@ -2321,10 +2490,16 @@ def folder_add_preview(body: FolderAddRequest) -> dict:
def folder_add(body: FolderAddRequest) -> JobStatus:
"""Add browsed files to the collection. A job, like import: copying can be long."""
_require_no_pending_stems("Adding files")
source, dest, destination, plan = _folder_add_plan(body)
in_place = _is_server_add(body)
if in_place:
source, dest, plan = _server_add_plan(body)
destination = None
else:
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" or importer.places_audio(dest):
# Nothing is copied in place, so there is no space to check.
if not in_place and (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:
@@ -2340,7 +2515,7 @@ def folder_add(body: FolderAddRequest) -> JobStatus:
def work(handle):
result = importer.run(
source, dest, plan, handle,
reference=body.mode == "reference",
reference=in_place or body.mode == "reference",
into_playlist=body.playlist_id,
)
# Export sets are Konduktor's own data, not the library's, so they are
@@ -2423,11 +2598,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())
+4 -2
View File
@@ -34,7 +34,9 @@ from .core.model import AutoHotcue, Track, TrackCues
#: (major, minor). A client speaks to a server of the SAME major whose minor is
#: at least its own: minors only add. Bump the minor for an added route or
#: method, the major for anything an older client would misread.
API_VERSION: tuple[int, int] = (1, 0)
#: 1.1 — `move_playlist` (sidebar drag and drop).
#: 1.2 — `/v1/folder/*`: the content folder browsed as a Files tree.
API_VERSION: tuple[int, int] = (1, 2)
#: 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
@@ -73,7 +75,7 @@ _READ = (
)
_MUTATING = (
"create_playlist", "create_folder", "rename_playlist", "delete_playlist",
"set_playlist_entries", "remove_tracks", "set_track_metadata", "set_key", "set_cue",
"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",
+48 -2
View File
@@ -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]
@@ -493,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):
@@ -502,11 +521,15 @@ class Drive(BaseModel):
candidate `/api/sources` reports, attached to the drive it lives on so the
sidebar can show one row per drive rather than a device list and a drive
list that disagree about what is plugged in.
`server` is a remote library's content folder (path `server:`), listed
first while a remote library is open — the one place its music can be
browsed by folder from this computer.
"""
name: str
path: str
kind: Literal["local", "external"]
kind: Literal["local", "external", "server"]
library: SourceCandidate | None = None
@@ -514,14 +537,37 @@ class FolderTracks(BaseModel):
"""The audio files directly inside one folder, projected as tracks."""
path: str
# A file the collection holds is listed AS the collection's track (its id,
# key, rating, cues…); any other file as its own tags, id = its path.
tracks: list[Track]
# Ids (= absolute paths) of the files the collection already points at.
# Collection ids of the rows that are collection tracks.
in_collection: list[str]
# Those rows' collection id → the file's folder id, which adding takes.
files: dict[str, str] = {}
# On an external drive: a track referenced in place goes missing when the
# drive is unplugged, which the add dialog has to say.
removable: bool
class DroppedPaths(BaseModel):
"""Files and folders dropped onto the window from Finder / Explorer."""
paths: list[str]
class DroppedFiles(BaseModel):
"""What a drop resolved to: the audio in it, as a folder lists its files."""
tracks: list[Track]
# As FolderTracks: rows the collection holds are its tracks, and this maps
# their collection id back to the file's folder id, which adding takes.
files: dict[str, str] = {}
# Dropped files that are not audio the library can hold, or are gone.
skipped: int = 0
# Too many files: only the first MAX_DROPPED are here.
truncated: bool = False
class FolderAddRequest(BaseModel):
"""Add browsed files to the collection, and optionally to a playlist/export.
+72
View File
@@ -44,6 +44,7 @@ from ..core.adapter import (
NotFound,
Unsupported,
)
from ..core.folder import FolderScanner
from ..core.places import is_os_housekeeping
from .config import ConfigError, ServerConfig
from .session import InUse, Lost, SessionLock
@@ -65,6 +66,10 @@ class Server:
self.lock = lock or SessionLock()
self.rev = 0
self._rev_lock = threading.Lock()
#: The content folder's audio as browsed from a client's Files tree —
#: tags read once per folder state, and the gatekeeper for streaming
#: one of those files (only a file a listing found is served).
self.folders = FolderScanner()
# ---- opening ---------------------------------------------------------------
def open(self) -> None:
@@ -388,6 +393,73 @@ def create_app(server: Server) -> FastAPI:
"entries": entries,
}
@app.get("/v1/folder/tracks")
def folder_tracks(path: str | None = None) -> dict:
"""The audio directly inside a content folder, projected as tracks — the
client's Files tree for the server, like `/api/folder/tracks` for a
drive of its own. Tags only (no decoding). `held` maps each file the
library already points at to the library's id for it, so the client
can tick it off and add it to a playlist without adding it twice."""
from .. import importer
folder = server.confine(path)
if not folder.is_dir():
raise HTTPException(404, f"Not a folder: {folder}")
adapter = server.adapter
source = server.folders.scan(folder, adapter.capabilities().tracks.audio_formats)
library = importer._existing_files(adapter)
files, held = {}, {}
for track in source.tracks:
try:
st = Path(track.id).stat()
except OSError:
continue
files[track.id] = {"size": st.st_size, "mtime_ns": st.st_mtime_ns}
known = library.get(importer._key(Path(track.id)))
if known is not None:
held[track.id] = known
return {
"path": str(folder),
"tracks": [t.model_dump(mode="json") for t in source.tracks if t.id in files],
"files": files,
"held": held,
}
def listed_file(path: str) -> Path:
# Confined (a symlink in a listing cannot lead out of the content
# folder), and only a file a listing found: this is not a way to read
# any path on the server.
server.confine(path)
source = server.folders.source_for_file(path)
if source is None:
raise HTTPException(404, "File not found — list its folder first")
target = Path(path)
if not target.is_file():
raise HTTPException(404, "The audio file is missing")
return target
@app.get("/v1/folder/audio")
def folder_audio(path: str):
target = listed_file(path)
st = target.stat()
media = mimetypes.guess_type(str(target))[0] or "application/octet-stream"
return FileResponse(target, media_type=media, headers={
"X-Konduktor-Size": str(st.st_size),
"X-Konduktor-Mtime-Ns": str(st.st_mtime_ns),
})
@app.post("/v1/folder/leads")
def folder_leads(body: dict = Body(...)) -> dict:
"""The analysis lead of each listed file, as an upload reports it: what
a client adding these files IN PLACE measures with. None for every file
when the platform does not analyse what it adds."""
lead = getattr(server.adapter, "analysis_lead", None)
out = {}
for path in body.get("paths") or []:
target = listed_file(str(path))
out[str(path)] = lead(target) if lead else None
return {"leads": out}
@app.get("/v1/fs/space")
def fs_space(path: str | None = None) -> dict:
folder = server.confine(path)
+29 -14
View File
@@ -39,11 +39,25 @@ _BYTES_PER_SECOND = {256_000: 5 * 256_000 / 8 * 1.03, 320_000: 5 * 320_000 / 8 *
_WORK_BYTES_PER_SECOND = 5 * 2 * 4 * sf.SR
#: Shares of ONE track's conversion time, for the status bar's within-track
#: progress (measured on the M3 Pro: decode ~1 s, separate ~50 s, encode +
#: verify ~4 s for a 4-minute track).
_DECODE_SHARE = 0.03
_SEPARATE_SHARE = 0.90
#: Shares of ONE track's conversion time (decode, separate; encoding + verifying
#: take the rest), for the status bar's within-track progress, by AAC encoder.
#: Measured: `aac_at` on the M3 Pro (4-minute track: decode ~1 s, separate
#: ~50 s, encode + verify ~4 s); `aac` on an i7-9750H + RTX 2070 (5-minute
#: track: decode 0.5 s, separate ~102 s, encode ~38 s on five threads, verify ~1 s).
_SHARES = {"aac_at": (0.03, 0.90), "aac": (0.01, 0.71)}
def track_shares(encoder: str) -> tuple[float, float]:
return _SHARES.get(encoder, _SHARES["aac"])
def encode_reporter(handle, start: float, end: float = 0.99) -> Callable[[float], None]:
"""`on_encode` for `stem_file.build`: the encode runs from `start` to `end`
of the track, and the ~1 s of tags + verification after it reads as such."""
def report(f: float) -> None:
frac = start + f * (end - start)
handle.progress(fraction=frac, status=f"{'verifying' if f >= 1 else 'encoding'} {frac * 100:.0f} %")
return report
class ConvertError(Exception):
@@ -227,6 +241,7 @@ def run(handle, adapter, planned: Plan, opts: Options, pending: Pending, *,
work = work_root() / f"batch-{id(handle):x}"
finished: list[tuple[Planned, dict, sf.Written]] = []
needs_engine = any(p.reuse is None for p in items)
encoder = sf.default_encoder()
if needs_engine and not mgr.ready():
raise ConvertError("The stem engine is not installed")
@@ -258,22 +273,22 @@ def run(handle, adapter, planned: Plan, opts: Options, pending: Pending, *,
"stem": str(item.target), "state": "converting", "facts": source_facts(item.source)})
item.target.parent.mkdir(parents=True, exist_ok=True)
# Of a TRACK's time, separation is nearly all (~90 % on MPS);
# decoding before it and encoding + verifying after share the rest.
# Of a TRACK's time, separation is nearly all; decoding before it
# and encoding + verifying after share the rest.
decode_share, separate_share = track_shares(encoder)
def on_progress(f: float) -> None:
frac = _DECODE_SHARE + f * (_SEPARATE_SHARE)
frac = decode_share + f * separate_share
handle.progress(fraction=frac, status=f"separating {frac * 100:.0f} %")
def separate(pcm):
handle.progress(fraction=_DECODE_SHARE, status=f"separating {_DECODE_SHARE * 100:.0f} %")
stems = engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled)
done_at = _DECODE_SHARE + _SEPARATE_SHARE
handle.progress(fraction=done_at, status=f"encoding {done_at * 100:.0f} %")
return stems
handle.progress(fraction=decode_share, status=f"separating {decode_share * 100:.0f} %")
return engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled)
handle.progress(status="decoding 0 %")
try:
written = sf.build(item.source, partial, separate, checkpoint=checkpoint)
written = sf.build(item.source, partial, separate, encoder=encoder, checkpoint=checkpoint,
on_encode=encode_reporter(handle, decode_share + separate_share))
except (_Cancel, EngineCancelled):
partial.unlink(missing_ok=True)
pending.drop([pitem])
+3 -4
View File
@@ -153,13 +153,12 @@ def run(handle, adapter, planned: RemotePlan, opts: convert.Options, *, still_cu
def separate(pcm):
handle.progress(fraction=0.05, status="separating 5 %")
stems = engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled)
handle.progress(fraction=0.85, status="encoding 85 %")
return stems
return engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled)
partial = work / f"{n}.stem.m4a"
try:
written = sf.build(local, partial, separate, checkpoint=checkpoint)
written = sf.build(local, partial, separate, checkpoint=checkpoint,
on_encode=convert.encode_reporter(handle, 0.85, 0.9))
except (convert._Cancel, EngineCancelled):
partial.unlink(missing_ok=True)
raise
+1 -1
View File
@@ -1,4 +1,4 @@
# Build-only dependencies (not needed to run the backend in dev).
# Freezes the backend into a standalone sidecar binary for the desktop build.
# Freezes the backend into a standalone sidecar folder (onedir) for the desktop build.
# See konduktor-sidecar.spec and build_sidecar.sh.
pyinstaller>=6.16 # 6.16+ supports Python 3.14
+2 -2
View File
@@ -14,5 +14,5 @@ Pillow>=11 # a Rekordbox add writes the cover's artwork files
dulwich>=0.22 # version history, beside the library
platformdirs>=4.0
# From GitHub, NOT PyPI — see requirements.txt for why.
traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git
pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git
traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git@39a9c15f29d6b0ea2ce61cd7d548501eea38319d
pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git@43137cb91f8297c768d2a8bdce5b27b2225f0a2d
+13 -10
View File
@@ -4,7 +4,7 @@ fastapi>=0.115
uvicorn[standard]>=0.34
pydantic>=2.11
mutagen>=1.47 # embedded audio-file tag read/write (ID3/MP4/FLAC/AIFF)
av>=18.1 # PyAV: FFmpeg's decoders in the wheel — waveforms for export, AAC on every OS
av>=18.1,<20 # PyAV: FFmpeg's decoders in the wheel — waveforms for export, AAC on every OS. Before allowing a new major, check core/pyav.py (19 broke av.open)
Pillow>=11 # cover art -> the 80/240 px JPEGs a Pioneer export carries
python-multipart>=0.0.9 # multipart form parsing for cover-art upload
# Version-history backups: a self-contained git impl (no system git needed;
@@ -18,19 +18,22 @@ librosa>=0.11
scikit-learn>=1.5
# Traktor Pro 4 (NML v20) support requires the GitHub master (v4.0.0),
# NOT the stale PyPI release (3.1.0), which cannot parse v4 files.
traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git
#
# Both GitHub dependencies are PINNED TO A COMMIT. Unpinned, a fresh install
# (CI's release build) takes whatever master is that day while a dev venv keeps
# what it had: pyrekordbox renamed `devicelib_plus` to `onelibrary` upstream,
# every local test passed, and the released app could not export or read a
# OneLibrary stick. Move a pin deliberately, with ./run_tests.sh.
traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git@39a9c15f29d6b0ea2ce61cd7d548501eea38319d
# Rekordbox (master.db is SQLCipher-encrypted SQLite + per-track ANLZ analysis
# files). Both ship prebuilt Python 3.14 wheels — no Rust/OpenSSL source build.
#
# FROM GITHUB, NOT PyPI — the same situation as traktor-nml-utils above, and for
# the same kind of reason. PyPI's latest (0.4.4) has no `devicelib_plus`, which
# is the OneLibrary (`exportLibrary.db`) reader the OneLibrary adapter is built
# on; it exists only on master. Do not "simplify" this back to a version pin.
#
# The upgrade also renames `db6` to `masterdb`. `db6` still works as a
# deprecated alias and is removed in 0.6.0, so the Rekordbox adapter keeps
# running as-is — but that rename is the thing to fix before taking 0.6.
pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git
# the same kind of reason. PyPI's latest (0.4.4) has no `onelibrary` module
# (`exportLibrary.db`, which the OneLibrary adapter is built on; it was called
# `devicelib_plus` before the rename) and no `masterdb` (formerly `db6`, now
# removed). Do not "simplify" this back to a version pin.
pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git@43137cb91f8297c768d2a8bdce5b27b2225f0a2d
# The stem engine and its weights are downloaded over HTTPS by the sidecar; a
# frozen Python on macOS has no system CA bundle of its own.
certifi>=2024.7
+26 -4
View File
@@ -28,16 +28,38 @@ def _watch_parent_and_exit() -> None:
shut down, so the backend can never be orphaned (the Rust-side kill-on-exit
only covers the graceful path). When run standalone from a terminal, stdin is
a TTY and this blocks harmlessly forever.
NOT on Windows: there a read left pending on the stdin pipe stalls loading
scipy's OpenBLAS DLL in any other thread, forever — so the first analysis
hung the packaged app (dev runs no watcher). Measured 2026-10-12 with plain
Python, through the CRT and through kernel32.ReadFile alike. Windows waits
on the parent PROCESS instead, which also covers a crash.
"""
try:
while sys.stdin.buffer.read(1):
if sys.platform == "win32":
_wait_for_parent_process()
else:
try:
while sys.stdin.buffer.read(1):
pass
except Exception:
pass
except Exception:
pass
_release_remote()
os._exit(0)
def _wait_for_parent_process() -> None:
"""Block until the process that started us exits (Windows only)."""
import ctypes
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
kernel32.OpenProcess.restype = ctypes.c_void_p
kernel32.WaitForSingleObject.argtypes = (ctypes.c_void_p, ctypes.c_uint32)
synchronize, infinite = 0x00100000, 0xFFFFFFFF
handle = kernel32.OpenProcess(synchronize, False, os.getppid())
if handle: # None: the parent is already gone
kernel32.WaitForSingleObject(handle, infinite)
def _release_remote() -> None:
"""Hand back a remote library's session on the way out, so the next
computer opens it at once instead of waiting out the lease (or being asked
+10 -4
View File
@@ -177,9 +177,9 @@ check("bpm x100, rating, file type, bitmask as rekordbox writes them",
check("the file path is drive-relative", lib.tracks[0]["file_path"] == "/Contents/House/One.wav", lib.tracks[0]["file_path"])
check("no computer's masterDbId is claimed", all(t["u3"] == 0 and t["u4"] == 0 for t in lib.tracks))
tree = {p["name"]: p for p in lib.playlists}
check("the tree: a folder named after the export > House > Peak, plus Other for loose tracks",
tree["GIG"]["folder"] and tree["House"]["parent"] == tree["GIG"]["id"]
and tree["Peak"]["parent"] == tree["House"]["id"] and tree["Other"]["parent"] == tree["GIG"]["id"])
check("the tree: House > Peak, plus Other for loose tracks, at the top level (parent 0)",
"GIG" not in tree and tree["House"]["folder"] and tree["House"]["parent"] == 0
and tree["Peak"]["parent"] == tree["House"]["id"] and tree["Other"]["parent"] == 0)
peak = [e for e in lib.entries if e[2] == tree["Peak"]["id"]]
check("playlist entries in order, 1-based", peak == [(1, 1, tree["Peak"]["id"]), (2, 2, tree["Peak"]["id"])], peak)
check("every track has an analysis path, and the files exist",
@@ -188,6 +188,13 @@ check("artwork rows name the a<n>.jpg files, which exist",
all((root / p.lstrip("/")).is_file() for p in lib.artwork.values()) and len(lib.artwork) == 3)
check("every file written is reported, so a re-export can clear it",
all(p.exists() for p in written.all_paths))
import dataclasses # noqa: E402
rooted_tree = {p["name"]: p for p in P.read(
dev.write(dataclasses.replace(payload, root_folder=True), root).library.read_bytes()).playlists}
check("with the root-folder setting: a folder named after the export holds House and Other",
rooted_tree["GIG"]["folder"] and rooted_tree["GIG"]["parent"] == 0
and rooted_tree["House"]["parent"] == rooted_tree["GIG"]["id"]
and rooted_tree["Other"]["parent"] == rooted_tree["GIG"]["id"])
print("== alongside OneLibrary: one set of analysis files and artwork ==")
both = Path(tempfile.mkdtemp())
@@ -195,7 +202,6 @@ for t in tracks:
dst = both / t.destination.relative_to(root)
dst.parent.mkdir(parents=True, exist_ok=True)
dst.write_bytes(t.destination.read_bytes())
import dataclasses # noqa: E402
moved = [dataclasses.replace(t, destination=both / t.destination.relative_to(root)) for t in tracks]
both_payload = ExportPayload(name="GIG", tracks=moved, playlists=payload.playlists)
ol_written = core_export.for_platform("onelibrary").write(both_payload, both)
+24 -11
View File
@@ -137,19 +137,20 @@ def walk(nodes, path=()):
walk(back.playlist_tree())
check("one folder named after the export", ("GIG",) in tree and tree[("GIG",)].kind == "folder")
check("nested folders are preserved", ("GIG", "House") in tree)
check("and nest further", ("GIG", "House", "Slow") in tree)
# By default the tree sits at the top level: an export is a library of its own.
check("no folder named after the export by default", ("GIG",) not in tree)
check("nested folders are preserved", ("House",) in tree and tree[("House",)].kind == "folder")
check("and nest further", ("House", "Slow") in tree)
check("playlists land in their folder",
("GIG", "House", "Peak Time") in tree and ("GIG", "House", "Slow", "Warmup") in tree)
("House", "Peak Time") in tree and ("House", "Slow", "Warmup") in tree)
check("with the right counts",
tree[("GIG", "House", "Peak Time")].count == 2
and tree[("GIG", "House", "Slow", "Warmup")].count == 1)
tree[("House", "Peak Time")].count == 2
and tree[("House", "Slow", "Warmup")].count == 1)
# A track added individually would otherwise be reachable only by search.
check("loose tracks get an 'Other' playlist", ("GIG", "Other") in tree)
check("loose tracks get an 'Other' playlist, at the top level", ("Other",) in tree)
check("holding exactly the ones no playlist claimed",
tree[("GIG", "Other")].count == 1, tree[("GIG", "Other")].count)
other_ids = back.playlist_entries(tree[("GIG", "Other")].id)
tree[("Other",)].count == 1, tree[("Other",)].count)
other_ids = back.playlist_entries(tree[("Other",)].id)
check("and it is the right track",
back.track(other_ids[0]).title == plain.title)
@@ -182,7 +183,19 @@ again = exporter.write(payload, dest).library
check("the entry count did not double",
f'<COLLECTION ENTRIES="{len(chosen)}">' in again.read_text(encoding="utf-8"))
check("and the tree did not duplicate",
len(TraktorDriver().open(again).playlist_tree()) == 1)
len(TraktorDriver().open(again).playlist_tree()) == len(back.playlist_tree()))
print("== with the root-folder setting: everything under one folder named after the export ==")
payload.root_folder = True
rooted = TraktorDriver().open(exporter.write(payload, dest).library)
tree.clear()
walk(rooted.playlist_tree())
check("one top-level node: a folder named after the export",
[n.name for n in rooted.playlist_tree()] == ["GIG"] and tree[("GIG",)].kind == "folder")
check("the tree nests inside it",
("GIG", "House", "Peak Time") in tree and ("GIG", "House", "Slow", "Warmup") in tree)
check("and so does 'Other'", ("GIG", "Other") in tree and tree[("GIG", "Other")].count == 1)
payload.root_folder = False
# ==============================================================================
# Running an export: the copy, the safety rules, and the rollback.
@@ -207,7 +220,7 @@ for i, track in enumerate(src.tracks[:4]):
seed_items.append(ExportTrack(track=track, destination=audio, cues=src.track_cues(track.id)))
exporter_obj = core_export.for_platform("traktor")
exporter_obj.write(
_Payload(name="Source", tracks=seed_items,
_Payload(name="Source", tracks=seed_items, root_folder=True,
playlists=[ExportPlaylist(name="Peak Time",
track_ids=[src.tracks[0].id, src.tracks[1].id])]),
lib_root,
+17 -3
View File
@@ -173,9 +173,23 @@ for platform, reopen in (
tree.clear()
walk(back.playlist_tree())
check("a folder named after the export", ("GIG",) in tree)
check("nested folders are preserved", ("GIG", "House") in tree)
check("no folder named after the export by default", ("GIG",) not in tree)
check("nested folders are preserved, at the top level", ("House",) in tree)
check("with the playlist inside",
("House", "Peak Time") in tree
and tree[("House", "Peak Time")].count == len(chosen))
print(f"-- {platform}: with the root-folder setting")
rooted_root = Path(tempfile.mkdtemp()) / "GIG"
rooted_payload = build(rooted_root)
rooted_payload.root_folder = True
exporter.write(rooted_payload, rooted_root)
rooted = reopen(rooted_root)
tree.clear()
walk(rooted.playlist_tree())
check("one top-level node: a folder named after the export",
[n.name for n in rooted.playlist_tree()] == ["GIG"])
check("the tree nests inside it",
("GIG", "House", "Peak Time") in tree
and tree[("GIG", "House", "Peak Time")].count == len(chosen))
@@ -490,7 +504,7 @@ print("\n== content.contentLink is what rekordbox writes ==")
# row's song-list preview plain blue and put a "?" beside CUE — exactly what
# every row of Konduktor's exports showed while it was NULL.
import sqlcipher3.dbapi2 as _sq # noqa: E402
from pyrekordbox.devicelib_plus.database import BLOB as _BLOB # noqa: E402
from pyrekordbox.onelibrary.database import BLOB as _BLOB # noqa: E402
from pyrekordbox.utils import deobfuscate as _deob # noqa: E402
_con = _sq.connect(str(art_written.library))
+81 -1
View File
@@ -154,7 +154,11 @@ with TestClient(main.app, raise_server_exceptions=False) as c:
check("it is in the playlist", a.playlist_entries(playlist) == [added])
check("it was saved, not left pending", not a.dirty)
body = c.get("/api/folder/tracks", params={"path": str(music)}).json()
check("the folder now marks it as held", body["in_collection"] == [str(one)], str(body["in_collection"]))
check("the folder now marks it as held", body["in_collection"] == [added], str(body["in_collection"]))
row = next((t for t in body["tracks"] if t["id"] == added), None)
check("…its row IS the collection track (its id and data), mapped back to the file",
row is not None and body["files"] == {added: str(one)}
and row["import_date"] == a.track(added).import_date, str(body["files"]))
print("== a held file is never added twice, but still reaches its target ==")
library = STATE.library_id
@@ -193,6 +197,82 @@ with TestClient(main.app, raise_server_exceptions=False) as c:
c.post("/api/folder/add/preview",
json={"track_ids": ["/etc/passwd"], "mode": "reference"}).status_code == 404)
print("== a drop onto the window: folders all the way down, files as themselves ==")
drop = Path(tempfile.mkdtemp()) / "Dropped"
d_a = flac(drop / "Album" / "a.flac", title="Dropped A")
d_b = flac(drop / "Album" / "CD2" / "b.flac")
(drop / "Album" / "cover.jpg").write_bytes(b"not audio")
flac(drop / "Album" / ".cache" / "h.flac")
single = flac(drop / "Loose" / "single.flac", title="Single")
sibling = flac(drop / "Loose" / "sibling.flac")
(drop / "Loose" / "readme.txt").write_text("not audio")
r = c.post("/api/folder/dropped", json={"paths": [
str(drop / "Album"), str(single), str(drop / "Loose" / "readme.txt"),
str(drop / "gone.flac"), str(single), str(d_a),
]})
check("answers 200", r.status_code == 200, r.text[:300])
body = r.json()
ids = [t["id"] for t in body["tracks"]]
check("the folder's audio, subfolders included, then the file — each once",
ids == [str(d_a), str(d_b), str(single)], str(ids))
check("a hidden folder inside is left out", str(drop / "Album" / ".cache" / "h.flac") not in ids)
check("a dropped non-audio file and a missing one are counted as skipped",
body["skipped"] == 2, str(body["skipped"]))
check("non-audio INSIDE a dropped folder is not counted", body["skipped"] == 2)
check("tags are read", body["tracks"][0]["title"] == "Dropped A")
check("not truncated", body["truncated"] is False)
check("a dropped file streams",
c.get("/api/folder/tracks/audio", params={"track_id": str(single)}).status_code == 200)
check("so does one found inside a dropped folder",
c.get("/api/folder/tracks/audio", params={"track_id": str(d_b)}).status_code == 200)
check("but not its undropped sibling",
c.get("/api/folder/tracks/audio", params={"track_id": str(sibling)}).status_code == 404)
listed = [t["id"] for t in c.get("/api/folder/tracks", params={"path": str(drop / "Loose")}).json()["tracks"]]
check("browsing that folder afterwards still lists ALL of it",
listed == [str(sibling), str(single)], str(listed))
r = c.post("/api/folder/dropped", json={"paths": [str(drop / "Loose" / "readme.txt")]})
check("a non-audio file is never made streamable",
r.json()["tracks"] == [] and c.get("/api/folder/tracks/audio", params={
"track_id": str(drop / "Loose" / "readme.txt")}).status_code == 404)
capped = main.FOLDERS.dropped([str(drop / "Album")], main._formats(), limit=1)
check("past the cap the rest are left out, and it says so",
len(capped.tracks) == 1 and capped.truncated)
body = c.post("/api/folder/dropped", json={"paths": [str(one)]}).json()
check("a dropped file the collection holds IS its collection track",
[t["id"] for t in body["tracks"]] == [added] and body["files"] == {added: str(one)},
str(body))
req = {"track_ids": [str(d_b)], "mode": "copy", "destination": str(drop / "Album")}
p = c.post("/api/folder/add/preview", json=req).json()
check("copying into the folder they are already in is flagged", p.get("in_destination") == 1, str(p))
req["destination"] = str(Path(tempfile.mkdtemp()))
p = c.post("/api/folder/add/preview", json=req).json()
check("…and not elsewhere", p.get("in_destination") == 0, str(p))
real_drives = main.places.drives
main.places.drives = lambda: [
{"name": "Computer", "path": drop.anchor, "kind": "local"},
{"name": "Stick", "path": str(drop / "Album"), "kind": "external"},
]
try:
req = {"track_ids": [str(d_a), str(single)], "mode": "reference"}
p = c.post("/api/folder/add/preview", json=req).json()
check("the external-drive warning counts files per drive, not by the first",
p["removable"] is True and p["removable_count"] == 1 and p["removable_drives"] == ["Stick"],
str(p))
p = c.post("/api/folder/add/preview", json={"track_ids": [str(single), str(d_a)],
"mode": "reference"}).json()
check("…whichever file comes first", p["removable_count"] == 1, str(p))
finally:
main.places.drives = real_drives
n = len(a.tracks)
job = wait(c, c.post("/api/folder/add", json={"track_ids": [str(d_a), str(single)],
"mode": "reference"}).json())
check("dropped files are added like browsed ones", job["state"] == "done" and len(a.tracks) == n + 2,
str(job))
print("== Rekordbox: the same route adds to a master.db ==")
from konduktor.adapters.rekordbox import discovery as rb_discovery
+37
View File
@@ -447,6 +447,43 @@ check("re-importing flags the tracks as already present",
check("but does not refuse them — the user chose to add everything",
len(plan8.importable) == 2)
print("== import route: chosen tracks into a playlist and an export (drag and drop) ==")
# Device tracks dropped on a collection playlist open Import with that playlist
# as the target: only the chosen tracks, no drive folder, all into the playlist.
nml9, music9, _ = fresh_collection()
drive9 = Path(tempfile.mkdtemp(prefix="konduktor-import-drive-")) / "Dingus"
shutil.copytree(FIXTURE, drive9, ignore=shutil.ignore_patterns("rekordbox-edited"))
from fastapi.testclient import TestClient # noqa: E402
import konduktor.main as main # noqa: E402
with TestClient(main.app) as c:
check("the collection opens", c.post("/api/library/open", json={"path": str(nml9)}).status_code == 200)
check("the drive opens as a source", c.post("/api/source/open", json={"path": str(drive9)}).status_code == 200)
picked = c.get("/api/source/tracks", params={"limit": 10}).json()
picked = picked["items"][:1]
target = c.post("/api/playlists", json={"name": "Dropped"}).json()["id"]
eset = c.post("/api/exports", json={"name": "Gig", "targets": ["traktor"],
"destination": str(music9.parent / "gig")}).json()["id"]
r = c.post("/api/import", json={"destination": str(music9), "track_ids": [picked[0]["id"]],
"into_playlist": target, "export_id": eset})
check("the import starts", r.status_code == 200, r.text[:200])
job = r.json()
for _ in range(200):
job = c.get(f"/api/jobs/{job['id']}").json()
if job["state"] != "running":
break
time.sleep(0.05)
check("…and finishes", job["state"] == "done", str(job)[:300])
entries = c.get(f"/api/playlists/{target}/tracks").json()
check("the one chosen track lands in the target playlist",
len(entries) == 1 and entries[0]["title"] == picked[0]["title"], str([e["title"] for e in entries]))
names = [n["name"] for n in c.get("/api/playlists").json()]
check("no drive folder is made when no playlist was chosen", "Dingus" not in names, str(names))
ex = next(e for e in c.get("/api/exports").json() if e["id"] == eset)
check("…and it is added to the export too", ex["track_ids"] == [entries[0]["id"]], str(ex["track_ids"]))
c.delete("/api/source")
print()
print("RESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+39 -1
View File
@@ -60,7 +60,7 @@ def dump(db: Path) -> dict:
"""Every row of every table; keyed by primary key, or by the whole row for
the link tables, which have none."""
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.devicelib_plus.database import BLOB
from pyrekordbox.onelibrary.database import BLOB
from pyrekordbox.utils import deobfuscate
con = sqlcipher.connect(str(db))
@@ -264,6 +264,44 @@ seqs = sorted(r["sequenceNo"] for r in after["playlist"].values() if r["playlist
check("and closes the gap among its siblings", seqs == list(range(len(seqs))), str(seqs))
a.close()
print("== moving playlists (sidebar drag and drop) ==")
drive = fresh_drive()
a = OneLibraryAdapter(drive)
folder = a.create_folder("Gigs")
probe = a.create_playlist("Probe")
a.save()
before = dump(db_of(drive))
check("every node offers can_move", all(n.can_move for n in a.playlist_tree()))
demos = next(n for n in a.playlist_tree() if n.name == "demos")
a.move_playlist(demos.id, folder, 0)
a.move_playlist(probe, None, 1)
tree = a.playlist_tree()
check("a playlist moved into a folder is its child",
[c.id for c in next(n for n in tree if n.id == folder).children] == [demos.id])
check("a playlist moves to the index asked for", [n.id for n in tree] == [folder, probe],
str([n.name for n in tree]))
check("a folder cannot be moved into itself",
_raises(lambda: a.move_playlist(folder, folder, 0), InvalidCommand))
check("nor into a playlist", _raises(lambda: a.move_playlist(probe, demos.id, 0), InvalidCommand))
a.save()
after = dump(db_of(drive))
changes = diff(before, after)
check("only playlist rows change, by UPDATE",
{(t, kind) for t, _, kind, _ in changes} == {("playlist", "UPDATE")}, describe(changes))
check("only parent and sequenceNo columns change",
{c for *_, f in changes for c in f} <= {"playlist_id_parent", "sequenceNo"},
str([f for *_, f in changes]))
for parent in (0, int(folder)):
seqs = sorted(r["sequenceNo"] for r in after["playlist"].values() if r["playlist_id_parent"] == parent)
check(f"sequenceNo stays 0..n-1 under {parent}", seqs == list(range(len(seqs))), str(seqs))
a.close()
reopened = OneLibraryAdapter(drive)
check("the move round-trips through a reopen",
[c.id for c in next(n for n in reopened.playlist_tree() if n.id == folder).children] == [demos.id])
reopened.move_playlist(probe, None, 1)
check("moving a node onto its own place is not an edit", reopened.dirty is False)
reopened.close()
# ---- E: a stick's hazards ------------------------------------------------------------
print("== another app wrote the drive since it was opened ==")
drive = fresh_drive()
+1 -1
View File
@@ -65,7 +65,7 @@ def fingerprint(root: Path) -> str:
def rows(root: Path, sql: str):
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.devicelib_plus.database import BLOB
from pyrekordbox.onelibrary.database import BLOB
from pyrekordbox.utils import deobfuscate
con = sqlcipher.connect(str(root / "PIONEER" / "rekordbox" / "exportLibrary.db"))
+37
View File
@@ -172,6 +172,43 @@ check("COLLECTION still byte-identical after folder delete",
check("unknown folder is 404",
client.delete("/api/playlists/fld:No Such Folder").status_code == 404)
print("== drag and drop: add with duplicates, move ==")
target = client.post("/api/playlists", json={"name": "Konduktor Drop"}).json()["id"]
first, rest = track_ids[:2], track_ids[2:4]
r = client.post(f"/api/playlists/{target}/add", json={"track_ids": first}).json()
check("a plain add appends", r["added"] == 2 and r["duplicates"] == 0)
r = client.post(f"/api/playlists/{target}/add",
json={"track_ids": first[:1] + rest, "duplicates": "ask"}).json()
check("'ask' with a duplicate changes nothing and counts it",
r["status"] == "duplicates" and r["duplicates"] == 1
and client.get(f"/api/playlists/{target}/tracks").json().__len__() == 2)
r = client.post(f"/api/playlists/{target}/add",
json={"track_ids": first[:1] + rest, "duplicates": "skip"}).json()
check("'skip' adds only the new ones", r["added"] == 2 and r["duplicates"] == 1 and r["count"] == 4)
r = client.post(f"/api/playlists/{target}/add",
json={"track_ids": first[:1], "duplicates": "add"}).json()
check("'add' adds it again (Traktor can hold a track twice)", r["added"] == 1 and r["count"] == 5)
r = client.post(f"/api/playlists/{target}/add",
json={"track_ids": track_ids[4:5], "duplicates": "ask"}).json()
check("'ask' with nothing duplicated simply adds", r["status"] == "added" and r["added"] == 1)
check("capabilities say Traktor holds duplicates",
client.get("/api/capabilities").json()["playlists"]["duplicates"] is True)
box = client.post("/api/playlists/folders", json={"name": "Konduktor Drop Box"}).json()["id"]
r = client.post("/api/playlists/move", json={"node_id": target, "parent_id": box, "index": 0})
check("move answers the playlist's id", r.status_code == 200 and r.json()["id"] == target)
r = client.post("/api/playlists/move", json={"node_id": box, "parent_id": None, "index": 0})
check("moving a folder answers its (path) id", r.json()["id"] == box)
check("…and it is first at the top level", client.get("/api/playlists").json()[0]["id"] == box)
r = client.post("/api/playlists/move", json={"node_id": box, "parent_id": box, "index": 0})
check("a folder into itself is a 400", r.status_code == 400)
r = client.post("/api/playlists/move", json={"node_id": "nope", "parent_id": None, "index": 0})
check("an unknown node is a 404", r.status_code == 404)
client.delete(f"/api/playlists/{box}")
client.post("/api/save")
check("COLLECTION still byte-identical after drops and moves",
collection_span(WORK.read_bytes()) == collection_before)
print("== original untouched ==")
check(
"original collection.nml never modified",
+46
View File
@@ -31,6 +31,7 @@ os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-rbfid-appd
from konduktor.adapters.rekordbox import discovery # noqa: E402
from konduktor.adapters.rekordbox.adapter import RekordboxAdapter # noqa: E402
from konduktor.core.adapter import InvalidCommand # noqa: E402
failed = False
@@ -302,6 +303,51 @@ with tempfile.TemporaryDirectory() as d:
folder_reopened.close()
after_folder.close()
# ---- E2: moving nodes in the tree (sidebar drag and drop) -----------
print("== E2: move_playlist reorders and reparents, touching only playlist rows ==")
clean_copy(REAL, work, closing=[adapter, again, final, reopened])
adapter = RekordboxAdapter(work)
folder_id = adapter.create_folder("Konduktor Move Folder")
a_id = adapter.create_playlist("Konduktor Move A")
b_id = adapter.create_playlist("Konduktor Move B")
adapter.save()
adapter.close()
before = dump(work)
adapter = RekordboxAdapter(work)
check("every node offers can_move", all(n.can_move for n in adapter.playlist_tree()))
adapter.move_playlist(b_id, folder_id, 0)
adapter.move_playlist(a_id, None, 0)
tree = adapter.playlist_tree()
check("a playlist moved into a folder is its child",
[c.id for c in next(n for n in tree if n.id == folder_id).children] == [b_id])
check("a playlist moved to index 0 is first at the top level", tree[0].id == a_id,
[n.name for n in tree[:3]])
try:
adapter.move_playlist(folder_id, folder_id, 0)
check("a folder cannot be moved into itself", False)
except InvalidCommand:
check("a folder cannot be moved into itself", True)
adapter.save()
changes = diff(before, dump(work))
check("only djmdPlaylist rows and the counter change",
{t for t, _, _, _ in changes} <= {"djmdPlaylist", "agentRegistry"}, describe(changes))
rows = dump(work)["djmdPlaylist"]
for parent in ("root", folder_id):
seqs = sorted(int(r["Seq"]) for r in rows.values()
if str(r["ParentID"]) == parent and not r["rb_local_deleted"])
check(f"Seq stays 1..n under {parent}", seqs == list(range(1, len(seqs) + 1)), seqs)
adapter.close()
reopened = RekordboxAdapter(work)
tree = reopened.playlist_tree()
check("the moves round-trip through a reopen",
tree[0].id == a_id
and [c.id for c in next(n for n in tree if n.id == folder_id).children] == [b_id])
reopened.move_playlist(b_id, None, len(tree))
check("a playlist moved out of a folder lands last at the top level",
reopened.playlist_tree()[-1].id == b_id)
reopened.close()
again = final = RekordboxAdapter(work)
# ---- F: a cue write touches the cue row AND its mirror ---------------
print("== F: a hot cue write is localized, and keeps the mirror in step ==")
clean_copy(REAL, work, closing=[adapter, again, final, reopened])
+85
View File
@@ -293,6 +293,91 @@ with tempfile.TemporaryDirectory() as d:
check("…and to the mirror here", any((tr.filepath or "").endswith("Brand New.mp3")
for tr in main.require_adapter().tracks))
print("== the content folder, browsed like a drive ==")
loose = make_mp3(content / "Crate" / "Loose One.mp3", seconds=3, seed=11)
drives = c.get("/api/fs/drives").json()
check("the server is listed first among the drives, under the remote's name",
drives and drives[0] == {"name": "NAS", "path": "server:", "kind": "server", "library": None},
drives[:1])
tops = c.get("/api/fs/folders", params={"path": "server:"}).json()
check("its Files tree starts at the content folder",
{e["name"] for e in tops} >= {"Crate", "Mapped"}
and all(e["path"].startswith("server:") for e in tops), tops)
r = c.get("/api/folder/tracks", params={"path": f"server:{content}/Mapped"})
listed = r.json()
check("a folder's files the library holds are listed AS its tracks, ticked off",
r.status_code == 200 and sorted(tr["id"] for tr in listed["tracks"]) == sorted(ids)
and sorted(listed["in_collection"]) == sorted(ids) and not listed["removable"]
and all(v.startswith("server:") for v in listed["files"].values()), r.text[:300])
check("…with the collection's data, not the file's tags",
next(tr for tr in listed["tracks"] if tr["id"] == target)["genre"] == "Remote Edit")
r = c.get("/api/folder/tracks", params={"path": "server:/etc"})
check("…and nothing outside the content folder is listed", r.status_code == 400, r.text[:200])
crate = c.get("/api/folder/tracks", params={"path": f"server:{content}/Crate"}).json()
loose_id = f"server:{loose}"
check("a file the library does not hold is listed unticked",
[tr["id"] for tr in crate["tracks"]] == [loose_id] and crate["in_collection"] == [])
caps = c.get("/api/folder/capabilities", params={"path": f"server:{content}/Crate"}).json()
check("…read-only, like any browsed folder", not caps["writable"]
and caps["readonly_cause"] == "not_in_library")
folder_downloads = []
real_folder_download = adapter.client.folder_download
adapter.client.folder_download = lambda *a, **k: (folder_downloads.append(a[0]),
real_folder_download(*a, **k))[1]
r = c.get("/api/folder/tracks/audio", params={"track_id": loose_id})
check("the deck can audition it", r.status_code == 200 and r.content == loose.read_bytes())
c.get("/api/folder/tracks/audio", params={"track_id": loose_id})
check("…downloaded once", folder_downloads == [str(loose)], folder_downloads)
r = c.get("/api/folder/tracks/audio", params={"track_id": f"server:{content}/Crate/nope.mp3"})
check("a file no listing returned is not served", r.status_code == 404)
srv_unlisted = httpx.get(f"http://127.0.0.1:{port}/v1/folder/audio",
params={"path": str(work)}, auth=("dj", "secret"))
check("…nor, asked of the server directly, anything outside the content folder",
srv_unlisted.status_code == 400, srv_unlisted.text[:200])
pl = c.post("/api/playlists", json={"name": "From the server"}).json()["id"]
held_track = listed["in_collection"][0]
held_id = listed["files"][held_track] # adding speaks in folder ids
add = {"track_ids": [loose_id, held_id], "mode": "reference", "playlist_id": pl}
r = c.post("/api/folder/add/preview", json=add)
pv = r.json()
check("(preview) one new, one already held, nothing to copy",
r.status_code == 200 and pv["importable"] == 1 and len(pv["existing"]) == 1
and pv["total_bytes"] == 0 and pv["enough_space"] is None, r.text[:300])
mixed = c.post("/api/folder/add/preview", json={**add, "track_ids": [loose_id, str(incoming)]})
check("files here and on the server are not mixed in one add", mixed.status_code == 400)
# Pretend the platform analyses what it adds (as Rekordbox does): the file
# is then fetched and analysed HERE, and the server receives the result.
received = []
real_add = server_adapter.add_tracks
server_adapter.add_tracks = lambda items, **k: (received.extend(items), real_add(items, **k))[1]
server_adapter.analysis_lead = lambda path: 0.0
before = sorted(p.name for p in content.rglob("*") if p.is_file())
job = c.post("/api/folder/add", json=add).json()
for _ in range(400):
j = c.get(f"/api/jobs/{job['id']}").json()
if j["state"] != "running":
break
time.sleep(0.05)
del server_adapter.analysis_lead
server_adapter.add_tracks = real_add
added = [tr for tr in server_adapter.tracks if server_adapter.audio_path(tr.id) == loose]
check("the file is added to the library WHERE IT IS", j["state"] == "done" and len(added) == 1,
j.get("error"))
check("…nothing uploaded or copied", sorted(p.name for p in content.rglob("*") if p.is_file()) == before)
check("…analysed here on the cached copy, the result sent along",
len(received) == 1 and received[0].analysis is not None and folder_downloads == [str(loose)],
f"{len(received)} {folder_downloads}")
entries = server_adapter.playlist_entries(pl) or []
check("…both land in the playlist, the held one not added twice",
added and entries == [added[0].id, held_track]
and len(server_adapter.tracks) == len(main.require_adapter().tracks), entries)
crate = c.get("/api/folder/tracks", params={"path": f"server:{content}/Crate"}).json()
check("…and the folder now shows it ticked off, as the collection track",
crate["in_collection"] == [added[0].id] and crate["files"] == {added[0].id: loose_id}
if added else False, crate)
check("the save is versioned on the server", not server_adapter.dirty)
print("== another computer takes over ==")
other = RemoteClient(remote_config.Remote(id="o", name="NAS", host=f"127.0.0.1:{port}", username="dj"), "secret")
other.acquire("other-client", "Studio iMac", takeover=True)
+105
View File
@@ -1086,5 +1086,110 @@ with tempfile.TemporaryDirectory() as d:
check("N: …and written in Camelot", target.info.key == "1A", target.info.key)
# ---- O: moving playlists in the tree ----------------------------------
# Drag and drop in the sidebar. Moving a node relocates its whole block, so
# the guarantee is: the COLLECTION is untouched, the tree reads back as moved,
# and moving it back reproduces the original bytes exactly.
print("\n== O. move_playlist ==")
def _collection_span(data: bytes) -> bytes:
return data[data.find(b"<COLLECTION"):data.find(b"</COLLECTION>")]
def _find(nodes, name):
for n in nodes:
if n.name == name:
return n
hit = _find(n.children, name)
if hit is not None:
return hit
return None
with tempfile.TemporaryDirectory() as d:
work = Path(d) / "collection.nml"
shutil.copy2(REAL, work)
before = work.read_bytes()
store = TraktorStore(work)
roots = store.tree()
folders = [n for n in roots if n.kind == "folder" and n.children]
loose = [n for n in roots if n.kind == "playlist"]
if len(folders) < 2 or len(loose) < 2:
print(" [SKIP] the reference collection has too few top-level nodes")
else:
src, dst = folders[0], folders[1]
pl = next((c for c in src.children if c.kind == "playlist"), None) or loose[0]
home = _find(roots, pl.name)
home_parent = next((f.id for f in roots if any(c.id == pl.id for c in f.children)), None)
home_index = ([c.id for c in (src.children if home_parent else roots)].index(pl.id))
check("O: every node offers can_move", all(n.can_move for n in roots))
# A playlist into another folder, at a position.
new_id = store.move_playlist(pl.id, dst.id, 1)
tree = store.tree()
moved_into = next(n for n in tree if n.id == dst.id)
check("O: a playlist keeps its id when moved", new_id == pl.id, new_id)
check("O: …and lands at the index asked for",
len(moved_into.children) > 1 and moved_into.children[1].id == pl.id,
[c.name for c in moved_into.children[:3]])
store.save()
moved = work.read_bytes()
check("O: the COLLECTION is untouched by a move",
_collection_span(moved) == _collection_span(before))
reread = TraktorStore(work).tree()
check("O: the move round-trips through a save",
any(c.id == pl.id for c in next(n for n in reread if n.id == dst.id).children))
# …and back again: byte-identical to the original.
store.move_playlist(pl.id, home_parent, home_index)
store.save()
check("O: moving it back restores the original bytes", work.read_bytes() == before,
f"{diff_count(before, work.read_bytes())} lines differ")
# A folder moves with its subtree, and its id (a path) changes with it.
new_folder = store.move_playlist(src.id, dst.id, 0)
check("O: a moved folder answers its new path id",
new_folder == f"{dst.id}/{src.name}", new_folder)
inner = next(n for n in store.tree() if n.id == dst.id).children[0]
check("O: …and its subtree moved with it",
inner.id == new_folder and len(inner.children) == len(src.children))
child_ids = [c.id for c in inner.children]
check("O: …children keep addressable ids",
all(c.startswith((new_folder.replace("fld:", "sl:") + "/", new_folder + "/"))
or not c.startswith(("fld:", "sl:")) for c in child_ids), child_ids[:3])
# Into itself: refused, nothing changed.
snapshot = store._render()
try:
store.move_playlist(dst.id, new_folder, 0)
check("O: a folder cannot be moved into its own descendant", False)
except PlaylistError:
check("O: a folder cannot be moved into its own descendant",
store._render() == snapshot)
# A namesake folder in the target: refused (two paths would be one).
store.create_folder(src.name, None)
snapshot = store._render()
try:
store.move_playlist(new_folder, None, 0)
check("O: a folder cannot land beside a namesake", False)
except PlaylistError:
check("O: a folder cannot land beside a namesake", store._render() == snapshot)
# A smart playlist moves too, by its path id.
smart = next((c for c in inner.children if c.kind == "smart"), None)
if smart is not None:
sid = store.move_playlist(smart.id, None, 0)
check("O: a smart playlist moves and answers its new id",
sid == f"sl:{smart.name}" and store.tree()[0].id == sid, sid)
# A no-op move leaves the store clean.
fresh = TraktorStore(work)
first = fresh.tree()[0]
fresh.move_playlist(first.id, None, 0)
check("O: moving a node onto its own place is not an edit", not fresh.dirty)
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+60
View File
@@ -262,11 +262,71 @@ def stop_in_encode():
raise Stop()
def encoder_threads():
import threading
return [t.name for t in threading.enumerate() if t.name.startswith("stem-encode-")]
try:
sf.build(MP3, tmp / "cancelled.partial", fake_separate, encoder="aac", checkpoint=stop_in_encode)
check("a checkpoint that raises stops the build", False, "it finished")
except Stop:
check("a checkpoint that raises stops the build", True)
check("…and no encoder thread outlives it", not encoder_threads(), str(encoder_threads()))
print("== 6. the encode runs on one thread per stream ==")
def encode_single_threaded(fp, tracks, *, bit_rate, encoder):
"""The encode as it was before it was threaded: the reference for the bytes."""
tb = fractions.Fraction(1, SR)
c = av.open(fp, "w", format="ipod")
try:
streams = []
for k in range(len(tracks)):
s = c.add_stream(encoder, rate=SR, layout="stereo")
s.bit_rate = bit_rate
if k:
s.disposition = 0
streams.append(s)
for offset in range(0, tracks[0].shape[1], sf.FRAME):
for s, x in zip(streams, tracks):
f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, offset:offset + sf.FRAME]),
format="fltp", layout="stereo")
f.sample_rate, f.pts, f.time_base = SR, offset, tb
for p in s.encode(f):
c.mux(p)
for s in streams:
for p in s.encode(None):
c.mux(p)
finally:
c.close()
source = sf.decode(MP3)
# A length that is not a whole number of frames, and stems that differ from the mix.
five = [np.ascontiguousarray(t[:, :-333]) for t in (source.pcm, *fake_separate(source.pcm))]
for enc in encoders:
ref, par = tmp / f"ref.{enc}.m4a", tmp / f"par.{enc}.m4a"
with open(ref, "wb") as fp:
encode_single_threaded(fp, five, bit_rate=320_000, encoder=enc)
seen = []
with open(par, "wb") as fp:
sf._encode(fp, five, bit_rate=320_000, encoder=enc, checkpoint=None, progress=seen.append)
check(f"{enc}: the threaded encode is byte-identical to the single-threaded one",
ref.read_bytes() == par.read_bytes(), f"{ref.stat().st_size} vs {par.stat().st_size} bytes")
check(f"{enc}: progress runs 0 -> 1, never backwards",
len(seen) >= 3 and seen[0] == 0 and seen[-1] == 1.0 and seen == sorted(seen), str(seen))
try:
with open(tmp / "broken.m4a", "wb") as fp:
# A mono array in a stereo stream: that stream's thread fails on its first frame.
sf._encode(fp, [five[0], five[1][:1], *five[2:]], bit_rate=320_000, encoder="aac", checkpoint=None)
check("a failing encoder thread fails the encode", False, "it finished")
except Exception as ex: # noqa: BLE001
check("a failing encoder thread fails the encode, with its own error", not isinstance(ex, Stop), repr(ex))
check("…and no encoder thread outlives it", not encoder_threads(), str(encoder_threads()))
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+21
View File
@@ -73,6 +73,27 @@ check("a stem file lists its four stems with names and colours, in stream order"
check("a plain MP3 has none", sf.stem_layout(plain) is None)
check("a missing file has none (no exception)", sf.stem_layout(ROOT / "nope.stem.m4a") is None)
print("== a stem file whose tags are not UTF-8 ==")
# PyAV 18 will not open such a file unless told to ignore the bad bytes, and
# PyAV 19 rejects the keyword that tells it (core/pyav.py). A release built on
# 19 while dev ran 18 played every stem track as the mix: the route 500'd.
from mutagen.mp4 import MP4 # noqa: E402
bad = ROOT / "BadTag.stem.m4a"
shutil.copy2(stem, bad)
m = MP4(bad)
m["\xa9nam"] = ["XéX"]
m.save()
raw = bad.read_bytes()
assert raw.count("XéX".encode()) == 1
bad.write_bytes(raw.replace("XéX".encode(), b"X\xe9\xe9X")) # same length: no box sizes change
check(f"it still lists its stems (PyAV {av.__version__})", sf.stem_layout(bad) == layout, str(sf.stem_layout(bad)))
with open(ROOT / "bad-stem-1.m4a", "wb") as fp:
sf.extract_stream(bad, 1, fp)
check("…a stem still extracts, bit-identical to the stream in place",
np.array_equal(decode(ROOT / "bad-stem-1.m4a"), decode(stem, 1)))
check("…and it still decodes for conversion", sf.decode(bad).pcm.shape[1] > 0)
print("== a temp collection pointing at them ==")
work = ROOT / "collection.nml"
shutil.copy2(REAL, work)
+3 -3
View File
@@ -33,7 +33,7 @@ import numpy as np # noqa: E402
from konduktor.adapters.traktor import timebase # noqa: E402
from konduktor.adapters.traktor.adapter import TraktorAdapter # noqa: E402
from konduktor.adapters.traktor.export import SKELETON # noqa: E402
from konduktor.core import mp3_gapless # noqa: E402
from konduktor.core import mp3_gapless, pyav # noqa: E402
from konduktor.core.adapter import NewTrack # noqa: E402
from konduktor.core.model import Track # noqa: E402
@@ -197,7 +197,7 @@ else:
pad8 = re.search(r'<CUE_V2 [^>]*START="([^"]*)"[^>]*HOTCUE="7"', e)
if not pad8 or not (KIT / name).is_file():
continue
with av.open(str(KIT / name), metadata_errors="ignore") as c:
with pyav.open_input(KIT / name) as c:
st = c.streams.audio[0]
sr = st.rate
y = np.concatenate([f.to_ndarray()[0] for f in c.decode(st)]).astype(np.float64)
@@ -258,7 +258,7 @@ else:
name = c.Content.FileNameL if c.Content else ""
if not name.startswith("K4-") or c.Kind != 9 or not (KIT / name).is_file():
continue # pad H: the ones placed by hand
with av.open(str(KIT / name), metadata_errors="ignore") as con:
with pyav.open_input(KIT / name) as con:
st = con.streams.audio[0]
sr = st.rate
y = np.concatenate([f.to_ndarray()[0] for f in con.decode(st)]).astype(np.float64)
+7
View File
@@ -106,6 +106,13 @@ with tempfile.TemporaryDirectory() as d:
adapter.set_track_metadata(tid, {"genre": "Konduktor Test Genre"})
check("metadata edit is visible in the projection",
adapter.track(tid).genre == "Konduktor Test Genre")
# search reaches both comments, case-insensitively
adapter.set_track_metadata(tid, {"comment": "Konduktor Search One",
"comment2": "Konduktor Search Two"})
for q in ("search one", "SEARCH TWO"):
hits = adapter.query_tracks(q=q, limit=20000).items
check(f"search {q!r} finds the track by its comment",
[x.id for x in hits] == [tid], f"{len(hits)} hits")
# key — the projection's wheel, mode AND display text all follow
t = adapter.set_key(tid, 4, "minor") # 4A = F minor = Open Key 9m
+69
View File
@@ -0,0 +1,69 @@
# Build the Konduktor desktop app on Windows: freeze + stage the backend sidecar,
# then build the Tauri installers. First run? See one-time setup in
# BUILDING-WINDOWS.md (the backend venv with requirements-build.txt, and
# `npm install`).
#
# .\build.ps1 # sidecar + app (release installers)
# .\build.ps1 -SkipSidecar # frontend-only change: reuse the staged sidecar
# .\build.ps1 --debug # anything else is passed on to `tauri build`
# (if scripts are blocked: powershell -ExecutionPolicy Bypass -File .\build.ps1)
param([switch]$SkipSidecar)
$ErrorActionPreference = "Stop"
$Root = $PSScriptRoot
$TauriArgs = $args
$Py = Join-Path $Root "backend\.venv\Scripts\python.exe"
if (-not (Test-Path $Py)) { throw "No backend venv at backend\.venv - see BUILDING-WINDOWS.md for setup." }
if (-not (Test-Path (Join-Path $Root "frontend\node_modules"))) { throw "No frontend\node_modules - run ``npm install`` in frontend first." }
$Staged = Join-Path $Root "frontend\src-tauri\binaries\konduktor-sidecar\konduktor-sidecar.exe"
# rustup puts cargo in %USERPROFILE%\.cargo\bin and adds it to PATH only for
# terminals opened AFTER the install - so find it there before giving up, rather
# than failing ten minutes in, after the sidecar build.
if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) {
$CargoBin = Join-Path $env:USERPROFILE ".cargo\bin"
if (-not (Test-Path (Join-Path $CargoBin "cargo.exe"))) { throw "No Rust toolchain (cargo) - install it from https://rustup.rs, see BUILDING-WINDOWS.md." }
$env:PATH = "$CargoBin;$env:PATH"
}
$Started = Get-Date
# build_sidecar.ps1 changes directory itself, and a location change outlives the
# script it was made in - so put ours back whatever happens.
Push-Location $Root
try {
if ($SkipSidecar) {
if (-not (Test-Path $Staged)) { throw "No staged sidecar to reuse - run without -SkipSidecar first." }
Write-Host "==> Reusing the staged sidecar (-SkipSidecar)"
}
else {
Write-Host "==> 1/2 Freezing the backend sidecar"
& (Join-Path $Root "backend\build_sidecar.ps1")
}
Write-Host ""
Write-Host "==> 2/2 Building the app (tauri build $TauriArgs)"
Set-Location (Join-Path $Root "frontend")
# npx is a .cmd and cargo reports progress on stderr: relax "Stop" for the
# call (as build_sidecar.ps1 does for PyInstaller) and judge by exit code.
$ErrorActionPreference = "Continue"
& npx tauri build @TauriArgs
$code = $LASTEXITCODE
$ErrorActionPreference = "Stop"
if ($code -ne 0) { throw "tauri build failed ($code)" }
}
finally {
Pop-Location
}
# List what this run produced (release or --debug profile).
$Bundles = Join-Path $Root "frontend\src-tauri\target\*\bundle"
$Built = Get-ChildItem -Path "$Bundles\nsis\*-setup.exe", "$Bundles\msi\*.msi" -File -ErrorAction SilentlyContinue |
Where-Object { $_.LastWriteTime -ge $Started }
Write-Host ""
if ($Built) {
Write-Host "Installers:"
$Built | ForEach-Object { Write-Host " $($_.FullName)" }
}
else {
Write-Host "Done (no installer bundled - see frontend\src-tauri\target\)."
}
+42
View File
@@ -0,0 +1,42 @@
# Start both Konduktor servers (backend + frontend) together - the Windows
# counterpart of dev.sh. Ctrl-C stops both. First run? See one-time setup in
# BUILDING-WINDOWS.md (the backend venv and `npm install`).
#
# .\dev.ps1
# (if scripts are blocked: powershell -ExecutionPolicy Bypass -File .\dev.ps1)
$ErrorActionPreference = "Stop"
$Root = $PSScriptRoot
$Py = Join-Path $Root "backend\.venv\Scripts\python.exe"
if (-not (Test-Path $Py)) { throw "No backend venv at backend\.venv - see BUILDING-WINDOWS.md for setup." }
# Vite through node, not `npm run dev`: npm is a .cmd batch file, and Ctrl-C in a
# shared console makes cmd ask "Terminate batch job (Y/N)?" instead of exiting.
$Vite = Join-Path $Root "frontend\node_modules\vite\bin\vite.js"
if (-not (Test-Path $Vite)) { throw "No frontend\node_modules - run ``npm install`` in frontend first." }
# Backend (FastAPI on :8000)
$Backend = Start-Process -FilePath $Py -NoNewWindow -PassThru `
-ArgumentList "-m", "uvicorn", "konduktor.main:app", "--reload", "--port", "8000", "--app-dir", "`"$Root\backend`""
# Frontend (Vite on :5173, proxies /api -> :8000)
$Frontend = Start-Process -FilePath "node" -NoNewWindow -PassThru `
-WorkingDirectory (Join-Path $Root "frontend") -ArgumentList "`"$Vite`""
Write-Host ""
Write-Host " Konduktor is starting..."
Write-Host " -> App: http://localhost:5173"
Write-Host " -> API docs: http://localhost:8000/docs"
Write-Host " (Ctrl-C to stop both)"
Write-Host ""
try {
# If either one dies, stop the other rather than leave half a dev setup.
while (-not $Backend.HasExited -and -not $Frontend.HasExited) { Start-Sleep -Milliseconds 500 }
}
finally {
# Kill the whole tree: uvicorn --reload runs the server in a child process,
# which would otherwise keep :8000 bound after the reloader has gone.
foreach ($p in $Backend, $Frontend) {
if ($p -and -not $p.HasExited) { & taskkill /PID $p.Id /T /F 2>&1 | Out-Null }
}
}
+149
View File
@@ -0,0 +1,149 @@
# Building Konduktor
Most people should just [download a release](https://github.com/MrPatben8/konduktor/releases). This page is for running Konduktor from source or packaging the desktop app yourself.
## Run from source (development)
Konduktor runs as two small local servers (a Python backend and a web
frontend). Do the one-time setup, then start them — the same steps work on
macOS, Linux, and Windows.
### 1. Install (once)
**Backend** — needs Python 3.11+. Create a virtual environment and install the
dependencies:
```bash
cd backend
python3 -m venv .venv # Windows: python -m venv .venv
```
Activate it, then install:
```bash
source .venv/bin/activate # Windows (PowerShell): .\.venv\Scripts\Activate.ps1
pip install -r requirements.txt
cd ..
```
**Frontend** — needs Node 18+ (same on every platform):
```bash
cd frontend
npm install
cd ..
```
### 2. Run it (development)
Konduktor runs as two local servers (backend on `:8000`, frontend on `:5173`).
**macOS / Linux** — one command starts both:
```bash
./dev.sh
```
**Windows** — start each server in its own terminal:
```powershell
# Terminal 1 — backend
cd backend; .\.venv\Scripts\Activate.ps1; uvicorn konduktor.main:app --reload --port 8000
# Terminal 2 — frontend
cd frontend; npm run dev
```
Either way, open **http://localhost:5173** in your browser (`Ctrl-C` stops a
server). This is the fastest way to try Konduktor or hack on it — the frontend
hot-reloads as you edit. To package a real double-clickable app instead, see
[Build a standalone app](#build-a-standalone-app-production) below.
### 3. Open a library
On launch, pick your platform (Traktor, Rekordbox, OneLibrary or Remote), then
let Konduktor find the library **automatically**, reopen the **last one** you
used, or **browse** for it yourself.
Testing writes? `./dev-sandbox.sh` starts both servers against a throwaway copy
of your Traktor collection, with prefs and version history in a temp folder.
---
## Build a standalone app (production)
Prefer a real double-clickable app over running the dev servers? Konduktor
packages into a native desktop app (via **Tauri**) that bundles the Python
backend as a sidecar — no terminal, no servers to start by hand.
### Extra prerequisites
On top of the Python 3.11+ and Node 18+ from above:
- **Rust** — install from <https://rustup.rs> (the app shell is Tauri/Rust).
- **PyInstaller** — into the backend venv:
`pip install -r backend/requirements-build.txt`
- **Windows only:** also the MSVC C++ build tools and the WebView2 runtime — see
[BUILDING-WINDOWS.md](../BUILDING-WINDOWS.md) for the one-time toolchain setup.
The build is a two-step recipe on both platforms: **freeze the backend into a
sidecar folder**, then **build the app**. The only difference is which sidecar
script you run — `.sh` on macOS/Linux, `.ps1` on Windows. Each build runs on its
own OS (the app can't be cross-compiled).
### macOS / Linux
```bash
# 1) Freeze the backend into a sidecar folder (from the activated backend venv)
cd backend && source .venv/bin/activate && ./build_sidecar.sh && cd ..
# 2) Build the app
cd frontend && npx tauri build
```
The installer lands at
`frontend/src-tauri/target/release/bundle/dmg/Konduktor_<version>_aarch64.dmg`
(with the `.app` beside it).
### Windows
```powershell
# 1) Freeze the backend into a sidecar folder (from the activated backend venv)
cd backend; .\.venv\Scripts\Activate.ps1; .\build_sidecar.ps1; cd ..
# 2) Build the app
cd frontend; npx tauri build
```
The installers land in `frontend\src-tauri\target\release\bundle\` (an `.msi` and
an NSIS `-setup.exe`). See [BUILDING-WINDOWS.md](../BUILDING-WINDOWS.md) for the full
walkthrough and Windows-specific notes.
> **First launch — getting past the OS security prompt.** Builds are
> **ad-hoc signed, not notarized** (no paid Apple/Windows developer cert yet), so
> the OS flags them the first time. This is expected — the app isn't damaged.
>
> - **macOS:** right-click the app → **Open** → **Open** (or System Settings →
> Privacy & Security → **Open Anyway** after the first blocked attempt). If it
> still refuses — common for a `.dmg` downloaded via a browser, which macOS
> quarantines — clear the quarantine flag once from Terminal:
> ```bash
> xattr -cr /Applications/Konduktor.app
> ```
> - **Windows:** click **More info → Run anyway** past SmartScreen.
>
> The macOS `.dmg` is Apple-Silicon (`aarch64`) only.
> **Faster local builds:** `npx tauri build --debug --bundles app` skips the
> optimizer and the installer, giving you a runnable app in seconds — handy while
> iterating.
### Rebuilding after changes
Changed **backend** Python? Re-run the sidecar script for your OS
(`./build_sidecar.sh` or `.\build_sidecar.ps1`), then `npx tauri build`.
Frontend-only change? Just `npx tauri build` — it rebuilds the web app for you.
---
Curious about the internals or want to contribute? [CLAUDE.md](../CLAUDE.md) describes the architecture and conventions.
+40
View File
@@ -0,0 +1,40 @@
# Remote libraries: a Konduktor server on your 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.
Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 325 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 543 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 184 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 320 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 522 KiB

+5
View File
@@ -5,6 +5,11 @@
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Konduktor</title>
<!-- The app's base colour before any stylesheet loads, so the window's
first frame is dark (the shell sets the same colour on the window).
On body ONLY: a background on html stops body's from spreading to the
page, and body's own box then paints over AmbientBackdrop (-z-10). -->
<style>:root { color-scheme: dark; } body { background: #05060a; }</style>
</head>
<body>
<div id="root"></div>
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "frontend",
"private": true,
"version": "0.2.1",
"version": "0.2.7",
"type": "module",
"scripts": {
"dev": "vite",
+1 -1
View File
@@ -3,6 +3,6 @@
/target/
/gen/schemas
# Frozen backend sidecar — a build artifact (23MB); rebuild with
# Frozen backend sidecar (a onedir folder) — a build artifact; rebuild with
# backend/build_sidecar.sh. The Rust/config that reference it ARE tracked.
/binaries/
+7 -6
View File
@@ -3,12 +3,13 @@
<plist version="1.0">
<dict>
<!--
The backend is a PyInstaller one-file binary: at launch it extracts its
bundled Python.framework to a temp dir and dlopen()s it. Tauri signs every
nested binary with the hardened runtime (adhoc,runtime), which enforces
library validation — and the extracted framework has a different Team ID
than the ad-hoc-signed bootloader, so it's rejected ("different Team IDs")
and the sidecar dies on launch. Disabling library validation lets it load.
The backend is a PyInstaller onedir folder (Contents/Resources/sidecar)
whose executable dlopen()s its own ad-hoc-signed Python.framework and
native libraries. Under the hardened runtime (adhoc,runtime) library
validation rejects code with a different Team ID ("different Team IDs"),
which killed the sidecar on launch when it was a one-file binary Tauri
signed itself. Kept disabled so any process the app's signature covers
can still load those libraries.
-->
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
+190 -77
View File
@@ -1,22 +1,38 @@
// Konduktor desktop shell (Tauri v2).
//
// The backend is the frozen Python sidecar (see backend/sidecar.py): on launch
// we spawn it, read the `KONDUKTOR_PORT=<n>` line it prints on stdout, wait for
// it to actually accept connections, then create the app window with an
// initialization script that hands the frontend its API base
// (`window.__KONDUKTOR_API__`). The sidecar is killed when the app exits.
// The backend is the frozen Python sidecar (see backend/sidecar.py), a
// PyInstaller ONEDIR folder bundled as the `sidecar/` resource — not an
// `externalBin`, which must be one file. A one-file build unpacked ~390 native
// libraries into a new temp folder on every launch, and macOS scans each
// library it has not seen before as it loads, so the window took ~10 s to
// appear; installed as a folder they are scanned once.
//
// The window opens AT ONCE and shows the startup screen (StartupScreen.tsx)
// while the backend starts: a first launch after an install or update still
// waits for that one-time scan, and a window that appears seconds late looks
// like an app that failed to open. Meanwhile we spawn the sidecar, read the
// `KONDUKTOR_PORT=<n>` line it prints on stdout and wait for the socket to
// accept connections. The page asks `backend_status` and listens for
// `konduktor://backend` (starting / ready + url / stopped + the output's last
// lines); `backend_restart` is its Try again. There is no timeout here — a
// fresh install can take a minute — so the page decides when to ask the user.
// The sidecar is killed when the app exits.
//
// Quitting ASKS FIRST. Closing the window or Cmd/Ctrl+Q is prevented and
// becomes a `konduktor://quit-requested` event; the frontend (QuitGuard.tsx)
// acknowledges it, checks for unsaved changes and either quits (`quit_now`) or
// asks Save / Discard / Cancel. The sidecar must outlive that question — a
// Save or Discard runs in it — so it is killed only once the app really exits.
// If the webview does not acknowledge within ~2 s (hung, or not loaded yet),
// the app quits anyway: a broken page must never make the app unquittable.
use std::sync::atomic::{AtomicBool, Ordering};
// becomes a `konduktor://quit-requested` event; the frontend (QuitGuard.tsx,
// or the startup screen before the app has loaded) acknowledges it, checks for
// unsaved changes and either quits (`quit_now`) or asks Save / Discard /
// Cancel. The sidecar must outlive that question — a Save or Discard runs in
// it — so it is killed only once the app really exits. If the webview does not
// acknowledge within ~2 s (hung, or not loaded yet), the app quits anyway: a
// broken page must never make the app unquittable.
use std::collections::VecDeque;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Mutex;
use std::time::Duration;
use serde::Serialize;
use tauri::window::Color;
use tauri::{AppHandle, Emitter, Manager, RunEvent, WebviewUrl, WebviewWindowBuilder, WindowEvent};
use tauri_plugin_shell::process::{CommandChild, CommandEvent};
use tauri_plugin_shell::ShellExt;
@@ -24,6 +40,26 @@ use tauri_plugin_shell::ShellExt;
/// Holds the running sidecar child so we can terminate it on exit.
struct Sidecar(Mutex<Option<CommandChild>>);
/// How many of the sidecar's last output lines a "couldn't start" report keeps.
const LOG_LINES: usize = 30;
/// What the startup screen shows. Serialised as `{"state": "starting"}`,
/// `{"state": "ready", "url": …}` or `{"state": "stopped", "code", "signal", "log"}`.
#[derive(Clone, Serialize)]
#[serde(tag = "state", rename_all = "snake_case")]
enum BackendStatus {
Starting,
Ready { url: String },
Stopped { code: Option<i32>, signal: Option<i32>, log: Vec<String> },
}
/// The backend's current status, plus a generation counter: each spawn bumps
/// it, so events from a sidecar that was replaced (Try again) are ignored.
struct Backend {
status: Mutex<BackendStatus>,
generation: AtomicU64,
}
/// Quit handshake state: `allowed` once the frontend (or the timeout) has said
/// quit; `acked` once the frontend has seen the current request.
struct Quit {
@@ -59,6 +95,125 @@ fn request_quit(app: &AppHandle) {
});
}
/// Record a new status for generation `gen` (ignored if a newer sidecar has
/// been spawned since) and tell the page.
fn set_status(app: &AppHandle, gen: u64, status: BackendStatus) {
let backend = app.state::<Backend>();
if backend.generation.load(Ordering::SeqCst) != gen {
return;
}
*backend.status.lock().unwrap() = status.clone();
let _ = app.emit("konduktor://backend", status);
}
fn push_lines(log: &mut VecDeque<String>, bytes: &[u8]) {
for line in String::from_utf8_lossy(bytes).lines() {
if log.len() == LOG_LINES {
log.pop_front();
}
log.push_back(line.to_string());
}
}
/// Spawn the sidecar and follow it until it is serving (ready) or exits (stopped).
fn start_backend(app: &AppHandle) {
kill_sidecar(app);
let gen = app.state::<Backend>().generation.fetch_add(1, Ordering::SeqCst) + 1;
set_status(app, gen, BackendStatus::Starting);
// The frozen backend lives in the bundled `sidecar/` folder (staged into
// src-tauri/binaries/ by backend/build_sidecar.*).
let exe = if cfg!(windows) { "konduktor-sidecar.exe" } else { "konduktor-sidecar" };
let spawned = app
.path()
.resource_dir()
.map_err(|e| e.to_string())
.and_then(|dir| {
let program = dir.join("sidecar").join(exe);
app.shell()
.command(&program)
.spawn()
.map_err(|e| format!("{}: {e}", program.display()))
});
let (mut rx, child) = match spawned {
Ok(pair) => pair,
Err(e) => {
let log = vec![format!("Could not start the library service: {e}")];
set_status(app, gen, BackendStatus::Stopped { code: None, signal: None, log });
return;
}
};
app.state::<Sidecar>().0.lock().unwrap().replace(child);
let handle = app.clone();
tauri::async_runtime::spawn(async move {
let mut log = VecDeque::with_capacity(LOG_LINES);
let mut announced = false;
// Keep draining to the end, so the sidecar's pipes never fill and block it.
while let Some(event) = rx.recv().await {
match event {
CommandEvent::Stdout(bytes) => {
if !announced {
let text = String::from_utf8_lossy(&bytes);
let port = text.lines().find_map(|line| {
line.trim().strip_prefix("KONDUKTOR_PORT=")?.trim().parse::<u16>().ok()
});
if let Some(port) = port {
announced = true;
wait_until_serving(handle.clone(), gen, port);
}
}
push_lines(&mut log, &bytes);
}
CommandEvent::Stderr(bytes) => push_lines(&mut log, &bytes),
CommandEvent::Error(e) => push_lines(&mut log, e.as_bytes()),
CommandEvent::Terminated(payload) => {
let status = BackendStatus::Stopped {
code: payload.code,
signal: payload.signal,
log: log.iter().cloned().collect(),
};
set_status(&handle, gen, status);
}
_ => {}
}
}
});
}
/// The port line is printed before uvicorn binds: report ready once the socket
/// actually accepts connections (or give up quietly if this sidecar is gone).
fn wait_until_serving(app: AppHandle, gen: u64, port: u16) {
tauri::async_runtime::spawn(async move {
loop {
let backend = app.state::<Backend>();
let current = backend.generation.load(Ordering::SeqCst) == gen
&& matches!(*backend.status.lock().unwrap(), BackendStatus::Starting);
if !current {
return;
}
if std::net::TcpStream::connect(("127.0.0.1", port)).is_ok() {
let url = format!("http://127.0.0.1:{port}");
set_status(&app, gen, BackendStatus::Ready { url });
return;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
});
}
/// Where the backend is: the startup screen asks once on load, then listens.
#[tauri::command]
fn backend_status(app: AppHandle) -> BackendStatus {
app.state::<Backend>().status.lock().unwrap().clone()
}
/// The startup screen's Try again.
#[tauri::command]
fn backend_restart(app: AppHandle) {
start_backend(&app);
}
/// The frontend has seen the quit request (it may now take as long as it likes).
#[tauri::command]
fn quit_ack(app: AppHandle) {
@@ -82,8 +237,15 @@ pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_shell::init())
.manage(Sidecar(Mutex::new(None)))
.manage(Backend { status: Mutex::new(BackendStatus::Starting), generation: AtomicU64::new(0) })
.manage(Quit { allowed: AtomicBool::new(false), acked: AtomicBool::new(false) })
.invoke_handler(tauri::generate_handler![quit_ack, quit_cancel, quit_now])
.invoke_handler(tauri::generate_handler![
backend_status,
backend_restart,
quit_ack,
quit_cancel,
quit_now
])
.on_window_event(|window, event| {
if let WindowEvent::CloseRequested { api, .. } = event {
let app = window.app_handle();
@@ -102,71 +264,22 @@ pub fn run() {
)?;
}
let handle = app.handle().clone();
start_backend(app.handle());
// Spawn the frozen backend. In dev/bundle the shell plugin resolves
// the sidecar from `binaries/konduktor-sidecar-<target-triple>`.
let (mut rx, child) = app
.shell()
.sidecar("konduktor-sidecar")
.expect("sidecar binary not found (build it into src-tauri/binaries/)")
.spawn()
.expect("failed to spawn backend sidecar");
app.state::<Sidecar>().0.lock().unwrap().replace(child);
tauri::async_runtime::block_on(async move {
// Read stdout until the backend announces its port (bounded so a
// misbehaving sidecar can't hang the launch forever).
let find_port = async {
while let Some(event) = rx.recv().await {
if let CommandEvent::Stdout(bytes) = event {
let text = String::from_utf8_lossy(&bytes);
for line in text.lines() {
if let Some(p) = line.trim().strip_prefix("KONDUKTOR_PORT=") {
if let Ok(n) = p.trim().parse::<u16>() {
return Some(n);
}
}
}
}
}
None
};
let port = tokio::time::timeout(Duration::from_secs(20), find_port)
.await
.ok()
.flatten()
.expect("backend sidecar did not report a port");
// Keep draining events so the sidecar's stdout/stderr pipes never
// fill and block it; the task ends when the child exits.
tauri::async_runtime::spawn(async move { while rx.recv().await.is_some() {} });
// Wait for the socket to actually accept connections (the port
// line is printed before uvicorn binds).
for _ in 0..200 {
if std::net::TcpStream::connect(("127.0.0.1", port)).is_ok() {
break;
}
std::thread::sleep(Duration::from_millis(50));
}
let inject =
format!("window.__KONDUKTOR_API__ = 'http://127.0.0.1:{port}';");
WebviewWindowBuilder::new(&handle, "main", WebviewUrl::App("index.html".into()))
.title("Konduktor")
.inner_size(1400.0, 900.0)
.min_inner_size(900.0, 600.0)
// On Windows the webview would otherwise be served from
// https://tauri.localhost, and fetching the sidecar over
// http://127.0.0.1 would be blocked as mixed content. Force
// the http custom-protocol scheme so both are http. (No-op on
// macOS, which uses the tauri:// scheme.)
.use_https_scheme(false)
.initialization_script(&inject)
.build()
.expect("failed to create the main window");
});
WebviewWindowBuilder::new(app, "main", WebviewUrl::App("index.html".into()))
.title("Konduktor")
.inner_size(1400.0, 900.0)
.min_inner_size(900.0, 600.0)
// The page's own base colour (ink-950), so the first frame —
// before any CSS has loaded — is dark rather than white.
.background_color(Color(5, 6, 10, 255))
// On Windows the webview would otherwise be served from
// https://tauri.localhost, and fetching the sidecar over
// http://127.0.0.1 would be blocked as mixed content. Force
// the http custom-protocol scheme so both are http. (No-op on
// macOS, which uses the tauri:// scheme.)
.use_https_scheme(false)
.build()?;
Ok(())
})
-1
View File
@@ -19,7 +19,6 @@
"bundle": {
"active": true,
"targets": "all",
"externalBin": ["binaries/konduktor-sidecar"],
"icon": [
"icons/32x32.png",
"icons/128x128.png",
+8
View File
@@ -0,0 +1,8 @@
{
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"bundle": {
"macOS": {
"files": { "Resources/sidecar": "binaries/konduktor-sidecar" }
}
}
}
@@ -0,0 +1,6 @@
{
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"bundle": {
"resources": { "binaries/konduktor-sidecar/": "sidecar/" }
}
}
+293 -38
View File
@@ -1,11 +1,16 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import type { ColumnSizingState, SortingState, VisibilityState } from '@tanstack/react-table'
import { CapabilitiesContext, slotLabeller } from './lib/capabilities'
import { removalNote, writeHint } from './lib/platformCopy'
import { readOnlyNotice, removalNote, writeHint } from './lib/platformCopy'
import { invalidateTrackLists } from './lib/trackQueries'
import { addTracksToPlaylist } from './lib/addTracks'
import { useDragPayload, useDropTarget } from './lib/drag'
import { useNativeFileDrop } from './lib/fileDrop'
import { api, type AnalyzeOptions, type AnalyzeResult, type CueBatchResult, type AutoCueSlot, type PlaylistNode, type StemBatchResult, type Track, type TrackOrigin } from './api'
import { confirmDiscardUnsaved } from './lib/unsaved'
import { askConfirm } from './lib/confirm'
import {
COLUMN_MENU,
DEFAULT_COLUMN_ORDER,
@@ -27,9 +32,10 @@ import { RelocateDialog } from './components/RelocateDialog'
import { HistoryPanel } from './components/HistoryPanel'
import { PrepStrip } from './components/PrepStrip'
import { ImportDialog } from './components/ImportDialog'
import { AddFilesDialog, type AddTarget } from './components/AddFilesDialog'
import { AddFilesDialog, type AddTarget, type ForeignOrigin } from './components/AddFilesDialog'
import { ConvertStemsDialog } from './components/ConvertStemsDialog'
import { StemReportDialog } from './components/StemReportDialog'
import { SetPositionDialog } from './components/SetPositionDialog'
import { Icon } from './lib/icons'
import { usePrefsWriter } from './lib/prefs'
@@ -39,7 +45,7 @@ function applyFilters(tracks: Track[], f: Filters): Track[] {
const bpmMax = f.bpmMax ? parseFloat(f.bpmMax) : null
return tracks.filter((t) => {
if (q) {
const hay = `${t.artist ?? ''} ${t.title ?? ''} ${t.album ?? ''}`.toLowerCase()
const hay = [t.artist, t.title, t.album, t.comment, t.comment2].filter(Boolean).join(' ').toLowerCase()
if (!hay.includes(q)) return false
}
if (f.genre && t.genre !== f.genre) return false
@@ -77,10 +83,20 @@ export default function App() {
const [prepOrigin, setPrepOrigin] = useState<TrackOrigin>('collection')
// The view's origin, read by the load callbacks below (defined before it).
const viewOriginRef = useRef<TrackOrigin>('collection')
// Browsed files being added to the collection (and maybe a playlist/export).
const [adding, setAdding] = useState<{ ids: string[]; target: AddTarget | null } | null>(null)
// The browsed folder's rows that ARE collection tracks: collection id → the
// file's folder id. A ref, for the callbacks below that outlive a render.
const folderFilesRef = useRef<Record<string, string>>({})
// Browsed (or dropped) files being added to the collection (and maybe a
// playlist/export). `note` says what a drop left out.
const [adding, setAdding] = useState<{ ids: string[]; target: AddTarget | null; note?: string | null } | null>(null)
// How many dropped items are being read (a dropped folder is searched all
// the way down, which can take a while): shown until the dialog opens.
const [readingDrop, setReadingDrop] = useState(0)
const [playRequest, setPlayRequest] = useState(0) // bump → deck loads & auto-plays
const [importing, setImporting] = useState(false)
// Device tracks dropped on a collection playlist / export: Import, with
// just those tracks and that target.
const [importDrop, setImportDrop] = useState<{ ids: string[]; target: AddTarget } | null>(null)
// Batch analysis (grid, or Auto Hotcues): a confirm step, then the running
// job, polled into the status bar. ONE at a time across both kinds — the
// backend refuses a second, since a grid run would move the beats a hotcue
@@ -91,6 +107,8 @@ export default function App() {
// Convert to Stems: the dialog's selection, a finished run's Details, and a
// running engine download (which outlives the dialog — decided).
const [stemDialog, setStemDialog] = useState<string[] | null>(null)
// Set Position…: the tracks being moved within the open playlist.
const [positioning, setPositioning] = useState<string[] | null>(null)
const [stemReport, setStemReport] = useState<StemBatchResult | null>(null)
const [engineJob, setEngineJob] = useState<string | null>(null)
const [batchCancelling, setBatchCancelling] = useState(false)
@@ -98,9 +116,11 @@ export default function App() {
// Every Remove ▸ action (and the playlist Delete key) confirms first.
const [confirmReq, setConfirmReq] = useState<ConfirmRequest | null>(null)
const loadTrack = useCallback((t: Track) => {
const loadTrack = useCallback((t: Track, origin: TrackOrigin = viewOriginRef.current) => {
setPrepTrack(t)
setPrepOrigin(viewOriginRef.current)
// A folder row the collection holds IS the collection track, so the deck
// loads it as one: its cues and grid, and editable (decided 2026-10-10).
setPrepOrigin(origin === 'folder' && folderFilesRef.current[t.id] ? 'collection' : origin)
}, [])
const playTrack = useCallback(
(t: Track) => {
@@ -299,6 +319,11 @@ export default function App() {
() => new Set(folderView.data?.in_collection ?? []),
[folderView.data],
)
const folderFiles = useMemo(() => folderView.data?.files ?? {}, [folderView.data])
folderFilesRef.current = viewingFolder ? folderFiles : {}
// Adding speaks in FOLDER ids; a row the collection holds carries its
// collection id, and maps back (the add dialog then reports it as held).
const toFolderIds = (ids: string[]) => ids.map((id) => folderFiles[id] ?? id)
viewOriginRef.current = viewingDevice ? 'device' : viewingFolder ? 'folder' : 'collection'
// Tracks in view belong to ANOTHER library (a device) or to none (a folder),
// so no collection command may be offered on them: their ids mean nothing to
@@ -339,20 +364,142 @@ export default function App() {
},
[refreshExport, exportSets.data, notify, onError],
)
// The same path as a drop on a sidebar playlist (lib/addTracks.ts), so the
// menu and the drag ask about duplicates alike.
const duplicatesAllowed = !!capabilities.data?.playlists.duplicates
const addToPlaylist = useCallback(
async (uuid: string, ids: string[]) => {
try {
const res = await api.addEntries(uuid, ids)
qc.invalidateQueries({ queryKey: ['state'] })
qc.invalidateQueries({ queryKey: ['playlists'] })
qc.invalidateQueries({ queryKey: ['playlist', uuid] })
const name = addablePlaylists.find((p) => p.id === uuid)?.name ?? 'playlist'
notify('success', `Added ${res.added} track${res.added === 1 ? '' : 's'} to ${name}`)
const msg = await addTracksToPlaylist({ qc, playlist: { id: uuid, name }, ids, duplicatesAllowed })
if (msg) notify('success', msg)
} catch (e) {
onError((e as Error).message)
}
},
[qc, addablePlaylists, notify, onError],
[qc, addablePlaylists, duplicatesAllowed, notify, onError],
)
// Tracks from a device or a Files folder dropped on a collection playlist or
// export: they are not in the collection yet, so the drop opens the dialog
// that adds them — with that target filled in, and copy-vs-reference still
// asked (decided 2026-10-06).
// Files dragged in from Finder / Explorer (lib/fileDrop.ts). What is in them
// is read first — folders all the way down — and then they go where a
// browsed folder's files go: the add dialog, copy-vs-reference asked.
const readDrop = useCallback(
async (paths: string[]) => {
setReadingDrop(paths.length)
try {
return await api.folderDropped(paths)
} catch (e) {
onError((e as Error).message)
return null
} finally {
setReadingDrop(0)
}
},
[onError],
)
const dropFiles = useCallback(
async (paths: string[], target: AddTarget | null) => {
const r = await readDrop(paths)
if (!r) return
if (!r.tracks.length) {
onError(
paths.length === 1 && r.skipped
? 'That is not an audio file this library can hold.'
: 'No audio files this library can hold were found there.',
)
return
}
const notes: string[] = []
if (r.skipped)
notes.push(
r.skipped === 1
? '1 dropped item is not audio this library can hold and was left out.'
: `${r.skipped} dropped items are not audio this library can hold and were left out.`,
)
if (r.truncated) notes.push(`Only the first ${r.tracks.length.toLocaleString()} files are included.`)
// Files the collection holds are its tracks already: as with a folder's
// rows, nothing to add first — straight into the target, if there is one.
const held = r.tracks.filter((t) => r.files[t.id]).map((t) => t.id)
if (held.length === r.tracks.length) {
if (target?.kind === 'playlist') void addToPlaylist(target.id, held)
else if (target) void addToExport(target.id, held)
else
notify(
'success',
held.length === 1 ? 'Already in your collection' : `All ${held.length} are already in your collection`,
)
return
}
setAdding({ ids: r.tracks.map((t) => r.files[t.id] ?? t.id), target, note: notes.join(' ') || null })
},
[readDrop, addToPlaylist, addToExport, notify, onError],
)
// One dropped audio file on the deck: loaded to listen to, added to nothing.
const loadDropped = useCallback(
async (path: string) => {
const r = await readDrop([path])
if (!r) return
const t = r.tracks[0]
if (!t) {
onError('That is not an audio file this library can hold.')
return
}
loadTrack(t, r.files[t.id] ? 'collection' : 'folder')
},
[readDrop, loadTrack, onError],
)
const addForeign = useCallback(
(origin: ForeignOrigin, ids: string[], target: AddTarget) => {
if (origin === 'dropped') void dropFiles(ids, target)
else if (origin === 'folder') {
const files = folderFilesRef.current
// Rows that are all collection tracks already: nothing to add first.
if (ids.every((id) => files[id])) {
if (target.kind === 'playlist') void addToPlaylist(target.id, ids)
else void addToExport(target.id, ids)
} else setAdding({ ids: ids.map((id) => files[id] ?? id), target })
} else if (origin === 'device') setImportDrop({ ids, target })
},
[addToPlaylist, addToExport, dropFiles],
)
const audioFormats = capabilities.data?.tracks.audio_formats
const isAudioPath = (path: string) =>
path.lastIndexOf('.') > 0 && !!audioFormats?.includes(path.slice(path.lastIndexOf('.')).toLowerCase())
const [deckDropRef, deckOver] = useDropTarget<true>({
hint: (p) =>
p.kind === 'tracks' || (p.kind === 'files' && p.paths.length === 1 && isAudioPath(p.paths[0])) ? true : null,
label: (p) => (p.kind === 'tracks' && p.ids.length > 1 ? `Load “${p.lead.title || 'Untitled'}” into the deck` : 'Load into the deck'),
onDrop: (p) => {
if (p.kind === 'tracks') loadTrack(p.lead, p.origin)
else if (p.kind === 'files') void loadDropped(p.paths[0])
},
})
// Files dropped anywhere no other target takes them: the collection. A
// library that cannot add tracks still takes the drop, to say why not —
// silently ignoring it would read as the feature being broken.
const canAddFiles = (capabilities.data?.writable ?? false) && !!capabilities.data?.tracks.addable
const cannotAddFiles =
capabilities.data && !capabilities.data.writable
? (readOnlyNotice(capabilities.data) ?? 'This library is read-only.')
: 'Tracks cannot be added to this library.'
const [rootDropRef, rootOver] = useDropTarget<true>({
hint: (p) => (p.kind === 'files' ? true : null),
label: () => (canAddFiles ? 'Add to your collection…' : null),
onDrop: (p) => {
if (p.kind !== 'files') return
if (canAddFiles) void dropFiles(p.paths, null)
else notify('error', cannotAddFiles)
},
})
const draggingFiles = useDragPayload()?.kind === 'files'
useNativeFileDrop(loaded && !forcePicker, () =>
notify(
'warning',
'Dropping files works in the Konduktor app, not in a browser (it cannot tell the page where a file is). Browse to it under Files in the sidebar instead.',
),
)
const removeFromExport = useCallback(
async (id: string, ids: string[]) => {
@@ -383,7 +530,10 @@ export default function App() {
: origin === 'folder'
? (folderCaps.data ?? readOnlyCaps('not_in_library'))
: capabilities.data!
const viewCaps = capsFor(viewOriginRef.current)
// A folder's table runs on the COLLECTION's: the rows it holds are collection
// tracks and edit as such, and a loose row asks to be added first
// (`folderMayEdit`) rather than rendering inert.
const viewCaps = viewingFolder ? capabilities.data! : capsFor(viewOriginRef.current)
// The deck follows its TRACK's library, not the view's.
const deckCaps = capsFor(prepOrigin)
@@ -419,9 +569,12 @@ export default function App() {
// PrepStrip keys its audio on the id, so a new object for the same id
// reloads nothing.
useEffect(() => {
if (!prepTrack || viewOriginRef.current !== prepOrigin) return
if (!prepTrack) return
const fresh = tracks.find((t) => t.id === prepTrack.id)
if (fresh && JSON.stringify(fresh) !== JSON.stringify(prepTrack)) setPrepTrack(fresh)
if (!fresh) return
const origin =
viewOriginRef.current === 'folder' && folderFilesRef.current[fresh.id] ? 'collection' : viewOriginRef.current
if (origin === prepOrigin && JSON.stringify(fresh) !== JSON.stringify(prepTrack)) setPrepTrack(fresh)
// Only a refetch of the list matters; prepTrack is read, not tracked.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tracks])
@@ -612,7 +765,7 @@ export default function App() {
}
// ---- Convert to Stems ------------------------------------------------------
const canStems = canEdit && !viewForeign && !!capabilities.data?.tracks.stem_convertible
const canStems = canEdit && !viewingDevice && !!capabilities.data?.tracks.stem_convertible
const finishStemBatch = (state: string, r: StemBatchResult | null, error: string | null) => {
qc.invalidateQueries({ queryKey: ['state'] })
if (state === 'failed' || !r) {
@@ -764,7 +917,7 @@ export default function App() {
// the rest with a reason.
const canAnalyzeGrid = !!capabilities.data?.grid.editable
const canAnalyzeKey = !!capabilities.data?.tracks.key_writable
const canAnalyze = canEdit && !viewForeign && (canAnalyzeGrid || canAnalyzeKey)
const canAnalyze = canEdit && !viewingDevice && (canAnalyzeGrid || canAnalyzeKey)
const startCueBatch = (ids: string[]) => {
const byId = new Map(tracks.map((t) => [t.id, t]))
@@ -777,7 +930,7 @@ export default function App() {
setBatchCancelling(false)
setBatchJob({ id: job.id, kind: 'cues' })
}
const canAutoCue = canEdit && !viewForeign && (capabilities.data?.cues.hotcue_slots ?? 0) > 0
const canAutoCue = canEdit && !viewingDevice && (capabilities.data?.cues.hotcue_slots ?? 0) > 0
// ---- Remove ▸ -----------------------------------------------------------
@@ -910,12 +1063,48 @@ export default function App() {
}),
})
const canClearGrids = canEdit && !viewForeign && !!capabilities.data?.grid.editable
const canClearGrids = canEdit && !viewingDevice && !!capabilities.data?.grid.editable
const canClearCues = canAutoCue
const canRemoveTracks = canEdit && !viewForeign && !!capabilities.data?.tracks.removable
const canRemoveTracks = canEdit && !viewingDevice && !!capabilities.data?.tracks.removable
// The COLLECTION's capabilities, deliberately: adding happens while a folder
// or device is on screen, whose own capabilities are read-only.
const canAddTracks = canEdit && !!capabilities.data?.tracks.addable
// In a folder, only the rows the collection holds can be edited. Anything
// that would edit a loose file says so and offers to add it, rather than
// being absent or silently inert (decided 2026-10-10).
const askToAdd = async (ids: string[]) => {
const loose = ids.filter((id) => !folderFiles[id])
if (!loose.length) return
const first = tracks.find((t) => t.id === loose[0])
const what =
loose.length === 1
? `“${first?.title || 'This file'}” is not in your collection`
: `${loose.length} of these files are not in your collection`
if (!canAddTracks) {
notify('error', `${what}, and tracks cannot be added to this library.`)
return
}
const add = await askConfirm({
title: 'Add to your collection first',
body: `${what} yet. Add ${loose.length === 1 ? 'it' : 'them'} to edit tags, cues or the beatgrid.`,
confirmLabel: 'Add to Collection…',
tone: 'primary',
})
if (add) setAdding({ ids: loose, target: null })
}
const folderEditField = (track: Track, field: keyof Track, value: string | number) => {
if (folderFiles[track.id]) editField(track, field, value)
else void askToAdd([track.id])
}
const folderMayEdit = (track: Track) => {
if (folderFiles[track.id]) return true
void askToAdd([track.id])
return false
}
// The open menu's loose files: every editing item then asks to add them.
const menuLoose = menu && viewingFolder ? menu.ids.filter((id) => !folderFiles[id]) : []
const gated = (fn: () => void) => (menuLoose.length ? () => void askToAdd(menuLoose) : fn)
const exportRootId =
source.kind === 'export' ? source.id : source.kind === 'export-other' ? source.exportId : null
const removeItems = (ids: string[]): MenuItem[] => [
@@ -983,8 +1172,26 @@ export default function App() {
<CapabilitiesContext.Provider value={capabilities.data!}>
{/* Floating glass panels with gaps between them: the ambient backdrop
(main.tsx) shows through the gutters as well as through the glass. */}
<div className="flex h-screen w-screen flex-col gap-3 overflow-hidden p-3">
<div ref={rootDropRef} className="flex h-screen w-screen flex-col gap-3 overflow-hidden p-3">
<Toast toast={toast} onClose={() => setToast(null)} />
{draggingFiles && rootOver &&
createPortal(
<div aria-hidden className="pointer-events-none fixed inset-0 z-[85] flex items-center justify-center">
<div className="absolute inset-1.5 rounded-[26px] ring-2 ring-accent" />
<div className="glass-overlay flex items-center gap-2.5 overflow-hidden rounded-2xl px-5 py-3 text-sm text-text shadow-lg">
<Icon name="music" size={15} className={canAddFiles ? 'text-accent' : 'text-pink'} />
{canAddFiles ? 'Drop to add to your collection' : cannotAddFiles}
</div>
</div>,
document.body,
)}
{readingDrop > 0 &&
createPortal(
<div className="glass-overlay pointer-events-none fixed bottom-14 left-1/2 z-[80] -translate-x-1/2 overflow-hidden rounded-full px-4 py-2 text-xs text-muted shadow-lg">
Looking for audio in {readingDrop === 1 ? 'the dropped item' : `${readingDrop} dropped items`}…
</div>,
document.body,
)}
{menu && (
<ContextMenu
// Remount per opening: a right-click on another row while a menu is
@@ -999,8 +1206,8 @@ export default function App() {
: []),
// Offering "Edit Tags…" on a read-only library would open a dialog
// whose every save is refused, so it is not offered at all.
...(canEdit && !viewForeign && menu.ids.length === 1
? [{ label: 'Edit Tags…', onClick: () => setEditing(menu.track) }]
...(canEdit && !viewingDevice && menu.ids.length === 1
? [{ label: 'Edit Tags…', onClick: gated(() => setEditing(menu.track)) }]
: []),
...(canAnalyze
? [
@@ -1008,7 +1215,7 @@ export default function App() {
label: 'Analyze…',
hint: batchJob ? 'busy' : menu.ids.length > 1 ? String(menu.ids.length) : undefined,
disabled: !!batchJob,
onClick: () => setAnalyzing(menu.ids),
onClick: gated(() => setAnalyzing(menu.ids)),
},
]
: []),
@@ -1020,20 +1227,20 @@ export default function App() {
label: 'Auto Hotcues…',
hint: batchJob ? 'busy' : menu.ids.length > 1 ? String(menu.ids.length) : undefined,
disabled: !!batchJob,
onClick: () => startCueBatch(menu.ids),
onClick: gated(() => startCueBatch(menu.ids)),
},
]
: []),
// Shown disabled WITH a reason where the platform cannot play stem
// files as stems, rather than hidden: a missing item reads as a bug.
...(canEdit && !viewForeign
...(canEdit && !viewingDevice
? [
canStems
? {
label: 'Convert to Stems…',
hint: batchJob ? 'busy' : menu.ids.length > 1 ? String(menu.ids.length) : undefined,
disabled: !!batchJob,
onClick: () => setStemDialog(menu.ids),
onClick: gated(() => setStemDialog(menu.ids)),
}
: {
label: 'Convert to Stems…',
@@ -1046,12 +1253,14 @@ export default function App() {
// A device's track ids belong to the stick, not the collection, so
// there is nothing they could be added to. A folder's files CAN be
// added — through the add dialog, which puts them in the
// collection first.
// collection first; rows it already holds are collection tracks.
...(viewingFolder
? canAddTracks
? !menuLoose.length
? [{ label: 'Add to', submenu: addToItems(menu.ids) }]
: canAddTracks
? [
{ label: 'Add to Collection…', onClick: () => setAdding({ ids: menu.ids, target: null }) },
{ label: 'Add to', submenu: folderAddToItems(menu.ids) },
{ label: 'Add to Collection…', onClick: () => setAdding({ ids: menuLoose, target: null }) },
{ label: 'Add to', submenu: folderAddToItems(toFolderIds(menu.ids)) },
]
: [{
label: 'Add to Collection…',
@@ -1062,8 +1271,13 @@ export default function App() {
: viewingDevice
? []
: [{ label: 'Add to', submenu: addToItems(menu.ids) }]),
// Unlike drag-reorder this stays on while sorted or filtered: it
// moves within the playlist's FULL order, which the # column shows.
...(playlistEditable
? [{ label: 'Set Position…', onClick: () => setPositioning(menu.ids) }]
: []),
...(() => {
const items = removeItems(menu.ids)
const items = menuLoose.length ? [] : removeItems(menu.ids)
return items.length ? [{ label: 'Remove', submenu: items }] : []
})(),
]}
@@ -1103,6 +1317,14 @@ export default function App() {
/>
)}
{stemReport && <StemReportDialog result={stemReport} onClose={() => setStemReport(null)} />}
{positioning && (
<SetPositionDialog
order={tracks.map((t) => t.id)}
ids={positioning}
onMove={reorderPlaylist}
onClose={() => setPositioning(null)}
/>
)}
{editing && (
<EditTagsDialog
track={editing}
@@ -1182,6 +1404,7 @@ export default function App() {
<AddFilesDialog
trackIds={adding.ids}
target={adding.target}
note={adding.note}
onClose={() => setAdding(null)}
onDone={(msg) => {
setAdding(null)
@@ -1191,7 +1414,27 @@ export default function App() {
/>
)}
{/* Prep strip spans the top of the window; the library sits below it. */}
{importDrop && (
<ImportDialog
playlistId={null}
trackIds={importDrop.ids}
target={importDrop.target}
deviceLabel={deviceLabel}
onClose={() => setImportDrop(null)}
onDone={(msg) => {
setImportDrop(null)
notify('success', msg)
}}
onError={onError}
/>
)}
{/* Prep strip spans the top of the window; the library sits below it.
A track dropped on it loads (paused) — the row the drag started on. */}
<div ref={deckDropRef} className="relative shrink-0">
{deckOver && (
<div aria-hidden className="pointer-events-none absolute inset-0 z-10 rounded-[22px] ring-2 ring-accent" />
)}
<CapabilitiesContext.Provider value={deckCaps}>
<PrepStrip
track={prepTrack}
@@ -1203,6 +1446,7 @@ export default function App() {
onPlayingChange={setDeckPlaying}
/>
</CapabilitiesContext.Provider>
</div>
<div className="flex min-h-0 flex-1 gap-3">
<Sidebar
@@ -1214,6 +1458,7 @@ export default function App() {
onSwitchLibrary={() => setForcePicker(true)}
onOpenLibrary={(path) => void openForEditing(path)}
onDone={(msg) => notify('success', msg)}
onAddForeign={addForeign}
onOpenPathMapping={() => setShowPaths(true)}
onDiscarded={() => afterBulk(prepTrack ? [prepTrack.id] : [], true)}
/>
@@ -1256,9 +1501,11 @@ export default function App() {
{' · this folder only'}
</span>
<span className="ml-auto flex items-center gap-2">
<span className="rounded-full bg-gold/10 px-2 py-0.5 text-[10px] uppercase tracking-wide text-gold shadow-[inset_0_0_0_1px_rgb(255_200_97/0.3)]">
Not in collection
</span>
{tracks.length > heldInFolder.size && (
<span className="rounded-full bg-gold/10 px-2 py-0.5 text-[10px] uppercase tracking-wide text-gold shadow-[inset_0_0_0_1px_rgb(255_200_97/0.3)]">
Not in collection
</span>
)}
{tracks.length > 0 && canAddTracks && (
<button
onClick={() =>
@@ -1266,7 +1513,7 @@ export default function App() {
// The selection when there is one, else everything in
// view that the collection does not already hold.
ids: selected.size
? filtered.filter((t) => selected.has(t.id)).map((t) => t.id)
? toFolderIds(filtered.filter((t) => selected.has(t.id)).map((t) => t.id))
: filtered.filter((t) => !heldInFolder.has(t.id)).map((t) => t.id),
target: null,
})
@@ -1396,9 +1643,12 @@ export default function App() {
onSortingChange={setSorting}
selection={{ selected, onChange: setSelected }}
marked={{ ids: heldInFolder, title: 'Already in your collection' }}
dragFrom={{ origin: 'folder' }}
onRowContextMenu={(track, x, y) => openMenu(track, x, y, true)}
onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })}
onPlay={playTrack}
onEditField={canEdit ? folderEditField : undefined}
mayEdit={folderMayEdit}
activeTrackId={prepTrack?.id ?? null}
activePlaying={deckPlaying}
columnVisibility={columnVisibility}
@@ -1431,6 +1681,7 @@ export default function App() {
sorting={sorting}
onSortingChange={setSorting}
onRowContextMenu={(track, x, y) => openMenu(track, x, y, false)}
dragFrom={{ origin: 'device' }}
onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })}
onPlay={playTrack}
activeTrackId={prepTrack?.id ?? null}
@@ -1492,6 +1743,10 @@ export default function App() {
: undefined
}
onRemove={playlistEditable ? confirmRemoveFromPlaylist : undefined}
dragFrom={{
origin: 'collection',
playlistId: playlistEditable && source.kind === 'playlist' ? source.id : undefined,
}}
onRowContextMenu={(track, x, y) => openMenu(track, x, y, true)}
onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })}
onPlay={playTrack}
+71 -15
View File
@@ -83,6 +83,8 @@ export interface PlaylistNode {
can_rename: boolean
can_delete: boolean
can_contain_children: boolean
/** Can be dragged elsewhere in the tree (reordered, or into a folder). */
can_move: boolean
}
export type SortField =
@@ -270,7 +272,13 @@ export interface Capabilities {
/** Added files can be left where they are rather than copied. */
reference: boolean
}
playlists: { folders: boolean; smart: 'none' | 'read_only'; reorder: boolean }
playlists: {
folders: boolean
smart: 'none' | 'read_only'
reorder: boolean
/** A playlist can hold the same track twice (else duplicates are skipped). */
duplicates: boolean
}
/** Path mapping / rewriting / the missing-files check apply to this library. */
paths: { remappable: boolean }
save: SaveCapabilities
@@ -433,6 +441,10 @@ export interface ImportRequest {
playlist_ids?: string[]
/** Playlists land in a folder named this; null keeps them at the root. */
folder_name?: string | null
/** Every imported track (and any already held) also goes into this
* collection playlist / export — a drop of device tracks on one. */
into_playlist?: string | null
export_id?: string | null
}
export interface ImportPreview {
@@ -466,17 +478,28 @@ export interface ImportPreview {
export interface Drive {
name: string
path: string
/** `local` = boot disk or a drive built in; anything uncertain is external. */
kind: 'local' | 'external'
/** `local` = boot disk or a drive built in; anything uncertain is external.
* `server` = a remote library's content folder (path `server:`). */
kind: 'local' | 'external' | 'server'
/** The OneLibrary library on this drive, if it carries one. */
library: SourceCandidate | null
}
/** A path in a remote library's content folder, as the Files routes take it:
* `server:` + the path ON THE SERVER, so it cannot be taken for the same
* path on this computer. Such files are already where the library can reach
* them, so adding one never copies or uploads it. */
export const isServerPath = (path: string) => path.startsWith('server:')
export interface FolderTracks {
path: string
tracks: Track[]
/** Ids of the files the collection already points at. */
/** Collection ids of the rows that ARE collection tracks: a file the
* collection holds is listed as its track (id, key, rating, cues…), so it
* plays, edits and drags as one. Any other file is its own tags, id = path. */
in_collection: string[]
/** Those rows' collection id → the file's folder id, which adding takes. */
files: Record<string, string>
/** On an external drive — referencing in place would go missing on unplug. */
removable: boolean
}
@@ -491,7 +514,27 @@ export interface FolderAddRequest {
}
export interface FolderAddPreview extends ImportPreview {
/** Some of the files to add are on an external drive. */
removable: boolean
/** How many, and on which drives — per FILE, since a drop can mix drives. */
removable_count?: number
removable_drives?: string[]
/** Copy mode: files already inside the import folder (copying makes a
* second copy beside them). */
in_destination?: number
}
/** What files dropped onto the window from the OS resolved to: the audio in
* them (folders searched all the way down), listed as a folder lists its
* files — a file the collection holds is its collection track. */
export interface DroppedFiles {
tracks: Track[]
/** Collection id → the file's folder id (= its path), for held rows. */
files: Record<string, string>
/** Dropped files that are not audio this library can hold, or are gone. */
skipped: number
/** Too many files: only the first 20,000 are included. */
truncated: boolean
}
export type JobState = 'running' | 'done' | 'failed' | 'cancelled'
@@ -814,14 +857,15 @@ export interface PrefixSuggestions {
}
// API origin. In the packaged desktop app the frontend is served from
// tauri://localhost, so it can't use relative /api paths — the Tauri shell
// injects window.__KONDUKTOR_API__ (the sidecar's http://127.0.0.1:<port>)
// before any app script runs. In the browser dev server it's undefined, so we
// fall back to relative URLs and let Vite proxy /api to the backend.
export const API_BASE: string =
(typeof window !== 'undefined' &&
(window as unknown as { __KONDUKTOR_API__?: string }).__KONDUKTOR_API__) ||
''
// tauri://localhost, so it can't use relative /api paths: the sidecar's
// http://127.0.0.1:<port> is only known once it has started, and the startup
// screen (StartupScreen.tsx) sets it here before anything else renders. In the
// browser dev server it stays '', so URLs are relative and Vite proxies /api.
export let API_BASE = ''
export function setApiBase(url: string): void {
API_BASE = url
}
async function getJSON<T>(url: string): Promise<T> {
const res = await fetch(API_BASE + url)
@@ -988,12 +1032,23 @@ export const api = {
send<{ status: string; count: number }>('PUT', `/api/playlists/${encodeURIComponent(nodeId)}/entries`, {
track_ids: trackIds,
}),
addEntries: (nodeId: string, trackIds: string[]) =>
send<{ status: string; added: number; count: number }>(
/** Append tracks. `duplicates` decides tracks already there: skip them,
* add them again (where `playlists.duplicates`), or `ask` — nothing changes
* and the answer's `status: 'duplicates'` says how many, to ask and resend. */
addEntries: (nodeId: string, trackIds: string[], duplicates: 'skip' | 'add' | 'ask' = 'skip') =>
send<{ status: 'added' | 'duplicates'; added: number; duplicates: number; count: number }>(
'POST',
`/api/playlists/${encodeURIComponent(nodeId)}/add`,
{ track_ids: trackIds },
{ track_ids: trackIds, duplicates },
),
/** Move a tree node to `index` among `parentId`'s children (null = top
* level), counted without it. Answers its id AFTER the move. */
movePlaylist: (nodeId: string, parentId: string | null, index: number) =>
send<{ status: string; id: string }>('POST', '/api/playlists/move', {
node_id: nodeId,
parent_id: parentId,
index,
}),
getPrefs: () => getJSON<Record<string, unknown>>('/api/prefs'),
patchPrefs: (patch: Record<string, unknown>) =>
send<Record<string, unknown>>('PATCH', '/api/prefs', patch),
@@ -1142,6 +1197,7 @@ export const api = {
folderAddPreview: (body: FolderAddRequest) =>
send<FolderAddPreview>('POST', '/api/folder/add/preview', body),
folderAdd: (body: FolderAddRequest) => send<JobStatus>('POST', '/api/folder/add', body),
folderDropped: (paths: string[]) => send<DroppedFiles>('POST', '/api/folder/dropped', { paths }),
// ---- import ----
importPreview: (body: ImportRequest) => send<ImportPreview>('POST', '/api/import/preview', body),
/** Starts the job and returns immediately — poll `job()` for progress. */
+56 -11
View File
@@ -1,7 +1,7 @@
import { createPortal } from 'react-dom'
import { useEffect, useRef, useState, type ReactNode } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { api, type FolderAddPreview, type FolderAddRequest, type JobStatus } from '../api'
import { api, isServerPath, type FolderAddPreview, type FolderAddRequest, type JobStatus, type TrackOrigin } from '../api'
import { useCaps } from '../lib/capabilities'
import { placedAudioSummary } from '../lib/platformCopy'
import { FolderPicker } from './FolderPicker'
@@ -20,7 +20,14 @@ import { FolderPicker } from './FolderPicker'
*
* A library held by a server (`tracks.audio_destination === 'library'`) is the
* other exception: it cannot see this computer's files, so the only choice is
* which folder ON THE SERVER they are uploaded into.
* which folder ON THE SERVER they are uploaded into — unless the files were
* browsed in that server's own content folder: they are already where the
* library can reach them, so they are added in place, uploaded nowhere and
* nothing asked (decided 2026-10-10).
*
* Files dropped onto the window from the OS (`lib/fileDrop.ts`) arrive here
* too, so a drop asks exactly what the sidebar's Add to Collection asks. A
* drop can mix drives, so the external-drive warning counts files per drive.
*
* A playlist or export target still needs the files in the collection first —
* both hold collection track ids — so the dialog says so rather than doing it
@@ -42,26 +49,47 @@ export interface AddTarget {
name: string
}
/** Where tracks headed for the collection come from: another library's or a
* folder's track ids, or — `dropped` — paths dragged in from the OS. */
export type ForeignOrigin = TrackOrigin | 'dropped'
interface Props {
trackIds: string[]
target: AddTarget | null
/** A line about what was left out before the dialog (a drop's non-audio files). */
note?: string | null
onClose: () => void
onDone: (msg: string) => void
onError: (msg: string) => void
}
export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: Props) {
/** The leave-in-place warning, per drive: a drop can mix the computer's own
* disk with a stick, and only the stick's files go missing on unplug. */
function removableWarning(p: FolderAddPreview, newCount: number): string {
const count = p.removable_count ?? newCount
const drives = p.removable_drives ?? []
const where = drives.length === 1 ? `${drives[0]}, an external drive` : 'external drives'
const what = count >= newCount ? 'These files are' : `${count} of these files are`
const unplugged = drives.length === 1 ? 'it is' : 'they are'
return `${what} on ${where}. They will go missing from your collection whenever ${unplugged} unplugged.`
}
export function AddFilesDialog({ trackIds, target, note, onClose, onDone, onError }: Props) {
const qc = useQueryClient()
// The LIBRARY's capabilities (this dialog is mounted outside the browsed
// view's swapped context). A library that places its own audio — a stick —
// decides copy vs in place itself, so there is nothing to ask.
const caps = useCaps()
const places = caps.tracks.places_audio
// Already in the server's content folder: added where they are.
const onServer = trackIds.length > 0 && trackIds.every(isServerPath)
// Uploaded into a folder on the server: nothing to ask but where.
const uploads = !places && caps.tracks.audio_destination === 'library'
const [mode, setMode] = useState<'copy' | 'reference' | null>(uploads ? 'copy' : null)
const uploads = !places && !onServer && caps.tracks.audio_destination === 'library'
const [mode, setMode] = useState<'copy' | 'reference' | null>(
onServer ? 'reference' : uploads ? 'copy' : null,
)
const [folder, setFolder] = useState('')
const remote = useServerImportFolder(uploads)
const remote = useServerImportFolder(uploads || onServer)
const [browsing, setBrowsing] = useState(false)
const [job, setJob] = useState<JobStatus | null>(null)
const [starting, setStarting] = useState(false)
@@ -170,9 +198,12 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
const newCount = p?.importable ?? 0
const shown = places ? 'placed' : mode
const libraryName = places ? caps.save.app_name : 'your collection'
// Every file is held already: nothing is copied or referenced, so there is
// nothing to ask — only the target to fill.
const nothingNew = !!p && newCount === 0 && p.existing.length > 0
const canAdd =
!starting && shown !== null && !!p && (newCount > 0 || (!!target && p.existing.length > 0)) &&
p.enough_space !== false
!starting && (shown !== null || nothingNew) && !!p &&
(newCount > 0 || (!!target && p.existing.length > 0)) && p.enough_space !== false
const title = target
? `Add ${n} track${n === 1 ? '' : 's'} to ${target.name}`
@@ -251,7 +282,16 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
</div>
)}
{!places && !uploads && (
{onServer && (
<div className="rounded well px-3 py-2 text-xs text-muted">
Already on {remote.serverName}, so your collection points at them where they
are. Nothing is uploaded or copied.
</div>
)}
{note && <div className="text-xs text-muted">{note}</div>}
{!places && !uploads && !onServer && !nothingNew && (
<div className="space-y-1">
{option(
'copy',
@@ -282,9 +322,14 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
)}
{mode === 'reference' && p?.removable && (
<div className="rounded well px-3 py-2 text-xs text-gold">{removableWarning(p, newCount)}</div>
)}
{mode === 'copy' && !!p?.in_destination && (
<div className="rounded well px-3 py-2 text-xs text-gold">
These files are on an external drive. They will go missing from your
collection whenever the drive is unplugged.
{p.in_destination === newCount ? 'These files are' : `${p.in_destination} of these files are`}{' '}
already in your import folder. Copying makes a second copy beside{' '}
{p.in_destination === 1 ? 'it' : 'them'}.
</div>
)}
+109
View File
@@ -0,0 +1,109 @@
import { createPortal } from 'react-dom'
import { useEffect, useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { api } from '../api'
/**
* Settings → Konduktor: preferences about the app itself rather than about a
* library or a feature (those have their own entries in the gear menu). Each
* setting is a pref in userprefs.json, written as soon as it is changed.
*/
/** The prefs this dialog owns, and what each is when never set. */
export const APP_SETTING_DEFAULTS = {
expandPlaylistFolders: false,
/** Read by the backend when an export runs (`main.run_export`). */
exportRootFolder: false,
}
type AppSettingKey = keyof typeof APP_SETTING_DEFAULTS
/** One app setting, read from the shared ['prefs'] query (the default until it loads). */
export function useAppSetting<K extends AppSettingKey>(key: K): (typeof APP_SETTING_DEFAULTS)[K] {
const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs }).data
const v = prefs?.[key]
return typeof v === typeof APP_SETTING_DEFAULTS[key] ? (v as (typeof APP_SETTING_DEFAULTS)[K]) : APP_SETTING_DEFAULTS[key]
}
export function AppSettings({ onClose }: { onClose: () => void }) {
const qc = useQueryClient()
const expandFolders = useAppSetting('expandPlaylistFolders')
const exportRootFolder = useAppSetting('exportRootFolder')
const [error, setError] = useState<string | null>(null)
useEffect(() => {
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [onClose])
const set = async (patch: Partial<typeof APP_SETTING_DEFAULTS>) => {
setError(null)
try {
qc.setQueryData(['prefs'], await api.patchPrefs(patch))
} catch (e) {
setError((e as Error).message)
}
}
return createPortal(
<div
aria-modal="true"
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-6 backdrop-blur-[3px]"
onClick={onClose}
>
<div className="flex w-full max-w-md flex-col overflow-hidden glass-overlay" onClick={(e) => e.stopPropagation()}>
<div className="flex items-center justify-between border-b border-line px-5 py-3">
<h2 className="text-sm font-semibold text-text">Konduktor settings</h2>
<button onClick={onClose} className="rounded px-1.5 text-faint hover:text-text" aria-label="Close">
×
</button>
</div>
<div className="space-y-4 px-5 py-4 text-sm">
<section className="space-y-2">
<h3 className="text-[11px] font-semibold uppercase tracking-wider text-faint">Sidebar</h3>
<label className="flex cursor-pointer items-start gap-2.5">
<input
type="checkbox"
className="mt-0.5"
checked={expandFolders}
onChange={(e) => void set({ expandPlaylistFolders: e.target.checked })}
/>
<span className="min-w-0">
<span className="block text-sm text-text">Expand playlist folders by default</span>
<span className="block text-xs text-faint">
Show every folder open when a library is opened. Off, they start collapsed.
</span>
</span>
</label>
</section>
<section className="space-y-2">
<h3 className="text-[11px] font-semibold uppercase tracking-wider text-faint">Exports</h3>
<label className="flex cursor-pointer items-start gap-2.5">
<input
type="checkbox"
className="mt-0.5"
checked={exportRootFolder}
onChange={(e) => void set({ exportRootFolder: e.target.checked })}
/>
<span className="min-w-0">
<span className="block text-sm text-text">Put exported playlists in a folder</span>
<span className="block text-xs text-faint">
Nest an export's playlists in one folder named after the export. Off, they sit at the
top level of the exported library. Applies from the next export.
</span>
</span>
</label>
</section>
{error && <div className="text-xs text-pink">{error}</div>}
</div>
<div className="flex justify-end gap-2 border-t border-line px-5 py-3">
<button onClick={onClose} className="rounded-full btn-primary px-4 py-1.5 text-sm font-semibold">
Done
</button>
</div>
</div>
</div>,
document.body,
)
}
+17 -1
View File
@@ -10,6 +10,10 @@ export interface ConfirmRequest {
/** `danger` (default) for destructive actions — a pink button; `primary`
* for a caution that is not destruction, e.g. switching library. */
tone?: 'danger' | 'primary'
/** A second way to go ahead, as a plain button beside the confirm one
* (e.g. "Add them again" next to "Add 6 new"). Enter still means confirm. */
altLabel?: string
onAlt?: () => void
onConfirm: () => Promise<void> | void
}
@@ -19,7 +23,7 @@ interface Props extends ConfirmRequest {
/** A yes/no confirmation for destructive actions. Enter confirms and Esc
* cancels, so a confirmed Delete key stays a two-keystroke action. */
export function ConfirmDialog({ title, body, confirmLabel, tone = 'danger', onConfirm, onClose }: Props) {
export function ConfirmDialog({ title, body, confirmLabel, tone = 'danger', altLabel, onAlt, onConfirm, onClose }: Props) {
const [busy, setBusy] = useState(false)
const confirm = async () => {
@@ -69,6 +73,18 @@ export function ConfirmDialog({ title, body, confirmLabel, tone = 'danger', onCo
>
Cancel
</button>
{altLabel && onAlt && (
<button
onClick={() => {
onAlt()
onClose()
}}
disabled={busy}
className="btn-glass rounded-full px-4 py-1.5 text-sm text-text disabled:opacity-40"
>
{altLabel}
</button>
)}
<button
onClick={() => void confirm()}
disabled={busy}
+13 -5
View File
@@ -1,13 +1,14 @@
import { useEffect, useState, type ReactNode } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api, type Drive, type PlaylistNode } from '../api'
import { api, isServerPath, type Drive, type PlaylistNode } from '../api'
import type { Source } from './Sidebar'
import { Icon } from '../lib/icons'
import { ContextMenu, type MenuItem } from './ContextMenu'
/**
* Every drive, in the sidebar: plugged-in ones under Devices, and the computer's
* own under an expandable Local Storage.
* own under an expandable Local Storage. While a remote library is open, the
* server holding it comes first: its content folder, browsed like any drive.
*
* A drive carrying a OneLibrary library opens as a device, the way rekordbox and
* Traktor show a stick: its playlists appear under it and the ordinary track
@@ -86,13 +87,15 @@ export function DevicesSection({ source, onSelect, onError, onImport, onOpenLibr
})
const list = drives.data ?? []
const server = list.filter((d) => d.kind === 'server')
const external = list.filter((d) => d.kind === 'external')
const local = list.filter((d) => d.kind === 'local')
// A drive can be physically unplugged while it is open. Nothing crashes — the
// routes just start failing — but leaving it selected would show a library
// that is not there, so fall back to the collection. The same goes for a
// folder on it being browsed.
// folder on it being browsed — and for a folder on the server, the remote
// library being closed.
const stillPresent = !openPath || list.some((d) => d.library?.path === openPath)
useEffect(() => {
if (!drives.isSuccess || !openPath || stillPresent || eject.isPending) return
@@ -102,7 +105,11 @@ export function DevicesSection({ source, onSelect, onError, onImport, onOpenLibr
const folderGone =
source.kind === 'folder' &&
drives.isSuccess &&
!list.some((d) => d.path === '/' || isInside(source.path, d.path))
!list.some((d) =>
isServerPath(source.path)
? d.kind === 'server'
: d.path === '/' || isInside(source.path, d.path),
)
useEffect(() => {
if (folderGone) onSelect({ kind: 'all' })
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -137,7 +144,7 @@ export function DevicesSection({ source, onSelect, onError, onImport, onOpenLibr
<div key={d.path}>
<TreeRow
depth={depth}
icon={<span className="text-gold"><Icon name="drive" size={15} /></span>}
icon={<span className="text-gold"><Icon name={d.kind === 'server' ? 'server' : 'drive'} size={15} /></span>}
label={d.name}
title={d.path}
expanded={expandedHere}
@@ -212,6 +219,7 @@ export function DevicesSection({ source, onSelect, onError, onImport, onOpenLibr
</div>
<div className="mt-1 min-h-0 overflow-y-auto px-2 pb-1">
{server.map((d) => driveRow(d, 0))}
{external.map((d) => driveRow(d, 0))}
{local.length > 0 && (
+71 -2
View File
@@ -1,11 +1,15 @@
import { useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api, type ExportSet } from '../api'
import type { AddTarget, ForeignOrigin } from './AddFilesDialog'
import { useCaps } from '../lib/capabilities'
import { ExportDialog } from './ExportDialog'
import { ExportRunDialog } from './ExportRunDialog'
import type { Source } from './Sidebar'
import { askConfirm } from '../lib/confirm'
import { Icon } from '../lib/icons'
import { useDropTarget, type DragPayload } from '../lib/drag'
import { playlistIdsUnder } from '../lib/playlistTree'
/**
* Exports in the sidebar: each one a named, persisted slice of the library
@@ -27,9 +31,10 @@ interface Props {
onSelect: (s: Source) => void
onDone: (msg: string) => void
onError: (msg: string) => void
onAddForeign: (origin: ForeignOrigin, ids: string[], target: AddTarget) => void
}
export function ExportsSection({ source, onSelect, onDone, onError }: Props) {
export function ExportsSection({ source, onSelect, onDone, onError, onAddForeign }: Props) {
const qc = useQueryClient()
const [dialog, setDialog] = useState<{ editing: ExportSet | null } | null>(null)
const [running, setRunning] = useState<ExportSet | null>(null)
@@ -105,6 +110,8 @@ export function ExportsSection({ source, onSelect, onDone, onError }: Props) {
onSelect={onSelect}
onEdit={() => setDialog({ editing: set })}
onRun={() => setRunning(set)}
onDone={onDone}
onAddForeign={onAddForeign}
onDelete={async () => {
// Deleting a set never touches its destination folder — the files
// already exported are the user's, not Konduktor's to clean up.
@@ -132,7 +139,9 @@ function ExportRow({
onEdit,
onRun,
onDelete,
onDone,
onError,
onAddForeign,
}: {
set: ExportSet
source: Source
@@ -140,9 +149,14 @@ function ExportRow({
onEdit: () => void
onRun: () => void
onDelete: () => void
onDone: (msg: string) => void
onError: (msg: string) => void
onAddForeign: (origin: ForeignOrigin, ids: string[], target: AddTarget) => void
}) {
const qc = useQueryClient()
// The COLLECTION's capabilities (the sidebar sits outside the browsed view's
// swap): a device's or folder's tracks must be added to it first.
const caps = useCaps()
const selected = source.kind === 'export' && source.id === set.id
const inside =
selected ||
@@ -170,11 +184,66 @@ function ExportRow({
const data = contents.data
const expanded = open || inside
// A drop target for the collection's tracks (they become loose tracks) and
// for playlists or folders dragged from the tree (referenced, live, as
// "Add to export" does). Not gated on the library being writable: an export
// set is Konduktor's own data.
const refresh = () => {
qc.invalidateQueries({ queryKey: ['export-contents', set.id] })
qc.invalidateQueries({ queryKey: ['export-tracks', set.id] })
qc.invalidateQueries({ queryKey: ['export-loose', set.id] })
}
const accepts = (p: DragPayload) =>
p.kind === 'tracks'
? p.origin === 'collection' || (caps.writable && caps.tracks.addable)
: p.kind === 'files'
? caps.writable && caps.tracks.addable
: playlistIdsUnder(p.node).length > 0
const [dropRef, over] = useDropTarget<true>({
hint: (p) => (accepts(p) ? true : null),
label: (p) =>
p.kind === 'tracks' && p.origin === 'device'
? `Import into export ${set.name}…`
: `Add to export ${set.name}${(p.kind === 'tracks' && p.origin === 'folder') || p.kind === 'files' ? '…' : ''}`,
onDrop: async (p) => {
if (p.kind === 'files') {
onAddForeign('dropped', p.paths, { kind: 'export', id: set.id, name: set.name })
return
}
if (p.kind === 'tracks' && p.origin !== 'collection') {
onAddForeign(p.origin, p.ids, { kind: 'export', id: set.id, name: set.name })
return
}
try {
if (p.kind === 'tracks') {
await api.addToExport(set.id, { track_ids: p.ids })
onDone(`Added ${p.ids.length} track${p.ids.length === 1 ? '' : 's'} to ${set.name}`)
} else {
const ids = playlistIdsUnder(p.node)
await api.addToExport(set.id, { playlist_ids: ids })
onDone(
p.node.kind === 'folder'
? `Added ${ids.length} playlist${ids.length === 1 ? '' : 's'} from “${p.node.name}” to ${set.name}`
: `Added “${p.node.name}” to ${set.name}`,
)
}
refresh()
} catch (e) {
onError((e as Error).message)
}
},
})
return (
<div>
<div
ref={dropRef}
className={`group flex w-full items-center gap-1 rounded-md pr-1 transition-colors ${
selected ? 'is-selected text-text' : 'text-muted hover:bg-ink-800 hover:text-text'
over
? 'bg-gold/10 text-text ring-1 ring-gold'
: selected
? 'is-selected text-text'
: 'text-muted hover:bg-ink-800 hover:text-text'
}`}
>
<button
+34 -11
View File
@@ -4,6 +4,7 @@ import { useQuery, useQueryClient } from '@tanstack/react-query'
import { api, type ImportPreview, type JobStatus } from '../api'
import { useCaps } from '../lib/capabilities'
import { placedAudioSummary } from '../lib/platformCopy'
import type { AddTarget } from './AddFilesDialog'
import { FolderPicker } from './FolderPicker'
import { useServerImportFolder } from './AddFilesDialog'
@@ -29,13 +30,18 @@ function gb(bytes: number): string {
interface Props {
/** Playlist to import, or null for the whole device. */
playlistId: string | null
/** Instead: just these device tracks (dragged out of the device's view). */
trackIds?: string[]
/** Where they go once imported — the playlist or export they were dropped
* on. They are in the collection first either way. */
target?: AddTarget | null
deviceLabel: string
onClose: () => void
onDone: (msg: string) => void
onError: (msg: string) => void
}
export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError }: Props) {
export function ImportDialog({ playlistId, trackIds, target, deviceLabel, onClose, onDone, onError }: Props) {
const qc = useQueryClient()
// The BASE folder, and whether to put this device's audio in its own
// subfolder of it. Kept apart rather than as one path because they are two
@@ -81,13 +87,15 @@ export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError
const body = {
destination,
playlist_ids: playlistId ? [playlistId] : [],
track_ids: [],
playlist_ids: trackIds ? [] : playlistId ? [playlistId] : [],
track_ids: trackIds ?? [],
folder_name: deviceLabel,
into_playlist: target?.kind === 'playlist' ? target.id : null,
export_id: target?.kind === 'export' ? target.id : null,
}
const preview = useQuery<ImportPreview>({
queryKey: ['import-preview', destination, playlistId],
queryKey: ['import-preview', destination, playlistId, trackIds?.join('\n'), target?.id],
queryFn: () => api.importPreview(body),
enabled: !!destination && !job,
staleTime: 0,
@@ -113,9 +121,16 @@ export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError
qc.invalidateQueries({ queryKey: ['collection'] })
qc.invalidateQueries({ queryKey: ['state'] })
qc.invalidateQueries({ queryKey: ['facets'] })
if (target) {
qc.invalidateQueries({ queryKey: ['playlist', target.id] })
qc.invalidateQueries({ queryKey: ['export-contents', target.id] })
qc.invalidateQueries({ queryKey: ['export-tracks', target.id] })
qc.invalidateQueries({ queryKey: ['export-loose', target.id] })
}
onDone(
`Imported ${r?.tracks ?? 0} track${r?.tracks === 1 ? '' : 's'}` +
(r?.playlists ? ` and ${r.playlists} playlist${r.playlists === 1 ? '' : 's'}` : ''),
(r?.playlists ? ` and ${r.playlists} playlist${r.playlists === 1 ? '' : 's'}` : '') +
(target ? ` into ${target.name}` : ''),
)
} else if (next.state === 'failed') {
onError(next.error || 'Import failed')
@@ -129,7 +144,7 @@ export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError
return () => {
if (pollRef.current) window.clearInterval(pollRef.current)
}
}, [job, qc, onDone, onError])
}, [job, qc, onDone, onError, target])
const start = async () => {
setStarting(true)
@@ -174,9 +189,15 @@ export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError
<div className="w-full max-w-lg glass-overlay">
<div className="border-b border-line px-5 py-3">
<h2 className="text-sm font-semibold text-text">
Import from {deviceLabel}
{playlistId ? '' : ' — everything'}
{trackIds
? `Import ${trackIds.length} track${trackIds.length === 1 ? '' : 's'} from ${deviceLabel}`
: `Import from ${deviceLabel}${playlistId ? '' : ' — everything'}`}
</h2>
{target && (
<p className="mt-0.5 text-xs text-muted">
Into your collection, then into {target.kind === 'export' ? 'the export ' : ''}“{target.name}”.
</p>
)}
</div>
<div className="space-y-4 px-5 py-4 text-sm">
@@ -270,9 +291,11 @@ export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError
</div>
)}
<div className="text-xs text-faint">
Playlists land in a folder called “{deviceLabel}”.
</div>
{p.playlists.length > 0 && (
<div className="text-xs text-faint">
Playlists land in a folder called “{deviceLabel}”.
</div>
)}
</div>
)}
</>
@@ -0,0 +1,106 @@
import { createPortal } from 'react-dom'
import { useEffect, useRef, useState } from 'react'
import { maxPosition, moveToPosition } from '../lib/playlistOrder'
interface Props {
/** The playlist's full entry order — never the sorted or filtered view, so
* the move is safe whatever the table is showing. */
order: string[]
/** The tracks to move; they keep their playlist order as one block. */
ids: string[]
onMove: (order: string[]) => void
onClose: () => void
}
/** "Set Position…": type where the first selected track should end up. */
export function SetPositionDialog({ order, ids, onMove, onClose }: Props) {
const moving = new Set(ids)
const count = order.filter((id) => moving.has(id)).length
const max = maxPosition(order, moving)
const current = order.findIndex((id) => moving.has(id)) + 1
const [value, setValue] = useState(String(current))
const input = useRef<HTMLInputElement>(null)
useEffect(() => input.current?.select(), [])
const typed = Number.parseInt(value, 10)
const position = Number.isFinite(typed) ? Math.min(Math.max(typed, 1), max) : null
const submit = () => {
if (position === null) return
const next = moveToPosition(order, moving, position)
if (next.some((id, i) => id !== order[i])) onMove(next)
onClose()
}
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose()
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [onClose])
const span = (p: number) => (count > 1 ? `#${p}–${p + count - 1}` : `#${p}`)
return createPortal(
<div
aria-modal="true"
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6"
onClick={onClose}
>
<form
className="w-full max-w-sm overflow-hidden glass-overlay"
onClick={(e) => e.stopPropagation()}
onSubmit={(e) => {
e.preventDefault()
submit()
}}
>
<div className="border-b border-line px-5 py-4 text-[15px] font-semibold tracking-tight">
Set position
</div>
<div className="space-y-3 px-5 py-4 text-sm text-muted">
<label className="flex items-center gap-2">
<span>{count > 1 ? `Move ${count} tracks to position` : 'Move to position'}</span>
<input
ref={input}
type="number"
inputMode="numeric"
min={1}
max={max}
value={value}
onChange={(e) => setValue(e.target.value)}
className="w-20 rounded-lg well px-2.5 py-1.5 text-sm tabular-nums text-text outline-none focus:ring-1 focus:ring-accent"
/>
<span>of {max}</span>
</label>
<div className="tabular-nums">
{position === null
? 'Type a position.'
: count > 1
? `Will occupy ${span(position)}`
: `Now ${span(current)} · will be ${span(position)}`}
</div>
</div>
<div className="flex items-center justify-end gap-2 border-t border-line px-5 py-3">
<button
type="button"
onClick={onClose}
className="btn-glass rounded-full px-4 py-1.5 text-sm text-muted hover:text-text"
>
Cancel
</button>
<button
type="submit"
disabled={position === null}
className="btn-primary rounded-full px-4 py-1.5 text-sm font-semibold disabled:opacity-50"
>
Move
</button>
</div>
</form>
</div>,
document.body,
)
}
+16 -3
View File
@@ -1,6 +1,7 @@
import { useEffect, useRef, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { api } from '../api'
import { AppSettings } from './AppSettings'
import { useCaps } from '../lib/capabilities'
import { RemoteCacheSettings } from './RemoteCacheSettings'
import { ShortcutsDialog } from './ShortcutsDialog'
@@ -12,14 +13,15 @@ interface Props {
up?: boolean
}
/** Overflow menu for low-frequency, collection-level settings. Currently holds
* path remapping, Stems and the shortcut list; the natural home for future advanced
* settings. The shortcuts dialog is owned here, since nothing else opens it. */
/** Overflow menu for low-frequency settings: the app's own (Konduktor
* settings), path remapping, Stems and the shortcut list. The dialogs are owned
* here, since nothing else opens them. */
export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
const [open, setOpen] = useState(false)
const [showShortcuts, setShowShortcuts] = useState(false)
const [showStems, setShowStems] = useState(false)
const [showCache, setShowCache] = useState(false)
const [showApp, setShowApp] = useState(false)
const ref = useRef<HTMLDivElement>(null)
// Path remapping is a library on THIS computer's business; a remote's
// mapping is its server's configuration.
@@ -66,6 +68,16 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
up ? 'bottom-full mb-1' : 'mt-1'
}`}
>
<button
onClick={() => {
setShowApp(true)
setOpen(false)
}}
className={item}
>
<span className="text-sm text-text">Konduktor Settings…</span>
<span className="text-[11px] text-faint">How the app behaves, whatever library is open</span>
</button>
{remappable && (
<button
onClick={() => {
@@ -117,6 +129,7 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
{showShortcuts && <ShortcutsDialog onClose={() => setShowShortcuts(false)} />}
{showStems && <StemsSettings onClose={() => setShowStems(false)} />}
{showCache && <RemoteCacheSettings onClose={() => setShowCache(false)} />}
{showApp && <AppSettings onClose={() => setShowApp(false)} />}
</div>
)
}
+7 -1
View File
@@ -58,11 +58,17 @@ function sections(slots: number): Section[] {
{ keys: [[MOD, 'Click']], action: 'Add to / remove from the selection' },
{ keys: [['Double-click']], action: 'Edit a cell' },
{ keys: [['Right-click']], action: 'Track menu (header: choose columns)' },
{ keys: [['Drag rows']], action: 'Onto a playlist or export to add, onto the deck to load, within a playlist to reorder' },
{ keys: [[ALT_KEY, 'Drag']], action: 'Move tracks to another playlist (out of this one)' },
{ keys: [['Esc']], action: 'While dragging: cancel the drag' },
],
},
{
title: 'Sidebar',
rows: [{ keys: [['Right-click']], action: 'New playlist or folder, rename, delete' }],
rows: [
{ keys: [['Right-click']], action: 'New playlist or folder, rename, delete' },
{ keys: [['Drag']], action: 'Rearrange playlists and folders; onto an export to add one' },
],
},
{
title: 'Fields & dialogs',
+250 -19
View File
@@ -1,16 +1,21 @@
import { useRef, useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api, type PlaylistKind, type PlaylistNode } from '../api'
import type { AddTarget, ForeignOrigin } from './AddFilesDialog'
import { useCaps } from '../lib/capabilities'
import { SaveBar } from './SaveBar'
import { confirmDiscardUnsaved } from '../lib/unsaved'
import { SettingsMenu } from './SettingsMenu'
import { useAppSetting } from './AppSettings'
import { DevicesSection } from './DevicesSection'
import { ExportsSection } from './ExportsSection'
import { ConfirmDialog, type ConfirmRequest } from './ConfirmDialog'
import { ContextMenu, type MenuItem } from './ContextMenu'
import { Icon, type IconName } from '../lib/icons'
import { PlatformIcon } from '../lib/platformIcons'
import { addTracksToPlaylist } from '../lib/addTracks'
import { useDragPayload, usePressToDrag, useDropTarget, type DragPayload, type TracksOrFiles } from '../lib/drag'
import { findNode, idsAfter, nodeIdsUnder, playlistIdsUnder } from '../lib/playlistTree'
/**
* Which view the main table is showing.
@@ -50,6 +55,10 @@ interface Props {
/** Open a drive's library as THE library (Devices' "Open for editing…"). */
onOpenLibrary: (path: string) => void
onDone: (msg: string) => void
/** Tracks not in the collection yet (a device's, a folder's — or files
* dropped from the OS, as paths) dropped on a playlist or export: open the
* dialog that adds them, target filled in. */
onAddForeign: (origin: ForeignOrigin, ids: string[], target: AddTarget) => void
onOpenPathMapping: () => void
/** After unsaved edits were discarded (SaveBar). */
onDiscarded?: () => void
@@ -57,11 +66,6 @@ interface Props {
// Kind picks the icon; every behavioural question is answered by the node's own
// flags, so nothing here infers what a node can do from what it is called.
/** Every selectable playlist at or under a node, in tree order. */
function playlistIdsUnder(node: PlaylistNode): string[] {
const here = node.kind === 'folder' ? [] : [node.id]
return [...here, ...(node.children ?? []).flatMap(playlistIdsUnder)]
}
/** The confirm wording for deleting a node. A folder says what goes with it,
* since the whole subtree is deleted and the row only shows the folder. */
@@ -97,16 +101,38 @@ type Draft = { kind: 'playlist' | 'folder'; parentId: string | null }
/** Actions a row can ask of the sidebar. They live there, not in the row, so
* the right-click menu and the hover buttons run the very same code. */
interface RowActions {
/** Whether a folder is open, and opening / closing it. */
isOpen: (node: PlaylistNode) => boolean
setOpen: (node: PlaylistNode, open: boolean) => void
onContextMenu: (e: React.MouseEvent, node: PlaylistNode) => void
onRename: (node: PlaylistNode, name: string) => void
onRename: (node: PlaylistNode, name: string, parentId: string | null) => void
onDelete: (node: PlaylistNode) => void
onAddToExport: (node: PlaylistNode, setId: string) => void
/** The row's export button: the export list as a menu under it. */
onPickExport: (e: React.MouseEvent<HTMLElement>, node: PlaylistNode) => void
onCommitDraft: (name: string) => void
onCancelDraft: () => void
/** Whether a drag of tracks (or of files from the OS) may drop on this playlist. */
acceptsTracks: (node: PlaylistNode, p: TracksOrFiles) => boolean
/** Tracks dropped on a playlist; `alt` (Option) moves them out of the
* playlist they came from. */
onDropTracks: (node: PlaylistNode, p: TracksOrFiles, alt: boolean) => void
/** Whether a node may be dragged elsewhere in the tree. */
canMove: (node: PlaylistNode) => boolean
/** A node dropped in the tree: `index` among `parentId`'s children,
* counted without it (what `move_playlist` takes). */
onMoveNode: (node: PlaylistNode, parentId: string | null, index: number, into: PlaylistNode | null) => void
}
/** Where a dragged node would land, relative to the row under the pointer:
* `before`/`after` it, `into` it (a folder; appended), or `first` inside it —
* the lower edge of an EXPANDED folder, where the line sits above its first
* child. `tracks` is a track drop on a playlist; `peek` is tracks held over a
* collapsed folder, which opens it and drops nothing. */
type RowHint =
| { zone: 'tracks' | 'peek' }
| { zone: 'before' | 'after' | 'into' | 'first'; parentId: string | null; index: number }
/** The inline name field for a node being created. Enter or clicking away
* commits a non-empty name; Esc (or an empty name) creates nothing. */
function DraftRow({
@@ -156,6 +182,8 @@ function DraftRow({
function NodeRow({
node,
parentId,
siblings,
depth,
source,
onSelect,
@@ -166,6 +194,10 @@ function NodeRow({
actions,
}: {
node: PlaylistNode
/** The folder this node sits in; null = the top level. */
parentId: string | null
/** That folder's children, this node included, in order. */
siblings: PlaylistNode[]
depth: number
source: Source
onSelect: (s: Source) => void
@@ -175,7 +207,7 @@ function NodeRow({
exportSets: { id: string; name: string }[]
actions: RowActions
}) {
const [open, setOpen] = useState(true)
const open = actions.isOpen(node)
const renaming = renamingId === node.id
const [renameDraft, setRenameDraft] = useState(node.name)
const isFolder = node.kind === 'folder'
@@ -191,17 +223,105 @@ function NodeRow({
setRenamingId(node.id)
}
// A row is a drag SOURCE (onto an export, or elsewhere in the tree) and a
// drop TARGET for tracks. Whether it takes them is the node's own
// `can_add_tracks` plus the library being writable, decided by the sidebar.
const startDrag = usePressToDrag(() => (renaming ? null : { kind: 'node', node, parentId }))
const moves = (p: DragPayload, alt: boolean) =>
p.kind === 'tracks' && alt && !!p.fromPlaylist && p.fromPlaylist !== node.id
// A node held over this row: which zone, and where that puts it. Never into
// itself or anything nested in it; a drop that would leave it exactly where
// it is shows nothing.
const placeNode = (p: Extract<DragPayload, { kind: 'node' }>, y: number, el: HTMLElement): RowHint | null => {
if (!actions.canMove(p.node) || nodeIdsUnder(p.node).has(node.id)) return null
const r = el.getBoundingClientRect()
const f = (y - r.top) / r.height
const opened = expanded && node.children.length > 0
const zone: 'before' | 'after' | 'into' | 'first' = node.can_contain_children
? f < 0.25 ? 'before' : f > 0.75 ? (opened ? 'first' : 'after') : 'into'
: f < 0.5 ? 'before' : 'after'
let target: string | null
let index: number
let current: PlaylistNode[]
if (zone === 'into' || zone === 'first') {
target = node.id
current = node.children
index = zone === 'first' ? 0 : node.children.filter((c) => c.id !== p.node.id).length
} else {
target = parentId
current = siblings
const i = siblings.filter((c) => c.id !== p.node.id).findIndex((c) => c.id === node.id)
index = zone === 'before' ? i : i + 1
}
if (target === p.parentId && current.findIndex((c) => c.id === p.node.id) === index) return null
return { zone, parentId: target, index }
}
const [dropRef, over] = useDropTarget<RowHint>({
hint: (p, at, el) => {
if (p.kind === 'node') return placeNode(p, at.y, el)
if (actions.acceptsTracks(node, p)) return { zone: 'tracks' }
return isFolder && !expanded ? { zone: 'peek' } : null
},
label: (p, h, at) => {
if (h.zone === 'tracks') {
if (p.kind === 'tracks' && p.origin === 'device') return `Import into ${node.name}…`
if ((p.kind === 'tracks' && p.origin === 'folder') || p.kind === 'files') return `Add to ${node.name}…`
return `${moves(p, at.alt) ? 'Move' : 'Add'} to ${node.name}`
}
if (h.zone === 'peek') return null
return h.zone === 'into' || h.zone === 'first' ? `Move into ${node.name}` : `Move ${h.zone} ${node.name}`
},
onDrop: (p, h, at) => {
if (p.kind !== 'node') {
if (h.zone === 'tracks') actions.onDropTracks(node, p, at.alt)
} else if ('parentId' in h) {
actions.onMoveNode(p.node, h.parentId, h.index, h.zone === 'into' && !expanded ? node : null)
}
},
})
// Holding a drag over a collapsed folder opens it, so a playlist nested in
// it can be reached without letting go.
const opening = over?.zone === 'into' || over?.zone === 'peek'
const openLater = useRef(() => actions.setOpen(node, true))
openLater.current = () => actions.setOpen(node, true)
useEffect(() => {
if (!opening || expanded) return
const t = setTimeout(() => openLater.current(), 600)
return () => clearTimeout(t)
}, [opening, expanded])
const ringed = over?.zone === 'tracks' || over?.zone === 'into'
const dragging = useDragPayload()
const beingMoved = dragging?.kind === 'node' && dragging.node.id === node.id
const line = over?.zone === 'before' || over?.zone === 'after' || over?.zone === 'first' ? over.zone : null
return (
<div>
<div className={beingMoved ? 'opacity-40' : undefined}>
<div
ref={dropRef}
data-node-row
onPointerDown={startDrag}
onContextMenu={(e) => actions.onContextMenu(e, node)}
className={`group flex items-center gap-1 rounded-[10px] pr-1 text-sm transition-colors ${
selected ? 'is-selected font-medium text-text' : 'text-muted hover:bg-ink-800 hover:text-text'
className={`group relative flex items-center gap-1 rounded-[10px] pr-1 text-sm transition-colors ${
ringed
? 'bg-accent-soft/40 text-text ring-1 ring-accent'
: selected
? 'is-selected font-medium text-text'
: 'text-muted hover:bg-ink-800 hover:text-text'
}`}
>
{line && (
<span
aria-hidden
className={`pointer-events-none absolute right-1 h-0.5 rounded-full bg-accent ${
line === 'before' ? '-top-px' : '-bottom-px'
}`}
style={{ left: 8 + (line === 'first' ? depth + 1 : depth) * 14 }}
/>
)}
<button
onClick={() => {
if (isFolder) setOpen((o) => !o)
if (isFolder) actions.setOpen(node, !open)
else if (selectable) onSelect({ kind: 'playlist', id: node.id, name: node.name })
}}
className={`flex min-w-0 flex-1 items-center gap-2 py-1.5 pl-2 text-left ${
@@ -235,7 +355,7 @@ function NodeRow({
if (e.key === 'Enter') {
setRenamingId(null)
if (renameDraft.trim() && renameDraft.trim() !== node.name)
actions.onRename(node, renameDraft.trim())
actions.onRename(node, renameDraft.trim(), parentId)
} else if (e.key === 'Escape') {
setRenamingId(null)
}
@@ -298,6 +418,8 @@ function NodeRow({
<NodeRow
key={c.id}
node={c}
parentId={node.id}
siblings={node.children}
depth={depth + 1}
source={source}
onSelect={onSelect}
@@ -323,6 +445,7 @@ export function Sidebar({
onSwitchLibrary,
onOpenLibrary,
onDone,
onAddForeign,
onOpenPathMapping,
onDiscarded,
}: Props) {
@@ -339,8 +462,9 @@ export function Sidebar({
}
// There is no per-node flag for "you may create a NEW playlist" — the node
// flags describe existing nodes — so this is the library-level gate.
const canCreate = useCaps().writable
const foldersSupported = useCaps().playlists.folders
const caps = useCaps()
const canCreate = caps.writable
const foldersSupported = caps.playlists.folders
const { data: playlists, isLoading } = useQuery({
queryKey: ['playlists'],
queryFn: api.playlists,
@@ -352,6 +476,32 @@ export function Sidebar({
const [menu, setMenu] = useState<{ x: number; y: number; items: MenuItem[] } | null>(null)
const [confirmReq, setConfirmReq] = useState<ConfirmRequest | null>(null)
// Which folders are open: the setting, except where the user has opened or
// closed one. Held here rather than in each row, so it survives a row
// remounting and can be reset — on a new library, and when the setting
// changes (so changing it visibly does something).
const expandByDefault = useAppSetting('expandPlaylistFolders')
const [openOverrides, setOpenOverrides] = useState<Record<string, boolean>>({})
useEffect(() => setOpenOverrides({}), [library?.path, expandByDefault])
const setFolderOpen = (id: string, open: boolean) =>
setOpenOverrides((o) => ({ ...o, [id]: open }))
// A folder's id — and so every id under it — may change when it is renamed
// or moved (a platform addressing folders by path), so open state follows
// the subtree to its new ids. Reads the tree as refetched after the edit.
const carryOpen = async (before: PlaylistNode, newId: string) => {
if (before.kind !== 'folder') return
await qc.refetchQueries({ queryKey: ['playlists'] })
const after = findNode(qc.getQueryData<PlaylistNode[]>(['playlists']) ?? [], newId)
if (!after) return
const ids = idsAfter(before, after)
setOpenOverrides((o) => {
const next = { ...o }
for (const [from, to] of ids) if (from !== to && from in o) delete next[from]
for (const [from, to] of ids) if (from !== to && from in o) next[to] = o[from]
return next
})
}
const invalidate = () => {
qc.invalidateQueries({ queryKey: ['playlists'] })
qc.invalidateQueries({ queryKey: ['state'] })
@@ -370,10 +520,19 @@ export function Sidebar({
})
const rename = useMutation({
mutationFn: ({ node, name }: { node: PlaylistNode; name: string }) =>
mutationFn: ({ node, name }: { node: PlaylistNode; name: string; parentId: string | null }) =>
api.renamePlaylist(node.id, name),
onSuccess: (_d, { node, name }) => {
onSuccess: async (_d, { node, name, parentId }) => {
invalidate()
// The rename does not answer the new id, so the folder is found by its
// new name among its siblings (a folder may not share a sibling's name).
if (node.kind === 'folder') {
await qc.refetchQueries({ queryKey: ['playlists'] })
const tree = qc.getQueryData<PlaylistNode[]>(['playlists']) ?? []
const siblings = parentId === null ? tree : (findNode(tree, parentId)?.children ?? [])
const renamed = siblings.find((n) => n.kind === 'folder' && n.name === name)
if (renamed) await carryOpen(node, renamed.id)
}
if (source.kind === 'playlist' && source.id === node.id)
onSelect({ kind: 'playlist', id: node.id, name })
},
@@ -408,6 +567,9 @@ export function Sidebar({
const startDraft = (kind: Draft['kind'], parentId: string | null) => {
setRenamingId(null)
// Open the folder it goes in, or the new node would vanish into a
// collapsed folder once named.
if (parentId !== null) setFolderOpen(parentId, true)
setDraft({ kind, parentId })
}
@@ -469,8 +631,10 @@ export function Sidebar({
}
const actions: RowActions = {
isOpen: (node) => openOverrides[node.id] ?? expandByDefault,
setOpen: (node, open) => setFolderOpen(node.id, open),
onContextMenu: (e, node) => openMenu(e, nodeItems(node)),
onRename: (node, name) => rename.mutate({ node, name }),
onRename: (node, name, parentId) => rename.mutate({ node, name, parentId }),
onDelete: confirmDelete,
onAddToExport: (node, setId) => addToExport.mutate({ node, setId }),
// Opened as the shared ContextMenu rather than a popover inside the row: the
@@ -496,8 +660,64 @@ export function Sidebar({
setDraft(null)
},
onCancelDraft: () => setDraft(null),
// A device's or a folder's tracks are not in the collection yet, so they
// can only come if the collection can ADD tracks — via the add dialog.
acceptsTracks: (node, p) =>
caps.writable &&
node.can_add_tracks &&
(p.kind === 'tracks' && p.origin === 'collection' ? p.fromPlaylist !== node.id : caps.tracks.addable),
canMove: (node) => caps.writable && node.can_move,
onMoveNode: async (node, parentId, index, into) => {
try {
const { id } = await api.movePlaylist(node.id, parentId, index)
invalidate()
void carryOpen(node, id)
// Into a COLLAPSED folder the node vanishes from view, so say where.
if (into) onDone(`Moved “${node.name}” into ${into.name}`)
} catch (e) {
onError((e as Error).message)
}
},
onDropTracks: async (node, p, alt) => {
if (p.kind === 'files') {
onAddForeign('dropped', p.paths, { kind: 'playlist', id: node.id, name: node.name })
return
}
if (p.origin !== 'collection') {
onAddForeign(p.origin, p.ids, { kind: 'playlist', id: node.id, name: node.name })
return
}
try {
const msg = await addTracksToPlaylist({
qc,
playlist: node,
ids: p.ids,
duplicatesAllowed: caps.playlists.duplicates,
moveFrom: alt ? p.fromPlaylist : undefined,
})
if (msg) onDone(msg)
} catch (e) {
onError((e as Error).message)
}
},
}
// The empty space below the rows: a node dropped there goes to the END of
// the top level. Only the space itself — over a row that declined (a folder
// into its own subtree), nothing happens rather than this.
const roots = playlists ?? []
const [rootDropRef, rootOver] = useDropTarget<{ index: number }>({
hint: (p, at) => {
if (p.kind !== 'node' || !actions.canMove(p.node)) return null
if (document.elementFromPoint(at.x, at.y)?.closest('[data-node-row]')) return null
const index = roots.filter((n) => n.id !== p.node.id).length
if (p.parentId === null && roots.findIndex((n) => n.id === p.node.id) === index) return null
return { index }
},
label: () => 'Move to the top level',
onDrop: (p, h) => p.kind === 'node' && actions.onMoveNode(p.node, null, h.index, null),
})
return (
<aside className="glass flex h-full w-64 shrink-0 flex-col">
{/* Which library is open — and the way to open a different one. Until
@@ -563,6 +783,8 @@ export function Sidebar({
{/* Right-click here (below the rows) creates at the top level; rows
stop the event so they get their own menu. */}
<div
ref={rootDropRef}
data-drag-scroll=""
className="mt-1 min-h-24 flex-1 overflow-y-auto px-2 pb-4"
onContextMenu={(e) => openMenu(e, createItems(null))}
>
@@ -572,6 +794,8 @@ export function Sidebar({
<NodeRow
key={n.id}
node={n}
parentId={null}
siblings={playlists}
depth={0}
source={source}
onSelect={onSelect}
@@ -582,12 +806,19 @@ export function Sidebar({
actions={actions}
/>
))}
{rootOver && <div aria-hidden className="mx-2 mt-0.5 h-0.5 rounded-full bg-accent" />}
</div>
{menu && <ContextMenu {...menu} onClose={() => setMenu(null)} />}
{confirmReq && <ConfirmDialog {...confirmReq} onClose={() => setConfirmReq(null)} />}
<ExportsSection source={source} onSelect={onSelect} onDone={onDone} onError={onError} />
<ExportsSection
source={source}
onSelect={onSelect}
onDone={onDone}
onError={onError}
onAddForeign={onAddForeign}
/>
<DevicesSection
source={source}
+464
View File
@@ -0,0 +1,464 @@
import { useEffect, useRef, useState, type ReactNode } from 'react'
import { createPortal } from 'react-dom'
import { setApiBase } from '../api'
import { Icon } from '../lib/icons'
/**
* What the desktop window shows while the backend starts, and the gate that
* keeps the app from rendering before it can reach the backend.
*
* The shell (src-tauri/src/lib.rs) opens the window at once and starts the
* sidecar beside it; this asks `backend_status` and listens for
* `konduktor://backend`. A normal launch is about half a second. The first
* launch after an install or update can take much longer — macOS checks every
* native library in the sidecar once — so after `SLOW_MS` a note says why,
* and after `STUCK_MS` the user may quit or keep waiting. If the sidecar
* exits, its last output is shown with Try again (`backend_restart`).
*
* Until the backend is ready, nothing else is mounted: App, QuitGuard and
* UpdateCheck would all query an API with no address yet. So this answers
* the shell's quit request itself (there is nothing unsaved to ask about),
* and stops answering once ready, when QuitGuard takes over.
*
* In a plain browser (dev) there is no shell and Vite proxies /api, so the
* children render at once.
*/
type BackendStatus =
| { state: 'starting' }
| { state: 'ready'; url: string }
| { state: 'stopped'; code: number | null; signal: number | null; log: string[] }
/** When the "takes longer" note appears. */
const SLOW_MS = 6_000
/** When the user is offered Quit / Keep waiting (and again after each wait). */
const STUCK_MS = 90_000
/** The cross-fade into the app. */
const FADE_MS = 450
const IN_SHELL = typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window
export function StartupGate({ children }: { children: ReactNode }) {
const [status, setStatus] = useState<BackendStatus | null>(null)
const [ready, setReady] = useState(!IN_SHELL)
const [leaving, setLeaving] = useState(false)
const [gone, setGone] = useState(!IN_SHELL)
// The backend's status: asked once, then followed. An event that arrives
// before the answer is newer than it, so the answer is then dropped.
useEffect(() => {
if (!IN_SHELL) return
let unlisten: (() => void) | undefined
let cancelled = false
void (async () => {
const [{ listen }, { invoke }] = await Promise.all([
import('@tauri-apps/api/event'),
import('@tauri-apps/api/core'),
])
let heard = false
const off = await listen<BackendStatus>('konduktor://backend', (e) => {
heard = true
setStatus(e.payload)
})
if (cancelled) return off()
unlisten = off
const now = await invoke<BackendStatus>('backend_status')
if (!heard && !cancelled) setStatus(now)
})()
return () => {
cancelled = true
unlisten?.()
}
}, [])
// Ready: point the API at the sidecar, mount the app, fade this out over it.
// Once ready it stays ready — a later crash is not a startup problem.
useEffect(() => {
if (status?.state !== 'ready' || ready) return
setApiBase(status.url)
setReady(true)
setLeaving(true)
const t = window.setTimeout(() => setGone(true), FADE_MS)
return () => window.clearTimeout(t)
}, [status, ready])
// Before the app is mounted, a quit request is answered here: nothing can
// be unsaved yet. Stops at ready, so it never races QuitGuard.
useEffect(() => {
if (!IN_SHELL || ready) return
let unlisten: (() => void) | undefined
let cancelled = false
void (async () => {
const [{ listen }, { invoke }] = await Promise.all([
import('@tauri-apps/api/event'),
import('@tauri-apps/api/core'),
])
const off = await listen('konduktor://quit-requested', async () => {
await invoke('quit_ack')
await invoke('quit_now')
})
if (cancelled) off()
else unlisten = off
})()
return () => {
cancelled = true
unlisten?.()
}
}, [ready])
return (
<>
{ready && children}
{!gone && <StartupScreen status={status} leaving={leaving} />}
</>
)
}
async function shell(command: 'backend_restart' | 'quit_now') {
const { invoke } = await import('@tauri-apps/api/core')
await invoke(command)
}
function StartupScreen({ status, leaving }: { status: BackendStatus | null; leaving: boolean }) {
const stopped = status?.state === 'stopped' ? status : null
return createPortal(
<div
className="fixed inset-0 z-[90] flex items-center justify-center p-6 transition-opacity ease-out"
style={{ opacity: leaving ? 0 : 1, transitionDuration: `${FADE_MS}ms`, pointerEvents: leaving ? 'none' : undefined }}
>
{stopped ? <StoppedCard status={stopped} /> : <Starting />}
<div className="absolute inset-x-0 bottom-[22px] text-center font-mono text-[11px] tracking-[0.02em] text-faint">
v{__APP_VERSION__}
</div>
</div>,
document.body,
)
}
/** The OS doing the checking, for the slow-launch note. */
function osName(): string {
const ua = navigator.userAgent
if (ua.includes('Windows')) return 'Windows'
if (ua.includes('Mac')) return 'macOS'
return 'your system'
}
function Starting() {
// Timed from mount: Try again replaces the failure card with a fresh one,
// so each attempt gets its own clock.
const [startedAt] = useState(() => Date.now())
const [stuckAt, setStuckAt] = useState(STUCK_MS)
const [elapsed, setElapsed] = useState(0)
useEffect(() => {
const t = window.setInterval(() => setElapsed(Date.now() - startedAt), 250)
return () => window.clearInterval(t)
}, [startedAt])
const slow = elapsed >= SLOW_MS
const stuck = elapsed >= stuckAt
return (
<div className="flex flex-col items-center text-center">
<StartupMark />
<div className="mt-[22px] text-[26px] font-semibold tracking-[-0.02em]">Konduktor</div>
<div className="mt-1.5 min-h-[21px] text-sm text-muted" role="status" aria-live="polite">
{stuck ? 'Still starting…' : 'Starting…'}
</div>
<p
className="mt-[18px] max-w-[46ch] text-[13px] leading-[1.55] text-faint transition-[opacity,transform] duration-[600ms]"
style={{ opacity: slow ? 1 : 0, transform: slow ? 'none' : 'translateY(4px)' }}
aria-hidden={!slow}
>
The first launch after installing or updating takes longer while {osName()} checks the app. Later
launches start in a second or two.
</p>
<div
className="mt-4 flex justify-center gap-2 transition-opacity duration-[400ms]"
style={{ opacity: stuck ? 1 : 0, pointerEvents: stuck ? undefined : 'none' }}
aria-hidden={!stuck}
>
<button
tabIndex={stuck ? 0 : -1}
onClick={() => void shell('quit_now')}
className="btn-glass rounded-full px-4 py-2 text-sm text-muted hover:text-text"
>
Quit
</button>
<button
tabIndex={stuck ? 0 : -1}
onClick={() => setStuckAt(elapsed + STUCK_MS)}
className="btn-glass rounded-full px-4 py-2 text-sm text-muted hover:text-text"
>
Keep waiting
</button>
</div>
</div>
)
}
function StoppedCard({ status }: { status: Extract<BackendStatus, { state: 'stopped' }> }) {
const [busy, setBusy] = useState(false)
const [copied, setCopied] = useState(false)
const logRef = useRef<HTMLPreElement>(null)
const summary =
status.code !== null
? `The library service exited with code ${status.code}.`
: status.signal !== null
? `The library service was stopped by signal ${status.signal}.`
: null
const lines = status.log.length ? status.log : ['It wrote nothing before stopping.']
const details = [`Konduktor v${__APP_VERSION__}`, ...(summary ? [summary] : []), ...lines].join('\n')
// Show the end of the output: that is where the error is.
useEffect(() => {
const el = logRef.current
if (el) el.scrollTop = el.scrollHeight
}, [status])
const copy = async () => {
try {
await navigator.clipboard.writeText(details)
setCopied(true)
window.setTimeout(() => setCopied(false), 2000)
} catch {
// No clipboard access: select the text so Cmd/Ctrl+C works.
const el = logRef.current
if (!el) return
const range = document.createRange()
range.selectNodeContents(el)
window.getSelection()?.removeAllRanges()
window.getSelection()?.addRange(range)
}
}
const retry = async () => {
setBusy(true)
try {
await shell('backend_restart')
} finally {
setBusy(false)
}
}
return (
<div
role="alertdialog"
aria-modal="true"
aria-labelledby="startup-failed-title"
className="glass-overlay w-full max-w-[560px] overflow-hidden"
>
<div className="flex items-start gap-3.5 px-6 pb-4 pt-[22px]">
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-pink/10 text-pink shadow-[inset_0_0_0_1px_rgb(255_122_154/0.35)]">
<Icon name="warning" size={18} />
</span>
<div className="min-w-0">
<h2 id="startup-failed-title" className="text-base font-semibold tracking-[-0.01em]">
Konduktor couldn't start
</h2>
<p className="mt-1 text-[13px] leading-[1.55] text-muted">
Its library service stopped before it was ready. Nothing in your libraries was changed. Try again, and
if it keeps happening, send the details below with your report.
</p>
</div>
</div>
<pre
ref={logRef}
className="well mx-6 max-h-[180px] select-text overflow-auto rounded-xl px-3.5 py-3 font-mono text-[11.5px] leading-[1.6] text-muted"
>
{summary && <div>{summary}</div>}
{lines.map((line, i) => (
<div key={i} className={i === lines.length - 1 ? 'text-pink' : undefined}>
{line || ' '}
</div>
))}
</pre>
<div className="flex items-center gap-2 px-6 pb-5 pt-4">
<button onClick={() => void copy()} className="rounded-full px-2.5 py-2 text-sm text-faint hover:text-text">
{copied ? 'Copied' : 'Copy details'}
</button>
<div className="flex-1" />
<button
onClick={() => void shell('quit_now')}
className="btn-glass rounded-full px-4 py-2 text-sm text-muted hover:text-text"
>
Quit
</button>
<button
autoFocus
disabled={busy}
onClick={() => void retry()}
className="btn-primary rounded-full px-4 py-2 text-sm font-semibold disabled:opacity-50"
>
Try again
</button>
</div>
</div>
)
}
// ---- The mark: the app icon, with a track scrolling under a fixed playhead ----
const BEAT = 60 / 128
/** CSS px per second of audio, at the mark's 104 px. */
const SPEED = 46
/** 2 px bars with a 1 px gap: the main waveform's rhythm. */
const BAR = 2
const SLOT = 3
/** The icon's own four bands, back to front. */
const BANDS = ['#ff6a3d', '#8f6bff', '#3f9dff', '#7fe6ff']
const jitter = (i: number) => {
const x = Math.sin(i * 12.9898) * 43758.5453
return x - Math.floor(x)
}
/** Band levels (0..1) of a generated house track at time t: a kick on every
* beat, offbeat bass and hats, a clap on 2 and 4, a fill every 16 beats. */
function levels(t: number) {
const n = Math.floor(t / BEAT)
const pos = t - n * BEAT
const in16 = n % 16
const fill = in16 >= 14
const sixteenth = BEAT / 4
const p16 = t % sixteenth
const kick = fill ? 0 : Math.exp(-pos / 0.11)
const bass = pos > BEAT / 2 ? 0.5 * Math.exp(-(pos - BEAT / 2) / 0.16) : 0
const roll = fill ? 0.35 + (0.5 * ((in16 - 14) * 4 + Math.floor(pos / sixteenth))) / 8 : 0
const clap = (n % 2 === 1 ? 0.8 : 0) * Math.exp(-pos / 0.07) + roll * Math.exp(-p16 / 0.05)
const pad = 0.22 + 0.08 * Math.sin(t * 0.9)
const hat = 0.85 * Math.exp(-Math.abs(pos - BEAT / 2) / 0.025) + 0.3 * Math.exp(-p16 / 0.02)
return { low: Math.max(kick, bass), mid: Math.max(clap, pad, kick * 0.5), high: Math.max(hat, clap * 0.6) }
}
function drawWave(ctx: CanvasRenderingContext2D, w: number, h: number, scroll: number) {
ctx.clearRect(0, 0, w, h)
const mid = h / 2
const half = h * 0.34
const centre = w / 2
const first = Math.floor(scroll / SLOT) - 1
const last = first + Math.ceil(w / SLOT) + 2
for (let i = first; i <= last; i++) {
const x = i * SLOT - scroll
const t = (i * SLOT) / SPEED
// The peak over the slot, so a kick never falls between two samples.
const a = levels(t)
const b = levels(t + SLOT / SPEED / 2)
const low = Math.max(a.low, b.low)
const md = Math.max(a.mid, b.mid)
const hi = Math.max(a.high, b.high)
const j = 0.9 + 0.2 * jitter(i)
const h0 = half * Math.min(1, (0.16 + 0.84 * Math.max(low, md * 0.8, hi * 0.55)) * j)
const h1 = Math.min(h0 * 0.86, half * (0.1 + 0.6 * md) * j)
const h2 = Math.min(h1 * 0.84, half * (0.07 + 0.5 * hi) * j)
const h3 = Math.min(h2 * 0.78, half * (0.04 + 0.32 * hi) * j)
// Played audio, left of the playhead, sits dimmer, as on a deck.
ctx.globalAlpha = x + BAR / 2 < centre ? 0.6 : 1
;[h0, h1, h2, h3].forEach((bh, k) => {
ctx.fillStyle = BANDS[k]
ctx.fillRect(x, mid - bh, BAR, bh * 2)
})
}
ctx.globalAlpha = 1
// Bars enter and leave softly at the icon's edges.
ctx.globalCompositeOperation = 'destination-in'
const g = ctx.createLinearGradient(0, 0, w, 0)
g.addColorStop(0, 'rgba(0,0,0,0)')
g.addColorStop(0.14, '#000')
g.addColorStop(0.86, '#000')
g.addColorStop(1, 'rgba(0,0,0,0)')
ctx.fillStyle = g
ctx.fillRect(0, 0, w, h)
ctx.globalCompositeOperation = 'source-over'
}
function StartupMark() {
const canvas = useRef<HTMLCanvasElement>(null)
useEffect(() => {
const el = canvas.current
const ctx = el?.getContext('2d')
if (!el || !ctx) return
const w = el.offsetWidth
const h = el.offsetHeight
const dpr = window.devicePixelRatio || 1
el.width = Math.round(w * dpr)
el.height = Math.round(h * dpr)
ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
// Reduced motion: one still frame.
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
drawWave(ctx, w, h, 0)
return
}
let raf = 0
let start: number | null = null
const frame = (now: number) => {
start ??= now
drawWave(ctx, w, h, ((now - start) / 1000) * SPEED)
raf = requestAnimationFrame(frame)
}
raf = requestAnimationFrame(frame)
return () => cancelAnimationFrame(raf)
}, [])
return (
<div
role="img"
aria-label="Konduktor"
className="relative h-[104px] w-[104px] [filter:drop-shadow(0_22px_40px_rgb(0_0_0/0.55))]"
>
<svg viewBox="0 0 100 100" className="absolute inset-0 h-full w-full" aria-hidden>
<defs>
<clipPath id="startup-clip">
<rect x="2" y="2" width="96" height="96" rx="22" />
</clipPath>
<filter id="startup-blur" filterUnits="userSpaceOnUse" x="-60" y="-60" width="220" height="220">
<feGaussianBlur stdDeviation="13" />
</filter>
</defs>
<g clipPath="url(#startup-clip)">
<rect width="100" height="100" fill="#07070d" />
<g filter="url(#startup-blur)">
<circle cx="22" cy="18" r="32" fill="#6d4aff" />
<circle cx="90" cy="28" r="26" fill="#e0409a" />
<circle cx="76" cy="96" r="32" fill="#12b5c9" />
<circle cx="8" cy="82" r="26" fill="#2f3fe0" />
</g>
<rect width="100" height="100" fill="#05060a" opacity="0.5" />
</g>
</svg>
{/* Clipped to the icon's rounded square: rx 22 inside a 2-unit inset. */}
<canvas
ref={canvas}
aria-hidden
className="absolute"
style={{ inset: '1.92%', width: '96.15%', height: '96.15%', borderRadius: '22.9%' }}
/>
<svg viewBox="0 0 100 100" className="absolute inset-0 h-full w-full" aria-hidden>
<defs>
<clipPath id="startup-clip-top">
<rect x="2" y="2" width="96" height="96" rx="22" />
</clipPath>
<filter id="startup-shadow" filterUnits="userSpaceOnUse" x="-20" y="-20" width="140" height="140">
<feGaussianBlur stdDeviation="2.2" />
</filter>
<linearGradient id="startup-sheen" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stopColor="#fff" stopOpacity=".16" />
<stop offset=".42" stopColor="#fff" stopOpacity="0" />
</linearGradient>
<linearGradient id="startup-rim" x1="0" y1="0" x2="0.4" y2="1">
<stop offset="0" stopColor="#fff" stopOpacity=".55" />
<stop offset=".5" stopColor="#fff" stopOpacity=".08" />
<stop offset="1" stopColor="#fff" stopOpacity=".22" />
</linearGradient>
</defs>
<g clipPath="url(#startup-clip-top)">
<g filter="url(#startup-shadow)" fill="#000" opacity=".95">
<rect x="45.5" y="11" width="9" height="78" />
</g>
<rect x="47.8" y="12" width="4.4" height="76" fill="#fff" />
<path d="M42 12h16L50 21z M42 88h16L50 79z" fill="#fff" />
<rect width="100" height="100" fill="url(#startup-sheen)" />
</g>
<rect x="2.4" y="2.4" width="95.2" height="95.2" rx="21.6" fill="none" stroke="url(#startup-rim)" strokeWidth=".8" />
</svg>
</div>
)
}
+1 -1
View File
@@ -59,7 +59,7 @@ export function Toolbar({
value={filters.search}
onChange={(e) => set({ search: e.target.value })}
ref={searchRef}
placeholder="Search artist, title, album…"
placeholder="Artist, title, album, comment…"
className="well w-72 rounded-full py-1.5 pl-9 pr-8 text-sm text-text outline-none placeholder:text-faint focus:ring-1 focus:ring-accent"
/>
{filters.search && (
+92 -95
View File
@@ -1,4 +1,4 @@
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type MutableRefObject } from 'react'
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type MutableRefObject } from 'react'
import {
flexRender,
getCoreRowModel,
@@ -29,7 +29,8 @@ import {
useSortable,
} from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import type { Track } from '../api'
import type { Track, TrackOrigin } from '../api'
import { beginDrag, useDragPayload, useDropTarget } from '../lib/drag'
import { TRACK_COLUMNS } from '../lib/trackColumns'
/** Fields this platform can persist, for the table's per-cell edit gating.
@@ -71,6 +72,9 @@ interface Props {
/** A view with a manual order. `enabled` is false while a sort or filter is
* active: reordering a partial or re-sorted list would lose the real order. */
reorder?: { enabled: boolean; onReorder: (ids: string[]) => void }
/** Where dragged rows come from: whose ids they are, and the editable
* playlist they leave on an Option-drag (move). Defaults to the collection. */
dragFrom?: { origin: TrackOrigin; playlistId?: string }
/** Delete/Backspace removes the selected tracks from this view. */
onRemove?: (ids: string[]) => void
onRowContextMenu?: (track: Track, x: number, y: number) => void
@@ -78,6 +82,8 @@ interface Props {
onHeaderContextMenu?: (x: number, y: number) => void
onPlay?: (track: Track) => void
onEditField?: (track: Track, field: keyof Track, value: string | number) => void
/** Per-row gate on opening an inline editor (`TableMeta.mayEdit`). */
mayEdit?: (track: Track) => boolean
activeTrackId?: string | null
/** Whether the deck is playing `activeTrackId` (vs. loaded but paused). */
activePlaying?: boolean
@@ -277,11 +283,13 @@ export function TrackTable({
positions,
marked,
reorder,
dragFrom,
onRemove,
onRowContextMenu,
onHeaderContextMenu,
onPlay,
onEditField,
mayEdit,
activeTrackId,
activePlaying = false,
}: Props) {
@@ -294,7 +302,7 @@ export function TrackTable({
data,
columns: TRACK_COLUMNS,
state: { sorting, columnVisibility, columnOrder, columnSizing },
meta: { onEditField, editableFields },
meta: { onEditField, editableFields, mayEdit },
onSortingChange: (updater) =>
onSortingChange(typeof updater === 'function' ? updater(sorting) : updater),
onColumnSizingChange: (updater) =>
@@ -363,7 +371,7 @@ export function TrackTable({
}
const clickRow = (index: number, e: { shiftKey: boolean; metaKey: boolean; ctrlKey: boolean }) => {
if (!selection || justDraggedRef.current) return
if (!selection) return
const id = rows[index].original.id
const toggle = e.metaKey || e.ctrlKey
const anchor = indexOf(anchorRef.current)
@@ -381,102 +389,88 @@ export function TrackTable({
}
}
// ---- row drag-to-reorder ----------------------------------------------
// `drop` is the gap the dragged rows would land in (0 = above the first row).
const [drag, setDrag] = useState<{ moving: Set<number>; drop: number } | null>(null)
// ---- dragging rows ------------------------------------------------------
// Every table's rows are a drag SOURCE (onto playlists, exports, the deck —
// lib/drag.tsx); a view with a manual order is also its own drop TARGET, the
// in-table reorder. `drop` is the gap the rows would land in (0 = above the
// first row).
const pressRef = useRef<{ x: number; y: number; index: number } | null>(null)
const justDraggedRef = useRef(false)
const canDrag = !!reorder?.enabled
const tableKey = useRef({}).current
const dragging = useDragPayload()
const ownDrag = dragging?.kind === 'tracks' && dragging.source === tableKey ? dragging : null
const movingIds = useMemo(() => new Set(ownDrag?.ids ?? []), [ownDrag])
useEffect(() => {
if (!canDrag) return
let raf = 0
let lastY = 0
let active: { moving: Set<number>; drop: number } | null = null
const dropAt = (clientY: number) => {
const top = bodyRef.current?.getBoundingClientRect().top ?? 0
return Math.max(0, Math.min(rowsRef.current.length, Math.round((clientY - top) / ROW_HEIGHT)))
}
// Hold near the top/bottom edge to scroll while dragging.
const autoScroll = () => {
const el = parentRef.current
if (el && active) {
const r = el.getBoundingClientRect()
const edge = 48
const dy =
lastY < r.top + edge + ROW_HEIGHT ? -12 : lastY > r.bottom - edge ? 12 : 0
if (dy) {
el.scrollTop += dy
active = { ...active, drop: dropAt(lastY) }
setDrag(active)
}
}
raf = requestAnimationFrame(autoScroll)
}
const onMove = (e: PointerEvent) => {
const press = pressRef.current
if (!press) return
lastY = e.clientY
if (!active) {
if (Math.hypot(e.clientX - press.x, e.clientY - press.y) < 6) return
// Dragging a selected row moves the whole selection; any other row
// moves alone (and becomes the selection, so what moves is visible).
const rs = rowsRef.current
const sel = selectionRef.current
const pressedId = rs[press.index].original.id
let moving: Set<number>
if (sel?.selected.has(pressedId)) {
moving = new Set(rs.flatMap((r, i) => (sel.selected.has(r.original.id) ? [i] : [])))
} else {
moving = new Set([press.index])
sel?.onChange(new Set([pressedId]))
anchorRef.current = leadRef.current = pressedId
}
active = { moving, drop: dropAt(e.clientY) }
document.body.style.userSelect = 'none'
document.body.style.cursor = 'grabbing'
window.getSelection()?.removeAllRanges()
raf = requestAnimationFrame(autoScroll)
} else {
active = { ...active, drop: dropAt(e.clientY) }
}
setDrag(active)
}
const end = () => {
if (!press || Math.hypot(e.clientX - press.x, e.clientY - press.y) < 6) return
pressRef.current = null
if (!active) return
const { moving, drop } = active
active = null
cancelAnimationFrame(raf)
document.body.style.userSelect = ''
document.body.style.cursor = ''
setDrag(null)
// Swallow the click that follows the pointerup, so a drop is not also a
// click that re-selects the row it ended on.
justDraggedRef.current = true
setTimeout(() => (justDraggedRef.current = false), 0)
// Dragging a selected row carries the whole selection (in the table's
// order); any other row goes alone and becomes the selection, so what is
// being dragged is visible.
const rs = rowsRef.current
const sel = selectionRef.current
const pressed = rs[press.index]?.original
if (!pressed) return
let carried: Track[]
if (sel?.selected.has(pressed.id)) {
carried = rs.filter((r) => sel.selected.has(r.original.id)).map((r) => r.original)
} else {
carried = [pressed]
sel?.onChange(new Set([pressed.id]))
anchorRef.current = leadRef.current = pressed.id
}
const from = dragFromRef.current
beginDrag(
{
kind: 'tracks',
ids: [...new Set(carried.map((t) => t.id))],
tracks: carried,
lead: pressed,
origin: from?.origin ?? 'collection',
fromPlaylist: from?.playlistId,
source: tableKey,
},
{ x: e.clientX, y: e.clientY, alt: e.altKey },
)
}
const release = () => (pressRef.current = null)
window.addEventListener('pointermove', onMove)
window.addEventListener('pointerup', release)
window.addEventListener('pointercancel', release)
return () => {
window.removeEventListener('pointermove', onMove)
window.removeEventListener('pointerup', release)
window.removeEventListener('pointercancel', release)
}
}, [tableKey])
const [dropRef, dropHint] = useDropTarget<{ drop: number }>({
hint: (p, at) => {
if (p.kind !== 'tracks' || p.source !== tableKey || !reorderRef.current?.enabled) return null
const top = bodyRef.current?.getBoundingClientRect().top ?? 0
return { drop: Math.max(0, Math.min(rowsRef.current.length, Math.round((at.y - top) / ROW_HEIGHT))) }
},
onDrop: (p, { drop }) => {
if (p.kind !== 'tracks') return
const ids = new Set(p.ids)
const rs = rowsRef.current.map((r) => r.original)
const kept = rs.filter((_, i) => !moving.has(i))
const block = rs.filter((_, i) => moving.has(i))
const at = drop - [...moving].filter((i) => i < drop).length
const kept = rs.filter((t) => !ids.has(t.id))
const block = rs.filter((t) => ids.has(t.id))
const at = drop - rs.slice(0, drop).filter((t) => ids.has(t.id)).length
const next = [...kept.slice(0, at), ...block, ...kept.slice(at)]
if (next.every((t, i) => t === rs[i])) return
setData(next)
reorderRef.current?.onReorder(next.map((t) => t.id))
}
window.addEventListener('pointermove', onMove)
window.addEventListener('pointerup', end)
window.addEventListener('pointercancel', end)
return () => {
cancelAnimationFrame(raf)
window.removeEventListener('pointermove', onMove)
window.removeEventListener('pointerup', end)
window.removeEventListener('pointercancel', end)
document.body.style.userSelect = ''
document.body.style.cursor = ''
}
}, [canDrag])
},
})
const scrollerRef = useCallback(
(el: HTMLDivElement | null) => {
parentRef.current = el
dropRef(el)
},
[dropRef],
)
// Latest values for the once-attached window listeners.
const rowsRef = useRef(rows)
@@ -485,6 +479,8 @@ export function TrackTable({
selectionRef.current = selection
const reorderRef = useRef(reorder)
reorderRef.current = reorder
const dragFromRef = useRef(dragFrom)
dragFromRef.current = dragFrom
// Keyboard: ↑/↓ move the selection (Shift extends it), Cmd/Ctrl+A selects
// every visible row, Esc clears, Delete/Backspace removes (where the view
@@ -547,7 +543,8 @@ export function TrackTable({
return (
<div
ref={parentRef}
ref={scrollerRef}
data-drag-scroll={bodyOffset.header}
className="h-full overflow-auto px-1.5"
onClick={(e) => {
// A click in the empty space below the rows clears the selection.
@@ -568,13 +565,13 @@ export function TrackTable({
const row = rows[vr.index]
const isSelected = selection?.selected.has(row.original.id) ?? false
const isActive = activeTrackId === row.original.id
const isMoving = drag?.moving.has(vr.index) ?? false
const isMoving = movingIds.has(row.original.id)
return (
<div
key={row.id}
data-row
className={`group absolute left-0 flex items-center border-b border-ink-850 text-sm ${
isSelected ? 'bg-accent-soft/50' : drag ? '' : 'hover:bg-ink-850'
isSelected ? 'bg-accent-soft/50' : dragging ? '' : 'hover:bg-ink-850'
} ${isMoving ? 'opacity-40' : ''}`}
style={{ top: 0, transform: `translateY(${vr.start - bodyOffset.top}px)`, height: vr.size, width: '100%' }}
onMouseDown={(e) => {
@@ -582,7 +579,7 @@ export function TrackTable({
if (selection && (e.shiftKey || e.metaKey || e.ctrlKey)) e.preventDefault()
}}
onPointerDown={(e) => {
if (!canDrag || e.button !== 0 || e.shiftKey || e.metaKey || e.ctrlKey) return
if (e.button !== 0 || e.shiftKey || e.metaKey || e.ctrlKey) return
// Not from a control inside the row (play, stars, an edit field).
if ((e.target as HTMLElement).closest('button, input, textarea, select, a')) return
pressRef.current = { x: e.clientX, y: e.clientY, index: vr.index }
@@ -620,10 +617,10 @@ export function TrackTable({
</div>
)
})}
{drag && (
{dropHint && (
<div
className="pointer-events-none absolute left-0 z-10 h-0.5 w-full bg-accent"
style={{ top: drag.drop * ROW_HEIGHT - 1 }}
style={{ top: dropHint.drop * ROW_HEIGHT - 1 }}
/>
)}
</div>
+7
View File
@@ -87,6 +87,13 @@ body,
overscroll-behavior: none;
}
/* While something is being dragged (lib/drag.tsx), the cursor is the hand
everywhere — buttons and links would otherwise show their own. */
html.is-dragging,
html.is-dragging * {
cursor: grabbing !important;
}
body {
margin: 0;
background: var(--color-ink-950);
+69
View File
@@ -0,0 +1,69 @@
import type { QueryClient } from '@tanstack/react-query'
import { api } from '../api'
import { askChoice } from './confirm'
const plural = (n: number) => `${n} track${n === 1 ? '' : 's'}`
/**
* Add tracks to a playlist — the context menu's "Add to" and a drop on a
* sidebar playlist alike, so the two cannot drift.
*
* Tracks the playlist already holds are ASKED about (decided 2026-10-06), but
* only where the platform can hold a track twice (`playlists.duplicates`);
* elsewhere they are skipped and the message says so. Nothing is asked when
* there are none.
*
* `moveFrom` is an Option-drag out of another (editable) playlist: once the
* tracks are in the target they leave the source. Cancelling the duplicates
* question cancels the move too.
*
* Resolves the message to show, or null when the user cancelled.
*/
export async function addTracksToPlaylist(opts: {
qc: QueryClient
playlist: { id: string; name: string }
ids: string[]
duplicatesAllowed: boolean
moveFrom?: string
}): Promise<string | null> {
const { qc, playlist, ids, duplicatesAllowed, moveFrom } = opts
let res = await api.addEntries(playlist.id, ids, duplicatesAllowed ? 'ask' : 'skip')
if (res.status === 'duplicates') {
const fresh = ids.length - res.duplicates
const all = fresh === 0
const choice = await askChoice({
title: all
? `${ids.length === 1 ? 'This track is' : `All ${ids.length} tracks are`} already in “${playlist.name}”`
: `${plural(res.duplicates)} ${res.duplicates === 1 ? 'is' : 'are'} already in “${playlist.name}”`,
body: all
? ids.length === 1
? 'Add it again, so the playlist holds it twice?'
: 'Add them again, so the playlist holds them twice?'
: `Add only the ${plural(fresh)} not there yet, or add every track — the ${res.duplicates === 1 ? 'one already there' : `${res.duplicates} already there`} a second time?`,
// All of them there: "skip" would add nothing, which is just Cancel —
// so the question is only whether to add them again.
confirmLabel: all ? 'Add again' : `Add ${plural(fresh)}`,
altLabel: all ? undefined : `Add all ${ids.length}`,
tone: 'primary',
})
if (choice === null) return null
res = await api.addEntries(playlist.id, ids, choice === 'alt' || all ? 'add' : 'skip')
}
let moved = false
if (moveFrom && moveFrom !== playlist.id) {
const gone = new Set(ids)
const current = await api.playlistTracks(moveFrom)
await api.setEntries(moveFrom, current.map((t) => t.id).filter((id) => !gone.has(id)))
qc.invalidateQueries({ queryKey: ['playlist', moveFrom] })
moved = true
}
qc.invalidateQueries({ queryKey: ['state'] })
qc.invalidateQueries({ queryKey: ['playlists'] })
qc.invalidateQueries({ queryKey: ['playlist', playlist.id] })
const skipped = ids.length - res.added
if (moved) return `Moved ${plural(ids.length)} to ${playlist.name}`
if (res.added === 0) return `Nothing added — ${ids.length === 1 ? 'it is' : 'they are all'} already in ${playlist.name}`
return `Added ${plural(res.added)} to ${playlist.name}${skipped > 0 ? ` · ${skipped} already there` : ''}`
}
+15 -7
View File
@@ -12,19 +12,26 @@
import { useEffect, useState } from 'react'
import { ConfirmDialog, type ConfirmRequest } from '../components/ConfirmDialog'
type Ask = Omit<ConfirmRequest, 'onConfirm'>
type Pending = { req: Ask; resolve: (ok: boolean) => void }
type Ask = Omit<ConfirmRequest, 'onConfirm' | 'onAlt' | 'altLabel'>
type Choice = 'confirm' | 'alt' | null
type Pending = { req: Ask & { altLabel?: string }; resolve: (choice: Choice) => void }
let open: ((p: Pending) => void) | null = null
/** Show a confirmation and resolve true (confirmed) or false (cancelled). */
export function askConfirm(req: Ask): Promise<boolean> {
return askChoice(req).then((c) => c === 'confirm')
}
/** A confirmation with a SECOND way to go ahead (`altLabel`): resolves
* 'confirm', 'alt', or null when cancelled. */
export function askChoice(req: Ask & { altLabel?: string }): Promise<Choice> {
return new Promise((resolve) => {
if (open) open({ req, resolve })
// No host mounted (should not happen outside tests): refuse rather than
// fall back to a native dialog, since a destructive action must not go
// ahead unconfirmed.
else resolve(false)
else resolve(null)
})
}
@@ -34,7 +41,7 @@ export function ConfirmHost() {
useEffect(() => {
open = (p) =>
setPending((prev) => {
prev?.resolve(false) // a second ask supersedes an unanswered one
prev?.resolve(null) // a second ask supersedes an unanswered one
return p
})
return () => {
@@ -45,10 +52,11 @@ export function ConfirmHost() {
return (
<ConfirmDialog
{...pending.req}
// A promise settles once, so confirm-then-close resolves `true`.
onConfirm={() => pending.resolve(true)}
// A promise settles once, so confirm-then-close resolves 'confirm'.
onConfirm={() => pending.resolve('confirm')}
onAlt={() => pending.resolve('alt')}
onClose={() => {
pending.resolve(false)
pending.resolve(null)
setPending(null)
}}
/>
+350
View File
@@ -0,0 +1,350 @@
import { useCallback, useEffect, useRef, useSyncExternalStore } from 'react'
import { createPortal } from 'react-dom'
import type { PlaylistNode, Track, TrackOrigin } from '../api'
import { Icon } from './icons'
/**
* Drag and drop across the whole window: track rows onto sidebar playlists,
* exports and the deck; playlists around the sidebar tree.
*
* ONE gesture, and the drop TARGET decides what it means. A source calls
* `beginDrag` once the pointer has moved past its threshold; targets register
* with `useDropTarget` and are found by hit-testing (`elementFromPoint`, then up
* through the ancestors), so the virtualized table, the sidebar and the deck
* need no shared React tree — and the innermost target that accepts wins, with
* the search falling through to an enclosing one where it declines.
*
* Pointer events, NOT HTML5 drag and drop: Tauri's webview captures native drag
* events for its own file drop on Windows, so HTML5 DnD silently dies in the
* packaged app.
*
* Files dragged in from Finder / Explorer ride the same store as a `files`
* payload: Tauri reports that drag (with real paths) instead of the webview,
* and `lib/fileDrop.ts` feeds it in through `nativeDragStart` / `Move` / `End`,
* so the same targets light up and the same ghost names what a drop would do.
*
* The state lives in a module-level store read through useSyncExternalStore
* with narrow selectors, so a pointer move re-renders only the target under it
* (and the ghost) — never the table.
*/
export type DragPayload =
| {
kind: 'tracks'
ids: string[]
tracks: Track[]
/** The row the drag started on — what a drop on the deck loads. */
lead: Track
/** Which library the ids belong to — a device's or a folder's are not
* the collection's, so collection targets must not take them as such. */
origin: TrackOrigin
/** The editable playlist they were dragged out of, for Option = move. */
fromPlaylist?: string
/** Identity of the table that started the drag (its own reorder target). */
source: object
}
| { kind: 'node'; node: PlaylistNode; parentId: string | null }
/** Files and folders from the OS, as absolute paths. Not yet tracks: a
* target hands them to the drop resolver, which reads what is in them. */
| { kind: 'files'; paths: string[] }
/** What a playlist or export row takes: track rows, or files from the OS. */
export type TracksOrFiles = Exclude<DragPayload, { kind: 'node' }>
export interface DropPoint {
x: number
y: number
/** Option/Alt held: tracks dragged out of a playlist MOVE instead of copy. */
alt: boolean
}
export interface DropSpec<H> {
/** The hint for a pointer at `at` over this target — anything the target
* needs to draw and to drop (an insertion index, a before/into/after zone) —
* or null where it does not accept this drop, so the search continues to an
* enclosing target. */
hint: (p: DragPayload, at: DropPoint, el: HTMLElement) => H | null
/** What a drop here would do, shown on the ghost ("Add to Warmup"). */
label?: (p: DragPayload, hint: H, at: DropPoint) => string | null
onDrop: (p: DragPayload, hint: H, at: DropPoint) => void
}
interface State {
payload: DragPayload | null
x: number
y: number
alt: boolean
target: HTMLElement | null
hint: unknown
label: string | null
}
const IDLE: State = { payload: null, x: 0, y: 0, alt: false, target: null, hint: null, label: null }
let state: State = IDLE
const listeners = new Set<() => void>()
const targets = new Map<HTMLElement, { current: DropSpec<unknown> }>()
function set(next: Partial<State>) {
state = { ...state, ...next }
listeners.forEach((l) => l())
}
function subscribe(l: () => void) {
listeners.add(l)
return () => listeners.delete(l)
}
/** Keep the previous hint object when the new one has the same fields, so a
* target re-renders only when what it draws changes, not on every move. */
function sameHint(a: unknown, b: unknown): boolean {
if (a === b) return true
if (!a || !b || typeof a !== 'object' || typeof b !== 'object') return false
const ka = Object.keys(a)
return (
ka.length === Object.keys(b).length &&
ka.every((k) => (a as Record<string, unknown>)[k] === (b as Record<string, unknown>)[k])
)
}
/** Find the innermost target under the pointer that accepts, and record its hint. */
function evaluate() {
const { payload, x, y, alt } = state
if (!payload) return
const at = { x, y, alt }
let el = document.elementFromPoint(x, y) as HTMLElement | null
while (el) {
const spec = targets.get(el)
if (spec) {
const hint = spec.current.hint(payload, at, el)
if (hint != null) {
const keep = state.target === el && sameHint(state.hint, hint) ? state.hint : hint
set({ target: el, hint: keep, label: spec.current.label?.(payload, keep, at) ?? null })
return
}
}
el = el.parentElement
}
set({ target: null, hint: null, label: null })
}
let detach: (() => void) | null = null
/** End the drag in progress, dropping on the target under the pointer if `drop`. */
function finish(drop: boolean) {
const { payload: p, target, hint, x, y, alt } = state
detach?.()
if (!drop || !p || !target) return
const spec = targets.get(target)
try {
spec?.current.onDrop(p, hint, { x, y, alt })
} catch (err) {
console.error('drop failed', err)
}
}
/** Publish a new drag and start edge auto-scroll. Returns what undoes both. */
function open(payload: DragPayload, at: { x: number; y: number; alt: boolean }): () => void {
detach?.()
set({ ...IDLE, payload, ...at })
document.documentElement.classList.add('is-dragging')
window.getSelection()?.removeAllRanges()
// Hold near the edge of a `data-drag-scroll` element to scroll it. Its
// value is the height covered at the top (a sticky header). The edge is
// thinner than a row and must be HELD for a moment first: otherwise the
// first or last visible row cannot be dropped on, because the list scrolls
// out from under a pointer resting on it.
let raf = 0
const dwell = new Map<HTMLElement, number>()
const autoScroll = () => {
const { x, y } = state
let scrolled = false
document.querySelectorAll<HTMLElement>('[data-drag-scroll]').forEach((el) => {
const r = el.getBoundingClientRect()
const top = r.top + Number(el.dataset.dragScroll || 0)
const edge = 20
const inside = x >= r.left && x <= r.right && y >= r.top - 24 && y <= r.bottom + 24
const dy = !inside ? 0 : y < top + edge ? -Math.ceil((top + edge - y) / 3) : y > r.bottom - edge ? Math.ceil((y - r.bottom + edge) / 3) : 0
if (!dy) {
dwell.delete(el)
return
}
const since = dwell.get(el) ?? performance.now()
dwell.set(el, since)
if (performance.now() - since < 250) return
const before = el.scrollTop
el.scrollTop += Math.max(-20, Math.min(20, dy))
scrolled ||= el.scrollTop !== before
})
if (scrolled) evaluate()
raf = requestAnimationFrame(autoScroll)
}
raf = requestAnimationFrame(autoScroll)
return () => {
cancelAnimationFrame(raf)
document.documentElement.classList.remove('is-dragging')
set(IDLE)
}
}
/** Start a drag. Call it once the press has moved past the source's threshold. */
export function beginDrag(payload: DragPayload, at: { x: number; y: number; alt: boolean }) {
const close = open(payload, at)
const onMove = (e: PointerEvent) => {
// One notification per move: evaluate() publishes the position with the hint.
state = { ...state, x: e.clientX, y: e.clientY, alt: e.altKey }
evaluate()
}
const onUp = () => finish(true)
const onCancel = () => finish(false)
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape' && e.type === 'keydown') {
// Before every other Esc handler: cancelling the drag is all Esc does.
e.preventDefault()
e.stopImmediatePropagation()
finish(false)
return
}
if (e.key === 'Alt' && state.alt !== (e.type === 'keydown')) {
set({ alt: e.type === 'keydown' })
evaluate()
}
}
window.addEventListener('pointermove', onMove)
window.addEventListener('pointerup', onUp)
window.addEventListener('pointercancel', onCancel)
window.addEventListener('keydown', onKey, true)
window.addEventListener('keyup', onKey, true)
window.addEventListener('blur', onCancel)
detach = () => {
detach = null
window.removeEventListener('pointermove', onMove)
window.removeEventListener('pointerup', onUp)
window.removeEventListener('pointercancel', onCancel)
window.removeEventListener('keydown', onKey, true)
window.removeEventListener('keyup', onKey, true)
window.removeEventListener('blur', onCancel)
// The pointerup that ended the drag is followed by a click on whatever
// is under it; that click is part of the drop, not a click of its own.
const swallow = (e: MouseEvent) => {
e.stopPropagation()
e.preventDefault()
}
window.addEventListener('click', swallow, true)
setTimeout(() => window.removeEventListener('click', swallow, true), 0)
close()
}
evaluate()
}
/** A drag the OS owns (files from Finder / Explorer): it enters the window… */
export function nativeDragStart(payload: DragPayload, at: { x: number; y: number }) {
const close = open(payload, { ...at, alt: false })
detach = () => {
detach = null
close()
}
evaluate()
}
/** …moves over it (window coordinates, CSS pixels)… */
export function nativeDragMove(at: { x: number; y: number }) {
if (!state.payload) return
state = { ...state, ...at }
evaluate()
}
/** …and is dropped (or leaves the window: `drop` false). */
export function nativeDragEnd(drop: boolean, at?: { x: number; y: number }) {
if (drop && at) nativeDragMove(at)
finish(drop)
}
/** A pointerdown handler that starts a drag once the press moves 6 px. A plain
* click never moves that far, so the element keeps its click; a press on a
* field inside it (a rename input) never drags. `make` is asked at the moment
* the drag starts and may return null to refuse. */
export function usePressToDrag(make: () => DragPayload | null): (e: React.PointerEvent) => void {
const makeRef = useRef(make)
makeRef.current = make
return useCallback((e: React.PointerEvent) => {
if (e.button !== 0 || e.shiftKey || e.metaKey || e.ctrlKey) return
if ((e.target as HTMLElement).closest('input, textarea, select')) return
const start = { x: e.clientX, y: e.clientY }
const onMove = (m: PointerEvent) => {
if (Math.hypot(m.clientX - start.x, m.clientY - start.y) < 6) return
stop()
const payload = makeRef.current()
if (payload) beginDrag(payload, { x: m.clientX, y: m.clientY, alt: m.altKey })
}
const stop = () => {
window.removeEventListener('pointermove', onMove)
window.removeEventListener('pointerup', stop)
window.removeEventListener('pointercancel', stop)
}
window.addEventListener('pointermove', onMove)
window.addEventListener('pointerup', stop)
window.addEventListener('pointercancel', stop)
}, [])
}
/** The drag in progress, or null. Changes only when a drag starts or ends. */
export function useDragPayload(): DragPayload | null {
return useSyncExternalStore(subscribe, () => state.payload)
}
/** Register an element as a drop target. Returns the ref to attach and the
* current hint while the pointer is over it (null otherwise). */
export function useDropTarget<H>(spec: DropSpec<H>): [(el: HTMLElement | null) => void, H | null] {
const specRef = useRef(spec as DropSpec<unknown>)
specRef.current = spec as DropSpec<unknown>
const elRef = useRef<HTMLElement | null>(null)
const ref = useCallback((el: HTMLElement | null) => {
if (elRef.current) targets.delete(elRef.current)
elRef.current = el
if (el) targets.set(el, specRef)
}, [])
useEffect(() => () => {
if (elRef.current) targets.delete(elRef.current)
}, [])
const hint = useSyncExternalStore(subscribe, () =>
state.target !== null && state.target === elRef.current ? state.hint : null,
)
return [ref, hint as H | null]
}
/** What the ghost says it is carrying. */
function describe(p: DragPayload): { icon: 'music' | 'playlist' | 'folder' | 'smart'; text: string } {
if (p.kind === 'node')
return { icon: p.node.kind === 'folder' ? 'folder' : p.node.kind === 'smart' ? 'smart' : 'playlist', text: p.node.name }
if (p.kind === 'files')
return p.paths.length === 1
? { icon: 'music', text: p.paths[0].split(/[\\/]/).filter(Boolean).pop() ?? p.paths[0] }
: { icon: 'music', text: `${p.paths.length} items` }
if (p.ids.length === 1) {
const t = p.tracks[0]
return { icon: 'music', text: t ? [t.artist, t.title].filter(Boolean).join(' – ') || 'Untitled' : '1 track' }
}
return { icon: 'music', text: `${p.ids.length} tracks` }
}
/** The ghost under the cursor. Mounted once, in main.tsx. */
export function DragLayer() {
const s = useSyncExternalStore(subscribe, () => state)
if (!s.payload) return null
const { icon, text } = describe(s.payload)
return createPortal(
<div
className="glass-overlay pointer-events-none fixed left-0 top-0 z-[90] flex max-w-72 flex-col gap-0.5 overflow-hidden rounded-xl px-3 py-1.5 text-xs shadow-lg"
style={{ transform: `translate(${s.x + 14}px, ${s.y + 12}px)` }}
>
<span className="flex min-w-0 items-center gap-1.5 text-text">
<Icon name={icon} size={13} className="shrink-0 text-muted" />
<span className="truncate">{text}</span>
</span>
{s.label && <span className="truncate text-[11px] text-accent">{s.label}</span>}
</div>,
document.body,
)
}
Loaded 100 of 107 files, more files were not shown because too many files have changed in this diff. Show more