Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
87cbd3720e | ||
|
|
591f2bc791 | ||
|
|
ebe30c1128 | ||
|
|
cd1914216f | ||
|
|
d10b11f8eb | ||
|
|
79a8a843c5 | ||
|
|
0204a322ff | ||
|
|
05051e7056 | ||
|
|
b5dabbc8a0 | ||
|
|
86bbb7b961 | ||
|
|
d474c662db | ||
|
|
a0df683fee | ||
|
|
3385b794e9 | ||
|
|
2c352b76a1 | ||
|
|
40630ff78e | ||
|
|
966f3fe8c5 | ||
|
|
a03b9056a9 | ||
|
|
26b556d975 | ||
|
|
c87444bda5 | ||
|
|
7ba71981c8 | ||
|
|
89c7dade25 | ||
|
|
b154df430a | ||
|
|
e5c7b67626 | ||
|
|
9f79f5a849 | ||
|
|
c8b86100f0 | ||
|
|
0fac84cb73 | ||
|
|
71ee877784 | ||
|
|
920146f2c0 |
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: |
|
||||
@@ -145,6 +146,8 @@ jobs:
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v6
|
||||
env:
|
||||
DOCKER_BUILD_RECORD_UPLOAD: false # no .dockerbuild artifact in the run
|
||||
with:
|
||||
context: .
|
||||
file: server/Dockerfile
|
||||
@@ -180,6 +183,9 @@ jobs:
|
||||
- name: Download installers from both builds
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
# Only the installers: the run also holds server-image's Docker build
|
||||
# record, which is not a release asset (and once failed to download).
|
||||
pattern: konduktor-*
|
||||
path: artifacts # → artifacts/konduktor-macOS/…, artifacts/konduktor-Windows/…
|
||||
|
||||
- name: Publish release
|
||||
|
||||
@@ -33,13 +33,25 @@ npm install
|
||||
cd ..
|
||||
```
|
||||
|
||||
## 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. This is `dev.sh` for Windows.
|
||||
It runs the Python source, not the frozen sidecar, so it cannot show
|
||||
desktop-shell behaviour (startup screen, quit prompt, WebView2). For that, use
|
||||
`npx tauri dev` in `frontend` — but note it still spawns the FROZEN sidecar from
|
||||
`src-tauri\binaries\`, so backend changes need `build_sidecar.ps1` first.
|
||||
|
||||
## Build
|
||||
|
||||
```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
|
||||
.\build_sidecar.ps1 # → frontend\src-tauri\binaries\konduktor-sidecar\ (a folder)
|
||||
cd ..
|
||||
|
||||
# 2) Build the app
|
||||
@@ -56,7 +68,8 @@ frontend\src-tauri\target\release\bundle\msi\Konduktor_0.1.0_x64_en-US.msi
|
||||
frontend\src-tauri\target\release\bundle\nsis\Konduktor_0.1.0_x64-setup.exe
|
||||
```
|
||||
|
||||
Either one installs the app (bundling the sidecar `.exe` alongside it).
|
||||
Either one installs the app, with the sidecar folder in its `sidecar\` resource
|
||||
folder (`tauri.windows.conf.json`).
|
||||
|
||||
## Rebuilding after changes
|
||||
|
||||
|
||||
@@ -35,6 +35,21 @@ Two independent apps that talk over HTTP:
|
||||
- `adapter.py` — the `LibraryAdapter` / `LibraryDriver` protocols and the
|
||||
error tree (`NotFound` → 404, `InvalidCommand` → 400, `Unsupported` → 422),
|
||||
mapped to status codes once in `main.py` rather than per route.
|
||||
**`move_playlist(node_id, parent_id, index)`** (sidebar drag and drop,
|
||||
`POST /api/playlists/move`) moves any tree node; `index` counts the new
|
||||
parent's children WITHOUT the node, and it returns the node's id AFTER
|
||||
the move — a Traktor folder's / smart playlist's id is its path, so it
|
||||
changes (playlists keep their UUID, so export sets never need
|
||||
retargeting). Gated per node on `PlaylistNode.can_move`. Traktor refuses a
|
||||
folder or smart playlist landing beside a namesake (as rename does);
|
||||
Rekordbox renumbers `Seq` itself (pyrekordbox's version cannot move to the
|
||||
top level) and keeps `masterPlaylists6.xml`'s `ParentId` in step;
|
||||
OneLibrary renumbers `sequenceNo` from 0, and the pdb follows at Save.
|
||||
`POST /api/playlists/{id}/add` takes `duplicates`: `skip` / `add` / `ask`
|
||||
(nothing changes, the count comes back so the UI can ask and resend);
|
||||
`add` only where `capabilities.playlists.duplicates` — Traktor only, since
|
||||
OneLibrary's `playlist_content` is keyed on (playlist, content) and
|
||||
rekordbox's tolerance of a repeat is unmeasured.
|
||||
- `capabilities.py` — `Capabilities`: what the loaded library can persist, so
|
||||
the UI can gate controls instead of branching on the platform.
|
||||
- `query.py` (`TrackIndex`) — all query/filter/sort/facet/stats logic, over
|
||||
@@ -155,7 +170,14 @@ Two independent apps that talk over HTTP:
|
||||
file** (Convert to Stems). An `ipod` MP4 with five AAC stereo 44.1 kHz
|
||||
streams (mix, drums, bass, synths, vox), streams 1-4 `disposition` 0,
|
||||
muxed IN LOCKSTEP, plus a `moov/udta/stem` JSON box appended in place
|
||||
(moov is last, so only two sizes change). The separation is a CALLBACK —
|
||||
(moov is last, so only two sizes change). **Each stream encodes on its
|
||||
own thread** (PyAV releases the GIL in FFmpeg; ~3x faster with `aac`,
|
||||
104 → 35 s for a 5-minute track's real stems) while ONE thread muxes in
|
||||
the single-threaded order, so the file is byte-identical; every codec is
|
||||
opened and the header written before a worker starts, since the first
|
||||
`mux()` would otherwise open codecs a worker is using. `aac_coder=fast`
|
||||
was measured and rejected: 3-4x faster per stream, but it drops whole
|
||||
8-20 kHz bands for moments (twoloop: never). The separation is a CALLBACK —
|
||||
the backend never imports torch; the engine (below) supplies it, the
|
||||
tests a fake. Measured traps: FFmpeg's resampler upmixes mono at -3 dB,
|
||||
so mono is duplicated by hand; resampling does not move time; both
|
||||
@@ -553,7 +575,11 @@ Two independent apps that talk over HTTP:
|
||||
/ `removed`), `audio` (Range), `art`, `upload` (into a folder CONFINED
|
||||
to the content folder — resolve then `is_relative_to`, so neither `..`
|
||||
nor a symlink escapes — never overwriting, `-2` suffixes, per-session
|
||||
so a cancel deletes only its own), `fs/list|space`, `save`, `discard`,
|
||||
so a cancel deletes only its own), `fs/list|space`, `folder/tracks|audio|leads`
|
||||
(the content folder as a Files tree: tags via the shared `FolderScanner`,
|
||||
file facts, `held` = file → the library's id; audio only for a file a
|
||||
listing returned, confined; `leads` = the analysis lead per file, None
|
||||
unless the platform analyses), `save`, `discard`,
|
||||
`history`, `export-sets`, and the stems routes below. Capabilities are
|
||||
the adapter's plus `tracks.audio_destination="library"`,
|
||||
`reference=False`, `paths.remappable=False`, `overwrite_risk="none"`.
|
||||
@@ -602,6 +628,21 @@ Two independent apps that talk over HTTP:
|
||||
Rekordbox's add analysis — waveform, grid AND key — is computed HERE
|
||||
(`core/add_analysis.prepare` with the lead the upload reports, sent as
|
||||
`NewTrack.analysis`).
|
||||
**The content folder browsed like a drive** (decided 2026-10-10,
|
||||
`folder.py`): `/api/fs/drives` lists the server FIRST (`kind:
|
||||
"server"`, path `server:`) while a remote is open, and the ordinary
|
||||
Files routes (`/api/fs/folders`, `/api/folder/*`) take `server:` +
|
||||
the path ON THE SERVER — so the folder view, deck and add dialog need no
|
||||
second set of routes, and a server path is never taken for the same path
|
||||
here. `RemoteAdapter.folder_listing` remembers what was listed
|
||||
(`ServerFiles`, a read-only source); `folder_audio` downloads into the
|
||||
shared cache by the same facts as a library track's. Adding one is IN
|
||||
PLACE (`on_library_host` → `importer.plan_on_host` + `run(reference=True)`):
|
||||
nothing uploaded, nothing asked; files the library holds map to their
|
||||
ids; where the server reports a lead the file is fetched and analysed
|
||||
here, as an upload is. Server paths go back to the server in its own
|
||||
spelling (`_server_paths`), never `str(Path(…))`, which rewrites them on
|
||||
Windows.
|
||||
**Convert to Stems** (`stems/remote_convert.py`): the server plans
|
||||
(`/v1/stems/plan`, its `convert.plan`), this computer downloads,
|
||||
separates and encodes, uploads each verified file (`/v1/stems/stage`,
|
||||
@@ -776,9 +817,17 @@ Two independent apps that talk over HTTP:
|
||||
expandable Local Storage. A drive carrying a OneLibrary library opens as a
|
||||
device as before, and EVERY drive has a lazily-fetched **Files** tree;
|
||||
clicking a folder is the `folder` source kind — its audio in the ordinary
|
||||
table, read-only via `readonly_cause: 'not_in_library'`, with files the
|
||||
collection already holds checked off in the # column (`TrackTable`'s
|
||||
`marked`). A browsed device is read-only (cause `browsing`); **"Open for
|
||||
table, with files the collection already holds checked off in the #
|
||||
column (`TrackTable`'s `marked`). **A held file's row IS the collection
|
||||
track** (decided 2026-10-10: `main._folder_rows`; `FolderTracks.files` maps
|
||||
its collection id back to the folder id that adding takes): it shows the
|
||||
collection's key/rating/cues/plays, loads into the deck as origin
|
||||
`collection` (`loadTrack`), edits inline and from the menu, and drops onto
|
||||
a playlist directly. The table runs on the COLLECTION's capabilities; a
|
||||
LOOSE row's edit — inline (`TableMeta.mayEdit`, asked before the editor
|
||||
opens), rating, Edit Tags / Analyze / Auto Hotcues / Stems — asks to add
|
||||
it first (`askToAdd`), and in the deck it stays read-only
|
||||
(`not_in_library`). A browsed device is read-only (cause `browsing`); **"Open for
|
||||
editing…"** — the drive row's right-click menu, and a button while browsing
|
||||
a device whose caps say `browsing` — opens it as THE library via App's
|
||||
`openForEditing` (unsaved-edits confirm, source closed, library opened).
|
||||
@@ -811,6 +860,21 @@ Two independent apps that talk over HTTP:
|
||||
space below the rows creates at the top level, and the new node is named
|
||||
in place (Esc or an empty name creates nothing). Rename/Delete are on the
|
||||
same menu and the row's hover buttons, which share one set of actions.
|
||||
**Drag and drop** (lib/drag.tsx, below): a row is a drag source and a drop
|
||||
target with ZONES — a playlist's upper/lower half is before/after; a
|
||||
folder's top/bottom quarter before/after and its middle INTO (appended),
|
||||
except the bottom quarter of an OPEN folder, which is "first inside"; the
|
||||
empty space below the rows is "end of the top level". Never into the
|
||||
dragged node's own subtree, and a drop that would change nothing shows no
|
||||
indicator. Holding over a collapsed folder opens it after 0.6 s (tracks
|
||||
too, so nested playlists are reachable). Tracks dropped on a playlist go
|
||||
through `lib/addTracks.ts` — shared with the context menu's "Add to" —
|
||||
which ASKS about duplicates where the platform can hold them (decided:
|
||||
ask each time), and Option/Alt moves them out of the editable playlist
|
||||
they came from. A device's or Files folder's tracks open `ImportDialog`
|
||||
(`trackIds` + `target`) / `AddFilesDialog` with the target filled in
|
||||
(`onAddForeign`), so copy-vs-reference is still asked. Export rows take the
|
||||
collection's tracks and any playlist/folder (as "Add to export" does).
|
||||
A Traktor folder's id is its PATH of names, so the `PATCH`/`DELETE`
|
||||
playlist routes take a `:path` param, a folder name may not contain `/`,
|
||||
and renaming onto a sibling folder's name is refused), `QuitGuard` (mounted in `main.tsx`: the desktop shell PREVENTS window close /
|
||||
@@ -818,8 +882,18 @@ Two independent apps that talk over HTTP:
|
||||
shell quits anyway after ~2 s without one, so a hung page cannot trap the
|
||||
user), quits (`quit_now`) when nothing is unsaved, else asks Save · Discard
|
||||
· Cancel; the sidecar is killed only at `RunEvent::Exit`, after the answer;
|
||||
browser dev gets `beforeunload`), `SaveBar` (+ "Discard changes…" when
|
||||
dirty, and the settings gear beside it, whose menu opens `ShortcutsDialog` — the shortcut list is written out BY HAND, so a new or changed shortcut in `PrepStrip` / `TrackTable` must be added there too), `Toolbar` (search/filters; columns are chosen by right-clicking the table header),
|
||||
browser dev gets `beforeunload`), `StartupGate` (mounted in `main.tsx`
|
||||
around everything but `AmbientBackdrop`: the shell opens the window AT ONCE
|
||||
and starts the sidecar beside it, so nothing that calls the API mounts
|
||||
until `backend_status` / `konduktor://backend` says ready, which is when
|
||||
`setApiBase` gets the sidecar's address. Meanwhile `StartupScreen` shows
|
||||
the icon with a generated waveform scrolling under a fixed playhead, a
|
||||
"first launch takes longer" note after 6 s, Quit / Keep waiting after 90 s,
|
||||
and if the sidecar exits its last 30 output lines with Copy details / Quit
|
||||
/ Try again (`backend_restart`). The shell has no timeout of its own. Before
|
||||
ready it answers quit requests itself — nothing can be unsaved — and stops
|
||||
at ready so it never races `QuitGuard`), `SaveBar` (+ "Discard changes…" when
|
||||
dirty, and the settings gear beside it, whose menu opens `ShortcutsDialog` — the shortcut list is written out BY HAND, so a new or changed shortcut in `PrepStrip` / `TrackTable` must be added there too — and `AppSettings` ("Konduktor Settings…": app-level prefs, each with its default in `APP_SETTING_DEFAULTS` and read through `useAppSetting`; today `expandPlaylistFolders` and `exportRootFolder`, both default off — the latter read by the backend at `run_export` and passed down as `ExportPayload.root_folder`. The Sidebar holds folder open state as per-id overrides of that setting, reset on a new library or a change of the setting, and carried to the new ids when a rename/move changes a folder's path id)), `Toolbar` (search/filters; columns are chosen by right-clicking the table header),
|
||||
`TrackTable` (**the one track list** — All Tracks, playlists, exports and
|
||||
devices. TanStack Table + **virtualized** grid; per-row play button,
|
||||
configurable columns, header sorting, inline double-click editing, and
|
||||
@@ -838,7 +912,28 @@ Two independent apps that talk over HTTP:
|
||||
not dnd-kit sortable**: a SortableContext around the virtualizer loops on its
|
||||
flushSync-driven measurement — which is why playlists were once a separate,
|
||||
non-virtualized `PlaylistTable`. Fixed 44 px rows make the drop index just
|
||||
pointer-y / ROW_HEIGHT. dnd-kit still reorders the header's columns.)
|
||||
pointer-y / ROW_HEIGHT. dnd-kit still reorders the header's columns.
|
||||
Every table's rows are a DRAG SOURCE through `lib/drag.tsx` (a selected row
|
||||
carries the selection, the payload's `lead` is the row grabbed, `dragFrom`
|
||||
says whose ids they are and which editable playlist an Option-drag leaves);
|
||||
the in-table reorder is just the table's own drop target.)
|
||||
**`lib/drag.tsx` — drag and drop across the window** (decided 2026-10-06,
|
||||
[the discussion](.claude/discussions/discuss-drag-and-drop-2026-10-06.md)):
|
||||
ONE gesture, the TARGET decides what it means. Pointer events, NOT HTML5
|
||||
DnD — Tauri's webview captures native drag events for file drops on
|
||||
Windows. A source calls `beginDrag` past a 6 px threshold (`usePressToDrag`
|
||||
for plain elements); targets register with `useDropTarget({ hint, label,
|
||||
onDrop })` and are found by `elementFromPoint` then up the ancestors, the
|
||||
innermost whose `hint` is non-null winning, so a target declines a spot by
|
||||
returning null. A module-level store read through narrow
|
||||
`useSyncExternalStore` selectors: a move re-renders only the target under
|
||||
the pointer and the ghost (`DragLayer`, mounted in main.tsx), never the
|
||||
table. Esc cancels (before every other Esc handler); the click after a drop
|
||||
is swallowed; `data-drag-scroll="<top inset>"` makes an element scroll at a
|
||||
20 px edge after a 250 ms dwell — any less and the first/last visible row
|
||||
could not be dropped on. Targets: playlist + export rows (Sidebar,
|
||||
ExportsSection), the tree's zones, the table's reorder, and the DECK
|
||||
(App), which loads the grabbed row paused, in its own origin.
|
||||
`ConvertStemsDialog` (**Convert to Stems**, one dialog — decided: Where =
|
||||
Replace the originals (its option STATES that Save deletes them, since
|
||||
the choice is remembered and may be preselected) or Save to a folder; In
|
||||
@@ -884,7 +979,11 @@ Two independent apps that talk over HTTP:
|
||||
`ContextMenu` (supports `▸` submenus, section headings, separators and
|
||||
checkbox items that toggle without closing — the header row's right-click
|
||||
column chooser uses those; "Add to" lists
|
||||
playlists + exports and acts on the whole selection; "Remove ▸" holds
|
||||
playlists + exports and acts on the whole selection; in an editable
|
||||
playlist "Set Position…" (`SetPositionDialog`, `lib/playlistOrder.ts`)
|
||||
moves the selection as ONE block in playlist order so its first track
|
||||
lands at #N — allowed while sorted/filtered, unlike drag, because it
|
||||
reorders the FULL entry list; "Remove ▸" holds
|
||||
From this playlist / From this export / Grids / Hotcues / From collection,
|
||||
each behind a `ConfirmDialog` — as is the playlist Delete key. Enter
|
||||
confirms unless a button has focus, so Tab-to-Cancel + Enter cancels) + `EditTagsDialog`
|
||||
@@ -1006,6 +1105,7 @@ Two independent apps that talk over HTTP:
|
||||
|
||||
```bash
|
||||
./dev.sh # start both servers (see README for one-time setup)
|
||||
.\dev.ps1 # the same on Windows (BUILDING-WINDOWS.md)
|
||||
|
||||
# Backend
|
||||
cd backend && source .venv/bin/activate
|
||||
@@ -1051,10 +1151,17 @@ serialization path.** It enforces:
|
||||
KEY attribute and one `<MUSICAL_KEY>` between LOUDNESS and CUE_V2 in
|
||||
Traktor's layout; the encoding matches the real collection; a Camelot
|
||||
collection gets Camelot; an ADDED Pioneer key ("Abm") lands as "6m"; and the
|
||||
key tag reaches TKEY / `initialkey` in MP3, FLAC and M4A.
|
||||
key tag reaches TKEY / `initialkey` in MP3, FLAC and M4A. And
|
||||
**`move_playlist`** (O): the COLLECTION is untouched, a move round-trips and
|
||||
moving back is byte-identical; a folder moves with its subtree and answers
|
||||
its new path id; into its own descendant / beside a namesake is refused with
|
||||
nothing changed; a smart playlist moves by its path id; a no-op is not dirty.
|
||||
The guard that catches serialization regressions like the lxml reformatting bug.
|
||||
- `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays
|
||||
Traktor-valid, backup-first, COLLECTION byte-identical, original untouched.
|
||||
Traktor-valid, backup-first, COLLECTION byte-identical, original untouched;
|
||||
plus the drag-and-drop routes: `/add`'s three `duplicates` modes (`ask`
|
||||
changes nothing and counts) and `/api/playlists/move` (path id answered,
|
||||
400 into itself, 404 unknown).
|
||||
- `test_timebase.py` — Traktor's MP3 time base: `mp3_gapless` on generated
|
||||
MP3s (header found after a 1 MB ID3 tag; header-less has none), the offset
|
||||
in samples (2257 at 44.1 and 48 kHz, 0 header-less / WAV / missing), every
|
||||
@@ -1071,7 +1178,10 @@ serialization path.** It enforces:
|
||||
48 kHz resampling does not move time; MP3 and FLAC through both encoders give
|
||||
five streams with only the mix enabled, no shift (cross-correlation), the
|
||||
bitrate rule (256 floor, lossless 320), every tag + cover; `verify` refuses a
|
||||
shifted, truncated or box-less file; a raising checkpoint cancels.
|
||||
shifted, truncated or box-less file; a raising checkpoint cancels. The
|
||||
threaded encode is byte-identical to a single-threaded reference (with each
|
||||
encoder present), reports progress 0 → 1, and a cancel or a failing encoder
|
||||
thread leaves no thread running.
|
||||
- `test_stem_swap.py` — `apply_stem_swaps` on a temp copy of the real
|
||||
collection with a generated MP3 (with header) and a real stem file: prep
|
||||
reads back at the same decoded second while its START moves by the 2257-
|
||||
@@ -1122,7 +1232,9 @@ serialization path.** It enforces:
|
||||
against SQLite). Asserts a no-op save changes zero rows; a one-field edit
|
||||
changes exactly two — the track and `agentRegistry.localUpdateCount` — with the
|
||||
counter up by one and the edited row stamped with it; edits are invisible on
|
||||
disk until save; and playlist create/fill/rename/delete round-trip. And
|
||||
disk until save; and playlist create/fill/rename/delete round-trip, and
|
||||
`move_playlist` (E2) changes only `djmdPlaylist` rows + the counter with
|
||||
`Seq` 1..n in both parents. And
|
||||
**removing a track** deletes exactly the rows Rekordbox 7 deletes (measured
|
||||
2026-10-01 by diffing a removal made in Rekordbox itself: `djmdContent`,
|
||||
`djmdCue`, `contentCue`, `contentFile`, `djmdMixerParam`, `djmdSongPlaylist`
|
||||
@@ -1161,7 +1273,8 @@ serialization path.** It enforces:
|
||||
changes zero rows, a title edit exactly `content.title` (no counter, as
|
||||
rekordbox), dates as `YYYY-MM-DD` text, lookups found-or-created with
|
||||
`nameForSearch` NULL, a new playlist on top with siblings shifted, entries
|
||||
from 1; and the stick hazards — another app's write refused, an unplugged
|
||||
from 1, a move changing only parent + `sequenceNo` (0..n-1 in both
|
||||
parents); and the stick hazards — another app's write refused, an unplugged
|
||||
drive keeps the edits, stale `-shm` deleted, the backup holds the old rows,
|
||||
the drive never held open, file tags written (title yes, rating no). And
|
||||
`set_key`: an existing key changes only `content.key_id` and reaches TKEY as
|
||||
@@ -1198,6 +1311,9 @@ serialization path.** It enforces:
|
||||
companion cue is invented), that the existing 8,485 entries render
|
||||
byte-identically, that the job registry runs/fails/cancels, and that a
|
||||
cancelled import leaves **no orphaned audio and an untouched collection**.
|
||||
And the route with chosen `track_ids` + `into_playlist` + `export_id` (a
|
||||
device drop): only that track, into the playlist and the export, no drive
|
||||
folder made.
|
||||
- `test_grid_detect.py` — beatgrid detection on **synthetic** audio, so the
|
||||
tempo and first beat are known rather than borrowed from another analyser:
|
||||
exact integer and non-integer BPMs, the 125 BPM the old detector could not
|
||||
@@ -1345,7 +1461,11 @@ serialization path.** It enforces:
|
||||
only the edited `<ENTRY>` THROUGH the trip, one download per file, Analyze
|
||||
on the cached copy, export (and a re-export copying nothing), an upload
|
||||
stored in the mapping's stored form, takeover → read-only at once,
|
||||
reopening names the holder and the edits left, leaving releases.
|
||||
reopening names the holder and the edits left, leaving releases. And the
|
||||
content folder as a drive: listed first, confined, held files ticked off,
|
||||
auditioned with one download, an add IN PLACE (no upload, the held one not
|
||||
added twice, both into the playlist, analysed here when the server reports
|
||||
a lead).
|
||||
- `test_remote_stems.py` — Convert to Stems on a remote with the FAKE engine:
|
||||
the plan's transfer and two-machine space, Replace parks and swaps ON THE
|
||||
SERVER (saved file untouched until Save, which deletes the parked
|
||||
@@ -1366,14 +1486,25 @@ frontend at `http://localhost:5173`.
|
||||
|
||||
1. **`traktor-nml-utils` MUST come from GitHub, not PyPI.** PyPI's `3.1.0` is
|
||||
stale and **cannot parse Traktor Pro 4 (NML v20)** files — its strict parser
|
||||
dies on the v4 `<GRID>` element inside `CUE_V2`. `requirements.txt` pins the
|
||||
GitHub `master` (v4.0.0). Do not "simplify" this to a plain PyPI pin.
|
||||
dies on the v4 `<GRID>` element inside `CUE_V2`. `requirements.txt` pins a
|
||||
GitHub commit (v4.0.0). Do not "simplify" this to a plain PyPI pin.
|
||||
**`pyrekordbox` is now the same situation**: PyPI's latest (0.4.4) has no
|
||||
`devicelib_plus`, which is the OneLibrary (`exportLibrary.db`) reader, so
|
||||
`requirements.txt` pins the GitHub master. That upgrade renamed `db6` →
|
||||
`masterdb` and `tables` → `models` and moved `BLOB` out of `db6.database`;
|
||||
the Rekordbox adapter uses the new names. `db6` still works as a deprecated
|
||||
alias and is **removed in 0.6.0**.
|
||||
`onelibrary` module, which is the OneLibrary (`exportLibrary.db`) reader
|
||||
(`OneLibrary` class; `devicelib_plus` / `DeviceLibraryPlus` before upstream's
|
||||
rename), nor `masterdb` (formerly `db6`, now removed upstream; `tables` →
|
||||
`models`, `BLOB` in `masterdb.database`).
|
||||
**Both GitHub deps are pinned to a COMMIT, never bare master**: the
|
||||
`devicelib_plus` → `onelibrary` rename reached CI's fresh install while dev
|
||||
venvs kept the old commit, and a release shipped that could not export or
|
||||
read OneLibrary while every local test passed. Move a pin on purpose, with
|
||||
`./run_tests.sh`.
|
||||
**PyAV: open files for reading through `core/pyav.open_input`, never
|
||||
`av.open` directly.** PyAV 18 refuses a file with non-UTF-8 tags unless
|
||||
given `metadata_errors="ignore"`; PyAV 19 removed that keyword. CI installs
|
||||
fresh (it got 19) while a dev venv keeps what it had (18), so code passing
|
||||
the keyword passed every local test and shipped a release whose deck played
|
||||
every stem track as the mix. `requirements.txt` caps `av<20`: check
|
||||
`pyav.py` before raising it.
|
||||
2. **The collection is real, irreplaceable data — protect it.** Every save
|
||||
writes a timestamped `.bak` first (into a `backups/` folder next to the
|
||||
collection). When testing writes, point `KONDUKTOR_NML` at a COPY. Warn the
|
||||
@@ -1383,6 +1514,21 @@ frontend at `http://localhost:5173`.
|
||||
render is the library's own pipeline (see "Write path"), which reproduces
|
||||
Traktor's byte-exact layout so a no-op save is byte-identical and only edited
|
||||
objects diff. `test_save_fidelity.py` enforces this.
|
||||
4. **The desktop sidecar is a PyInstaller ONEDIR folder — never go back to
|
||||
onefile.** A onefile binary unpacked ~390 native libraries into a NEW temp
|
||||
folder on every launch, and macOS (XProtect / syspolicyd) checks each library
|
||||
it has not seen before as it is dlopen()ed, keyed per FILE: the window
|
||||
appeared only after ~10 s on every launch (measured 2026-10-12: 95 s to load
|
||||
them all fresh, 1 s once seen). As a folder in the app they are checked
|
||||
once; a launch is ~0.5 s. `build_sidecar.*` stages
|
||||
`src-tauri/binaries/konduktor-sidecar/`; `lib.rs` spawns
|
||||
`<resources>/sidecar/konduktor-sidecar[.exe]`. On macOS it is bundled by
|
||||
`tauri.macos.conf.json`'s `bundle.macOS.files`, NOT `bundle.resources`:
|
||||
the resource copier follows symlinks, turning PyInstaller's 37 library
|
||||
aliases (`_internal/libavcodec… -> av/.dylibs/…`, `Python.framework`'s
|
||||
`Versions/Current`) into second copies a library could be loaded twice
|
||||
from. Windows has no such links and uses `resources`
|
||||
(`tauri.windows.conf.json`).
|
||||
|
||||
## Data model notes
|
||||
|
||||
@@ -1648,7 +1794,11 @@ that number and nothing else — everything derives from it:
|
||||
**volume-relative** `DIR`, never a host path — so a USB export is portable by
|
||||
construction, and the `.nml` cannot be written until the destination is known.
|
||||
Also settled: loose tracks land in an **"Other" playlist**, playlist folders
|
||||
are preserved, and the export is a **standalone `collection.nml`** the user
|
||||
are preserved — at the exported library's TOP LEVEL by default; the
|
||||
`exportRootFolder` setting (`ExportPayload.root_folder`) nests the whole
|
||||
tree, Other included, in one folder named after the export, in all four
|
||||
writers (decided 2026-10-12: the export is a library of its own, so the
|
||||
wrapper was one more click at the gig), and the export is a **standalone `collection.nml`** the user
|
||||
swaps into a Traktor install — so it needs the full skeleton, verified from the
|
||||
real file: `<NML VERSION="20">`, `<HEAD>`, `<COLLECTION ENTRIES>`,
|
||||
`<SETS ENTRIES="0">`, `<PLAYLISTS>` wrapping a `$ROOT` FOLDER node with a
|
||||
@@ -1679,7 +1829,7 @@ that number and nothing else — everything derives from it:
|
||||
deliberately NOT in the fixture, since they carry the machine's name and
|
||||
UUIDs; those are generated fresh per export.
|
||||
- **The two Pioneer key blobs are different.** `masterdb`'s key and
|
||||
`devicelib_plus`'s are not the same string; mixing them up yields a database
|
||||
`onelibrary`'s are not the same string; mixing them up yields a database
|
||||
Rekordbox cannot open.
|
||||
`adapters/onelibrary/export.py` writes a whole drive (`PIONEER/rekordbox/
|
||||
exportLibrary.db` from the checked-in DDL, plus ANLZ under `PIONEER/USBANLZ/`,
|
||||
@@ -1895,6 +2045,9 @@ that number and nothing else — everything derives from it:
|
||||
yet**, since nothing can be written. Note the OneLibrary work already demonstrated
|
||||
creating an `exportLibrary.db` from nothing, and `fixtures/onelibrary/schema.sql`
|
||||
is the DDL to do it with.
|
||||
- ✅ **Drag and drop** (2026-10-06) — tracks onto playlists / exports / the
|
||||
deck, playlists around the tree and onto exports; see `lib/drag.tsx` and
|
||||
the Sidebar under Architecture.
|
||||
- ✅ **Remote libraries** (2026-10-02) — a Konduktor server in a container
|
||||
(TrueNAS) holds a Traktor or Rekordbox library; the app opens it as
|
||||
"Remote": browse, prep, edit, Save (versioned on the server), export sticks,
|
||||
|
||||
@@ -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",
|
||||
)
|
||||
@@ -193,6 +193,7 @@ class OneLibraryAdapter:
|
||||
can_rename=writable,
|
||||
can_delete=writable,
|
||||
can_contain_children=kind == "folder",
|
||||
can_move=writable,
|
||||
)
|
||||
parent = str(getattr(r, "playlist_id_parent", 0) or 0)
|
||||
parents[node_id] = "root" if parent in ("0", "", "None") else parent
|
||||
@@ -425,6 +426,10 @@ class OneLibraryAdapter:
|
||||
self._require_writable("Deleting playlists")
|
||||
self._store.delete_playlist(node_id)
|
||||
|
||||
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
|
||||
self._require_writable("Moving playlists")
|
||||
return self._store.move_playlist(node_id, parent_id, index)
|
||||
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
|
||||
self._require_writable("Editing playlists")
|
||||
return self._store.set_playlist_entries(node_id, track_ids)
|
||||
|
||||
@@ -49,7 +49,7 @@ class OneLibraryDriver:
|
||||
def _has_onelibrary_schema(path: Path) -> bool:
|
||||
try:
|
||||
import sqlcipher3.dbapi2 as sqlcipher
|
||||
from pyrekordbox.devicelib_plus.database import BLOB
|
||||
from pyrekordbox.onelibrary.database import BLOB
|
||||
from pyrekordbox.utils import deobfuscate
|
||||
except ImportError: # pragma: no cover — dependency missing
|
||||
return False
|
||||
|
||||
@@ -121,7 +121,7 @@ class OneLibraryExporter:
|
||||
|
||||
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
|
||||
import sqlcipher3.dbapi2 as sqlcipher
|
||||
from pyrekordbox.devicelib_plus.database import BLOB
|
||||
from pyrekordbox.onelibrary.database import BLOB
|
||||
from pyrekordbox.utils import deobfuscate
|
||||
|
||||
root = Path(destination)
|
||||
@@ -381,7 +381,8 @@ class OneLibraryExporter:
|
||||
# ---- playlists -----------------------------------------------------------
|
||||
|
||||
def _write_playlists(self, con, payload: ExportPayload, by_source: dict) -> None:
|
||||
"""One folder named after the export, with the tree preserved under it.
|
||||
"""The tree preserved — at the top level (parent NULL), or with
|
||||
`payload.root_folder` under one folder named after the export.
|
||||
|
||||
`playlist` is a flat table with `playlist_id_parent`, so folders and
|
||||
playlists are the same row kind told apart by `attribute` (1 = folder).
|
||||
@@ -397,8 +398,8 @@ class OneLibraryExporter:
|
||||
)
|
||||
return next_id[0]
|
||||
|
||||
root = add(payload.name, None, folder=True)
|
||||
folders: dict[tuple[str, ...], int] = {(): root}
|
||||
root = add(payload.name, None, folder=True) if payload.root_folder else None
|
||||
folders: dict[tuple[str, ...], int | None] = {(): root}
|
||||
|
||||
for playlist in payload.playlists:
|
||||
parent = root
|
||||
@@ -427,8 +428,10 @@ class OneLibraryExporter:
|
||||
)
|
||||
|
||||
|
||||
#: rekordbox's `fileType` codes, as `pyrekordbox.devicelib_plus.FileType` has them.
|
||||
#: `.stem.m4a` (a Traktor STEM) is an M4A to a Pioneer player.
|
||||
#: rekordbox's `fileType` codes. `.stem.m4a` (a Traktor STEM) is an M4A to a
|
||||
#: Pioneer player. `pyrekordbox.onelibrary.FileType` now also lists MP4 = 3 (the
|
||||
#: `.mp4` container) and ALAC = 6 (an ALAC `.m4a`); neither is measured here, so
|
||||
#: both still write 4.
|
||||
_FILE_TYPES = {".mp3": 1, ".m4a": 4, ".mp4": 4, ".aac": 4, ".flac": 5, ".wav": 11,
|
||||
".aif": 12, ".aiff": 12}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""OneLibrary rows -> the generic projection.
|
||||
|
||||
The only place a ``devicelib_plus`` ORM object becomes a generic `Track` /
|
||||
The only place a ``pyrekordbox.onelibrary`` ORM object becomes a generic `Track` /
|
||||
`TrackCues`. Everything above this file sees generic types exclusively.
|
||||
|
||||
Field conventions are read off a real rekordbox 7 export rather than guessed:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""The retained native model for a OneLibrary drive.
|
||||
|
||||
Owns the drive's ``exportLibrary.db`` and the layout around it, and is the only
|
||||
place a ``pyrekordbox.devicelib_plus`` row or an ANLZ tag is touched.
|
||||
place a ``pyrekordbox.onelibrary`` row or an ANLZ tag is touched.
|
||||
|
||||
The database is SQLCipher-encrypted SQLite, like Rekordbox's ``master.db``, but
|
||||
with a **different and universal key**: every OneLibrary drive from every vendor
|
||||
@@ -170,10 +170,10 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
def _load(self) -> None:
|
||||
"""Copy the drive's database into app-data and open the copy."""
|
||||
try:
|
||||
from pyrekordbox.devicelib_plus import DeviceLibraryPlus
|
||||
from pyrekordbox.onelibrary import OneLibrary
|
||||
except ImportError as ex: # pragma: no cover — dependency missing
|
||||
raise LibraryNotSupported(
|
||||
"Reading OneLibrary drives needs pyrekordbox with devicelib_plus"
|
||||
"Reading OneLibrary drives needs pyrekordbox with its onelibrary module"
|
||||
) from ex
|
||||
_clear_stale_work()
|
||||
work = Path(tempfile.mkdtemp(prefix="drive-", dir=_work_root()))
|
||||
@@ -186,7 +186,7 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
sidecar = self.path.with_name(self.path.name + suffix)
|
||||
if sidecar.is_file() and sidecar.stat().st_size:
|
||||
shutil.copyfile(sidecar, working.with_name(working.name + suffix))
|
||||
db = DeviceLibraryPlus(str(working))
|
||||
db = OneLibrary(str(working))
|
||||
except Exception as ex: # noqa: BLE001 — surfaced as a clean 4xx
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
raise LibraryNotSupported(f"Could not open OneLibrary database: {ex}") from ex
|
||||
@@ -206,7 +206,7 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
"""Release the working copy and delete it.
|
||||
|
||||
The drive itself is never held open (see the module docstring); the copy
|
||||
is, and `DeviceLibraryPlus.close()` only unregisters events, so the
|
||||
is, and `OneLibrary.close()` only unregisters events, so the
|
||||
session and engine are closed here explicitly.
|
||||
"""
|
||||
db, self._db = self._db, None
|
||||
@@ -316,7 +316,7 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
image_id = getattr(self.content(track_id), "image_id", None)
|
||||
if not image_id:
|
||||
return None
|
||||
from pyrekordbox.devicelib_plus import models
|
||||
from pyrekordbox.onelibrary import models
|
||||
|
||||
row = self._require_db().query(models.Image).filter_by(image_id=image_id).one_or_none()
|
||||
small = self.layout.resolve(getattr(row, "path", None)) if row is not None else None
|
||||
@@ -456,7 +456,7 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
"""
|
||||
if not name:
|
||||
return None
|
||||
from pyrekordbox.devicelib_plus import models
|
||||
from pyrekordbox.onelibrary import models
|
||||
|
||||
model = getattr(models, model_name)
|
||||
pk = f"{model.__tablename__}_id"
|
||||
@@ -497,7 +497,7 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
stick already has. A new key gets rekordbox's own spelling."""
|
||||
if wheel is None or mode is None:
|
||||
return None
|
||||
from pyrekordbox.devicelib_plus import models
|
||||
from pyrekordbox.onelibrary import models
|
||||
|
||||
from ..rekordbox.projection import parse_key, render_key
|
||||
|
||||
@@ -567,7 +567,7 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
|
||||
# ---- writes: playlists --------------------------------------------------
|
||||
def _playlist(self, node_id: str):
|
||||
from pyrekordbox.devicelib_plus import models
|
||||
from pyrekordbox.onelibrary import models
|
||||
|
||||
try:
|
||||
pid = int(node_id)
|
||||
@@ -579,14 +579,14 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
return row
|
||||
|
||||
def _siblings(self, parent_id: int, *, excluding: int | None = None) -> list:
|
||||
from pyrekordbox.devicelib_plus import models
|
||||
from pyrekordbox.onelibrary import models
|
||||
|
||||
rows = self._require_db().query(models.Playlist).filter_by(playlist_id_parent=parent_id).all()
|
||||
rows = [r for r in rows if r.playlist_id != excluding]
|
||||
return sorted(rows, key=lambda r: (int(r.sequenceNo or 0), int(r.playlist_id)))
|
||||
|
||||
def _create_node(self, name: str, parent_id: str | None, attribute: int) -> str:
|
||||
from pyrekordbox.devicelib_plus import models
|
||||
from pyrekordbox.onelibrary import models
|
||||
|
||||
name = (name or "").strip()
|
||||
noun = "folder" if attribute == ATTRIBUTE_FOLDER else "playlist"
|
||||
@@ -631,7 +631,7 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
def delete_playlist(self, node_id: str) -> None:
|
||||
"""Delete a playlist, or a folder WITH everything in it, and close the gap
|
||||
its `sequenceNo` leaves among its siblings."""
|
||||
from pyrekordbox.devicelib_plus import models
|
||||
from pyrekordbox.onelibrary import models
|
||||
|
||||
db = self._require_db()
|
||||
row = self._playlist(node_id)
|
||||
@@ -652,9 +652,48 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
db.flush()
|
||||
self._journal.record("playlist", "delete", name)
|
||||
|
||||
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
|
||||
"""Move a node to `index` among `parent_id`'s children, renumbering
|
||||
`sequenceNo` from 0 in both parents as create and delete do. The
|
||||
Device Library's playlist tree follows at Save (`device_library`
|
||||
mirrors parent and sort from these rows)."""
|
||||
db = self._require_db()
|
||||
row = self._playlist(node_id)
|
||||
dest = 0
|
||||
if parent_id:
|
||||
folder = self._playlist(parent_id)
|
||||
if int(folder.attribute or 0) != ATTRIBUTE_FOLDER:
|
||||
raise InvalidCommand("A playlist can only be moved into a folder")
|
||||
dest = int(folder.playlist_id)
|
||||
ancestor = folder
|
||||
while ancestor is not None:
|
||||
if int(ancestor.playlist_id) == int(row.playlist_id):
|
||||
raise InvalidCommand("A folder cannot be moved into itself")
|
||||
up = int(ancestor.playlist_id_parent or 0)
|
||||
ancestor = self._playlist(str(up)) if up else None
|
||||
source = int(row.playlist_id_parent or 0)
|
||||
siblings = self._siblings(dest, excluding=row.playlist_id)
|
||||
index = max(0, min(int(index), len(siblings)))
|
||||
order = siblings[:index] + [row] + siblings[index:]
|
||||
if source == dest and [r.playlist_id for r in order] == [
|
||||
r.playlist_id for r in self._siblings(dest)
|
||||
]:
|
||||
return str(row.playlist_id)
|
||||
row.playlist_id_parent = dest
|
||||
for n, r in enumerate(order):
|
||||
if int(r.sequenceNo or 0) != n:
|
||||
r.sequenceNo = n
|
||||
if source != dest:
|
||||
for n, r in enumerate(self._siblings(source, excluding=row.playlist_id)):
|
||||
if int(r.sequenceNo or 0) != n:
|
||||
r.sequenceNo = n
|
||||
db.flush()
|
||||
self._journal.record("playlist", "move", row.name)
|
||||
return str(row.playlist_id)
|
||||
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
|
||||
"""Replace a playlist's contents, in order, numbered from 1 (measured)."""
|
||||
from pyrekordbox.devicelib_plus import models
|
||||
from pyrekordbox.onelibrary import models
|
||||
|
||||
db = self._require_db()
|
||||
playlist = self._playlist(node_id)
|
||||
@@ -1339,9 +1378,9 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
return SaveOutcome(summary=summary, snapshot=None, tag_results=tag_results)
|
||||
|
||||
def _reopen_working(self, work: Path) -> None:
|
||||
from pyrekordbox.devicelib_plus import DeviceLibraryPlus
|
||||
from pyrekordbox.onelibrary import OneLibrary
|
||||
|
||||
self._db, self._work = DeviceLibraryPlus(str(work / self.path.name)), work
|
||||
self._db, self._work = OneLibrary(str(work / self.path.name)), work
|
||||
self._content_cache = None
|
||||
self._by_id = None
|
||||
|
||||
|
||||
@@ -172,6 +172,7 @@ class RekordboxAdapter:
|
||||
can_rename=writable,
|
||||
can_delete=writable,
|
||||
can_contain_children=kind == "folder",
|
||||
can_move=writable,
|
||||
)
|
||||
parent = str(r.ParentID or "root")
|
||||
parents[node_id] = "root" if parent in ("0", "", "root", "None") else parent
|
||||
@@ -276,6 +277,10 @@ class RekordboxAdapter:
|
||||
self._require_writable("Deleting playlists")
|
||||
self._store.delete_playlist(node_id)
|
||||
|
||||
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
|
||||
self._require_writable("Moving playlists")
|
||||
return self._store.move_playlist(node_id, parent_id, index)
|
||||
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
|
||||
self._require_writable("Editing playlists")
|
||||
return self._store.set_playlist_entries(node_id, track_ids)
|
||||
|
||||
@@ -198,8 +198,9 @@ class RekordboxDeviceExporter:
|
||||
|
||||
@staticmethod
|
||||
def _playlists(payload: ExportPayload, by_source: dict) -> tuple[list[bytes], list[bytes]]:
|
||||
"""The tree under one folder named after the export, as the other
|
||||
targets build it. `sort_order` is a node's position among its siblings."""
|
||||
"""The tree as the other targets build it — at the top level (parent
|
||||
0), or with `payload.root_folder` under one folder named after the
|
||||
export. `sort_order` is a node's position among its siblings."""
|
||||
tree: list[bytes] = []
|
||||
entries: list[bytes] = []
|
||||
next_id = [0]
|
||||
@@ -220,7 +221,7 @@ class RekordboxDeviceExporter:
|
||||
index += 1
|
||||
entries.append(pdb.playlist_entry_row(index, track_id, playlist_id))
|
||||
|
||||
root = add(payload.name, 0, folder=True)
|
||||
root = add(payload.name, 0, folder=True) if payload.root_folder else 0
|
||||
folders: dict[tuple[str, ...], int] = {(): root}
|
||||
for playlist in payload.playlists:
|
||||
parent = root
|
||||
|
||||
@@ -125,7 +125,7 @@ class RekordboxExporter:
|
||||
)
|
||||
|
||||
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
|
||||
# `masterdb`'s OWN key blob. `devicelib_plus` has a different one — a
|
||||
# `masterdb`'s OWN key blob. `onelibrary` has a different one — a
|
||||
# OneLibrary drive uses a universal key shared across vendors, and
|
||||
# master.db does not. Mixing them up produces a database Rekordbox
|
||||
# cannot open, and pyrekordbox rejects the wrong one outright.
|
||||
@@ -383,9 +383,12 @@ class RekordboxExporter:
|
||||
# ---- playlists ---------------------------------------------------------------
|
||||
|
||||
def _write_playlists(self, db, payload: ExportPayload, rows: dict) -> None:
|
||||
"""The tree, under one folder named after the export."""
|
||||
root = db.create_playlist_folder(payload.name)
|
||||
db.flush()
|
||||
"""The tree — at the top level, or with `payload.root_folder` under one
|
||||
folder named after the export (None = the top level)."""
|
||||
root = None
|
||||
if payload.root_folder:
|
||||
root = db.create_playlist_folder(payload.name)
|
||||
db.flush()
|
||||
folders: dict[tuple[str, ...], object] = {(): root}
|
||||
|
||||
for playlist in payload.playlists:
|
||||
|
||||
@@ -608,6 +608,79 @@ class RekordboxStore(ReplaceGridCommands):
|
||||
self._db.delete_playlist(row)
|
||||
self._journal.record("playlist", "delete", name)
|
||||
|
||||
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
|
||||
"""Move a node to `index` among `parent_id`'s visible children.
|
||||
|
||||
Not pyrekordbox's `move_playlist`: its `parent=None` means "keep the
|
||||
parent", so nothing can be moved to the top level with it. The same
|
||||
writes are made here — `ParentID`, the moved row's `updated_at`, and
|
||||
`Seq` renumbered from 1 in both parents (only rows whose `Seq` changes
|
||||
are touched) — plus `masterPlaylists6.xml`'s `ParentId`, which
|
||||
pyrekordbox's version leaves stale. Rekordbox's hidden working lists
|
||||
share the table and the numbering, so `index` is placed relative to
|
||||
the VISIBLE siblings and the hidden ones keep their order around it."""
|
||||
import datetime
|
||||
|
||||
from pyrekordbox.masterdb.database import SPECIAL_PLAYLIST_IDS
|
||||
|
||||
t = self._tables
|
||||
row = self._playlist(node_id)
|
||||
dest = self._playlist(parent_id) if parent_id else None
|
||||
if dest is not None and int(dest.Attribute or 0) != int(t.PlaylistType.FOLDER):
|
||||
raise InvalidCommand("A playlist can only be moved into a folder")
|
||||
ancestor = dest
|
||||
while ancestor is not None:
|
||||
if str(ancestor.ID) == str(row.ID):
|
||||
raise InvalidCommand("A folder cannot be moved into itself")
|
||||
up = str(ancestor.ParentID or "root")
|
||||
ancestor = None if up in ("root", "0", "") else self._playlist(up)
|
||||
|
||||
def children(key: str) -> list:
|
||||
return (
|
||||
self._db.session.query(t.DjmdPlaylist)
|
||||
.filter(t.DjmdPlaylist.ParentID == key)
|
||||
.filter(t.DjmdPlaylist.rb_local_deleted == 0)
|
||||
.order_by(t.DjmdPlaylist.Seq)
|
||||
.all()
|
||||
)
|
||||
|
||||
old_key = str(row.ParentID or "root")
|
||||
new_key = str(dest.ID) if dest is not None else "root"
|
||||
siblings = [c for c in children(new_key) if str(c.ID) != str(row.ID)]
|
||||
visible = [c for c in siblings if str(c.ID) not in SPECIAL_PLAYLIST_IDS]
|
||||
index = max(0, min(int(index), len(visible)))
|
||||
if index < len(visible):
|
||||
at = siblings.index(visible[index])
|
||||
else:
|
||||
at = siblings.index(visible[-1]) + 1 if visible else len(siblings)
|
||||
order = siblings[:at] + [row] + siblings[at:]
|
||||
if old_key == new_key and [str(c.ID) for c in order] == [
|
||||
str(c.ID) for c in children(new_key)
|
||||
]:
|
||||
return str(row.ID)
|
||||
|
||||
row.ParentID = new_key
|
||||
with self._db.registry.disabled():
|
||||
row.updated_at = datetime.datetime.now()
|
||||
for n, c in enumerate(order, start=1):
|
||||
if c.Seq != n:
|
||||
c.Seq = n
|
||||
if old_key != new_key:
|
||||
for n, c in enumerate(
|
||||
(c for c in children(old_key) if str(c.ID) != str(row.ID)), start=1
|
||||
):
|
||||
if c.Seq != n:
|
||||
c.Seq = n
|
||||
xml = getattr(self._db, "playlist_xml", None)
|
||||
if xml is not None:
|
||||
try:
|
||||
xml.update(row.ID, parent_id=new_key)
|
||||
except ValueError:
|
||||
pass # a playlist the XML never listed: nothing to keep in step
|
||||
self._db.flush()
|
||||
self._journal.record("playlist", "move", row.Name)
|
||||
return str(row.ID)
|
||||
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
|
||||
"""Replace a playlist's contents, in the given order.
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ from ... import remote_protocol as rp
|
||||
from ...core.adapter import (
|
||||
AudioFacts,
|
||||
FileTagResult,
|
||||
NotFound,
|
||||
SaveOutcome,
|
||||
Unavailable,
|
||||
Unsupported,
|
||||
@@ -39,6 +40,7 @@ from ...core.query import TrackIndex
|
||||
from .cache import RemoteAudioCache, StaleFacts
|
||||
from .cache import shared as shared_cache
|
||||
from .client import RemoteClient, SessionLost
|
||||
from .folder import ServerFile, ServerFiles
|
||||
from .session import RemoteSession
|
||||
|
||||
_NOT_HERE = "A remote library's paths are the server's configuration"
|
||||
@@ -60,6 +62,13 @@ class RemoteAdapter:
|
||||
self._facts: dict[str, AudioFacts] = {}
|
||||
#: Server path of an upload → (the local file it came from, its analysis lead).
|
||||
self._uploads: dict[str, tuple[Path, float | None]] = {}
|
||||
#: Content-folder files a listing returned, by their server path.
|
||||
self._listed: dict[str, ServerFile] = {}
|
||||
#: `str(Path(p))` → `p` for every server path this side has turned into
|
||||
#: a `Path` (an upload's target, a listed file): on Windows that
|
||||
#: conversion rewrites the separators, and the server must get its own
|
||||
#: spelling back.
|
||||
self._server_paths: dict[str, str] = {}
|
||||
self._dirty = bool(hello.get("dirty"))
|
||||
self._load()
|
||||
|
||||
@@ -194,6 +203,9 @@ class RemoteAdapter:
|
||||
def delete_playlist(self, node_id):
|
||||
return self._call("delete_playlist", node_id=node_id)
|
||||
|
||||
def move_playlist(self, node_id, parent_id, index):
|
||||
return self._call("move_playlist", node_id=node_id, parent_id=parent_id, index=index)
|
||||
|
||||
def set_playlist_entries(self, node_id, track_ids):
|
||||
return self._call("set_playlist_entries", node_id=node_id, track_ids=list(track_ids))
|
||||
|
||||
@@ -257,6 +269,7 @@ class RemoteAdapter:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
self._uploads[landed["path"]] = (Path(source), landed.get("analysis_lead"))
|
||||
self._server_paths[str(Path(landed["path"]))] = landed["path"]
|
||||
return Path(landed["path"])
|
||||
|
||||
def free_space(self, path: str) -> int:
|
||||
@@ -265,8 +278,13 @@ class RemoteAdapter:
|
||||
|
||||
def delete_upload(self, path) -> None:
|
||||
"""Undo `upload_audio` (a cancelled or failed import)."""
|
||||
self._uploads.pop(str(path), None)
|
||||
self.client.delete_upload(str(path))
|
||||
key = self._server_key(path)
|
||||
self._uploads.pop(key, None)
|
||||
self.client.delete_upload(key)
|
||||
|
||||
def _server_key(self, path) -> str:
|
||||
text = str(path)
|
||||
return self._server_paths.get(text, text)
|
||||
|
||||
def add_tracks(self, items, *, checkpoint=None):
|
||||
"""Add uploaded files. Where the platform analyses what it adds (the
|
||||
@@ -276,10 +294,20 @@ class RemoteAdapter:
|
||||
|
||||
wire = []
|
||||
total = len(items)
|
||||
for n, item in enumerate(items, start=1):
|
||||
key = str(item.audio_path)
|
||||
keys = [self._server_key(item.audio_path) for item in items]
|
||||
# Files already in the content folder (added in place): the server says
|
||||
# whether the platform analyses, and only then is the file fetched.
|
||||
in_place = [k for k, item in zip(keys, items)
|
||||
if item.analysis is None and k not in self._uploads and k in self._listed]
|
||||
leads = self.client.folder_leads(in_place) if in_place else {}
|
||||
for n, (item, key) in enumerate(zip(items, keys), start=1):
|
||||
source, lead = self._uploads.get(key, (None, None))
|
||||
analysis = item.analysis
|
||||
if analysis is None and source is None and leads.get(key) is not None:
|
||||
lead = leads[key]
|
||||
if checkpoint is not None:
|
||||
checkpoint(f"Downloading {item.track.title or Path(key).name} ({n}/{total})", step=n, of=total)
|
||||
source = self.folder_audio(key)
|
||||
if analysis is None and lead is not None and source is not None:
|
||||
if checkpoint is not None:
|
||||
checkpoint(f"Analysing {item.track.title or source.name} ({n}/{total})", step=n, of=total)
|
||||
@@ -299,8 +327,8 @@ class RemoteAdapter:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
self._apply(envelope)
|
||||
for item in items:
|
||||
self._uploads.pop(str(item.audio_path), None)
|
||||
for key in keys:
|
||||
self._uploads.pop(key, None)
|
||||
return envelope["result"]
|
||||
|
||||
def apply_stem_swaps(self, swaps, *, add_to_playlist=None):
|
||||
@@ -390,6 +418,46 @@ class RemoteAdapter:
|
||||
facts = self.audio_facts([track_id]).get(track_id)
|
||||
return self.cache.get(facts) if facts else None
|
||||
|
||||
# ---- the content folder, browsed --------------------------------------------------
|
||||
def folder_listing(self, path: str | None) -> ServerFiles:
|
||||
"""The audio directly inside a content folder (None: the folder itself),
|
||||
as the server lists it — and remembered, so a file can then be played
|
||||
or added by its path."""
|
||||
listing = ServerFiles.from_wire(self, self.client.folder_tracks(path))
|
||||
with self._lock:
|
||||
self._listed = {k: f for k, f in self._listed.items() if f.folder != listing.path}
|
||||
self._listed.update(listing.files)
|
||||
self._server_paths.update({str(Path(k)): k for k in listing.files})
|
||||
return listing
|
||||
|
||||
def listed_files(self, paths) -> ServerFiles | None:
|
||||
"""The listed files among `paths` as one source (they may come from
|
||||
several folders); None when none of them was listed."""
|
||||
with self._lock:
|
||||
found = [self._listed[p] for p in paths if p in self._listed]
|
||||
return ServerFiles(self, found[0].folder, found) if found else None
|
||||
|
||||
def folder_audio(self, path: str, *, progress=None) -> Path:
|
||||
"""A local copy of a listed file, downloaded into the shared cache —
|
||||
keyed by the same facts as a library track's, so a file that is both
|
||||
downloads once."""
|
||||
for attempt in range(2):
|
||||
with self._lock:
|
||||
found = self._listed.get(path)
|
||||
if found is None:
|
||||
raise NotFound("File not found — browse to its folder first")
|
||||
cached = self.cache.get(found.facts)
|
||||
if cached is not None:
|
||||
return cached
|
||||
try:
|
||||
return self.cache.fetch(
|
||||
found.facts, lambda partial: self.client.folder_download(path, partial, progress=progress))
|
||||
except StaleFacts:
|
||||
if attempt:
|
||||
raise
|
||||
self.folder_listing(found.folder) # changed on the server: re-read it
|
||||
raise NotFound(path)
|
||||
|
||||
# ---- paths: the server's business ------------------------------------------------
|
||||
def set_path_mapping(self, mapping):
|
||||
raise Unsupported(_NOT_HERE)
|
||||
|
||||
@@ -246,6 +246,29 @@ class RemoteClient:
|
||||
def fs_list(self, path: str | None) -> dict:
|
||||
return self.request("GET", "/v1/fs/list", params={"path": path} if path else None).json()
|
||||
|
||||
def folder_tracks(self, path: str | None) -> dict:
|
||||
return self.request("GET", "/v1/folder/tracks", params={"path": path} if path else None,
|
||||
timeout=None).json()
|
||||
|
||||
def folder_leads(self, paths: list[str]) -> dict[str, float | None]:
|
||||
return self.request("POST", "/v1/folder/leads", json={"paths": paths}).json()["leads"]
|
||||
|
||||
def folder_download(self, path: str, target: Path, *, progress=None) -> dict:
|
||||
"""Stream a listed content-folder file into `target` (as `download`)."""
|
||||
with self.stream("GET", "/v1/folder/audio", params={"path": path}, timeout=None) as response:
|
||||
if response.status_code >= 400:
|
||||
response.read()
|
||||
self.check(response)
|
||||
with open(target, "wb") as out:
|
||||
for chunk in response.iter_bytes(1 << 20):
|
||||
out.write(chunk)
|
||||
if progress is not None:
|
||||
progress(len(chunk))
|
||||
return {
|
||||
"size": int(response.headers.get("X-Konduktor-Size") or 0),
|
||||
"mtime_ns": int(response.headers.get("X-Konduktor-Mtime-Ns") or 0),
|
||||
}
|
||||
|
||||
def fs_space(self, path: str | None) -> int:
|
||||
return int(self.request("GET", "/v1/fs/space", params={"path": path} if path else None).json()["free"])
|
||||
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
"""The server's content folder, browsed from this computer like a drive.
|
||||
|
||||
The sidebar's Files trees read folders on THIS computer (`core/folder.py`). On a
|
||||
remote library the music lives in the server's content folder, which this
|
||||
computer cannot see — so the server lists it (`/v1/folder/tracks`: tags, file
|
||||
facts, and which files the library already holds) and this module holds the
|
||||
answer as a read-only SOURCE, the shape the table, the deck and the importer
|
||||
already read.
|
||||
|
||||
Adding one of these files never uploads anything: it is already where the
|
||||
library can reach it, so it is added IN PLACE (`on_library_host`), and the
|
||||
importer skips both the copy and the copy-or-reference question.
|
||||
|
||||
Ids are the file's path ON THE SERVER — a string, never a `Path` on this side
|
||||
until the importer needs one, because a server path is not a path here (on a
|
||||
Windows laptop `Path("/music/x.mp3")` is `\\music\\x.mp3`).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from ...core.adapter import AudioFacts
|
||||
from ...core.model import PlaylistNode, Track, TrackCues
|
||||
|
||||
|
||||
@dataclass
|
||||
class ServerFile:
|
||||
folder: str
|
||||
track: Track
|
||||
facts: AudioFacts
|
||||
#: The library's id for this file, when it already points at it.
|
||||
held: str | None = None
|
||||
|
||||
|
||||
class ServerFiles:
|
||||
"""Files in the content folder, as the read half of a source."""
|
||||
|
||||
#: The importer's cue that these are already on the machine holding the
|
||||
#: library: added where they are, neither copied nor uploaded.
|
||||
on_library_host = True
|
||||
|
||||
def __init__(self, adapter, path: str, files: list[ServerFile]):
|
||||
self.adapter = adapter
|
||||
self.path = path
|
||||
self._files = {f.track.id: f for f in files}
|
||||
|
||||
@classmethod
|
||||
def from_wire(cls, adapter, body: dict) -> "ServerFiles":
|
||||
folder = body["path"]
|
||||
facts = body.get("files") or {}
|
||||
held = body.get("held") or {}
|
||||
files = []
|
||||
for raw in body.get("tracks") or []:
|
||||
track = Track.model_validate(raw)
|
||||
fact = facts.get(track.id)
|
||||
if fact is None:
|
||||
continue
|
||||
files.append(ServerFile(
|
||||
folder=folder, track=track,
|
||||
facts=AudioFacts(key=track.id, size=int(fact["size"]), mtime_ns=int(fact["mtime_ns"])),
|
||||
held=held.get(track.id),
|
||||
))
|
||||
return cls(adapter, folder, files)
|
||||
|
||||
@property
|
||||
def files(self) -> dict[str, ServerFile]:
|
||||
return self._files
|
||||
|
||||
@property
|
||||
def tracks(self) -> list[Track]:
|
||||
return [f.track for f in self._files.values()]
|
||||
|
||||
def track(self, track_id: str) -> Track | None:
|
||||
found = self._files.get(track_id)
|
||||
return found.track if found else None
|
||||
|
||||
def held(self, track_id: str) -> str | None:
|
||||
found = self._files.get(track_id)
|
||||
return found.held if found else None
|
||||
|
||||
def size(self, track_id: str) -> int:
|
||||
found = self._files.get(track_id)
|
||||
return found.facts.size if found else 0
|
||||
|
||||
def track_cues(self, track_id: str) -> TrackCues | None:
|
||||
return TrackCues(cues=[], grid_markers=[]) if track_id in self._files else None
|
||||
|
||||
def audio_facts(self, track_ids) -> dict[str, AudioFacts]:
|
||||
return {t: self._files[t].facts for t in track_ids if t in self._files}
|
||||
|
||||
def audio_path(self, track_id: str, *, progress=None) -> Path | None:
|
||||
"""A local copy (downloaded into the shared cache, like a library track)."""
|
||||
if track_id not in self._files:
|
||||
return None
|
||||
return self.adapter.folder_audio(track_id, progress=progress)
|
||||
|
||||
def playlist_tree(self) -> list[PlaylistNode]:
|
||||
return []
|
||||
|
||||
def playlist_tracks(self, node_id: str) -> list[Track] | None:
|
||||
return None
|
||||
@@ -131,6 +131,10 @@ class TraktorAdapter:
|
||||
with _translate():
|
||||
self._store.delete_playlist(node_id)
|
||||
|
||||
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
|
||||
with _translate():
|
||||
return self._store.move_playlist(node_id, parent_id, index)
|
||||
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
|
||||
"""Replace a playlist's contents. The adapter resolves each id to its
|
||||
native entry kind, so callers never see Traktor's STEM/TRACK split."""
|
||||
|
||||
@@ -74,7 +74,12 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
|
||||
"need a manual Import Cover Art to show up."
|
||||
),
|
||||
),
|
||||
playlists=PlaylistCapabilities(folders=True, smart="read_only", reorder=True),
|
||||
playlists=PlaylistCapabilities(
|
||||
folders=True, smart="read_only", reorder=True,
|
||||
# A playlist's entries are a plain list of PRIMARYKEYs, and Traktor
|
||||
# itself adds a track twice when asked.
|
||||
duplicates=True,
|
||||
),
|
||||
save=SaveCapabilities(
|
||||
app_name="Traktor",
|
||||
library_label="collection.nml",
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -160,11 +160,13 @@ class TraktorStore:
|
||||
can_reorder=True,
|
||||
can_rename=True,
|
||||
can_delete=True,
|
||||
can_move=True,
|
||||
)
|
||||
if ntype == "SMARTLIST" or node.smartplaylist is not None:
|
||||
# Rule-based, so it has no static entry list to show or edit.
|
||||
return PlaylistNode(
|
||||
id="sl:" + "/".join(parent_path + [name]), name=name, kind="smart"
|
||||
id="sl:" + "/".join(parent_path + [name]), name=name, kind="smart",
|
||||
can_move=True,
|
||||
)
|
||||
path = parent_path + [name]
|
||||
return PlaylistNode(
|
||||
@@ -175,6 +177,7 @@ class TraktorStore:
|
||||
can_contain_children=True,
|
||||
can_rename=True,
|
||||
can_delete=True,
|
||||
can_move=True,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
@@ -348,6 +351,79 @@ class TraktorStore:
|
||||
self._note("playlist-delete", node.name)
|
||||
self.dirty = True
|
||||
|
||||
def _find_node(self, node_id: str) -> Nodetype:
|
||||
"""Any node by its id: a playlist's UUID, a folder's `fld:` path or a
|
||||
smart playlist's `sl:` path (its folder path plus its own name)."""
|
||||
if node_id.startswith("fld:"):
|
||||
return self._find_folder(node_id)
|
||||
if node_id.startswith("sl:"):
|
||||
*folders, name = node_id[len("sl:"):].split("/")
|
||||
parent = self._find_folder("fld:" + "/".join(folders) if folders else None)
|
||||
match = next(
|
||||
(c for c in self._children(parent)
|
||||
if (c.type == "SMARTLIST" or c.smartplaylist is not None) and c.name == name),
|
||||
None,
|
||||
)
|
||||
if match is None:
|
||||
raise PlaylistError(f"Smart playlist not found: {node_id}")
|
||||
return match
|
||||
node = self._find_playlist_node(node_id)
|
||||
if node is None:
|
||||
raise PlaylistError(f"Playlist not found: {node_id}")
|
||||
return node
|
||||
|
||||
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
|
||||
"""Move a node to `index` among `parent_id`'s children (counted without
|
||||
it) and return its id afterwards — a folder's and a smart playlist's id
|
||||
is their path of names, so moving one changes it (and its subtree's).
|
||||
|
||||
A folder or smart playlist landing beside a namesake of its own kind is
|
||||
refused, as rename refuses it: the two paths would be one, and one of
|
||||
them unaddressable. Playlists are UUIDs, so their names may repeat."""
|
||||
with self._lock:
|
||||
node = self._find_node(node_id)
|
||||
if node is self._root():
|
||||
raise PlaylistError("Cannot move the root folder")
|
||||
dest = self._find_folder(parent_id)
|
||||
if dest is node or any(n is dest for n in self._iter_nodes(node)):
|
||||
raise PlaylistError("A folder cannot be moved into itself")
|
||||
is_folder = node.playlist is None and node.smartplaylist is None and (
|
||||
node.type or "FOLDER") == "FOLDER"
|
||||
is_smart = node.type == "SMARTLIST" or node.smartplaylist is not None
|
||||
if is_folder or is_smart:
|
||||
kind = "folder" if is_folder else "smart playlist"
|
||||
for c in self._children(dest):
|
||||
same_kind = (
|
||||
(c.type or "FOLDER") == "FOLDER" and c.playlist is None
|
||||
and c.smartplaylist is None
|
||||
) if is_folder else (c.type == "SMARTLIST" or c.smartplaylist is not None)
|
||||
if c is not node and same_kind and c.name == node.name:
|
||||
raise PlaylistError(f'There is already a {kind} called "{node.name}" there')
|
||||
source = self._find_parent_of(node)
|
||||
if source is None:
|
||||
raise PlaylistError("Cannot move a top-level node")
|
||||
siblings = [c for c in self._children(dest) if c is not node]
|
||||
index = max(0, min(int(index), len(siblings)))
|
||||
if source is dest and self._children(dest).index(node) == index:
|
||||
return self._node_id(node, parent_id) # already there
|
||||
source.subnodes.node.remove(node)
|
||||
source.subnodes.count = len(source.subnodes.node)
|
||||
if dest.subnodes is None:
|
||||
dest.subnodes = Subnodestype(node=[], count=0)
|
||||
dest.subnodes.node.insert(index, node)
|
||||
dest.subnodes.count = len(dest.subnodes.node)
|
||||
self._note("playlist-move", node.name)
|
||||
self.dirty = True
|
||||
return self._node_id(node, parent_id)
|
||||
|
||||
def _node_id(self, node: Nodetype, parent_id: str | None) -> str:
|
||||
"""The id `_to_model` gives `node` inside the folder `parent_id`."""
|
||||
if node.playlist is not None:
|
||||
return node.playlist.uuid
|
||||
prefix = parent_id[len("fld:"):] if parent_id and parent_id.startswith("fld:") else ""
|
||||
tag = "sl:" if (node.type == "SMARTLIST" or node.smartplaylist is not None) else "fld:"
|
||||
return tag + "/".join(p for p in (prefix, node.name or "(unnamed)") if p)
|
||||
|
||||
def set_entries(self, playlist_uuid: str, entries: list[tuple[str, str]]) -> None:
|
||||
with self._lock:
|
||||
node = self._find_playlist_node(playlist_uuid)
|
||||
|
||||
@@ -247,6 +247,12 @@ class LibraryAdapter(Protocol):
|
||||
def create_folder(self, name: str, parent_id: str | None = None) -> str: ...
|
||||
def rename_playlist(self, node_id: str, name: str) -> None: ...
|
||||
def delete_playlist(self, node_id: str) -> None: ...
|
||||
# Move a node (playlist, folder or smart playlist) to `index` among
|
||||
# `parent_id`'s children (None = the top level), counted with the moved
|
||||
# node left out. Returns the node's id AFTER the move: an id is opaque, and
|
||||
# on a platform that addresses a folder by its path it changes. A folder
|
||||
# cannot go into itself or a descendant (InvalidCommand).
|
||||
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str: ...
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: ...
|
||||
|
||||
# ---- commands: adding tracks ----------------------------------------
|
||||
|
||||
@@ -106,6 +106,9 @@ class PlaylistCapabilities(BaseModel):
|
||||
folders: bool = False
|
||||
smart: Literal["none", "read_only"] = "none"
|
||||
reorder: bool = False
|
||||
# A playlist can hold the same track more than once. Where it cannot, a
|
||||
# drop of tracks already there skips them rather than asking.
|
||||
duplicates: bool = False
|
||||
|
||||
|
||||
class PathCapabilities(BaseModel):
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
@@ -130,6 +130,9 @@ class PlaylistNode(BaseModel):
|
||||
can_rename: bool = False
|
||||
can_delete: bool = False
|
||||
can_contain_children: bool = False # a valid parent for a new playlist
|
||||
# Can be dragged elsewhere in the tree (`move_playlist`): reordered among
|
||||
# its siblings or moved into another folder.
|
||||
can_move: bool = False
|
||||
|
||||
|
||||
PlaylistNode.model_rebuild()
|
||||
|
||||
@@ -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))
|
||||
@@ -105,6 +105,8 @@ class TrackIndex:
|
||||
if (t.artist and ql in t.artist.lower())
|
||||
or (t.title and ql in t.title.lower())
|
||||
or (t.album and ql in t.album.lower())
|
||||
or (t.comment and ql in t.comment.lower())
|
||||
or (t.comment2 and ql in t.comment2.lower())
|
||||
]
|
||||
if genre:
|
||||
items = [t for t in items if t.genre == genre]
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -92,6 +92,8 @@ from .schemas import (
|
||||
RemapResult,
|
||||
RenamePlaylist,
|
||||
SaveResult,
|
||||
AddEntries,
|
||||
MovePlaylist,
|
||||
SetEntries,
|
||||
SourceCandidate,
|
||||
SourceStatus,
|
||||
@@ -118,8 +120,12 @@ app.add_middleware(
|
||||
"http://localhost:5173",
|
||||
"http://127.0.0.1:5173",
|
||||
# Packaged desktop app: the webview's origin when Tauri loads the built
|
||||
# frontend (macOS uses tauri://, Windows/Linux use https://tauri.localhost).
|
||||
# frontend. macOS uses tauri://; Windows/Linux default to
|
||||
# https://tauri.localhost, but lib.rs forces the http scheme
|
||||
# (use_https_scheme(false)) so the sidecar is not mixed content —
|
||||
# without the http origin here, the Windows app reaches no API at all.
|
||||
"tauri://localhost",
|
||||
"http://tauri.localhost",
|
||||
"https://tauri.localhost",
|
||||
],
|
||||
allow_methods=["*"],
|
||||
@@ -763,7 +769,10 @@ def run_export(set_id: str) -> JobStatus:
|
||||
built = exporter.plan(adapter, found)
|
||||
if built.blocked:
|
||||
raise HTTPException(409, built.blocked)
|
||||
job = JOBS.submit("export", lambda handle: exporter.run(adapter, found, built, handle))
|
||||
# A Konduktor setting, read when the export starts.
|
||||
root_folder = bool(prefs.load_prefs().get("exportRootFolder", False))
|
||||
job = JOBS.submit("export", lambda handle: exporter.run(
|
||||
adapter, found, built, handle, root_folder=root_folder))
|
||||
return JobStatus(**job.as_dict())
|
||||
|
||||
|
||||
@@ -1227,6 +1236,7 @@ def create_playlist(body: CreatePlaylist) -> PlaylistNode:
|
||||
can_reorder=True,
|
||||
can_rename=True,
|
||||
can_delete=True,
|
||||
can_move=True,
|
||||
)
|
||||
|
||||
|
||||
@@ -1241,6 +1251,7 @@ def create_folder(body: CreatePlaylist) -> PlaylistNode:
|
||||
can_contain_children=True,
|
||||
can_rename=True,
|
||||
can_delete=True,
|
||||
can_move=True,
|
||||
)
|
||||
|
||||
|
||||
@@ -1265,17 +1276,35 @@ def set_entries(playlist_uuid: str, body: SetEntries) -> dict:
|
||||
return {"status": "updated", "id": playlist_uuid, "count": n}
|
||||
|
||||
|
||||
@app.post("/api/playlists/move")
|
||||
def move_playlist(body: MovePlaylist) -> dict:
|
||||
"""Move a playlist, folder or smart playlist in the tree. Answers the
|
||||
node's id AFTER the move, which on some platforms is not the one sent."""
|
||||
new_id = require_adapter().move_playlist(body.node_id, body.parent_id, body.index)
|
||||
return {"status": "moved", "id": new_id}
|
||||
|
||||
|
||||
@app.post("/api/playlists/{playlist_uuid}/add")
|
||||
def add_entries(playlist_uuid: str, body: SetEntries) -> dict:
|
||||
"""Append tracks to a playlist (skips ids already present)."""
|
||||
def add_entries(playlist_uuid: str, body: AddEntries) -> dict:
|
||||
"""Append tracks to a playlist. Tracks already there are skipped, added
|
||||
again, or — `duplicates="ask"` — counted with nothing changed (see
|
||||
`AddEntries`). `duplicates` in the answer is how many there were."""
|
||||
a = require_adapter()
|
||||
current = a.playlist_entries(playlist_uuid)
|
||||
if current is None:
|
||||
raise HTTPException(404, f"Playlist not found: {playlist_uuid}")
|
||||
have = set(current)
|
||||
added = [tid for tid in body.track_ids if tid not in have]
|
||||
n = a.set_playlist_entries(playlist_uuid, current + added)
|
||||
return {"status": "added", "id": playlist_uuid, "added": len(added), "count": n}
|
||||
dupes = [tid for tid in body.track_ids if tid in have]
|
||||
mode = body.duplicates
|
||||
if mode != "skip" and not a.capabilities().playlists.duplicates:
|
||||
mode = "skip"
|
||||
if mode == "ask" and dupes:
|
||||
return {"status": "duplicates", "id": playlist_uuid, "added": 0,
|
||||
"duplicates": len(dupes), "count": len(current)}
|
||||
added = list(body.track_ids) if mode == "add" else [t for t in body.track_ids if t not in have]
|
||||
n = a.set_playlist_entries(playlist_uuid, current + added) if added else len(current)
|
||||
return {"status": "added", "id": playlist_uuid, "added": len(added),
|
||||
"duplicates": len(dupes), "count": n}
|
||||
|
||||
|
||||
@app.patch("/api/tracks")
|
||||
@@ -1637,10 +1666,10 @@ def analyze_preview(body: AnalyzeRequest) -> AnalyzePreview:
|
||||
|
||||
def _decode_for_analysis(path: Path):
|
||||
"""Mono samples at the rate BOTH detectors work at (they share one decode)."""
|
||||
import librosa
|
||||
from .core import waveform
|
||||
|
||||
assert grid_detect._SR == key_detect.SR, "grid and key detection must share a sample rate"
|
||||
return librosa.load(str(path), sr=key_detect.SR, mono=True)
|
||||
return waveform.load(path, sr=key_detect.SR)
|
||||
|
||||
|
||||
def _analyse_one(a, track_id: str, body: AnalyzeRequest, result: dict) -> None:
|
||||
@@ -2161,6 +2190,50 @@ def source_track_stems(track_id: str) -> dict:
|
||||
|
||||
FOLDERS = FolderScanner()
|
||||
|
||||
# A remote library's content folder rides the same routes. Its paths carry this
|
||||
# prefix, so a path on the server can never be taken for the same path on this
|
||||
# computer — and the UI's folder view, deck and add dialog need no second set of
|
||||
# routes. The prefix alone is the content folder itself.
|
||||
SERVER_FOLDER = "server:"
|
||||
|
||||
|
||||
def _on_server(path: str) -> str | None:
|
||||
"""The server path behind a prefixed one ('' = the content folder), else None."""
|
||||
return path[len(SERVER_FOLDER):] if path.startswith(SERVER_FOLDER) else None
|
||||
|
||||
|
||||
def _server_track(track: Track) -> Track:
|
||||
return track.model_copy(update={"id": SERVER_FOLDER + track.id})
|
||||
|
||||
|
||||
def _folder_rows(dest, tracks: list[Track], held_of) -> tuple[list[Track], dict[str, str]]:
|
||||
"""A folder's files as table rows. Where the library holds a file, the row
|
||||
IS the library's track — its key, rating, comments, cues and plays, and
|
||||
its id, so it plays, edits and drags as the collection track it is
|
||||
(decided 2026-10-10) — else the file's own tags. Also returns library id →
|
||||
the file's folder id, for the rows that are library tracks: adding still
|
||||
speaks in folder ids."""
|
||||
rows: list[Track] = []
|
||||
files: dict[str, str] = {}
|
||||
for track in tracks:
|
||||
known = held_of(track)
|
||||
held = dest.track(known) if known else None
|
||||
if held is None or held.id in files:
|
||||
rows.append(track)
|
||||
continue
|
||||
rows.append(held)
|
||||
files[held.id] = track.id
|
||||
return rows, files
|
||||
|
||||
|
||||
def _server_file(track_id: str) -> tuple[object, str]:
|
||||
"""The remote adapter and the server path of a listed content-folder file."""
|
||||
adapter = _require_remote()
|
||||
raw = _on_server(track_id) or ""
|
||||
if adapter.listed_files([raw]) is None:
|
||||
raise HTTPException(404, "Track not found — browse to its folder first")
|
||||
return adapter, raw
|
||||
|
||||
|
||||
def _drive_of(path: Path, drives: list[dict]) -> dict | None:
|
||||
"""The drive `path` lives on: the longest drive root that contains it."""
|
||||
@@ -2187,6 +2260,10 @@ def fs_drives() -> list[Drive]:
|
||||
found = places.drives()
|
||||
libraries = sources()
|
||||
out = [Drive(**d) for d in found]
|
||||
if STATE.remote is not None and STATE.remote_config is not None:
|
||||
# The server holding the library, first: its content folder is where
|
||||
# this library's music is, and this computer cannot see it otherwise.
|
||||
out.insert(0, Drive(name=STATE.remote_config.name, path=SERVER_FOLDER, kind="server"))
|
||||
externals = [d for d in found if d["path"] != "/"]
|
||||
for lib in libraries:
|
||||
home = _drive_of(Path(lib.path), externals)
|
||||
@@ -2201,6 +2278,11 @@ def fs_drives() -> list[Drive]:
|
||||
@app.get("/api/fs/folders", response_model=list[FsEntry])
|
||||
def fs_folders(path: str) -> list[FsEntry]:
|
||||
"""The visible folders directly inside `path` — one level of a Files tree."""
|
||||
raw = _on_server(path)
|
||||
if raw is not None:
|
||||
listing = _require_remote().client.fs_list(raw or None)
|
||||
return [FsEntry(name=e["name"], path=SERVER_FOLDER + e["path"])
|
||||
for e in listing["entries"] if e["is_dir"]]
|
||||
base = Path(path).expanduser()
|
||||
if not base.is_dir():
|
||||
raise HTTPException(404, f"Not a folder: {base}")
|
||||
@@ -2214,16 +2296,27 @@ def _formats() -> list[str]:
|
||||
@app.get("/api/folder/tracks", response_model=FolderTracks)
|
||||
def folder_tracks(path: str) -> FolderTracks:
|
||||
"""The audio files directly inside a folder, and which are already held."""
|
||||
raw = _on_server(path)
|
||||
if raw is not None:
|
||||
adapter = _require_remote()
|
||||
listing = adapter.folder_listing(raw or None)
|
||||
rows, files = _folder_rows(adapter, [_server_track(t) for t in listing.tracks],
|
||||
lambda t: listing.held(t.id[len(SERVER_FOLDER):]))
|
||||
return FolderTracks(path=SERVER_FOLDER + listing.path, tracks=rows,
|
||||
in_collection=list(files), files=files, removable=False)
|
||||
base = Path(path).expanduser()
|
||||
if not base.is_dir():
|
||||
raise HTTPException(404, f"Not a folder: {base}")
|
||||
source = FOLDERS.scan(base, _formats())
|
||||
held = importer._existing_files(require_adapter())
|
||||
dest = require_adapter()
|
||||
held = importer._existing_files(dest)
|
||||
rows, files = _folder_rows(dest, source.tracks, lambda t: held.get(importer._key(Path(t.id))))
|
||||
drive = _drive_of(base, places.drives())
|
||||
return FolderTracks(
|
||||
path=str(base),
|
||||
tracks=source.tracks,
|
||||
in_collection=[t.id for t in source.tracks if importer._key(Path(t.id)) in held],
|
||||
tracks=rows,
|
||||
in_collection=list(files),
|
||||
files=files,
|
||||
removable=drive is None or drive["kind"] == "external",
|
||||
)
|
||||
|
||||
@@ -2241,11 +2334,17 @@ def _folder_track(track_id: str) -> FolderSource:
|
||||
def folder_capabilities(path: str) -> Capabilities:
|
||||
from .core.folder import capabilities_for
|
||||
|
||||
raw = _on_server(path)
|
||||
if raw is not None:
|
||||
return capabilities_for(Path(raw) if raw else Path(STATE.remote_config.name if STATE.remote_config else "Server"))
|
||||
return capabilities_for(Path(path))
|
||||
|
||||
|
||||
@app.get("/api/folder/tracks/cues", response_model=TrackCues)
|
||||
def folder_track_cues(track_id: str) -> TrackCues:
|
||||
if _on_server(track_id) is not None:
|
||||
_server_file(track_id)
|
||||
return TrackCues(cues=[], grid_markers=[])
|
||||
cues = _folder_track(track_id).track_cues(track_id)
|
||||
assert cues is not None
|
||||
return cues
|
||||
@@ -2253,7 +2352,11 @@ def folder_track_cues(track_id: str) -> TrackCues:
|
||||
|
||||
@app.get("/api/folder/tracks/audio")
|
||||
def folder_track_audio(track_id: str, stem: int | None = None) -> FileResponse:
|
||||
path = _folder_track(track_id).audio_path(track_id)
|
||||
if _on_server(track_id) is not None:
|
||||
adapter, raw = _server_file(track_id)
|
||||
path = adapter.folder_audio(raw) # this computer's copy, as for a library track
|
||||
else:
|
||||
path = _folder_track(track_id).audio_path(track_id)
|
||||
if path is None or not path.is_file():
|
||||
raise HTTPException(404, "Audio file not found")
|
||||
if stem is not None:
|
||||
@@ -2264,6 +2367,9 @@ def folder_track_audio(track_id: str, stem: int | None = None) -> FileResponse:
|
||||
|
||||
@app.get("/api/folder/tracks/stems")
|
||||
def folder_track_stems(track_id: str) -> dict:
|
||||
if _on_server(track_id) is not None:
|
||||
adapter, raw = _server_file(track_id)
|
||||
return _stem_layout_of(adapter.folder_audio(raw))
|
||||
return _stem_layout_of(_folder_track(track_id).audio_path(track_id))
|
||||
|
||||
|
||||
@@ -2273,6 +2379,34 @@ def _require_addable(dest) -> None:
|
||||
raise HTTPException(422, "Tracks cannot be added to this library")
|
||||
|
||||
|
||||
def _check_add_targets(dest, body: FolderAddRequest) -> None:
|
||||
if body.playlist_id is not None and dest.playlist_entries(body.playlist_id) is None:
|
||||
raise HTTPException(404, f"Playlist not found: {body.playlist_id}")
|
||||
if body.export_id is not None:
|
||||
if STATE.library_id is None or exports.get(STATE.library_id, body.export_id) is None:
|
||||
raise HTTPException(404, f"Export not found: {body.export_id}")
|
||||
|
||||
|
||||
def _is_server_add(body: FolderAddRequest) -> bool:
|
||||
on_server = [_on_server(t) is not None for t in body.track_ids]
|
||||
if any(on_server) and not all(on_server):
|
||||
raise HTTPException(400, "Files on the server and on this computer are added separately")
|
||||
return bool(on_server) and all(on_server)
|
||||
|
||||
|
||||
def _server_add_plan(body: FolderAddRequest):
|
||||
"""Files in the remote library's content folder: already where the library
|
||||
can reach them, so they are added IN PLACE — nothing uploaded, nothing asked."""
|
||||
dest = _require_remote()
|
||||
_require_addable(dest)
|
||||
paths = [_on_server(t) for t in body.track_ids]
|
||||
source = dest.listed_files(paths)
|
||||
if source is None:
|
||||
raise HTTPException(400, "No tracks to add")
|
||||
_check_add_targets(dest, body)
|
||||
return source, dest, importer.plan_on_host(source, paths)
|
||||
|
||||
|
||||
def _folder_add_plan(body: FolderAddRequest):
|
||||
dest = require_adapter()
|
||||
_require_addable(dest)
|
||||
@@ -2293,11 +2427,7 @@ def _folder_add_plan(body: FolderAddRequest):
|
||||
if not body.destination:
|
||||
raise HTTPException(400, "Copying needs a destination folder")
|
||||
destination = Path(body.destination).expanduser()
|
||||
if body.playlist_id is not None and dest.playlist_entries(body.playlist_id) is None:
|
||||
raise HTTPException(404, f"Playlist not found: {body.playlist_id}")
|
||||
if body.export_id is not None:
|
||||
if STATE.library_id is None or exports.get(STATE.library_id, body.export_id) is None:
|
||||
raise HTTPException(404, f"Export not found: {body.export_id}")
|
||||
_check_add_targets(dest, body)
|
||||
return source, dest, destination, importer.plan(
|
||||
source, dest, destination, track_ids=[t.id for t in tracks]
|
||||
)
|
||||
@@ -2305,6 +2435,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):
|
||||
@@ -2321,10 +2456,16 @@ def folder_add_preview(body: FolderAddRequest) -> dict:
|
||||
def folder_add(body: FolderAddRequest) -> JobStatus:
|
||||
"""Add browsed files to the collection. A job, like import: copying can be long."""
|
||||
_require_no_pending_stems("Adding files")
|
||||
source, dest, destination, plan = _folder_add_plan(body)
|
||||
in_place = _is_server_add(body)
|
||||
if in_place:
|
||||
source, dest, plan = _server_add_plan(body)
|
||||
destination = None
|
||||
else:
|
||||
source, dest, destination, plan = _folder_add_plan(body)
|
||||
if not plan.importable and not plan.existing:
|
||||
raise HTTPException(400, "Nothing to add (none of those files exist)")
|
||||
if body.mode == "copy" or importer.places_audio(dest):
|
||||
# Nothing is copied in place, so there is no space to check.
|
||||
if not in_place and (body.mode == "copy" or importer.places_audio(dest)):
|
||||
free = importer.free_bytes(destination, dest)
|
||||
needed = importer.placed_bytes(dest, plan) if importer.places_audio(dest) else plan.total_bytes
|
||||
if free is not None and free < needed + importer.SPACE_HEADROOM:
|
||||
@@ -2340,7 +2481,7 @@ def folder_add(body: FolderAddRequest) -> JobStatus:
|
||||
def work(handle):
|
||||
result = importer.run(
|
||||
source, dest, plan, handle,
|
||||
reference=body.mode == "reference",
|
||||
reference=in_place or body.mode == "reference",
|
||||
into_playlist=body.playlist_id,
|
||||
)
|
||||
# Export sets are Konduktor's own data, not the library's, so they are
|
||||
@@ -2423,11 +2564,18 @@ def start_import(body: ImportRequest) -> JobStatus:
|
||||
folder_name = body.folder_name
|
||||
if folder_name is None and STATE.source is not None:
|
||||
folder_name = STATE.source.capabilities().save.library_label
|
||||
library = STATE.library_id
|
||||
|
||||
job = JOBS.submit(
|
||||
"import",
|
||||
lambda handle: importer.run(source, dest, plan, handle, folder_name=folder_name),
|
||||
)
|
||||
def work(handle):
|
||||
result = importer.run(
|
||||
source, dest, plan, handle, folder_name=folder_name, into_playlist=body.into_playlist,
|
||||
)
|
||||
# As folder add: an export set is Konduktor's data, updated afterwards.
|
||||
if body.export_id is not None and library is not None:
|
||||
exports.add(library, body.export_id, track_ids=result["track_ids"])
|
||||
return result
|
||||
|
||||
job = JOBS.submit("import", work)
|
||||
return JobStatus(**job.as_dict())
|
||||
|
||||
|
||||
|
||||
@@ -34,7 +34,9 @@ from .core.model import AutoHotcue, Track, TrackCues
|
||||
#: (major, minor). A client speaks to a server of the SAME major whose minor is
|
||||
#: at least its own: minors only add. Bump the minor for an added route or
|
||||
#: method, the major for anything an older client would misread.
|
||||
API_VERSION: tuple[int, int] = (1, 0)
|
||||
#: 1.1 — `move_playlist` (sidebar drag and drop).
|
||||
#: 1.2 — `/v1/folder/*`: the content folder browsed as a Files tree.
|
||||
API_VERSION: tuple[int, int] = (1, 2)
|
||||
|
||||
#: How long a session survives without a heartbeat, and how often the holder
|
||||
#: sends one. Long enough to ride out a Wi-Fi blip or a switch to the fallback
|
||||
@@ -73,7 +75,7 @@ _READ = (
|
||||
)
|
||||
_MUTATING = (
|
||||
"create_playlist", "create_folder", "rename_playlist", "delete_playlist",
|
||||
"set_playlist_entries", "remove_tracks", "set_track_metadata", "set_key", "set_cue",
|
||||
"move_playlist", "set_playlist_entries", "remove_tracks", "set_track_metadata", "set_key", "set_cue",
|
||||
"set_cue_type", "set_cue_color", "delete_cue", "place_cues", "add_grid_marker",
|
||||
"move_grid_marker", "set_grid_marker_bpm", "delete_grid_marker", "replace_grid",
|
||||
"set_analysed_grid", "delete_grid", "set_grid_lock", "add_tracks",
|
||||
|
||||
@@ -21,6 +21,20 @@ class SetEntries(BaseModel):
|
||||
track_ids: list[str] # ordered; full desired contents of the playlist
|
||||
|
||||
|
||||
class AddEntries(BaseModel):
|
||||
track_ids: list[str]
|
||||
# Tracks the playlist already holds: "skip" them, "add" them again (only
|
||||
# where `playlists.duplicates`, else skipped), or "ask" — change nothing and
|
||||
# report how many, so the UI can ask and send again with skip/add.
|
||||
duplicates: Literal["skip", "add", "ask"] = "skip"
|
||||
|
||||
|
||||
class MovePlaylist(BaseModel):
|
||||
node_id: str
|
||||
parent_id: str | None = None # None = the top level
|
||||
index: int # among the new parent's children, not counting the node
|
||||
|
||||
|
||||
class EditTrack(BaseModel):
|
||||
track_id: str
|
||||
fields: dict[str, str | int | None]
|
||||
@@ -493,6 +507,11 @@ class ImportRequest(BaseModel):
|
||||
# Playlists land in a folder named after the drive. Null keeps them at the
|
||||
# root; the default is filled in from the source's label.
|
||||
folder_name: str | None = None
|
||||
# Device tracks dropped on a collection playlist / an export (drag and
|
||||
# drop): every imported track — and every one the collection already
|
||||
# holds — goes into it, as folder add does.
|
||||
into_playlist: str | None = None
|
||||
export_id: str | None = None
|
||||
|
||||
|
||||
class Drive(BaseModel):
|
||||
@@ -502,11 +521,15 @@ class Drive(BaseModel):
|
||||
candidate `/api/sources` reports, attached to the drive it lives on so the
|
||||
sidebar can show one row per drive rather than a device list and a drive
|
||||
list that disagree about what is plugged in.
|
||||
|
||||
`server` is a remote library's content folder (path `server:`), listed
|
||||
first while a remote library is open — the one place its music can be
|
||||
browsed by folder from this computer.
|
||||
"""
|
||||
|
||||
name: str
|
||||
path: str
|
||||
kind: Literal["local", "external"]
|
||||
kind: Literal["local", "external", "server"]
|
||||
library: SourceCandidate | None = None
|
||||
|
||||
|
||||
@@ -514,9 +537,13 @@ class FolderTracks(BaseModel):
|
||||
"""The audio files directly inside one folder, projected as tracks."""
|
||||
|
||||
path: str
|
||||
# A file the collection holds is listed AS the collection's track (its id,
|
||||
# key, rating, cues…); any other file as its own tags, id = its path.
|
||||
tracks: list[Track]
|
||||
# Ids (= absolute paths) of the files the collection already points at.
|
||||
# Collection ids of the rows that are collection tracks.
|
||||
in_collection: list[str]
|
||||
# Those rows' collection id → the file's folder id, which adding takes.
|
||||
files: dict[str, str] = {}
|
||||
# On an external drive: a track referenced in place goes missing when the
|
||||
# drive is unplugged, which the add dialog has to say.
|
||||
removable: bool
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -447,6 +447,43 @@ check("re-importing flags the tracks as already present",
|
||||
check("but does not refuse them — the user chose to add everything",
|
||||
len(plan8.importable) == 2)
|
||||
|
||||
print("== import route: chosen tracks into a playlist and an export (drag and drop) ==")
|
||||
# Device tracks dropped on a collection playlist open Import with that playlist
|
||||
# as the target: only the chosen tracks, no drive folder, all into the playlist.
|
||||
nml9, music9, _ = fresh_collection()
|
||||
drive9 = Path(tempfile.mkdtemp(prefix="konduktor-import-drive-")) / "Dingus"
|
||||
shutil.copytree(FIXTURE, drive9, ignore=shutil.ignore_patterns("rekordbox-edited"))
|
||||
from fastapi.testclient import TestClient # noqa: E402
|
||||
|
||||
import konduktor.main as main # noqa: E402
|
||||
|
||||
with TestClient(main.app) as c:
|
||||
check("the collection opens", c.post("/api/library/open", json={"path": str(nml9)}).status_code == 200)
|
||||
check("the drive opens as a source", c.post("/api/source/open", json={"path": str(drive9)}).status_code == 200)
|
||||
picked = c.get("/api/source/tracks", params={"limit": 10}).json()
|
||||
picked = picked["items"][:1]
|
||||
target = c.post("/api/playlists", json={"name": "Dropped"}).json()["id"]
|
||||
eset = c.post("/api/exports", json={"name": "Gig", "targets": ["traktor"],
|
||||
"destination": str(music9.parent / "gig")}).json()["id"]
|
||||
r = c.post("/api/import", json={"destination": str(music9), "track_ids": [picked[0]["id"]],
|
||||
"into_playlist": target, "export_id": eset})
|
||||
check("the import starts", r.status_code == 200, r.text[:200])
|
||||
job = r.json()
|
||||
for _ in range(200):
|
||||
job = c.get(f"/api/jobs/{job['id']}").json()
|
||||
if job["state"] != "running":
|
||||
break
|
||||
time.sleep(0.05)
|
||||
check("…and finishes", job["state"] == "done", str(job)[:300])
|
||||
entries = c.get(f"/api/playlists/{target}/tracks").json()
|
||||
check("the one chosen track lands in the target playlist",
|
||||
len(entries) == 1 and entries[0]["title"] == picked[0]["title"], str([e["title"] for e in entries]))
|
||||
names = [n["name"] for n in c.get("/api/playlists").json()]
|
||||
check("no drive folder is made when no playlist was chosen", "Dingus" not in names, str(names))
|
||||
ex = next(e for e in c.get("/api/exports").json() if e["id"] == eset)
|
||||
check("…and it is added to the export too", ex["track_ids"] == [entries[0]["id"]], str(ex["track_ids"]))
|
||||
c.delete("/api/source")
|
||||
|
||||
print()
|
||||
print("RESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -60,7 +60,7 @@ def dump(db: Path) -> dict:
|
||||
"""Every row of every table; keyed by primary key, or by the whole row for
|
||||
the link tables, which have none."""
|
||||
import sqlcipher3.dbapi2 as sqlcipher
|
||||
from pyrekordbox.devicelib_plus.database import BLOB
|
||||
from pyrekordbox.onelibrary.database import BLOB
|
||||
from pyrekordbox.utils import deobfuscate
|
||||
|
||||
con = sqlcipher.connect(str(db))
|
||||
@@ -264,6 +264,44 @@ seqs = sorted(r["sequenceNo"] for r in after["playlist"].values() if r["playlist
|
||||
check("and closes the gap among its siblings", seqs == list(range(len(seqs))), str(seqs))
|
||||
a.close()
|
||||
|
||||
print("== moving playlists (sidebar drag and drop) ==")
|
||||
drive = fresh_drive()
|
||||
a = OneLibraryAdapter(drive)
|
||||
folder = a.create_folder("Gigs")
|
||||
probe = a.create_playlist("Probe")
|
||||
a.save()
|
||||
before = dump(db_of(drive))
|
||||
check("every node offers can_move", all(n.can_move for n in a.playlist_tree()))
|
||||
demos = next(n for n in a.playlist_tree() if n.name == "demos")
|
||||
a.move_playlist(demos.id, folder, 0)
|
||||
a.move_playlist(probe, None, 1)
|
||||
tree = a.playlist_tree()
|
||||
check("a playlist moved into a folder is its child",
|
||||
[c.id for c in next(n for n in tree if n.id == folder).children] == [demos.id])
|
||||
check("a playlist moves to the index asked for", [n.id for n in tree] == [folder, probe],
|
||||
str([n.name for n in tree]))
|
||||
check("a folder cannot be moved into itself",
|
||||
_raises(lambda: a.move_playlist(folder, folder, 0), InvalidCommand))
|
||||
check("nor into a playlist", _raises(lambda: a.move_playlist(probe, demos.id, 0), InvalidCommand))
|
||||
a.save()
|
||||
after = dump(db_of(drive))
|
||||
changes = diff(before, after)
|
||||
check("only playlist rows change, by UPDATE",
|
||||
{(t, kind) for t, _, kind, _ in changes} == {("playlist", "UPDATE")}, describe(changes))
|
||||
check("only parent and sequenceNo columns change",
|
||||
{c for *_, f in changes for c in f} <= {"playlist_id_parent", "sequenceNo"},
|
||||
str([f for *_, f in changes]))
|
||||
for parent in (0, int(folder)):
|
||||
seqs = sorted(r["sequenceNo"] for r in after["playlist"].values() if r["playlist_id_parent"] == parent)
|
||||
check(f"sequenceNo stays 0..n-1 under {parent}", seqs == list(range(len(seqs))), str(seqs))
|
||||
a.close()
|
||||
reopened = OneLibraryAdapter(drive)
|
||||
check("the move round-trips through a reopen",
|
||||
[c.id for c in next(n for n in reopened.playlist_tree() if n.id == folder).children] == [demos.id])
|
||||
reopened.move_playlist(probe, None, 1)
|
||||
check("moving a node onto its own place is not an edit", reopened.dirty is False)
|
||||
reopened.close()
|
||||
|
||||
# ---- E: a stick's hazards ------------------------------------------------------------
|
||||
print("== another app wrote the drive since it was opened ==")
|
||||
drive = fresh_drive()
|
||||
|
||||
@@ -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"))
|
||||
|
||||
@@ -172,6 +172,43 @@ check("COLLECTION still byte-identical after folder delete",
|
||||
check("unknown folder is 404",
|
||||
client.delete("/api/playlists/fld:No Such Folder").status_code == 404)
|
||||
|
||||
print("== drag and drop: add with duplicates, move ==")
|
||||
target = client.post("/api/playlists", json={"name": "Konduktor Drop"}).json()["id"]
|
||||
first, rest = track_ids[:2], track_ids[2:4]
|
||||
r = client.post(f"/api/playlists/{target}/add", json={"track_ids": first}).json()
|
||||
check("a plain add appends", r["added"] == 2 and r["duplicates"] == 0)
|
||||
r = client.post(f"/api/playlists/{target}/add",
|
||||
json={"track_ids": first[:1] + rest, "duplicates": "ask"}).json()
|
||||
check("'ask' with a duplicate changes nothing and counts it",
|
||||
r["status"] == "duplicates" and r["duplicates"] == 1
|
||||
and client.get(f"/api/playlists/{target}/tracks").json().__len__() == 2)
|
||||
r = client.post(f"/api/playlists/{target}/add",
|
||||
json={"track_ids": first[:1] + rest, "duplicates": "skip"}).json()
|
||||
check("'skip' adds only the new ones", r["added"] == 2 and r["duplicates"] == 1 and r["count"] == 4)
|
||||
r = client.post(f"/api/playlists/{target}/add",
|
||||
json={"track_ids": first[:1], "duplicates": "add"}).json()
|
||||
check("'add' adds it again (Traktor can hold a track twice)", r["added"] == 1 and r["count"] == 5)
|
||||
r = client.post(f"/api/playlists/{target}/add",
|
||||
json={"track_ids": track_ids[4:5], "duplicates": "ask"}).json()
|
||||
check("'ask' with nothing duplicated simply adds", r["status"] == "added" and r["added"] == 1)
|
||||
check("capabilities say Traktor holds duplicates",
|
||||
client.get("/api/capabilities").json()["playlists"]["duplicates"] is True)
|
||||
|
||||
box = client.post("/api/playlists/folders", json={"name": "Konduktor Drop Box"}).json()["id"]
|
||||
r = client.post("/api/playlists/move", json={"node_id": target, "parent_id": box, "index": 0})
|
||||
check("move answers the playlist's id", r.status_code == 200 and r.json()["id"] == target)
|
||||
r = client.post("/api/playlists/move", json={"node_id": box, "parent_id": None, "index": 0})
|
||||
check("moving a folder answers its (path) id", r.json()["id"] == box)
|
||||
check("…and it is first at the top level", client.get("/api/playlists").json()[0]["id"] == box)
|
||||
r = client.post("/api/playlists/move", json={"node_id": box, "parent_id": box, "index": 0})
|
||||
check("a folder into itself is a 400", r.status_code == 400)
|
||||
r = client.post("/api/playlists/move", json={"node_id": "nope", "parent_id": None, "index": 0})
|
||||
check("an unknown node is a 404", r.status_code == 404)
|
||||
client.delete(f"/api/playlists/{box}")
|
||||
client.post("/api/save")
|
||||
check("COLLECTION still byte-identical after drops and moves",
|
||||
collection_span(WORK.read_bytes()) == collection_before)
|
||||
|
||||
print("== original untouched ==")
|
||||
check(
|
||||
"original collection.nml never modified",
|
||||
|
||||
@@ -31,6 +31,7 @@ os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-rbfid-appd
|
||||
|
||||
from konduktor.adapters.rekordbox import discovery # noqa: E402
|
||||
from konduktor.adapters.rekordbox.adapter import RekordboxAdapter # noqa: E402
|
||||
from konduktor.core.adapter import InvalidCommand # noqa: E402
|
||||
|
||||
failed = False
|
||||
|
||||
@@ -302,6 +303,51 @@ with tempfile.TemporaryDirectory() as d:
|
||||
folder_reopened.close()
|
||||
after_folder.close()
|
||||
|
||||
# ---- E2: moving nodes in the tree (sidebar drag and drop) -----------
|
||||
print("== E2: move_playlist reorders and reparents, touching only playlist rows ==")
|
||||
clean_copy(REAL, work, closing=[adapter, again, final, reopened])
|
||||
adapter = RekordboxAdapter(work)
|
||||
folder_id = adapter.create_folder("Konduktor Move Folder")
|
||||
a_id = adapter.create_playlist("Konduktor Move A")
|
||||
b_id = adapter.create_playlist("Konduktor Move B")
|
||||
adapter.save()
|
||||
adapter.close()
|
||||
before = dump(work)
|
||||
adapter = RekordboxAdapter(work)
|
||||
check("every node offers can_move", all(n.can_move for n in adapter.playlist_tree()))
|
||||
adapter.move_playlist(b_id, folder_id, 0)
|
||||
adapter.move_playlist(a_id, None, 0)
|
||||
tree = adapter.playlist_tree()
|
||||
check("a playlist moved into a folder is its child",
|
||||
[c.id for c in next(n for n in tree if n.id == folder_id).children] == [b_id])
|
||||
check("a playlist moved to index 0 is first at the top level", tree[0].id == a_id,
|
||||
[n.name for n in tree[:3]])
|
||||
try:
|
||||
adapter.move_playlist(folder_id, folder_id, 0)
|
||||
check("a folder cannot be moved into itself", False)
|
||||
except InvalidCommand:
|
||||
check("a folder cannot be moved into itself", True)
|
||||
adapter.save()
|
||||
changes = diff(before, dump(work))
|
||||
check("only djmdPlaylist rows and the counter change",
|
||||
{t for t, _, _, _ in changes} <= {"djmdPlaylist", "agentRegistry"}, describe(changes))
|
||||
rows = dump(work)["djmdPlaylist"]
|
||||
for parent in ("root", folder_id):
|
||||
seqs = sorted(int(r["Seq"]) for r in rows.values()
|
||||
if str(r["ParentID"]) == parent and not r["rb_local_deleted"])
|
||||
check(f"Seq stays 1..n under {parent}", seqs == list(range(1, len(seqs) + 1)), seqs)
|
||||
adapter.close()
|
||||
reopened = RekordboxAdapter(work)
|
||||
tree = reopened.playlist_tree()
|
||||
check("the moves round-trip through a reopen",
|
||||
tree[0].id == a_id
|
||||
and [c.id for c in next(n for n in tree if n.id == folder_id).children] == [b_id])
|
||||
reopened.move_playlist(b_id, None, len(tree))
|
||||
check("a playlist moved out of a folder lands last at the top level",
|
||||
reopened.playlist_tree()[-1].id == b_id)
|
||||
reopened.close()
|
||||
again = final = RekordboxAdapter(work)
|
||||
|
||||
# ---- F: a cue write touches the cue row AND its mirror ---------------
|
||||
print("== F: a hot cue write is localized, and keeps the mirror in step ==")
|
||||
clean_copy(REAL, work, closing=[adapter, again, final, reopened])
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -1086,5 +1086,110 @@ with tempfile.TemporaryDirectory() as d:
|
||||
check("N: …and written in Camelot", target.info.key == "1A", target.info.key)
|
||||
|
||||
|
||||
# ---- O: moving playlists in the tree ----------------------------------
|
||||
# Drag and drop in the sidebar. Moving a node relocates its whole block, so
|
||||
# the guarantee is: the COLLECTION is untouched, the tree reads back as moved,
|
||||
# and moving it back reproduces the original bytes exactly.
|
||||
print("\n== O. move_playlist ==")
|
||||
|
||||
|
||||
def _collection_span(data: bytes) -> bytes:
|
||||
return data[data.find(b"<COLLECTION"):data.find(b"</COLLECTION>")]
|
||||
|
||||
|
||||
def _find(nodes, name):
|
||||
for n in nodes:
|
||||
if n.name == name:
|
||||
return n
|
||||
hit = _find(n.children, name)
|
||||
if hit is not None:
|
||||
return hit
|
||||
return None
|
||||
|
||||
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
work = Path(d) / "collection.nml"
|
||||
shutil.copy2(REAL, work)
|
||||
before = work.read_bytes()
|
||||
store = TraktorStore(work)
|
||||
roots = store.tree()
|
||||
folders = [n for n in roots if n.kind == "folder" and n.children]
|
||||
loose = [n for n in roots if n.kind == "playlist"]
|
||||
if len(folders) < 2 or len(loose) < 2:
|
||||
print(" [SKIP] the reference collection has too few top-level nodes")
|
||||
else:
|
||||
src, dst = folders[0], folders[1]
|
||||
pl = next((c for c in src.children if c.kind == "playlist"), None) or loose[0]
|
||||
home = _find(roots, pl.name)
|
||||
home_parent = next((f.id for f in roots if any(c.id == pl.id for c in f.children)), None)
|
||||
home_index = ([c.id for c in (src.children if home_parent else roots)].index(pl.id))
|
||||
check("O: every node offers can_move", all(n.can_move for n in roots))
|
||||
|
||||
# A playlist into another folder, at a position.
|
||||
new_id = store.move_playlist(pl.id, dst.id, 1)
|
||||
tree = store.tree()
|
||||
moved_into = next(n for n in tree if n.id == dst.id)
|
||||
check("O: a playlist keeps its id when moved", new_id == pl.id, new_id)
|
||||
check("O: …and lands at the index asked for",
|
||||
len(moved_into.children) > 1 and moved_into.children[1].id == pl.id,
|
||||
[c.name for c in moved_into.children[:3]])
|
||||
store.save()
|
||||
moved = work.read_bytes()
|
||||
check("O: the COLLECTION is untouched by a move",
|
||||
_collection_span(moved) == _collection_span(before))
|
||||
reread = TraktorStore(work).tree()
|
||||
check("O: the move round-trips through a save",
|
||||
any(c.id == pl.id for c in next(n for n in reread if n.id == dst.id).children))
|
||||
|
||||
# …and back again: byte-identical to the original.
|
||||
store.move_playlist(pl.id, home_parent, home_index)
|
||||
store.save()
|
||||
check("O: moving it back restores the original bytes", work.read_bytes() == before,
|
||||
f"{diff_count(before, work.read_bytes())} lines differ")
|
||||
|
||||
# A folder moves with its subtree, and its id (a path) changes with it.
|
||||
new_folder = store.move_playlist(src.id, dst.id, 0)
|
||||
check("O: a moved folder answers its new path id",
|
||||
new_folder == f"{dst.id}/{src.name}", new_folder)
|
||||
inner = next(n for n in store.tree() if n.id == dst.id).children[0]
|
||||
check("O: …and its subtree moved with it",
|
||||
inner.id == new_folder and len(inner.children) == len(src.children))
|
||||
child_ids = [c.id for c in inner.children]
|
||||
check("O: …children keep addressable ids",
|
||||
all(c.startswith((new_folder.replace("fld:", "sl:") + "/", new_folder + "/"))
|
||||
or not c.startswith(("fld:", "sl:")) for c in child_ids), child_ids[:3])
|
||||
|
||||
# Into itself: refused, nothing changed.
|
||||
snapshot = store._render()
|
||||
try:
|
||||
store.move_playlist(dst.id, new_folder, 0)
|
||||
check("O: a folder cannot be moved into its own descendant", False)
|
||||
except PlaylistError:
|
||||
check("O: a folder cannot be moved into its own descendant",
|
||||
store._render() == snapshot)
|
||||
|
||||
# A namesake folder in the target: refused (two paths would be one).
|
||||
store.create_folder(src.name, None)
|
||||
snapshot = store._render()
|
||||
try:
|
||||
store.move_playlist(new_folder, None, 0)
|
||||
check("O: a folder cannot land beside a namesake", False)
|
||||
except PlaylistError:
|
||||
check("O: a folder cannot land beside a namesake", store._render() == snapshot)
|
||||
|
||||
# A smart playlist moves too, by its path id.
|
||||
smart = next((c for c in inner.children if c.kind == "smart"), None)
|
||||
if smart is not None:
|
||||
sid = store.move_playlist(smart.id, None, 0)
|
||||
check("O: a smart playlist moves and answers its new id",
|
||||
sid == f"sl:{smart.name}" and store.tree()[0].id == sid, sid)
|
||||
|
||||
# A no-op move leaves the store clean.
|
||||
fresh = TraktorStore(work)
|
||||
first = fresh.tree()[0]
|
||||
fresh.move_playlist(first.id, None, 0)
|
||||
check("O: moving a node onto its own place is not an edit", not fresh.dirty)
|
||||
|
||||
|
||||
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -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)
|
||||
|
||||
@@ -106,6 +106,13 @@ with tempfile.TemporaryDirectory() as d:
|
||||
adapter.set_track_metadata(tid, {"genre": "Konduktor Test Genre"})
|
||||
check("metadata edit is visible in the projection",
|
||||
adapter.track(tid).genre == "Konduktor Test Genre")
|
||||
# search reaches both comments, case-insensitively
|
||||
adapter.set_track_metadata(tid, {"comment": "Konduktor Search One",
|
||||
"comment2": "Konduktor Search Two"})
|
||||
for q in ("search one", "SEARCH TWO"):
|
||||
hits = adapter.query_tracks(q=q, limit=20000).items
|
||||
check(f"search {q!r} finds the track by its comment",
|
||||
[x.id for x in hits] == [tid], f"{len(hits)} hits")
|
||||
|
||||
# key — the projection's wheel, mode AND display text all follow
|
||||
t = adapter.set_key(tid, 4, "minor") # 4A = F minor = Open Key 9m
|
||||
|
||||
@@ -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.1",
|
||||
"version": "0.2.6",
|
||||
"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/" }
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,11 @@ import type { ColumnSizingState, SortingState, VisibilityState } from '@tanstack
|
||||
import { CapabilitiesContext, slotLabeller } from './lib/capabilities'
|
||||
import { removalNote, writeHint } from './lib/platformCopy'
|
||||
import { invalidateTrackLists } from './lib/trackQueries'
|
||||
import { addTracksToPlaylist } from './lib/addTracks'
|
||||
import { useDropTarget } from './lib/drag'
|
||||
import { api, type AnalyzeOptions, type AnalyzeResult, type CueBatchResult, type AutoCueSlot, type PlaylistNode, type StemBatchResult, type Track, type TrackOrigin } from './api'
|
||||
import { confirmDiscardUnsaved } from './lib/unsaved'
|
||||
import { askConfirm } from './lib/confirm'
|
||||
import {
|
||||
COLUMN_MENU,
|
||||
DEFAULT_COLUMN_ORDER,
|
||||
@@ -30,6 +33,7 @@ import { ImportDialog } from './components/ImportDialog'
|
||||
import { AddFilesDialog, type AddTarget } from './components/AddFilesDialog'
|
||||
import { ConvertStemsDialog } from './components/ConvertStemsDialog'
|
||||
import { StemReportDialog } from './components/StemReportDialog'
|
||||
import { SetPositionDialog } from './components/SetPositionDialog'
|
||||
import { Icon } from './lib/icons'
|
||||
import { usePrefsWriter } from './lib/prefs'
|
||||
|
||||
@@ -39,7 +43,7 @@ function applyFilters(tracks: Track[], f: Filters): Track[] {
|
||||
const bpmMax = f.bpmMax ? parseFloat(f.bpmMax) : null
|
||||
return tracks.filter((t) => {
|
||||
if (q) {
|
||||
const hay = `${t.artist ?? ''} ${t.title ?? ''} ${t.album ?? ''}`.toLowerCase()
|
||||
const hay = [t.artist, t.title, t.album, t.comment, t.comment2].filter(Boolean).join(' ').toLowerCase()
|
||||
if (!hay.includes(q)) return false
|
||||
}
|
||||
if (f.genre && t.genre !== f.genre) return false
|
||||
@@ -77,10 +81,16 @@ export default function App() {
|
||||
const [prepOrigin, setPrepOrigin] = useState<TrackOrigin>('collection')
|
||||
// The view's origin, read by the load callbacks below (defined before it).
|
||||
const viewOriginRef = useRef<TrackOrigin>('collection')
|
||||
// The browsed folder's rows that ARE collection tracks: collection id → the
|
||||
// file's folder id. A ref, for the callbacks below that outlive a render.
|
||||
const folderFilesRef = useRef<Record<string, string>>({})
|
||||
// Browsed files being added to the collection (and maybe a playlist/export).
|
||||
const [adding, setAdding] = useState<{ ids: string[]; target: AddTarget | null } | null>(null)
|
||||
const [playRequest, setPlayRequest] = useState(0) // bump → deck loads & auto-plays
|
||||
const [importing, setImporting] = useState(false)
|
||||
// Device tracks dropped on a collection playlist / export: Import, with
|
||||
// just those tracks and that target.
|
||||
const [importDrop, setImportDrop] = useState<{ ids: string[]; target: AddTarget } | null>(null)
|
||||
// Batch analysis (grid, or Auto Hotcues): a confirm step, then the running
|
||||
// job, polled into the status bar. ONE at a time across both kinds — the
|
||||
// backend refuses a second, since a grid run would move the beats a hotcue
|
||||
@@ -91,6 +101,8 @@ export default function App() {
|
||||
// Convert to Stems: the dialog's selection, a finished run's Details, and a
|
||||
// running engine download (which outlives the dialog — decided).
|
||||
const [stemDialog, setStemDialog] = useState<string[] | null>(null)
|
||||
// Set Position…: the tracks being moved within the open playlist.
|
||||
const [positioning, setPositioning] = useState<string[] | null>(null)
|
||||
const [stemReport, setStemReport] = useState<StemBatchResult | null>(null)
|
||||
const [engineJob, setEngineJob] = useState<string | null>(null)
|
||||
const [batchCancelling, setBatchCancelling] = useState(false)
|
||||
@@ -98,9 +110,11 @@ export default function App() {
|
||||
// Every Remove ▸ action (and the playlist Delete key) confirms first.
|
||||
const [confirmReq, setConfirmReq] = useState<ConfirmRequest | null>(null)
|
||||
|
||||
const loadTrack = useCallback((t: Track) => {
|
||||
const loadTrack = useCallback((t: Track, origin: TrackOrigin = viewOriginRef.current) => {
|
||||
setPrepTrack(t)
|
||||
setPrepOrigin(viewOriginRef.current)
|
||||
// A folder row the collection holds IS the collection track, so the deck
|
||||
// loads it as one: its cues and grid, and editable (decided 2026-10-10).
|
||||
setPrepOrigin(origin === 'folder' && folderFilesRef.current[t.id] ? 'collection' : origin)
|
||||
}, [])
|
||||
const playTrack = useCallback(
|
||||
(t: Track) => {
|
||||
@@ -299,6 +313,11 @@ export default function App() {
|
||||
() => new Set(folderView.data?.in_collection ?? []),
|
||||
[folderView.data],
|
||||
)
|
||||
const folderFiles = useMemo(() => folderView.data?.files ?? {}, [folderView.data])
|
||||
folderFilesRef.current = viewingFolder ? folderFiles : {}
|
||||
// Adding speaks in FOLDER ids; a row the collection holds carries its
|
||||
// collection id, and maps back (the add dialog then reports it as held).
|
||||
const toFolderIds = (ids: string[]) => ids.map((id) => folderFiles[id] ?? id)
|
||||
viewOriginRef.current = viewingDevice ? 'device' : viewingFolder ? 'folder' : 'collection'
|
||||
// Tracks in view belong to ANOTHER library (a device) or to none (a folder),
|
||||
// so no collection command may be offered on them: their ids mean nothing to
|
||||
@@ -339,21 +358,43 @@ export default function App() {
|
||||
},
|
||||
[refreshExport, exportSets.data, notify, onError],
|
||||
)
|
||||
// The same path as a drop on a sidebar playlist (lib/addTracks.ts), so the
|
||||
// menu and the drag ask about duplicates alike.
|
||||
const duplicatesAllowed = !!capabilities.data?.playlists.duplicates
|
||||
const addToPlaylist = useCallback(
|
||||
async (uuid: string, ids: string[]) => {
|
||||
try {
|
||||
const res = await api.addEntries(uuid, ids)
|
||||
qc.invalidateQueries({ queryKey: ['state'] })
|
||||
qc.invalidateQueries({ queryKey: ['playlists'] })
|
||||
qc.invalidateQueries({ queryKey: ['playlist', uuid] })
|
||||
const name = addablePlaylists.find((p) => p.id === uuid)?.name ?? 'playlist'
|
||||
notify('success', `Added ${res.added} track${res.added === 1 ? '' : 's'} to ${name}`)
|
||||
const msg = await addTracksToPlaylist({ qc, playlist: { id: uuid, name }, ids, duplicatesAllowed })
|
||||
if (msg) notify('success', msg)
|
||||
} catch (e) {
|
||||
onError((e as Error).message)
|
||||
}
|
||||
},
|
||||
[qc, addablePlaylists, notify, onError],
|
||||
[qc, addablePlaylists, duplicatesAllowed, notify, onError],
|
||||
)
|
||||
// Tracks from a device or a Files folder dropped on a collection playlist or
|
||||
// export: they are not in the collection yet, so the drop opens the dialog
|
||||
// that adds them — with that target filled in, and copy-vs-reference still
|
||||
// asked (decided 2026-10-06).
|
||||
const addForeign = useCallback(
|
||||
(origin: TrackOrigin, ids: string[], target: AddTarget) => {
|
||||
if (origin === 'folder') {
|
||||
const files = folderFilesRef.current
|
||||
// Rows that are all collection tracks already: nothing to add first.
|
||||
if (ids.every((id) => files[id])) {
|
||||
if (target.kind === 'playlist') void addToPlaylist(target.id, ids)
|
||||
else void addToExport(target.id, ids)
|
||||
} else setAdding({ ids: ids.map((id) => files[id] ?? id), target })
|
||||
} else if (origin === 'device') setImportDrop({ ids, target })
|
||||
},
|
||||
[addToPlaylist, addToExport],
|
||||
)
|
||||
const [deckDropRef, deckOver] = useDropTarget<true>({
|
||||
hint: (p) => (p.kind === 'tracks' ? true : null),
|
||||
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),
|
||||
})
|
||||
const removeFromExport = useCallback(
|
||||
async (id: string, ids: string[]) => {
|
||||
try {
|
||||
@@ -383,7 +424,10 @@ export default function App() {
|
||||
: origin === 'folder'
|
||||
? (folderCaps.data ?? readOnlyCaps('not_in_library'))
|
||||
: capabilities.data!
|
||||
const viewCaps = capsFor(viewOriginRef.current)
|
||||
// A folder's table runs on the COLLECTION's: the rows it holds are collection
|
||||
// tracks and edit as such, and a loose row asks to be added first
|
||||
// (`folderMayEdit`) rather than rendering inert.
|
||||
const viewCaps = viewingFolder ? capabilities.data! : capsFor(viewOriginRef.current)
|
||||
// The deck follows its TRACK's library, not the view's.
|
||||
const deckCaps = capsFor(prepOrigin)
|
||||
|
||||
@@ -419,9 +463,12 @@ export default function App() {
|
||||
// PrepStrip keys its audio on the id, so a new object for the same id
|
||||
// reloads nothing.
|
||||
useEffect(() => {
|
||||
if (!prepTrack || viewOriginRef.current !== prepOrigin) return
|
||||
if (!prepTrack) return
|
||||
const fresh = tracks.find((t) => t.id === prepTrack.id)
|
||||
if (fresh && JSON.stringify(fresh) !== JSON.stringify(prepTrack)) setPrepTrack(fresh)
|
||||
if (!fresh) return
|
||||
const origin =
|
||||
viewOriginRef.current === 'folder' && folderFilesRef.current[fresh.id] ? 'collection' : viewOriginRef.current
|
||||
if (origin === prepOrigin && JSON.stringify(fresh) !== JSON.stringify(prepTrack)) setPrepTrack(fresh)
|
||||
// Only a refetch of the list matters; prepTrack is read, not tracked.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [tracks])
|
||||
@@ -612,7 +659,7 @@ export default function App() {
|
||||
}
|
||||
|
||||
// ---- Convert to Stems ------------------------------------------------------
|
||||
const canStems = canEdit && !viewForeign && !!capabilities.data?.tracks.stem_convertible
|
||||
const canStems = canEdit && !viewingDevice && !!capabilities.data?.tracks.stem_convertible
|
||||
const finishStemBatch = (state: string, r: StemBatchResult | null, error: string | null) => {
|
||||
qc.invalidateQueries({ queryKey: ['state'] })
|
||||
if (state === 'failed' || !r) {
|
||||
@@ -764,7 +811,7 @@ export default function App() {
|
||||
// the rest with a reason.
|
||||
const canAnalyzeGrid = !!capabilities.data?.grid.editable
|
||||
const canAnalyzeKey = !!capabilities.data?.tracks.key_writable
|
||||
const canAnalyze = canEdit && !viewForeign && (canAnalyzeGrid || canAnalyzeKey)
|
||||
const canAnalyze = canEdit && !viewingDevice && (canAnalyzeGrid || canAnalyzeKey)
|
||||
|
||||
const startCueBatch = (ids: string[]) => {
|
||||
const byId = new Map(tracks.map((t) => [t.id, t]))
|
||||
@@ -777,7 +824,7 @@ export default function App() {
|
||||
setBatchCancelling(false)
|
||||
setBatchJob({ id: job.id, kind: 'cues' })
|
||||
}
|
||||
const canAutoCue = canEdit && !viewForeign && (capabilities.data?.cues.hotcue_slots ?? 0) > 0
|
||||
const canAutoCue = canEdit && !viewingDevice && (capabilities.data?.cues.hotcue_slots ?? 0) > 0
|
||||
|
||||
|
||||
// ---- Remove ▸ -----------------------------------------------------------
|
||||
@@ -910,12 +957,48 @@ export default function App() {
|
||||
}),
|
||||
})
|
||||
|
||||
const canClearGrids = canEdit && !viewForeign && !!capabilities.data?.grid.editable
|
||||
const canClearGrids = canEdit && !viewingDevice && !!capabilities.data?.grid.editable
|
||||
const canClearCues = canAutoCue
|
||||
const canRemoveTracks = canEdit && !viewForeign && !!capabilities.data?.tracks.removable
|
||||
const canRemoveTracks = canEdit && !viewingDevice && !!capabilities.data?.tracks.removable
|
||||
// The COLLECTION's capabilities, deliberately: adding happens while a folder
|
||||
// or device is on screen, whose own capabilities are read-only.
|
||||
const canAddTracks = canEdit && !!capabilities.data?.tracks.addable
|
||||
|
||||
// In a folder, only the rows the collection holds can be edited. Anything
|
||||
// that would edit a loose file says so and offers to add it, rather than
|
||||
// being absent or silently inert (decided 2026-10-10).
|
||||
const askToAdd = async (ids: string[]) => {
|
||||
const loose = ids.filter((id) => !folderFiles[id])
|
||||
if (!loose.length) return
|
||||
const first = tracks.find((t) => t.id === loose[0])
|
||||
const what =
|
||||
loose.length === 1
|
||||
? `“${first?.title || 'This file'}” is not in your collection`
|
||||
: `${loose.length} of these files are not in your collection`
|
||||
if (!canAddTracks) {
|
||||
notify('error', `${what}, and tracks cannot be added to this library.`)
|
||||
return
|
||||
}
|
||||
const add = await askConfirm({
|
||||
title: 'Add to your collection first',
|
||||
body: `${what} yet. Add ${loose.length === 1 ? 'it' : 'them'} to edit tags, cues or the beatgrid.`,
|
||||
confirmLabel: 'Add to Collection…',
|
||||
tone: 'primary',
|
||||
})
|
||||
if (add) setAdding({ ids: loose, target: null })
|
||||
}
|
||||
const folderEditField = (track: Track, field: keyof Track, value: string | number) => {
|
||||
if (folderFiles[track.id]) editField(track, field, value)
|
||||
else void askToAdd([track.id])
|
||||
}
|
||||
const folderMayEdit = (track: Track) => {
|
||||
if (folderFiles[track.id]) return true
|
||||
void askToAdd([track.id])
|
||||
return false
|
||||
}
|
||||
// The open menu's loose files: every editing item then asks to add them.
|
||||
const menuLoose = menu && viewingFolder ? menu.ids.filter((id) => !folderFiles[id]) : []
|
||||
const gated = (fn: () => void) => (menuLoose.length ? () => void askToAdd(menuLoose) : fn)
|
||||
const exportRootId =
|
||||
source.kind === 'export' ? source.id : source.kind === 'export-other' ? source.exportId : null
|
||||
const removeItems = (ids: string[]): MenuItem[] => [
|
||||
@@ -999,8 +1082,8 @@ export default function App() {
|
||||
: []),
|
||||
// Offering "Edit Tags…" on a read-only library would open a dialog
|
||||
// whose every save is refused, so it is not offered at all.
|
||||
...(canEdit && !viewForeign && menu.ids.length === 1
|
||||
? [{ label: 'Edit Tags…', onClick: () => setEditing(menu.track) }]
|
||||
...(canEdit && !viewingDevice && menu.ids.length === 1
|
||||
? [{ label: 'Edit Tags…', onClick: gated(() => setEditing(menu.track)) }]
|
||||
: []),
|
||||
...(canAnalyze
|
||||
? [
|
||||
@@ -1008,7 +1091,7 @@ export default function App() {
|
||||
label: 'Analyze…',
|
||||
hint: batchJob ? 'busy' : menu.ids.length > 1 ? String(menu.ids.length) : undefined,
|
||||
disabled: !!batchJob,
|
||||
onClick: () => setAnalyzing(menu.ids),
|
||||
onClick: gated(() => setAnalyzing(menu.ids)),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
@@ -1020,20 +1103,20 @@ export default function App() {
|
||||
label: 'Auto Hotcues…',
|
||||
hint: batchJob ? 'busy' : menu.ids.length > 1 ? String(menu.ids.length) : undefined,
|
||||
disabled: !!batchJob,
|
||||
onClick: () => startCueBatch(menu.ids),
|
||||
onClick: gated(() => startCueBatch(menu.ids)),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
// Shown disabled WITH a reason where the platform cannot play stem
|
||||
// files as stems, rather than hidden: a missing item reads as a bug.
|
||||
...(canEdit && !viewForeign
|
||||
...(canEdit && !viewingDevice
|
||||
? [
|
||||
canStems
|
||||
? {
|
||||
label: 'Convert to Stems…',
|
||||
hint: batchJob ? 'busy' : menu.ids.length > 1 ? String(menu.ids.length) : undefined,
|
||||
disabled: !!batchJob,
|
||||
onClick: () => setStemDialog(menu.ids),
|
||||
onClick: gated(() => setStemDialog(menu.ids)),
|
||||
}
|
||||
: {
|
||||
label: 'Convert to Stems…',
|
||||
@@ -1046,12 +1129,14 @@ export default function App() {
|
||||
// A device's track ids belong to the stick, not the collection, so
|
||||
// there is nothing they could be added to. A folder's files CAN be
|
||||
// added — through the add dialog, which puts them in the
|
||||
// collection first.
|
||||
// collection first; rows it already holds are collection tracks.
|
||||
...(viewingFolder
|
||||
? canAddTracks
|
||||
? !menuLoose.length
|
||||
? [{ label: 'Add to', submenu: addToItems(menu.ids) }]
|
||||
: canAddTracks
|
||||
? [
|
||||
{ label: 'Add to Collection…', onClick: () => setAdding({ ids: menu.ids, target: null }) },
|
||||
{ label: 'Add to', submenu: folderAddToItems(menu.ids) },
|
||||
{ label: 'Add to Collection…', onClick: () => setAdding({ ids: menuLoose, target: null }) },
|
||||
{ label: 'Add to', submenu: folderAddToItems(toFolderIds(menu.ids)) },
|
||||
]
|
||||
: [{
|
||||
label: 'Add to Collection…',
|
||||
@@ -1062,8 +1147,13 @@ export default function App() {
|
||||
: viewingDevice
|
||||
? []
|
||||
: [{ label: 'Add to', submenu: addToItems(menu.ids) }]),
|
||||
// Unlike drag-reorder this stays on while sorted or filtered: it
|
||||
// moves within the playlist's FULL order, which the # column shows.
|
||||
...(playlistEditable
|
||||
? [{ label: 'Set Position…', onClick: () => setPositioning(menu.ids) }]
|
||||
: []),
|
||||
...(() => {
|
||||
const items = removeItems(menu.ids)
|
||||
const items = menuLoose.length ? [] : removeItems(menu.ids)
|
||||
return items.length ? [{ label: 'Remove', submenu: items }] : []
|
||||
})(),
|
||||
]}
|
||||
@@ -1103,6 +1193,14 @@ export default function App() {
|
||||
/>
|
||||
)}
|
||||
{stemReport && <StemReportDialog result={stemReport} onClose={() => setStemReport(null)} />}
|
||||
{positioning && (
|
||||
<SetPositionDialog
|
||||
order={tracks.map((t) => t.id)}
|
||||
ids={positioning}
|
||||
onMove={reorderPlaylist}
|
||||
onClose={() => setPositioning(null)}
|
||||
/>
|
||||
)}
|
||||
{editing && (
|
||||
<EditTagsDialog
|
||||
track={editing}
|
||||
@@ -1191,7 +1289,27 @@ export default function App() {
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Prep strip spans the top of the window; the library sits below it. */}
|
||||
{importDrop && (
|
||||
<ImportDialog
|
||||
playlistId={null}
|
||||
trackIds={importDrop.ids}
|
||||
target={importDrop.target}
|
||||
deviceLabel={deviceLabel}
|
||||
onClose={() => setImportDrop(null)}
|
||||
onDone={(msg) => {
|
||||
setImportDrop(null)
|
||||
notify('success', msg)
|
||||
}}
|
||||
onError={onError}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Prep strip spans the top of the window; the library sits below it.
|
||||
A track dropped on it loads (paused) — the row the drag started on. */}
|
||||
<div ref={deckDropRef} className="relative shrink-0">
|
||||
{deckOver && (
|
||||
<div aria-hidden className="pointer-events-none absolute inset-0 z-10 rounded-[22px] ring-2 ring-accent" />
|
||||
)}
|
||||
<CapabilitiesContext.Provider value={deckCaps}>
|
||||
<PrepStrip
|
||||
track={prepTrack}
|
||||
@@ -1203,6 +1321,7 @@ export default function App() {
|
||||
onPlayingChange={setDeckPlaying}
|
||||
/>
|
||||
</CapabilitiesContext.Provider>
|
||||
</div>
|
||||
|
||||
<div className="flex min-h-0 flex-1 gap-3">
|
||||
<Sidebar
|
||||
@@ -1214,6 +1333,7 @@ export default function App() {
|
||||
onSwitchLibrary={() => setForcePicker(true)}
|
||||
onOpenLibrary={(path) => void openForEditing(path)}
|
||||
onDone={(msg) => notify('success', msg)}
|
||||
onAddForeign={addForeign}
|
||||
onOpenPathMapping={() => setShowPaths(true)}
|
||||
onDiscarded={() => afterBulk(prepTrack ? [prepTrack.id] : [], true)}
|
||||
/>
|
||||
@@ -1256,9 +1376,11 @@ export default function App() {
|
||||
{' · this folder only'}
|
||||
</span>
|
||||
<span className="ml-auto flex items-center gap-2">
|
||||
<span className="rounded-full bg-gold/10 px-2 py-0.5 text-[10px] uppercase tracking-wide text-gold shadow-[inset_0_0_0_1px_rgb(255_200_97/0.3)]">
|
||||
Not in collection
|
||||
</span>
|
||||
{tracks.length > heldInFolder.size && (
|
||||
<span className="rounded-full bg-gold/10 px-2 py-0.5 text-[10px] uppercase tracking-wide text-gold shadow-[inset_0_0_0_1px_rgb(255_200_97/0.3)]">
|
||||
Not in collection
|
||||
</span>
|
||||
)}
|
||||
{tracks.length > 0 && canAddTracks && (
|
||||
<button
|
||||
onClick={() =>
|
||||
@@ -1266,7 +1388,7 @@ export default function App() {
|
||||
// The selection when there is one, else everything in
|
||||
// view that the collection does not already hold.
|
||||
ids: selected.size
|
||||
? filtered.filter((t) => selected.has(t.id)).map((t) => t.id)
|
||||
? toFolderIds(filtered.filter((t) => selected.has(t.id)).map((t) => t.id))
|
||||
: filtered.filter((t) => !heldInFolder.has(t.id)).map((t) => t.id),
|
||||
target: null,
|
||||
})
|
||||
@@ -1396,9 +1518,12 @@ export default function App() {
|
||||
onSortingChange={setSorting}
|
||||
selection={{ selected, onChange: setSelected }}
|
||||
marked={{ ids: heldInFolder, title: 'Already in your collection' }}
|
||||
dragFrom={{ origin: 'folder' }}
|
||||
onRowContextMenu={(track, x, y) => openMenu(track, x, y, true)}
|
||||
onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })}
|
||||
onPlay={playTrack}
|
||||
onEditField={canEdit ? folderEditField : undefined}
|
||||
mayEdit={folderMayEdit}
|
||||
activeTrackId={prepTrack?.id ?? null}
|
||||
activePlaying={deckPlaying}
|
||||
columnVisibility={columnVisibility}
|
||||
@@ -1431,6 +1556,7 @@ export default function App() {
|
||||
sorting={sorting}
|
||||
onSortingChange={setSorting}
|
||||
onRowContextMenu={(track, x, y) => openMenu(track, x, y, false)}
|
||||
dragFrom={{ origin: 'device' }}
|
||||
onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })}
|
||||
onPlay={playTrack}
|
||||
activeTrackId={prepTrack?.id ?? null}
|
||||
@@ -1492,6 +1618,10 @@ export default function App() {
|
||||
: undefined
|
||||
}
|
||||
onRemove={playlistEditable ? confirmRemoveFromPlaylist : undefined}
|
||||
dragFrom={{
|
||||
origin: 'collection',
|
||||
playlistId: playlistEditable && source.kind === 'playlist' ? source.id : undefined,
|
||||
}}
|
||||
onRowContextMenu={(track, x, y) => openMenu(track, x, y, true)}
|
||||
onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })}
|
||||
onPlay={playTrack}
|
||||
|
||||
@@ -83,6 +83,8 @@ export interface PlaylistNode {
|
||||
can_rename: boolean
|
||||
can_delete: boolean
|
||||
can_contain_children: boolean
|
||||
/** Can be dragged elsewhere in the tree (reordered, or into a folder). */
|
||||
can_move: boolean
|
||||
}
|
||||
|
||||
export type SortField =
|
||||
@@ -270,7 +272,13 @@ export interface Capabilities {
|
||||
/** Added files can be left where they are rather than copied. */
|
||||
reference: boolean
|
||||
}
|
||||
playlists: { folders: boolean; smart: 'none' | 'read_only'; reorder: boolean }
|
||||
playlists: {
|
||||
folders: boolean
|
||||
smart: 'none' | 'read_only'
|
||||
reorder: boolean
|
||||
/** A playlist can hold the same track twice (else duplicates are skipped). */
|
||||
duplicates: boolean
|
||||
}
|
||||
/** Path mapping / rewriting / the missing-files check apply to this library. */
|
||||
paths: { remappable: boolean }
|
||||
save: SaveCapabilities
|
||||
@@ -433,6 +441,10 @@ export interface ImportRequest {
|
||||
playlist_ids?: string[]
|
||||
/** Playlists land in a folder named this; null keeps them at the root. */
|
||||
folder_name?: string | null
|
||||
/** Every imported track (and any already held) also goes into this
|
||||
* collection playlist / export — a drop of device tracks on one. */
|
||||
into_playlist?: string | null
|
||||
export_id?: string | null
|
||||
}
|
||||
|
||||
export interface ImportPreview {
|
||||
@@ -466,17 +478,28 @@ export interface ImportPreview {
|
||||
export interface Drive {
|
||||
name: string
|
||||
path: string
|
||||
/** `local` = boot disk or a drive built in; anything uncertain is external. */
|
||||
kind: 'local' | 'external'
|
||||
/** `local` = boot disk or a drive built in; anything uncertain is external.
|
||||
* `server` = a remote library's content folder (path `server:`). */
|
||||
kind: 'local' | 'external' | 'server'
|
||||
/** The OneLibrary library on this drive, if it carries one. */
|
||||
library: SourceCandidate | null
|
||||
}
|
||||
|
||||
/** A path in a remote library's content folder, as the Files routes take it:
|
||||
* `server:` + the path ON THE SERVER, so it cannot be taken for the same
|
||||
* path on this computer. Such files are already where the library can reach
|
||||
* them, so adding one never copies or uploads it. */
|
||||
export const isServerPath = (path: string) => path.startsWith('server:')
|
||||
|
||||
export interface FolderTracks {
|
||||
path: string
|
||||
tracks: Track[]
|
||||
/** Ids of the files the collection already points at. */
|
||||
/** Collection ids of the rows that ARE collection tracks: a file the
|
||||
* collection holds is listed as its track (id, key, rating, cues…), so it
|
||||
* plays, edits and drags as one. Any other file is its own tags, id = path. */
|
||||
in_collection: string[]
|
||||
/** Those rows' collection id → the file's folder id, which adding takes. */
|
||||
files: Record<string, string>
|
||||
/** On an external drive — referencing in place would go missing on unplug. */
|
||||
removable: boolean
|
||||
}
|
||||
@@ -814,14 +837,15 @@ export interface PrefixSuggestions {
|
||||
}
|
||||
|
||||
// API origin. In the packaged desktop app the frontend is served from
|
||||
// tauri://localhost, so it can't use relative /api paths — the Tauri shell
|
||||
// injects window.__KONDUKTOR_API__ (the sidecar's http://127.0.0.1:<port>)
|
||||
// before any app script runs. In the browser dev server it's undefined, so we
|
||||
// fall back to relative URLs and let Vite proxy /api to the backend.
|
||||
export const API_BASE: string =
|
||||
(typeof window !== 'undefined' &&
|
||||
(window as unknown as { __KONDUKTOR_API__?: string }).__KONDUKTOR_API__) ||
|
||||
''
|
||||
// tauri://localhost, so it can't use relative /api paths: the sidecar's
|
||||
// http://127.0.0.1:<port> is only known once it has started, and the startup
|
||||
// screen (StartupScreen.tsx) sets it here before anything else renders. In the
|
||||
// browser dev server it stays '', so URLs are relative and Vite proxies /api.
|
||||
export let API_BASE = ''
|
||||
|
||||
export function setApiBase(url: string): void {
|
||||
API_BASE = url
|
||||
}
|
||||
|
||||
async function getJSON<T>(url: string): Promise<T> {
|
||||
const res = await fetch(API_BASE + url)
|
||||
@@ -988,12 +1012,23 @@ export const api = {
|
||||
send<{ status: string; count: number }>('PUT', `/api/playlists/${encodeURIComponent(nodeId)}/entries`, {
|
||||
track_ids: trackIds,
|
||||
}),
|
||||
addEntries: (nodeId: string, trackIds: string[]) =>
|
||||
send<{ status: string; added: number; count: number }>(
|
||||
/** Append tracks. `duplicates` decides tracks already there: skip them,
|
||||
* add them again (where `playlists.duplicates`), or `ask` — nothing changes
|
||||
* and the answer's `status: 'duplicates'` says how many, to ask and resend. */
|
||||
addEntries: (nodeId: string, trackIds: string[], duplicates: 'skip' | 'add' | 'ask' = 'skip') =>
|
||||
send<{ status: 'added' | 'duplicates'; added: number; duplicates: number; count: number }>(
|
||||
'POST',
|
||||
`/api/playlists/${encodeURIComponent(nodeId)}/add`,
|
||||
{ track_ids: trackIds },
|
||||
{ track_ids: trackIds, duplicates },
|
||||
),
|
||||
/** Move a tree node to `index` among `parentId`'s children (null = top
|
||||
* level), counted without it. Answers its id AFTER the move. */
|
||||
movePlaylist: (nodeId: string, parentId: string | null, index: number) =>
|
||||
send<{ status: string; id: string }>('POST', '/api/playlists/move', {
|
||||
node_id: nodeId,
|
||||
parent_id: parentId,
|
||||
index,
|
||||
}),
|
||||
getPrefs: () => getJSON<Record<string, unknown>>('/api/prefs'),
|
||||
patchPrefs: (patch: Record<string, unknown>) =>
|
||||
send<Record<string, unknown>>('PATCH', '/api/prefs', patch),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createPortal } from 'react-dom'
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react'
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { api, type FolderAddPreview, type FolderAddRequest, type JobStatus } from '../api'
|
||||
import { api, isServerPath, type FolderAddPreview, type FolderAddRequest, type JobStatus } from '../api'
|
||||
import { useCaps } from '../lib/capabilities'
|
||||
import { placedAudioSummary } from '../lib/platformCopy'
|
||||
import { FolderPicker } from './FolderPicker'
|
||||
@@ -20,7 +20,10 @@ import { FolderPicker } from './FolderPicker'
|
||||
*
|
||||
* A library held by a server (`tracks.audio_destination === 'library'`) is the
|
||||
* other exception: it cannot see this computer's files, so the only choice is
|
||||
* which folder ON THE SERVER they are uploaded into.
|
||||
* which folder ON THE SERVER they are uploaded into — unless the files were
|
||||
* browsed in that server's own content folder: they are already where the
|
||||
* library can reach them, so they are added in place, uploaded nowhere and
|
||||
* nothing asked (decided 2026-10-10).
|
||||
*
|
||||
* A playlist or export target still needs the files in the collection first —
|
||||
* both hold collection track ids — so the dialog says so rather than doing it
|
||||
@@ -57,11 +60,15 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
|
||||
// decides copy vs in place itself, so there is nothing to ask.
|
||||
const caps = useCaps()
|
||||
const places = caps.tracks.places_audio
|
||||
// Already in the server's content folder: added where they are.
|
||||
const onServer = trackIds.length > 0 && trackIds.every(isServerPath)
|
||||
// Uploaded into a folder on the server: nothing to ask but where.
|
||||
const uploads = !places && caps.tracks.audio_destination === 'library'
|
||||
const [mode, setMode] = useState<'copy' | 'reference' | null>(uploads ? 'copy' : null)
|
||||
const uploads = !places && !onServer && caps.tracks.audio_destination === 'library'
|
||||
const [mode, setMode] = useState<'copy' | 'reference' | null>(
|
||||
onServer ? 'reference' : uploads ? 'copy' : null,
|
||||
)
|
||||
const [folder, setFolder] = useState('')
|
||||
const remote = useServerImportFolder(uploads)
|
||||
const remote = useServerImportFolder(uploads || onServer)
|
||||
const [browsing, setBrowsing] = useState(false)
|
||||
const [job, setJob] = useState<JobStatus | null>(null)
|
||||
const [starting, setStarting] = useState(false)
|
||||
@@ -251,7 +258,14 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!places && !uploads && (
|
||||
{onServer && (
|
||||
<div className="rounded well px-3 py-2 text-xs text-muted">
|
||||
Already on {remote.serverName}, so your collection points at them where they
|
||||
are. Nothing is uploaded or copied.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!places && !uploads && !onServer && (
|
||||
<div className="space-y-1">
|
||||
{option(
|
||||
'copy',
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
}
|
||||
@@ -10,6 +10,10 @@ export interface ConfirmRequest {
|
||||
/** `danger` (default) for destructive actions — a pink button; `primary`
|
||||
* for a caution that is not destruction, e.g. switching library. */
|
||||
tone?: 'danger' | 'primary'
|
||||
/** A second way to go ahead, as a plain button beside the confirm one
|
||||
* (e.g. "Add them again" next to "Add 6 new"). Enter still means confirm. */
|
||||
altLabel?: string
|
||||
onAlt?: () => void
|
||||
onConfirm: () => Promise<void> | void
|
||||
}
|
||||
|
||||
@@ -19,7 +23,7 @@ interface Props extends ConfirmRequest {
|
||||
|
||||
/** A yes/no confirmation for destructive actions. Enter confirms and Esc
|
||||
* cancels, so a confirmed Delete key stays a two-keystroke action. */
|
||||
export function ConfirmDialog({ title, body, confirmLabel, tone = 'danger', onConfirm, onClose }: Props) {
|
||||
export function ConfirmDialog({ title, body, confirmLabel, tone = 'danger', altLabel, onAlt, onConfirm, onClose }: Props) {
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
const confirm = async () => {
|
||||
@@ -69,6 +73,18 @@ export function ConfirmDialog({ title, body, confirmLabel, tone = 'danger', onCo
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
{altLabel && onAlt && (
|
||||
<button
|
||||
onClick={() => {
|
||||
onAlt()
|
||||
onClose()
|
||||
}}
|
||||
disabled={busy}
|
||||
className="btn-glass rounded-full px-4 py-1.5 text-sm text-text disabled:opacity-40"
|
||||
>
|
||||
{altLabel}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={() => void confirm()}
|
||||
disabled={busy}
|
||||
|
||||
@@ -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,11 +1,15 @@
|
||||
import { useState } from 'react'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { api, type ExportSet } from '../api'
|
||||
import { api, type ExportSet, type TrackOrigin } from '../api'
|
||||
import type { AddTarget } from './AddFilesDialog'
|
||||
import { useCaps } from '../lib/capabilities'
|
||||
import { ExportDialog } from './ExportDialog'
|
||||
import { ExportRunDialog } from './ExportRunDialog'
|
||||
import type { Source } from './Sidebar'
|
||||
import { askConfirm } from '../lib/confirm'
|
||||
import { Icon } from '../lib/icons'
|
||||
import { useDropTarget, type DragPayload } from '../lib/drag'
|
||||
import { playlistIdsUnder } from '../lib/playlistTree'
|
||||
|
||||
/**
|
||||
* Exports in the sidebar: each one a named, persisted slice of the library
|
||||
@@ -27,9 +31,10 @@ interface Props {
|
||||
onSelect: (s: Source) => void
|
||||
onDone: (msg: string) => void
|
||||
onError: (msg: string) => void
|
||||
onAddForeign: (origin: TrackOrigin, ids: string[], target: AddTarget) => void
|
||||
}
|
||||
|
||||
export function ExportsSection({ source, onSelect, onDone, onError }: Props) {
|
||||
export function ExportsSection({ source, onSelect, onDone, onError, onAddForeign }: Props) {
|
||||
const qc = useQueryClient()
|
||||
const [dialog, setDialog] = useState<{ editing: ExportSet | null } | null>(null)
|
||||
const [running, setRunning] = useState<ExportSet | null>(null)
|
||||
@@ -105,6 +110,8 @@ export function ExportsSection({ source, onSelect, onDone, onError }: Props) {
|
||||
onSelect={onSelect}
|
||||
onEdit={() => setDialog({ editing: set })}
|
||||
onRun={() => setRunning(set)}
|
||||
onDone={onDone}
|
||||
onAddForeign={onAddForeign}
|
||||
onDelete={async () => {
|
||||
// Deleting a set never touches its destination folder — the files
|
||||
// already exported are the user's, not Konduktor's to clean up.
|
||||
@@ -132,7 +139,9 @@ function ExportRow({
|
||||
onEdit,
|
||||
onRun,
|
||||
onDelete,
|
||||
onDone,
|
||||
onError,
|
||||
onAddForeign,
|
||||
}: {
|
||||
set: ExportSet
|
||||
source: Source
|
||||
@@ -140,9 +149,14 @@ function ExportRow({
|
||||
onEdit: () => void
|
||||
onRun: () => void
|
||||
onDelete: () => void
|
||||
onDone: (msg: string) => void
|
||||
onError: (msg: string) => void
|
||||
onAddForeign: (origin: TrackOrigin, ids: string[], target: AddTarget) => void
|
||||
}) {
|
||||
const qc = useQueryClient()
|
||||
// The COLLECTION's capabilities (the sidebar sits outside the browsed view's
|
||||
// swap): a device's or folder's tracks must be added to it first.
|
||||
const caps = useCaps()
|
||||
const selected = source.kind === 'export' && source.id === set.id
|
||||
const inside =
|
||||
selected ||
|
||||
@@ -170,11 +184,60 @@ function ExportRow({
|
||||
const data = contents.data
|
||||
const expanded = open || inside
|
||||
|
||||
// A drop target for the collection's tracks (they become loose tracks) and
|
||||
// for playlists or folders dragged from the tree (referenced, live, as
|
||||
// "Add to export" does). Not gated on the library being writable: an export
|
||||
// set is Konduktor's own data.
|
||||
const refresh = () => {
|
||||
qc.invalidateQueries({ queryKey: ['export-contents', set.id] })
|
||||
qc.invalidateQueries({ queryKey: ['export-tracks', set.id] })
|
||||
qc.invalidateQueries({ queryKey: ['export-loose', set.id] })
|
||||
}
|
||||
const accepts = (p: DragPayload) =>
|
||||
p.kind === 'tracks'
|
||||
? p.origin === 'collection' || (caps.writable && caps.tracks.addable)
|
||||
: 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' ? '…' : ''}`,
|
||||
onDrop: async (p) => {
|
||||
if (p.kind === 'tracks' && p.origin !== 'collection') {
|
||||
onAddForeign(p.origin, p.ids, { kind: 'export', id: set.id, name: set.name })
|
||||
return
|
||||
}
|
||||
try {
|
||||
if (p.kind === 'tracks') {
|
||||
await api.addToExport(set.id, { track_ids: p.ids })
|
||||
onDone(`Added ${p.ids.length} track${p.ids.length === 1 ? '' : 's'} to ${set.name}`)
|
||||
} else {
|
||||
const ids = playlistIdsUnder(p.node)
|
||||
await api.addToExport(set.id, { playlist_ids: ids })
|
||||
onDone(
|
||||
p.node.kind === 'folder'
|
||||
? `Added ${ids.length} playlist${ids.length === 1 ? '' : 's'} from “${p.node.name}” to ${set.name}`
|
||||
: `Added “${p.node.name}” to ${set.name}`,
|
||||
)
|
||||
}
|
||||
refresh()
|
||||
} catch (e) {
|
||||
onError((e as Error).message)
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div
|
||||
ref={dropRef}
|
||||
className={`group flex w-full items-center gap-1 rounded-md pr-1 transition-colors ${
|
||||
selected ? 'is-selected text-text' : 'text-muted hover:bg-ink-800 hover:text-text'
|
||||
over
|
||||
? 'bg-gold/10 text-text ring-1 ring-gold'
|
||||
: selected
|
||||
? 'is-selected text-text'
|
||||
: 'text-muted hover:bg-ink-800 hover:text-text'
|
||||
}`}
|
||||
>
|
||||
<button
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { api, type ImportPreview, type JobStatus } from '../api'
|
||||
import { useCaps } from '../lib/capabilities'
|
||||
import { placedAudioSummary } from '../lib/platformCopy'
|
||||
import type { AddTarget } from './AddFilesDialog'
|
||||
import { FolderPicker } from './FolderPicker'
|
||||
import { useServerImportFolder } from './AddFilesDialog'
|
||||
|
||||
@@ -29,13 +30,18 @@ function gb(bytes: number): string {
|
||||
interface Props {
|
||||
/** Playlist to import, or null for the whole device. */
|
||||
playlistId: string | null
|
||||
/** Instead: just these device tracks (dragged out of the device's view). */
|
||||
trackIds?: string[]
|
||||
/** Where they go once imported — the playlist or export they were dropped
|
||||
* on. They are in the collection first either way. */
|
||||
target?: AddTarget | null
|
||||
deviceLabel: string
|
||||
onClose: () => void
|
||||
onDone: (msg: string) => void
|
||||
onError: (msg: string) => void
|
||||
}
|
||||
|
||||
export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError }: Props) {
|
||||
export function ImportDialog({ playlistId, trackIds, target, deviceLabel, onClose, onDone, onError }: Props) {
|
||||
const qc = useQueryClient()
|
||||
// The BASE folder, and whether to put this device's audio in its own
|
||||
// subfolder of it. Kept apart rather than as one path because they are two
|
||||
@@ -81,13 +87,15 @@ export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError
|
||||
|
||||
const body = {
|
||||
destination,
|
||||
playlist_ids: playlistId ? [playlistId] : [],
|
||||
track_ids: [],
|
||||
playlist_ids: trackIds ? [] : playlistId ? [playlistId] : [],
|
||||
track_ids: trackIds ?? [],
|
||||
folder_name: deviceLabel,
|
||||
into_playlist: target?.kind === 'playlist' ? target.id : null,
|
||||
export_id: target?.kind === 'export' ? target.id : null,
|
||||
}
|
||||
|
||||
const preview = useQuery<ImportPreview>({
|
||||
queryKey: ['import-preview', destination, playlistId],
|
||||
queryKey: ['import-preview', destination, playlistId, trackIds?.join('\n'), target?.id],
|
||||
queryFn: () => api.importPreview(body),
|
||||
enabled: !!destination && !job,
|
||||
staleTime: 0,
|
||||
@@ -113,9 +121,16 @@ export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError
|
||||
qc.invalidateQueries({ queryKey: ['collection'] })
|
||||
qc.invalidateQueries({ queryKey: ['state'] })
|
||||
qc.invalidateQueries({ queryKey: ['facets'] })
|
||||
if (target) {
|
||||
qc.invalidateQueries({ queryKey: ['playlist', target.id] })
|
||||
qc.invalidateQueries({ queryKey: ['export-contents', target.id] })
|
||||
qc.invalidateQueries({ queryKey: ['export-tracks', target.id] })
|
||||
qc.invalidateQueries({ queryKey: ['export-loose', target.id] })
|
||||
}
|
||||
onDone(
|
||||
`Imported ${r?.tracks ?? 0} track${r?.tracks === 1 ? '' : 's'}` +
|
||||
(r?.playlists ? ` and ${r.playlists} playlist${r.playlists === 1 ? '' : 's'}` : ''),
|
||||
(r?.playlists ? ` and ${r.playlists} playlist${r.playlists === 1 ? '' : 's'}` : '') +
|
||||
(target ? ` into ${target.name}` : ''),
|
||||
)
|
||||
} else if (next.state === 'failed') {
|
||||
onError(next.error || 'Import failed')
|
||||
@@ -129,7 +144,7 @@ export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError
|
||||
return () => {
|
||||
if (pollRef.current) window.clearInterval(pollRef.current)
|
||||
}
|
||||
}, [job, qc, onDone, onError])
|
||||
}, [job, qc, onDone, onError, target])
|
||||
|
||||
const start = async () => {
|
||||
setStarting(true)
|
||||
@@ -174,9 +189,15 @@ export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError
|
||||
<div className="w-full max-w-lg glass-overlay">
|
||||
<div className="border-b border-line px-5 py-3">
|
||||
<h2 className="text-sm font-semibold text-text">
|
||||
Import from {deviceLabel}
|
||||
{playlistId ? '' : ' — everything'}
|
||||
{trackIds
|
||||
? `Import ${trackIds.length} track${trackIds.length === 1 ? '' : 's'} from ${deviceLabel}`
|
||||
: `Import from ${deviceLabel}${playlistId ? '' : ' — everything'}`}
|
||||
</h2>
|
||||
{target && (
|
||||
<p className="mt-0.5 text-xs text-muted">
|
||||
Into your collection, then into {target.kind === 'export' ? 'the export ' : ''}“{target.name}”.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-4 px-5 py-4 text-sm">
|
||||
@@ -270,9 +291,11 @@ export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="text-xs text-faint">
|
||||
Playlists land in a folder called “{deviceLabel}”.
|
||||
</div>
|
||||
{p.playlists.length > 0 && (
|
||||
<div className="text-xs text-faint">
|
||||
Playlists land in a folder called “{deviceLabel}”.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import { createPortal } from 'react-dom'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { maxPosition, moveToPosition } from '../lib/playlistOrder'
|
||||
|
||||
interface Props {
|
||||
/** The playlist's full entry order — never the sorted or filtered view, so
|
||||
* the move is safe whatever the table is showing. */
|
||||
order: string[]
|
||||
/** The tracks to move; they keep their playlist order as one block. */
|
||||
ids: string[]
|
||||
onMove: (order: string[]) => void
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
/** "Set Position…": type where the first selected track should end up. */
|
||||
export function SetPositionDialog({ order, ids, onMove, onClose }: Props) {
|
||||
const moving = new Set(ids)
|
||||
const count = order.filter((id) => moving.has(id)).length
|
||||
const max = maxPosition(order, moving)
|
||||
const current = order.findIndex((id) => moving.has(id)) + 1
|
||||
const [value, setValue] = useState(String(current))
|
||||
const input = useRef<HTMLInputElement>(null)
|
||||
|
||||
useEffect(() => input.current?.select(), [])
|
||||
|
||||
const typed = Number.parseInt(value, 10)
|
||||
const position = Number.isFinite(typed) ? Math.min(Math.max(typed, 1), max) : null
|
||||
|
||||
const submit = () => {
|
||||
if (position === null) return
|
||||
const next = moveToPosition(order, moving, position)
|
||||
if (next.some((id, i) => id !== order[i])) onMove(next)
|
||||
onClose()
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') onClose()
|
||||
}
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [onClose])
|
||||
|
||||
const span = (p: number) => (count > 1 ? `#${p}–${p + count - 1}` : `#${p}`)
|
||||
|
||||
return createPortal(
|
||||
<div
|
||||
aria-modal="true"
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6"
|
||||
onClick={onClose}
|
||||
>
|
||||
<form
|
||||
className="w-full max-w-sm overflow-hidden glass-overlay"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault()
|
||||
submit()
|
||||
}}
|
||||
>
|
||||
<div className="border-b border-line px-5 py-4 text-[15px] font-semibold tracking-tight">
|
||||
Set position
|
||||
</div>
|
||||
<div className="space-y-3 px-5 py-4 text-sm text-muted">
|
||||
<label className="flex items-center gap-2">
|
||||
<span>{count > 1 ? `Move ${count} tracks to position` : 'Move to position'}</span>
|
||||
<input
|
||||
ref={input}
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
min={1}
|
||||
max={max}
|
||||
value={value}
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
className="w-20 rounded-lg well px-2.5 py-1.5 text-sm tabular-nums text-text outline-none focus:ring-1 focus:ring-accent"
|
||||
/>
|
||||
<span>of {max}</span>
|
||||
</label>
|
||||
<div className="tabular-nums">
|
||||
{position === null
|
||||
? 'Type a position.'
|
||||
: count > 1
|
||||
? `Will occupy ${span(position)}`
|
||||
: `Now ${span(current)} · will be ${span(position)}`}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center justify-end gap-2 border-t border-line px-5 py-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="btn-glass rounded-full px-4 py-1.5 text-sm text-muted hover:text-text"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={position === null}
|
||||
className="btn-primary rounded-full px-4 py-1.5 text-sm font-semibold disabled:opacity-50"
|
||||
>
|
||||
Move
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>,
|
||||
document.body,
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -58,11 +58,17 @@ function sections(slots: number): Section[] {
|
||||
{ keys: [[MOD, 'Click']], action: 'Add to / remove from the selection' },
|
||||
{ keys: [['Double-click']], action: 'Edit a cell' },
|
||||
{ keys: [['Right-click']], action: 'Track menu (header: choose columns)' },
|
||||
{ keys: [['Drag rows']], action: 'Onto a playlist or export to add, onto the deck to load, within a playlist to reorder' },
|
||||
{ keys: [[ALT_KEY, 'Drag']], action: 'Move tracks to another playlist (out of this one)' },
|
||||
{ keys: [['Esc']], action: 'While dragging: cancel the drag' },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Sidebar',
|
||||
rows: [{ keys: [['Right-click']], action: 'New playlist or folder, rename, delete' }],
|
||||
rows: [
|
||||
{ keys: [['Right-click']], action: 'New playlist or folder, rename, delete' },
|
||||
{ keys: [['Drag']], action: 'Rearrange playlists and folders; onto an export to add one' },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Fields & dialogs',
|
||||
|
||||
@@ -1,16 +1,21 @@
|
||||
import { useRef, useState } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { api, type PlaylistKind, type PlaylistNode } from '../api'
|
||||
import { api, type PlaylistKind, type PlaylistNode, type TrackOrigin } from '../api'
|
||||
import type { AddTarget } from './AddFilesDialog'
|
||||
import { useCaps } from '../lib/capabilities'
|
||||
import { SaveBar } from './SaveBar'
|
||||
import { confirmDiscardUnsaved } from '../lib/unsaved'
|
||||
import { SettingsMenu } from './SettingsMenu'
|
||||
import { useAppSetting } from './AppSettings'
|
||||
import { DevicesSection } from './DevicesSection'
|
||||
import { ExportsSection } from './ExportsSection'
|
||||
import { ConfirmDialog, type ConfirmRequest } from './ConfirmDialog'
|
||||
import { ContextMenu, type MenuItem } from './ContextMenu'
|
||||
import { Icon, type IconName } from '../lib/icons'
|
||||
import { PlatformIcon } from '../lib/platformIcons'
|
||||
import { addTracksToPlaylist } from '../lib/addTracks'
|
||||
import { useDragPayload, usePressToDrag, useDropTarget, type DragPayload } from '../lib/drag'
|
||||
import { findNode, idsAfter, nodeIdsUnder, playlistIdsUnder } from '../lib/playlistTree'
|
||||
|
||||
/**
|
||||
* Which view the main table is showing.
|
||||
@@ -50,6 +55,9 @@ 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
|
||||
onOpenPathMapping: () => void
|
||||
/** After unsaved edits were discarded (SaveBar). */
|
||||
onDiscarded?: () => void
|
||||
@@ -57,11 +65,6 @@ interface Props {
|
||||
|
||||
// Kind picks the icon; every behavioural question is answered by the node's own
|
||||
// flags, so nothing here infers what a node can do from what it is called.
|
||||
/** Every selectable playlist at or under a node, in tree order. */
|
||||
function playlistIdsUnder(node: PlaylistNode): string[] {
|
||||
const here = node.kind === 'folder' ? [] : [node.id]
|
||||
return [...here, ...(node.children ?? []).flatMap(playlistIdsUnder)]
|
||||
}
|
||||
|
||||
/** The confirm wording for deleting a node. A folder says what goes with it,
|
||||
* since the whole subtree is deleted and the row only shows the folder. */
|
||||
@@ -97,16 +100,38 @@ type Draft = { kind: 'playlist' | 'folder'; parentId: string | null }
|
||||
/** Actions a row can ask of the sidebar. They live there, not in the row, so
|
||||
* the right-click menu and the hover buttons run the very same code. */
|
||||
interface RowActions {
|
||||
/** Whether a folder is open, and opening / closing it. */
|
||||
isOpen: (node: PlaylistNode) => boolean
|
||||
setOpen: (node: PlaylistNode, open: boolean) => void
|
||||
onContextMenu: (e: React.MouseEvent, node: PlaylistNode) => void
|
||||
onRename: (node: PlaylistNode, name: string) => void
|
||||
onRename: (node: PlaylistNode, name: string, parentId: string | null) => void
|
||||
onDelete: (node: PlaylistNode) => void
|
||||
onAddToExport: (node: PlaylistNode, setId: string) => void
|
||||
/** The row's export button: the export list as a menu under it. */
|
||||
onPickExport: (e: React.MouseEvent<HTMLElement>, node: PlaylistNode) => void
|
||||
onCommitDraft: (name: string) => void
|
||||
onCancelDraft: () => void
|
||||
/** Whether a drag of tracks may drop on this playlist. */
|
||||
acceptsTracks: (node: PlaylistNode, p: Extract<DragPayload, { kind: 'tracks' }>) => 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
|
||||
/** Whether a node may be dragged elsewhere in the tree. */
|
||||
canMove: (node: PlaylistNode) => boolean
|
||||
/** A node dropped in the tree: `index` among `parentId`'s children,
|
||||
* counted without it (what `move_playlist` takes). */
|
||||
onMoveNode: (node: PlaylistNode, parentId: string | null, index: number, into: PlaylistNode | null) => void
|
||||
}
|
||||
|
||||
/** Where a dragged node would land, relative to the row under the pointer:
|
||||
* `before`/`after` it, `into` it (a folder; appended), or `first` inside it —
|
||||
* the lower edge of an EXPANDED folder, where the line sits above its first
|
||||
* child. `tracks` is a track drop on a playlist; `peek` is tracks held over a
|
||||
* collapsed folder, which opens it and drops nothing. */
|
||||
type RowHint =
|
||||
| { zone: 'tracks' | 'peek' }
|
||||
| { zone: 'before' | 'after' | 'into' | 'first'; parentId: string | null; index: number }
|
||||
|
||||
/** The inline name field for a node being created. Enter or clicking away
|
||||
* commits a non-empty name; Esc (or an empty name) creates nothing. */
|
||||
function DraftRow({
|
||||
@@ -156,6 +181,8 @@ function DraftRow({
|
||||
|
||||
function NodeRow({
|
||||
node,
|
||||
parentId,
|
||||
siblings,
|
||||
depth,
|
||||
source,
|
||||
onSelect,
|
||||
@@ -166,6 +193,10 @@ function NodeRow({
|
||||
actions,
|
||||
}: {
|
||||
node: PlaylistNode
|
||||
/** The folder this node sits in; null = the top level. */
|
||||
parentId: string | null
|
||||
/** That folder's children, this node included, in order. */
|
||||
siblings: PlaylistNode[]
|
||||
depth: number
|
||||
source: Source
|
||||
onSelect: (s: Source) => void
|
||||
@@ -175,7 +206,7 @@ function NodeRow({
|
||||
exportSets: { id: string; name: string }[]
|
||||
actions: RowActions
|
||||
}) {
|
||||
const [open, setOpen] = useState(true)
|
||||
const open = actions.isOpen(node)
|
||||
const renaming = renamingId === node.id
|
||||
const [renameDraft, setRenameDraft] = useState(node.name)
|
||||
const isFolder = node.kind === 'folder'
|
||||
@@ -191,17 +222,105 @@ function NodeRow({
|
||||
setRenamingId(node.id)
|
||||
}
|
||||
|
||||
// A row is a drag SOURCE (onto an export, or elsewhere in the tree) and a
|
||||
// drop TARGET for tracks. Whether it takes them is the node's own
|
||||
// `can_add_tracks` plus the library being writable, decided by the sidebar.
|
||||
const startDrag = usePressToDrag(() => (renaming ? null : { kind: 'node', node, parentId }))
|
||||
const moves = (p: DragPayload, alt: boolean) =>
|
||||
p.kind === 'tracks' && alt && !!p.fromPlaylist && p.fromPlaylist !== node.id
|
||||
|
||||
// A node held over this row: which zone, and where that puts it. Never into
|
||||
// itself or anything nested in it; a drop that would leave it exactly where
|
||||
// it is shows nothing.
|
||||
const placeNode = (p: Extract<DragPayload, { kind: 'node' }>, y: number, el: HTMLElement): RowHint | null => {
|
||||
if (!actions.canMove(p.node) || nodeIdsUnder(p.node).has(node.id)) return null
|
||||
const r = el.getBoundingClientRect()
|
||||
const f = (y - r.top) / r.height
|
||||
const opened = expanded && node.children.length > 0
|
||||
const zone: 'before' | 'after' | 'into' | 'first' = node.can_contain_children
|
||||
? f < 0.25 ? 'before' : f > 0.75 ? (opened ? 'first' : 'after') : 'into'
|
||||
: f < 0.5 ? 'before' : 'after'
|
||||
let target: string | null
|
||||
let index: number
|
||||
let current: PlaylistNode[]
|
||||
if (zone === 'into' || zone === 'first') {
|
||||
target = node.id
|
||||
current = node.children
|
||||
index = zone === 'first' ? 0 : node.children.filter((c) => c.id !== p.node.id).length
|
||||
} else {
|
||||
target = parentId
|
||||
current = siblings
|
||||
const i = siblings.filter((c) => c.id !== p.node.id).findIndex((c) => c.id === node.id)
|
||||
index = zone === 'before' ? i : i + 1
|
||||
}
|
||||
if (target === p.parentId && current.findIndex((c) => c.id === p.node.id) === index) return null
|
||||
return { zone, parentId: target, index }
|
||||
}
|
||||
const [dropRef, over] = useDropTarget<RowHint>({
|
||||
hint: (p, at, el) => {
|
||||
if (p.kind === 'node') return placeNode(p, at.y, el)
|
||||
if (actions.acceptsTracks(node, p)) return { zone: 'tracks' }
|
||||
return isFolder && !expanded ? { zone: 'peek' } : null
|
||||
},
|
||||
label: (p, h, at) => {
|
||||
if (h.zone === 'tracks') {
|
||||
if (p.kind === 'tracks' && p.origin === 'device') return `Import into ${node.name}…`
|
||||
if (p.kind === 'tracks' && p.origin === 'folder') 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 (h.zone === 'tracks') actions.onDropTracks(node, p, at.alt)
|
||||
} else if ('parentId' in h) {
|
||||
actions.onMoveNode(p.node, h.parentId, h.index, h.zone === 'into' && !expanded ? node : null)
|
||||
}
|
||||
},
|
||||
})
|
||||
// Holding a drag over a collapsed folder opens it, so a playlist nested in
|
||||
// it can be reached without letting go.
|
||||
const opening = over?.zone === 'into' || over?.zone === 'peek'
|
||||
const openLater = useRef(() => actions.setOpen(node, true))
|
||||
openLater.current = () => actions.setOpen(node, true)
|
||||
useEffect(() => {
|
||||
if (!opening || expanded) return
|
||||
const t = setTimeout(() => openLater.current(), 600)
|
||||
return () => clearTimeout(t)
|
||||
}, [opening, expanded])
|
||||
const ringed = over?.zone === 'tracks' || over?.zone === 'into'
|
||||
const dragging = useDragPayload()
|
||||
const beingMoved = dragging?.kind === 'node' && dragging.node.id === node.id
|
||||
const line = over?.zone === 'before' || over?.zone === 'after' || over?.zone === 'first' ? over.zone : null
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className={beingMoved ? 'opacity-40' : undefined}>
|
||||
<div
|
||||
ref={dropRef}
|
||||
data-node-row
|
||||
onPointerDown={startDrag}
|
||||
onContextMenu={(e) => actions.onContextMenu(e, node)}
|
||||
className={`group flex items-center gap-1 rounded-[10px] pr-1 text-sm transition-colors ${
|
||||
selected ? 'is-selected font-medium text-text' : 'text-muted hover:bg-ink-800 hover:text-text'
|
||||
className={`group relative flex items-center gap-1 rounded-[10px] pr-1 text-sm transition-colors ${
|
||||
ringed
|
||||
? 'bg-accent-soft/40 text-text ring-1 ring-accent'
|
||||
: selected
|
||||
? 'is-selected font-medium text-text'
|
||||
: 'text-muted hover:bg-ink-800 hover:text-text'
|
||||
}`}
|
||||
>
|
||||
{line && (
|
||||
<span
|
||||
aria-hidden
|
||||
className={`pointer-events-none absolute right-1 h-0.5 rounded-full bg-accent ${
|
||||
line === 'before' ? '-top-px' : '-bottom-px'
|
||||
}`}
|
||||
style={{ left: 8 + (line === 'first' ? depth + 1 : depth) * 14 }}
|
||||
/>
|
||||
)}
|
||||
<button
|
||||
onClick={() => {
|
||||
if (isFolder) setOpen((o) => !o)
|
||||
if (isFolder) actions.setOpen(node, !open)
|
||||
else if (selectable) onSelect({ kind: 'playlist', id: node.id, name: node.name })
|
||||
}}
|
||||
className={`flex min-w-0 flex-1 items-center gap-2 py-1.5 pl-2 text-left ${
|
||||
@@ -235,7 +354,7 @@ function NodeRow({
|
||||
if (e.key === 'Enter') {
|
||||
setRenamingId(null)
|
||||
if (renameDraft.trim() && renameDraft.trim() !== node.name)
|
||||
actions.onRename(node, renameDraft.trim())
|
||||
actions.onRename(node, renameDraft.trim(), parentId)
|
||||
} else if (e.key === 'Escape') {
|
||||
setRenamingId(null)
|
||||
}
|
||||
@@ -298,6 +417,8 @@ function NodeRow({
|
||||
<NodeRow
|
||||
key={c.id}
|
||||
node={c}
|
||||
parentId={node.id}
|
||||
siblings={node.children}
|
||||
depth={depth + 1}
|
||||
source={source}
|
||||
onSelect={onSelect}
|
||||
@@ -323,6 +444,7 @@ export function Sidebar({
|
||||
onSwitchLibrary,
|
||||
onOpenLibrary,
|
||||
onDone,
|
||||
onAddForeign,
|
||||
onOpenPathMapping,
|
||||
onDiscarded,
|
||||
}: Props) {
|
||||
@@ -339,8 +461,9 @@ export function Sidebar({
|
||||
}
|
||||
// There is no per-node flag for "you may create a NEW playlist" — the node
|
||||
// flags describe existing nodes — so this is the library-level gate.
|
||||
const canCreate = useCaps().writable
|
||||
const foldersSupported = useCaps().playlists.folders
|
||||
const caps = useCaps()
|
||||
const canCreate = caps.writable
|
||||
const foldersSupported = caps.playlists.folders
|
||||
const { data: playlists, isLoading } = useQuery({
|
||||
queryKey: ['playlists'],
|
||||
queryFn: api.playlists,
|
||||
@@ -352,6 +475,32 @@ export function Sidebar({
|
||||
const [menu, setMenu] = useState<{ x: number; y: number; items: MenuItem[] } | null>(null)
|
||||
const [confirmReq, setConfirmReq] = useState<ConfirmRequest | null>(null)
|
||||
|
||||
// Which folders are open: the setting, except where the user has opened or
|
||||
// closed one. Held here rather than in each row, so it survives a row
|
||||
// remounting and can be reset — on a new library, and when the setting
|
||||
// changes (so changing it visibly does something).
|
||||
const expandByDefault = useAppSetting('expandPlaylistFolders')
|
||||
const [openOverrides, setOpenOverrides] = useState<Record<string, boolean>>({})
|
||||
useEffect(() => setOpenOverrides({}), [library?.path, expandByDefault])
|
||||
const setFolderOpen = (id: string, open: boolean) =>
|
||||
setOpenOverrides((o) => ({ ...o, [id]: open }))
|
||||
// A folder's id — and so every id under it — may change when it is renamed
|
||||
// or moved (a platform addressing folders by path), so open state follows
|
||||
// the subtree to its new ids. Reads the tree as refetched after the edit.
|
||||
const carryOpen = async (before: PlaylistNode, newId: string) => {
|
||||
if (before.kind !== 'folder') return
|
||||
await qc.refetchQueries({ queryKey: ['playlists'] })
|
||||
const after = findNode(qc.getQueryData<PlaylistNode[]>(['playlists']) ?? [], newId)
|
||||
if (!after) return
|
||||
const ids = idsAfter(before, after)
|
||||
setOpenOverrides((o) => {
|
||||
const next = { ...o }
|
||||
for (const [from, to] of ids) if (from !== to && from in o) delete next[from]
|
||||
for (const [from, to] of ids) if (from !== to && from in o) next[to] = o[from]
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const invalidate = () => {
|
||||
qc.invalidateQueries({ queryKey: ['playlists'] })
|
||||
qc.invalidateQueries({ queryKey: ['state'] })
|
||||
@@ -370,10 +519,19 @@ export function Sidebar({
|
||||
})
|
||||
|
||||
const rename = useMutation({
|
||||
mutationFn: ({ node, name }: { node: PlaylistNode; name: string }) =>
|
||||
mutationFn: ({ node, name }: { node: PlaylistNode; name: string; parentId: string | null }) =>
|
||||
api.renamePlaylist(node.id, name),
|
||||
onSuccess: (_d, { node, name }) => {
|
||||
onSuccess: async (_d, { node, name, parentId }) => {
|
||||
invalidate()
|
||||
// The rename does not answer the new id, so the folder is found by its
|
||||
// new name among its siblings (a folder may not share a sibling's name).
|
||||
if (node.kind === 'folder') {
|
||||
await qc.refetchQueries({ queryKey: ['playlists'] })
|
||||
const tree = qc.getQueryData<PlaylistNode[]>(['playlists']) ?? []
|
||||
const siblings = parentId === null ? tree : (findNode(tree, parentId)?.children ?? [])
|
||||
const renamed = siblings.find((n) => n.kind === 'folder' && n.name === name)
|
||||
if (renamed) await carryOpen(node, renamed.id)
|
||||
}
|
||||
if (source.kind === 'playlist' && source.id === node.id)
|
||||
onSelect({ kind: 'playlist', id: node.id, name })
|
||||
},
|
||||
@@ -408,6 +566,9 @@ export function Sidebar({
|
||||
|
||||
const startDraft = (kind: Draft['kind'], parentId: string | null) => {
|
||||
setRenamingId(null)
|
||||
// Open the folder it goes in, or the new node would vanish into a
|
||||
// collapsed folder once named.
|
||||
if (parentId !== null) setFolderOpen(parentId, true)
|
||||
setDraft({ kind, parentId })
|
||||
}
|
||||
|
||||
@@ -469,8 +630,10 @@ export function Sidebar({
|
||||
}
|
||||
|
||||
const actions: RowActions = {
|
||||
isOpen: (node) => openOverrides[node.id] ?? expandByDefault,
|
||||
setOpen: (node, open) => setFolderOpen(node.id, open),
|
||||
onContextMenu: (e, node) => openMenu(e, nodeItems(node)),
|
||||
onRename: (node, name) => rename.mutate({ node, name }),
|
||||
onRename: (node, name, parentId) => rename.mutate({ node, name, parentId }),
|
||||
onDelete: confirmDelete,
|
||||
onAddToExport: (node, setId) => addToExport.mutate({ node, setId }),
|
||||
// Opened as the shared ContextMenu rather than a popover inside the row: the
|
||||
@@ -496,8 +659,60 @@ export function Sidebar({
|
||||
setDraft(null)
|
||||
},
|
||||
onCancelDraft: () => setDraft(null),
|
||||
// A device's or a folder's tracks are not in the collection yet, so they
|
||||
// can only come if the collection can ADD tracks — via the add dialog.
|
||||
acceptsTracks: (node, p) =>
|
||||
caps.writable &&
|
||||
node.can_add_tracks &&
|
||||
(p.origin === 'collection' ? p.fromPlaylist !== node.id : caps.tracks.addable),
|
||||
canMove: (node) => caps.writable && node.can_move,
|
||||
onMoveNode: async (node, parentId, index, into) => {
|
||||
try {
|
||||
const { id } = await api.movePlaylist(node.id, parentId, index)
|
||||
invalidate()
|
||||
void carryOpen(node, id)
|
||||
// Into a COLLAPSED folder the node vanishes from view, so say where.
|
||||
if (into) onDone(`Moved “${node.name}” into ${into.name}`)
|
||||
} catch (e) {
|
||||
onError((e as Error).message)
|
||||
}
|
||||
},
|
||||
onDropTracks: async (node, p, alt) => {
|
||||
if (p.origin !== 'collection') {
|
||||
onAddForeign(p.origin, p.ids, { kind: 'playlist', id: node.id, name: node.name })
|
||||
return
|
||||
}
|
||||
try {
|
||||
const msg = await addTracksToPlaylist({
|
||||
qc,
|
||||
playlist: node,
|
||||
ids: p.ids,
|
||||
duplicatesAllowed: caps.playlists.duplicates,
|
||||
moveFrom: alt ? p.fromPlaylist : undefined,
|
||||
})
|
||||
if (msg) onDone(msg)
|
||||
} catch (e) {
|
||||
onError((e as Error).message)
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
// The empty space below the rows: a node dropped there goes to the END of
|
||||
// the top level. Only the space itself — over a row that declined (a folder
|
||||
// into its own subtree), nothing happens rather than this.
|
||||
const roots = playlists ?? []
|
||||
const [rootDropRef, rootOver] = useDropTarget<{ index: number }>({
|
||||
hint: (p, at) => {
|
||||
if (p.kind !== 'node' || !actions.canMove(p.node)) return null
|
||||
if (document.elementFromPoint(at.x, at.y)?.closest('[data-node-row]')) return null
|
||||
const index = roots.filter((n) => n.id !== p.node.id).length
|
||||
if (p.parentId === null && roots.findIndex((n) => n.id === p.node.id) === index) return null
|
||||
return { index }
|
||||
},
|
||||
label: () => 'Move to the top level',
|
||||
onDrop: (p, h) => p.kind === 'node' && actions.onMoveNode(p.node, null, h.index, null),
|
||||
})
|
||||
|
||||
return (
|
||||
<aside className="glass flex h-full w-64 shrink-0 flex-col">
|
||||
{/* Which library is open — and the way to open a different one. Until
|
||||
@@ -563,6 +778,8 @@ export function Sidebar({
|
||||
{/* Right-click here (below the rows) creates at the top level; rows
|
||||
stop the event so they get their own menu. */}
|
||||
<div
|
||||
ref={rootDropRef}
|
||||
data-drag-scroll=""
|
||||
className="mt-1 min-h-24 flex-1 overflow-y-auto px-2 pb-4"
|
||||
onContextMenu={(e) => openMenu(e, createItems(null))}
|
||||
>
|
||||
@@ -572,6 +789,8 @@ export function Sidebar({
|
||||
<NodeRow
|
||||
key={n.id}
|
||||
node={n}
|
||||
parentId={null}
|
||||
siblings={playlists}
|
||||
depth={0}
|
||||
source={source}
|
||||
onSelect={onSelect}
|
||||
@@ -582,12 +801,19 @@ export function Sidebar({
|
||||
actions={actions}
|
||||
/>
|
||||
))}
|
||||
{rootOver && <div aria-hidden className="mx-2 mt-0.5 h-0.5 rounded-full bg-accent" />}
|
||||
</div>
|
||||
|
||||
{menu && <ContextMenu {...menu} onClose={() => setMenu(null)} />}
|
||||
{confirmReq && <ConfirmDialog {...confirmReq} onClose={() => setConfirmReq(null)} />}
|
||||
|
||||
<ExportsSection source={source} onSelect={onSelect} onDone={onDone} onError={onError} />
|
||||
<ExportsSection
|
||||
source={source}
|
||||
onSelect={onSelect}
|
||||
onDone={onDone}
|
||||
onError={onError}
|
||||
onAddForeign={onAddForeign}
|
||||
/>
|
||||
|
||||
<DevicesSection
|
||||
source={source}
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -59,7 +59,7 @@ export function Toolbar({
|
||||
value={filters.search}
|
||||
onChange={(e) => set({ search: e.target.value })}
|
||||
ref={searchRef}
|
||||
placeholder="Search artist, title, album…"
|
||||
placeholder="Artist, title, album, comment…"
|
||||
className="well w-72 rounded-full py-1.5 pl-9 pr-8 text-sm text-text outline-none placeholder:text-faint focus:ring-1 focus:ring-accent"
|
||||
/>
|
||||
{filters.search && (
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type MutableRefObject } from 'react'
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type MutableRefObject } from 'react'
|
||||
import {
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
@@ -29,7 +29,8 @@ import {
|
||||
useSortable,
|
||||
} from '@dnd-kit/sortable'
|
||||
import { CSS } from '@dnd-kit/utilities'
|
||||
import type { Track } from '../api'
|
||||
import type { Track, TrackOrigin } from '../api'
|
||||
import { beginDrag, useDragPayload, useDropTarget } from '../lib/drag'
|
||||
import { TRACK_COLUMNS } from '../lib/trackColumns'
|
||||
|
||||
/** Fields this platform can persist, for the table's per-cell edit gating.
|
||||
@@ -71,6 +72,9 @@ interface Props {
|
||||
/** A view with a manual order. `enabled` is false while a sort or filter is
|
||||
* active: reordering a partial or re-sorted list would lose the real order. */
|
||||
reorder?: { enabled: boolean; onReorder: (ids: string[]) => void }
|
||||
/** Where dragged rows come from: whose ids they are, and the editable
|
||||
* playlist they leave on an Option-drag (move). Defaults to the collection. */
|
||||
dragFrom?: { origin: TrackOrigin; playlistId?: string }
|
||||
/** Delete/Backspace removes the selected tracks from this view. */
|
||||
onRemove?: (ids: string[]) => void
|
||||
onRowContextMenu?: (track: Track, x: number, y: number) => void
|
||||
@@ -78,6 +82,8 @@ interface Props {
|
||||
onHeaderContextMenu?: (x: number, y: number) => void
|
||||
onPlay?: (track: Track) => void
|
||||
onEditField?: (track: Track, field: keyof Track, value: string | number) => void
|
||||
/** Per-row gate on opening an inline editor (`TableMeta.mayEdit`). */
|
||||
mayEdit?: (track: Track) => boolean
|
||||
activeTrackId?: string | null
|
||||
/** Whether the deck is playing `activeTrackId` (vs. loaded but paused). */
|
||||
activePlaying?: boolean
|
||||
@@ -277,11 +283,13 @@ export function TrackTable({
|
||||
positions,
|
||||
marked,
|
||||
reorder,
|
||||
dragFrom,
|
||||
onRemove,
|
||||
onRowContextMenu,
|
||||
onHeaderContextMenu,
|
||||
onPlay,
|
||||
onEditField,
|
||||
mayEdit,
|
||||
activeTrackId,
|
||||
activePlaying = false,
|
||||
}: Props) {
|
||||
@@ -294,7 +302,7 @@ export function TrackTable({
|
||||
data,
|
||||
columns: TRACK_COLUMNS,
|
||||
state: { sorting, columnVisibility, columnOrder, columnSizing },
|
||||
meta: { onEditField, editableFields },
|
||||
meta: { onEditField, editableFields, mayEdit },
|
||||
onSortingChange: (updater) =>
|
||||
onSortingChange(typeof updater === 'function' ? updater(sorting) : updater),
|
||||
onColumnSizingChange: (updater) =>
|
||||
@@ -363,7 +371,7 @@ export function TrackTable({
|
||||
}
|
||||
|
||||
const clickRow = (index: number, e: { shiftKey: boolean; metaKey: boolean; ctrlKey: boolean }) => {
|
||||
if (!selection || justDraggedRef.current) return
|
||||
if (!selection) return
|
||||
const id = rows[index].original.id
|
||||
const toggle = e.metaKey || e.ctrlKey
|
||||
const anchor = indexOf(anchorRef.current)
|
||||
@@ -381,102 +389,88 @@ export function TrackTable({
|
||||
}
|
||||
}
|
||||
|
||||
// ---- row drag-to-reorder ----------------------------------------------
|
||||
// `drop` is the gap the dragged rows would land in (0 = above the first row).
|
||||
const [drag, setDrag] = useState<{ moving: Set<number>; drop: number } | null>(null)
|
||||
// ---- dragging rows ------------------------------------------------------
|
||||
// Every table's rows are a drag SOURCE (onto playlists, exports, the deck —
|
||||
// lib/drag.tsx); a view with a manual order is also its own drop TARGET, the
|
||||
// in-table reorder. `drop` is the gap the rows would land in (0 = above the
|
||||
// first row).
|
||||
const pressRef = useRef<{ x: number; y: number; index: number } | null>(null)
|
||||
const justDraggedRef = useRef(false)
|
||||
const canDrag = !!reorder?.enabled
|
||||
const tableKey = useRef({}).current
|
||||
const dragging = useDragPayload()
|
||||
const ownDrag = dragging?.kind === 'tracks' && dragging.source === tableKey ? dragging : null
|
||||
const movingIds = useMemo(() => new Set(ownDrag?.ids ?? []), [ownDrag])
|
||||
|
||||
useEffect(() => {
|
||||
if (!canDrag) return
|
||||
let raf = 0
|
||||
let lastY = 0
|
||||
let active: { moving: Set<number>; drop: number } | null = null
|
||||
|
||||
const dropAt = (clientY: number) => {
|
||||
const top = bodyRef.current?.getBoundingClientRect().top ?? 0
|
||||
return Math.max(0, Math.min(rowsRef.current.length, Math.round((clientY - top) / ROW_HEIGHT)))
|
||||
}
|
||||
// Hold near the top/bottom edge to scroll while dragging.
|
||||
const autoScroll = () => {
|
||||
const el = parentRef.current
|
||||
if (el && active) {
|
||||
const r = el.getBoundingClientRect()
|
||||
const edge = 48
|
||||
const dy =
|
||||
lastY < r.top + edge + ROW_HEIGHT ? -12 : lastY > r.bottom - edge ? 12 : 0
|
||||
if (dy) {
|
||||
el.scrollTop += dy
|
||||
active = { ...active, drop: dropAt(lastY) }
|
||||
setDrag(active)
|
||||
}
|
||||
}
|
||||
raf = requestAnimationFrame(autoScroll)
|
||||
}
|
||||
const onMove = (e: PointerEvent) => {
|
||||
const press = pressRef.current
|
||||
if (!press) return
|
||||
lastY = e.clientY
|
||||
if (!active) {
|
||||
if (Math.hypot(e.clientX - press.x, e.clientY - press.y) < 6) return
|
||||
// Dragging a selected row moves the whole selection; any other row
|
||||
// moves alone (and becomes the selection, so what moves is visible).
|
||||
const rs = rowsRef.current
|
||||
const sel = selectionRef.current
|
||||
const pressedId = rs[press.index].original.id
|
||||
let moving: Set<number>
|
||||
if (sel?.selected.has(pressedId)) {
|
||||
moving = new Set(rs.flatMap((r, i) => (sel.selected.has(r.original.id) ? [i] : [])))
|
||||
} else {
|
||||
moving = new Set([press.index])
|
||||
sel?.onChange(new Set([pressedId]))
|
||||
anchorRef.current = leadRef.current = pressedId
|
||||
}
|
||||
active = { moving, drop: dropAt(e.clientY) }
|
||||
document.body.style.userSelect = 'none'
|
||||
document.body.style.cursor = 'grabbing'
|
||||
window.getSelection()?.removeAllRanges()
|
||||
raf = requestAnimationFrame(autoScroll)
|
||||
} else {
|
||||
active = { ...active, drop: dropAt(e.clientY) }
|
||||
}
|
||||
setDrag(active)
|
||||
}
|
||||
const end = () => {
|
||||
if (!press || Math.hypot(e.clientX - press.x, e.clientY - press.y) < 6) return
|
||||
pressRef.current = null
|
||||
if (!active) return
|
||||
const { moving, drop } = active
|
||||
active = null
|
||||
cancelAnimationFrame(raf)
|
||||
document.body.style.userSelect = ''
|
||||
document.body.style.cursor = ''
|
||||
setDrag(null)
|
||||
// Swallow the click that follows the pointerup, so a drop is not also a
|
||||
// click that re-selects the row it ended on.
|
||||
justDraggedRef.current = true
|
||||
setTimeout(() => (justDraggedRef.current = false), 0)
|
||||
// Dragging a selected row carries the whole selection (in the table's
|
||||
// order); any other row goes alone and becomes the selection, so what is
|
||||
// being dragged is visible.
|
||||
const rs = rowsRef.current
|
||||
const sel = selectionRef.current
|
||||
const pressed = rs[press.index]?.original
|
||||
if (!pressed) return
|
||||
let carried: Track[]
|
||||
if (sel?.selected.has(pressed.id)) {
|
||||
carried = rs.filter((r) => sel.selected.has(r.original.id)).map((r) => r.original)
|
||||
} else {
|
||||
carried = [pressed]
|
||||
sel?.onChange(new Set([pressed.id]))
|
||||
anchorRef.current = leadRef.current = pressed.id
|
||||
}
|
||||
const from = dragFromRef.current
|
||||
beginDrag(
|
||||
{
|
||||
kind: 'tracks',
|
||||
ids: [...new Set(carried.map((t) => t.id))],
|
||||
tracks: carried,
|
||||
lead: pressed,
|
||||
origin: from?.origin ?? 'collection',
|
||||
fromPlaylist: from?.playlistId,
|
||||
source: tableKey,
|
||||
},
|
||||
{ x: e.clientX, y: e.clientY, alt: e.altKey },
|
||||
)
|
||||
}
|
||||
const release = () => (pressRef.current = null)
|
||||
window.addEventListener('pointermove', onMove)
|
||||
window.addEventListener('pointerup', release)
|
||||
window.addEventListener('pointercancel', release)
|
||||
return () => {
|
||||
window.removeEventListener('pointermove', onMove)
|
||||
window.removeEventListener('pointerup', release)
|
||||
window.removeEventListener('pointercancel', release)
|
||||
}
|
||||
}, [tableKey])
|
||||
|
||||
const [dropRef, dropHint] = useDropTarget<{ drop: number }>({
|
||||
hint: (p, at) => {
|
||||
if (p.kind !== 'tracks' || p.source !== tableKey || !reorderRef.current?.enabled) return null
|
||||
const top = bodyRef.current?.getBoundingClientRect().top ?? 0
|
||||
return { drop: Math.max(0, Math.min(rowsRef.current.length, Math.round((at.y - top) / ROW_HEIGHT))) }
|
||||
},
|
||||
onDrop: (p, { drop }) => {
|
||||
if (p.kind !== 'tracks') return
|
||||
const ids = new Set(p.ids)
|
||||
const rs = rowsRef.current.map((r) => r.original)
|
||||
const kept = rs.filter((_, i) => !moving.has(i))
|
||||
const block = rs.filter((_, i) => moving.has(i))
|
||||
const at = drop - [...moving].filter((i) => i < drop).length
|
||||
const kept = rs.filter((t) => !ids.has(t.id))
|
||||
const block = rs.filter((t) => ids.has(t.id))
|
||||
const at = drop - rs.slice(0, drop).filter((t) => ids.has(t.id)).length
|
||||
const next = [...kept.slice(0, at), ...block, ...kept.slice(at)]
|
||||
if (next.every((t, i) => t === rs[i])) return
|
||||
setData(next)
|
||||
reorderRef.current?.onReorder(next.map((t) => t.id))
|
||||
}
|
||||
window.addEventListener('pointermove', onMove)
|
||||
window.addEventListener('pointerup', end)
|
||||
window.addEventListener('pointercancel', end)
|
||||
return () => {
|
||||
cancelAnimationFrame(raf)
|
||||
window.removeEventListener('pointermove', onMove)
|
||||
window.removeEventListener('pointerup', end)
|
||||
window.removeEventListener('pointercancel', end)
|
||||
document.body.style.userSelect = ''
|
||||
document.body.style.cursor = ''
|
||||
}
|
||||
}, [canDrag])
|
||||
},
|
||||
})
|
||||
const scrollerRef = useCallback(
|
||||
(el: HTMLDivElement | null) => {
|
||||
parentRef.current = el
|
||||
dropRef(el)
|
||||
},
|
||||
[dropRef],
|
||||
)
|
||||
|
||||
// Latest values for the once-attached window listeners.
|
||||
const rowsRef = useRef(rows)
|
||||
@@ -485,6 +479,8 @@ export function TrackTable({
|
||||
selectionRef.current = selection
|
||||
const reorderRef = useRef(reorder)
|
||||
reorderRef.current = reorder
|
||||
const dragFromRef = useRef(dragFrom)
|
||||
dragFromRef.current = dragFrom
|
||||
|
||||
// Keyboard: ↑/↓ move the selection (Shift extends it), Cmd/Ctrl+A selects
|
||||
// every visible row, Esc clears, Delete/Backspace removes (where the view
|
||||
@@ -547,7 +543,8 @@ export function TrackTable({
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={parentRef}
|
||||
ref={scrollerRef}
|
||||
data-drag-scroll={bodyOffset.header}
|
||||
className="h-full overflow-auto px-1.5"
|
||||
onClick={(e) => {
|
||||
// A click in the empty space below the rows clears the selection.
|
||||
@@ -568,13 +565,13 @@ export function TrackTable({
|
||||
const row = rows[vr.index]
|
||||
const isSelected = selection?.selected.has(row.original.id) ?? false
|
||||
const isActive = activeTrackId === row.original.id
|
||||
const isMoving = drag?.moving.has(vr.index) ?? false
|
||||
const isMoving = movingIds.has(row.original.id)
|
||||
return (
|
||||
<div
|
||||
key={row.id}
|
||||
data-row
|
||||
className={`group absolute left-0 flex items-center border-b border-ink-850 text-sm ${
|
||||
isSelected ? 'bg-accent-soft/50' : drag ? '' : 'hover:bg-ink-850'
|
||||
isSelected ? 'bg-accent-soft/50' : dragging ? '' : 'hover:bg-ink-850'
|
||||
} ${isMoving ? 'opacity-40' : ''}`}
|
||||
style={{ top: 0, transform: `translateY(${vr.start - bodyOffset.top}px)`, height: vr.size, width: '100%' }}
|
||||
onMouseDown={(e) => {
|
||||
@@ -582,7 +579,7 @@ export function TrackTable({
|
||||
if (selection && (e.shiftKey || e.metaKey || e.ctrlKey)) e.preventDefault()
|
||||
}}
|
||||
onPointerDown={(e) => {
|
||||
if (!canDrag || e.button !== 0 || e.shiftKey || e.metaKey || e.ctrlKey) return
|
||||
if (e.button !== 0 || e.shiftKey || e.metaKey || e.ctrlKey) return
|
||||
// Not from a control inside the row (play, stars, an edit field).
|
||||
if ((e.target as HTMLElement).closest('button, input, textarea, select, a')) return
|
||||
pressRef.current = { x: e.clientX, y: e.clientY, index: vr.index }
|
||||
@@ -620,10 +617,10 @@ export function TrackTable({
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
{drag && (
|
||||
{dropHint && (
|
||||
<div
|
||||
className="pointer-events-none absolute left-0 z-10 h-0.5 w-full bg-accent"
|
||||
style={{ top: drag.drop * ROW_HEIGHT - 1 }}
|
||||
style={{ top: dropHint.drop * ROW_HEIGHT - 1 }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -87,6 +87,13 @@ body,
|
||||
overscroll-behavior: none;
|
||||
}
|
||||
|
||||
/* While something is being dragged (lib/drag.tsx), the cursor is the hand
|
||||
everywhere — buttons and links would otherwise show their own. */
|
||||
html.is-dragging,
|
||||
html.is-dragging * {
|
||||
cursor: grabbing !important;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--color-ink-950);
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import type { QueryClient } from '@tanstack/react-query'
|
||||
import { api } from '../api'
|
||||
import { askChoice } from './confirm'
|
||||
|
||||
const plural = (n: number) => `${n} track${n === 1 ? '' : 's'}`
|
||||
|
||||
/**
|
||||
* Add tracks to a playlist — the context menu's "Add to" and a drop on a
|
||||
* sidebar playlist alike, so the two cannot drift.
|
||||
*
|
||||
* Tracks the playlist already holds are ASKED about (decided 2026-10-06), but
|
||||
* only where the platform can hold a track twice (`playlists.duplicates`);
|
||||
* elsewhere they are skipped and the message says so. Nothing is asked when
|
||||
* there are none.
|
||||
*
|
||||
* `moveFrom` is an Option-drag out of another (editable) playlist: once the
|
||||
* tracks are in the target they leave the source. Cancelling the duplicates
|
||||
* question cancels the move too.
|
||||
*
|
||||
* Resolves the message to show, or null when the user cancelled.
|
||||
*/
|
||||
export async function addTracksToPlaylist(opts: {
|
||||
qc: QueryClient
|
||||
playlist: { id: string; name: string }
|
||||
ids: string[]
|
||||
duplicatesAllowed: boolean
|
||||
moveFrom?: string
|
||||
}): Promise<string | null> {
|
||||
const { qc, playlist, ids, duplicatesAllowed, moveFrom } = opts
|
||||
let res = await api.addEntries(playlist.id, ids, duplicatesAllowed ? 'ask' : 'skip')
|
||||
if (res.status === 'duplicates') {
|
||||
const fresh = ids.length - res.duplicates
|
||||
const all = fresh === 0
|
||||
const choice = await askChoice({
|
||||
title: all
|
||||
? `${ids.length === 1 ? 'This track is' : `All ${ids.length} tracks are`} already in “${playlist.name}”`
|
||||
: `${plural(res.duplicates)} ${res.duplicates === 1 ? 'is' : 'are'} already in “${playlist.name}”`,
|
||||
body: all
|
||||
? ids.length === 1
|
||||
? 'Add it again, so the playlist holds it twice?'
|
||||
: 'Add them again, so the playlist holds them twice?'
|
||||
: `Add only the ${plural(fresh)} not there yet, or add every track — the ${res.duplicates === 1 ? 'one already there' : `${res.duplicates} already there`} a second time?`,
|
||||
// All of them there: "skip" would add nothing, which is just Cancel —
|
||||
// so the question is only whether to add them again.
|
||||
confirmLabel: all ? 'Add again' : `Add ${plural(fresh)}`,
|
||||
altLabel: all ? undefined : `Add all ${ids.length}`,
|
||||
tone: 'primary',
|
||||
})
|
||||
if (choice === null) return null
|
||||
res = await api.addEntries(playlist.id, ids, choice === 'alt' || all ? 'add' : 'skip')
|
||||
}
|
||||
|
||||
let moved = false
|
||||
if (moveFrom && moveFrom !== playlist.id) {
|
||||
const gone = new Set(ids)
|
||||
const current = await api.playlistTracks(moveFrom)
|
||||
await api.setEntries(moveFrom, current.map((t) => t.id).filter((id) => !gone.has(id)))
|
||||
qc.invalidateQueries({ queryKey: ['playlist', moveFrom] })
|
||||
moved = true
|
||||
}
|
||||
qc.invalidateQueries({ queryKey: ['state'] })
|
||||
qc.invalidateQueries({ queryKey: ['playlists'] })
|
||||
qc.invalidateQueries({ queryKey: ['playlist', playlist.id] })
|
||||
|
||||
const skipped = ids.length - res.added
|
||||
if (moved) return `Moved ${plural(ids.length)} to ${playlist.name}`
|
||||
if (res.added === 0) return `Nothing added — ${ids.length === 1 ? 'it is' : 'they are all'} already in ${playlist.name}`
|
||||
return `Added ${plural(res.added)} to ${playlist.name}${skipped > 0 ? ` · ${skipped} already there` : ''}`
|
||||
}
|
||||
@@ -12,19 +12,26 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { ConfirmDialog, type ConfirmRequest } from '../components/ConfirmDialog'
|
||||
|
||||
type Ask = Omit<ConfirmRequest, 'onConfirm'>
|
||||
type Pending = { req: Ask; resolve: (ok: boolean) => void }
|
||||
type Ask = Omit<ConfirmRequest, 'onConfirm' | 'onAlt' | 'altLabel'>
|
||||
type Choice = 'confirm' | 'alt' | null
|
||||
type Pending = { req: Ask & { altLabel?: string }; resolve: (choice: Choice) => void }
|
||||
|
||||
let open: ((p: Pending) => void) | null = null
|
||||
|
||||
/** Show a confirmation and resolve true (confirmed) or false (cancelled). */
|
||||
export function askConfirm(req: Ask): Promise<boolean> {
|
||||
return askChoice(req).then((c) => c === 'confirm')
|
||||
}
|
||||
|
||||
/** A confirmation with a SECOND way to go ahead (`altLabel`): resolves
|
||||
* 'confirm', 'alt', or null when cancelled. */
|
||||
export function askChoice(req: Ask & { altLabel?: string }): Promise<Choice> {
|
||||
return new Promise((resolve) => {
|
||||
if (open) open({ req, resolve })
|
||||
// No host mounted (should not happen outside tests): refuse rather than
|
||||
// fall back to a native dialog, since a destructive action must not go
|
||||
// ahead unconfirmed.
|
||||
else resolve(false)
|
||||
else resolve(null)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -34,7 +41,7 @@ export function ConfirmHost() {
|
||||
useEffect(() => {
|
||||
open = (p) =>
|
||||
setPending((prev) => {
|
||||
prev?.resolve(false) // a second ask supersedes an unanswered one
|
||||
prev?.resolve(null) // a second ask supersedes an unanswered one
|
||||
return p
|
||||
})
|
||||
return () => {
|
||||
@@ -45,10 +52,11 @@ export function ConfirmHost() {
|
||||
return (
|
||||
<ConfirmDialog
|
||||
{...pending.req}
|
||||
// A promise settles once, so confirm-then-close resolves `true`.
|
||||
onConfirm={() => pending.resolve(true)}
|
||||
// A promise settles once, so confirm-then-close resolves 'confirm'.
|
||||
onConfirm={() => pending.resolve('confirm')}
|
||||
onAlt={() => pending.resolve('alt')}
|
||||
onClose={() => {
|
||||
pending.resolve(false)
|
||||
pending.resolve(null)
|
||||
setPending(null)
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,301 @@
|
||||
import { useCallback, useEffect, useRef, useSyncExternalStore } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import type { PlaylistNode, Track, TrackOrigin } from '../api'
|
||||
import { Icon } from './icons'
|
||||
|
||||
/**
|
||||
* Drag and drop across the whole window: track rows onto sidebar playlists,
|
||||
* exports and the deck; playlists around the sidebar tree.
|
||||
*
|
||||
* ONE gesture, and the drop TARGET decides what it means. A source calls
|
||||
* `beginDrag` once the pointer has moved past its threshold; targets register
|
||||
* with `useDropTarget` and are found by hit-testing (`elementFromPoint`, then up
|
||||
* through the ancestors), so the virtualized table, the sidebar and the deck
|
||||
* need no shared React tree — and the innermost target that accepts wins, with
|
||||
* the search falling through to an enclosing one where it declines.
|
||||
*
|
||||
* Pointer events, NOT HTML5 drag and drop: Tauri's webview captures native drag
|
||||
* events for its own file drop on Windows, so HTML5 DnD silently dies in the
|
||||
* packaged app.
|
||||
*
|
||||
* The state lives in a module-level store read through useSyncExternalStore
|
||||
* with narrow selectors, so a pointer move re-renders only the target under it
|
||||
* (and the ghost) — never the table.
|
||||
*/
|
||||
|
||||
export type DragPayload =
|
||||
| {
|
||||
kind: 'tracks'
|
||||
ids: string[]
|
||||
tracks: Track[]
|
||||
/** The row the drag started on — what a drop on the deck loads. */
|
||||
lead: Track
|
||||
/** Which library the ids belong to — a device's or a folder's are not
|
||||
* the collection's, so collection targets must not take them as such. */
|
||||
origin: TrackOrigin
|
||||
/** The editable playlist they were dragged out of, for Option = move. */
|
||||
fromPlaylist?: string
|
||||
/** Identity of the table that started the drag (its own reorder target). */
|
||||
source: object
|
||||
}
|
||||
| { kind: 'node'; node: PlaylistNode; parentId: string | null }
|
||||
|
||||
export interface DropPoint {
|
||||
x: number
|
||||
y: number
|
||||
/** Option/Alt held: tracks dragged out of a playlist MOVE instead of copy. */
|
||||
alt: boolean
|
||||
}
|
||||
|
||||
export interface DropSpec<H> {
|
||||
/** The hint for a pointer at `at` over this target — anything the target
|
||||
* needs to draw and to drop (an insertion index, a before/into/after zone) —
|
||||
* or null where it does not accept this drop, so the search continues to an
|
||||
* enclosing target. */
|
||||
hint: (p: DragPayload, at: DropPoint, el: HTMLElement) => H | null
|
||||
/** What a drop here would do, shown on the ghost ("Add to Warmup"). */
|
||||
label?: (p: DragPayload, hint: H, at: DropPoint) => string | null
|
||||
onDrop: (p: DragPayload, hint: H, at: DropPoint) => void
|
||||
}
|
||||
|
||||
interface State {
|
||||
payload: DragPayload | null
|
||||
x: number
|
||||
y: number
|
||||
alt: boolean
|
||||
target: HTMLElement | null
|
||||
hint: unknown
|
||||
label: string | null
|
||||
}
|
||||
|
||||
const IDLE: State = { payload: null, x: 0, y: 0, alt: false, target: null, hint: null, label: null }
|
||||
let state: State = IDLE
|
||||
const listeners = new Set<() => void>()
|
||||
const targets = new Map<HTMLElement, { current: DropSpec<unknown> }>()
|
||||
|
||||
function set(next: Partial<State>) {
|
||||
state = { ...state, ...next }
|
||||
listeners.forEach((l) => l())
|
||||
}
|
||||
function subscribe(l: () => void) {
|
||||
listeners.add(l)
|
||||
return () => listeners.delete(l)
|
||||
}
|
||||
|
||||
/** Keep the previous hint object when the new one has the same fields, so a
|
||||
* target re-renders only when what it draws changes, not on every move. */
|
||||
function sameHint(a: unknown, b: unknown): boolean {
|
||||
if (a === b) return true
|
||||
if (!a || !b || typeof a !== 'object' || typeof b !== 'object') return false
|
||||
const ka = Object.keys(a)
|
||||
return (
|
||||
ka.length === Object.keys(b).length &&
|
||||
ka.every((k) => (a as Record<string, unknown>)[k] === (b as Record<string, unknown>)[k])
|
||||
)
|
||||
}
|
||||
|
||||
/** Find the innermost target under the pointer that accepts, and record its hint. */
|
||||
function evaluate() {
|
||||
const { payload, x, y, alt } = state
|
||||
if (!payload) return
|
||||
const at = { x, y, alt }
|
||||
let el = document.elementFromPoint(x, y) as HTMLElement | null
|
||||
while (el) {
|
||||
const spec = targets.get(el)
|
||||
if (spec) {
|
||||
const hint = spec.current.hint(payload, at, el)
|
||||
if (hint != null) {
|
||||
const keep = state.target === el && sameHint(state.hint, hint) ? state.hint : hint
|
||||
set({ target: el, hint: keep, label: spec.current.label?.(payload, keep, at) ?? null })
|
||||
return
|
||||
}
|
||||
}
|
||||
el = el.parentElement
|
||||
}
|
||||
set({ target: null, hint: null, label: null })
|
||||
}
|
||||
|
||||
let detach: (() => void) | null = null
|
||||
|
||||
/** 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 }) {
|
||||
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
|
||||
// first or last visible row cannot be dropped on, because the list scrolls
|
||||
// out from under a pointer resting on it.
|
||||
let raf = 0
|
||||
const dwell = new Map<HTMLElement, number>()
|
||||
const autoScroll = () => {
|
||||
const { x, y } = state
|
||||
let scrolled = false
|
||||
document.querySelectorAll<HTMLElement>('[data-drag-scroll]').forEach((el) => {
|
||||
const r = el.getBoundingClientRect()
|
||||
const top = r.top + Number(el.dataset.dragScroll || 0)
|
||||
const edge = 20
|
||||
const inside = x >= r.left && x <= r.right && y >= r.top - 24 && y <= r.bottom + 24
|
||||
const dy = !inside ? 0 : y < top + edge ? -Math.ceil((top + edge - y) / 3) : y > r.bottom - edge ? Math.ceil((y - r.bottom + edge) / 3) : 0
|
||||
if (!dy) {
|
||||
dwell.delete(el)
|
||||
return
|
||||
}
|
||||
const since = dwell.get(el) ?? performance.now()
|
||||
dwell.set(el, since)
|
||||
if (performance.now() - since < 250) return
|
||||
const before = el.scrollTop
|
||||
el.scrollTop += Math.max(-20, Math.min(20, dy))
|
||||
scrolled ||= el.scrollTop !== before
|
||||
})
|
||||
if (scrolled) evaluate()
|
||||
raf = requestAnimationFrame(autoScroll)
|
||||
}
|
||||
raf = requestAnimationFrame(autoScroll)
|
||||
|
||||
window.addEventListener('pointermove', onMove)
|
||||
window.addEventListener('pointerup', onUp)
|
||||
window.addEventListener('pointercancel', onCancel)
|
||||
window.addEventListener('keydown', onKey, true)
|
||||
window.addEventListener('keyup', onKey, true)
|
||||
window.addEventListener('blur', onCancel)
|
||||
detach = () => {
|
||||
detach = null
|
||||
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) => {
|
||||
e.stopPropagation()
|
||||
e.preventDefault()
|
||||
}
|
||||
window.addEventListener('click', swallow, true)
|
||||
setTimeout(() => window.removeEventListener('click', swallow, true), 0)
|
||||
set(IDLE)
|
||||
}
|
||||
evaluate()
|
||||
}
|
||||
|
||||
/** A pointerdown handler that starts a drag once the press moves 6 px. A plain
|
||||
* click never moves that far, so the element keeps its click; a press on a
|
||||
* field inside it (a rename input) never drags. `make` is asked at the moment
|
||||
* the drag starts and may return null to refuse. */
|
||||
export function usePressToDrag(make: () => DragPayload | null): (e: React.PointerEvent) => void {
|
||||
const makeRef = useRef(make)
|
||||
makeRef.current = make
|
||||
return useCallback((e: React.PointerEvent) => {
|
||||
if (e.button !== 0 || e.shiftKey || e.metaKey || e.ctrlKey) return
|
||||
if ((e.target as HTMLElement).closest('input, textarea, select')) return
|
||||
const start = { x: e.clientX, y: e.clientY }
|
||||
const onMove = (m: PointerEvent) => {
|
||||
if (Math.hypot(m.clientX - start.x, m.clientY - start.y) < 6) return
|
||||
stop()
|
||||
const payload = makeRef.current()
|
||||
if (payload) beginDrag(payload, { x: m.clientX, y: m.clientY, alt: m.altKey })
|
||||
}
|
||||
const stop = () => {
|
||||
window.removeEventListener('pointermove', onMove)
|
||||
window.removeEventListener('pointerup', stop)
|
||||
window.removeEventListener('pointercancel', stop)
|
||||
}
|
||||
window.addEventListener('pointermove', onMove)
|
||||
window.addEventListener('pointerup', stop)
|
||||
window.addEventListener('pointercancel', stop)
|
||||
}, [])
|
||||
}
|
||||
|
||||
/** The drag in progress, or null. Changes only when a drag starts or ends. */
|
||||
export function useDragPayload(): DragPayload | null {
|
||||
return useSyncExternalStore(subscribe, () => state.payload)
|
||||
}
|
||||
|
||||
/** Register an element as a drop target. Returns the ref to attach and the
|
||||
* current hint while the pointer is over it (null otherwise). */
|
||||
export function useDropTarget<H>(spec: DropSpec<H>): [(el: HTMLElement | null) => void, H | null] {
|
||||
const specRef = useRef(spec as DropSpec<unknown>)
|
||||
specRef.current = spec as DropSpec<unknown>
|
||||
const elRef = useRef<HTMLElement | null>(null)
|
||||
const ref = useCallback((el: HTMLElement | null) => {
|
||||
if (elRef.current) targets.delete(elRef.current)
|
||||
elRef.current = el
|
||||
if (el) targets.set(el, specRef)
|
||||
}, [])
|
||||
useEffect(() => () => {
|
||||
if (elRef.current) targets.delete(elRef.current)
|
||||
}, [])
|
||||
const hint = useSyncExternalStore(subscribe, () =>
|
||||
state.target !== null && state.target === elRef.current ? state.hint : null,
|
||||
)
|
||||
return [ref, hint as H | null]
|
||||
}
|
||||
|
||||
/** What the ghost says it is carrying. */
|
||||
function describe(p: DragPayload): { icon: 'music' | 'playlist' | 'folder' | 'smart'; text: string } {
|
||||
if (p.kind === 'node')
|
||||
return { icon: p.node.kind === 'folder' ? 'folder' : p.node.kind === 'smart' ? 'smart' : 'playlist', text: p.node.name }
|
||||
if (p.ids.length === 1) {
|
||||
const t = p.tracks[0]
|
||||
return { icon: 'music', text: t ? [t.artist, t.title].filter(Boolean).join(' – ') || 'Untitled' : '1 track' }
|
||||
}
|
||||
return { icon: 'music', text: `${p.ids.length} tracks` }
|
||||
}
|
||||
|
||||
/** The ghost under the cursor. Mounted once, in main.tsx. */
|
||||
export function DragLayer() {
|
||||
const s = useSyncExternalStore(subscribe, () => state)
|
||||
if (!s.payload) return null
|
||||
const { icon, text } = describe(s.payload)
|
||||
return createPortal(
|
||||
<div
|
||||
className="glass-overlay pointer-events-none fixed left-0 top-0 z-[90] flex max-w-72 flex-col gap-0.5 overflow-hidden rounded-xl px-3 py-1.5 text-xs shadow-lg"
|
||||
style={{ transform: `translate(${s.x + 14}px, ${s.y + 12}px)` }}
|
||||
>
|
||||
<span className="flex min-w-0 items-center gap-1.5 text-text">
|
||||
<Icon name={icon} size={13} className="shrink-0 text-muted" />
|
||||
<span className="truncate">{text}</span>
|
||||
</span>
|
||||
{s.label && <span className="truncate text-[11px] text-accent">{s.label}</span>}
|
||||
</div>,
|
||||
document.body,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { maxPosition, moveToPosition } from './playlistOrder'
|
||||
|
||||
const order = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
|
||||
const move = (ids: string[], position: number) => moveToPosition(order, new Set(ids), position).join('')
|
||||
|
||||
describe('moveToPosition', () => {
|
||||
it('puts the track AT the position, moving down or up', () => {
|
||||
expect(move(['B'], 5)).toBe('ACDEBFG')
|
||||
expect(move(['F'], 2)).toBe('AFBCDEG')
|
||||
expect(move(['A'], 1)).toBe('ABCDEFG')
|
||||
})
|
||||
|
||||
it('moves a selection as one block in playlist order', () => {
|
||||
expect(move(['F', 'B'], 2)).toBe('ABFCDEG')
|
||||
expect(move(['G', 'A', 'D'], 3)).toBe('BCADGEF')
|
||||
})
|
||||
|
||||
it('clamps past either end', () => {
|
||||
expect(move(['B', 'C'], 99)).toBe('ADEFGBC')
|
||||
expect(move(['C'], 0)).toBe('CABDEFG')
|
||||
})
|
||||
|
||||
it('moves every entry of a track listed twice', () => {
|
||||
expect(moveToPosition(['A', 'B', 'A', 'C'], new Set(['A']), 2).join('')).toBe('BAAC')
|
||||
})
|
||||
})
|
||||
|
||||
describe('maxPosition', () => {
|
||||
it('leaves room for the block behind its first track', () => {
|
||||
expect(maxPosition(order, new Set(['B']))).toBe(7)
|
||||
expect(maxPosition(order, new Set(['B', 'C', 'D']))).toBe(5)
|
||||
expect(move(['B', 'C', 'D'], 5)).toBe('AEFGBCD')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,17 @@
|
||||
/** A playlist's entry order with `moving` lifted out as one block, kept in
|
||||
* their PLAYLIST order, and put back so the block's first track lands at the
|
||||
* 1-based `position` of the result. A position past the end puts the block
|
||||
* last. A track listed twice in the playlist moves with both entries, since a
|
||||
* selection is by track id. */
|
||||
export function moveToPosition(order: string[], moving: ReadonlySet<string>, position: number): string[] {
|
||||
const block = order.filter((id) => moving.has(id))
|
||||
const rest = order.filter((id) => !moving.has(id))
|
||||
const at = Math.min(Math.max(Math.floor(position), 1) - 1, rest.length)
|
||||
return [...rest.slice(0, at), ...block, ...rest.slice(at)]
|
||||
}
|
||||
|
||||
/** The highest position the block's first track can take: the block's own
|
||||
* length is what sits behind it. */
|
||||
export function maxPosition(order: string[], moving: ReadonlySet<string>): number {
|
||||
return order.length - order.filter((id) => moving.has(id)).length + 1
|
||||
}
|
||||