Compare commits

...
11 Commits
Author SHA1 Message Date
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
69 changed files with 2240 additions and 561 deletions

No files matched your search

+4 -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: |
+3 -2
View File
@@ -39,7 +39,7 @@ cd ..
# 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
.\build_sidecar.ps1 # → frontend\src-tauri\binaries\konduktor-sidecar\ (a folder)
cd ..
# 2) Build the app
@@ -56,7 +56,8 @@ 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
```
Either one installs the app (bundling the sidecar `.exe` alongside it).
Either one installs the app, with the sidecar folder in its `sidecar\` resource
folder (`tauri.windows.conf.json`).
## Rebuilding after changes
+87 -16
View File
@@ -568,7 +568,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"`.
@@ -617,6 +621,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`,
@@ -791,9 +810,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).
@@ -848,8 +875,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
@@ -1413,7 +1450,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
@@ -1434,14 +1475,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
@@ -1451,6 +1503,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
@@ -1716,7 +1783,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
@@ -1747,7 +1818,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/`,
+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)
+11 -9
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
@@ -16,12 +17,13 @@ $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"
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",
)
@@ -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:
+15 -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)
@@ -693,7 +693,7 @@ class OneLibraryStore(ReplaceGridCommands):
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)
@@ -1378,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
@@ -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:
+71 -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()
@@ -260,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:
@@ -268,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
@@ -279,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)
@@ -302,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):
@@ -393,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
+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]
+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
+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))
+4 -4
View File
@@ -45,7 +45,7 @@ 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 +132,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
@@ -381,7 +381,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 +453,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]
+3 -1
View File
@@ -94,7 +94,9 @@ 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)
chunks = []
+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
+128 -13
View File
@@ -765,7 +765,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())
@@ -2183,6 +2186,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."""
@@ -2209,6 +2256,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)
@@ -2223,6 +2274,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}")
@@ -2236,16 +2292,27 @@ 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",
)
@@ -2263,11 +2330,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
@@ -2275,7 +2348,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:
@@ -2286,6 +2363,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))
@@ -2295,6 +2375,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)
@@ -2315,11 +2423,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]
)
@@ -2327,6 +2431,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):
@@ -2343,10 +2452,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:
@@ -2362,7 +2477,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
+2 -1
View File
@@ -35,7 +35,8 @@ from .core.model import AutoHotcue, Track, TrackCues
#: at least its own: minors only add. Bump the minor for an added route or
#: method, the major for anything an older client would misread.
#: 1.1 — `move_playlist` (sidebar drag and drop).
API_VERSION: tuple[int, int] = (1, 1)
#: 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
+10 -2
View File
@@ -521,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
@@ -533,9 +537,13 @@ 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
+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)
+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
+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))
+5 -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
+1 -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))
+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"))
+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)
+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)
+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.4",
"version": "0.2.6",
"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/" }
}
}
+92 -27
View File
@@ -8,6 +8,7 @@ import { addTracksToPlaylist } from './lib/addTracks'
import { useDropTarget } from './lib/drag'
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,
@@ -80,6 +81,9 @@ 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')
// 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 files being added to the collection (and maybe a playlist/export).
const [adding, setAdding] = useState<{ ids: string[]; target: AddTarget | null } | null>(null)
const [playRequest, setPlayRequest] = useState(0) // bump → deck loads & auto-plays
@@ -108,7 +112,9 @@ export default function App() {
const loadTrack = useCallback((t: Track, origin: TrackOrigin = viewOriginRef.current) => {
setPrepTrack(t)
setPrepOrigin(origin)
// 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) => {
@@ -307,6 +313,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
@@ -368,10 +379,16 @@ export default function App() {
// asked (decided 2026-10-06).
const addForeign = useCallback(
(origin: TrackOrigin, ids: string[], target: AddTarget) => {
if (origin === 'folder') setAdding({ ids, target })
else if (origin === 'device') setImportDrop({ ids, target })
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],
)
const [deckDropRef, deckOver] = useDropTarget<true>({
hint: (p) => (p.kind === 'tracks' ? true : null),
@@ -407,7 +424,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)
@@ -443,9 +463,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])
@@ -636,7 +659,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) {
@@ -788,7 +811,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]))
@@ -801,7 +824,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 ▸ -----------------------------------------------------------
@@ -934,12 +957,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[] => [
@@ -1023,8 +1082,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
? [
@@ -1032,7 +1091,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)),
},
]
: []),
@@ -1044,20 +1103,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…',
@@ -1070,12 +1129,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…',
@@ -1092,7 +1153,7 @@ export default function App() {
? [{ 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 }] : []
})(),
]}
@@ -1315,9 +1376,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={() =>
@@ -1325,7 +1388,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,
})
@@ -1459,6 +1522,8 @@ export default function App() {
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}
+23 -11
View File
@@ -478,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
}
@@ -826,14 +837,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)
+20 -6
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 } from '../api'
import { useCaps } from '../lib/capabilities'
import { placedAudioSummary } from '../lib/platformCopy'
import { FolderPicker } from './FolderPicker'
@@ -20,7 +20,10 @@ 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).
*
* 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
@@ -57,11 +60,15 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
// decides copy vs in place itself, so there is nothing to ask.
const caps = useCaps()
const places = caps.tracks.places_audio
// 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)
@@ -251,7 +258,14 @@ 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>
)}
{!places && !uploads && !onServer && (
<div className="space-y-1">
{option(
'copy',
+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,
)
}
+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 && (
+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>
)
}
+57 -10
View File
@@ -6,6 +6,7 @@ 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'
@@ -14,7 +15,7 @@ import { Icon, type IconName } from '../lib/icons'
import { PlatformIcon } from '../lib/platformIcons'
import { addTracksToPlaylist } from '../lib/addTracks'
import { useDragPayload, usePressToDrag, useDropTarget, type DragPayload } from '../lib/drag'
import { nodeIdsUnder, playlistIdsUnder } from '../lib/playlistTree'
import { findNode, idsAfter, nodeIdsUnder, playlistIdsUnder } from '../lib/playlistTree'
/**
* Which view the main table is showing.
@@ -99,8 +100,11 @@ 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. */
@@ -202,7 +206,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'
@@ -278,9 +282,11 @@ function NodeRow({
// 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(() => setOpen(true), 600)
const t = setTimeout(() => openLater.current(), 600)
return () => clearTimeout(t)
}, [opening, expanded])
const ringed = over?.zone === 'tracks' || over?.zone === 'into'
@@ -314,7 +320,7 @@ function NodeRow({
)}
<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 ${
@@ -348,7 +354,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)
}
@@ -469,6 +475,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'] })
@@ -487,10 +519,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 })
},
@@ -525,6 +566,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 })
}
@@ -586,8 +630,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
@@ -622,8 +668,9 @@ export function Sidebar({
canMove: (node) => caps.writable && node.can_move,
onMoveNode: async (node, parentId, index, into) => {
try {
await api.movePlaylist(node.id, parentId, index)
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) {
+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>
)
}
+4 -1
View File
@@ -82,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
@@ -287,6 +289,7 @@ export function TrackTable({
onHeaderContextMenu,
onPlay,
onEditField,
mayEdit,
activeTrackId,
activePlaying = false,
}: Props) {
@@ -299,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) =>
+23
View File
@@ -20,3 +20,26 @@ export function nodeIdsUnder(node: PlaylistNode): Set<string> {
walk(node)
return ids
}
/** The node with this id, anywhere in the tree. */
export function findNode(nodes: PlaylistNode[], id: string): PlaylistNode | undefined {
for (const n of nodes) {
if (n.id === id) return n
const found = findNode(n.children, id)
if (found) return found
}
return undefined
}
/** Old id → new id for a node and everything nested in it, after a rename or
* move that may have changed them (a platform addressing folders by path).
* Neither changes a subtree's shape, so the two are matched by position. */
export function idsAfter(before: PlaylistNode, after: PlaylistNode): Map<string, string> {
const map = new Map<string, string>()
const walk = (a: PlaylistNode, b: PlaylistNode) => {
map.set(a.id, b.id)
a.children.forEach((c, i) => b.children[i] && walk(c, b.children[i]))
}
walk(before, after)
return map
}
+17
View File
@@ -29,6 +29,10 @@ declare module '@tanstack/react-table' {
* platforms genuinely differ in WHICH fields they accept. Undefined means
* "not gated" — every field with a handler stays editable. */
editableFields?: ReadonlySet<string>
/** Asked before an inline editor opens on a row; false keeps it closed.
* A view mixing editable rows with others (a folder: collection tracks
* beside loose files) answers per row — and says why itself. */
mayEdit?: (track: Track) => boolean
}
}
@@ -42,6 +46,7 @@ function InlineEdit({
onCommit,
className = 'w-full min-w-0 truncate text-muted',
readOnly = false,
onBegin,
}: {
value: string | null
display?: ReactNode
@@ -49,6 +54,8 @@ function InlineEdit({
className?: string
/** Render the value without offering an editor. */
readOnly?: boolean
/** Asked on double-click; false keeps the editor closed. */
onBegin?: () => boolean
}) {
const [editing, setEditing] = useState(false)
const [val, setVal] = useState('')
@@ -91,6 +98,7 @@ function InlineEdit({
<div
onDoubleClick={(e) => {
e.stopPropagation()
if (onBegin && !onBegin()) return
setVal(value ?? '')
setEditing(true)
}}
@@ -102,6 +110,11 @@ function InlineEdit({
)
}
/** Whether this row's editor may open (`TableMeta.mayEdit`). */
function mayBegin(c: CellContext<Track, unknown>): boolean {
return c.table.options.meta?.mayEdit?.(c.row.original) ?? true
}
/** Whether this table may edit `field`, per the platform's capabilities. */
function canEdit(c: CellContext<Track, unknown>, field: string): boolean {
const meta = c.table.options.meta
@@ -116,6 +129,7 @@ function editable(field: keyof Track, className?: string) {
value={c.getValue() as string | null}
className={className}
readOnly={!canEdit(c, field)}
onBegin={() => mayBegin(c)}
onCommit={(v) => c.table.options.meta?.onEditField?.(c.row.original, field, v)}
/>
)
@@ -137,12 +151,14 @@ export const TRACK_COLUMNS: ColumnDef<Track, any>[] = [
display={title || <span className="text-faint">Untitled</span>}
className="w-full min-w-0 truncate font-medium text-text group-data-[active]:text-accent"
readOnly={!canEdit(c, 'title')}
onBegin={() => mayBegin(c)}
onCommit={(v) => edit?.(r, 'title', v)}
/>
<InlineEdit
value={r.artist}
className="w-full min-w-0 truncate text-xs text-muted"
readOnly={!canEdit(c, 'artist')}
onBegin={() => mayBegin(c)}
onCommit={(v) => edit?.(r, 'artist', v)}
/>
</div>
@@ -310,6 +326,7 @@ export const TRACK_COLUMNS: ColumnDef<Track, any>[] = [
value={c.getValue() as string | null}
display={<span className="tabular-nums text-muted">{formatDate(c.getValue() as string | null)}</span>}
readOnly={!canEdit(c, 'release_date')}
onBegin={() => mayBegin(c)}
onCommit={(v) => c.table.options.meta?.onEditField?.(c.row.original, 'release_date', v)}
/>
),
+2
View File
@@ -11,6 +11,8 @@ const TRACK_LIST_KEYS = [
['export-tracks'],
['export-playlist-tracks'],
['export-loose'],
// A folder lists the files the collection holds AS collection tracks.
['folder-tracks'],
] as const
/** Refetch every collection track list, plus the unsaved-edits state. */
+13 -9
View File
@@ -11,6 +11,7 @@ import { ConfirmHost } from './lib/confirm.tsx'
import { DragLayer } from './lib/drag.tsx'
import { QuitGuard } from './components/QuitGuard.tsx'
import { preventHistoryNavigation } from './lib/noNavigation.ts'
import { StartupGate } from './components/StartupScreen.tsx'
preventHistoryNavigation()
@@ -28,15 +29,18 @@ createRoot(document.getElementById('root')!).render(
<QueryClientProvider client={queryClient}>
{/* Behind everything, the picker screen included: every surface is glass over it. */}
<AmbientBackdrop />
<App />
{/* Mounted beside App so the update dialog shows even on the picker screen. */}
<UpdateCheck />
{/* askConfirm()'s dialogs — the app's replacement for window.confirm. */}
<ConfirmHost />
{/* Save · Discard · Cancel when quitting with unsaved changes. */}
<QuitGuard />
{/* The ghost under the cursor while dragging tracks or playlists. */}
<DragLayer />
{/* The desktop app's startup screen: nothing below mounts until the backend answers. */}
<StartupGate>
<App />
{/* Mounted beside App so the update dialog shows even on the picker screen. */}
<UpdateCheck />
{/* askConfirm()'s dialogs — the app's replacement for window.confirm. */}
<ConfirmHost />
{/* Save · Discard · Cancel when quitting with unsaved changes. */}
<QuitGuard />
{/* The ghost under the cursor while dragging tracks or playlists. */}
<DragLayer />
</StartupGate>
</QueryClientProvider>
</StrictMode>,
)