Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1464b1e211 | ||
|
|
10f175b206 | ||
|
|
a65ef959b2 | ||
|
|
87cbd3720e | ||
|
|
591f2bc791 | ||
|
|
ebe30c1128 | ||
|
|
cd1914216f | ||
|
|
d10b11f8eb | ||
|
|
79a8a843c5 | ||
|
|
0204a322ff | ||
|
|
05051e7056 | ||
|
|
b5dabbc8a0 | ||
|
|
86bbb7b961 | ||
|
|
d474c662db | ||
|
|
a0df683fee | ||
|
|
3385b794e9 | ||
|
|
2c352b76a1 | ||
|
|
40630ff78e |
No files matched your search
@@ -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: |
|
||||
|
||||
@@ -1,21 +1,27 @@
|
||||
# Building Konduktor for Windows
|
||||
|
||||
The desktop app can't be cross-compiled — a Windows build must be produced **on
|
||||
Windows** (Tauri needs the MSVC toolchain + WebView2; PyInstaller must freeze the
|
||||
backend into a Windows `.exe`). The macOS `.dmg` is built separately on a Mac.
|
||||
The desktop app can't be cross-compiled. A Windows build must be produced **on
|
||||
Windows**: Tauri needs the MSVC toolchain and WebView2, and PyInstaller must
|
||||
freeze the backend into a Windows `.exe`. The macOS `.dmg` is built separately
|
||||
on a Mac (see [docs/BUILDING.md](docs/BUILDING.md)).
|
||||
|
||||
This mirrors the macOS build exactly; only the toolchain install and the
|
||||
sidecar-build command differ.
|
||||
The recipe is the same as on macOS. Only the toolchain install and the
|
||||
sidecar-build command differ. CI does exactly this on `windows-latest`
|
||||
([.github/workflows/build.yml](.github/workflows/build.yml)), so if a local build
|
||||
disagrees with CI, check that workflow first.
|
||||
|
||||
## One-time setup
|
||||
|
||||
1. **Rust** — install via <https://rustup.rs> (gives the `x86_64-pc-windows-msvc`
|
||||
1. **Rust**: install via <https://rustup.rs> (gives the `x86_64-pc-windows-msvc`
|
||||
toolchain). You also need the **MSVC C++ build tools**: install "Desktop
|
||||
development with C++" from the Visual Studio Build Tools installer.
|
||||
2. **WebView2 Runtime** — preinstalled on current Windows 10/11. If missing, get
|
||||
the Evergreen runtime from Microsoft (Tauri's installer can also bootstrap it).
|
||||
3. **Python 3.11–3.14** — <https://python.org> (tick "Add to PATH").
|
||||
4. **Node 18+** — <https://nodejs.org>.
|
||||
2. **WebView2 Runtime**: preinstalled on current Windows 10/11. If it's missing,
|
||||
get the Evergreen runtime from Microsoft (Tauri's installer can also
|
||||
bootstrap it).
|
||||
3. **Python 3.11–3.14**: <https://python.org> (tick "Add to PATH"). CI builds
|
||||
with **3.12**, the safest choice.
|
||||
4. **Node 20.19+ or 22.12+**: <https://nodejs.org>. Vite 8 refuses older
|
||||
versions, so Node 18 no longer works. CI uses Node 20.
|
||||
|
||||
Then, from the repo root:
|
||||
|
||||
@@ -33,49 +39,115 @@ npm install
|
||||
cd ..
|
||||
```
|
||||
|
||||
## Build
|
||||
If PowerShell refuses to run `Activate.ps1` or `dev.ps1` ("running scripts is
|
||||
disabled on this system"), either allow local scripts once with
|
||||
`Set-ExecutionPolicy -Scope CurrentUser RemoteSigned`, or run a script with
|
||||
`powershell -ExecutionPolicy Bypass -File .\dev.ps1`.
|
||||
|
||||
## Develop (no build)
|
||||
|
||||
```powershell
|
||||
.\dev.ps1 # backend on :8000 + Vite on :5173, both reloading; Ctrl-C stops both
|
||||
```
|
||||
|
||||
Then open <http://localhost:5173> in a browser. `dev.ps1` is the Windows
|
||||
counterpart of `dev.sh`. It needs the `backend\.venv` and `frontend\node_modules`
|
||||
from the setup above. It runs the Python source, not the frozen sidecar, so it
|
||||
can't show desktop-shell behaviour (startup screen, quit prompt, WebView2, file
|
||||
drops from Explorer). For that, run `npx tauri dev` in `frontend`. Note that this
|
||||
still spawns the **frozen** sidecar staged in `src-tauri\binaries\`, so backend
|
||||
changes need `build_sidecar.ps1` first.
|
||||
|
||||
### Tests
|
||||
|
||||
`backend/run_tests.sh` expects a POSIX venv (`.venv/bin/activate`), so it won't
|
||||
run as-is on Windows. Run a suite directly with the venv's Python instead:
|
||||
|
||||
```powershell
|
||||
# 1) Freeze + stage the backend sidecar (from the activated backend venv)
|
||||
cd backend
|
||||
.\.venv\Scripts\Activate.ps1 # if not already active
|
||||
.\build_sidecar.ps1 # → frontend\src-tauri\binaries\konduktor-sidecar-<triple>.exe
|
||||
.\.venv\Scripts\python.exe test_save_fidelity.py
|
||||
```
|
||||
|
||||
## Build
|
||||
|
||||
One command does both steps and lists the installers it produced:
|
||||
|
||||
```powershell
|
||||
.\build.ps1 # sidecar + app
|
||||
.\build.ps1 -SkipSidecar # frontend-only change: reuse the staged sidecar
|
||||
.\build.ps1 --debug # any other argument is passed on to `tauri build`
|
||||
```
|
||||
|
||||
By hand, that is:
|
||||
|
||||
```powershell
|
||||
# 1) Freeze + stage the backend sidecar
|
||||
cd backend
|
||||
.\build_sidecar.ps1 # → frontend\src-tauri\binaries\konduktor-sidecar\ (a folder)
|
||||
cd ..
|
||||
|
||||
# 2) Build the app
|
||||
# 2) Build the app (its beforeBuildCommand runs the Vite build)
|
||||
cd frontend
|
||||
npx tauri build
|
||||
```
|
||||
|
||||
`build_sidecar.ps1` uses `backend\.venv\Scripts\python.exe` when it exists (else
|
||||
whatever `python` resolves to), so the venv doesn't need to be activated. It
|
||||
replaces the whole staged folder, so no file from an older build survives.
|
||||
|
||||
The sidecar is a PyInstaller **onedir** folder (`konduktor-sidecar.exe` plus
|
||||
`_internal\`), not a single `.exe`. Don't switch it back to onefile; see
|
||||
gotcha 4 in [CLAUDE.md](CLAUDE.md).
|
||||
|
||||
## Output
|
||||
|
||||
Installers land in:
|
||||
|
||||
```
|
||||
frontend\src-tauri\target\release\bundle\msi\Konduktor_0.1.0_x64_en-US.msi
|
||||
frontend\src-tauri\target\release\bundle\nsis\Konduktor_0.1.0_x64-setup.exe
|
||||
frontend\src-tauri\target\release\bundle\nsis\Konduktor_<version>_x64-setup.exe
|
||||
frontend\src-tauri\target\release\bundle\msi\Konduktor_<version>_x64_en-US.msi
|
||||
```
|
||||
|
||||
Either one installs the app (bundling the sidecar `.exe` alongside it).
|
||||
`<version>` is the `version` in [frontend/package.json](frontend/package.json),
|
||||
the app's only version source. Either installer works. Releases ship only the
|
||||
NSIS `-setup.exe`. Both put the sidecar folder in the app's `sidecar\` resource
|
||||
folder (`tauri.windows.conf.json` → `bundle.resources`), where `lib.rs` spawns
|
||||
`sidecar\konduktor-sidecar.exe`.
|
||||
|
||||
## Rebuilding after changes
|
||||
|
||||
Same as macOS: if you changed **backend** Python, re-run `build_sidecar.ps1`
|
||||
first; then `npx tauri build`. Frontend-only changes just need `npx tauri build`
|
||||
(its `beforeBuildCommand` rebuilds the web app).
|
||||
If you changed **backend** Python, run `.\build.ps1` (or `build_sidecar.ps1`,
|
||||
then `npx tauri build`). Frontend-only changes just need
|
||||
`.\build.ps1 -SkipSidecar` (or `npx tauri build`).
|
||||
|
||||
## Not part of this build: the stem engine
|
||||
|
||||
Convert to Stems uses a separate program, `engine/` (torch + demucs), built and
|
||||
released on its own channel by
|
||||
[.github/workflows/engine.yml](.github/workflows/engine.yml) (`windows-x64-cpu`
|
||||
and `windows-x64-cuda`). The app downloads it at runtime into a short
|
||||
`%LOCALAPPDATA%\Konduktor\engine` path to stay under Windows' 260-character path
|
||||
limit. You don't need it to build or run the app.
|
||||
|
||||
## Known Windows caveats
|
||||
|
||||
- **Unsigned build → SmartScreen.** We don't code-sign yet, so the first launch
|
||||
shows a "Windows protected your PC" prompt. Click **More info → Run anyway**.
|
||||
(Signing is a future step.)
|
||||
- **Unsigned build → SmartScreen.** Builds aren't code-signed yet, so the first
|
||||
launch shows a "Windows protected your PC" prompt. Click **More info → Run
|
||||
anyway**.
|
||||
- **Mixed content is already handled.** The webview is forced to the `http`
|
||||
custom-protocol scheme (`use_https_scheme(false)` in `src-tauri/src/lib.rs`) so
|
||||
it can fetch the sidecar at `http://127.0.0.1:<port>` without being blocked.
|
||||
Leave that setting as-is.
|
||||
- **Sidecar console window.** The sidecar is frozen as a console app (needed for
|
||||
the `KONDUKTOR_PORT` stdout handshake). Tauri's shell plugin normally spawns it
|
||||
without a visible window; if a console flashes on launch, tell me and we'll add
|
||||
the `CREATE_NO_WINDOW` spawn flag.
|
||||
- **The sidecar must be frozen on Windows** — a macOS-built sidecar won't run.
|
||||
- **The sidecar is a console app, but no console appears.** It's frozen with
|
||||
`console=True` because the shell reads the `KONDUKTOR_PORT=<n>` line from its
|
||||
stdout. Tauri's shell plugin spawns it with `CREATE_NO_WINDOW`, so no window
|
||||
flashes.
|
||||
- **The sidecar doesn't watch stdin on Windows.** On macOS it exits when its
|
||||
stdin closes. On Windows a pending stdin read stalled loading scipy's OpenBLAS
|
||||
DLL, which hung the first analysis, so it waits on the parent process instead
|
||||
(`backend/sidecar.py`). Keep this in mind before touching that watcher.
|
||||
- **Decode audio through `waveform.load`, never `librosa.load`.** librosa reads
|
||||
AAC only through CoreAudio or a system ffmpeg, so on Windows every `.m4a` /
|
||||
`.stem.m4a` failed with "Format not recognised". PyAV bundles FFmpeg.
|
||||
- **The sidecar must be frozen on Windows.** A macOS-built sidecar won't run.
|
||||
`build_sidecar.ps1` handles this; just don't copy binaries between OSes.
|
||||
@@ -170,7 +170,14 @@ Two independent apps that talk over HTTP:
|
||||
file** (Convert to Stems). An `ipod` MP4 with five AAC stereo 44.1 kHz
|
||||
streams (mix, drums, bass, synths, vox), streams 1-4 `disposition` 0,
|
||||
muxed IN LOCKSTEP, plus a `moov/udta/stem` JSON box appended in place
|
||||
(moov is last, so only two sizes change). The separation is a CALLBACK —
|
||||
(moov is last, so only two sizes change). **Each stream encodes on its
|
||||
own thread** (PyAV releases the GIL in FFmpeg; ~3x faster with `aac`,
|
||||
104 → 35 s for a 5-minute track's real stems) while ONE thread muxes in
|
||||
the single-threaded order, so the file is byte-identical; every codec is
|
||||
opened and the header written before a worker starts, since the first
|
||||
`mux()` would otherwise open codecs a worker is using. `aac_coder=fast`
|
||||
was measured and rejected: 3-4x faster per stream, but it drops whole
|
||||
8-20 kHz bands for moments (twoloop: never). The separation is a CALLBACK —
|
||||
the backend never imports torch; the engine (below) supplies it, the
|
||||
tests a fake. Measured traps: FFmpeg's resampler upmixes mono at -3 dB,
|
||||
so mono is duplicated by hand; resampling does not move time; both
|
||||
@@ -568,7 +575,11 @@ Two independent apps that talk over HTTP:
|
||||
/ `removed`), `audio` (Range), `art`, `upload` (into a folder CONFINED
|
||||
to the content folder — resolve then `is_relative_to`, so neither `..`
|
||||
nor a symlink escapes — never overwriting, `-2` suffixes, per-session
|
||||
so a cancel deletes only its own), `fs/list|space`, `save`, `discard`,
|
||||
so a cancel deletes only its own), `fs/list|space`, `folder/tracks|audio|leads`
|
||||
(the content folder as a Files tree: tags via the shared `FolderScanner`,
|
||||
file facts, `held` = file → the library's id; audio only for a file a
|
||||
listing returned, confined; `leads` = the analysis lead per file, None
|
||||
unless the platform analyses), `save`, `discard`,
|
||||
`history`, `export-sets`, and the stems routes below. Capabilities are
|
||||
the adapter's plus `tracks.audio_destination="library"`,
|
||||
`reference=False`, `paths.remappable=False`, `overwrite_risk="none"`.
|
||||
@@ -617,6 +628,21 @@ Two independent apps that talk over HTTP:
|
||||
Rekordbox's add analysis — waveform, grid AND key — is computed HERE
|
||||
(`core/add_analysis.prepare` with the lead the upload reports, sent as
|
||||
`NewTrack.analysis`).
|
||||
**The content folder browsed like a drive** (decided 2026-10-10,
|
||||
`folder.py`): `/api/fs/drives` lists the server FIRST (`kind:
|
||||
"server"`, path `server:`) while a remote is open, and the ordinary
|
||||
Files routes (`/api/fs/folders`, `/api/folder/*`) take `server:` +
|
||||
the path ON THE SERVER — so the folder view, deck and add dialog need no
|
||||
second set of routes, and a server path is never taken for the same path
|
||||
here. `RemoteAdapter.folder_listing` remembers what was listed
|
||||
(`ServerFiles`, a read-only source); `folder_audio` downloads into the
|
||||
shared cache by the same facts as a library track's. Adding one is IN
|
||||
PLACE (`on_library_host` → `importer.plan_on_host` + `run(reference=True)`):
|
||||
nothing uploaded, nothing asked; files the library holds map to their
|
||||
ids; where the server reports a lead the file is fetched and analysed
|
||||
here, as an upload is. Server paths go back to the server in its own
|
||||
spelling (`_server_paths`), never `str(Path(…))`, which rewrites them on
|
||||
Windows.
|
||||
**Convert to Stems** (`stems/remote_convert.py`): the server plans
|
||||
(`/v1/stems/plan`, its `convert.plan`), this computer downloads,
|
||||
separates and encodes, uploads each verified file (`/v1/stems/stage`,
|
||||
@@ -791,9 +817,17 @@ Two independent apps that talk over HTTP:
|
||||
expandable Local Storage. A drive carrying a OneLibrary library opens as a
|
||||
device as before, and EVERY drive has a lazily-fetched **Files** tree;
|
||||
clicking a folder is the `folder` source kind — its audio in the ordinary
|
||||
table, read-only via `readonly_cause: 'not_in_library'`, with files the
|
||||
collection already holds checked off in the # column (`TrackTable`'s
|
||||
`marked`). A browsed device is read-only (cause `browsing`); **"Open for
|
||||
table, with files the collection already holds checked off in the #
|
||||
column (`TrackTable`'s `marked`). **A held file's row IS the collection
|
||||
track** (decided 2026-10-10: `main._folder_rows`; `FolderTracks.files` maps
|
||||
its collection id back to the folder id that adding takes): it shows the
|
||||
collection's key/rating/cues/plays, loads into the deck as origin
|
||||
`collection` (`loadTrack`), edits inline and from the menu, and drops onto
|
||||
a playlist directly. The table runs on the COLLECTION's capabilities; a
|
||||
LOOSE row's edit — inline (`TableMeta.mayEdit`, asked before the editor
|
||||
opens), rating, Edit Tags / Analyze / Auto Hotcues / Stems — asks to add
|
||||
it first (`askToAdd`), and in the deck it stays read-only
|
||||
(`not_in_library`). A browsed device is read-only (cause `browsing`); **"Open for
|
||||
editing…"** — the drive row's right-click menu, and a button while browsing
|
||||
a device whose caps say `browsing` — opens it as THE library via App's
|
||||
`openForEditing` (unsaved-edits confirm, source closed, library opened).
|
||||
@@ -848,8 +882,18 @@ Two independent apps that talk over HTTP:
|
||||
shell quits anyway after ~2 s without one, so a hung page cannot trap the
|
||||
user), quits (`quit_now`) when nothing is unsaved, else asks Save · Discard
|
||||
· Cancel; the sidecar is killed only at `RunEvent::Exit`, after the answer;
|
||||
browser dev gets `beforeunload`), `SaveBar` (+ "Discard changes…" when
|
||||
dirty, and the settings gear beside it, whose menu opens `ShortcutsDialog` — the shortcut list is written out BY HAND, so a new or changed shortcut in `PrepStrip` / `TrackTable` must be added there too), `Toolbar` (search/filters; columns are chosen by right-clicking the table header),
|
||||
browser dev gets `beforeunload`), `StartupGate` (mounted in `main.tsx`
|
||||
around everything but `AmbientBackdrop`: the shell opens the window AT ONCE
|
||||
and starts the sidecar beside it, so nothing that calls the API mounts
|
||||
until `backend_status` / `konduktor://backend` says ready, which is when
|
||||
`setApiBase` gets the sidecar's address. Meanwhile `StartupScreen` shows
|
||||
the icon with a generated waveform scrolling under a fixed playhead, a
|
||||
"first launch takes longer" note after 6 s, Quit / Keep waiting after 90 s,
|
||||
and if the sidecar exits its last 30 output lines with Copy details / Quit
|
||||
/ Try again (`backend_restart`). The shell has no timeout of its own. Before
|
||||
ready it answers quit requests itself — nothing can be unsaved — and stops
|
||||
at ready so it never races `QuitGuard`), `SaveBar` (+ "Discard changes…" when
|
||||
dirty, and the settings gear beside it, whose menu opens `ShortcutsDialog` — the shortcut list is written out BY HAND, so a new or changed shortcut in `PrepStrip` / `TrackTable` must be added there too — and `AppSettings` ("Konduktor Settings…": app-level prefs, each with its default in `APP_SETTING_DEFAULTS` and read through `useAppSetting`; today `expandPlaylistFolders` and `exportRootFolder`, both default off — the latter read by the backend at `run_export` and passed down as `ExportPayload.root_folder`. The Sidebar holds folder open state as per-id overrides of that setting, reset on a new library or a change of the setting, and carried to the new ids when a rename/move changes a folder's path id)), `Toolbar` (search/filters; columns are chosen by right-clicking the table header),
|
||||
`TrackTable` (**the one track list** — All Tracks, playlists, exports and
|
||||
devices. TanStack Table + **virtualized** grid; per-row play button,
|
||||
configurable columns, header sorting, inline double-click editing, and
|
||||
@@ -890,6 +934,21 @@ Two independent apps that talk over HTTP:
|
||||
could not be dropped on. Targets: playlist + export rows (Sidebar,
|
||||
ExportsSection), the tree's zones, the table's reorder, and the DECK
|
||||
(App), which loads the grabbed row paused, in its own origin.
|
||||
**Files from Finder / Explorer** (decided 2026-10-13) ride the same store
|
||||
as a `files` payload: `lib/fileDrop.ts` feeds Tauri's `onDragDropEvent`
|
||||
(real paths; a plain browser has none, so no file drop there) through
|
||||
`nativeDragStart`/`Move`/`End`, refused at enter while an `aria-modal`
|
||||
dialog is open or no library is loaded. A playlist/export row opens
|
||||
`AddFilesDialog` with its target, ONE audio file on the deck loads it to
|
||||
listen to, anywhere else (App's root target, with a window overlay) adds
|
||||
to the collection — or says why the library cannot. `POST
|
||||
/api/folder/dropped` resolves the paths first (`FolderScanner.dropped`:
|
||||
folders RECURSIVELY, capped at `MAX_DROPPED`; single files held apart
|
||||
from the folder cache so a partial listing never hides a folder's other
|
||||
files from the sidebar) and makes each file addable and playable through
|
||||
the folder routes. Copy vs in place is asked as for a browsed folder; the
|
||||
add preview counts external-drive files PER FILE (`removable_count` /
|
||||
`removable_drives`, a drop can mix drives) and `in_destination`.
|
||||
`ConvertStemsDialog` (**Convert to Stems**, one dialog — decided: Where =
|
||||
Replace the originals (its option STATES that Save deletes them, since
|
||||
the choice is remembered and may be preselected) or Save to a folder; In
|
||||
@@ -1061,6 +1120,7 @@ Two independent apps that talk over HTTP:
|
||||
|
||||
```bash
|
||||
./dev.sh # start both servers (see README for one-time setup)
|
||||
.\dev.ps1 # the same on Windows (BUILDING-WINDOWS.md)
|
||||
|
||||
# Backend
|
||||
cd backend && source .venv/bin/activate
|
||||
@@ -1133,7 +1193,10 @@ serialization path.** It enforces:
|
||||
48 kHz resampling does not move time; MP3 and FLAC through both encoders give
|
||||
five streams with only the mix enabled, no shift (cross-correlation), the
|
||||
bitrate rule (256 floor, lossless 320), every tag + cover; `verify` refuses a
|
||||
shifted, truncated or box-less file; a raising checkpoint cancels.
|
||||
shifted, truncated or box-less file; a raising checkpoint cancels. The
|
||||
threaded encode is byte-identical to a single-threaded reference (with each
|
||||
encoder present), reports progress 0 → 1, and a cancel or a failing encoder
|
||||
thread leaves no thread running.
|
||||
- `test_stem_swap.py` — `apply_stem_swaps` on a temp copy of the real
|
||||
collection with a generated MP3 (with header) and a real stem file: prep
|
||||
reads back at the same decoded second while its START moves by the 2257-
|
||||
@@ -1330,7 +1393,11 @@ serialization path.** It enforces:
|
||||
scan did not find; **a file the collection already points at is never added
|
||||
twice** (on Traktor that would be two ENTRYs sharing a primary key — a corrupt
|
||||
collection) but still reaches the playlist/export it was headed for; "copy"
|
||||
points the entry at the copy and "reference" at the original.
|
||||
points the entry at the copy and "reference" at the original. And a DROP
|
||||
(`/api/folder/dropped`): folders recursively minus hidden ones, dropped
|
||||
non-audio counted as skipped, only what was dropped becomes streamable, the
|
||||
folder's own listing stays whole, the cap, held files as their collection
|
||||
track, and the preview's per-file external-drive count and `in_destination`.
|
||||
- `test_picker.py` — the picker's routes. Pins the scoping, because the bug it
|
||||
replaced was invisible: `/api/library/options` flattened every driver's
|
||||
detections and returned `[0]`, so a plugged-in USB stick could be offered as
|
||||
@@ -1413,7 +1480,11 @@ serialization path.** It enforces:
|
||||
only the edited `<ENTRY>` THROUGH the trip, one download per file, Analyze
|
||||
on the cached copy, export (and a re-export copying nothing), an upload
|
||||
stored in the mapping's stored form, takeover → read-only at once,
|
||||
reopening names the holder and the edits left, leaving releases.
|
||||
reopening names the holder and the edits left, leaving releases. And the
|
||||
content folder as a drive: listed first, confined, held files ticked off,
|
||||
auditioned with one download, an add IN PLACE (no upload, the held one not
|
||||
added twice, both into the playlist, analysed here when the server reports
|
||||
a lead).
|
||||
- `test_remote_stems.py` — Convert to Stems on a remote with the FAKE engine:
|
||||
the plan's transfer and two-machine space, Replace parks and swaps ON THE
|
||||
SERVER (saved file untouched until Save, which deletes the parked
|
||||
@@ -1434,14 +1505,25 @@ frontend at `http://localhost:5173`.
|
||||
|
||||
1. **`traktor-nml-utils` MUST come from GitHub, not PyPI.** PyPI's `3.1.0` is
|
||||
stale and **cannot parse Traktor Pro 4 (NML v20)** files — its strict parser
|
||||
dies on the v4 `<GRID>` element inside `CUE_V2`. `requirements.txt` pins the
|
||||
GitHub `master` (v4.0.0). Do not "simplify" this to a plain PyPI pin.
|
||||
dies on the v4 `<GRID>` element inside `CUE_V2`. `requirements.txt` pins a
|
||||
GitHub commit (v4.0.0). Do not "simplify" this to a plain PyPI pin.
|
||||
**`pyrekordbox` is now the same situation**: PyPI's latest (0.4.4) has no
|
||||
`devicelib_plus`, which is the OneLibrary (`exportLibrary.db`) reader, so
|
||||
`requirements.txt` pins the GitHub master. That upgrade renamed `db6` →
|
||||
`masterdb` and `tables` → `models` and moved `BLOB` out of `db6.database`;
|
||||
the Rekordbox adapter uses the new names. `db6` still works as a deprecated
|
||||
alias and is **removed in 0.6.0**.
|
||||
`onelibrary` module, which is the OneLibrary (`exportLibrary.db`) reader
|
||||
(`OneLibrary` class; `devicelib_plus` / `DeviceLibraryPlus` before upstream's
|
||||
rename), nor `masterdb` (formerly `db6`, now removed upstream; `tables` →
|
||||
`models`, `BLOB` in `masterdb.database`).
|
||||
**Both GitHub deps are pinned to a COMMIT, never bare master**: the
|
||||
`devicelib_plus` → `onelibrary` rename reached CI's fresh install while dev
|
||||
venvs kept the old commit, and a release shipped that could not export or
|
||||
read OneLibrary while every local test passed. Move a pin on purpose, with
|
||||
`./run_tests.sh`.
|
||||
**PyAV: open files for reading through `core/pyav.open_input`, never
|
||||
`av.open` directly.** PyAV 18 refuses a file with non-UTF-8 tags unless
|
||||
given `metadata_errors="ignore"`; PyAV 19 removed that keyword. CI installs
|
||||
fresh (it got 19) while a dev venv keeps what it had (18), so code passing
|
||||
the keyword passed every local test and shipped a release whose deck played
|
||||
every stem track as the mix. `requirements.txt` caps `av<20`: check
|
||||
`pyav.py` before raising it.
|
||||
2. **The collection is real, irreplaceable data — protect it.** Every save
|
||||
writes a timestamped `.bak` first (into a `backups/` folder next to the
|
||||
collection). When testing writes, point `KONDUKTOR_NML` at a COPY. Warn the
|
||||
@@ -1451,6 +1533,21 @@ frontend at `http://localhost:5173`.
|
||||
render is the library's own pipeline (see "Write path"), which reproduces
|
||||
Traktor's byte-exact layout so a no-op save is byte-identical and only edited
|
||||
objects diff. `test_save_fidelity.py` enforces this.
|
||||
4. **The desktop sidecar is a PyInstaller ONEDIR folder — never go back to
|
||||
onefile.** A onefile binary unpacked ~390 native libraries into a NEW temp
|
||||
folder on every launch, and macOS (XProtect / syspolicyd) checks each library
|
||||
it has not seen before as it is dlopen()ed, keyed per FILE: the window
|
||||
appeared only after ~10 s on every launch (measured 2026-10-12: 95 s to load
|
||||
them all fresh, 1 s once seen). As a folder in the app they are checked
|
||||
once; a launch is ~0.5 s. `build_sidecar.*` stages
|
||||
`src-tauri/binaries/konduktor-sidecar/`; `lib.rs` spawns
|
||||
`<resources>/sidecar/konduktor-sidecar[.exe]`. On macOS it is bundled by
|
||||
`tauri.macos.conf.json`'s `bundle.macOS.files`, NOT `bundle.resources`:
|
||||
the resource copier follows symlinks, turning PyInstaller's 37 library
|
||||
aliases (`_internal/libavcodec… -> av/.dylibs/…`, `Python.framework`'s
|
||||
`Versions/Current`) into second copies a library could be loaded twice
|
||||
from. Windows has no such links and uses `resources`
|
||||
(`tauri.windows.conf.json`).
|
||||
|
||||
## Data model notes
|
||||
|
||||
@@ -1716,7 +1813,11 @@ that number and nothing else — everything derives from it:
|
||||
**volume-relative** `DIR`, never a host path — so a USB export is portable by
|
||||
construction, and the `.nml` cannot be written until the destination is known.
|
||||
Also settled: loose tracks land in an **"Other" playlist**, playlist folders
|
||||
are preserved, and the export is a **standalone `collection.nml`** the user
|
||||
are preserved — at the exported library's TOP LEVEL by default; the
|
||||
`exportRootFolder` setting (`ExportPayload.root_folder`) nests the whole
|
||||
tree, Other included, in one folder named after the export, in all four
|
||||
writers (decided 2026-10-12: the export is a library of its own, so the
|
||||
wrapper was one more click at the gig), and the export is a **standalone `collection.nml`** the user
|
||||
swaps into a Traktor install — so it needs the full skeleton, verified from the
|
||||
real file: `<NML VERSION="20">`, `<HEAD>`, `<COLLECTION ENTRIES>`,
|
||||
`<SETS ENTRIES="0">`, `<PLAYLISTS>` wrapping a `$ROOT` FOLDER node with a
|
||||
@@ -1747,7 +1848,7 @@ that number and nothing else — everything derives from it:
|
||||
deliberately NOT in the fixture, since they carry the machine's name and
|
||||
UUIDs; those are generated fresh per export.
|
||||
- **The two Pioneer key blobs are different.** `masterdb`'s key and
|
||||
`devicelib_plus`'s are not the same string; mixing them up yields a database
|
||||
`onelibrary`'s are not the same string; mixing them up yields a database
|
||||
Rekordbox cannot open.
|
||||
`adapters/onelibrary/export.py` writes a whole drive (`PIONEER/rekordbox/
|
||||
exportLibrary.db` from the checked-in DDL, plus ANLZ under `PIONEER/USBANLZ/`,
|
||||
|
||||
@@ -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 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
|
||||
|
||||

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

|
||||
|
||||
**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 |
|
||||
|:---:|:---:|
|
||||
|  |  |
|
||||
| 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)
|
||||
@@ -1,6 +1,7 @@
|
||||
# Build the frozen backend sidecar on Windows (PyInstaller) and stage it for
|
||||
# Tauri as binaries\konduktor-sidecar-<target-triple>.exe.
|
||||
# Output: backend\dist\konduktor-sidecar.exe + frontend\src-tauri\binaries\...
|
||||
# Build the frozen backend sidecar on Windows (a PyInstaller onedir folder) and
|
||||
# stage it for Tauri as frontend\src-tauri\binaries\konduktor-sidecar\, which
|
||||
# tauri.conf.json bundles as a resource folder (`sidecar\` in the app).
|
||||
# Output: backend\dist\konduktor-sidecar\ + frontend\src-tauri\binaries\konduktor-sidecar\
|
||||
#
|
||||
# Run from a PowerShell prompt with the backend venv's Python on PATH, e.g.:
|
||||
# cd backend
|
||||
@@ -15,13 +16,19 @@ Set-Location $Root
|
||||
$Py = Join-Path $Root ".venv\Scripts\python.exe"
|
||||
if (-not (Test-Path $Py)) { $Py = "python" }
|
||||
|
||||
& $Py -m PyInstaller --noconfirm --clean konduktor-sidecar.spec
|
||||
Write-Host "Built: $Root\dist\konduktor-sidecar.exe"
|
||||
# PyInstaller logs to stderr. Windows PowerShell 5.1 (unlike pwsh 7) turns a
|
||||
# native command's stderr into an error record, which "Stop" makes fatal on the
|
||||
# first INFO line — so relax it for this call and judge by the exit code.
|
||||
$ErrorActionPreference = "Continue"
|
||||
& $Py -m PyInstaller --noconfirm --clean konduktor-sidecar.spec 2>&1 | ForEach-Object { "$_" }
|
||||
$ErrorActionPreference = "Stop"
|
||||
if ($LASTEXITCODE -ne 0) { throw "PyInstaller failed ($LASTEXITCODE)" }
|
||||
Write-Host "Built: $Root\dist\konduktor-sidecar\"
|
||||
|
||||
# Stage for Tauri: name with the host target triple + .exe so the shell plugin
|
||||
# resolves it. (rustc must be on PATH.)
|
||||
$Triple = (& rustc -vV | Select-String '^host: ').ToString().Replace('host: ', '').Trim()
|
||||
# Stage for Tauri, replacing the whole folder so no file from an older build survives.
|
||||
$Dest = Join-Path $Root "..\frontend\src-tauri\binaries"
|
||||
New-Item -ItemType Directory -Force -Path $Dest | Out-Null
|
||||
Copy-Item "$Root\dist\konduktor-sidecar.exe" (Join-Path $Dest "konduktor-sidecar-$Triple.exe") -Force
|
||||
Write-Host "Staged: $Dest\konduktor-sidecar-$Triple.exe"
|
||||
$Staged = Join-Path $Dest "konduktor-sidecar"
|
||||
if (Test-Path $Staged) { Remove-Item -Recurse -Force $Staged }
|
||||
Copy-Item -Recurse "$Root\dist\konduktor-sidecar" $Staged
|
||||
Write-Host "Staged: $Staged\"
|
||||
@@ -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/"
|
||||
@@ -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:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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"])
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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]
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -14,7 +14,9 @@ This is opened by the folder routes and nothing else.
|
||||
Three rules:
|
||||
|
||||
* **This folder only.** Subfolders are not scanned — the tree is how you get to
|
||||
them — so a click on a drive root never walks the whole drive.
|
||||
them — so a click on a drive root never walks the whole drive. A folder
|
||||
DROPPED onto the window is the exception (`FolderScanner.dropped`): the user
|
||||
asked for everything in it, so it recurses, capped at `MAX_DROPPED`.
|
||||
* **A track id is the file's absolute path.** It is the one identity a loose
|
||||
file has, and it is what the audio route checks a request against.
|
||||
* **Tags are read once per folder state.** Reading tags opens every file, which
|
||||
@@ -26,6 +28,7 @@ from __future__ import annotations
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from .capabilities import Capabilities, SaveCapabilities, TrackCapabilities
|
||||
@@ -165,17 +168,88 @@ class FolderSource:
|
||||
return capabilities_for(self.path)
|
||||
|
||||
|
||||
# A drop of a whole drive must not read tags for hours: past this many audio
|
||||
# files the rest are left out and the answer says so.
|
||||
MAX_DROPPED = 20_000
|
||||
|
||||
|
||||
@dataclass
|
||||
class Dropped:
|
||||
"""What a drop onto the window resolved to."""
|
||||
|
||||
tracks: list[Track] = field(default_factory=list)
|
||||
# Dropped FILES that are not audio this library can hold (or are gone).
|
||||
# Non-audio inside a dropped folder is not counted: an album folder's
|
||||
# cover and cue sheet are not something the user asked to add.
|
||||
skipped: int = 0
|
||||
# More than MAX_DROPPED audio files: the rest were left out.
|
||||
truncated: bool = False
|
||||
|
||||
|
||||
class FolderScanner:
|
||||
"""Scans folders on request, caching each until its contents change.
|
||||
|
||||
Also the gatekeeper for streaming: `source_for_file` answers only for a file
|
||||
found by a scan, so the audio route cannot be used to read an arbitrary path
|
||||
off the disk — only audio the user has browsed to.
|
||||
found by a scan — or dropped onto the window by the user — so the audio
|
||||
route cannot be used to read an arbitrary path off the disk, only audio the
|
||||
user has browsed to or handed over.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._lock = threading.Lock()
|
||||
self._cache: dict[str, tuple[float, tuple[str, ...], FolderSource]] = {}
|
||||
# Files dropped one by one: their folder was never scanned (and is not
|
||||
# cached as if it had been — a partial listing would hide its other
|
||||
# files from the sidebar), so each is held on its own.
|
||||
self._files: dict[str, Track] = {}
|
||||
|
||||
def dropped(self, paths: list[str], formats: list[str], limit: int = MAX_DROPPED) -> Dropped:
|
||||
"""Resolve paths dropped onto the window: folders RECURSIVELY (hidden
|
||||
and OS-housekeeping folders left out, as the tree leaves them out),
|
||||
files as themselves. Every audio file found becomes addable and
|
||||
playable through the folder routes, exactly as if it had been browsed."""
|
||||
wanted = {f.lower() for f in formats}
|
||||
out = Dropped()
|
||||
seen: set[str] = set()
|
||||
|
||||
def take(tracks: list[Track]) -> bool:
|
||||
for t in tracks:
|
||||
if t.id in seen:
|
||||
continue
|
||||
if len(out.tracks) >= limit:
|
||||
out.truncated = True
|
||||
return False
|
||||
seen.add(t.id)
|
||||
out.tracks.append(t)
|
||||
return True
|
||||
|
||||
for raw in paths:
|
||||
path = Path(raw).expanduser()
|
||||
if path.is_dir():
|
||||
for folder in _walk(path):
|
||||
if not audio_files(folder, formats):
|
||||
continue
|
||||
if not take(self.scan(folder, formats).tracks):
|
||||
return out
|
||||
elif path.is_file() and path.suffix.lower() in wanted and not is_hidden(path):
|
||||
track = self._file_track(path)
|
||||
if not take([track]):
|
||||
return out
|
||||
else:
|
||||
out.skipped += 1
|
||||
return out
|
||||
|
||||
def _file_track(self, path: Path) -> Track:
|
||||
key = str(path)
|
||||
with self._lock:
|
||||
hit = self._cache.get(str(path.parent))
|
||||
known = hit[2].track(key) if hit is not None else None
|
||||
if known is not None:
|
||||
return known
|
||||
track = read_track(path)
|
||||
with self._lock:
|
||||
self._files[key] = track
|
||||
return track
|
||||
|
||||
def scan(self, folder: Path, formats: list[str]) -> FolderSource:
|
||||
folder = Path(folder)
|
||||
@@ -198,10 +272,32 @@ class FolderScanner:
|
||||
folder = str(Path(track_id).parent)
|
||||
with self._lock:
|
||||
hit = self._cache.get(folder)
|
||||
if hit is None or hit[2].track(track_id) is None:
|
||||
return None
|
||||
return hit[2]
|
||||
loose = self._files.get(track_id)
|
||||
if hit is not None and hit[2].track(track_id) is not None:
|
||||
return hit[2]
|
||||
if loose is not None:
|
||||
return FolderSource(Path(folder), [loose])
|
||||
return None
|
||||
|
||||
def clear(self) -> None:
|
||||
with self._lock:
|
||||
self._cache.clear()
|
||||
self._files.clear()
|
||||
|
||||
|
||||
def _walk(root: Path):
|
||||
"""`root` and every visible folder under it, depth first, sorted by name."""
|
||||
yield root
|
||||
try:
|
||||
with os.scandir(root) as it:
|
||||
subs = []
|
||||
for entry in it:
|
||||
try:
|
||||
if entry.is_dir(follow_symlinks=False) and not is_hidden(entry):
|
||||
subs.append(Path(entry.path))
|
||||
except OSError:
|
||||
continue
|
||||
except OSError:
|
||||
return
|
||||
for sub in sorted(subs, key=lambda p: p.name.lower()):
|
||||
yield from _walk(sub)
|
||||
@@ -235,8 +235,8 @@ def detect_grid(
|
||||
if bpm is not None and not (20.0 <= bpm <= 400.0):
|
||||
raise ValueError(f"Not a usable BPM: {bpm}")
|
||||
if y is None:
|
||||
import librosa
|
||||
y, sr = librosa.load(audio_path, sr=sr, mono=True)
|
||||
from . import waveform
|
||||
y, sr = waveform.load(audio_path, sr=sr)
|
||||
y = np.asarray(y, dtype=np.float32)
|
||||
duration = len(y) / sr
|
||||
if duration < 1.5:
|
||||
|
||||
@@ -178,7 +178,7 @@ def with_detected_key(track, y: np.ndarray | None, sr: int):
|
||||
|
||||
|
||||
def detect_key(audio_path: str) -> KeyResult | None:
|
||||
import librosa
|
||||
from . import waveform
|
||||
|
||||
y, sr = librosa.load(audio_path, sr=SR, mono=True)
|
||||
y, sr = waveform.load(audio_path, sr=SR)
|
||||
return detect_key_samples(y, sr)
|
||||
@@ -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))
|
||||
@@ -37,15 +37,17 @@ from __future__ import annotations
|
||||
|
||||
import fractions
|
||||
import json
|
||||
import queue
|
||||
import struct
|
||||
import sys
|
||||
import threading
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import numpy as np
|
||||
|
||||
from . import mp4_edit, tag_copy
|
||||
from . import mp4_edit, pyav, tag_copy
|
||||
|
||||
SR = 44100
|
||||
FRAME = 1024 # AAC-LC frame size, for both encoders
|
||||
@@ -132,7 +134,7 @@ def decode(path: Path | str) -> Source:
|
||||
"""Decode the first audio stream to stereo float32 at 44.1 kHz."""
|
||||
import av
|
||||
|
||||
with av.open(str(path), metadata_errors="ignore") as container:
|
||||
with pyav.open_input(path) as container:
|
||||
stream = container.streams.audio[0]
|
||||
codec = stream.codec_context.name
|
||||
bit_rate = stream.bit_rate or container.bit_rate or None
|
||||
@@ -151,15 +153,36 @@ def decode(path: Path | str) -> Source:
|
||||
return Source(pcm=np.ascontiguousarray(pcm), codec=codec, bit_rate=bit_rate)
|
||||
|
||||
|
||||
#: Encoded frames each stream's thread may run ahead of the muxer.
|
||||
_ENCODE_QUEUE = 64
|
||||
#: Frames between `checkpoint()` / `progress()` calls (~6 s of audio).
|
||||
_ENCODE_TICK = 256
|
||||
|
||||
|
||||
def _encode(fp, tracks: list[np.ndarray], *, bit_rate: int, encoder: str,
|
||||
checkpoint: Callable[[], None] | None) -> None:
|
||||
"""Mux five AAC streams IN LOCKSTEP — one frame of each in turn — so the
|
||||
muxer never buffers a whole stream (which it would if they came one after
|
||||
another)."""
|
||||
checkpoint: Callable[[], None] | None,
|
||||
progress: Callable[[float], None] | None = None) -> None:
|
||||
"""Encode the AAC streams on one thread EACH and mux them on this one, IN
|
||||
LOCKSTEP — per frame stream 0..4, then each stream's flush — so the muxer
|
||||
never buffers a whole stream (which it would if they came one after another).
|
||||
|
||||
The encoders are independent and PyAV releases the GIL inside FFmpeg, so
|
||||
this is ~3x faster than one thread with FFmpeg's `aac` (a 5-minute track's
|
||||
real stems: 104 s -> 35 s on a 6-core i7) — and since the mux order is the single-threaded
|
||||
one, the file is byte-identical. Every codec is opened and the header written
|
||||
HERE before any worker starts: the first `mux()` would otherwise open (and
|
||||
read) codec contexts a worker may be opening or encoding with. After that
|
||||
this thread never touches a codec, and a worker never touches the container.
|
||||
|
||||
`checkpoint()` and `progress(fraction)` are called from this thread only.
|
||||
"""
|
||||
import av
|
||||
|
||||
n = tracks[0].shape[1]
|
||||
tb = fractions.Fraction(1, SR)
|
||||
offsets = range(0, n, FRAME)
|
||||
stop = threading.Event()
|
||||
threads: list[threading.Thread] = []
|
||||
container = av.open(fp, "w", format="ipod")
|
||||
try:
|
||||
streams = []
|
||||
@@ -169,21 +192,63 @@ def _encode(fp, tracks: list[np.ndarray], *, bit_rate: int, encoder: str,
|
||||
if k:
|
||||
s.disposition = 0 # present, not enabled: a plain player plays the mix
|
||||
streams.append(s)
|
||||
for i, offset in enumerate(range(0, n, FRAME)):
|
||||
if checkpoint is not None and i % 512 == 0:
|
||||
checkpoint()
|
||||
for s, x in zip(streams, tracks):
|
||||
frame = av.AudioFrame.from_ndarray(
|
||||
np.ascontiguousarray(x[:, offset:offset + FRAME], dtype=np.float32),
|
||||
format="fltp", layout="stereo",
|
||||
)
|
||||
frame.sample_rate, frame.pts, frame.time_base = SR, offset, tb
|
||||
for packet in s.encode(frame):
|
||||
container.mux(packet)
|
||||
for s in streams:
|
||||
for packet in s.encode(None):
|
||||
s.codec_context.open(strict=False)
|
||||
container.start_encoding()
|
||||
queues = [queue.Queue(maxsize=_ENCODE_QUEUE) for _ in tracks]
|
||||
|
||||
def put(q: queue.Queue, item) -> bool:
|
||||
while not stop.is_set():
|
||||
try:
|
||||
q.put(item, timeout=0.1)
|
||||
return True
|
||||
except queue.Full:
|
||||
pass
|
||||
return False # the muxer gave up: stop encoding
|
||||
|
||||
def work(s, x: np.ndarray, q: queue.Queue) -> None:
|
||||
try:
|
||||
for offset in offsets:
|
||||
frame = av.AudioFrame.from_ndarray(
|
||||
np.ascontiguousarray(x[:, offset:offset + FRAME], dtype=np.float32),
|
||||
format="fltp", layout="stereo",
|
||||
)
|
||||
frame.sample_rate, frame.pts, frame.time_base = SR, offset, tb
|
||||
if not put(q, s.encode(frame)):
|
||||
return
|
||||
put(q, s.encode(None))
|
||||
except BaseException as ex: # noqa: BLE001 — re-raised by the muxer
|
||||
put(q, ex)
|
||||
|
||||
def mux(q: queue.Queue) -> None:
|
||||
packets = q.get()
|
||||
if isinstance(packets, BaseException):
|
||||
raise packets
|
||||
for packet in packets:
|
||||
container.mux(packet)
|
||||
|
||||
threads = [threading.Thread(target=work, args=(s, x, q), daemon=True, name=f"stem-encode-{k}")
|
||||
for k, (s, x, q) in enumerate(zip(streams, tracks, queues))]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for i in range(len(offsets)):
|
||||
if i % _ENCODE_TICK == 0:
|
||||
if checkpoint is not None:
|
||||
checkpoint()
|
||||
if progress is not None:
|
||||
progress(i / len(offsets))
|
||||
for q in queues:
|
||||
mux(q)
|
||||
for q in queues:
|
||||
mux(q) # each stream's flush
|
||||
if progress is not None:
|
||||
progress(1.0)
|
||||
finally:
|
||||
# A cancel or a failure: the workers stop at their next frame, and must
|
||||
# have stopped before the container (and their codecs) are freed.
|
||||
stop.set()
|
||||
for t in threads:
|
||||
t.join()
|
||||
container.close()
|
||||
|
||||
|
||||
@@ -302,14 +367,16 @@ Separate = Callable[[np.ndarray], list[np.ndarray]]
|
||||
|
||||
|
||||
def build(source_path: Path | str, target: Path | str, separate: Separate, *,
|
||||
encoder: str | None = None, checkpoint: Callable[[], None] | None = None) -> Written:
|
||||
encoder: str | None = None, checkpoint: Callable[[], None] | None = None,
|
||||
on_encode: Callable[[float], None] | None = None) -> Written:
|
||||
"""Convert `source_path` into a stem file at `target`.
|
||||
|
||||
`separate(pcm)` gets the stereo 44.1 kHz mix and must return the four stems
|
||||
in `DEMUCS_ORDER`, each the mix's shape. `target` may be any name — the batch
|
||||
writes a `*.konduktor-partial` and renames it once the batch commits — since
|
||||
nothing here infers a format from the suffix. `checkpoint()` is called between
|
||||
phases and during the encode, and may raise to cancel.
|
||||
phases and during the encode, and may raise to cancel. `on_encode(fraction)`
|
||||
reports the encode's progress, 0 to 1 (verifying after it takes ~1 s).
|
||||
"""
|
||||
target = Path(target)
|
||||
tick = checkpoint or (lambda: None)
|
||||
@@ -322,7 +389,7 @@ def build(source_path: Path | str, target: Path | str, separate: Separate, *,
|
||||
bit_rate = choose_bitrate(source)
|
||||
with open(target, "wb") as fp:
|
||||
_encode(fp, [source.pcm, *stems], bit_rate=bit_rate,
|
||||
encoder=encoder or default_encoder(), checkpoint=checkpoint)
|
||||
encoder=encoder or default_encoder(), checkpoint=checkpoint, progress=on_encode)
|
||||
add_stem_box(target)
|
||||
tags = tag_copy.copy_tags(source_path, target)
|
||||
verify(target, source)
|
||||
@@ -381,7 +448,7 @@ def _audio_stream_count(path: Path) -> int:
|
||||
av = None
|
||||
if av is not None:
|
||||
try:
|
||||
with av.open(str(path), metadata_errors="ignore") as c:
|
||||
with pyav.open_input(path) as c:
|
||||
return len(c.streams.audio)
|
||||
except av.FFmpegError as ex:
|
||||
raise ValueError(str(ex))
|
||||
@@ -453,7 +520,7 @@ def extract_stream(path: Path | str, stream: int, fp) -> None:
|
||||
"""
|
||||
import av
|
||||
|
||||
with av.open(str(path), metadata_errors="ignore") as inp:
|
||||
with pyav.open_input(path) as inp:
|
||||
if not 0 <= stream < len(inp.streams.audio):
|
||||
raise StemFileError(f"The file has no audio stream {stream}")
|
||||
ist = inp.streams.audio[stream]
|
||||
|
||||
@@ -273,8 +273,8 @@ def analyse(
|
||||
if not markers:
|
||||
raise ValueError("Set a beatgrid first")
|
||||
if y is None:
|
||||
import librosa
|
||||
y, _ = librosa.load(audio_path, sr=_SR, mono=True)
|
||||
from . import waveform
|
||||
y, _ = waveform.load(audio_path, sr=_SR)
|
||||
y = np.asarray(y, dtype=np.float32)
|
||||
duration = len(y) / _SR
|
||||
beats, bar0 = grid_beats(markers, duration)
|
||||
|
||||
@@ -84,8 +84,8 @@ class Analysis:
|
||||
return self.columns.duration
|
||||
|
||||
|
||||
def _decode_pyav(path: Path) -> np.ndarray:
|
||||
"""Mono float32 at `SR`, via PyAV — FFmpeg's decoders, bundled in its wheel.
|
||||
def _decode_pyav(path: Path, sr: int = SR) -> np.ndarray:
|
||||
"""Mono float32 at `sr`, via PyAV — FFmpeg's decoders, bundled in its wheel.
|
||||
|
||||
The reason it is first: it decodes AAC (every Traktor `.stem.m4a`) on EVERY
|
||||
OS, where librosa needs CoreAudio (macOS only) or a system ffmpeg. Measured
|
||||
@@ -94,9 +94,11 @@ def _decode_pyav(path: Path) -> np.ndarray:
|
||||
"""
|
||||
import av
|
||||
|
||||
with av.open(str(path)) as container:
|
||||
from . import pyav
|
||||
|
||||
with pyav.open_input(path) as container:
|
||||
stream = container.streams.audio[0]
|
||||
resampler = av.AudioResampler(format="flt", layout="mono", rate=SR)
|
||||
resampler = av.AudioResampler(format="flt", layout="mono", rate=sr)
|
||||
chunks = []
|
||||
for frame in container.decode(stream):
|
||||
for out in resampler.resample(frame):
|
||||
@@ -120,16 +122,24 @@ def even_slices(n: int, k: int) -> list[slice]:
|
||||
return [slice(int(a), int(max(b, a + 1)) if n else 0) for a, b in zip(edges[:-1], edges[1:])]
|
||||
|
||||
|
||||
def _decode(path: Path) -> np.ndarray | None:
|
||||
def load(path: Path | str, sr: int = SR) -> tuple[np.ndarray, int]:
|
||||
"""Mono float32 at `sr` as `(y, sr)` — `librosa.load`'s shape, raising as it
|
||||
does. EVERY analysis decode goes through here, never `librosa.load` itself:
|
||||
librosa reads AAC only through CoreAudio or a system ffmpeg, so on Windows
|
||||
a `.stem.m4a` failed with "Format not recognised"."""
|
||||
try:
|
||||
return _decode_pyav(path)
|
||||
return _decode_pyav(Path(path), sr), sr
|
||||
except Exception as ex: # PyAV missing, or a file FFmpeg cannot open
|
||||
log.debug("PyAV could not decode %s (%s); trying librosa", path, ex)
|
||||
try:
|
||||
import librosa
|
||||
import librosa
|
||||
|
||||
y, _ = librosa.load(str(path), sr=SR, mono=True)
|
||||
return y
|
||||
y, _ = librosa.load(str(path), sr=sr, mono=True)
|
||||
return y, sr
|
||||
|
||||
|
||||
def _decode(path: Path) -> np.ndarray | None:
|
||||
try:
|
||||
return load(path)[0]
|
||||
except Exception as ex: # any decoder failure: no waveform, not a failed export
|
||||
log.warning("could not decode %s for a waveform: %s", path, ex)
|
||||
return None
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -69,6 +69,8 @@ from .schemas import (
|
||||
ExportSetOut,
|
||||
ExportPreview,
|
||||
Drive,
|
||||
DroppedFiles,
|
||||
DroppedPaths,
|
||||
FolderAddRequest,
|
||||
FolderTracks,
|
||||
FsEntry,
|
||||
@@ -120,8 +122,12 @@ app.add_middleware(
|
||||
"http://localhost:5173",
|
||||
"http://127.0.0.1:5173",
|
||||
# Packaged desktop app: the webview's origin when Tauri loads the built
|
||||
# frontend (macOS uses tauri://, Windows/Linux use https://tauri.localhost).
|
||||
# frontend. macOS uses tauri://; Windows/Linux default to
|
||||
# https://tauri.localhost, but lib.rs forces the http scheme
|
||||
# (use_https_scheme(false)) so the sidecar is not mixed content —
|
||||
# without the http origin here, the Windows app reaches no API at all.
|
||||
"tauri://localhost",
|
||||
"http://tauri.localhost",
|
||||
"https://tauri.localhost",
|
||||
],
|
||||
allow_methods=["*"],
|
||||
@@ -765,7 +771,10 @@ def run_export(set_id: str) -> JobStatus:
|
||||
built = exporter.plan(adapter, found)
|
||||
if built.blocked:
|
||||
raise HTTPException(409, built.blocked)
|
||||
job = JOBS.submit("export", lambda handle: exporter.run(adapter, found, built, handle))
|
||||
# A Konduktor setting, read when the export starts.
|
||||
root_folder = bool(prefs.load_prefs().get("exportRootFolder", False))
|
||||
job = JOBS.submit("export", lambda handle: exporter.run(
|
||||
adapter, found, built, handle, root_folder=root_folder))
|
||||
return JobStatus(**job.as_dict())
|
||||
|
||||
|
||||
@@ -1659,10 +1668,10 @@ def analyze_preview(body: AnalyzeRequest) -> AnalyzePreview:
|
||||
|
||||
def _decode_for_analysis(path: Path):
|
||||
"""Mono samples at the rate BOTH detectors work at (they share one decode)."""
|
||||
import librosa
|
||||
from .core import waveform
|
||||
|
||||
assert grid_detect._SR == key_detect.SR, "grid and key detection must share a sample rate"
|
||||
return librosa.load(str(path), sr=key_detect.SR, mono=True)
|
||||
return waveform.load(path, sr=key_detect.SR)
|
||||
|
||||
|
||||
def _analyse_one(a, track_id: str, body: AnalyzeRequest, result: dict) -> None:
|
||||
@@ -2183,6 +2192,50 @@ def source_track_stems(track_id: str) -> dict:
|
||||
|
||||
FOLDERS = FolderScanner()
|
||||
|
||||
# A remote library's content folder rides the same routes. Its paths carry this
|
||||
# prefix, so a path on the server can never be taken for the same path on this
|
||||
# computer — and the UI's folder view, deck and add dialog need no second set of
|
||||
# routes. The prefix alone is the content folder itself.
|
||||
SERVER_FOLDER = "server:"
|
||||
|
||||
|
||||
def _on_server(path: str) -> str | None:
|
||||
"""The server path behind a prefixed one ('' = the content folder), else None."""
|
||||
return path[len(SERVER_FOLDER):] if path.startswith(SERVER_FOLDER) else None
|
||||
|
||||
|
||||
def _server_track(track: Track) -> Track:
|
||||
return track.model_copy(update={"id": SERVER_FOLDER + track.id})
|
||||
|
||||
|
||||
def _folder_rows(dest, tracks: list[Track], held_of) -> tuple[list[Track], dict[str, str]]:
|
||||
"""A folder's files as table rows. Where the library holds a file, the row
|
||||
IS the library's track — its key, rating, comments, cues and plays, and
|
||||
its id, so it plays, edits and drags as the collection track it is
|
||||
(decided 2026-10-10) — else the file's own tags. Also returns library id →
|
||||
the file's folder id, for the rows that are library tracks: adding still
|
||||
speaks in folder ids."""
|
||||
rows: list[Track] = []
|
||||
files: dict[str, str] = {}
|
||||
for track in tracks:
|
||||
known = held_of(track)
|
||||
held = dest.track(known) if known else None
|
||||
if held is None or held.id in files:
|
||||
rows.append(track)
|
||||
continue
|
||||
rows.append(held)
|
||||
files[held.id] = track.id
|
||||
return rows, files
|
||||
|
||||
|
||||
def _server_file(track_id: str) -> tuple[object, str]:
|
||||
"""The remote adapter and the server path of a listed content-folder file."""
|
||||
adapter = _require_remote()
|
||||
raw = _on_server(track_id) or ""
|
||||
if adapter.listed_files([raw]) is None:
|
||||
raise HTTPException(404, "Track not found — browse to its folder first")
|
||||
return adapter, raw
|
||||
|
||||
|
||||
def _drive_of(path: Path, drives: list[dict]) -> dict | None:
|
||||
"""The drive `path` lives on: the longest drive root that contains it."""
|
||||
@@ -2209,6 +2262,10 @@ def fs_drives() -> list[Drive]:
|
||||
found = places.drives()
|
||||
libraries = sources()
|
||||
out = [Drive(**d) for d in found]
|
||||
if STATE.remote is not None and STATE.remote_config is not None:
|
||||
# The server holding the library, first: its content folder is where
|
||||
# this library's music is, and this computer cannot see it otherwise.
|
||||
out.insert(0, Drive(name=STATE.remote_config.name, path=SERVER_FOLDER, kind="server"))
|
||||
externals = [d for d in found if d["path"] != "/"]
|
||||
for lib in libraries:
|
||||
home = _drive_of(Path(lib.path), externals)
|
||||
@@ -2223,6 +2280,11 @@ def fs_drives() -> list[Drive]:
|
||||
@app.get("/api/fs/folders", response_model=list[FsEntry])
|
||||
def fs_folders(path: str) -> list[FsEntry]:
|
||||
"""The visible folders directly inside `path` — one level of a Files tree."""
|
||||
raw = _on_server(path)
|
||||
if raw is not None:
|
||||
listing = _require_remote().client.fs_list(raw or None)
|
||||
return [FsEntry(name=e["name"], path=SERVER_FOLDER + e["path"])
|
||||
for e in listing["entries"] if e["is_dir"]]
|
||||
base = Path(path).expanduser()
|
||||
if not base.is_dir():
|
||||
raise HTTPException(404, f"Not a folder: {base}")
|
||||
@@ -2236,20 +2298,43 @@ def _formats() -> list[str]:
|
||||
@app.get("/api/folder/tracks", response_model=FolderTracks)
|
||||
def folder_tracks(path: str) -> FolderTracks:
|
||||
"""The audio files directly inside a folder, and which are already held."""
|
||||
raw = _on_server(path)
|
||||
if raw is not None:
|
||||
adapter = _require_remote()
|
||||
listing = adapter.folder_listing(raw or None)
|
||||
rows, files = _folder_rows(adapter, [_server_track(t) for t in listing.tracks],
|
||||
lambda t: listing.held(t.id[len(SERVER_FOLDER):]))
|
||||
return FolderTracks(path=SERVER_FOLDER + listing.path, tracks=rows,
|
||||
in_collection=list(files), files=files, removable=False)
|
||||
base = Path(path).expanduser()
|
||||
if not base.is_dir():
|
||||
raise HTTPException(404, f"Not a folder: {base}")
|
||||
source = FOLDERS.scan(base, _formats())
|
||||
held = importer._existing_files(require_adapter())
|
||||
dest = require_adapter()
|
||||
held = importer._existing_files(dest)
|
||||
rows, files = _folder_rows(dest, source.tracks, lambda t: held.get(importer._key(Path(t.id))))
|
||||
drive = _drive_of(base, places.drives())
|
||||
return FolderTracks(
|
||||
path=str(base),
|
||||
tracks=source.tracks,
|
||||
in_collection=[t.id for t in source.tracks if importer._key(Path(t.id)) in held],
|
||||
tracks=rows,
|
||||
in_collection=list(files),
|
||||
files=files,
|
||||
removable=drive is None or drive["kind"] == "external",
|
||||
)
|
||||
|
||||
|
||||
@app.post("/api/folder/dropped", response_model=DroppedFiles)
|
||||
def folder_dropped(body: DroppedPaths) -> DroppedFiles:
|
||||
"""Files and folders dropped onto the window. Folders are searched all the
|
||||
way down; every audio file found is then addable and playable through the
|
||||
folder routes, as if it had been browsed to in the sidebar."""
|
||||
dest = require_adapter()
|
||||
dropped = FOLDERS.dropped(body.paths, _formats())
|
||||
held = importer._existing_files(dest)
|
||||
rows, files = _folder_rows(dest, dropped.tracks, lambda t: held.get(importer._key(Path(t.id))))
|
||||
return DroppedFiles(tracks=rows, files=files, skipped=dropped.skipped, truncated=dropped.truncated)
|
||||
|
||||
|
||||
def _folder_track(track_id: str) -> FolderSource:
|
||||
# Only a file a scan found. This is what keeps the audio route from being a
|
||||
# way to read any path on the disk.
|
||||
@@ -2263,11 +2348,17 @@ def _folder_track(track_id: str) -> FolderSource:
|
||||
def folder_capabilities(path: str) -> Capabilities:
|
||||
from .core.folder import capabilities_for
|
||||
|
||||
raw = _on_server(path)
|
||||
if raw is not None:
|
||||
return capabilities_for(Path(raw) if raw else Path(STATE.remote_config.name if STATE.remote_config else "Server"))
|
||||
return capabilities_for(Path(path))
|
||||
|
||||
|
||||
@app.get("/api/folder/tracks/cues", response_model=TrackCues)
|
||||
def folder_track_cues(track_id: str) -> TrackCues:
|
||||
if _on_server(track_id) is not None:
|
||||
_server_file(track_id)
|
||||
return TrackCues(cues=[], grid_markers=[])
|
||||
cues = _folder_track(track_id).track_cues(track_id)
|
||||
assert cues is not None
|
||||
return cues
|
||||
@@ -2275,7 +2366,11 @@ def folder_track_cues(track_id: str) -> TrackCues:
|
||||
|
||||
@app.get("/api/folder/tracks/audio")
|
||||
def folder_track_audio(track_id: str, stem: int | None = None) -> FileResponse:
|
||||
path = _folder_track(track_id).audio_path(track_id)
|
||||
if _on_server(track_id) is not None:
|
||||
adapter, raw = _server_file(track_id)
|
||||
path = adapter.folder_audio(raw) # this computer's copy, as for a library track
|
||||
else:
|
||||
path = _folder_track(track_id).audio_path(track_id)
|
||||
if path is None or not path.is_file():
|
||||
raise HTTPException(404, "Audio file not found")
|
||||
if stem is not None:
|
||||
@@ -2286,6 +2381,9 @@ def folder_track_audio(track_id: str, stem: int | None = None) -> FileResponse:
|
||||
|
||||
@app.get("/api/folder/tracks/stems")
|
||||
def folder_track_stems(track_id: str) -> dict:
|
||||
if _on_server(track_id) is not None:
|
||||
adapter, raw = _server_file(track_id)
|
||||
return _stem_layout_of(adapter.folder_audio(raw))
|
||||
return _stem_layout_of(_folder_track(track_id).audio_path(track_id))
|
||||
|
||||
|
||||
@@ -2295,6 +2393,34 @@ def _require_addable(dest) -> None:
|
||||
raise HTTPException(422, "Tracks cannot be added to this library")
|
||||
|
||||
|
||||
def _check_add_targets(dest, body: FolderAddRequest) -> None:
|
||||
if body.playlist_id is not None and dest.playlist_entries(body.playlist_id) is None:
|
||||
raise HTTPException(404, f"Playlist not found: {body.playlist_id}")
|
||||
if body.export_id is not None:
|
||||
if STATE.library_id is None or exports.get(STATE.library_id, body.export_id) is None:
|
||||
raise HTTPException(404, f"Export not found: {body.export_id}")
|
||||
|
||||
|
||||
def _is_server_add(body: FolderAddRequest) -> bool:
|
||||
on_server = [_on_server(t) is not None for t in body.track_ids]
|
||||
if any(on_server) and not all(on_server):
|
||||
raise HTTPException(400, "Files on the server and on this computer are added separately")
|
||||
return bool(on_server) and all(on_server)
|
||||
|
||||
|
||||
def _server_add_plan(body: FolderAddRequest):
|
||||
"""Files in the remote library's content folder: already where the library
|
||||
can reach them, so they are added IN PLACE — nothing uploaded, nothing asked."""
|
||||
dest = _require_remote()
|
||||
_require_addable(dest)
|
||||
paths = [_on_server(t) for t in body.track_ids]
|
||||
source = dest.listed_files(paths)
|
||||
if source is None:
|
||||
raise HTTPException(400, "No tracks to add")
|
||||
_check_add_targets(dest, body)
|
||||
return source, dest, importer.plan_on_host(source, paths)
|
||||
|
||||
|
||||
def _folder_add_plan(body: FolderAddRequest):
|
||||
dest = require_adapter()
|
||||
_require_addable(dest)
|
||||
@@ -2315,11 +2441,7 @@ def _folder_add_plan(body: FolderAddRequest):
|
||||
if not body.destination:
|
||||
raise HTTPException(400, "Copying needs a destination folder")
|
||||
destination = Path(body.destination).expanduser()
|
||||
if body.playlist_id is not None and dest.playlist_entries(body.playlist_id) is None:
|
||||
raise HTTPException(404, f"Playlist not found: {body.playlist_id}")
|
||||
if body.export_id is not None:
|
||||
if STATE.library_id is None or exports.get(STATE.library_id, body.export_id) is None:
|
||||
raise HTTPException(404, f"Export not found: {body.export_id}")
|
||||
_check_add_targets(dest, body)
|
||||
return source, dest, destination, importer.plan(
|
||||
source, dest, destination, track_ids=[t.id for t in tracks]
|
||||
)
|
||||
@@ -2327,6 +2449,11 @@ def _folder_add_plan(body: FolderAddRequest):
|
||||
|
||||
@app.post("/api/folder/add/preview")
|
||||
def folder_add_preview(body: FolderAddRequest) -> dict:
|
||||
if _is_server_add(body):
|
||||
_source, _dest, plan = _server_add_plan(body)
|
||||
out = plan.as_dict()
|
||||
out.update(total_bytes=0, free_bytes=None, enough_space=None, removable=False)
|
||||
return out
|
||||
_source, dest, destination, plan = _folder_add_plan(body)
|
||||
out = plan.as_dict(free_bytes=importer.free_bytes(destination, dest) if destination else None)
|
||||
if importer.places_audio(dest):
|
||||
@@ -2334,8 +2461,28 @@ def folder_add_preview(body: FolderAddRequest) -> dict:
|
||||
elif body.mode == "reference":
|
||||
# Nothing is copied, so there is no size to fit anywhere.
|
||||
out.update(total_bytes=0, free_bytes=None, enough_space=None)
|
||||
drive = _drive_of(Path(body.track_ids[0]), places.drives()) if body.track_ids else None
|
||||
out["removable"] = drive is None or drive["kind"] == "external"
|
||||
elif destination is not None:
|
||||
# Copying a file that is already in the import folder makes a second
|
||||
# copy beside it — legal, but rarely meant, so the dialog says so.
|
||||
home = destination.resolve()
|
||||
out["in_destination"] = sum(
|
||||
1 for t in plan.importable
|
||||
if t.source_path is not None and t.source_path.resolve().is_relative_to(home)
|
||||
)
|
||||
# Per FILE, not per request: a drop can mix the computer's own disk with a
|
||||
# stick, and only the files on the stick go missing when it is unplugged.
|
||||
drives = places.drives()
|
||||
external: dict[str, int] = {}
|
||||
for t in plan.importable:
|
||||
if t.source_path is None:
|
||||
continue
|
||||
drive = _drive_of(t.source_path, drives)
|
||||
if drive is None or drive["kind"] == "external":
|
||||
name = drive["name"] if drive else str(t.source_path.anchor or t.source_path.parent)
|
||||
external[name] = external.get(name, 0) + 1
|
||||
out["removable"] = bool(external)
|
||||
out["removable_count"] = sum(external.values())
|
||||
out["removable_drives"] = sorted(external)
|
||||
return out
|
||||
|
||||
|
||||
@@ -2343,10 +2490,16 @@ def folder_add_preview(body: FolderAddRequest) -> dict:
|
||||
def folder_add(body: FolderAddRequest) -> JobStatus:
|
||||
"""Add browsed files to the collection. A job, like import: copying can be long."""
|
||||
_require_no_pending_stems("Adding files")
|
||||
source, dest, destination, plan = _folder_add_plan(body)
|
||||
in_place = _is_server_add(body)
|
||||
if in_place:
|
||||
source, dest, plan = _server_add_plan(body)
|
||||
destination = None
|
||||
else:
|
||||
source, dest, destination, plan = _folder_add_plan(body)
|
||||
if not plan.importable and not plan.existing:
|
||||
raise HTTPException(400, "Nothing to add (none of those files exist)")
|
||||
if body.mode == "copy" or importer.places_audio(dest):
|
||||
# Nothing is copied in place, so there is no space to check.
|
||||
if not in_place and (body.mode == "copy" or importer.places_audio(dest)):
|
||||
free = importer.free_bytes(destination, dest)
|
||||
needed = importer.placed_bytes(dest, plan) if importer.places_audio(dest) else plan.total_bytes
|
||||
if free is not None and free < needed + importer.SPACE_HEADROOM:
|
||||
@@ -2362,7 +2515,7 @@ def folder_add(body: FolderAddRequest) -> JobStatus:
|
||||
def work(handle):
|
||||
result = importer.run(
|
||||
source, dest, plan, handle,
|
||||
reference=body.mode == "reference",
|
||||
reference=in_place or body.mode == "reference",
|
||||
into_playlist=body.playlist_id,
|
||||
)
|
||||
# Export sets are Konduktor's own data, not the library's, so they are
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,14 +537,37 @@ class FolderTracks(BaseModel):
|
||||
"""The audio files directly inside one folder, projected as tracks."""
|
||||
|
||||
path: str
|
||||
# A file the collection holds is listed AS the collection's track (its id,
|
||||
# key, rating, cues…); any other file as its own tags, id = its path.
|
||||
tracks: list[Track]
|
||||
# Ids (= absolute paths) of the files the collection already points at.
|
||||
# Collection ids of the rows that are collection tracks.
|
||||
in_collection: list[str]
|
||||
# Those rows' collection id → the file's folder id, which adding takes.
|
||||
files: dict[str, str] = {}
|
||||
# On an external drive: a track referenced in place goes missing when the
|
||||
# drive is unplugged, which the add dialog has to say.
|
||||
removable: bool
|
||||
|
||||
|
||||
class DroppedPaths(BaseModel):
|
||||
"""Files and folders dropped onto the window from Finder / Explorer."""
|
||||
|
||||
paths: list[str]
|
||||
|
||||
|
||||
class DroppedFiles(BaseModel):
|
||||
"""What a drop resolved to: the audio in it, as a folder lists its files."""
|
||||
|
||||
tracks: list[Track]
|
||||
# As FolderTracks: rows the collection holds are its tracks, and this maps
|
||||
# their collection id back to the file's folder id, which adding takes.
|
||||
files: dict[str, str] = {}
|
||||
# Dropped files that are not audio the library can hold, or are gone.
|
||||
skipped: int = 0
|
||||
# Too many files: only the first MAX_DROPPED are here.
|
||||
truncated: bool = False
|
||||
|
||||
|
||||
class FolderAddRequest(BaseModel):
|
||||
"""Add browsed files to the collection, and optionally to a playlist/export.
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -39,11 +39,25 @@ _BYTES_PER_SECOND = {256_000: 5 * 256_000 / 8 * 1.03, 320_000: 5 * 320_000 / 8 *
|
||||
_WORK_BYTES_PER_SECOND = 5 * 2 * 4 * sf.SR
|
||||
|
||||
|
||||
#: Shares of ONE track's conversion time, for the status bar's within-track
|
||||
#: progress (measured on the M3 Pro: decode ~1 s, separate ~50 s, encode +
|
||||
#: verify ~4 s for a 4-minute track).
|
||||
_DECODE_SHARE = 0.03
|
||||
_SEPARATE_SHARE = 0.90
|
||||
#: Shares of ONE track's conversion time (decode, separate; encoding + verifying
|
||||
#: take the rest), for the status bar's within-track progress, by AAC encoder.
|
||||
#: Measured: `aac_at` on the M3 Pro (4-minute track: decode ~1 s, separate
|
||||
#: ~50 s, encode + verify ~4 s); `aac` on an i7-9750H + RTX 2070 (5-minute
|
||||
#: track: decode 0.5 s, separate ~102 s, encode ~38 s on five threads, verify ~1 s).
|
||||
_SHARES = {"aac_at": (0.03, 0.90), "aac": (0.01, 0.71)}
|
||||
|
||||
|
||||
def track_shares(encoder: str) -> tuple[float, float]:
|
||||
return _SHARES.get(encoder, _SHARES["aac"])
|
||||
|
||||
|
||||
def encode_reporter(handle, start: float, end: float = 0.99) -> Callable[[float], None]:
|
||||
"""`on_encode` for `stem_file.build`: the encode runs from `start` to `end`
|
||||
of the track, and the ~1 s of tags + verification after it reads as such."""
|
||||
def report(f: float) -> None:
|
||||
frac = start + f * (end - start)
|
||||
handle.progress(fraction=frac, status=f"{'verifying' if f >= 1 else 'encoding'} {frac * 100:.0f} %")
|
||||
return report
|
||||
|
||||
|
||||
class ConvertError(Exception):
|
||||
@@ -227,6 +241,7 @@ def run(handle, adapter, planned: Plan, opts: Options, pending: Pending, *,
|
||||
work = work_root() / f"batch-{id(handle):x}"
|
||||
finished: list[tuple[Planned, dict, sf.Written]] = []
|
||||
needs_engine = any(p.reuse is None for p in items)
|
||||
encoder = sf.default_encoder()
|
||||
if needs_engine and not mgr.ready():
|
||||
raise ConvertError("The stem engine is not installed")
|
||||
|
||||
@@ -258,22 +273,22 @@ def run(handle, adapter, planned: Plan, opts: Options, pending: Pending, *,
|
||||
"stem": str(item.target), "state": "converting", "facts": source_facts(item.source)})
|
||||
item.target.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Of a TRACK's time, separation is nearly all (~90 % on MPS);
|
||||
# decoding before it and encoding + verifying after share the rest.
|
||||
# Of a TRACK's time, separation is nearly all; decoding before it
|
||||
# and encoding + verifying after share the rest.
|
||||
decode_share, separate_share = track_shares(encoder)
|
||||
|
||||
def on_progress(f: float) -> None:
|
||||
frac = _DECODE_SHARE + f * (_SEPARATE_SHARE)
|
||||
frac = decode_share + f * separate_share
|
||||
handle.progress(fraction=frac, status=f"separating {frac * 100:.0f} %")
|
||||
|
||||
def separate(pcm):
|
||||
handle.progress(fraction=_DECODE_SHARE, status=f"separating {_DECODE_SHARE * 100:.0f} %")
|
||||
stems = engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled)
|
||||
done_at = _DECODE_SHARE + _SEPARATE_SHARE
|
||||
handle.progress(fraction=done_at, status=f"encoding {done_at * 100:.0f} %")
|
||||
return stems
|
||||
handle.progress(fraction=decode_share, status=f"separating {decode_share * 100:.0f} %")
|
||||
return engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled)
|
||||
|
||||
handle.progress(status="decoding 0 %")
|
||||
try:
|
||||
written = sf.build(item.source, partial, separate, checkpoint=checkpoint)
|
||||
written = sf.build(item.source, partial, separate, encoder=encoder, checkpoint=checkpoint,
|
||||
on_encode=encode_reporter(handle, decode_share + separate_share))
|
||||
except (_Cancel, EngineCancelled):
|
||||
partial.unlink(missing_ok=True)
|
||||
pending.drop([pitem])
|
||||
|
||||
@@ -153,13 +153,12 @@ def run(handle, adapter, planned: RemotePlan, opts: convert.Options, *, still_cu
|
||||
|
||||
def separate(pcm):
|
||||
handle.progress(fraction=0.05, status="separating 5 %")
|
||||
stems = engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled)
|
||||
handle.progress(fraction=0.85, status="encoding 85 %")
|
||||
return stems
|
||||
return engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled)
|
||||
|
||||
partial = work / f"{n}.stem.m4a"
|
||||
try:
|
||||
written = sf.build(local, partial, separate, checkpoint=checkpoint)
|
||||
written = sf.build(local, partial, separate, checkpoint=checkpoint,
|
||||
on_encode=convert.encode_reporter(handle, 0.85, 0.9))
|
||||
except (convert._Cancel, EngineCancelled):
|
||||
partial.unlink(missing_ok=True)
|
||||
raise
|
||||
|
||||
@@ -1,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
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -28,16 +28,38 @@ def _watch_parent_and_exit() -> None:
|
||||
shut down, so the backend can never be orphaned (the Rust-side kill-on-exit
|
||||
only covers the graceful path). When run standalone from a terminal, stdin is
|
||||
a TTY and this blocks harmlessly forever.
|
||||
|
||||
NOT on Windows: there a read left pending on the stdin pipe stalls loading
|
||||
scipy's OpenBLAS DLL in any other thread, forever — so the first analysis
|
||||
hung the packaged app (dev runs no watcher). Measured 2026-10-12 with plain
|
||||
Python, through the CRT and through kernel32.ReadFile alike. Windows waits
|
||||
on the parent PROCESS instead, which also covers a crash.
|
||||
"""
|
||||
try:
|
||||
while sys.stdin.buffer.read(1):
|
||||
if sys.platform == "win32":
|
||||
_wait_for_parent_process()
|
||||
else:
|
||||
try:
|
||||
while sys.stdin.buffer.read(1):
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
_release_remote()
|
||||
os._exit(0)
|
||||
|
||||
|
||||
def _wait_for_parent_process() -> None:
|
||||
"""Block until the process that started us exits (Windows only)."""
|
||||
import ctypes
|
||||
|
||||
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
kernel32.OpenProcess.restype = ctypes.c_void_p
|
||||
kernel32.WaitForSingleObject.argtypes = (ctypes.c_void_p, ctypes.c_uint32)
|
||||
synchronize, infinite = 0x00100000, 0xFFFFFFFF
|
||||
handle = kernel32.OpenProcess(synchronize, False, os.getppid())
|
||||
if handle: # None: the parent is already gone
|
||||
kernel32.WaitForSingleObject(handle, infinite)
|
||||
|
||||
|
||||
def _release_remote() -> None:
|
||||
"""Hand back a remote library's session on the way out, so the next
|
||||
computer opens it at once instead of waiting out the lease (or being asked
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -154,7 +154,11 @@ with TestClient(main.app, raise_server_exceptions=False) as c:
|
||||
check("it is in the playlist", a.playlist_entries(playlist) == [added])
|
||||
check("it was saved, not left pending", not a.dirty)
|
||||
body = c.get("/api/folder/tracks", params={"path": str(music)}).json()
|
||||
check("the folder now marks it as held", body["in_collection"] == [str(one)], str(body["in_collection"]))
|
||||
check("the folder now marks it as held", body["in_collection"] == [added], str(body["in_collection"]))
|
||||
row = next((t for t in body["tracks"] if t["id"] == added), None)
|
||||
check("…its row IS the collection track (its id and data), mapped back to the file",
|
||||
row is not None and body["files"] == {added: str(one)}
|
||||
and row["import_date"] == a.track(added).import_date, str(body["files"]))
|
||||
|
||||
print("== a held file is never added twice, but still reaches its target ==")
|
||||
library = STATE.library_id
|
||||
@@ -193,6 +197,82 @@ with TestClient(main.app, raise_server_exceptions=False) as c:
|
||||
c.post("/api/folder/add/preview",
|
||||
json={"track_ids": ["/etc/passwd"], "mode": "reference"}).status_code == 404)
|
||||
|
||||
print("== a drop onto the window: folders all the way down, files as themselves ==")
|
||||
drop = Path(tempfile.mkdtemp()) / "Dropped"
|
||||
d_a = flac(drop / "Album" / "a.flac", title="Dropped A")
|
||||
d_b = flac(drop / "Album" / "CD2" / "b.flac")
|
||||
(drop / "Album" / "cover.jpg").write_bytes(b"not audio")
|
||||
flac(drop / "Album" / ".cache" / "h.flac")
|
||||
single = flac(drop / "Loose" / "single.flac", title="Single")
|
||||
sibling = flac(drop / "Loose" / "sibling.flac")
|
||||
(drop / "Loose" / "readme.txt").write_text("not audio")
|
||||
r = c.post("/api/folder/dropped", json={"paths": [
|
||||
str(drop / "Album"), str(single), str(drop / "Loose" / "readme.txt"),
|
||||
str(drop / "gone.flac"), str(single), str(d_a),
|
||||
]})
|
||||
check("answers 200", r.status_code == 200, r.text[:300])
|
||||
body = r.json()
|
||||
ids = [t["id"] for t in body["tracks"]]
|
||||
check("the folder's audio, subfolders included, then the file — each once",
|
||||
ids == [str(d_a), str(d_b), str(single)], str(ids))
|
||||
check("a hidden folder inside is left out", str(drop / "Album" / ".cache" / "h.flac") not in ids)
|
||||
check("a dropped non-audio file and a missing one are counted as skipped",
|
||||
body["skipped"] == 2, str(body["skipped"]))
|
||||
check("non-audio INSIDE a dropped folder is not counted", body["skipped"] == 2)
|
||||
check("tags are read", body["tracks"][0]["title"] == "Dropped A")
|
||||
check("not truncated", body["truncated"] is False)
|
||||
check("a dropped file streams",
|
||||
c.get("/api/folder/tracks/audio", params={"track_id": str(single)}).status_code == 200)
|
||||
check("so does one found inside a dropped folder",
|
||||
c.get("/api/folder/tracks/audio", params={"track_id": str(d_b)}).status_code == 200)
|
||||
check("but not its undropped sibling",
|
||||
c.get("/api/folder/tracks/audio", params={"track_id": str(sibling)}).status_code == 404)
|
||||
listed = [t["id"] for t in c.get("/api/folder/tracks", params={"path": str(drop / "Loose")}).json()["tracks"]]
|
||||
check("browsing that folder afterwards still lists ALL of it",
|
||||
listed == [str(sibling), str(single)], str(listed))
|
||||
r = c.post("/api/folder/dropped", json={"paths": [str(drop / "Loose" / "readme.txt")]})
|
||||
check("a non-audio file is never made streamable",
|
||||
r.json()["tracks"] == [] and c.get("/api/folder/tracks/audio", params={
|
||||
"track_id": str(drop / "Loose" / "readme.txt")}).status_code == 404)
|
||||
capped = main.FOLDERS.dropped([str(drop / "Album")], main._formats(), limit=1)
|
||||
check("past the cap the rest are left out, and it says so",
|
||||
len(capped.tracks) == 1 and capped.truncated)
|
||||
|
||||
body = c.post("/api/folder/dropped", json={"paths": [str(one)]}).json()
|
||||
check("a dropped file the collection holds IS its collection track",
|
||||
[t["id"] for t in body["tracks"]] == [added] and body["files"] == {added: str(one)},
|
||||
str(body))
|
||||
|
||||
req = {"track_ids": [str(d_b)], "mode": "copy", "destination": str(drop / "Album")}
|
||||
p = c.post("/api/folder/add/preview", json=req).json()
|
||||
check("copying into the folder they are already in is flagged", p.get("in_destination") == 1, str(p))
|
||||
req["destination"] = str(Path(tempfile.mkdtemp()))
|
||||
p = c.post("/api/folder/add/preview", json=req).json()
|
||||
check("…and not elsewhere", p.get("in_destination") == 0, str(p))
|
||||
|
||||
real_drives = main.places.drives
|
||||
main.places.drives = lambda: [
|
||||
{"name": "Computer", "path": drop.anchor, "kind": "local"},
|
||||
{"name": "Stick", "path": str(drop / "Album"), "kind": "external"},
|
||||
]
|
||||
try:
|
||||
req = {"track_ids": [str(d_a), str(single)], "mode": "reference"}
|
||||
p = c.post("/api/folder/add/preview", json=req).json()
|
||||
check("the external-drive warning counts files per drive, not by the first",
|
||||
p["removable"] is True and p["removable_count"] == 1 and p["removable_drives"] == ["Stick"],
|
||||
str(p))
|
||||
p = c.post("/api/folder/add/preview", json={"track_ids": [str(single), str(d_a)],
|
||||
"mode": "reference"}).json()
|
||||
check("…whichever file comes first", p["removable_count"] == 1, str(p))
|
||||
finally:
|
||||
main.places.drives = real_drives
|
||||
|
||||
n = len(a.tracks)
|
||||
job = wait(c, c.post("/api/folder/add", json={"track_ids": [str(d_a), str(single)],
|
||||
"mode": "reference"}).json())
|
||||
check("dropped files are added like browsed ones", job["state"] == "done" and len(a.tracks) == n + 2,
|
||||
str(job))
|
||||
|
||||
print("== Rekordbox: the same route adds to a master.db ==")
|
||||
from konduktor.adapters.rekordbox import discovery as rb_discovery
|
||||
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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"))
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -262,11 +262,71 @@ def stop_in_encode():
|
||||
raise Stop()
|
||||
|
||||
|
||||
def encoder_threads():
|
||||
import threading
|
||||
|
||||
return [t.name for t in threading.enumerate() if t.name.startswith("stem-encode-")]
|
||||
|
||||
|
||||
try:
|
||||
sf.build(MP3, tmp / "cancelled.partial", fake_separate, encoder="aac", checkpoint=stop_in_encode)
|
||||
check("a checkpoint that raises stops the build", False, "it finished")
|
||||
except Stop:
|
||||
check("a checkpoint that raises stops the build", True)
|
||||
check("…and no encoder thread outlives it", not encoder_threads(), str(encoder_threads()))
|
||||
|
||||
print("== 6. the encode runs on one thread per stream ==")
|
||||
|
||||
|
||||
def encode_single_threaded(fp, tracks, *, bit_rate, encoder):
|
||||
"""The encode as it was before it was threaded: the reference for the bytes."""
|
||||
tb = fractions.Fraction(1, SR)
|
||||
c = av.open(fp, "w", format="ipod")
|
||||
try:
|
||||
streams = []
|
||||
for k in range(len(tracks)):
|
||||
s = c.add_stream(encoder, rate=SR, layout="stereo")
|
||||
s.bit_rate = bit_rate
|
||||
if k:
|
||||
s.disposition = 0
|
||||
streams.append(s)
|
||||
for offset in range(0, tracks[0].shape[1], sf.FRAME):
|
||||
for s, x in zip(streams, tracks):
|
||||
f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, offset:offset + sf.FRAME]),
|
||||
format="fltp", layout="stereo")
|
||||
f.sample_rate, f.pts, f.time_base = SR, offset, tb
|
||||
for p in s.encode(f):
|
||||
c.mux(p)
|
||||
for s in streams:
|
||||
for p in s.encode(None):
|
||||
c.mux(p)
|
||||
finally:
|
||||
c.close()
|
||||
|
||||
|
||||
source = sf.decode(MP3)
|
||||
# A length that is not a whole number of frames, and stems that differ from the mix.
|
||||
five = [np.ascontiguousarray(t[:, :-333]) for t in (source.pcm, *fake_separate(source.pcm))]
|
||||
for enc in encoders:
|
||||
ref, par = tmp / f"ref.{enc}.m4a", tmp / f"par.{enc}.m4a"
|
||||
with open(ref, "wb") as fp:
|
||||
encode_single_threaded(fp, five, bit_rate=320_000, encoder=enc)
|
||||
seen = []
|
||||
with open(par, "wb") as fp:
|
||||
sf._encode(fp, five, bit_rate=320_000, encoder=enc, checkpoint=None, progress=seen.append)
|
||||
check(f"{enc}: the threaded encode is byte-identical to the single-threaded one",
|
||||
ref.read_bytes() == par.read_bytes(), f"{ref.stat().st_size} vs {par.stat().st_size} bytes")
|
||||
check(f"{enc}: progress runs 0 -> 1, never backwards",
|
||||
len(seen) >= 3 and seen[0] == 0 and seen[-1] == 1.0 and seen == sorted(seen), str(seen))
|
||||
|
||||
try:
|
||||
with open(tmp / "broken.m4a", "wb") as fp:
|
||||
# A mono array in a stereo stream: that stream's thread fails on its first frame.
|
||||
sf._encode(fp, [five[0], five[1][:1], *five[2:]], bit_rate=320_000, encoder="aac", checkpoint=None)
|
||||
check("a failing encoder thread fails the encode", False, "it finished")
|
||||
except Exception as ex: # noqa: BLE001
|
||||
check("a failing encoder thread fails the encode, with its own error", not isinstance(ex, Stop), repr(ex))
|
||||
check("…and no encoder thread outlives it", not encoder_threads(), str(encoder_threads()))
|
||||
|
||||
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
# Build the Konduktor desktop app on Windows: freeze + stage the backend sidecar,
|
||||
# then build the Tauri installers. First run? See one-time setup in
|
||||
# BUILDING-WINDOWS.md (the backend venv with requirements-build.txt, and
|
||||
# `npm install`).
|
||||
#
|
||||
# .\build.ps1 # sidecar + app (release installers)
|
||||
# .\build.ps1 -SkipSidecar # frontend-only change: reuse the staged sidecar
|
||||
# .\build.ps1 --debug # anything else is passed on to `tauri build`
|
||||
# (if scripts are blocked: powershell -ExecutionPolicy Bypass -File .\build.ps1)
|
||||
param([switch]$SkipSidecar)
|
||||
$ErrorActionPreference = "Stop"
|
||||
$Root = $PSScriptRoot
|
||||
$TauriArgs = $args
|
||||
|
||||
$Py = Join-Path $Root "backend\.venv\Scripts\python.exe"
|
||||
if (-not (Test-Path $Py)) { throw "No backend venv at backend\.venv - see BUILDING-WINDOWS.md for setup." }
|
||||
if (-not (Test-Path (Join-Path $Root "frontend\node_modules"))) { throw "No frontend\node_modules - run ``npm install`` in frontend first." }
|
||||
$Staged = Join-Path $Root "frontend\src-tauri\binaries\konduktor-sidecar\konduktor-sidecar.exe"
|
||||
|
||||
# rustup puts cargo in %USERPROFILE%\.cargo\bin and adds it to PATH only for
|
||||
# terminals opened AFTER the install - so find it there before giving up, rather
|
||||
# than failing ten minutes in, after the sidecar build.
|
||||
if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) {
|
||||
$CargoBin = Join-Path $env:USERPROFILE ".cargo\bin"
|
||||
if (-not (Test-Path (Join-Path $CargoBin "cargo.exe"))) { throw "No Rust toolchain (cargo) - install it from https://rustup.rs, see BUILDING-WINDOWS.md." }
|
||||
$env:PATH = "$CargoBin;$env:PATH"
|
||||
}
|
||||
|
||||
$Started = Get-Date
|
||||
# build_sidecar.ps1 changes directory itself, and a location change outlives the
|
||||
# script it was made in - so put ours back whatever happens.
|
||||
Push-Location $Root
|
||||
try {
|
||||
if ($SkipSidecar) {
|
||||
if (-not (Test-Path $Staged)) { throw "No staged sidecar to reuse - run without -SkipSidecar first." }
|
||||
Write-Host "==> Reusing the staged sidecar (-SkipSidecar)"
|
||||
}
|
||||
else {
|
||||
Write-Host "==> 1/2 Freezing the backend sidecar"
|
||||
& (Join-Path $Root "backend\build_sidecar.ps1")
|
||||
}
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "==> 2/2 Building the app (tauri build $TauriArgs)"
|
||||
Set-Location (Join-Path $Root "frontend")
|
||||
# npx is a .cmd and cargo reports progress on stderr: relax "Stop" for the
|
||||
# call (as build_sidecar.ps1 does for PyInstaller) and judge by exit code.
|
||||
$ErrorActionPreference = "Continue"
|
||||
& npx tauri build @TauriArgs
|
||||
$code = $LASTEXITCODE
|
||||
$ErrorActionPreference = "Stop"
|
||||
if ($code -ne 0) { throw "tauri build failed ($code)" }
|
||||
}
|
||||
finally {
|
||||
Pop-Location
|
||||
}
|
||||
|
||||
# List what this run produced (release or --debug profile).
|
||||
$Bundles = Join-Path $Root "frontend\src-tauri\target\*\bundle"
|
||||
$Built = Get-ChildItem -Path "$Bundles\nsis\*-setup.exe", "$Bundles\msi\*.msi" -File -ErrorAction SilentlyContinue |
|
||||
Where-Object { $_.LastWriteTime -ge $Started }
|
||||
Write-Host ""
|
||||
if ($Built) {
|
||||
Write-Host "Installers:"
|
||||
$Built | ForEach-Object { Write-Host " $($_.FullName)" }
|
||||
}
|
||||
else {
|
||||
Write-Host "Done (no installer bundled - see frontend\src-tauri\target\)."
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
# Start both Konduktor servers (backend + frontend) together - the Windows
|
||||
# counterpart of dev.sh. Ctrl-C stops both. First run? See one-time setup in
|
||||
# BUILDING-WINDOWS.md (the backend venv and `npm install`).
|
||||
#
|
||||
# .\dev.ps1
|
||||
# (if scripts are blocked: powershell -ExecutionPolicy Bypass -File .\dev.ps1)
|
||||
$ErrorActionPreference = "Stop"
|
||||
$Root = $PSScriptRoot
|
||||
|
||||
$Py = Join-Path $Root "backend\.venv\Scripts\python.exe"
|
||||
if (-not (Test-Path $Py)) { throw "No backend venv at backend\.venv - see BUILDING-WINDOWS.md for setup." }
|
||||
# Vite through node, not `npm run dev`: npm is a .cmd batch file, and Ctrl-C in a
|
||||
# shared console makes cmd ask "Terminate batch job (Y/N)?" instead of exiting.
|
||||
$Vite = Join-Path $Root "frontend\node_modules\vite\bin\vite.js"
|
||||
if (-not (Test-Path $Vite)) { throw "No frontend\node_modules - run ``npm install`` in frontend first." }
|
||||
|
||||
# Backend (FastAPI on :8000)
|
||||
$Backend = Start-Process -FilePath $Py -NoNewWindow -PassThru `
|
||||
-ArgumentList "-m", "uvicorn", "konduktor.main:app", "--reload", "--port", "8000", "--app-dir", "`"$Root\backend`""
|
||||
|
||||
# Frontend (Vite on :5173, proxies /api -> :8000)
|
||||
$Frontend = Start-Process -FilePath "node" -NoNewWindow -PassThru `
|
||||
-WorkingDirectory (Join-Path $Root "frontend") -ArgumentList "`"$Vite`""
|
||||
|
||||
Write-Host ""
|
||||
Write-Host " Konduktor is starting..."
|
||||
Write-Host " -> App: http://localhost:5173"
|
||||
Write-Host " -> API docs: http://localhost:8000/docs"
|
||||
Write-Host " (Ctrl-C to stop both)"
|
||||
Write-Host ""
|
||||
|
||||
try {
|
||||
# If either one dies, stop the other rather than leave half a dev setup.
|
||||
while (-not $Backend.HasExited -and -not $Frontend.HasExited) { Start-Sleep -Milliseconds 500 }
|
||||
}
|
||||
finally {
|
||||
# Kill the whole tree: uvicorn --reload runs the server in a child process,
|
||||
# which would otherwise keep :8000 bound after the reloader has gone.
|
||||
foreach ($p in $Backend, $Frontend) {
|
||||
if ($p -and -not $p.HasExited) { & taskkill /PID $p.Id /T /F 2>&1 | Out-Null }
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
|
After Width: | Height: | Size: 121 KiB |
|
After Width: | Height: | Size: 325 KiB |
|
After Width: | Height: | Size: 543 KiB |
|
After Width: | Height: | Size: 184 KiB |
|
After Width: | Height: | Size: 1.1 MiB |
|
After Width: | Height: | Size: 320 KiB |
|
After Width: | Height: | Size: 522 KiB |
@@ -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,7 +1,7 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"private": true,
|
||||
"version": "0.2.4",
|
||||
"version": "0.2.7",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -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/
|
||||
@@ -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/>
|
||||
|
||||
@@ -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(())
|
||||
})
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"targets": "all",
|
||||
"externalBin": ["binaries/konduktor-sidecar"],
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
|
||||
@@ -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/" }
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,16 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import type { ColumnSizingState, SortingState, VisibilityState } from '@tanstack/react-table'
|
||||
import { CapabilitiesContext, slotLabeller } from './lib/capabilities'
|
||||
import { removalNote, writeHint } from './lib/platformCopy'
|
||||
import { readOnlyNotice, removalNote, writeHint } from './lib/platformCopy'
|
||||
import { invalidateTrackLists } from './lib/trackQueries'
|
||||
import { addTracksToPlaylist } from './lib/addTracks'
|
||||
import { useDropTarget } from './lib/drag'
|
||||
import { useDragPayload, useDropTarget } from './lib/drag'
|
||||
import { useNativeFileDrop } from './lib/fileDrop'
|
||||
import { api, type AnalyzeOptions, type AnalyzeResult, type CueBatchResult, type AutoCueSlot, type PlaylistNode, type StemBatchResult, type Track, type TrackOrigin } from './api'
|
||||
import { confirmDiscardUnsaved } from './lib/unsaved'
|
||||
import { askConfirm } from './lib/confirm'
|
||||
import {
|
||||
COLUMN_MENU,
|
||||
DEFAULT_COLUMN_ORDER,
|
||||
@@ -29,7 +32,7 @@ import { RelocateDialog } from './components/RelocateDialog'
|
||||
import { HistoryPanel } from './components/HistoryPanel'
|
||||
import { PrepStrip } from './components/PrepStrip'
|
||||
import { ImportDialog } from './components/ImportDialog'
|
||||
import { AddFilesDialog, type AddTarget } from './components/AddFilesDialog'
|
||||
import { AddFilesDialog, type AddTarget, type ForeignOrigin } from './components/AddFilesDialog'
|
||||
import { ConvertStemsDialog } from './components/ConvertStemsDialog'
|
||||
import { StemReportDialog } from './components/StemReportDialog'
|
||||
import { SetPositionDialog } from './components/SetPositionDialog'
|
||||
@@ -80,8 +83,15 @@ export default function App() {
|
||||
const [prepOrigin, setPrepOrigin] = useState<TrackOrigin>('collection')
|
||||
// The view's origin, read by the load callbacks below (defined before it).
|
||||
const viewOriginRef = useRef<TrackOrigin>('collection')
|
||||
// Browsed files being added to the collection (and maybe a playlist/export).
|
||||
const [adding, setAdding] = useState<{ ids: string[]; target: AddTarget | null } | null>(null)
|
||||
// The browsed folder's rows that ARE collection tracks: collection id → the
|
||||
// file's folder id. A ref, for the callbacks below that outlive a render.
|
||||
const folderFilesRef = useRef<Record<string, string>>({})
|
||||
// Browsed (or dropped) files being added to the collection (and maybe a
|
||||
// playlist/export). `note` says what a drop left out.
|
||||
const [adding, setAdding] = useState<{ ids: string[]; target: AddTarget | null; note?: string | null } | null>(null)
|
||||
// How many dropped items are being read (a dropped folder is searched all
|
||||
// the way down, which can take a while): shown until the dialog opens.
|
||||
const [readingDrop, setReadingDrop] = useState(0)
|
||||
const [playRequest, setPlayRequest] = useState(0) // bump → deck loads & auto-plays
|
||||
const [importing, setImporting] = useState(false)
|
||||
// Device tracks dropped on a collection playlist / export: Import, with
|
||||
@@ -108,7 +118,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 +319,11 @@ export default function App() {
|
||||
() => new Set(folderView.data?.in_collection ?? []),
|
||||
[folderView.data],
|
||||
)
|
||||
const folderFiles = useMemo(() => folderView.data?.files ?? {}, [folderView.data])
|
||||
folderFilesRef.current = viewingFolder ? folderFiles : {}
|
||||
// Adding speaks in FOLDER ids; a row the collection holds carries its
|
||||
// collection id, and maps back (the add dialog then reports it as held).
|
||||
const toFolderIds = (ids: string[]) => ids.map((id) => folderFiles[id] ?? id)
|
||||
viewOriginRef.current = viewingDevice ? 'device' : viewingFolder ? 'folder' : 'collection'
|
||||
// Tracks in view belong to ANOTHER library (a device) or to none (a folder),
|
||||
// so no collection command may be offered on them: their ids mean nothing to
|
||||
@@ -366,18 +383,124 @@ export default function App() {
|
||||
// export: they are not in the collection yet, so the drop opens the dialog
|
||||
// that adds them — with that target filled in, and copy-vs-reference still
|
||||
// asked (decided 2026-10-06).
|
||||
const addForeign = useCallback(
|
||||
(origin: TrackOrigin, ids: string[], target: AddTarget) => {
|
||||
if (origin === 'folder') setAdding({ ids, target })
|
||||
else if (origin === 'device') setImportDrop({ ids, target })
|
||||
// Files dragged in from Finder / Explorer (lib/fileDrop.ts). What is in them
|
||||
// is read first — folders all the way down — and then they go where a
|
||||
// browsed folder's files go: the add dialog, copy-vs-reference asked.
|
||||
const readDrop = useCallback(
|
||||
async (paths: string[]) => {
|
||||
setReadingDrop(paths.length)
|
||||
try {
|
||||
return await api.folderDropped(paths)
|
||||
} catch (e) {
|
||||
onError((e as Error).message)
|
||||
return null
|
||||
} finally {
|
||||
setReadingDrop(0)
|
||||
}
|
||||
},
|
||||
[],
|
||||
[onError],
|
||||
)
|
||||
const dropFiles = useCallback(
|
||||
async (paths: string[], target: AddTarget | null) => {
|
||||
const r = await readDrop(paths)
|
||||
if (!r) return
|
||||
if (!r.tracks.length) {
|
||||
onError(
|
||||
paths.length === 1 && r.skipped
|
||||
? 'That is not an audio file this library can hold.'
|
||||
: 'No audio files this library can hold were found there.',
|
||||
)
|
||||
return
|
||||
}
|
||||
const notes: string[] = []
|
||||
if (r.skipped)
|
||||
notes.push(
|
||||
r.skipped === 1
|
||||
? '1 dropped item is not audio this library can hold and was left out.'
|
||||
: `${r.skipped} dropped items are not audio this library can hold and were left out.`,
|
||||
)
|
||||
if (r.truncated) notes.push(`Only the first ${r.tracks.length.toLocaleString()} files are included.`)
|
||||
// Files the collection holds are its tracks already: as with a folder's
|
||||
// rows, nothing to add first — straight into the target, if there is one.
|
||||
const held = r.tracks.filter((t) => r.files[t.id]).map((t) => t.id)
|
||||
if (held.length === r.tracks.length) {
|
||||
if (target?.kind === 'playlist') void addToPlaylist(target.id, held)
|
||||
else if (target) void addToExport(target.id, held)
|
||||
else
|
||||
notify(
|
||||
'success',
|
||||
held.length === 1 ? 'Already in your collection' : `All ${held.length} are already in your collection`,
|
||||
)
|
||||
return
|
||||
}
|
||||
setAdding({ ids: r.tracks.map((t) => r.files[t.id] ?? t.id), target, note: notes.join(' ') || null })
|
||||
},
|
||||
[readDrop, addToPlaylist, addToExport, notify, onError],
|
||||
)
|
||||
// One dropped audio file on the deck: loaded to listen to, added to nothing.
|
||||
const loadDropped = useCallback(
|
||||
async (path: string) => {
|
||||
const r = await readDrop([path])
|
||||
if (!r) return
|
||||
const t = r.tracks[0]
|
||||
if (!t) {
|
||||
onError('That is not an audio file this library can hold.')
|
||||
return
|
||||
}
|
||||
loadTrack(t, r.files[t.id] ? 'collection' : 'folder')
|
||||
},
|
||||
[readDrop, loadTrack, onError],
|
||||
)
|
||||
const addForeign = useCallback(
|
||||
(origin: ForeignOrigin, ids: string[], target: AddTarget) => {
|
||||
if (origin === 'dropped') void dropFiles(ids, target)
|
||||
else if (origin === 'folder') {
|
||||
const files = folderFilesRef.current
|
||||
// Rows that are all collection tracks already: nothing to add first.
|
||||
if (ids.every((id) => files[id])) {
|
||||
if (target.kind === 'playlist') void addToPlaylist(target.id, ids)
|
||||
else void addToExport(target.id, ids)
|
||||
} else setAdding({ ids: ids.map((id) => files[id] ?? id), target })
|
||||
} else if (origin === 'device') setImportDrop({ ids, target })
|
||||
},
|
||||
[addToPlaylist, addToExport, dropFiles],
|
||||
)
|
||||
const audioFormats = capabilities.data?.tracks.audio_formats
|
||||
const isAudioPath = (path: string) =>
|
||||
path.lastIndexOf('.') > 0 && !!audioFormats?.includes(path.slice(path.lastIndexOf('.')).toLowerCase())
|
||||
const [deckDropRef, deckOver] = useDropTarget<true>({
|
||||
hint: (p) => (p.kind === 'tracks' ? true : null),
|
||||
hint: (p) =>
|
||||
p.kind === 'tracks' || (p.kind === 'files' && p.paths.length === 1 && isAudioPath(p.paths[0])) ? true : null,
|
||||
label: (p) => (p.kind === 'tracks' && p.ids.length > 1 ? `Load “${p.lead.title || 'Untitled'}” into the deck` : 'Load into the deck'),
|
||||
onDrop: (p) => p.kind === 'tracks' && loadTrack(p.lead, p.origin),
|
||||
onDrop: (p) => {
|
||||
if (p.kind === 'tracks') loadTrack(p.lead, p.origin)
|
||||
else if (p.kind === 'files') void loadDropped(p.paths[0])
|
||||
},
|
||||
})
|
||||
// Files dropped anywhere no other target takes them: the collection. A
|
||||
// library that cannot add tracks still takes the drop, to say why not —
|
||||
// silently ignoring it would read as the feature being broken.
|
||||
const canAddFiles = (capabilities.data?.writable ?? false) && !!capabilities.data?.tracks.addable
|
||||
const cannotAddFiles =
|
||||
capabilities.data && !capabilities.data.writable
|
||||
? (readOnlyNotice(capabilities.data) ?? 'This library is read-only.')
|
||||
: 'Tracks cannot be added to this library.'
|
||||
const [rootDropRef, rootOver] = useDropTarget<true>({
|
||||
hint: (p) => (p.kind === 'files' ? true : null),
|
||||
label: () => (canAddFiles ? 'Add to your collection…' : null),
|
||||
onDrop: (p) => {
|
||||
if (p.kind !== 'files') return
|
||||
if (canAddFiles) void dropFiles(p.paths, null)
|
||||
else notify('error', cannotAddFiles)
|
||||
},
|
||||
})
|
||||
const draggingFiles = useDragPayload()?.kind === 'files'
|
||||
useNativeFileDrop(loaded && !forcePicker, () =>
|
||||
notify(
|
||||
'warning',
|
||||
'Dropping files works in the Konduktor app, not in a browser (it cannot tell the page where a file is). Browse to it under Files in the sidebar instead.',
|
||||
),
|
||||
)
|
||||
const removeFromExport = useCallback(
|
||||
async (id: string, ids: string[]) => {
|
||||
try {
|
||||
@@ -407,7 +530,10 @@ export default function App() {
|
||||
: origin === 'folder'
|
||||
? (folderCaps.data ?? readOnlyCaps('not_in_library'))
|
||||
: capabilities.data!
|
||||
const viewCaps = capsFor(viewOriginRef.current)
|
||||
// A folder's table runs on the COLLECTION's: the rows it holds are collection
|
||||
// tracks and edit as such, and a loose row asks to be added first
|
||||
// (`folderMayEdit`) rather than rendering inert.
|
||||
const viewCaps = viewingFolder ? capabilities.data! : capsFor(viewOriginRef.current)
|
||||
// The deck follows its TRACK's library, not the view's.
|
||||
const deckCaps = capsFor(prepOrigin)
|
||||
|
||||
@@ -443,9 +569,12 @@ export default function App() {
|
||||
// PrepStrip keys its audio on the id, so a new object for the same id
|
||||
// reloads nothing.
|
||||
useEffect(() => {
|
||||
if (!prepTrack || viewOriginRef.current !== prepOrigin) return
|
||||
if (!prepTrack) return
|
||||
const fresh = tracks.find((t) => t.id === prepTrack.id)
|
||||
if (fresh && JSON.stringify(fresh) !== JSON.stringify(prepTrack)) setPrepTrack(fresh)
|
||||
if (!fresh) return
|
||||
const origin =
|
||||
viewOriginRef.current === 'folder' && folderFilesRef.current[fresh.id] ? 'collection' : viewOriginRef.current
|
||||
if (origin === prepOrigin && JSON.stringify(fresh) !== JSON.stringify(prepTrack)) setPrepTrack(fresh)
|
||||
// Only a refetch of the list matters; prepTrack is read, not tracked.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [tracks])
|
||||
@@ -636,7 +765,7 @@ export default function App() {
|
||||
}
|
||||
|
||||
// ---- Convert to Stems ------------------------------------------------------
|
||||
const canStems = canEdit && !viewForeign && !!capabilities.data?.tracks.stem_convertible
|
||||
const canStems = canEdit && !viewingDevice && !!capabilities.data?.tracks.stem_convertible
|
||||
const finishStemBatch = (state: string, r: StemBatchResult | null, error: string | null) => {
|
||||
qc.invalidateQueries({ queryKey: ['state'] })
|
||||
if (state === 'failed' || !r) {
|
||||
@@ -788,7 +917,7 @@ export default function App() {
|
||||
// the rest with a reason.
|
||||
const canAnalyzeGrid = !!capabilities.data?.grid.editable
|
||||
const canAnalyzeKey = !!capabilities.data?.tracks.key_writable
|
||||
const canAnalyze = canEdit && !viewForeign && (canAnalyzeGrid || canAnalyzeKey)
|
||||
const canAnalyze = canEdit && !viewingDevice && (canAnalyzeGrid || canAnalyzeKey)
|
||||
|
||||
const startCueBatch = (ids: string[]) => {
|
||||
const byId = new Map(tracks.map((t) => [t.id, t]))
|
||||
@@ -801,7 +930,7 @@ export default function App() {
|
||||
setBatchCancelling(false)
|
||||
setBatchJob({ id: job.id, kind: 'cues' })
|
||||
}
|
||||
const canAutoCue = canEdit && !viewForeign && (capabilities.data?.cues.hotcue_slots ?? 0) > 0
|
||||
const canAutoCue = canEdit && !viewingDevice && (capabilities.data?.cues.hotcue_slots ?? 0) > 0
|
||||
|
||||
|
||||
// ---- Remove ▸ -----------------------------------------------------------
|
||||
@@ -934,12 +1063,48 @@ export default function App() {
|
||||
}),
|
||||
})
|
||||
|
||||
const canClearGrids = canEdit && !viewForeign && !!capabilities.data?.grid.editable
|
||||
const canClearGrids = canEdit && !viewingDevice && !!capabilities.data?.grid.editable
|
||||
const canClearCues = canAutoCue
|
||||
const canRemoveTracks = canEdit && !viewForeign && !!capabilities.data?.tracks.removable
|
||||
const canRemoveTracks = canEdit && !viewingDevice && !!capabilities.data?.tracks.removable
|
||||
// The COLLECTION's capabilities, deliberately: adding happens while a folder
|
||||
// or device is on screen, whose own capabilities are read-only.
|
||||
const canAddTracks = canEdit && !!capabilities.data?.tracks.addable
|
||||
|
||||
// In a folder, only the rows the collection holds can be edited. Anything
|
||||
// that would edit a loose file says so and offers to add it, rather than
|
||||
// being absent or silently inert (decided 2026-10-10).
|
||||
const askToAdd = async (ids: string[]) => {
|
||||
const loose = ids.filter((id) => !folderFiles[id])
|
||||
if (!loose.length) return
|
||||
const first = tracks.find((t) => t.id === loose[0])
|
||||
const what =
|
||||
loose.length === 1
|
||||
? `“${first?.title || 'This file'}” is not in your collection`
|
||||
: `${loose.length} of these files are not in your collection`
|
||||
if (!canAddTracks) {
|
||||
notify('error', `${what}, and tracks cannot be added to this library.`)
|
||||
return
|
||||
}
|
||||
const add = await askConfirm({
|
||||
title: 'Add to your collection first',
|
||||
body: `${what} yet. Add ${loose.length === 1 ? 'it' : 'them'} to edit tags, cues or the beatgrid.`,
|
||||
confirmLabel: 'Add to Collection…',
|
||||
tone: 'primary',
|
||||
})
|
||||
if (add) setAdding({ ids: loose, target: null })
|
||||
}
|
||||
const folderEditField = (track: Track, field: keyof Track, value: string | number) => {
|
||||
if (folderFiles[track.id]) editField(track, field, value)
|
||||
else void askToAdd([track.id])
|
||||
}
|
||||
const folderMayEdit = (track: Track) => {
|
||||
if (folderFiles[track.id]) return true
|
||||
void askToAdd([track.id])
|
||||
return false
|
||||
}
|
||||
// The open menu's loose files: every editing item then asks to add them.
|
||||
const menuLoose = menu && viewingFolder ? menu.ids.filter((id) => !folderFiles[id]) : []
|
||||
const gated = (fn: () => void) => (menuLoose.length ? () => void askToAdd(menuLoose) : fn)
|
||||
const exportRootId =
|
||||
source.kind === 'export' ? source.id : source.kind === 'export-other' ? source.exportId : null
|
||||
const removeItems = (ids: string[]): MenuItem[] => [
|
||||
@@ -1007,8 +1172,26 @@ export default function App() {
|
||||
<CapabilitiesContext.Provider value={capabilities.data!}>
|
||||
{/* Floating glass panels with gaps between them: the ambient backdrop
|
||||
(main.tsx) shows through the gutters as well as through the glass. */}
|
||||
<div className="flex h-screen w-screen flex-col gap-3 overflow-hidden p-3">
|
||||
<div ref={rootDropRef} className="flex h-screen w-screen flex-col gap-3 overflow-hidden p-3">
|
||||
<Toast toast={toast} onClose={() => setToast(null)} />
|
||||
{draggingFiles && rootOver &&
|
||||
createPortal(
|
||||
<div aria-hidden className="pointer-events-none fixed inset-0 z-[85] flex items-center justify-center">
|
||||
<div className="absolute inset-1.5 rounded-[26px] ring-2 ring-accent" />
|
||||
<div className="glass-overlay flex items-center gap-2.5 overflow-hidden rounded-2xl px-5 py-3 text-sm text-text shadow-lg">
|
||||
<Icon name="music" size={15} className={canAddFiles ? 'text-accent' : 'text-pink'} />
|
||||
{canAddFiles ? 'Drop to add to your collection' : cannotAddFiles}
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
)}
|
||||
{readingDrop > 0 &&
|
||||
createPortal(
|
||||
<div className="glass-overlay pointer-events-none fixed bottom-14 left-1/2 z-[80] -translate-x-1/2 overflow-hidden rounded-full px-4 py-2 text-xs text-muted shadow-lg">
|
||||
Looking for audio in {readingDrop === 1 ? 'the dropped item' : `${readingDrop} dropped items`}…
|
||||
</div>,
|
||||
document.body,
|
||||
)}
|
||||
{menu && (
|
||||
<ContextMenu
|
||||
// Remount per opening: a right-click on another row while a menu is
|
||||
@@ -1023,8 +1206,8 @@ export default function App() {
|
||||
: []),
|
||||
// Offering "Edit Tags…" on a read-only library would open a dialog
|
||||
// whose every save is refused, so it is not offered at all.
|
||||
...(canEdit && !viewForeign && menu.ids.length === 1
|
||||
? [{ label: 'Edit Tags…', onClick: () => setEditing(menu.track) }]
|
||||
...(canEdit && !viewingDevice && menu.ids.length === 1
|
||||
? [{ label: 'Edit Tags…', onClick: gated(() => setEditing(menu.track)) }]
|
||||
: []),
|
||||
...(canAnalyze
|
||||
? [
|
||||
@@ -1032,7 +1215,7 @@ export default function App() {
|
||||
label: 'Analyze…',
|
||||
hint: batchJob ? 'busy' : menu.ids.length > 1 ? String(menu.ids.length) : undefined,
|
||||
disabled: !!batchJob,
|
||||
onClick: () => setAnalyzing(menu.ids),
|
||||
onClick: gated(() => setAnalyzing(menu.ids)),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
@@ -1044,20 +1227,20 @@ export default function App() {
|
||||
label: 'Auto Hotcues…',
|
||||
hint: batchJob ? 'busy' : menu.ids.length > 1 ? String(menu.ids.length) : undefined,
|
||||
disabled: !!batchJob,
|
||||
onClick: () => startCueBatch(menu.ids),
|
||||
onClick: gated(() => startCueBatch(menu.ids)),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
// Shown disabled WITH a reason where the platform cannot play stem
|
||||
// files as stems, rather than hidden: a missing item reads as a bug.
|
||||
...(canEdit && !viewForeign
|
||||
...(canEdit && !viewingDevice
|
||||
? [
|
||||
canStems
|
||||
? {
|
||||
label: 'Convert to Stems…',
|
||||
hint: batchJob ? 'busy' : menu.ids.length > 1 ? String(menu.ids.length) : undefined,
|
||||
disabled: !!batchJob,
|
||||
onClick: () => setStemDialog(menu.ids),
|
||||
onClick: gated(() => setStemDialog(menu.ids)),
|
||||
}
|
||||
: {
|
||||
label: 'Convert to Stems…',
|
||||
@@ -1070,12 +1253,14 @@ export default function App() {
|
||||
// A device's track ids belong to the stick, not the collection, so
|
||||
// there is nothing they could be added to. A folder's files CAN be
|
||||
// added — through the add dialog, which puts them in the
|
||||
// collection first.
|
||||
// collection first; rows it already holds are collection tracks.
|
||||
...(viewingFolder
|
||||
? canAddTracks
|
||||
? !menuLoose.length
|
||||
? [{ label: 'Add to', submenu: addToItems(menu.ids) }]
|
||||
: canAddTracks
|
||||
? [
|
||||
{ label: 'Add to Collection…', onClick: () => setAdding({ ids: menu.ids, target: null }) },
|
||||
{ label: 'Add to', submenu: folderAddToItems(menu.ids) },
|
||||
{ label: 'Add to Collection…', onClick: () => setAdding({ ids: menuLoose, target: null }) },
|
||||
{ label: 'Add to', submenu: folderAddToItems(toFolderIds(menu.ids)) },
|
||||
]
|
||||
: [{
|
||||
label: 'Add to Collection…',
|
||||
@@ -1092,7 +1277,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 }] : []
|
||||
})(),
|
||||
]}
|
||||
@@ -1219,6 +1404,7 @@ export default function App() {
|
||||
<AddFilesDialog
|
||||
trackIds={adding.ids}
|
||||
target={adding.target}
|
||||
note={adding.note}
|
||||
onClose={() => setAdding(null)}
|
||||
onDone={(msg) => {
|
||||
setAdding(null)
|
||||
@@ -1315,9 +1501,11 @@ export default function App() {
|
||||
{' · this folder only'}
|
||||
</span>
|
||||
<span className="ml-auto flex items-center gap-2">
|
||||
<span className="rounded-full bg-gold/10 px-2 py-0.5 text-[10px] uppercase tracking-wide text-gold shadow-[inset_0_0_0_1px_rgb(255_200_97/0.3)]">
|
||||
Not in collection
|
||||
</span>
|
||||
{tracks.length > heldInFolder.size && (
|
||||
<span className="rounded-full bg-gold/10 px-2 py-0.5 text-[10px] uppercase tracking-wide text-gold shadow-[inset_0_0_0_1px_rgb(255_200_97/0.3)]">
|
||||
Not in collection
|
||||
</span>
|
||||
)}
|
||||
{tracks.length > 0 && canAddTracks && (
|
||||
<button
|
||||
onClick={() =>
|
||||
@@ -1325,7 +1513,7 @@ export default function App() {
|
||||
// The selection when there is one, else everything in
|
||||
// view that the collection does not already hold.
|
||||
ids: selected.size
|
||||
? filtered.filter((t) => selected.has(t.id)).map((t) => t.id)
|
||||
? toFolderIds(filtered.filter((t) => selected.has(t.id)).map((t) => t.id))
|
||||
: filtered.filter((t) => !heldInFolder.has(t.id)).map((t) => t.id),
|
||||
target: null,
|
||||
})
|
||||
@@ -1459,6 +1647,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}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -503,7 +514,27 @@ export interface FolderAddRequest {
|
||||
}
|
||||
|
||||
export interface FolderAddPreview extends ImportPreview {
|
||||
/** Some of the files to add are on an external drive. */
|
||||
removable: boolean
|
||||
/** How many, and on which drives — per FILE, since a drop can mix drives. */
|
||||
removable_count?: number
|
||||
removable_drives?: string[]
|
||||
/** Copy mode: files already inside the import folder (copying makes a
|
||||
* second copy beside them). */
|
||||
in_destination?: number
|
||||
}
|
||||
|
||||
/** What files dropped onto the window from the OS resolved to: the audio in
|
||||
* them (folders searched all the way down), listed as a folder lists its
|
||||
* files — a file the collection holds is its collection track. */
|
||||
export interface DroppedFiles {
|
||||
tracks: Track[]
|
||||
/** Collection id → the file's folder id (= its path), for held rows. */
|
||||
files: Record<string, string>
|
||||
/** Dropped files that are not audio this library can hold, or are gone. */
|
||||
skipped: number
|
||||
/** Too many files: only the first 20,000 are included. */
|
||||
truncated: boolean
|
||||
}
|
||||
|
||||
export type JobState = 'running' | 'done' | 'failed' | 'cancelled'
|
||||
@@ -826,14 +857,15 @@ export interface PrefixSuggestions {
|
||||
}
|
||||
|
||||
// API origin. In the packaged desktop app the frontend is served from
|
||||
// tauri://localhost, so it can't use relative /api paths — the Tauri shell
|
||||
// injects window.__KONDUKTOR_API__ (the sidecar's http://127.0.0.1:<port>)
|
||||
// before any app script runs. In the browser dev server it's undefined, so we
|
||||
// fall back to relative URLs and let Vite proxy /api to the backend.
|
||||
export const API_BASE: string =
|
||||
(typeof window !== 'undefined' &&
|
||||
(window as unknown as { __KONDUKTOR_API__?: string }).__KONDUKTOR_API__) ||
|
||||
''
|
||||
// tauri://localhost, so it can't use relative /api paths: the sidecar's
|
||||
// http://127.0.0.1:<port> is only known once it has started, and the startup
|
||||
// screen (StartupScreen.tsx) sets it here before anything else renders. In the
|
||||
// browser dev server it stays '', so URLs are relative and Vite proxies /api.
|
||||
export let API_BASE = ''
|
||||
|
||||
export function setApiBase(url: string): void {
|
||||
API_BASE = url
|
||||
}
|
||||
|
||||
async function getJSON<T>(url: string): Promise<T> {
|
||||
const res = await fetch(API_BASE + url)
|
||||
@@ -1165,6 +1197,7 @@ export const api = {
|
||||
folderAddPreview: (body: FolderAddRequest) =>
|
||||
send<FolderAddPreview>('POST', '/api/folder/add/preview', body),
|
||||
folderAdd: (body: FolderAddRequest) => send<JobStatus>('POST', '/api/folder/add', body),
|
||||
folderDropped: (paths: string[]) => send<DroppedFiles>('POST', '/api/folder/dropped', { paths }),
|
||||
// ---- import ----
|
||||
importPreview: (body: ImportRequest) => send<ImportPreview>('POST', '/api/import/preview', body),
|
||||
/** Starts the job and returns immediately — poll `job()` for progress. */
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createPortal } from 'react-dom'
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react'
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { api, type FolderAddPreview, type FolderAddRequest, type JobStatus } from '../api'
|
||||
import { api, isServerPath, type FolderAddPreview, type FolderAddRequest, type JobStatus, type TrackOrigin } from '../api'
|
||||
import { useCaps } from '../lib/capabilities'
|
||||
import { placedAudioSummary } from '../lib/platformCopy'
|
||||
import { FolderPicker } from './FolderPicker'
|
||||
@@ -20,7 +20,14 @@ import { FolderPicker } from './FolderPicker'
|
||||
*
|
||||
* A library held by a server (`tracks.audio_destination === 'library'`) is the
|
||||
* other exception: it cannot see this computer's files, so the only choice is
|
||||
* which folder ON THE SERVER they are uploaded into.
|
||||
* which folder ON THE SERVER they are uploaded into — unless the files were
|
||||
* browsed in that server's own content folder: they are already where the
|
||||
* library can reach them, so they are added in place, uploaded nowhere and
|
||||
* nothing asked (decided 2026-10-10).
|
||||
*
|
||||
* Files dropped onto the window from the OS (`lib/fileDrop.ts`) arrive here
|
||||
* too, so a drop asks exactly what the sidebar's Add to Collection asks. A
|
||||
* drop can mix drives, so the external-drive warning counts files per drive.
|
||||
*
|
||||
* A playlist or export target still needs the files in the collection first —
|
||||
* both hold collection track ids — so the dialog says so rather than doing it
|
||||
@@ -42,26 +49,47 @@ export interface AddTarget {
|
||||
name: string
|
||||
}
|
||||
|
||||
/** Where tracks headed for the collection come from: another library's or a
|
||||
* folder's track ids, or — `dropped` — paths dragged in from the OS. */
|
||||
export type ForeignOrigin = TrackOrigin | 'dropped'
|
||||
|
||||
interface Props {
|
||||
trackIds: string[]
|
||||
target: AddTarget | null
|
||||
/** A line about what was left out before the dialog (a drop's non-audio files). */
|
||||
note?: string | null
|
||||
onClose: () => void
|
||||
onDone: (msg: string) => void
|
||||
onError: (msg: string) => void
|
||||
}
|
||||
|
||||
export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: Props) {
|
||||
/** The leave-in-place warning, per drive: a drop can mix the computer's own
|
||||
* disk with a stick, and only the stick's files go missing on unplug. */
|
||||
function removableWarning(p: FolderAddPreview, newCount: number): string {
|
||||
const count = p.removable_count ?? newCount
|
||||
const drives = p.removable_drives ?? []
|
||||
const where = drives.length === 1 ? `${drives[0]}, an external drive` : 'external drives'
|
||||
const what = count >= newCount ? 'These files are' : `${count} of these files are`
|
||||
const unplugged = drives.length === 1 ? 'it is' : 'they are'
|
||||
return `${what} on ${where}. They will go missing from your collection whenever ${unplugged} unplugged.`
|
||||
}
|
||||
|
||||
export function AddFilesDialog({ trackIds, target, note, onClose, onDone, onError }: Props) {
|
||||
const qc = useQueryClient()
|
||||
// The LIBRARY's capabilities (this dialog is mounted outside the browsed
|
||||
// view's swapped context). A library that places its own audio — a stick —
|
||||
// decides copy vs in place itself, so there is nothing to ask.
|
||||
const caps = useCaps()
|
||||
const places = caps.tracks.places_audio
|
||||
// Already in the server's content folder: added where they are.
|
||||
const onServer = trackIds.length > 0 && trackIds.every(isServerPath)
|
||||
// Uploaded into a folder on the server: nothing to ask but where.
|
||||
const uploads = !places && caps.tracks.audio_destination === 'library'
|
||||
const [mode, setMode] = useState<'copy' | 'reference' | null>(uploads ? 'copy' : null)
|
||||
const uploads = !places && !onServer && caps.tracks.audio_destination === 'library'
|
||||
const [mode, setMode] = useState<'copy' | 'reference' | null>(
|
||||
onServer ? 'reference' : uploads ? 'copy' : null,
|
||||
)
|
||||
const [folder, setFolder] = useState('')
|
||||
const remote = useServerImportFolder(uploads)
|
||||
const remote = useServerImportFolder(uploads || onServer)
|
||||
const [browsing, setBrowsing] = useState(false)
|
||||
const [job, setJob] = useState<JobStatus | null>(null)
|
||||
const [starting, setStarting] = useState(false)
|
||||
@@ -170,9 +198,12 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
|
||||
const newCount = p?.importable ?? 0
|
||||
const shown = places ? 'placed' : mode
|
||||
const libraryName = places ? caps.save.app_name : 'your collection'
|
||||
// Every file is held already: nothing is copied or referenced, so there is
|
||||
// nothing to ask — only the target to fill.
|
||||
const nothingNew = !!p && newCount === 0 && p.existing.length > 0
|
||||
const canAdd =
|
||||
!starting && shown !== null && !!p && (newCount > 0 || (!!target && p.existing.length > 0)) &&
|
||||
p.enough_space !== false
|
||||
!starting && (shown !== null || nothingNew) && !!p &&
|
||||
(newCount > 0 || (!!target && p.existing.length > 0)) && p.enough_space !== false
|
||||
|
||||
const title = target
|
||||
? `Add ${n} track${n === 1 ? '' : 's'} to ${target.name}`
|
||||
@@ -251,7 +282,16 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!places && !uploads && (
|
||||
{onServer && (
|
||||
<div className="rounded well px-3 py-2 text-xs text-muted">
|
||||
Already on {remote.serverName}, so your collection points at them where they
|
||||
are. Nothing is uploaded or copied.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{note && <div className="text-xs text-muted">{note}</div>}
|
||||
|
||||
{!places && !uploads && !onServer && !nothingNew && (
|
||||
<div className="space-y-1">
|
||||
{option(
|
||||
'copy',
|
||||
@@ -282,9 +322,14 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
|
||||
)}
|
||||
|
||||
{mode === 'reference' && p?.removable && (
|
||||
<div className="rounded well px-3 py-2 text-xs text-gold">{removableWarning(p, newCount)}</div>
|
||||
)}
|
||||
|
||||
{mode === 'copy' && !!p?.in_destination && (
|
||||
<div className="rounded well px-3 py-2 text-xs text-gold">
|
||||
These files are on an external drive. They will go missing from your
|
||||
collection whenever the drive is unplugged.
|
||||
{p.in_destination === newCount ? 'These files are' : `${p.in_destination} of these files are`}{' '}
|
||||
already in your import folder. Copying makes a second copy beside{' '}
|
||||
{p.in_destination === 1 ? 'it' : 'them'}.
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
}
|
||||
@@ -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 && (
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState } from 'react'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { api, type ExportSet, type TrackOrigin } from '../api'
|
||||
import type { AddTarget } from './AddFilesDialog'
|
||||
import { api, type ExportSet } from '../api'
|
||||
import type { AddTarget, ForeignOrigin } from './AddFilesDialog'
|
||||
import { useCaps } from '../lib/capabilities'
|
||||
import { ExportDialog } from './ExportDialog'
|
||||
import { ExportRunDialog } from './ExportRunDialog'
|
||||
@@ -31,7 +31,7 @@ interface Props {
|
||||
onSelect: (s: Source) => void
|
||||
onDone: (msg: string) => void
|
||||
onError: (msg: string) => void
|
||||
onAddForeign: (origin: TrackOrigin, ids: string[], target: AddTarget) => void
|
||||
onAddForeign: (origin: ForeignOrigin, ids: string[], target: AddTarget) => void
|
||||
}
|
||||
|
||||
export function ExportsSection({ source, onSelect, onDone, onError, onAddForeign }: Props) {
|
||||
@@ -151,7 +151,7 @@ function ExportRow({
|
||||
onDelete: () => void
|
||||
onDone: (msg: string) => void
|
||||
onError: (msg: string) => void
|
||||
onAddForeign: (origin: TrackOrigin, ids: string[], target: AddTarget) => void
|
||||
onAddForeign: (origin: ForeignOrigin, ids: string[], target: AddTarget) => void
|
||||
}) {
|
||||
const qc = useQueryClient()
|
||||
// The COLLECTION's capabilities (the sidebar sits outside the browsed view's
|
||||
@@ -196,14 +196,20 @@ function ExportRow({
|
||||
const accepts = (p: DragPayload) =>
|
||||
p.kind === 'tracks'
|
||||
? p.origin === 'collection' || (caps.writable && caps.tracks.addable)
|
||||
: playlistIdsUnder(p.node).length > 0
|
||||
: p.kind === 'files'
|
||||
? caps.writable && caps.tracks.addable
|
||||
: playlistIdsUnder(p.node).length > 0
|
||||
const [dropRef, over] = useDropTarget<true>({
|
||||
hint: (p) => (accepts(p) ? true : null),
|
||||
label: (p) =>
|
||||
p.kind === 'tracks' && p.origin === 'device'
|
||||
? `Import into export ${set.name}…`
|
||||
: `Add to export ${set.name}${p.kind === 'tracks' && p.origin === 'folder' ? '…' : ''}`,
|
||||
: `Add to export ${set.name}${(p.kind === 'tracks' && p.origin === 'folder') || p.kind === 'files' ? '…' : ''}`,
|
||||
onDrop: async (p) => {
|
||||
if (p.kind === 'files') {
|
||||
onAddForeign('dropped', p.paths, { kind: 'export', id: set.id, name: set.name })
|
||||
return
|
||||
}
|
||||
if (p.kind === 'tracks' && p.origin !== 'collection') {
|
||||
onAddForeign(p.origin, p.ids, { kind: 'export', id: set.id, name: set.name })
|
||||
return
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { api, type PlaylistKind, type PlaylistNode, type TrackOrigin } from '../api'
|
||||
import type { AddTarget } from './AddFilesDialog'
|
||||
import { api, type PlaylistKind, type PlaylistNode } from '../api'
|
||||
import type { AddTarget, ForeignOrigin } from './AddFilesDialog'
|
||||
import { useCaps } from '../lib/capabilities'
|
||||
import { SaveBar } from './SaveBar'
|
||||
import { confirmDiscardUnsaved } from '../lib/unsaved'
|
||||
import { SettingsMenu } from './SettingsMenu'
|
||||
import { useAppSetting } from './AppSettings'
|
||||
import { DevicesSection } from './DevicesSection'
|
||||
import { ExportsSection } from './ExportsSection'
|
||||
import { ConfirmDialog, type ConfirmRequest } from './ConfirmDialog'
|
||||
@@ -13,8 +14,8 @@ import { ContextMenu, type MenuItem } from './ContextMenu'
|
||||
import { Icon, type IconName } from '../lib/icons'
|
||||
import { PlatformIcon } from '../lib/platformIcons'
|
||||
import { addTracksToPlaylist } from '../lib/addTracks'
|
||||
import { useDragPayload, usePressToDrag, useDropTarget, type DragPayload } from '../lib/drag'
|
||||
import { nodeIdsUnder, playlistIdsUnder } from '../lib/playlistTree'
|
||||
import { useDragPayload, usePressToDrag, useDropTarget, type DragPayload, type TracksOrFiles } from '../lib/drag'
|
||||
import { findNode, idsAfter, nodeIdsUnder, playlistIdsUnder } from '../lib/playlistTree'
|
||||
|
||||
/**
|
||||
* Which view the main table is showing.
|
||||
@@ -54,9 +55,10 @@ interface Props {
|
||||
/** Open a drive's library as THE library (Devices' "Open for editing…"). */
|
||||
onOpenLibrary: (path: string) => void
|
||||
onDone: (msg: string) => void
|
||||
/** Tracks not in the collection yet (a device's, a folder's) dropped on a
|
||||
* playlist or export: open the dialog that adds them, target filled in. */
|
||||
onAddForeign: (origin: TrackOrigin, ids: string[], target: AddTarget) => void
|
||||
/** Tracks not in the collection yet (a device's, a folder's — or files
|
||||
* dropped from the OS, as paths) dropped on a playlist or export: open the
|
||||
* dialog that adds them, target filled in. */
|
||||
onAddForeign: (origin: ForeignOrigin, ids: string[], target: AddTarget) => void
|
||||
onOpenPathMapping: () => void
|
||||
/** After unsaved edits were discarded (SaveBar). */
|
||||
onDiscarded?: () => void
|
||||
@@ -99,19 +101,22 @@ type Draft = { kind: 'playlist' | 'folder'; parentId: string | null }
|
||||
/** Actions a row can ask of the sidebar. They live there, not in the row, so
|
||||
* the right-click menu and the hover buttons run the very same code. */
|
||||
interface RowActions {
|
||||
/** Whether a folder is open, and opening / closing it. */
|
||||
isOpen: (node: PlaylistNode) => boolean
|
||||
setOpen: (node: PlaylistNode, open: boolean) => void
|
||||
onContextMenu: (e: React.MouseEvent, node: PlaylistNode) => void
|
||||
onRename: (node: PlaylistNode, name: string) => void
|
||||
onRename: (node: PlaylistNode, name: string, parentId: string | null) => void
|
||||
onDelete: (node: PlaylistNode) => void
|
||||
onAddToExport: (node: PlaylistNode, setId: string) => void
|
||||
/** The row's export button: the export list as a menu under it. */
|
||||
onPickExport: (e: React.MouseEvent<HTMLElement>, node: PlaylistNode) => void
|
||||
onCommitDraft: (name: string) => void
|
||||
onCancelDraft: () => void
|
||||
/** Whether a drag of tracks may drop on this playlist. */
|
||||
acceptsTracks: (node: PlaylistNode, p: Extract<DragPayload, { kind: 'tracks' }>) => boolean
|
||||
/** Whether a drag of tracks (or of files from the OS) may drop on this playlist. */
|
||||
acceptsTracks: (node: PlaylistNode, p: TracksOrFiles) => boolean
|
||||
/** Tracks dropped on a playlist; `alt` (Option) moves them out of the
|
||||
* playlist they came from. */
|
||||
onDropTracks: (node: PlaylistNode, p: Extract<DragPayload, { kind: 'tracks' }>, alt: boolean) => void
|
||||
onDropTracks: (node: PlaylistNode, p: TracksOrFiles, alt: boolean) => void
|
||||
/** Whether a node may be dragged elsewhere in the tree. */
|
||||
canMove: (node: PlaylistNode) => boolean
|
||||
/** A node dropped in the tree: `index` among `parentId`'s children,
|
||||
@@ -202,7 +207,7 @@ function NodeRow({
|
||||
exportSets: { id: string; name: string }[]
|
||||
actions: RowActions
|
||||
}) {
|
||||
const [open, setOpen] = useState(true)
|
||||
const open = actions.isOpen(node)
|
||||
const renaming = renamingId === node.id
|
||||
const [renameDraft, setRenameDraft] = useState(node.name)
|
||||
const isFolder = node.kind === 'folder'
|
||||
@@ -261,14 +266,14 @@ function NodeRow({
|
||||
label: (p, h, at) => {
|
||||
if (h.zone === 'tracks') {
|
||||
if (p.kind === 'tracks' && p.origin === 'device') return `Import into ${node.name}…`
|
||||
if (p.kind === 'tracks' && p.origin === 'folder') return `Add to ${node.name}…`
|
||||
if ((p.kind === 'tracks' && p.origin === 'folder') || p.kind === 'files') return `Add to ${node.name}…`
|
||||
return `${moves(p, at.alt) ? 'Move' : 'Add'} to ${node.name}`
|
||||
}
|
||||
if (h.zone === 'peek') return null
|
||||
return h.zone === 'into' || h.zone === 'first' ? `Move into ${node.name}` : `Move ${h.zone} ${node.name}`
|
||||
},
|
||||
onDrop: (p, h, at) => {
|
||||
if (p.kind === 'tracks') {
|
||||
if (p.kind !== 'node') {
|
||||
if (h.zone === 'tracks') actions.onDropTracks(node, p, at.alt)
|
||||
} else if ('parentId' in h) {
|
||||
actions.onMoveNode(p.node, h.parentId, h.index, h.zone === 'into' && !expanded ? node : null)
|
||||
@@ -278,9 +283,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 +321,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 +355,7 @@ function NodeRow({
|
||||
if (e.key === 'Enter') {
|
||||
setRenamingId(null)
|
||||
if (renameDraft.trim() && renameDraft.trim() !== node.name)
|
||||
actions.onRename(node, renameDraft.trim())
|
||||
actions.onRename(node, renameDraft.trim(), parentId)
|
||||
} else if (e.key === 'Escape') {
|
||||
setRenamingId(null)
|
||||
}
|
||||
@@ -469,6 +476,32 @@ export function Sidebar({
|
||||
const [menu, setMenu] = useState<{ x: number; y: number; items: MenuItem[] } | null>(null)
|
||||
const [confirmReq, setConfirmReq] = useState<ConfirmRequest | null>(null)
|
||||
|
||||
// Which folders are open: the setting, except where the user has opened or
|
||||
// closed one. Held here rather than in each row, so it survives a row
|
||||
// remounting and can be reset — on a new library, and when the setting
|
||||
// changes (so changing it visibly does something).
|
||||
const expandByDefault = useAppSetting('expandPlaylistFolders')
|
||||
const [openOverrides, setOpenOverrides] = useState<Record<string, boolean>>({})
|
||||
useEffect(() => setOpenOverrides({}), [library?.path, expandByDefault])
|
||||
const setFolderOpen = (id: string, open: boolean) =>
|
||||
setOpenOverrides((o) => ({ ...o, [id]: open }))
|
||||
// A folder's id — and so every id under it — may change when it is renamed
|
||||
// or moved (a platform addressing folders by path), so open state follows
|
||||
// the subtree to its new ids. Reads the tree as refetched after the edit.
|
||||
const carryOpen = async (before: PlaylistNode, newId: string) => {
|
||||
if (before.kind !== 'folder') return
|
||||
await qc.refetchQueries({ queryKey: ['playlists'] })
|
||||
const after = findNode(qc.getQueryData<PlaylistNode[]>(['playlists']) ?? [], newId)
|
||||
if (!after) return
|
||||
const ids = idsAfter(before, after)
|
||||
setOpenOverrides((o) => {
|
||||
const next = { ...o }
|
||||
for (const [from, to] of ids) if (from !== to && from in o) delete next[from]
|
||||
for (const [from, to] of ids) if (from !== to && from in o) next[to] = o[from]
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const invalidate = () => {
|
||||
qc.invalidateQueries({ queryKey: ['playlists'] })
|
||||
qc.invalidateQueries({ queryKey: ['state'] })
|
||||
@@ -487,10 +520,19 @@ export function Sidebar({
|
||||
})
|
||||
|
||||
const rename = useMutation({
|
||||
mutationFn: ({ node, name }: { node: PlaylistNode; name: string }) =>
|
||||
mutationFn: ({ node, name }: { node: PlaylistNode; name: string; parentId: string | null }) =>
|
||||
api.renamePlaylist(node.id, name),
|
||||
onSuccess: (_d, { node, name }) => {
|
||||
onSuccess: async (_d, { node, name, parentId }) => {
|
||||
invalidate()
|
||||
// The rename does not answer the new id, so the folder is found by its
|
||||
// new name among its siblings (a folder may not share a sibling's name).
|
||||
if (node.kind === 'folder') {
|
||||
await qc.refetchQueries({ queryKey: ['playlists'] })
|
||||
const tree = qc.getQueryData<PlaylistNode[]>(['playlists']) ?? []
|
||||
const siblings = parentId === null ? tree : (findNode(tree, parentId)?.children ?? [])
|
||||
const renamed = siblings.find((n) => n.kind === 'folder' && n.name === name)
|
||||
if (renamed) await carryOpen(node, renamed.id)
|
||||
}
|
||||
if (source.kind === 'playlist' && source.id === node.id)
|
||||
onSelect({ kind: 'playlist', id: node.id, name })
|
||||
},
|
||||
@@ -525,6 +567,9 @@ export function Sidebar({
|
||||
|
||||
const startDraft = (kind: Draft['kind'], parentId: string | null) => {
|
||||
setRenamingId(null)
|
||||
// Open the folder it goes in, or the new node would vanish into a
|
||||
// collapsed folder once named.
|
||||
if (parentId !== null) setFolderOpen(parentId, true)
|
||||
setDraft({ kind, parentId })
|
||||
}
|
||||
|
||||
@@ -586,8 +631,10 @@ export function Sidebar({
|
||||
}
|
||||
|
||||
const actions: RowActions = {
|
||||
isOpen: (node) => openOverrides[node.id] ?? expandByDefault,
|
||||
setOpen: (node, open) => setFolderOpen(node.id, open),
|
||||
onContextMenu: (e, node) => openMenu(e, nodeItems(node)),
|
||||
onRename: (node, name) => rename.mutate({ node, name }),
|
||||
onRename: (node, name, parentId) => rename.mutate({ node, name, parentId }),
|
||||
onDelete: confirmDelete,
|
||||
onAddToExport: (node, setId) => addToExport.mutate({ node, setId }),
|
||||
// Opened as the shared ContextMenu rather than a popover inside the row: the
|
||||
@@ -618,12 +665,13 @@ export function Sidebar({
|
||||
acceptsTracks: (node, p) =>
|
||||
caps.writable &&
|
||||
node.can_add_tracks &&
|
||||
(p.origin === 'collection' ? p.fromPlaylist !== node.id : caps.tracks.addable),
|
||||
(p.kind === 'tracks' && p.origin === 'collection' ? p.fromPlaylist !== node.id : caps.tracks.addable),
|
||||
canMove: (node) => caps.writable && node.can_move,
|
||||
onMoveNode: async (node, parentId, index, into) => {
|
||||
try {
|
||||
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) {
|
||||
@@ -631,6 +679,10 @@ export function Sidebar({
|
||||
}
|
||||
},
|
||||
onDropTracks: async (node, p, alt) => {
|
||||
if (p.kind === 'files') {
|
||||
onAddForeign('dropped', p.paths, { kind: 'playlist', id: node.id, name: node.name })
|
||||
return
|
||||
}
|
||||
if (p.origin !== 'collection') {
|
||||
onAddForeign(p.origin, p.ids, { kind: 'playlist', id: node.id, name: node.name })
|
||||
return
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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) =>
|
||||
|
||||
@@ -18,6 +18,11 @@ import { Icon } from './icons'
|
||||
* events for its own file drop on Windows, so HTML5 DnD silently dies in the
|
||||
* packaged app.
|
||||
*
|
||||
* Files dragged in from Finder / Explorer ride the same store as a `files`
|
||||
* payload: Tauri reports that drag (with real paths) instead of the webview,
|
||||
* and `lib/fileDrop.ts` feeds it in through `nativeDragStart` / `Move` / `End`,
|
||||
* so the same targets light up and the same ghost names what a drop would do.
|
||||
*
|
||||
* The state lives in a module-level store read through useSyncExternalStore
|
||||
* with narrow selectors, so a pointer move re-renders only the target under it
|
||||
* (and the ghost) — never the table.
|
||||
@@ -39,6 +44,12 @@ export type DragPayload =
|
||||
source: object
|
||||
}
|
||||
| { kind: 'node'; node: PlaylistNode; parentId: string | null }
|
||||
/** Files and folders from the OS, as absolute paths. Not yet tracks: a
|
||||
* target hands them to the drop resolver, which reads what is in them. */
|
||||
| { kind: 'files'; paths: string[] }
|
||||
|
||||
/** What a playlist or export row takes: track rows, or files from the OS. */
|
||||
export type TracksOrFiles = Exclude<DragPayload, { kind: 'node' }>
|
||||
|
||||
export interface DropPoint {
|
||||
x: number
|
||||
@@ -117,44 +128,26 @@ function evaluate() {
|
||||
|
||||
let detach: (() => void) | null = null
|
||||
|
||||
/** Start a drag. Call it once the press has moved past the source's threshold. */
|
||||
export function beginDrag(payload: DragPayload, at: { x: number; y: number; alt: boolean }) {
|
||||
/** End the drag in progress, dropping on the target under the pointer if `drop`. */
|
||||
function finish(drop: boolean) {
|
||||
const { payload: p, target, hint, x, y, alt } = state
|
||||
detach?.()
|
||||
if (!drop || !p || !target) return
|
||||
const spec = targets.get(target)
|
||||
try {
|
||||
spec?.current.onDrop(p, hint, { x, y, alt })
|
||||
} catch (err) {
|
||||
console.error('drop failed', err)
|
||||
}
|
||||
}
|
||||
|
||||
/** Publish a new drag and start edge auto-scroll. Returns what undoes both. */
|
||||
function open(payload: DragPayload, at: { x: number; y: number; alt: boolean }): () => void {
|
||||
detach?.()
|
||||
set({ ...IDLE, payload, ...at })
|
||||
document.documentElement.classList.add('is-dragging')
|
||||
window.getSelection()?.removeAllRanges()
|
||||
|
||||
const onMove = (e: PointerEvent) => {
|
||||
// One notification per move: evaluate() publishes the position with the hint.
|
||||
state = { ...state, x: e.clientX, y: e.clientY, alt: e.altKey }
|
||||
evaluate()
|
||||
}
|
||||
const finish = (drop: boolean) => {
|
||||
const { payload: p, target, hint, x, y, alt } = state
|
||||
detach?.()
|
||||
if (!drop || !p || !target) return
|
||||
const spec = targets.get(target)
|
||||
try {
|
||||
spec?.current.onDrop(p, hint, { x, y, alt })
|
||||
} catch (err) {
|
||||
console.error('drop failed', err)
|
||||
}
|
||||
}
|
||||
const onUp = () => finish(true)
|
||||
const onCancel = () => finish(false)
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape' && e.type === 'keydown') {
|
||||
// Before every other Esc handler: cancelling the drag is all Esc does.
|
||||
e.preventDefault()
|
||||
e.stopImmediatePropagation()
|
||||
finish(false)
|
||||
return
|
||||
}
|
||||
if (e.key === 'Alt' && state.alt !== (e.type === 'keydown')) {
|
||||
set({ alt: e.type === 'keydown' })
|
||||
evaluate()
|
||||
}
|
||||
}
|
||||
// Hold near the edge of a `data-drag-scroll` element to scroll it. Its
|
||||
// value is the height covered at the top (a sticky header). The edge is
|
||||
// thinner than a row and must be HELD for a moment first: otherwise the
|
||||
@@ -187,6 +180,37 @@ export function beginDrag(payload: DragPayload, at: { x: number; y: number; alt:
|
||||
}
|
||||
raf = requestAnimationFrame(autoScroll)
|
||||
|
||||
return () => {
|
||||
cancelAnimationFrame(raf)
|
||||
document.documentElement.classList.remove('is-dragging')
|
||||
set(IDLE)
|
||||
}
|
||||
}
|
||||
|
||||
/** Start a drag. Call it once the press has moved past the source's threshold. */
|
||||
export function beginDrag(payload: DragPayload, at: { x: number; y: number; alt: boolean }) {
|
||||
const close = open(payload, at)
|
||||
|
||||
const onMove = (e: PointerEvent) => {
|
||||
// One notification per move: evaluate() publishes the position with the hint.
|
||||
state = { ...state, x: e.clientX, y: e.clientY, alt: e.altKey }
|
||||
evaluate()
|
||||
}
|
||||
const onUp = () => finish(true)
|
||||
const onCancel = () => finish(false)
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape' && e.type === 'keydown') {
|
||||
// Before every other Esc handler: cancelling the drag is all Esc does.
|
||||
e.preventDefault()
|
||||
e.stopImmediatePropagation()
|
||||
finish(false)
|
||||
return
|
||||
}
|
||||
if (e.key === 'Alt' && state.alt !== (e.type === 'keydown')) {
|
||||
set({ alt: e.type === 'keydown' })
|
||||
evaluate()
|
||||
}
|
||||
}
|
||||
window.addEventListener('pointermove', onMove)
|
||||
window.addEventListener('pointerup', onUp)
|
||||
window.addEventListener('pointercancel', onCancel)
|
||||
@@ -195,14 +219,12 @@ export function beginDrag(payload: DragPayload, at: { x: number; y: number; alt:
|
||||
window.addEventListener('blur', onCancel)
|
||||
detach = () => {
|
||||
detach = null
|
||||
cancelAnimationFrame(raf)
|
||||
window.removeEventListener('pointermove', onMove)
|
||||
window.removeEventListener('pointerup', onUp)
|
||||
window.removeEventListener('pointercancel', onCancel)
|
||||
window.removeEventListener('keydown', onKey, true)
|
||||
window.removeEventListener('keyup', onKey, true)
|
||||
window.removeEventListener('blur', onCancel)
|
||||
document.documentElement.classList.remove('is-dragging')
|
||||
// The pointerup that ended the drag is followed by a click on whatever
|
||||
// is under it; that click is part of the drop, not a click of its own.
|
||||
const swallow = (e: MouseEvent) => {
|
||||
@@ -211,11 +233,34 @@ export function beginDrag(payload: DragPayload, at: { x: number; y: number; alt:
|
||||
}
|
||||
window.addEventListener('click', swallow, true)
|
||||
setTimeout(() => window.removeEventListener('click', swallow, true), 0)
|
||||
set(IDLE)
|
||||
close()
|
||||
}
|
||||
evaluate()
|
||||
}
|
||||
|
||||
/** A drag the OS owns (files from Finder / Explorer): it enters the window… */
|
||||
export function nativeDragStart(payload: DragPayload, at: { x: number; y: number }) {
|
||||
const close = open(payload, { ...at, alt: false })
|
||||
detach = () => {
|
||||
detach = null
|
||||
close()
|
||||
}
|
||||
evaluate()
|
||||
}
|
||||
|
||||
/** …moves over it (window coordinates, CSS pixels)… */
|
||||
export function nativeDragMove(at: { x: number; y: number }) {
|
||||
if (!state.payload) return
|
||||
state = { ...state, ...at }
|
||||
evaluate()
|
||||
}
|
||||
|
||||
/** …and is dropped (or leaves the window: `drop` false). */
|
||||
export function nativeDragEnd(drop: boolean, at?: { x: number; y: number }) {
|
||||
if (drop && at) nativeDragMove(at)
|
||||
finish(drop)
|
||||
}
|
||||
|
||||
/** A pointerdown handler that starts a drag once the press moves 6 px. A plain
|
||||
* click never moves that far, so the element keeps its click; a press on a
|
||||
* field inside it (a rename input) never drags. `make` is asked at the moment
|
||||
@@ -273,6 +318,10 @@ export function useDropTarget<H>(spec: DropSpec<H>): [(el: HTMLElement | null) =
|
||||
function describe(p: DragPayload): { icon: 'music' | 'playlist' | 'folder' | 'smart'; text: string } {
|
||||
if (p.kind === 'node')
|
||||
return { icon: p.node.kind === 'folder' ? 'folder' : p.node.kind === 'smart' ? 'smart' : 'playlist', text: p.node.name }
|
||||
if (p.kind === 'files')
|
||||
return p.paths.length === 1
|
||||
? { icon: 'music', text: p.paths[0].split(/[\\/]/).filter(Boolean).pop() ?? p.paths[0] }
|
||||
: { icon: 'music', text: `${p.paths.length} items` }
|
||||
if (p.ids.length === 1) {
|
||||
const t = p.tracks[0]
|
||||
return { icon: 'music', text: t ? [t.artist, t.title].filter(Boolean).join(' – ') || 'Untitled' : '1 track' }
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { nativeDragEnd, nativeDragMove, nativeDragStart } from './drag'
|
||||
|
||||
/**
|
||||
* Files dragged in from Finder / Explorer, fed into the window's ONE drag
|
||||
* store (`lib/drag.tsx`) as a `files` payload, so the targets that take track
|
||||
* rows — playlists, exports, the deck — take files too, and anywhere else is
|
||||
* "add to the collection" (App's own target).
|
||||
*
|
||||
* Tauri only: the shell's webview hands the OS drag to Tauri, which reports it
|
||||
* with real paths — what adding a file IN PLACE needs. A plain browser gives a
|
||||
* page `File` objects without paths, so in a browser a file drop is only
|
||||
* CAUGHT — left alone, the browser navigates to the dropped file and the app
|
||||
* is gone — and `onBrowserDrop` says why nothing happened.
|
||||
*
|
||||
* `enabled` false (no library open yet) and an open dialog both refuse the
|
||||
* drag at its start, before anything is highlighted.
|
||||
*/
|
||||
export function useNativeFileDrop(enabled: boolean, onBrowserDrop: () => void) {
|
||||
const enabledRef = useRef(enabled)
|
||||
enabledRef.current = enabled
|
||||
const onBrowserDropRef = useRef(onBrowserDrop)
|
||||
onBrowserDropRef.current = onBrowserDrop
|
||||
|
||||
useEffect(() => {
|
||||
if (!('__TAURI_INTERNALS__' in window)) {
|
||||
// Only drags carrying files: the app's own drags are pointer events,
|
||||
// and a text drag into a field must keep working.
|
||||
const hasFiles = (e: DragEvent) => !!e.dataTransfer?.types.includes('Files')
|
||||
const over = (e: DragEvent) => {
|
||||
if (hasFiles(e)) e.preventDefault()
|
||||
}
|
||||
const drop = (e: DragEvent) => {
|
||||
if (!hasFiles(e)) return
|
||||
e.preventDefault()
|
||||
onBrowserDropRef.current()
|
||||
}
|
||||
window.addEventListener('dragover', over)
|
||||
window.addEventListener('drop', drop)
|
||||
return () => {
|
||||
window.removeEventListener('dragover', over)
|
||||
window.removeEventListener('drop', drop)
|
||||
}
|
||||
}
|
||||
let unlisten: (() => void) | undefined
|
||||
let cancelled = false
|
||||
let active = false
|
||||
void (async () => {
|
||||
const { getCurrentWebview } = await import('@tauri-apps/api/webview')
|
||||
const off = await getCurrentWebview().onDragDropEvent(({ payload }) => {
|
||||
// Tauri reports PHYSICAL pixels; the page works in CSS pixels.
|
||||
const scale = window.devicePixelRatio || 1
|
||||
const at = 'position' in payload ? { x: payload.position.x / scale, y: payload.position.y / scale } : null
|
||||
switch (payload.type) {
|
||||
case 'enter':
|
||||
active =
|
||||
enabledRef.current &&
|
||||
payload.paths.length > 0 &&
|
||||
!document.querySelector('[aria-modal="true"]')
|
||||
if (active && at) nativeDragStart({ kind: 'files', paths: payload.paths }, at)
|
||||
break
|
||||
case 'over':
|
||||
if (active && at) nativeDragMove(at)
|
||||
break
|
||||
case 'drop':
|
||||
if (active) nativeDragEnd(true, at ?? undefined)
|
||||
active = false
|
||||
break
|
||||
case 'leave':
|
||||
if (active) nativeDragEnd(false)
|
||||
active = false
|
||||
break
|
||||
}
|
||||
})
|
||||
if (cancelled) off()
|
||||
else unlisten = off
|
||||
})()
|
||||
return () => {
|
||||
cancelled = true
|
||||
unlisten?.()
|
||||
if (active) nativeDragEnd(false)
|
||||
}
|
||||
}, [])
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)}
|
||||
/>
|
||||
),
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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>,
|
||||
)
|
||||