mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4fdb2b7ce1 | ||
|
|
65fbc775ce | ||
|
|
b57dd74445 | ||
|
|
31287bdeb7 | ||
|
|
210c1ab135 | ||
|
|
e211fd180a | ||
|
|
5d059c7604 | ||
|
|
667068c2f1 | ||
|
|
75cb0c8138 | ||
|
|
068e4da08b | ||
|
|
1a28ad6102 | ||
|
|
dd82fa99bb | ||
|
|
fae91e8772 | ||
|
|
68128a123e | ||
|
|
23a5cd72f4 | ||
|
|
17c177e34e |
No files matched your search
@@ -53,6 +53,13 @@ Two independent apps that talk over HTTP:
|
|||||||
inserts among the CURRENT entries (a drop between a table's rows);
|
inserts among the CURRENT entries (a drop between a table's rows);
|
||||||
folder add (`playlist_index`) and device import (`into_playlist_index`)
|
folder add (`playlist_index`) and device import (`into_playlist_index`)
|
||||||
take the same.
|
take the same.
|
||||||
|
`POST /api/playlists/{id}/remove` (`dry_run` counts, changes nothing)
|
||||||
|
drops EVERY occurrence of the given tracks, other entries kept as they
|
||||||
|
are — the track menu's **Remove ▸ From playlist ▸** (decided 2026-10-22,
|
||||||
|
[the discussion](.claude/discussions/discuss-playlist-subtraction-2026-10-22.md)):
|
||||||
|
tracks picked anywhere leave a playlist that is not open, so "A minus B"
|
||||||
|
is open B, select all, remove from A. Lists every `can_reorder`
|
||||||
|
playlist but the open one; the confirm says how many it holds, even 0.
|
||||||
- `capabilities.py` — `Capabilities`: what the loaded library can persist, so
|
- `capabilities.py` — `Capabilities`: what the loaded library can persist, so
|
||||||
the UI can gate controls instead of branching on the platform.
|
the UI can gate controls instead of branching on the platform.
|
||||||
- `query.py` (`TrackIndex`) — all query/filter/sort/facet/stats logic, over
|
- `query.py` (`TrackIndex`) — all query/filter/sort/facet/stats logic, over
|
||||||
@@ -299,6 +306,34 @@ Two independent apps that talk over HTTP:
|
|||||||
cached. The header itself is read by `core/mp3_gapless.py`, which skips
|
cached. The header itself is read by `core/mp3_gapless.py`, which skips
|
||||||
the ID3v2 tag first — a check that did not once misread every real MP3
|
the ID3v2 tag first — a check that did not once misread every real MP3
|
||||||
as header-less.
|
as header-less.
|
||||||
|
- `file_block.py` — **Traktor's own block INSIDE the audio file**, and
|
||||||
|
removing it from copies (measured in Traktor 4.5, 2026-10-24: 2MUCH /
|
||||||
|
Alone (Vip)). Traktor writes a `DMRT` chunk tree (reversed 4CCs; chunk =
|
||||||
|
name + u32 size + u32 child count + payload) into every file it tags:
|
||||||
|
MP4 `ilst` atom `NITR` (mutagen: `_failed_atoms`, or a parsed key), ID3
|
||||||
|
`PRIV` owner `TRAKTOR4` (MP3/AIFF/WAV), Vorbis `traktor4` (FLAC). It
|
||||||
|
holds `HBPM` (float32 BPM), `CUEP` (cues), `AUID` (= the NML AUDIO_ID
|
||||||
|
after a 4-byte length), `TRN3` transients, tags. **An entry with no
|
||||||
|
MODIFIED_DATE — every entry Konduktor creates — makes Traktor re-read
|
||||||
|
the file and take `HBPM` over the NML's BPM, LOCK or not** (anchor
|
||||||
|
kept; it then stamps MODIFIED_DATE/TIME = the file's mtime, UTC
|
||||||
|
seconds). So a grid fixed after Traktor last wrote the block reverted on
|
||||||
|
every export/push. Measured alternatives: AUDIO_ID added — no effect;
|
||||||
|
MODIFIED_DATE later than the file — grid kept but Traktor skips the
|
||||||
|
file entirely, cover art lost. Block removed (no date, no AUDIO_ID) —
|
||||||
|
grid, lock, cues AND art right, a stale `tmpo` ignored, and Traktor
|
||||||
|
writes a fresh, correct block on deck load. Hence the TraktorExporter's
|
||||||
|
`prepare_copy` and the adapter's optional `prepare_copied_audio`
|
||||||
|
(importer copies only): ONLY a copy Konduktor wrote is touched, never a
|
||||||
|
file referenced in place or an upload. The runners
|
||||||
|
(`exporter.prepare_copy` / `prepare_kept`, also used by `local_push`)
|
||||||
|
record `prepared` per copy in the manifest / push ledger, so a KEPT copy
|
||||||
|
from an older export, or one a new Traktor target joins, is cleaned IN
|
||||||
|
PLACE rather than copied again. Not covered: a Traktor collection
|
||||||
|
edited directly — a tag write at Save makes the file newer than the
|
||||||
|
entry, which by the same rule should make Traktor re-read it
|
||||||
|
(untested). Flexible grids are a separate rule: Traktor rounds every
|
||||||
|
segment to a whole number of beats on load, whatever the file says.
|
||||||
- `adapters/rekordbox/` — **track metadata, playlists and hot cues writable;
|
- `adapters/rekordbox/` — **track metadata, playlists and hot cues writable;
|
||||||
the beatgrid still read-only** (milestones 2 and 3a). Also home to
|
the beatgrid still read-only** (milestones 2 and 3a). Also home to
|
||||||
`anlz_writer.py`, which BUILDS analysis files from nothing — Pioneer's format,
|
`anlz_writer.py`, which BUILDS analysis files from nothing — Pioneer's format,
|
||||||
@@ -912,6 +947,47 @@ Two independent apps that talk over HTTP:
|
|||||||
`set_auto_gain` after `add_tracks` (kit G1: an AUDIO_ID-less entry keeps
|
`set_auto_gain` after `add_tracks` (kit G1: an AUDIO_ID-less entry keeps
|
||||||
PERCEIVED_DB through Traktor's first analysis), the Rekordbox Library
|
PERCEIVED_DB through Traktor's first analysis), the Rekordbox Library
|
||||||
through its replay store's `set_auto_gain`. No stick target has one.
|
through its replay store's `set_auto_gain`. No stick target has one.
|
||||||
|
- `local_push.py` — **push an export set into THIS computer's Traktor /
|
||||||
|
rekordbox** (decided 2026-10-20, [the discussion](.claude/discussions/discuss-export-to-local-library-2026-10-20.md)):
|
||||||
|
a set's `kind` is `folder` (an export, as before) or `computer`, whose
|
||||||
|
`mode` is `merge` (default) or `overwrite`; targets ⊆ `PLATFORMS`, no
|
||||||
|
destination. Which library each app uses, the SHARED audio folder and its
|
||||||
|
level are this computer's PREFS (`localLibraries` {platform: path|null =
|
||||||
|
detected}, `localAudioRoot` (default platformdirs Music + `Konduktor`),
|
||||||
|
`localNormalise`, `localLevel`), never the set's (a remote's sets live on
|
||||||
|
its server). Audio lands at `<root>/<source path minus its anchor>` — not
|
||||||
|
`common_dir_prefix`, which moves when a set changes — so a track is ONE
|
||||||
|
file and ONE entry whatever sets hold it; hence one level for the folder.
|
||||||
|
**Merge** opens the library standalone (`registry.open_library`), adds
|
||||||
|
new tracks (`add_tracks`; a file the library already holds maps to its
|
||||||
|
id), brings changed ones up to date — the SOURCE wins — through
|
||||||
|
`set_track_metadata` / `set_key` / `set_track_color` / `set_auto_gain` /
|
||||||
|
`audio_changed` and the protocol's **`replace_cues`** (clear, then the
|
||||||
|
add path's own placement), removes what left the set unless another set
|
||||||
|
holds it or rekordbox refuses (History, Sampler, …: kept + reported,
|
||||||
|
retried), and rebuilds the set's playlists in ONE folder named after it
|
||||||
|
(suffixed `(Konduktor)` beside a user folder of that name; skipped when
|
||||||
|
its hash is unchanged). **Overwrite** runs the platform's export writer
|
||||||
|
into app-data and swaps the files in (rekordbox: `master.db`, the XML,
|
||||||
|
`share/` merged, stale `-wal`/`-shm` deleted); the other sets pushed
|
||||||
|
there are forgotten and their files deleted. The ledger
|
||||||
|
(`app_data/local_push/ledger.json`): per library (`library_id`) and set,
|
||||||
|
source id → local id, copy `rel`, prep hash; per audio root, the export
|
||||||
|
manifest's copy records (`exporter._record`). A copy no set holds is
|
||||||
|
deleted after the push. Refused while the app runs (`core/apps_running.py`,
|
||||||
|
psutil: `rekordbox` exactly, `traktor*` — macOS `Traktor Pro 4`; re-checked
|
||||||
|
before each save), for the library open in Konduktor, and cloud-synced
|
||||||
|
rekordbox. A target library NOT on this computer (`not_found`) is
|
||||||
|
SKIPPED, not a block (`TargetPlan.skipped`): a remote's sets are shared
|
||||||
|
by every computer opening it, so the set dialog lets it be ticked or
|
||||||
|
unticked anywhere; only none found blocks (`no_library_here`). Backup first: Traktor a version-history baseline + a commit per
|
||||||
|
push, rekordbox `master.db` + XML copied to `app_data/local_push/backups`
|
||||||
|
(10 kept). New copies are placed before the library is written; a copy
|
||||||
|
REPLACING a file a library plays waits as `*.konduktor-partial` until a
|
||||||
|
save. Routes `GET /api/local-libraries`, `POST /api/exports/{id}/push/preview`
|
||||||
|
and `/push` (job `local-push`); `/preview` and `/run` 400 a computer set.
|
||||||
|
UI: `ExportDialog`'s Where (folder / This computer, at creation only),
|
||||||
|
`PushRunDialog`, Settings → Local libraries (`LocalLibrariesSettings`).
|
||||||
- `prefs.py` — persisted user prefs (`userprefs.json` in the per-OS app-data
|
- `prefs.py` — persisted user prefs (`userprefs.json` in the per-OS app-data
|
||||||
dir). Last-opened collection (global AND per-platform), library column
|
dir). Last-opened collection (global AND per-platform), library column
|
||||||
layout, prep-deck zoom, import destination. Best-effort, but **every
|
layout, prep-deck zoom, import destination. Best-effort, but **every
|
||||||
@@ -1059,8 +1135,9 @@ Two independent apps that talk over HTTP:
|
|||||||
picker used to be a one-way door with `forcePicker` never set, so changing
|
picker used to be a one-way door with `forcePicker` never set, so changing
|
||||||
library meant restarting; switching confirms first when there are unsaved
|
library meant restarting; switching confirms first when there are unsaved
|
||||||
edits, since the adapter holds them in a native model that opening another
|
edits, since the adapter holds them in a native model that opening another
|
||||||
library replaces — plus the playlist tree. **Creating is right-click
|
library replaces — plus the playlist tree. **Creating is right-click,
|
||||||
only**: a folder's menu offers New Playlist / New Folder inside it, empty
|
or the Playlists header's +** (the top-level menu under the button; with
|
||||||
|
no folders, straight to a new playlist): a folder's menu offers New Playlist / New Folder inside it, empty
|
||||||
space below the rows creates at the top level, and the new node is named
|
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
|
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.
|
same menu and the row's hover buttons, which share one set of actions.
|
||||||
@@ -1230,8 +1307,9 @@ Two independent apps that talk over HTTP:
|
|||||||
newest non-draft, non-prerelease `v…` tag — NOT `/releases/latest`, since the
|
newest non-draft, non-prerelease `v…` tag — NOT `/releases/latest`, since the
|
||||||
stem engine publishes `engine-v*` releases in the same repo — and,
|
stem engine publishes `engine-v*` releases in the same repo — and,
|
||||||
if its tag's **semver part** is newer than `__APP_VERSION__` — build-number
|
if its tag's **semver part** is newer than `__APP_VERSION__` — build-number
|
||||||
`-b<N>` bumps don't count — shows an update dialog with the release's
|
`-b<N>` bumps don't count — shows an update dialog with the "What's
|
||||||
"What's Changed" bullets; "Skip this version" persists
|
Changed" bullets of EVERY release newer than the running version (paged,
|
||||||
|
one section per release, newest first); "Skip this version" persists
|
||||||
`skippedUpdateVersion` to userprefs via `/api/prefs`; check failures are
|
`skippedUpdateVersion` to userprefs via `/api/prefs`; check failures are
|
||||||
silent. **In the desktop app, Update installs it** (decided 2026-10-16,
|
silent. **In the desktop app, Update installs it** (decided 2026-10-16,
|
||||||
[the discussion](.claude/discussions/discuss-self-update-2026-10-16.md)):
|
[the discussion](.claude/discussions/discuss-self-update-2026-10-16.md)):
|
||||||
@@ -1283,13 +1361,14 @@ Two independent apps that talk over HTTP:
|
|||||||
`OverviewWaveform`, which frames the main view's visible range around the
|
`OverviewWaveform`, which frames the main view's visible range around the
|
||||||
playhead (it takes `secPerView` for exactly that). **Controls**: play, CUE, `LoopControls`, then
|
playhead (it takes `secPerView` for exactly that). **Controls**: play, CUE, `LoopControls`, then
|
||||||
(where `cues.memory_cues`) the **Hot / Mem** switch (`ModeSwitch`, the same component as BEAT / MAN), then
|
(where `cues.memory_cues`) the **Hot / Mem** switch (`ModeSwitch`, the same component as BEAT / MAN), then
|
||||||
`HotcueBar`, `MemoryCueStrip` (Mem) OR — in **Grid mode** — `GridEditStrip`, then `TempoControls`
|
`HotcueBar`, `MemoryCueStrip` (Mem) OR — in **Grid mode** — `GridEditStrip`, then the
|
||||||
(±0.01 / ±0.25, ÷2 ×2, tap, lock) and the Grid toggle. The row is a
|
**CUES / GRID** switch (also a `ModeSwitch`) and `TempoControls`
|
||||||
|
(±0.01 / ±0.25, ÷2 ×2, tap, lock). A two-option `ModeSwitch` flips on a
|
||||||
|
click anywhere on it. The row is a
|
||||||
**container** and gives way in stages instead of overlapping: each pad
|
**container** and gives way in stages instead of overlapping: each pad
|
||||||
queries its own width and drops its name below 4rem (the bank never goes
|
queries its own width and drops its name below 4rem (the bank never goes
|
||||||
below `PAD_MIN` per pad), then the tempo group folds into `TempoFold`'s
|
below `PAD_MIN` per pad), then the tempo group folds into `TempoFold`'s
|
||||||
portalled popover, then Grid keeps only its icon. The two row breakpoints
|
portalled popover. That breakpoint is a measured width — move them if controls are added to the row. Every grid control acts
|
||||||
are measured widths — move them if controls are added to the row. Every grid control acts
|
|
||||||
on the marker **governing the playhead**, since a beatgrid is a marker list
|
on the marker **governing the playhead**, since a beatgrid is a marker list
|
||||||
and there is no separate marker selection; see "Beatgrid" below.
|
and there is no separate marker selection; see "Beatgrid" below.
|
||||||
- **One size for loops AND beat jump** (`beatSize`, 1/32–32, persisted as
|
- **One size for loops AND beat jump** (`beatSize`, 1/32–32, persisted as
|
||||||
@@ -1475,7 +1554,8 @@ serialization path.** It enforces:
|
|||||||
- `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays
|
- `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`
|
plus the drag-and-drop routes: `/add`'s three `duplicates` modes (`ask`
|
||||||
changes nothing and counts) and `/api/playlists/move` (path id answered,
|
changes nothing and counts), `/remove` (every copy, order kept, `dry_run`
|
||||||
|
counts and changes nothing, 404 unknown) and `/api/playlists/move` (path id answered,
|
||||||
400 into itself, 404 unknown).
|
400 into itself, 404 unknown).
|
||||||
- `test_timebase.py` — Traktor's MP3 time base: `mp3_gapless` on generated
|
- `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
|
MP3s (header found after a 1 MB ID3 tag; header-less has none), the offset
|
||||||
@@ -1725,6 +1805,30 @@ serialization path.** It enforces:
|
|||||||
none; a levelled copy has its own waveform-cache key; and a file that
|
none; a levelled copy has its own waveform-cache key; and a file that
|
||||||
cannot be levelled (as HE-AAC) is copied unchanged at gain 0 without
|
cannot be levelled (as HE-AAC) is copied unchanged at gain 0 without
|
||||||
failing the export.
|
failing the export.
|
||||||
|
- `test_local_push.py` — pushing into this computer's DJ apps, through the
|
||||||
|
routes: a temp copy of the real collection as the SOURCE (generated MP3s) and
|
||||||
|
ANOTHER as the laptop's collection. A merge removes no line of the user's
|
||||||
|
but the entry / subnode counts; the set's folder holds its tree; cues + a
|
||||||
|
locked grid cross; history commits; an unchanged re-push copies and saves
|
||||||
|
nothing; an edited cue / title reaches the entry (only those two updated);
|
||||||
|
a re-levelled copy is swapped in with FILESIZE following; a user folder with
|
||||||
|
the set's name is left alone; a shared track is one entry and survives one
|
||||||
|
set's removal; a running app 409s; the open library is never a target; a
|
||||||
|
copy failure leaves the collection and folder untouched; overwrite leaves
|
||||||
|
only that set and deletes the other's files. On a temp copy of the local
|
||||||
|
rekordbox library (skipped when absent): merge, backup, a refused removal
|
||||||
|
kept and reported then retried, overwrite with a stale WAL.
|
||||||
|
- `test_traktor_file_block.py` — Traktor's block inside the file, on
|
||||||
|
GENERATED MP3 / M4A / FLAC carrying one that says 175 while the library's
|
||||||
|
grid says 176, with collections built from the empty Traktor skeleton:
|
||||||
|
each format's block removed with everything else kept (audio
|
||||||
|
sample-identical, a foreign PRIV frame, the cover, the ID3 version), a file
|
||||||
|
without one never rewritten; an export's copies lose it while the sources
|
||||||
|
keep it, the manifest records `prepared`, a re-export rewrites nothing, a
|
||||||
|
kept copy from an older export is cleaned in place (same inode), a target
|
||||||
|
without the hook (Rekordbox Export) leaves it and adding Traktor cleans the
|
||||||
|
kept copies; a local push's shared copies and an import's copies lose it,
|
||||||
|
a file added in place is never touched.
|
||||||
- `test_auto_hotcues.py` — Auto Hotcues in three layers: `structure.analyse`
|
- `test_auto_hotcues.py` — Auto Hotcues in three layers: `structure.analyse`
|
||||||
on SYNTHETIC audio with known sections (the intro with a kick is not a drop;
|
on SYNTHETIC audio with known sections (the intro with a kick is not a drop;
|
||||||
no breakdown after the last drop), `plan`'s outcomes and beat-counted offsets
|
no breakdown after the last drop), `plan`'s outcomes and beat-counted offsets
|
||||||
@@ -2028,6 +2132,18 @@ frontend at `http://localhost:5173`.
|
|||||||
`ConfirmDialog` by the `ConfirmHost` mounted once in `main.tsx`. `tone` is
|
`ConfirmDialog` by the `ConfirmHost` mounted once in `main.tsx`. `tone` is
|
||||||
`danger` (default, pink) or `primary`. Components that already hold dialog
|
`danger` (default, pink) or `primary`. Components that already hold dialog
|
||||||
state may still render `ConfirmDialog` directly.
|
state may still render `ConfirmDialog` directly.
|
||||||
|
- **Every dialog is a `<Modal>`** (`components/Modal.tsx`; decided 2026-11-02):
|
||||||
|
the portal, backdrop, `aria-modal`, Esc and outside click in ONE place —
|
||||||
|
never a hand-rolled backdrop or a per-dialog Esc listener. `onDismiss` is
|
||||||
|
what the dialog's Cancel / Close (or Hide, while a job runs) does, `null`
|
||||||
|
while that is unavailable (busy): Esc and the backdrop then do nothing. An
|
||||||
|
outside click closes only when the press AND the release are both on the
|
||||||
|
backdrop — a plain `onClick` fires on the common ancestor, so a text
|
||||||
|
selection dragged out of the dialog closed it. Esc reaches only the TOP
|
||||||
|
modal (by opening order) and never while a menu is open. `layer="nested"`
|
||||||
|
= `z-[60]` (a dialog opened from a dialog, QuitGuard). The one exception is
|
||||||
|
`RelocateDialog`'s `backdropDismiss={false}` (Esc only: "Not now" lasts
|
||||||
|
until the library is reopened).
|
||||||
|
|
||||||
## Theme — "dark liquid glass"
|
## Theme — "dark liquid glass"
|
||||||
|
|
||||||
@@ -2052,7 +2168,7 @@ easy to break:
|
|||||||
opened far from the cursor. `.glass`'s blur and tint therefore live on its
|
opened far from the cursor. `.glass`'s blur and tint therefore live on its
|
||||||
`::after` (z-index -1 under `isolation: isolate`), not on the panel.
|
`::after` (z-index -1 under `isolation: isolate`), not on the panel.
|
||||||
- **Every overlay renders through `createPortal(…, document.body)`** — all
|
- **Every overlay renders through `createPortal(…, document.body)`** — all
|
||||||
dialogs, `ContextMenu` and `Toast`. Each `.glass` panel is a stacking context
|
dialogs (via `Modal`), `ContextMenu` and `Toast`. Each `.glass` panel is a stacking context
|
||||||
(`isolation`), so an overlay rendered INSIDE one can never rise above a
|
(`isolation`), so an overlay rendered INSIDE one can never rise above a
|
||||||
neighbouring panel, whatever its z-index: New Export (from the sidebar) sat
|
neighbouring panel, whatever its z-index: New Export (from the sidebar) sat
|
||||||
behind the library, and the deck's Auto Hotcues dialog behind both. One
|
behind the library, and the deck's Auto Hotcues dialog behind both. One
|
||||||
|
|||||||
@@ -608,3 +608,8 @@ class OneLibraryAdapter:
|
|||||||
|
|
||||||
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues:
|
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues:
|
||||||
raise Unsupported("OneLibrary has no beatgrid lock")
|
raise Unsupported("OneLibrary has no beatgrid lock")
|
||||||
|
|
||||||
|
def replace_cues(self, track_id: str, cues: TrackCues) -> TrackCues:
|
||||||
|
# Only a DJ app's library on this computer is pushed into; a stick is
|
||||||
|
# filled by an export.
|
||||||
|
raise Unsupported("A OneLibrary drive is filled by an export, not a push")
|
||||||
@@ -21,7 +21,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from ...core.adapter import InvalidCommand, Unsupported, local_audio_facts
|
from ...core.adapter import InvalidCommand, NotFound, Unsupported, local_audio_facts
|
||||||
from ...core.capabilities import Capabilities
|
from ...core.capabilities import Capabilities
|
||||||
from ...core.model import GridMarker, PlaylistNode, Track, TrackCues
|
from ...core.model import GridMarker, PlaylistNode, Track, TrackCues
|
||||||
from ...core.pathmap import PathMapping, common_dir_prefix
|
from ...core.pathmap import PathMapping, common_dir_prefix
|
||||||
@@ -460,6 +460,30 @@ class RekordboxAdapter:
|
|||||||
self._store.delete_grid(track_id)
|
self._store.delete_grid(track_id)
|
||||||
return self._refresh_cues(track_id)
|
return self._refresh_cues(track_id)
|
||||||
|
|
||||||
|
def replace_cues(self, track_id: str, cues: TrackCues) -> TrackCues:
|
||||||
|
"""Clear the track's cues and grid, then place `cues` as `add_tracks`
|
||||||
|
does (`_place_imported_cues`). Rekordbox has no grid lock, so
|
||||||
|
`grid_locked` is not carried; a cue on the reserved `Kind=4` (shown,
|
||||||
|
not editable) is left where it is."""
|
||||||
|
self._require_writable("Replacing cues")
|
||||||
|
current = self.track_cues(track_id)
|
||||||
|
if current is None:
|
||||||
|
raise NotFound(f"Track not found: {track_id}")
|
||||||
|
for cue in current.cues:
|
||||||
|
if not cue.editable:
|
||||||
|
continue
|
||||||
|
if cue.role == "hotcue" and cue.slot is not None:
|
||||||
|
self._store.delete_cue(track_id, cue.slot)
|
||||||
|
elif cue.id:
|
||||||
|
self._store.delete_memory_cue(track_id, cue.id)
|
||||||
|
markers = list(cues.grid_markers or [])
|
||||||
|
if markers:
|
||||||
|
self._store.replace_grid(track_id, self._markers_from(markers))
|
||||||
|
elif current.grid_markers:
|
||||||
|
self._store.delete_grid(track_id)
|
||||||
|
self._place_imported_cues(track_id, cues)
|
||||||
|
return self._refresh_cues(track_id)
|
||||||
|
|
||||||
# ---- save -------------------------------------------------------------
|
# ---- save -------------------------------------------------------------
|
||||||
@property
|
@property
|
||||||
def dirty(self) -> bool:
|
def dirty(self) -> bool:
|
||||||
|
|||||||
@@ -280,6 +280,11 @@ class RemoteAdapter:
|
|||||||
def set_grid_lock(self, track_id, locked):
|
def set_grid_lock(self, track_id, locked):
|
||||||
return self._call("set_grid_lock", track_id=track_id, locked=locked)
|
return self._call("set_grid_lock", track_id=track_id, locked=locked)
|
||||||
|
|
||||||
|
def replace_cues(self, track_id, cues):
|
||||||
|
# Never travels (`remote_protocol.EXCLUDED`): a push targets a library
|
||||||
|
# on THIS computer.
|
||||||
|
raise Unsupported("A library held by a server is not a push target")
|
||||||
|
|
||||||
# ---- adding tracks ------------------------------------------------------------------
|
# ---- adding tracks ------------------------------------------------------------------
|
||||||
def upload_audio(self, source: Path, folder: str, name: str, *, progress=None) -> Path:
|
def upload_audio(self, source: Path, folder: str, name: str, *, progress=None) -> Path:
|
||||||
"""Send `source` into `folder` on the server; the path it landed at (a
|
"""Send `source` into `folder` on the server; the path it landed at (a
|
||||||
|
|||||||
@@ -459,6 +459,39 @@ class TraktorAdapter:
|
|||||||
self._store.set_lock(track_id, locked)
|
self._store.set_lock(track_id, locked)
|
||||||
return self._refresh(track_id)
|
return self._refresh(track_id)
|
||||||
|
|
||||||
|
def replace_cues(self, track_id: str, cues: TrackCues) -> TrackCues:
|
||||||
|
"""Clear the entry's prep, then replay `cues` exactly as `add_tracks`
|
||||||
|
does (`_apply_imported_cues`), so an updated entry and a new one cannot
|
||||||
|
differ. `delete_grid` takes the paired companion cues with it."""
|
||||||
|
current = self.track_cues(track_id)
|
||||||
|
if current is None:
|
||||||
|
raise NotFound(f"Track not found: {track_id}")
|
||||||
|
with _translate():
|
||||||
|
if current.grid_markers:
|
||||||
|
self._store.delete_grid(track_id)
|
||||||
|
# One at a time, re-reading between: a memory cue's id is derived
|
||||||
|
# from its content and its rank among cues at the same START, so a
|
||||||
|
# deletion can renumber the next one.
|
||||||
|
for _ in range(len(self.track_cues(track_id).cues)):
|
||||||
|
self._refresh(track_id)
|
||||||
|
left = self.track_cues(track_id).cues
|
||||||
|
cue = next((c for c in left if c.slot is not None or c.id), None)
|
||||||
|
if cue is None:
|
||||||
|
break
|
||||||
|
if cue.slot is not None:
|
||||||
|
self._store.delete_hotcue(track_id, cue.slot)
|
||||||
|
else:
|
||||||
|
self._store.delete_memory_cue(track_id, cue.id)
|
||||||
|
if current.grid_locked and not cues.grid_locked:
|
||||||
|
self._store.set_lock(track_id, False)
|
||||||
|
self._refresh(track_id)
|
||||||
|
if current.grid_locked and cues.grid_locked:
|
||||||
|
# Already locked: `_apply_imported_cues` would lock it again and
|
||||||
|
# move LOCK_MODIFICATION_TIME for nothing.
|
||||||
|
cues = cues.model_copy(update={"grid_locked": False})
|
||||||
|
self._apply_imported_cues(track_id, cues)
|
||||||
|
return self._refresh(track_id)
|
||||||
|
|
||||||
# ---- audio / paths ----------------------------------------------------
|
# ---- audio / paths ----------------------------------------------------
|
||||||
def audio_path(self, track_id: str):
|
def audio_path(self, track_id: str):
|
||||||
return self._store.audio_path(track_id)
|
return self._store.audio_path(track_id)
|
||||||
@@ -479,6 +512,15 @@ class TraktorAdapter:
|
|||||||
track uploaded there is stored as that computer would have stored it."""
|
track uploaded there is stored as that computer would have stored it."""
|
||||||
self._store.set_write_stored_paths(enabled)
|
self._store.set_write_stored_paths(enabled)
|
||||||
|
|
||||||
|
def prepare_copied_audio(self, path: Path) -> bool:
|
||||||
|
"""OPTIONAL: ready a file the importer just COPIED for this library —
|
||||||
|
Traktor's own block removed (`file_block`), which Traktor would
|
||||||
|
otherwise restore over the entry's grid. Never called for a file
|
||||||
|
added in place."""
|
||||||
|
from . import file_block
|
||||||
|
|
||||||
|
return file_block.strip(path)
|
||||||
|
|
||||||
def unresolved_path_groups(self) -> list[PathGroup]:
|
def unresolved_path_groups(self) -> list[PathGroup]:
|
||||||
return self._store.unresolved_path_groups()
|
return self._store.unresolved_path_groups()
|
||||||
|
|
||||||
|
|||||||
@@ -35,8 +35,9 @@ import logging
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from ...core.adapter import NewTrack
|
from ...core.adapter import NewTrack
|
||||||
from ...core.export import ExportPayload, WrittenLibrary
|
from ...core.export import OTHER_PLAYLIST, ExportPayload, WrittenLibrary, write_playlist_tree
|
||||||
from .adapter import TraktorAdapter
|
from .adapter import TraktorAdapter
|
||||||
|
from . import file_block
|
||||||
from .capabilities import capabilities_for
|
from .capabilities import capabilities_for
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
@@ -56,11 +57,6 @@ SKELETON = (
|
|||||||
"</INDEXING>\n</NML>\n"
|
"</INDEXING>\n</NML>\n"
|
||||||
)
|
)
|
||||||
|
|
||||||
#: Loose tracks — added individually rather than through a playlist — would
|
|
||||||
#: otherwise be reachable only by search in the exported library.
|
|
||||||
OTHER_PLAYLIST = "Other"
|
|
||||||
|
|
||||||
|
|
||||||
class TraktorExporter:
|
class TraktorExporter:
|
||||||
platform = "traktor"
|
platform = "traktor"
|
||||||
menu_order = 20
|
menu_order = 20
|
||||||
@@ -73,6 +69,12 @@ class TraktorExporter:
|
|||||||
#: analysis, which overwrites only ANALYZED_DB).
|
#: analysis, which overwrites only ANALYZED_DB).
|
||||||
writes_auto_gain = True
|
writes_auto_gain = True
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def prepare_copy(path: Path) -> bool:
|
||||||
|
"""Remove Traktor's own block from a copy (`file_block`): left in, it
|
||||||
|
is restored over this entry's grid when Traktor opens the collection."""
|
||||||
|
return file_block.strip(path)
|
||||||
|
|
||||||
def capabilities(self):
|
def capabilities(self):
|
||||||
"""What a Traktor library can hold — answered with no library to read.
|
"""What a Traktor library can hold — answered with no library to read.
|
||||||
|
|
||||||
@@ -119,35 +121,5 @@ class TraktorExporter:
|
|||||||
"""Recreate the tree — at the top level, or with `payload.root_folder`
|
"""Recreate the tree — at the top level, or with `payload.root_folder`
|
||||||
under one folder named after the export (None = the top level)."""
|
under one folder named after the export (None = the top level)."""
|
||||||
root = adapter.create_folder(payload.name) if payload.root_folder else None
|
root = adapter.create_folder(payload.name) if payload.root_folder else None
|
||||||
folders: dict[tuple[str, ...], str | None] = {(): root}
|
write_playlist_tree(adapter, payload.playlists, [t.source_id for t in payload.tracks],
|
||||||
|
moved, root)
|
||||||
for playlist in payload.playlists:
|
|
||||||
parent = self._folder_for(adapter, folders, tuple(playlist.folders), root)
|
|
||||||
node_id = adapter.create_playlist(playlist.name, parent)
|
|
||||||
entries = [moved[t] for t in playlist.track_ids if t in moved]
|
|
||||||
if entries:
|
|
||||||
adapter.set_playlist_entries(node_id, entries)
|
|
||||||
|
|
||||||
loose = self._loose(payload, moved)
|
|
||||||
if loose:
|
|
||||||
node_id = adapter.create_playlist(OTHER_PLAYLIST, root)
|
|
||||||
adapter.set_playlist_entries(node_id, loose)
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
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]
|
|
||||||
if branch not in folders:
|
|
||||||
folders[branch] = adapter.create_folder(branch[-1], folders[branch[:-1]])
|
|
||||||
return folders.get(path, root)
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _loose(payload: ExportPayload, moved: dict) -> list[str]:
|
|
||||||
"""Tracks no exported playlist accounts for, in payload order."""
|
|
||||||
in_playlists = {t for p in payload.playlists for t in p.track_ids}
|
|
||||||
return [
|
|
||||||
moved[t.source_id]
|
|
||||||
for t in payload.tracks
|
|
||||||
if t.source_id not in in_playlists and t.source_id in moved
|
|
||||||
]
|
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
"""Traktor's own block INSIDE an audio file, and removing it from a copy.
|
||||||
|
|
||||||
|
Traktor writes a binary block of its analysis into every file it tags — the
|
||||||
|
same `DMRT` chunk tree in each format, stored where the format allows:
|
||||||
|
|
||||||
|
- MP4 (`.m4a`, stem files): the `ilst` atom `NITR`
|
||||||
|
- ID3 (MP3, AIFF, WAV): a `PRIV` frame owned by `TRAKTOR4`
|
||||||
|
- Vorbis comments (FLAC, Ogg): the field `traktor4`
|
||||||
|
|
||||||
|
It holds a BPM (`HBPM`), the cues (`CUEP`), the audio id, transients, tags.
|
||||||
|
Measured in Traktor 4.5 (2026-10-24, 2MUCH / Alone (Vip)): on an entry it did
|
||||||
|
not write itself — no MODIFIED_DATE, as every entry Konduktor creates — Traktor
|
||||||
|
re-reads the file and takes the block's BPM over the collection's, LOCK or not,
|
||||||
|
keeping the anchor. A grid fixed after Traktor last wrote the block (in
|
||||||
|
Konduktor, or in Traktor without a tag write) is reverted on every export.
|
||||||
|
|
||||||
|
Giving the entry a MODIFIED_DATE later than the file stops that, but Traktor
|
||||||
|
then skips the file altogether, cover art included. Giving it the block's
|
||||||
|
AUDIO_ID changes nothing. Removing the block from the copy does both: Traktor
|
||||||
|
imports the file as new — art, file facts and analysis from the file; BPM,
|
||||||
|
grid, lock and cues from the entry — and writes a fresh, correct block itself
|
||||||
|
when the track is first loaded. A stale `TBPM`/`tmpo` tag is ignored.
|
||||||
|
|
||||||
|
Only ever applied to a COPY Konduktor wrote. A file the user's library
|
||||||
|
references in place is the user's, and is never touched.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
#: The ID3 PRIV owner and the Vorbis field name Traktor writes the block under.
|
||||||
|
_PRIV_OWNER = "TRAKTOR4"
|
||||||
|
_VORBIS_FIELD = "traktor4"
|
||||||
|
#: The MP4 atom. mutagen keeps it among the atoms it could not parse — or, in
|
||||||
|
#: some files, parses it into an ordinary key; both are checked.
|
||||||
|
_MP4_ATOM = "NITR"
|
||||||
|
|
||||||
|
|
||||||
|
def has_block(path: Path) -> bool:
|
||||||
|
"""Whether the file carries Traktor's block. False for anything unreadable."""
|
||||||
|
audio = _open(path)
|
||||||
|
return audio is not None and bool(_remove(audio, dry_run=True))
|
||||||
|
|
||||||
|
|
||||||
|
def strip(path: Path) -> bool:
|
||||||
|
"""Remove Traktor's block from `path`, in place; True if it held one.
|
||||||
|
|
||||||
|
Everything else in the file is kept: other tags, cover, the stem box, the
|
||||||
|
audio. A file without a block is not rewritten at all. A file that cannot
|
||||||
|
be read or written is left as it is — a copy that still carries the block
|
||||||
|
is the old behaviour, never a failed export — and the reason is logged.
|
||||||
|
"""
|
||||||
|
audio = _open(path)
|
||||||
|
if audio is None or not _remove(audio, dry_run=False):
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
version = getattr(audio.tags, "version", None)
|
||||||
|
if version is not None and _is_id3(audio):
|
||||||
|
# Keep the file's own ID3 version: nothing else in it is changing.
|
||||||
|
audio.save(v2_version=3 if version[1] == 3 else 4)
|
||||||
|
else:
|
||||||
|
audio.save()
|
||||||
|
except Exception as ex: # noqa: BLE001 — see the docstring
|
||||||
|
log.warning("could not remove Traktor's block from %s: %s", path, ex)
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def _open(path: Path):
|
||||||
|
try:
|
||||||
|
import mutagen
|
||||||
|
|
||||||
|
audio = mutagen.File(path)
|
||||||
|
except Exception as ex: # noqa: BLE001 — an unreadable file has no block we can see
|
||||||
|
log.debug("cannot read tags of %s: %s", path, ex)
|
||||||
|
return None
|
||||||
|
if audio is None or audio.tags is None:
|
||||||
|
return None
|
||||||
|
return audio
|
||||||
|
|
||||||
|
|
||||||
|
def _is_id3(audio) -> bool:
|
||||||
|
from mutagen.id3 import ID3
|
||||||
|
|
||||||
|
return isinstance(audio.tags, ID3)
|
||||||
|
|
||||||
|
|
||||||
|
def _remove(audio, *, dry_run: bool) -> int:
|
||||||
|
"""How many block entries `audio`'s tags hold, removing them unless
|
||||||
|
`dry_run`. Never saves."""
|
||||||
|
from mutagen.mp4 import MP4Tags
|
||||||
|
|
||||||
|
tags = audio.tags
|
||||||
|
found = 0
|
||||||
|
if isinstance(tags, MP4Tags):
|
||||||
|
failed = getattr(tags, "_failed_atoms", {})
|
||||||
|
if _MP4_ATOM in failed:
|
||||||
|
found += 1
|
||||||
|
if not dry_run:
|
||||||
|
del failed[_MP4_ATOM]
|
||||||
|
if _MP4_ATOM in tags:
|
||||||
|
found += 1
|
||||||
|
if not dry_run:
|
||||||
|
del tags[_MP4_ATOM]
|
||||||
|
elif _is_id3(audio):
|
||||||
|
keys = [k for k, frame in tags.items()
|
||||||
|
if k.startswith("PRIV:") and getattr(frame, "owner", None) == _PRIV_OWNER]
|
||||||
|
found += len(keys)
|
||||||
|
if not dry_run:
|
||||||
|
for k in keys:
|
||||||
|
del tags[k]
|
||||||
|
elif hasattr(tags, "keys"): # Vorbis comments: case-insensitive field names
|
||||||
|
keys = [k for k in tags.keys() if k.lower() == _VORBIS_FIELD]
|
||||||
|
found += len(keys)
|
||||||
|
if not dry_run:
|
||||||
|
for k in keys:
|
||||||
|
del tags[k]
|
||||||
|
return found
|
||||||
@@ -349,6 +349,12 @@ class LibraryAdapter(Protocol):
|
|||||||
def set_cue_color(self, track_id: str, slot: int, color: str | None) -> TrackCues: ...
|
def set_cue_color(self, track_id: str, slot: int, color: str | None) -> TrackCues: ...
|
||||||
def delete_cue(self, track_id: str, slot: int) -> TrackCues: ...
|
def delete_cue(self, track_id: str, slot: int) -> TrackCues: ...
|
||||||
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues: ...
|
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues: ...
|
||||||
|
# Make a track's prep EXACTLY `cues` — its hot cues, memory cues, grid and
|
||||||
|
# lock — placed as `add_tracks` would place them on a new entry (a taken or
|
||||||
|
# out-of-bank pad moves, else becomes a memory cue). What was there goes
|
||||||
|
# first, grid companions included. A push into a DJ app's library uses it
|
||||||
|
# to bring a track it added earlier up to date with the source.
|
||||||
|
def replace_cues(self, track_id: str, cues: TrackCues) -> TrackCues: ...
|
||||||
|
|
||||||
# ---- commands: memory cues --------------------------------------------
|
# ---- commands: memory cues --------------------------------------------
|
||||||
# Cues on no pad, addressed by `CuePoint.id`. Gated on `cues.memory_cues`.
|
# Cues on no pad, addressed by `CuePoint.id`. Gated on `cues.memory_cues`.
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
"""Is a DJ app running on this computer right now?
|
||||||
|
|
||||||
|
Asked before a push writes into the app's own library, which must not happen
|
||||||
|
under a running app: Traktor writes `collection.nml` back when it QUITS, so a
|
||||||
|
push made while it runs is silently undone, and rekordbox holds `master.db`
|
||||||
|
open. Answered from the process list (`psutil`), by executable name:
|
||||||
|
|
||||||
|
* rekordbox — exactly `rekordbox` (pyrekordbox's own test, minus `.exe`). Its
|
||||||
|
helpers (`rekordboxAgent`, `rb_http_server`, `edb_streamd`) are other names,
|
||||||
|
and `rekordboxAgent` runs whenever rekordbox is installed, so a prefix test
|
||||||
|
would refuse forever.
|
||||||
|
* Traktor — any name starting with `traktor`: the macOS executable is
|
||||||
|
`Traktor Pro 4` (read from the 4.5 bundle, 2026-10-20); the Windows one is
|
||||||
|
not measured, and a prefix covers `Traktor.exe` and `Traktor Pro 4.exe`
|
||||||
|
alike. Konduktor's own processes start with `konduktor`, not `traktor`.
|
||||||
|
|
||||||
|
A process list that cannot be read answers "not running": this is a guard
|
||||||
|
against a mistake, and refusing every push on a locked-down machine would make
|
||||||
|
the feature unusable rather than safe.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _names() -> list[str]:
|
||||||
|
try:
|
||||||
|
import psutil
|
||||||
|
except ImportError: # the server image does not ship it, and never pushes
|
||||||
|
return []
|
||||||
|
out = []
|
||||||
|
try:
|
||||||
|
for proc in psutil.process_iter(["name"]):
|
||||||
|
name = proc.info.get("name")
|
||||||
|
if name:
|
||||||
|
out.append(os.path.splitext(name)[0].lower())
|
||||||
|
except Exception as ex: # noqa: BLE001 — see the module docstring
|
||||||
|
log.warning("could not read the process list: %s", ex)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _matches(platform: str, name: str) -> bool:
|
||||||
|
if platform == "traktor":
|
||||||
|
return name.startswith("traktor")
|
||||||
|
if platform == "rekordbox":
|
||||||
|
return name == "rekordbox"
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def running(platforms: list[str]) -> set[str]:
|
||||||
|
"""Which of `platforms` (platform ids) have their app running now."""
|
||||||
|
names = _names()
|
||||||
|
return {p for p in platforms if any(_matches(p, n) for n in names)}
|
||||||
@@ -119,6 +119,40 @@ class ExportPayload:
|
|||||||
default=lambda message, step=None, of=None: None, repr=False)
|
default=lambda message, step=None, of=None: None, repr=False)
|
||||||
|
|
||||||
|
|
||||||
|
#: The playlist an export's LOOSE tracks (in no exported playlist) land in.
|
||||||
|
OTHER_PLAYLIST = "Other"
|
||||||
|
|
||||||
|
|
||||||
|
def write_playlist_tree(adapter, playlists: list[ExportPlaylist], track_ids: list[str],
|
||||||
|
moved: dict[str, str], root: str | None) -> None:
|
||||||
|
"""Recreate `playlists` under `root` (None = the top level) through the
|
||||||
|
generic playlist commands: each folder chain once, each playlist with the
|
||||||
|
entries `moved` maps its SOURCE ids to, and the tracks of `track_ids` no
|
||||||
|
playlist accounts for in an "Other" playlist. Shared by the Traktor writer
|
||||||
|
and the push into a DJ app's library, which builds the same tree inside
|
||||||
|
the set's own folder."""
|
||||||
|
folders: dict[tuple[str, ...], str | None] = {(): root}
|
||||||
|
|
||||||
|
def folder_for(path: tuple[str, ...]) -> str | None:
|
||||||
|
for depth in range(1, len(path) + 1):
|
||||||
|
branch = path[:depth]
|
||||||
|
if branch not in folders:
|
||||||
|
folders[branch] = adapter.create_folder(branch[-1], folders[branch[:-1]])
|
||||||
|
return folders.get(path, root)
|
||||||
|
|
||||||
|
for playlist in playlists:
|
||||||
|
node_id = adapter.create_playlist(playlist.name, folder_for(tuple(playlist.folders)))
|
||||||
|
entries = [moved[t] for t in playlist.track_ids if t in moved]
|
||||||
|
if entries:
|
||||||
|
adapter.set_playlist_entries(node_id, entries)
|
||||||
|
|
||||||
|
in_playlists = {t for p in playlists for t in p.track_ids}
|
||||||
|
loose = [moved[t] for t in track_ids if t not in in_playlists and t in moved]
|
||||||
|
if loose:
|
||||||
|
node_id = adapter.create_playlist(OTHER_PLAYLIST, root)
|
||||||
|
adapter.set_playlist_entries(node_id, loose)
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class WrittenLibrary:
|
class WrittenLibrary:
|
||||||
"""What an exporter put on disk.
|
"""What an exporter put on disk.
|
||||||
@@ -158,6 +192,14 @@ class LibraryExporter(Protocol):
|
|||||||
#: destination, so this is a warning the UI raises, not a refusal: the other
|
#: destination, so this is a warning the UI raises, not a refusal: the other
|
||||||
#: targets in the same export are still perfectly valid in any folder.
|
#: targets in the same export are still perfectly valid in any folder.
|
||||||
drive_root: bool = False
|
drive_root: bool = False
|
||||||
|
#: Optional, and not a protocol member so a target needs nothing to opt
|
||||||
|
#: out: `prepare_copy(path) -> bool` readies one audio COPY for this
|
||||||
|
#: library, in place, before its size is recorded or a library refers to
|
||||||
|
#: it, returning True if it changed the file. Called once per copy and
|
||||||
|
#: target (the runner records which targets have prepared it, so a kept
|
||||||
|
#: copy is prepared when a target joins the set). Traktor's removes its
|
||||||
|
#: own block from the file (`adapters/traktor/file_block.py`). Never
|
||||||
|
#: called on a file a library references in place.
|
||||||
|
|
||||||
def capabilities(self) -> Capabilities:
|
def capabilities(self) -> Capabilities:
|
||||||
"""What this target can represent — STATIC, with no library to read."""
|
"""What this target can represent — STATIC, with no library to read."""
|
||||||
|
|||||||
@@ -126,6 +126,9 @@ class PlannedTrack:
|
|||||||
level_outcome: str | None = None
|
level_outcome: str | None = None
|
||||||
#: The run needs this source's loudness (it normalises, or writes auto gain).
|
#: The run needs this source's loudness (it normalises, or writes auto gain).
|
||||||
needs_loudness: bool = False
|
needs_loudness: bool = False
|
||||||
|
#: The targets whose `prepare_copy` the copy has been through (sorted
|
||||||
|
#: platforms; recorded in the manifest, missing = none).
|
||||||
|
prepared: tuple[str, ...] = ()
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
@@ -321,9 +324,43 @@ def _record(planned: PlannedTrack, copy: Path) -> dict:
|
|||||||
# The level the copy was written at: a copy kept by a later export must
|
# The level the copy was written at: a copy kept by a later export must
|
||||||
# be at the level THAT export wants (missing = 0, every older manifest).
|
# be at the level THAT export wants (missing = 0, every older manifest).
|
||||||
"gain_db": planned.gain_db,
|
"gain_db": planned.gain_db,
|
||||||
|
# The targets that have prepared the copy (`prepare_copy`): a kept copy
|
||||||
|
# is prepared for any target not listed (missing = none, every older
|
||||||
|
# manifest — which is how existing exports lose Traktor's block).
|
||||||
|
"prepared": list(planned.prepared),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def prepare_copy(path: Path, exporters, done=()) -> tuple[str, ...]:
|
||||||
|
"""Run each target's optional `prepare_copy` on one copy, in place,
|
||||||
|
skipping the targets in `done` (already prepared it). Returns every target
|
||||||
|
that now has — `done` included, so a target leaving the set does not make
|
||||||
|
a later one prepare the copy twice."""
|
||||||
|
ready = set(done)
|
||||||
|
for exporter in exporters:
|
||||||
|
hook = getattr(exporter, "prepare_copy", None)
|
||||||
|
if hook is None or exporter.platform in ready:
|
||||||
|
continue
|
||||||
|
hook(path)
|
||||||
|
ready.add(exporter.platform)
|
||||||
|
return tuple(sorted(ready))
|
||||||
|
|
||||||
|
|
||||||
|
def prepare_kept(path: Path, planned: PlannedTrack, record: dict, exporters) -> dict:
|
||||||
|
"""Prepare a KEPT copy for any target that has not yet (an export made
|
||||||
|
before a target's `prepare_copy` existed, or a target new to the set), and
|
||||||
|
the record that now describes it — the copy's size and mtime as they are
|
||||||
|
after, so a rollback's manifest still matches the file."""
|
||||||
|
done = record.get("prepared")
|
||||||
|
done = tuple(done) if isinstance(done, list) else ()
|
||||||
|
planned.prepared = prepare_copy(path, exporters, done)
|
||||||
|
if planned.prepared == tuple(sorted(done)):
|
||||||
|
return record
|
||||||
|
st = path.stat()
|
||||||
|
return {**record, "copy_size": st.st_size, "copy_mtime_ns": st.st_mtime_ns,
|
||||||
|
"prepared": list(planned.prepared)}
|
||||||
|
|
||||||
|
|
||||||
def _previous_copies(destination: Path) -> dict[str, tuple[Path, dict]]:
|
def _previous_copies(destination: Path) -> dict[str, tuple[Path, dict]]:
|
||||||
"""The last export's copies, by SOURCE path — not by where they sit, since
|
"""The last export's copies, by SOURCE path — not by where they sit, since
|
||||||
adding a track from another folder moves the shared root and with it every
|
adding a track from another folder moves the shared root and with it every
|
||||||
@@ -599,6 +636,10 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle, *,
|
|||||||
if reused:
|
if reused:
|
||||||
handle.progress(message=f"Keeping {len(reused)} unchanged track{'' if len(reused) == 1 else 's'}…")
|
handle.progress(message=f"Keeping {len(reused)} unchanged track{'' if len(reused) == 1 else 's'}…")
|
||||||
_move_kept(destination, reused, kept)
|
_move_kept(destination, reused, kept)
|
||||||
|
for planned in reused:
|
||||||
|
handle.raise_if_cancelled()
|
||||||
|
path = Path(planned.destination)
|
||||||
|
kept[path] = prepare_kept(path, planned, kept[path], exporters)
|
||||||
|
|
||||||
payload_tracks: list[ExportTrack] = []
|
payload_tracks: list[ExportTrack] = []
|
||||||
for planned in items:
|
for planned in items:
|
||||||
@@ -617,30 +658,8 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle, *,
|
|||||||
done += n
|
done += n
|
||||||
handle.progress(done=done)
|
handle.progress(done=done)
|
||||||
|
|
||||||
# The file to READ: on this machine that is the source itself;
|
write_copy(adapter, planned, partial, handle, advance)
|
||||||
# on a library held by a server, a downloaded copy of it.
|
planned.prepared = prepare_copy(partial, exporters)
|
||||||
local = adapter.audio_path(planned.track_id) or planned.source_path
|
|
||||||
levelled = False
|
|
||||||
if planned.gain_db:
|
|
||||||
from .core import level_edit
|
|
||||||
|
|
||||||
handle.progress(message=f"Normalising {planned.title} ({planned.gain_db:+.1f} dB)")
|
|
||||||
try:
|
|
||||||
level_edit.apply(local, partial, planned.gain_db)
|
|
||||||
handle.raise_if_cancelled()
|
|
||||||
# A copy carried to a gig must be the source at the
|
|
||||||
# gain, nothing else: decode both and compare.
|
|
||||||
level_edit.verify(local, partial, planned.gain_db)
|
|
||||||
levelled = True
|
|
||||||
advance(planned.size)
|
|
||||||
except level_edit.LevelEditError as ex:
|
|
||||||
# Only the file says some things (HE-AAC in an .m4a):
|
|
||||||
# such a copy goes as it is, never fails the export.
|
|
||||||
log.warning("copying %s unlevelled: %s", planned.title, ex)
|
|
||||||
partial.unlink(missing_ok=True)
|
|
||||||
planned.gain_db, planned.level_outcome = 0.0, "unsupported"
|
|
||||||
if not levelled:
|
|
||||||
copy_file(local, partial, handle, advance)
|
|
||||||
os.replace(partial, target)
|
os.replace(partial, target)
|
||||||
payload_tracks.append(
|
payload_tracks.append(
|
||||||
ExportTrack(
|
ExportTrack(
|
||||||
@@ -748,6 +767,33 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle, *,
|
|||||||
raise
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
def write_copy(adapter, planned: PlannedTrack, partial: Path, handle: JobHandle, advance) -> None:
|
||||||
|
"""Write one copy of `planned`'s source to `partial`: at its planned gain
|
||||||
|
(decode-verified), else byte for byte. A file that cannot be levelled
|
||||||
|
(HE-AAC in an .m4a — only the file says so) is copied as it is and its
|
||||||
|
plan says so (`gain_db` 0, outcome "unsupported"); never a failure."""
|
||||||
|
# The file to READ: on this machine that is the source itself; on a
|
||||||
|
# library held by a server, a downloaded copy of it.
|
||||||
|
local = adapter.audio_path(planned.track_id) or planned.source_path
|
||||||
|
if planned.gain_db:
|
||||||
|
from .core import level_edit
|
||||||
|
|
||||||
|
handle.progress(message=f"Normalising {planned.title} ({planned.gain_db:+.1f} dB)")
|
||||||
|
try:
|
||||||
|
level_edit.apply(local, partial, planned.gain_db)
|
||||||
|
handle.raise_if_cancelled()
|
||||||
|
# A copy carried to a gig must be the source at the gain, nothing
|
||||||
|
# else: decode both and compare.
|
||||||
|
level_edit.verify(local, partial, planned.gain_db)
|
||||||
|
advance(planned.size)
|
||||||
|
return
|
||||||
|
except level_edit.LevelEditError as ex:
|
||||||
|
log.warning("copying %s unlevelled: %s", planned.title, ex)
|
||||||
|
partial.unlink(missing_ok=True)
|
||||||
|
planned.gain_db, planned.level_outcome = 0.0, "unsupported"
|
||||||
|
copy_file(local, partial, handle, advance)
|
||||||
|
|
||||||
|
|
||||||
def _move_kept(destination: Path, reused: list[PlannedTrack], kept: dict[Path, dict]) -> None:
|
def _move_kept(destination: Path, reused: list[PlannedTrack], kept: dict[Path, dict]) -> None:
|
||||||
"""Rename each kept copy to where this export puts it — instant on one drive.
|
"""Rename each kept copy to where this export puts it — instant on one drive.
|
||||||
|
|
||||||
@@ -794,11 +840,13 @@ def _fingerprint(planned: PlannedTrack) -> str:
|
|||||||
return fingerprint(source, planned.size, planned.mtime_ns)
|
return fingerprint(source, planned.size, planned.mtime_ns)
|
||||||
|
|
||||||
|
|
||||||
def _measure_missing(adapter, built: ExportPlan, handle: JobHandle, *, store, level: Level | None) -> None:
|
def _measure_missing(adapter, built: ExportPlan, handle: JobHandle, *, store, level: Level | None,
|
||||||
|
previous: dict[str, tuple[Path, dict]] | None = None) -> None:
|
||||||
"""Measure the sources the run needs a loudness for and has none, store
|
"""Measure the sources the run needs a loudness for and has none, store
|
||||||
each, then settle their copies' levels and which previous copies can be
|
each, then settle their copies' levels and which previous copies can be
|
||||||
kept. Before anything at the destination changes, so a cancel here
|
kept (`previous`: the copies on record, by source path — by default the
|
||||||
leaves the previous export as it was."""
|
destination's manifest). Before anything at the destination changes, so a
|
||||||
|
cancel here leaves the previous export as it was."""
|
||||||
todo = [t for t in built.exportable if t.needs_loudness and t.loudness is None]
|
todo = [t for t in built.exportable if t.needs_loudness and t.loudness is None]
|
||||||
if not todo or store is None:
|
if not todo or store is None:
|
||||||
return
|
return
|
||||||
@@ -821,7 +869,7 @@ def _measure_missing(adapter, built: ExportPlan, handle: JobHandle, *, store, le
|
|||||||
store.put(fact, values)
|
store.put(fact, values)
|
||||||
if level is not None:
|
if level is not None:
|
||||||
set_level(planned, level)
|
set_level(planned, level)
|
||||||
assign_reuse(built, _previous_copies(Path(built.destination)))
|
assign_reuse(built, previous if previous is not None else _previous_copies(Path(built.destination)))
|
||||||
|
|
||||||
|
|
||||||
def _cover(adapter, track_id: str):
|
def _cover(adapter, track_id: str):
|
||||||
|
|||||||
@@ -44,6 +44,10 @@ from . import paths
|
|||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
#: A set's `kind` and a "computer" set's `mode` (see `ExportSet`).
|
||||||
|
KINDS = ("folder", "computer")
|
||||||
|
MODES = ("merge", "overwrite")
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class ExportSet:
|
class ExportSet:
|
||||||
@@ -56,6 +60,16 @@ class ExportSet:
|
|||||||
|
|
||||||
id: str
|
id: str
|
||||||
name: str
|
name: str
|
||||||
|
#: Where the set goes. "folder": a folder or drive the export writes a
|
||||||
|
#: library into (`destination`). "computer": PUSHED into the DJ apps'
|
||||||
|
#: own libraries on this computer (`local_push.py`) — `targets` names the
|
||||||
|
#: apps, `destination` is unused, and which file each app's library is
|
||||||
|
#: lives in this computer's prefs, not here (a remote library's sets are
|
||||||
|
#: kept on its server, but the paths belong to whichever laptop pushes).
|
||||||
|
kind: str = "folder"
|
||||||
|
#: A "computer" set's push: "merge" adds and updates only what this set
|
||||||
|
#: put there; "overwrite" replaces the whole library with this set.
|
||||||
|
mode: str = "merge"
|
||||||
#: Platform ids of the export TARGETS, e.g. ["traktor", "onelibrary"]. Never
|
#: Platform ids of the export TARGETS, e.g. ["traktor", "onelibrary"]. Never
|
||||||
#: empty; ordered as the user ticked them, which is the order they are written.
|
#: empty; ordered as the user ticked them, which is the order they are written.
|
||||||
targets: list[str] = field(default_factory=lambda: ["traktor"])
|
targets: list[str] = field(default_factory=lambda: ["traktor"])
|
||||||
@@ -194,6 +208,8 @@ def _load(library_id: str) -> dict[str, ExportSet]:
|
|||||||
out[set_id] = ExportSet(
|
out[set_id] = ExportSet(
|
||||||
id=set_id,
|
id=set_id,
|
||||||
name=values.get("name") or "Untitled",
|
name=values.get("name") or "Untitled",
|
||||||
|
kind=values.get("kind") if values.get("kind") in KINDS else "folder",
|
||||||
|
mode=values.get("mode") if values.get("mode") in MODES else "merge",
|
||||||
targets=_targets(values),
|
targets=_targets(values),
|
||||||
destination=values.get("destination") or "",
|
destination=values.get("destination") or "",
|
||||||
playlist_ids=list(values.get("playlist_ids") or []),
|
playlist_ids=list(values.get("playlist_ids") or []),
|
||||||
@@ -251,6 +267,8 @@ def destination_conflict(library_id: str, destination: str, *, ignore: str | Non
|
|||||||
if not target:
|
if not target:
|
||||||
return None
|
return None
|
||||||
for existing in _load(library_id).values():
|
for existing in _load(library_id).values():
|
||||||
|
if existing.kind != "folder":
|
||||||
|
continue # a push has no destination folder to clear
|
||||||
if existing.id != ignore and _normalise(existing.destination) == target:
|
if existing.id != ignore and _normalise(existing.destination) == target:
|
||||||
return existing.name
|
return existing.name
|
||||||
return None
|
return None
|
||||||
@@ -266,12 +284,15 @@ def _normalise(destination: str) -> str:
|
|||||||
# ---- writing -----------------------------------------------------------------
|
# ---- writing -----------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
def create(library_id: str, *, name: str, targets: list[str], destination: str) -> ExportSet:
|
def create(library_id: str, *, name: str, targets: list[str], destination: str,
|
||||||
|
kind: str = "folder", mode: str = "merge") -> ExportSet:
|
||||||
sets = _load(library_id)
|
sets = _load(library_id)
|
||||||
now = time.time()
|
now = time.time()
|
||||||
created = ExportSet(
|
created = ExportSet(
|
||||||
id=uuid.uuid4().hex,
|
id=uuid.uuid4().hex,
|
||||||
name=name.strip() or "Untitled",
|
name=name.strip() or "Untitled",
|
||||||
|
kind=kind if kind in KINDS else "folder",
|
||||||
|
mode=mode if mode in MODES else "merge",
|
||||||
targets=list(dict.fromkeys(targets)),
|
targets=list(dict.fromkeys(targets)),
|
||||||
destination=destination,
|
destination=destination,
|
||||||
created=now,
|
created=now,
|
||||||
@@ -292,6 +313,10 @@ def update(library_id: str, set_id: str, **fields) -> ExportSet | None:
|
|||||||
for key in ("name", "destination"):
|
for key in ("name", "destination"):
|
||||||
if key in fields and fields[key] is not None:
|
if key in fields and fields[key] is not None:
|
||||||
setattr(found, key, fields[key])
|
setattr(found, key, fields[key])
|
||||||
|
if fields.get("kind") in KINDS:
|
||||||
|
found.kind = fields["kind"]
|
||||||
|
if fields.get("mode") in MODES:
|
||||||
|
found.mode = fields["mode"]
|
||||||
if fields.get("targets"):
|
if fields.get("targets"):
|
||||||
found.targets = list(dict.fromkeys(fields["targets"]))
|
found.targets = list(dict.fromkeys(fields["targets"]))
|
||||||
for key in ("lock_grids", "normalise", "auto_gain"):
|
for key in ("lock_grids", "normalise", "auto_gain"):
|
||||||
|
|||||||
@@ -347,6 +347,10 @@ def run(
|
|||||||
# a folder on the server, instead of copied here. Nothing can be left in
|
# a folder on the server, instead of copied here. Nothing can be left in
|
||||||
# place — the server cannot see this computer's files.
|
# place — the server cannot see this computer's files.
|
||||||
uploads = not places and uploads_audio(dest)
|
uploads = not places and uploads_audio(dest)
|
||||||
|
# The library's optional readying of a file copied FOR it (Traktor: its
|
||||||
|
# own block removed from the copy). Only copies made here: never a file
|
||||||
|
# added in place, nor an upload (written on the server).
|
||||||
|
prepare = getattr(dest, "prepare_copied_audio", None)
|
||||||
if uploads and reference and not getattr(source, "on_library_host", False):
|
if uploads and reference and not getattr(source, "on_library_host", False):
|
||||||
raise ValueError("A remote library cannot reference files on this computer")
|
raise ValueError("A remote library cannot reference files on this computer")
|
||||||
if not reference and not places and not uploads:
|
if not reference and not places and not uploads:
|
||||||
@@ -404,6 +408,8 @@ def run(
|
|||||||
handle.progress(message=f"Copying {planned.title}")
|
handle.progress(message=f"Copying {planned.title}")
|
||||||
created.append(target) # registered BEFORE the write, so a cancel
|
created.append(target) # registered BEFORE the write, so a cancel
|
||||||
copy_file(planned.source_path, target, handle, bump) # mid-file is cleaned
|
copy_file(planned.source_path, target, handle, bump) # mid-file is cleaned
|
||||||
|
if prepare is not None:
|
||||||
|
prepare(target)
|
||||||
copied.append((planned, target))
|
copied.append((planned, target))
|
||||||
|
|
||||||
handle.raise_if_cancelled()
|
handle.raise_if_cancelled()
|
||||||
|
|||||||
@@ -0,0 +1,979 @@
|
|||||||
|
"""Pushing an export set into the DJ apps' own libraries on THIS computer.
|
||||||
|
|
||||||
|
An export set of kind "computer" is not written into a folder: its tracks and
|
||||||
|
playlists go straight into the Traktor collection and/or rekordbox library this
|
||||||
|
computer's DJ apps use — the collection a DJ keeps on a server, prepared there,
|
||||||
|
and pushed to the laptop that plays the gig. Decided 2026-10-20
|
||||||
|
(`.claude/discussions/discuss-export-to-local-library-2026-10-20.md`).
|
||||||
|
|
||||||
|
## Two modes, chosen on the set
|
||||||
|
|
||||||
|
**Merge** (the default) adds and updates ONLY what this set put there: the
|
||||||
|
user's own tracks and playlists are never touched, and several sets can push
|
||||||
|
into one library side by side. Each push brings the set's tracks up to date
|
||||||
|
from the source (the source wins: a cue added on the laptop to a pushed track
|
||||||
|
is replaced), rebuilds the set's playlists inside ONE folder named after the
|
||||||
|
set, and removes from the library what left the set — unless another set still
|
||||||
|
holds it, or rekordbox refuses (a track in its History, Sampler, …), in which
|
||||||
|
case it stays, is reported, and the next push tries again.
|
||||||
|
|
||||||
|
**Overwrite** replaces the whole library with this set: the export writers
|
||||||
|
build a fresh one in app-data and it is swapped in, as a user would swap an
|
||||||
|
exported `collection.nml` / `master.db` by hand. Every other set that had been
|
||||||
|
pushed into that library is gone from it afterwards.
|
||||||
|
|
||||||
|
## One shared audio folder
|
||||||
|
|
||||||
|
Every pushed file lives under one folder (default `~/Music/Konduktor`), at its
|
||||||
|
SOURCE path minus the anchor — stable across sets and pushes, so a track in
|
||||||
|
two sets is one file and one entry in the DJ app. (`common_dir_prefix`, which
|
||||||
|
an export mirrors from, moves whenever a set changes; in a shared folder that
|
||||||
|
would leave the same track at two paths.) Being shared, the files can have only
|
||||||
|
one level, so Normalise lives with the folder in the app's settings, not on a
|
||||||
|
set. A file is deleted when no set in any library still holds it.
|
||||||
|
|
||||||
|
## What Konduktor remembers
|
||||||
|
|
||||||
|
A ledger in app-data (`local_push/ledger.json`, Konduktor's own data, never
|
||||||
|
written into a library): per library (by `library_id`) and set, which local
|
||||||
|
track each source track became, the copy it uses, a hash of the prep last
|
||||||
|
pushed (an unchanged track costs nothing on a re-push), and the set's folder;
|
||||||
|
per audio folder, the facts of each copy (the export manifest's record), so an
|
||||||
|
unchanged file is never copied again.
|
||||||
|
|
||||||
|
## Safety
|
||||||
|
|
||||||
|
A push refuses while the DJ app runs (Traktor writes its collection back on
|
||||||
|
quit, undoing the push; rekordbox holds its database open), checked again
|
||||||
|
just before each save. It never writes the library open in Konduktor itself,
|
||||||
|
nor a cloud-synced rekordbox library. Before writing, a Traktor collection
|
||||||
|
gets a version-history baseline and each push is committed to it (restored by
|
||||||
|
opening that collection in Konduktor); a rekordbox library is copied to
|
||||||
|
app-data, the last 10 kept. Audio is copied FIRST and the library written
|
||||||
|
LAST: a cancel before any save leaves every library untouched and removes the
|
||||||
|
files this run placed. A copy that REPLACES a file a library already plays
|
||||||
|
waits under a temporary name until a library has been saved.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import tempfile
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from . import __version__, exports, history, library_id, paths, prefs
|
||||||
|
from .core import apps_running, registry
|
||||||
|
from .core import export as core_export
|
||||||
|
from .core.adapter import AudioChange, NewTrack, Unsupported
|
||||||
|
from .core.analysis_cache import AnalysisCache
|
||||||
|
from .core.export import ExportPayload, ExportPlaylist, ExportTrack, write_playlist_tree
|
||||||
|
from .core.level_plan import shifted
|
||||||
|
from .exporter import (
|
||||||
|
PARTIAL_SUFFIX,
|
||||||
|
ExportPlan,
|
||||||
|
Level,
|
||||||
|
PlannedTrack,
|
||||||
|
_cover,
|
||||||
|
_fingerprint,
|
||||||
|
_folder_paths,
|
||||||
|
_locked,
|
||||||
|
_measure_missing,
|
||||||
|
_record,
|
||||||
|
assign_reuse,
|
||||||
|
prepare_copy,
|
||||||
|
prepare_kept,
|
||||||
|
set_level,
|
||||||
|
write_copy,
|
||||||
|
)
|
||||||
|
from .importer import SPACE_HEADROOM, _existing_files, _key, free_bytes
|
||||||
|
from .jobs import JobHandle
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
#: The DJ apps a set can be pushed into, in the order they are offered.
|
||||||
|
PLATFORMS = ("traktor", "rekordbox")
|
||||||
|
JOB_KIND = "local-push"
|
||||||
|
_BACKUPS_KEPT = 10
|
||||||
|
|
||||||
|
#: Why a library cannot be pushed into. Facts; the UI words them.
|
||||||
|
NOT_FOUND = "not_found"
|
||||||
|
OPEN_IN_KONDUKTOR = "open_in_konduktor"
|
||||||
|
CLOUD_SYNCED = "cloud_synced"
|
||||||
|
UNREADABLE = "unreadable"
|
||||||
|
#: Why a push cannot run.
|
||||||
|
BLOCKED_NO_TARGET = "no_target"
|
||||||
|
#: Every library the set names is missing on THIS computer.
|
||||||
|
BLOCKED_NONE_HERE = "no_library_here"
|
||||||
|
BLOCKED_EMPTY = "nothing_to_push"
|
||||||
|
BLOCKED_UNAVAILABLE = "target_unavailable"
|
||||||
|
BLOCKED_RUNNING = "app_running"
|
||||||
|
|
||||||
|
_LOCK = threading.RLock()
|
||||||
|
|
||||||
|
|
||||||
|
class PushRefused(Exception):
|
||||||
|
"""A push that must not go ahead (a DJ app started, a library became
|
||||||
|
unwritable). The message is for the user."""
|
||||||
|
|
||||||
|
|
||||||
|
# ---- where things are ---------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _local_dir() -> Path:
|
||||||
|
return paths.app_data_dir() / "local_push"
|
||||||
|
|
||||||
|
|
||||||
|
def audio_root() -> Path:
|
||||||
|
"""The shared folder pushed audio lives in: the setting, else the user's
|
||||||
|
Music folder (platformdirs — hardcoding `~/Music` is wrong somewhere on
|
||||||
|
every OS) + `Konduktor`."""
|
||||||
|
raw = prefs.load_prefs().get("localAudioRoot")
|
||||||
|
if isinstance(raw, str) and raw.strip():
|
||||||
|
return Path(raw).expanduser()
|
||||||
|
import platformdirs
|
||||||
|
|
||||||
|
return Path(platformdirs.user_music_dir()) / "Konduktor"
|
||||||
|
|
||||||
|
|
||||||
|
def level() -> Level | None:
|
||||||
|
"""The shared folder's Normalise level, or None when it is off. The
|
||||||
|
measure / target / ceiling default to Normalize's app settings."""
|
||||||
|
p = prefs.load_prefs()
|
||||||
|
if not p.get("localNormalise"):
|
||||||
|
return None
|
||||||
|
raw = p.get("localLevel") if isinstance(p.get("localLevel"), dict) else {}
|
||||||
|
try:
|
||||||
|
measure = raw.get("measure", p.get("levelMeasure", "lufs"))
|
||||||
|
return Level(measure=measure if measure in ("lufs", "rms") else "lufs",
|
||||||
|
target=float(raw.get("target", p.get("levelTarget", -9.0))),
|
||||||
|
ceiling=float(raw.get("ceiling", p.get("levelCeiling", -1.0))))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return Level()
|
||||||
|
|
||||||
|
|
||||||
|
def _override(platform: str) -> Path | None:
|
||||||
|
raw = prefs.load_prefs().get("localLibraries")
|
||||||
|
value = raw.get(platform) if isinstance(raw, dict) else None
|
||||||
|
return Path(value).expanduser() if isinstance(value, str) and value.strip() else None
|
||||||
|
|
||||||
|
|
||||||
|
def library_path(platform: str) -> tuple[Path | None, bool]:
|
||||||
|
"""(the library a push into `platform` writes, whether it was DETECTED).
|
||||||
|
The setting wins; else the platform's own detection, best first (Traktor:
|
||||||
|
the newest `Traktor x.y` folder)."""
|
||||||
|
chosen = _override(platform)
|
||||||
|
if chosen is not None:
|
||||||
|
return chosen, False
|
||||||
|
for found in registry.detect_for(platform):
|
||||||
|
raw = found.get("path") if isinstance(found, dict) else getattr(found, "path", None)
|
||||||
|
if raw and Path(raw).is_file():
|
||||||
|
return Path(raw), True
|
||||||
|
return None, True
|
||||||
|
|
||||||
|
|
||||||
|
def _same(a: Path | None, b: Path | None) -> bool:
|
||||||
|
if a is None or b is None:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
return Path(a).resolve() == Path(b).resolve()
|
||||||
|
except OSError:
|
||||||
|
return str(a) == str(b)
|
||||||
|
|
||||||
|
|
||||||
|
# Opening a library to ask whether it can be written costs a parse; the answer
|
||||||
|
# only changes with the file, so it is kept per path + mtime. Only a platform
|
||||||
|
# whose library can be read-only is opened for it: rekordbox (cloud sync). A
|
||||||
|
# Traktor collection is always writable, and parsing 8,000 entries to hear so
|
||||||
|
# would hold up the dialog that asks.
|
||||||
|
_MAY_BE_READ_ONLY = {"rekordbox"}
|
||||||
|
_WRITABLE: dict[tuple[str, int], str | None] = {}
|
||||||
|
|
||||||
|
|
||||||
|
def _unwritable(path: Path, platform: str) -> str | None:
|
||||||
|
"""Why `platform`'s library at `path` cannot be written, or None."""
|
||||||
|
try:
|
||||||
|
stamp = (str(path), path.stat().st_mtime_ns)
|
||||||
|
except OSError:
|
||||||
|
return NOT_FOUND
|
||||||
|
if stamp in _WRITABLE:
|
||||||
|
return _WRITABLE[stamp]
|
||||||
|
reason: str | None
|
||||||
|
adapter = None
|
||||||
|
try:
|
||||||
|
driver = registry.driver_for(path) # the cheap probe: is it that format at all?
|
||||||
|
if driver.platform != platform:
|
||||||
|
reason = UNREADABLE # e.g. a master.db chosen as the Traktor collection
|
||||||
|
elif driver.platform not in _MAY_BE_READ_ONLY:
|
||||||
|
reason = None
|
||||||
|
else:
|
||||||
|
adapter = driver.open(path)
|
||||||
|
caps = adapter.capabilities()
|
||||||
|
if caps.writable:
|
||||||
|
reason = None
|
||||||
|
else:
|
||||||
|
reason = CLOUD_SYNCED if caps.readonly_cause == "cloud_synced" else UNREADABLE
|
||||||
|
except Exception as ex: # noqa: BLE001 — anything that will not open is not a target
|
||||||
|
log.warning("cannot open %s to push into: %s", path, ex)
|
||||||
|
reason = UNREADABLE
|
||||||
|
finally:
|
||||||
|
_close(adapter)
|
||||||
|
_WRITABLE[stamp] = reason
|
||||||
|
return reason
|
||||||
|
|
||||||
|
|
||||||
|
def _close(adapter) -> None:
|
||||||
|
close = getattr(adapter, "close", None)
|
||||||
|
if close is not None:
|
||||||
|
try:
|
||||||
|
close()
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
log.warning("closing a pushed-into library failed", exc_info=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _display_name(platform: str) -> str:
|
||||||
|
try:
|
||||||
|
return registry.driver_by_platform(platform).display_name
|
||||||
|
except registry.LibraryNotSupported:
|
||||||
|
return platform
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class LocalLibrary:
|
||||||
|
"""One DJ app's library on this computer, as a push target."""
|
||||||
|
|
||||||
|
platform: str
|
||||||
|
name: str
|
||||||
|
path: str | None
|
||||||
|
detected: bool
|
||||||
|
#: Why it cannot be pushed into (`NOT_FOUND`, `OPEN_IN_KONDUKTOR`,
|
||||||
|
#: `CLOUD_SYNCED`, `UNREADABLE`), or None.
|
||||||
|
blocked: str | None = None
|
||||||
|
running: bool = False
|
||||||
|
|
||||||
|
def as_dict(self) -> dict:
|
||||||
|
return dict(self.__dict__)
|
||||||
|
|
||||||
|
|
||||||
|
def local_libraries(open_path: Path | None, platforms=PLATFORMS) -> list[LocalLibrary]:
|
||||||
|
"""The push targets this computer has, each with why it cannot be used."""
|
||||||
|
running = apps_running.running(list(platforms))
|
||||||
|
out = []
|
||||||
|
for platform in platforms:
|
||||||
|
path, detected = library_path(platform)
|
||||||
|
lib = LocalLibrary(platform=platform, name=_display_name(platform),
|
||||||
|
path=str(path) if path else None, detected=detected,
|
||||||
|
running=platform in running)
|
||||||
|
if path is None or not path.is_file():
|
||||||
|
lib.blocked = NOT_FOUND
|
||||||
|
elif _same(path, open_path):
|
||||||
|
# Its edits are the open session's; a push would race them.
|
||||||
|
lib.blocked = OPEN_IN_KONDUKTOR
|
||||||
|
else:
|
||||||
|
lib.blocked = _unwritable(path, platform)
|
||||||
|
out.append(lib)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# ---- the ledger ----------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _ledger_path() -> Path:
|
||||||
|
return _local_dir() / "ledger.json"
|
||||||
|
|
||||||
|
|
||||||
|
def _read_ledger() -> dict:
|
||||||
|
data = paths.read_json(_ledger_path(), {})
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
data = {}
|
||||||
|
data.setdefault("libraries", {})
|
||||||
|
data.setdefault("audio", {})
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def _write_ledger(doc: dict) -> None:
|
||||||
|
paths.write_json(_ledger_path(), doc)
|
||||||
|
|
||||||
|
|
||||||
|
def _rel_for(source: Path) -> str:
|
||||||
|
"""Where `source` sits under the shared folder: its whole path minus the
|
||||||
|
anchor (`/Volumes/Music/a.mp3` -> `Volumes/Music/a.mp3`, `D:\\x.mp3` ->
|
||||||
|
`D/x.mp3`). Never collides, and never moves when a set changes."""
|
||||||
|
text = str(source).replace("\\", "/")
|
||||||
|
if len(text) >= 2 and text[1] == ":":
|
||||||
|
text = text[0] + text[2:]
|
||||||
|
return text.lstrip("/")
|
||||||
|
|
||||||
|
|
||||||
|
def _owned(doc: dict) -> set[str]:
|
||||||
|
"""Every copy (by `rel`) some set in some library still holds."""
|
||||||
|
out = set()
|
||||||
|
for lib in doc["libraries"].values():
|
||||||
|
for entry in (lib.get("sets") or {}).values():
|
||||||
|
for rec in (entry.get("tracks") or {}).values():
|
||||||
|
if rec.get("rel"):
|
||||||
|
out.add(rec["rel"])
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# ---- planning -------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class TargetPlan:
|
||||||
|
platform: str
|
||||||
|
name: str
|
||||||
|
path: str | None
|
||||||
|
blocked: str | None = None
|
||||||
|
running: bool = False
|
||||||
|
#: Tracks this set has not pushed into this library before.
|
||||||
|
add: int = 0
|
||||||
|
#: Tracks it has: kept as they are, or brought up to date where changed.
|
||||||
|
already: int = 0
|
||||||
|
#: Tracks that left the set since the last push (removed from the library
|
||||||
|
#: unless another set holds them, or rekordbox refuses).
|
||||||
|
remove: int = 0
|
||||||
|
#: Overwrite: the other sets pushed into this library, which it removes.
|
||||||
|
wipes_sets: list[str] = field(default_factory=list)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def skipped(self) -> bool:
|
||||||
|
"""Not on this computer, so passed over rather than blocking: a set's
|
||||||
|
targets are shared by every computer that opens the library (a
|
||||||
|
remote's sets live on its server), and one with only Traktor must
|
||||||
|
still push a Traktor + rekordbox set."""
|
||||||
|
return self.blocked == NOT_FOUND
|
||||||
|
|
||||||
|
def as_dict(self) -> dict:
|
||||||
|
return {**self.__dict__, "skipped": self.skipped}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class PushPlan:
|
||||||
|
#: The audio, planned as an export into the shared folder: one
|
||||||
|
#: `PlannedTrack` per track, `destination` = its copy there, `reuse` set
|
||||||
|
#: where the copy on record is still good.
|
||||||
|
audio: ExportPlan
|
||||||
|
playlists: list[ExportPlaylist]
|
||||||
|
targets: list[TargetPlan]
|
||||||
|
mode: str = "merge"
|
||||||
|
blocked: str | None = None
|
||||||
|
#: The copies on record before this push, by source path (for `reuse`).
|
||||||
|
previous: dict = field(default_factory=dict)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def tracks(self) -> list[PlannedTrack]:
|
||||||
|
return self.audio.tracks
|
||||||
|
|
||||||
|
@property
|
||||||
|
def active(self) -> list[TargetPlan]:
|
||||||
|
"""The targets this push writes: every one found on this computer."""
|
||||||
|
return [t for t in self.targets if not t.skipped]
|
||||||
|
|
||||||
|
def as_dict(self) -> dict:
|
||||||
|
audio = self.audio
|
||||||
|
free = free_bytes(audio.destination) if audio.destination else None
|
||||||
|
need = audio.total_bytes
|
||||||
|
counts: dict[str, int] = {}
|
||||||
|
for t in audio.exportable:
|
||||||
|
if t.level_outcome:
|
||||||
|
counts[t.level_outcome] = counts.get(t.level_outcome, 0) + 1
|
||||||
|
return {
|
||||||
|
"mode": self.mode,
|
||||||
|
"tracks": len(audio.tracks),
|
||||||
|
"pushable": len(audio.exportable),
|
||||||
|
"unchanged": audio.unchanged,
|
||||||
|
"missing": [t.title for t in audio.tracks if t.missing],
|
||||||
|
"playlists": [p.name for p in self.playlists],
|
||||||
|
"total_bytes": need,
|
||||||
|
"audio_root": str(audio.destination),
|
||||||
|
"free_bytes": free,
|
||||||
|
"enough_space": None if free is None else free >= need + SPACE_HEADROOM,
|
||||||
|
"normalised": sum(1 for t in audio.exportable if t.gain_db),
|
||||||
|
"level_counts": counts,
|
||||||
|
"to_measure": sum(1 for t in audio.exportable if t.needs_loudness and t.loudness is None),
|
||||||
|
"targets": [t.as_dict() for t in self.targets],
|
||||||
|
"blocked": self.blocked,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def plan(adapter, export_set, *, store=None, level: Level | None = None,
|
||||||
|
auto_gain: bool = False, open_path: Path | None = None) -> PushPlan:
|
||||||
|
"""What a push of `export_set` would do now. Reads only — neither the
|
||||||
|
target libraries (their state is the ledger's, checked again by the run)
|
||||||
|
nor any audio file."""
|
||||||
|
root = audio_root()
|
||||||
|
built = ExportPlan(destination=root)
|
||||||
|
doc = _read_ledger()
|
||||||
|
records = doc["audio"].get(str(root)) or {}
|
||||||
|
previous = {r["source"]: (root / rel, r) for rel, r in records.items()
|
||||||
|
if isinstance(r, dict) and isinstance(r.get("source"), str)}
|
||||||
|
|
||||||
|
resolved = exports.resolve(adapter, export_set)
|
||||||
|
tracks = [t for t in (adapter.track(i) for i in resolved.track_ids) if t is not None]
|
||||||
|
facts = adapter.audio_facts([t.id for t in tracks])
|
||||||
|
wants_loudness = store is not None and (level is not None or auto_gain)
|
||||||
|
entries = store.get([f.key for f in facts.values() if f is not None]) if wants_loudness else {}
|
||||||
|
for track in tracks:
|
||||||
|
fact = facts.get(track.id)
|
||||||
|
source = Path(fact.key) if fact is not None else None
|
||||||
|
planned = PlannedTrack(
|
||||||
|
track_id=track.id,
|
||||||
|
title=track.title or (source.name if source else track.id),
|
||||||
|
source_path=source,
|
||||||
|
destination=(root / _rel_for(source)) if source else None,
|
||||||
|
size=fact.size if fact else 0,
|
||||||
|
mtime_ns=fact.mtime_ns if fact else 0,
|
||||||
|
missing=fact is None,
|
||||||
|
needs_loudness=fact is not None and wants_loudness,
|
||||||
|
)
|
||||||
|
if planned.needs_loudness:
|
||||||
|
entry = entries.get(fact.key)
|
||||||
|
planned.loudness = entry.values if entry is not None and not entry.stale(fact) else None
|
||||||
|
if fact is not None and level is not None:
|
||||||
|
set_level(planned, level)
|
||||||
|
built.tracks.append(planned)
|
||||||
|
assign_reuse(built, previous)
|
||||||
|
|
||||||
|
folders = _folder_paths(adapter)
|
||||||
|
playlists = [ExportPlaylist(name=p.name, track_ids=list(p.track_ids), folders=folders.get(p.id, []))
|
||||||
|
for p in resolved.playlists if not p.missing and p.track_ids]
|
||||||
|
|
||||||
|
pushable = {t.track_id for t in built.exportable}
|
||||||
|
targets = []
|
||||||
|
known = {lib.platform: lib for lib in local_libraries(open_path, [
|
||||||
|
t for t in export_set.targets if t in PLATFORMS])}
|
||||||
|
for platform in export_set.targets:
|
||||||
|
lib = known.get(platform)
|
||||||
|
if lib is None:
|
||||||
|
targets.append(TargetPlan(platform=platform, name=_display_name(platform), path=None,
|
||||||
|
blocked=NOT_FOUND))
|
||||||
|
continue
|
||||||
|
target = TargetPlan(platform=platform, name=lib.name, path=lib.path,
|
||||||
|
blocked=lib.blocked, running=lib.running)
|
||||||
|
lid = library_id.read_sidecar(Path(lib.path)) if lib.path else None
|
||||||
|
sets = (doc["libraries"].get(lid) or {}).get("sets") or {} if lid else {}
|
||||||
|
mine = (sets.get(export_set.id) or {}).get("tracks") or {}
|
||||||
|
target.add = sum(1 for t in pushable if t not in mine)
|
||||||
|
target.already = sum(1 for t in pushable if t in mine)
|
||||||
|
target.remove = sum(1 for t in mine if t not in pushable)
|
||||||
|
if export_set.mode == "overwrite":
|
||||||
|
target.wipes_sets = sorted(s.get("name") or "Untitled"
|
||||||
|
for sid, s in sets.items() if sid != export_set.id)
|
||||||
|
targets.append(target)
|
||||||
|
|
||||||
|
out = PushPlan(audio=built, playlists=playlists, targets=targets, mode=export_set.mode,
|
||||||
|
previous=previous)
|
||||||
|
if not targets:
|
||||||
|
out.blocked = BLOCKED_NO_TARGET
|
||||||
|
elif not out.active:
|
||||||
|
out.blocked = BLOCKED_NONE_HERE
|
||||||
|
elif not built.exportable:
|
||||||
|
out.blocked = BLOCKED_EMPTY
|
||||||
|
elif any(t.blocked for t in out.active):
|
||||||
|
out.blocked = BLOCKED_UNAVAILABLE
|
||||||
|
elif any(t.running for t in out.active):
|
||||||
|
out.blocked = BLOCKED_RUNNING
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# ---- running --------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _partial(target: Path) -> Path:
|
||||||
|
return target.with_name(target.name + PARTIAL_SUFFIX)
|
||||||
|
|
||||||
|
|
||||||
|
def _jsonable(value):
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
dump = getattr(value, "model_dump", None)
|
||||||
|
if dump is not None:
|
||||||
|
return dump()
|
||||||
|
if hasattr(value, "__dict__"):
|
||||||
|
return dict(value.__dict__)
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
_PREP_FIELDS = ("title", "artist", "album", "genre", "label", "remixer", "producer", "mix",
|
||||||
|
"comment", "comment2", "release_date", "rating", "key_wheel", "key_mode", "color")
|
||||||
|
_METADATA_FIELDS = ("title", "artist", "album", "genre", "label", "remixer", "producer", "mix",
|
||||||
|
"comment", "comment2", "release_date", "rating")
|
||||||
|
|
||||||
|
|
||||||
|
def _prep_hash(item: ExportTrack) -> str:
|
||||||
|
"""What a re-push compares: the track's own fields, its cues and grid
|
||||||
|
(lock included) and the auto gain it would get — not the file, whose
|
||||||
|
copy is checked by its own facts."""
|
||||||
|
blob = {
|
||||||
|
"track": {k: getattr(item.track, k, None) for k in _PREP_FIELDS},
|
||||||
|
"cues": _jsonable(item.cues),
|
||||||
|
"loudness": _jsonable(item.loudness),
|
||||||
|
"gain_db": round(item.gain_db, 4),
|
||||||
|
}
|
||||||
|
return hashlib.sha256(json.dumps(blob, sort_keys=True, default=str).encode()).hexdigest()[:24]
|
||||||
|
|
||||||
|
|
||||||
|
def _checkpoint(handle: JobHandle):
|
||||||
|
def checkpoint(message: str, step: int | None = None, of: int | None = None) -> None:
|
||||||
|
handle.raise_if_cancelled()
|
||||||
|
if step is not None and of:
|
||||||
|
handle.progress(done=step - 1, total=of, unit="tracks", message=message)
|
||||||
|
else:
|
||||||
|
handle.progress(message=message)
|
||||||
|
return checkpoint
|
||||||
|
|
||||||
|
|
||||||
|
def _refuse_if_running(platform: str) -> None:
|
||||||
|
if apps_running.running([platform]):
|
||||||
|
raise PushRefused(f"{_display_name(platform)} is running — quit it, then push again")
|
||||||
|
|
||||||
|
|
||||||
|
def run(adapter, export_set, built: PushPlan, handle: JobHandle, *, lock_grids: bool = True,
|
||||||
|
store=None, level: Level | None = None, auto_gain: bool = False) -> dict:
|
||||||
|
"""Copy what changed into the shared folder, then push into each target.
|
||||||
|
See the module docstring for the order and what a cancel leaves."""
|
||||||
|
if built.blocked:
|
||||||
|
raise PushRefused(f"This push cannot run: {built.blocked}")
|
||||||
|
for target in built.active:
|
||||||
|
_refuse_if_running(target.platform)
|
||||||
|
|
||||||
|
root = Path(built.audio.destination)
|
||||||
|
created: list[Path] = [] # new files this run placed (rolled back)
|
||||||
|
waiting: list[tuple[Path, Path]] = [] # (partial, file) replacing a file in use
|
||||||
|
written: set[str] = set() # source ids whose copy this run wrote
|
||||||
|
saved = False
|
||||||
|
done = 0
|
||||||
|
try:
|
||||||
|
_measure_missing(adapter, built.audio, handle, store=store, level=level,
|
||||||
|
previous=built.previous)
|
||||||
|
items = built.audio.exportable
|
||||||
|
# The targets' writers, for `prepare_copy` (Traktor's removes its own
|
||||||
|
# block from the file, which it would restore over the pushed grid).
|
||||||
|
writers = [w for w in (core_export.for_platform(t.platform) for t in built.active) if w]
|
||||||
|
handle.progress(done=0, total=built.audio.total_bytes, unit="bytes", message="Copying…")
|
||||||
|
for planned in items:
|
||||||
|
handle.raise_if_cancelled()
|
||||||
|
if planned.reuse is not None:
|
||||||
|
# Kept: prepared for any target that has not yet. In place —
|
||||||
|
# no target app is running (refused above), and a library
|
||||||
|
# already holding the file re-reads its tags on its own.
|
||||||
|
old = built.previous.get(str(planned.source_path))
|
||||||
|
prepare_kept(planned.reuse, planned, old[1] if old else {}, writers)
|
||||||
|
continue
|
||||||
|
target = Path(planned.destination)
|
||||||
|
target.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
partial = _partial(target)
|
||||||
|
created.append(partial)
|
||||||
|
|
||||||
|
def advance(n: int) -> None:
|
||||||
|
nonlocal done
|
||||||
|
done += n
|
||||||
|
handle.progress(done=done)
|
||||||
|
|
||||||
|
handle.progress(message=f"Copying {planned.title}")
|
||||||
|
write_copy(adapter, planned, partial, handle, advance)
|
||||||
|
planned.prepared = prepare_copy(partial, writers)
|
||||||
|
written.add(planned.track_id)
|
||||||
|
if target.exists():
|
||||||
|
# A library may be playing this file: it is replaced only
|
||||||
|
# once a library has been saved to match.
|
||||||
|
waiting.append((partial, target))
|
||||||
|
else:
|
||||||
|
os.replace(partial, target)
|
||||||
|
created.remove(partial)
|
||||||
|
created.append(target)
|
||||||
|
|
||||||
|
cache = AnalysisCache(_local_dir() / "analysis")
|
||||||
|
payload_tracks = []
|
||||||
|
for planned in items:
|
||||||
|
handle.raise_if_cancelled()
|
||||||
|
payload_tracks.append(ExportTrack(
|
||||||
|
track=adapter.track(planned.track_id),
|
||||||
|
destination=Path(planned.destination),
|
||||||
|
cues=_locked(adapter.track_cues(planned.track_id), lock_grids),
|
||||||
|
art=_cover(adapter, planned.track_id),
|
||||||
|
fingerprint=_fingerprint(planned),
|
||||||
|
analysis_cache=cache,
|
||||||
|
loudness=(shifted(planned.loudness, planned.gain_db)
|
||||||
|
if auto_gain and planned.loudness is not None else None),
|
||||||
|
gain_db=planned.gain_db,
|
||||||
|
))
|
||||||
|
payload = ExportPayload(name=export_set.name, root_folder=True, tracks=payload_tracks,
|
||||||
|
playlists=built.playlists, checkpoint=_checkpoint(handle))
|
||||||
|
|
||||||
|
results = []
|
||||||
|
for target in built.active:
|
||||||
|
handle.raise_if_cancelled()
|
||||||
|
handle.progress(done=0, total=0, unit="tracks",
|
||||||
|
message=f"Pushing into {target.name}…")
|
||||||
|
push = _overwrite if export_set.mode == "overwrite" else _merge
|
||||||
|
results.append(push(target, export_set, payload, handle,
|
||||||
|
planned={t.track_id: t for t in items}, written=written,
|
||||||
|
waiting=waiting, previous=built.previous))
|
||||||
|
saved = True
|
||||||
|
# The library now plays the new files: the waiting ones go in.
|
||||||
|
for partial, final in waiting:
|
||||||
|
os.replace(partial, final)
|
||||||
|
waiting.clear()
|
||||||
|
|
||||||
|
with _LOCK:
|
||||||
|
doc = _read_ledger()
|
||||||
|
records = doc["audio"].setdefault(str(root), {})
|
||||||
|
for planned in items:
|
||||||
|
records[_rel_for(planned.source_path)] = _record(planned, Path(planned.destination))
|
||||||
|
removed = _prune_audio(doc, root)
|
||||||
|
_write_ledger(doc)
|
||||||
|
return {
|
||||||
|
"tracks": len(items),
|
||||||
|
"copied": len(written),
|
||||||
|
"unchanged": built.audio.unchanged,
|
||||||
|
"normalised": sum(1 for t in items if t.gain_db),
|
||||||
|
"skipped": len(built.audio.tracks) - len(items),
|
||||||
|
"deleted_files": removed,
|
||||||
|
"audio_root": str(root),
|
||||||
|
"targets": results,
|
||||||
|
"skipped_targets": [t.name for t in built.targets if t.skipped],
|
||||||
|
}
|
||||||
|
except BaseException:
|
||||||
|
for partial, _final in waiting:
|
||||||
|
partial.unlink(missing_ok=True)
|
||||||
|
if not saved:
|
||||||
|
# No library refers to anything this run placed.
|
||||||
|
for path in created:
|
||||||
|
path.unlink(missing_ok=True)
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
def _prune_audio(doc: dict, root: Path) -> int:
|
||||||
|
"""Delete the shared folder's copies no set holds any more."""
|
||||||
|
records = doc["audio"].get(str(root)) or {}
|
||||||
|
owned = _owned(doc)
|
||||||
|
gone = [rel for rel in records if rel not in owned]
|
||||||
|
for rel in gone:
|
||||||
|
path = root / rel
|
||||||
|
try:
|
||||||
|
path.unlink(missing_ok=True)
|
||||||
|
except OSError as ex:
|
||||||
|
log.warning("could not delete %s: %s", path, ex)
|
||||||
|
continue
|
||||||
|
records.pop(rel, None)
|
||||||
|
_prune_empty(path.parent, root)
|
||||||
|
return len(gone)
|
||||||
|
|
||||||
|
|
||||||
|
def _prune_empty(folder: Path, root: Path) -> None:
|
||||||
|
while folder != root and root in folder.parents:
|
||||||
|
try:
|
||||||
|
folder.rmdir()
|
||||||
|
except OSError:
|
||||||
|
return
|
||||||
|
folder = folder.parent
|
||||||
|
|
||||||
|
|
||||||
|
# ---- one library: merge ------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _backup(platform: str, path: Path) -> None:
|
||||||
|
"""Before a push writes `path`. Traktor: a version-history baseline (the
|
||||||
|
push itself is committed after). rekordbox, which Konduktor does not
|
||||||
|
version (a library is more than one file): the database, its WAL and the
|
||||||
|
playlist XML copied to app-data, the last 10 kept."""
|
||||||
|
if platform == "traktor":
|
||||||
|
history.ensure_baseline(path)
|
||||||
|
return
|
||||||
|
base = _local_dir() / "backups" / platform
|
||||||
|
dest = base / time.strftime("%Y%m%d-%H%M%S")
|
||||||
|
n = 1
|
||||||
|
while dest.exists():
|
||||||
|
n += 1
|
||||||
|
dest = base / f"{time.strftime('%Y%m%d-%H%M%S')}-{n}"
|
||||||
|
dest.mkdir(parents=True)
|
||||||
|
for p in (path, path.with_name(path.name + "-wal"), path.with_name("masterPlaylists6.xml")):
|
||||||
|
if p.is_file():
|
||||||
|
shutil.copy2(p, dest / p.name)
|
||||||
|
for old in sorted(d for d in base.iterdir() if d.is_dir())[:-_BACKUPS_KEPT]:
|
||||||
|
shutil.rmtree(old, ignore_errors=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _commit(platform: str, path: Path, data: bytes | None, summary: str) -> None:
|
||||||
|
if platform == "traktor" and data is not None:
|
||||||
|
history.commit(path, data, summary, __version__)
|
||||||
|
|
||||||
|
|
||||||
|
def _folder_name(adapter, wanted: str, own: str | None) -> str:
|
||||||
|
"""The set's folder name: `wanted`, unless a top-level node the user owns
|
||||||
|
already has it — Traktor's `create_folder` would hand back THEIR folder,
|
||||||
|
and the next push would delete it."""
|
||||||
|
taken = {n.name for n in adapter.playlist_tree() if n.id != own}
|
||||||
|
name, n = wanted, 1
|
||||||
|
while name in taken:
|
||||||
|
name = f"{wanted} (Konduktor)" if n == 1 else f"{wanted} (Konduktor {n})"
|
||||||
|
n += 1
|
||||||
|
return name
|
||||||
|
|
||||||
|
|
||||||
|
def _tree_hash(name: str, payload: ExportPayload, moved: dict[str, str]) -> str:
|
||||||
|
blob = [name, [[p.name, p.folders, [moved.get(t) for t in p.track_ids]] for p in payload.playlists],
|
||||||
|
[moved.get(t.source_id) for t in payload.tracks]]
|
||||||
|
return hashlib.sha256(json.dumps(blob).encode()).hexdigest()[:24]
|
||||||
|
|
||||||
|
|
||||||
|
def _node_ids(nodes) -> set[str]:
|
||||||
|
out = set()
|
||||||
|
for n in nodes or []:
|
||||||
|
out.add(n.id)
|
||||||
|
out |= _node_ids(getattr(n, "children", None))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _update(target, local_id: str, item: ExportTrack, *, audio_change: AudioChange | None) -> None:
|
||||||
|
"""Bring a track this set pushed earlier up to date with the source."""
|
||||||
|
caps = target.capabilities().tracks
|
||||||
|
now = target.track(local_id)
|
||||||
|
fields = {}
|
||||||
|
for k in _METADATA_FIELDS:
|
||||||
|
if k in caps.editable_fields:
|
||||||
|
value = getattr(item.track, k, None)
|
||||||
|
if (getattr(now, k, None) or None) != (value or None):
|
||||||
|
fields[k] = value if value is not None else ("" if k != "rating" else 0)
|
||||||
|
if fields:
|
||||||
|
target.set_track_metadata(local_id, fields)
|
||||||
|
if caps.key_writable and item.track.key_wheel and item.track.key_mode and (
|
||||||
|
(now.key_wheel, now.key_mode) != (item.track.key_wheel, item.track.key_mode)):
|
||||||
|
target.set_key(local_id, item.track.key_wheel, item.track.key_mode)
|
||||||
|
if caps.colors and now.color != item.track.color:
|
||||||
|
target.set_track_color(local_id, item.track.color)
|
||||||
|
if audio_change is not None and caps.normalizable:
|
||||||
|
target.audio_changed(local_id, audio_change)
|
||||||
|
if item.loudness is not None and caps.auto_gain:
|
||||||
|
target.set_auto_gain(local_id, item.loudness)
|
||||||
|
if item.cues is not None:
|
||||||
|
target.replace_cues(local_id, item.cues)
|
||||||
|
|
||||||
|
|
||||||
|
def _audio_change(target, item: ExportTrack, planned: PlannedTrack, previous: dict,
|
||||||
|
waiting: list) -> AudioChange:
|
||||||
|
"""What a copy written this run means to a library already playing it:
|
||||||
|
its size, the level change, and — for a platform that draws waveforms
|
||||||
|
from the file (rekordbox) — the new audio measured at its time base."""
|
||||||
|
final = item.destination
|
||||||
|
path = next((p for p, f in waiting if f == final), final)
|
||||||
|
old = previous.get(str(planned.source_path))
|
||||||
|
before = float((old[1] if old else {}).get("gain_db") or 0.0)
|
||||||
|
measured = None
|
||||||
|
lead = getattr(target, "analysis_lead", None)
|
||||||
|
if lead is not None:
|
||||||
|
from .core import waveform
|
||||||
|
|
||||||
|
try:
|
||||||
|
measured = waveform.analyse(path, lead=lead(final))
|
||||||
|
except Exception as ex: # noqa: BLE001 — the old waveform stays drawn
|
||||||
|
log.warning("could not measure %s for its waveform: %s", path, ex)
|
||||||
|
return AudioChange(gain_db=item.gain_db - before, size=path.stat().st_size, measured=measured)
|
||||||
|
|
||||||
|
|
||||||
|
def _merge(tp: TargetPlan, export_set, payload: ExportPayload, handle: JobHandle, *,
|
||||||
|
planned: dict[str, PlannedTrack], written: set[str], waiting: list,
|
||||||
|
previous: dict) -> dict:
|
||||||
|
path = Path(tp.path)
|
||||||
|
lid = library_id.for_path(path, platform=tp.platform, label=tp.name)
|
||||||
|
with _LOCK:
|
||||||
|
doc = _read_ledger()
|
||||||
|
lib = doc["libraries"].get(lid) or {}
|
||||||
|
sets = lib.get("sets") or {}
|
||||||
|
mine = sets.get(export_set.id) or {}
|
||||||
|
tracks: dict[str, dict] = dict(mine.get("tracks") or {})
|
||||||
|
others = {rec.get("local_id") for sid, s in sets.items() if sid != export_set.id
|
||||||
|
for rec in (s.get("tracks") or {}).values()}
|
||||||
|
|
||||||
|
_backup(tp.platform, path)
|
||||||
|
target = registry.open_library(path)
|
||||||
|
try:
|
||||||
|
caps = target.capabilities()
|
||||||
|
if not caps.writable:
|
||||||
|
raise PushRefused(f"{tp.name} cannot be written: {caps.readonly_cause}")
|
||||||
|
held = _existing_files(target)
|
||||||
|
moved: dict[str, str] = {}
|
||||||
|
new_items: list[ExportTrack] = []
|
||||||
|
updates: list[tuple[ExportTrack, str]] = []
|
||||||
|
for item in payload.tracks:
|
||||||
|
sid = item.source_id
|
||||||
|
rec = tracks.get(sid)
|
||||||
|
local = rec.get("local_id") if rec and rec.get("local_id") else None
|
||||||
|
if local is not None and target.track(local) is None:
|
||||||
|
local = None # removed in the DJ app since: add it again
|
||||||
|
if local is None:
|
||||||
|
# Already in the library at that path (another set's, or a
|
||||||
|
# ledger that was lost): the same file is the same track — a
|
||||||
|
# second entry would be a corrupt Traktor collection.
|
||||||
|
local = held.get(_key(item.destination))
|
||||||
|
if local is None:
|
||||||
|
new_items.append(item)
|
||||||
|
continue
|
||||||
|
moved[sid] = local
|
||||||
|
if rec is None or rec.get("prep") != _prep_hash(item) or sid in written:
|
||||||
|
updates.append((item, local))
|
||||||
|
|
||||||
|
added = target.add_tracks(
|
||||||
|
[NewTrack(track=i.track, audio_path=i.destination, cues=i.cues, art=i.art)
|
||||||
|
for i in new_items], checkpoint=payload.checkpoint) if new_items else []
|
||||||
|
for item, local in zip(new_items, added):
|
||||||
|
moved[item.source_id] = local
|
||||||
|
if item.loudness is not None and caps.tracks.auto_gain:
|
||||||
|
target.set_auto_gain(local, item.loudness)
|
||||||
|
for n, (item, local) in enumerate(updates, start=1):
|
||||||
|
payload.checkpoint(f"Updating {item.track.title or item.destination.name}", step=n,
|
||||||
|
of=len(updates))
|
||||||
|
change = (_audio_change(target, item, planned[item.source_id], previous, waiting)
|
||||||
|
if item.source_id in written else None)
|
||||||
|
_update(target, local, item, audio_change=change)
|
||||||
|
|
||||||
|
# What left the set.
|
||||||
|
present = {i.source_id for i in payload.tracks}
|
||||||
|
kept: list[str] = []
|
||||||
|
removed = 0
|
||||||
|
for sid in [s for s in tracks if s not in present]:
|
||||||
|
rec = tracks[sid]
|
||||||
|
local = rec.get("local_id")
|
||||||
|
if not local or local in others or target.track(local) is None:
|
||||||
|
tracks.pop(sid)
|
||||||
|
continue
|
||||||
|
title = target.track(local).title or local
|
||||||
|
try:
|
||||||
|
target.remove_tracks([local])
|
||||||
|
removed += 1
|
||||||
|
tracks.pop(sid)
|
||||||
|
except Unsupported as ex:
|
||||||
|
# rekordbox: a track in its History, Sampler, … — kept, and
|
||||||
|
# the next push tries again.
|
||||||
|
kept.append(title)
|
||||||
|
rec["kept"] = str(ex)
|
||||||
|
for item in payload.tracks:
|
||||||
|
local = moved.get(item.source_id)
|
||||||
|
if local is not None:
|
||||||
|
tracks[item.source_id] = {
|
||||||
|
"local_id": local, "rel": _rel_for(planned[item.source_id].source_path),
|
||||||
|
"prep": _prep_hash(item)}
|
||||||
|
|
||||||
|
# The set's folder, rebuilt when anything in it would change.
|
||||||
|
existing = _node_ids(target.playlist_tree())
|
||||||
|
folder = mine.get("folder_id") if mine.get("folder_id") in existing else None
|
||||||
|
tree = _tree_hash(export_set.name, payload, moved)
|
||||||
|
if folder is None or mine.get("tree") != tree or mine.get("folder_name") != export_set.name:
|
||||||
|
if folder is not None:
|
||||||
|
target.delete_playlist(folder)
|
||||||
|
name = _folder_name(target, export_set.name, None)
|
||||||
|
folder = target.create_folder(name)
|
||||||
|
write_playlist_tree(target, payload.playlists, [t.source_id for t in payload.tracks],
|
||||||
|
moved, folder)
|
||||||
|
folder_name = export_set.name
|
||||||
|
else:
|
||||||
|
folder_name = mine.get("folder_name")
|
||||||
|
|
||||||
|
if target.dirty:
|
||||||
|
_refuse_if_running(tp.platform)
|
||||||
|
handle.progress(message=f"Saving {tp.name}…")
|
||||||
|
outcome = target.save()
|
||||||
|
_commit(tp.platform, path, getattr(outcome, "snapshot", None),
|
||||||
|
f"Pushed “{export_set.name}” from Konduktor")
|
||||||
|
with _LOCK:
|
||||||
|
doc = _read_ledger()
|
||||||
|
lib = doc["libraries"].setdefault(lid, {})
|
||||||
|
lib.update({"platform": tp.platform, "path": str(path)})
|
||||||
|
lib.setdefault("sets", {})[export_set.id] = {
|
||||||
|
"name": export_set.name, "folder_id": folder, "folder_name": folder_name,
|
||||||
|
"tree": tree, "tracks": tracks, "pushed": time.time(),
|
||||||
|
}
|
||||||
|
_write_ledger(doc)
|
||||||
|
return {"platform": tp.platform, "name": tp.name, "added": len(new_items),
|
||||||
|
"updated": len(updates), "removed": removed, "kept": kept}
|
||||||
|
finally:
|
||||||
|
_close(target)
|
||||||
|
|
||||||
|
|
||||||
|
# ---- one library: overwrite ----------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _replace_file(source: Path, final: Path) -> None:
|
||||||
|
"""Put `source` at `final` atomically: copied beside it, then renamed."""
|
||||||
|
partial = final.with_name(final.name + PARTIAL_SUFFIX)
|
||||||
|
shutil.copy2(source, partial)
|
||||||
|
os.replace(partial, final)
|
||||||
|
|
||||||
|
|
||||||
|
def _overwrite(tp: TargetPlan, export_set, payload: ExportPayload, handle: JobHandle, *,
|
||||||
|
planned: dict[str, PlannedTrack], written: set[str], waiting: list,
|
||||||
|
previous: dict) -> dict:
|
||||||
|
"""Replace the library with this set: the platform's export writer builds
|
||||||
|
a fresh one in app-data (the playlists in a folder named after the set,
|
||||||
|
as a merge puts them), and its files are swapped in."""
|
||||||
|
path = Path(tp.path)
|
||||||
|
lid = library_id.for_path(path, platform=tp.platform, label=tp.name)
|
||||||
|
writer = core_export.for_platform(tp.platform)
|
||||||
|
if writer is None:
|
||||||
|
raise PushRefused(f"Konduktor cannot write a {tp.name} library")
|
||||||
|
# The old library goes, so nothing still plays the files being replaced —
|
||||||
|
# and the writer measures and sizes each file as it now is.
|
||||||
|
for partial, final in waiting:
|
||||||
|
os.replace(partial, final)
|
||||||
|
waiting.clear()
|
||||||
|
work_root = _local_dir() / "work"
|
||||||
|
work_root.mkdir(parents=True, exist_ok=True)
|
||||||
|
work = Path(tempfile.mkdtemp(dir=work_root))
|
||||||
|
try:
|
||||||
|
result = writer.write(payload, work)
|
||||||
|
handle.raise_if_cancelled()
|
||||||
|
_refuse_if_running(tp.platform)
|
||||||
|
handle.progress(message=f"Replacing the {tp.name} library…")
|
||||||
|
_backup(tp.platform, path)
|
||||||
|
if tp.platform == "traktor":
|
||||||
|
_replace_file(result.library, path)
|
||||||
|
_commit(tp.platform, path, path.read_bytes(), f"Replaced by “{export_set.name}” from Konduktor")
|
||||||
|
else:
|
||||||
|
# rekordbox: the database, its playlist XML and the analysis files
|
||||||
|
# under `share/` beside it (new UUID paths, so nothing collides).
|
||||||
|
# A WAL left by the old database would be replayed into the new one.
|
||||||
|
for suffix in ("-wal", "-shm"):
|
||||||
|
path.with_name(path.name + suffix).unlink(missing_ok=True)
|
||||||
|
_replace_file(result.library, path)
|
||||||
|
xml = work / "masterPlaylists6.xml"
|
||||||
|
if xml.is_file():
|
||||||
|
_replace_file(xml, path.with_name(xml.name))
|
||||||
|
share = work / "share"
|
||||||
|
if share.is_dir():
|
||||||
|
shutil.copytree(share, path.parent / "share", dirs_exist_ok=True)
|
||||||
|
finally:
|
||||||
|
shutil.rmtree(work, ignore_errors=True)
|
||||||
|
|
||||||
|
# Record what the new library holds, so a later merge push of this set
|
||||||
|
# finds its tracks and folder.
|
||||||
|
target = registry.open_library(path)
|
||||||
|
try:
|
||||||
|
held = _existing_files(target)
|
||||||
|
tracks = {}
|
||||||
|
for item in payload.tracks:
|
||||||
|
local = held.get(_key(item.destination))
|
||||||
|
if local is not None:
|
||||||
|
tracks[item.source_id] = {"local_id": local,
|
||||||
|
"rel": _rel_for(planned[item.source_id].source_path),
|
||||||
|
"prep": _prep_hash(item)}
|
||||||
|
folder = next((n.id for n in target.playlist_tree() if n.name == export_set.name), None)
|
||||||
|
moved = {sid: rec["local_id"] for sid, rec in tracks.items()}
|
||||||
|
finally:
|
||||||
|
_close(target)
|
||||||
|
with _LOCK:
|
||||||
|
doc = _read_ledger()
|
||||||
|
doc["libraries"][lid] = {"platform": tp.platform, "path": str(path), "sets": {
|
||||||
|
export_set.id: {"name": export_set.name, "folder_id": folder,
|
||||||
|
"folder_name": export_set.name,
|
||||||
|
"tree": _tree_hash(export_set.name, payload, moved),
|
||||||
|
"tracks": tracks, "pushed": time.time()}}}
|
||||||
|
_write_ledger(doc)
|
||||||
|
return {"platform": tp.platform, "name": tp.name, "added": len(tracks), "updated": 0,
|
||||||
|
"removed": 0, "kept": [], "replaced": True, "wiped_sets": tp.wipes_sets}
|
||||||
+127
-12
@@ -16,7 +16,7 @@ from fastapi import FastAPI, File, Form, HTTPException, Query, Response, UploadF
|
|||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
from fastapi.responses import FileResponse, JSONResponse
|
from fastapi.responses import FileResponse, JSONResponse
|
||||||
|
|
||||||
from . import __version__, exporter, exports, loudness_store, prefs
|
from . import __version__, exporter, exports, local_push, loudness_store, prefs
|
||||||
from .app_state import STATE
|
from .app_state import STATE
|
||||||
from .core import auto_hotcues as ah
|
from .core import auto_hotcues as ah
|
||||||
from .core import grid_detect, key_detect, loudness, structure
|
from .core import grid_detect, key_detect, loudness, structure
|
||||||
@@ -74,6 +74,8 @@ from .schemas import (
|
|||||||
ExportSetMembers,
|
ExportSetMembers,
|
||||||
ExportSetOut,
|
ExportSetOut,
|
||||||
ExportPreview,
|
ExportPreview,
|
||||||
|
LocalLibrariesOut,
|
||||||
|
PushPreview,
|
||||||
Drive,
|
Drive,
|
||||||
DroppedFiles,
|
DroppedFiles,
|
||||||
DroppedPaths,
|
DroppedPaths,
|
||||||
@@ -102,6 +104,7 @@ from .schemas import (
|
|||||||
RenamePlaylist,
|
RenamePlaylist,
|
||||||
SaveResult,
|
SaveResult,
|
||||||
AddEntries,
|
AddEntries,
|
||||||
|
RemoveEntries,
|
||||||
MovePlaylist,
|
MovePlaylist,
|
||||||
SetEntries,
|
SetEntries,
|
||||||
SourceCandidate,
|
SourceCandidate,
|
||||||
@@ -316,7 +319,7 @@ def delete_remote(remote_id: str) -> dict:
|
|||||||
def _running_batch() -> str | None:
|
def _running_batch() -> str | None:
|
||||||
"""The kind of batch running here, for the heartbeat: another computer
|
"""The kind of batch running here, for the heartbeat: another computer
|
||||||
asking to take over is told what it would cancel."""
|
asking to take over is told what it would cancel."""
|
||||||
for kind in BATCH_JOBS + ("import", "export"):
|
for kind in BATCH_JOBS + ("import", "export", local_push.JOB_KIND):
|
||||||
if JOBS.active(kind):
|
if JOBS.active(kind):
|
||||||
return kind
|
return kind
|
||||||
return None
|
return None
|
||||||
@@ -642,30 +645,33 @@ def list_exports() -> list[ExportSetOut]:
|
|||||||
|
|
||||||
@app.post("/api/exports", response_model=ExportSetOut)
|
@app.post("/api/exports", response_model=ExportSetOut)
|
||||||
def create_export(body: CreateExportSet) -> ExportSetOut:
|
def create_export(body: CreateExportSet) -> ExportSetOut:
|
||||||
if not body.destination.strip():
|
if body.kind == "folder" and not body.destination.strip():
|
||||||
raise HTTPException(400, "An export needs a destination folder")
|
raise HTTPException(400, "An export needs a destination folder")
|
||||||
# Only platforms that can actually be WRITTEN may be targets. Gating here as
|
# Only platforms that can actually be WRITTEN may be targets. Gating here as
|
||||||
# well as in the UI, because a set persists: one created against a target
|
# well as in the UI, because a set persists: one created against a target
|
||||||
# that later stops being supported would otherwise fail at export time.
|
# that later stops being supported would otherwise fail at export time.
|
||||||
_check_targets(body.targets)
|
_check_targets(body.targets, kind=body.kind)
|
||||||
created = exports.create(
|
created = exports.create(
|
||||||
_require_library_id(),
|
_require_library_id(),
|
||||||
name=body.name,
|
name=body.name,
|
||||||
targets=body.targets,
|
targets=body.targets,
|
||||||
destination=body.destination,
|
destination=body.destination if body.kind == "folder" else "",
|
||||||
|
kind=body.kind,
|
||||||
|
mode=body.mode,
|
||||||
)
|
)
|
||||||
return ExportSetOut(**created.as_dict())
|
return ExportSetOut(**created.as_dict())
|
||||||
|
|
||||||
|
|
||||||
@app.patch("/api/exports/{set_id}", response_model=ExportSetOut)
|
@app.patch("/api/exports/{set_id}", response_model=ExportSetOut)
|
||||||
def update_export(set_id: str, body: UpdateExportSet) -> ExportSetOut:
|
def update_export(set_id: str, body: UpdateExportSet) -> ExportSetOut:
|
||||||
_require_set(set_id)
|
found = _require_set(set_id)
|
||||||
if body.targets is not None:
|
if body.targets is not None:
|
||||||
_check_targets(body.targets)
|
_check_targets(body.targets, kind=found.kind)
|
||||||
updated = exports.update(
|
updated = exports.update(
|
||||||
_require_library_id(),
|
_require_library_id(),
|
||||||
set_id,
|
set_id,
|
||||||
name=body.name,
|
name=body.name,
|
||||||
|
mode=body.mode,
|
||||||
targets=body.targets,
|
targets=body.targets,
|
||||||
destination=body.destination,
|
destination=body.destination,
|
||||||
lock_grids=body.lock_grids,
|
lock_grids=body.lock_grids,
|
||||||
@@ -724,7 +730,7 @@ def export_contents(set_id: str) -> ExportContents:
|
|||||||
dangling=resolved.dangling_track_ids,
|
dangling=resolved.dangling_track_ids,
|
||||||
destination_conflict=exports.destination_conflict(
|
destination_conflict=exports.destination_conflict(
|
||||||
_require_library_id(), found.destination, ignore=set_id
|
_require_library_id(), found.destination, ignore=set_id
|
||||||
),
|
) if found.kind == "folder" else None,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -800,7 +806,7 @@ def _export_options(found, body: RunExport | None) -> dict:
|
|||||||
def preview_export(set_id: str, body: RunExport | None = None) -> ExportPreview:
|
def preview_export(set_id: str, body: RunExport | None = None) -> ExportPreview:
|
||||||
"""What this export would do, right now, with the run dialog's options as
|
"""What this export would do, right now, with the run dialog's options as
|
||||||
ticked. Never cached — the set is live."""
|
ticked. Never cached — the set is live."""
|
||||||
found = _require_set(set_id)
|
found = _require_folder_set(set_id)
|
||||||
built = exporter.plan(require_adapter(), found, **_export_options(found, body))
|
built = exporter.plan(require_adapter(), found, **_export_options(found, body))
|
||||||
return ExportPreview(**built.as_dict(exporter.space_for(built)))
|
return ExportPreview(**built.as_dict(exporter.space_for(built)))
|
||||||
|
|
||||||
@@ -816,7 +822,7 @@ def run_export(set_id: str, body: RunExport | None = None) -> JobStatus:
|
|||||||
The dialog's options arrive with the click and are remembered on the set,
|
The dialog's options arrive with the click and are remembered on the set,
|
||||||
so the next export of the same stick starts from the same answer.
|
so the next export of the same stick starts from the same answer.
|
||||||
"""
|
"""
|
||||||
found = _require_set(set_id)
|
found = _require_folder_set(set_id)
|
||||||
if body is not None:
|
if body is not None:
|
||||||
changes = {k: v for k, v in (("lock_grids", body.lock_grids), ("normalise", body.normalise),
|
changes = {k: v for k, v in (("lock_grids", body.lock_grids), ("normalise", body.normalise),
|
||||||
("auto_gain", body.auto_gain)) if v is not None}
|
("auto_gain", body.auto_gain)) if v is not None}
|
||||||
@@ -836,6 +842,80 @@ def run_export(set_id: str, body: RunExport | None = None) -> JobStatus:
|
|||||||
return JobStatus(**job.as_dict())
|
return JobStatus(**job.as_dict())
|
||||||
|
|
||||||
|
|
||||||
|
# ---- pushing into this computer's DJ apps (`local_push.py`) -----------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _local_level_out(level) -> dict | None:
|
||||||
|
return {"measure": level.measure, "target": level.target, "ceiling": level.ceiling} if level else None
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/local-libraries", response_model=LocalLibrariesOut)
|
||||||
|
def local_libraries() -> LocalLibrariesOut:
|
||||||
|
"""The DJ apps' libraries on this computer a "computer" set pushes into,
|
||||||
|
each with why it cannot be used, plus the shared audio folder and its
|
||||||
|
level. Changed through `/api/prefs` (`localLibraries`, `localAudioRoot`,
|
||||||
|
`localNormalise`, `localLevel`)."""
|
||||||
|
import platformdirs
|
||||||
|
|
||||||
|
return LocalLibrariesOut(
|
||||||
|
libraries=[lib.as_dict() for lib in local_push.local_libraries(STATE.path)],
|
||||||
|
audio_root=str(local_push.audio_root()),
|
||||||
|
audio_root_default=str(Path(platformdirs.user_music_dir()) / "Konduktor"),
|
||||||
|
level=_local_level_out(local_push.level()),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _require_computer_set(set_id: str):
|
||||||
|
found = _require_set(set_id)
|
||||||
|
if found.kind != "computer":
|
||||||
|
raise HTTPException(400, "This set is exported into a folder, not pushed")
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def _push_options(found) -> dict:
|
||||||
|
"""The push's options: the set's lock and auto gain (as the run dialog
|
||||||
|
left them), the shared folder's level (the app setting, not the set's)."""
|
||||||
|
return {"store": STATE.loudness, "level": local_push.level(), "auto_gain": bool(found.auto_gain)}
|
||||||
|
|
||||||
|
|
||||||
|
def _remember_run_options(found, body: RunExport | None):
|
||||||
|
if body is None:
|
||||||
|
return found
|
||||||
|
changes = {k: v for k, v in (("lock_grids", body.lock_grids), ("auto_gain", body.auto_gain))
|
||||||
|
if v is not None}
|
||||||
|
return exports.update(_require_library_id(), found.id, **changes) if changes else found
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/exports/{set_id}/push/preview", response_model=PushPreview)
|
||||||
|
def preview_push(set_id: str, body: RunExport | None = None) -> PushPreview:
|
||||||
|
"""What pushing this set would do now, with the dialog's ticks."""
|
||||||
|
found = _require_computer_set(set_id)
|
||||||
|
if body is not None and body.auto_gain is not None:
|
||||||
|
found.auto_gain = body.auto_gain # a look, not a change: not saved
|
||||||
|
built = local_push.plan(require_adapter(), found, open_path=STATE.path, **_push_options(found))
|
||||||
|
return PushPreview(**built.as_dict())
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/exports/{set_id}/push", response_model=JobStatus)
|
||||||
|
def run_push(set_id: str, body: RunExport | None = None) -> JobStatus:
|
||||||
|
"""Start the push on a background thread; poll `/api/jobs/{id}`. Planned
|
||||||
|
again here (a playlist may have changed since the preview, or Traktor been
|
||||||
|
started); the dialog's ticks are remembered on the set."""
|
||||||
|
found = _remember_run_options(_require_computer_set(set_id), body)
|
||||||
|
adapter = require_adapter()
|
||||||
|
options = _push_options(found)
|
||||||
|
built = local_push.plan(adapter, found, open_path=STATE.path, **options)
|
||||||
|
if built.blocked:
|
||||||
|
raise HTTPException(409, built.blocked)
|
||||||
|
try:
|
||||||
|
job = JOBS.submit(local_push.JOB_KIND, lambda handle: local_push.run(
|
||||||
|
adapter, found, built, handle, lock_grids=found.lock_grids, **options),
|
||||||
|
exclusive_with=(local_push.JOB_KIND,))
|
||||||
|
except JobBusy:
|
||||||
|
raise HTTPException(409, "A push is already running")
|
||||||
|
return JobStatus(**job.as_dict())
|
||||||
|
|
||||||
|
|
||||||
def _export_targets() -> set[str]:
|
def _export_targets() -> set[str]:
|
||||||
"""Platforms Konduktor can write a NEW library for.
|
"""Platforms Konduktor can write a NEW library for.
|
||||||
|
|
||||||
@@ -847,14 +927,27 @@ def _export_targets() -> set[str]:
|
|||||||
return core_export.targets()
|
return core_export.targets()
|
||||||
|
|
||||||
|
|
||||||
def _check_targets(targets: list[str]) -> None:
|
def _require_folder_set(set_id: str):
|
||||||
|
found = _require_set(set_id)
|
||||||
|
if found.kind != "folder":
|
||||||
|
raise HTTPException(400, "This set is pushed into this computer's DJ apps, not exported")
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def _check_targets(targets: list[str], *, kind: str = "folder") -> None:
|
||||||
"""Refuse a set with no targets, or one naming a platform with no exporter.
|
"""Refuse a set with no targets, or one naming a platform with no exporter.
|
||||||
|
|
||||||
Checked when the set is saved: a target that later stops being supported
|
Checked when the set is saved: a target that later stops being supported
|
||||||
would otherwise fail at export time.
|
would otherwise fail at export time. A "computer" set pushes into the DJ
|
||||||
|
apps a computer runs, which are `local_push.PLATFORMS`.
|
||||||
"""
|
"""
|
||||||
if not targets:
|
if not targets:
|
||||||
raise HTTPException(400, "An export needs at least one platform to export for")
|
raise HTTPException(400, "An export needs at least one platform to export for")
|
||||||
|
if kind == "computer":
|
||||||
|
unsupported = [t for t in targets if t not in local_push.PLATFORMS]
|
||||||
|
if unsupported:
|
||||||
|
raise HTTPException(422, f"Konduktor cannot push into {', '.join(unsupported)}")
|
||||||
|
return
|
||||||
unsupported = [t for t in targets if t not in _export_targets()]
|
unsupported = [t for t in targets if t not in _export_targets()]
|
||||||
if unsupported:
|
if unsupported:
|
||||||
raise HTTPException(422, f"Konduktor cannot export to {', '.join(unsupported)} yet")
|
raise HTTPException(422, f"Konduktor cannot export to {', '.join(unsupported)} yet")
|
||||||
@@ -1381,6 +1474,28 @@ def add_entries(playlist_uuid: str, body: AddEntries) -> dict:
|
|||||||
"duplicates": len(dupes), "count": n}
|
"duplicates": len(dupes), "count": n}
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/playlists/{playlist_uuid}/remove")
|
||||||
|
def remove_entries(playlist_uuid: str, body: RemoveEntries) -> dict:
|
||||||
|
"""Remove tracks from a playlist — EVERY occurrence of each — without the
|
||||||
|
caller holding its entry list (the track menu's Remove ▸ From playlist).
|
||||||
|
Other entries keep their order, including ones whose track is missing
|
||||||
|
from the collection. `tracks` = how many of the given tracks it held,
|
||||||
|
`removed` = entries dropped (more, where a track was there twice)."""
|
||||||
|
a = require_adapter()
|
||||||
|
current = a.playlist_entries(playlist_uuid)
|
||||||
|
if current is None:
|
||||||
|
raise HTTPException(404, f"Playlist not found: {playlist_uuid}")
|
||||||
|
gone = set(body.track_ids)
|
||||||
|
kept = [t for t in current if t not in gone]
|
||||||
|
held = len(gone & set(current))
|
||||||
|
removed = len(current) - len(kept)
|
||||||
|
n = len(current)
|
||||||
|
if removed and not body.dry_run:
|
||||||
|
n = a.set_playlist_entries(playlist_uuid, kept)
|
||||||
|
return {"status": "counted" if body.dry_run else "removed", "id": playlist_uuid,
|
||||||
|
"tracks": held, "removed": removed, "count": n}
|
||||||
|
|
||||||
|
|
||||||
@app.patch("/api/tracks")
|
@app.patch("/api/tracks")
|
||||||
def edit_track(body: EditTrack) -> dict:
|
def edit_track(body: EditTrack) -> dict:
|
||||||
"""Edit a single track's safe metadata fields (in-memory; persisted on save)."""
|
"""Edit a single track's safe metadata fields (in-memory; persisted on save)."""
|
||||||
|
|||||||
@@ -109,6 +109,7 @@ EXCLUDED: dict[str, str] = {
|
|||||||
"set_cover_art": "PUT /v1/art — bytes",
|
"set_cover_art": "PUT /v1/art — bytes",
|
||||||
"apply_stem_swaps": "the server applies stem swaps itself (POST /v1/stems/publish)",
|
"apply_stem_swaps": "the server applies stem swaps itself (POST /v1/stems/publish)",
|
||||||
"audio_changed": "the server applies a Normalize itself, at its own end step (POST /v1/gain/publish)",
|
"audio_changed": "the server applies a Normalize itself, at its own end step (POST /v1/gain/publish)",
|
||||||
|
"replace_cues": "a push targets a DJ app's library on THIS computer, never one a server holds",
|
||||||
"set_path_mapping": "the server's path mapping is its own configuration",
|
"set_path_mapping": "the server's path mapping is its own configuration",
|
||||||
"set_session_mappings": "the missing-files check searches THIS computer's drives",
|
"set_session_mappings": "the missing-files check searches THIS computer's drives",
|
||||||
"unresolved_path_groups": "the missing-files check searches THIS computer's drives",
|
"unresolved_path_groups": "the missing-files check searches THIS computer's drives",
|
||||||
|
|||||||
@@ -32,6 +32,12 @@ class AddEntries(BaseModel):
|
|||||||
index: int | None = None
|
index: int | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class RemoveEntries(BaseModel):
|
||||||
|
track_ids: list[str]
|
||||||
|
# Count what would go and change nothing — the confirm dialog's numbers.
|
||||||
|
dry_run: bool = False
|
||||||
|
|
||||||
|
|
||||||
class MovePlaylist(BaseModel):
|
class MovePlaylist(BaseModel):
|
||||||
node_id: str
|
node_id: str
|
||||||
parent_id: str | None = None # None = the top level
|
parent_id: str | None = None # None = the top level
|
||||||
@@ -402,6 +408,10 @@ class CollectionOptions(BaseModel):
|
|||||||
class ExportSetOut(BaseModel):
|
class ExportSetOut(BaseModel):
|
||||||
id: str
|
id: str
|
||||||
name: str
|
name: str
|
||||||
|
#: "folder": exported into `destination`; "computer": pushed into the DJ
|
||||||
|
#: apps' own libraries on this computer (`local_push.py`), `mode` saying how.
|
||||||
|
kind: Literal["folder", "computer"] = "folder"
|
||||||
|
mode: Literal["merge", "overwrite"] = "merge"
|
||||||
targets: list[str] # platform ids of the export TARGETS, never empty
|
targets: list[str] # platform ids of the export TARGETS, never empty
|
||||||
destination: str
|
destination: str
|
||||||
playlist_ids: list[str] = []
|
playlist_ids: list[str] = []
|
||||||
@@ -416,8 +426,10 @@ class ExportSetOut(BaseModel):
|
|||||||
|
|
||||||
class CreateExportSet(BaseModel):
|
class CreateExportSet(BaseModel):
|
||||||
name: str
|
name: str
|
||||||
|
kind: Literal["folder", "computer"] = "folder"
|
||||||
|
mode: Literal["merge", "overwrite"] = "merge"
|
||||||
targets: list[str] = ["traktor"]
|
targets: list[str] = ["traktor"]
|
||||||
destination: str
|
destination: str = "" # a "computer" set has none
|
||||||
|
|
||||||
|
|
||||||
class ExportLevel(BaseModel):
|
class ExportLevel(BaseModel):
|
||||||
@@ -429,6 +441,7 @@ class ExportLevel(BaseModel):
|
|||||||
|
|
||||||
class UpdateExportSet(BaseModel):
|
class UpdateExportSet(BaseModel):
|
||||||
name: str | None = None
|
name: str | None = None
|
||||||
|
mode: Literal["merge", "overwrite"] | None = None
|
||||||
targets: list[str] | None = None
|
targets: list[str] | None = None
|
||||||
destination: str | None = None
|
destination: str | None = None
|
||||||
lock_grids: bool | None = None
|
lock_grids: bool | None = None
|
||||||
@@ -502,6 +515,71 @@ class ExportPreview(BaseModel):
|
|||||||
level_counts: dict[str, int] = {}
|
level_counts: dict[str, int] = {}
|
||||||
|
|
||||||
|
|
||||||
|
# ---- pushing into this computer's DJ apps (`local_push.py`) -------------------
|
||||||
|
|
||||||
|
|
||||||
|
class LocalLibraryOut(BaseModel):
|
||||||
|
"""One DJ app's library on this computer, as a push target."""
|
||||||
|
|
||||||
|
platform: str
|
||||||
|
name: str
|
||||||
|
path: str | None = None
|
||||||
|
#: Found by the platform's own detection (False: the user's setting).
|
||||||
|
detected: bool = True
|
||||||
|
#: A FACT: `not_found`, `open_in_konduktor`, `cloud_synced`, `unreadable`.
|
||||||
|
blocked: str | None = None
|
||||||
|
running: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
class LocalLibrariesOut(BaseModel):
|
||||||
|
libraries: list[LocalLibraryOut] = []
|
||||||
|
#: The shared folder pushed audio lives in, and where it is by default.
|
||||||
|
audio_root: str
|
||||||
|
audio_root_default: str
|
||||||
|
#: The shared folder's Normalise level (None: off).
|
||||||
|
level: ExportLevel | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class PushTargetOut(BaseModel):
|
||||||
|
platform: str
|
||||||
|
name: str
|
||||||
|
path: str | None = None
|
||||||
|
blocked: str | None = None
|
||||||
|
#: Not on this computer (`blocked` = not_found): passed over by the push
|
||||||
|
#: instead of blocking it.
|
||||||
|
skipped: bool = False
|
||||||
|
running: bool = False
|
||||||
|
add: int = 0
|
||||||
|
already: int = 0
|
||||||
|
remove: int = 0
|
||||||
|
#: Overwrite: the other sets pushed into this library, which it removes.
|
||||||
|
wipes_sets: list[str] = []
|
||||||
|
|
||||||
|
|
||||||
|
class PushPreview(BaseModel):
|
||||||
|
"""What a push would do now. Computed fresh; never stored."""
|
||||||
|
|
||||||
|
mode: Literal["merge", "overwrite"] = "merge"
|
||||||
|
tracks: int = 0
|
||||||
|
pushable: int = 0
|
||||||
|
#: Copies in the shared folder kept rather than copied again.
|
||||||
|
unchanged: int = 0
|
||||||
|
missing: list[str] = []
|
||||||
|
playlists: list[str] = []
|
||||||
|
total_bytes: int = 0
|
||||||
|
audio_root: str
|
||||||
|
free_bytes: int | None = None
|
||||||
|
enough_space: bool | None = None
|
||||||
|
normalised: int = 0
|
||||||
|
to_measure: int = 0
|
||||||
|
level_counts: dict[str, int] = {}
|
||||||
|
targets: list[PushTargetOut] = []
|
||||||
|
#: A FACT: `no_target`, `no_library_here` (none of the set's libraries
|
||||||
|
#: is on this computer), `nothing_to_push`, `target_unavailable`,
|
||||||
|
#: `app_running`, or null when it can run.
|
||||||
|
blocked: str | None = None
|
||||||
|
|
||||||
|
|
||||||
class FsPlace(BaseModel):
|
class FsPlace(BaseModel):
|
||||||
"""A shortcut in the file browser's sidebar.
|
"""A shortcut in the file browser's sidebar.
|
||||||
|
|
||||||
|
|||||||
@@ -12,6 +12,9 @@ python-multipart>=0.0.9 # multipart form parsing for cover-art upload
|
|||||||
# app-data dir. Both bundle cleanly into the frozen sidecar.
|
# app-data dir. Both bundle cleanly into the frozen sidecar.
|
||||||
dulwich>=0.22
|
dulwich>=0.22
|
||||||
platformdirs>=4.0
|
platformdirs>=4.0
|
||||||
|
# Is Traktor / rekordbox running? (core/apps_running.py — a push refuses while
|
||||||
|
# one is). Came only through pyrekordbox before; imported directly now.
|
||||||
|
psutil>=5.9
|
||||||
# Auto Hotcues: structural segmentation (McFee/Ellis Laplacian). Pure-Python,
|
# Auto Hotcues: structural segmentation (McFee/Ellis Laplacian). Pure-Python,
|
||||||
# ~150MB; numba/llvmlite ship Python 3.14 wheels (verified). No torch/native build.
|
# ~150MB; numba/llvmlite ship Python 3.14 wheels (verified). No torch/native build.
|
||||||
librosa>=0.11
|
librosa>=0.11
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
|
|||||||
source .venv/bin/activate
|
source .venv/bin/activate
|
||||||
|
|
||||||
fail=0
|
fail=0
|
||||||
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_key_detect.py test_loudness.py test_loudness_store.py test_level_plan.py test_level_edit.py test_aac_gain.py test_normalize.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_prefs.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_export_level.py test_device_export.py test_phase3.py test_history.py test_discard.py test_remote_protocol.py test_remote_server.py test_remote_adapter.py test_remote_stems.py test_remote_normalize.py; do
|
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_key_detect.py test_loudness.py test_loudness_store.py test_level_plan.py test_level_edit.py test_aac_gain.py test_normalize.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_prefs.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_export_level.py test_local_push.py test_traktor_file_block.py test_device_export.py test_phase3.py test_history.py test_discard.py test_remote_protocol.py test_remote_server.py test_remote_adapter.py test_remote_stems.py test_remote_normalize.py; do
|
||||||
echo "──────────────────────────────────────────"
|
echo "──────────────────────────────────────────"
|
||||||
echo "▶ $t"
|
echo "▶ $t"
|
||||||
echo "──────────────────────────────────────────"
|
echo "──────────────────────────────────────────"
|
||||||
|
|||||||
@@ -150,6 +150,20 @@ check("paths are compared normalised, not as strings",
|
|||||||
exports.destination_conflict(LIB, str(work / "out") + "/./", ignore=s3.id) == "Ibiza")
|
exports.destination_conflict(LIB, str(work / "out") + "/./", ignore=s3.id) == "Ibiza")
|
||||||
exports.delete(LIB, s3.id)
|
exports.delete(LIB, s3.id)
|
||||||
|
|
||||||
|
print("== a set pushed into this computer's DJ apps ==")
|
||||||
|
check("a set saved before kinds existed loads as a folder export, merge",
|
||||||
|
(exports.get(LIB, s1.id).kind, exports.get(LIB, s1.id).mode) == ("folder", "merge"))
|
||||||
|
s4 = exports.create(LIB, name="Laptop", targets=["traktor"], destination="", kind="computer",
|
||||||
|
mode="overwrite")
|
||||||
|
check("kind and mode persist", (exports.get(LIB, s4.id).kind, exports.get(LIB, s4.id).mode)
|
||||||
|
== ("computer", "overwrite"))
|
||||||
|
exports.update(LIB, s4.id, mode="merge", kind="nonsense")
|
||||||
|
check("mode changes; an unknown kind is ignored",
|
||||||
|
(exports.get(LIB, s4.id).kind, exports.get(LIB, s4.id).mode) == ("computer", "merge"))
|
||||||
|
check("a computer set has no destination to clash over",
|
||||||
|
exports.destination_conflict(LIB, "", ignore=s1.id) is None)
|
||||||
|
exports.delete(LIB, s4.id)
|
||||||
|
|
||||||
print("== following track ids that change under a path remap ==")
|
print("== following track ids that change under a path remap ==")
|
||||||
exports.retarget(LIB, {all_tracks[0]: "Macintosh HD/:Moved/:one.mp3"})
|
exports.retarget(LIB, {all_tracks[0]: "Macintosh HD/:Moved/:one.mp3"})
|
||||||
check("a renamed id is followed",
|
check("a renamed id is followed",
|
||||||
|
|||||||
@@ -0,0 +1,437 @@
|
|||||||
|
"""Pushing an export set into this computer's Traktor / rekordbox library
|
||||||
|
(`local_push.py`), through the routes.
|
||||||
|
|
||||||
|
The source library is a temp copy of the real collection pointed at GENERATED
|
||||||
|
audio; the "local" Traktor collection pushed into is ANOTHER temp copy of the
|
||||||
|
real one — the user's own 8,485 entries — and the shared audio folder is a temp
|
||||||
|
folder. Prefs and app-data are redirected, and whether a DJ app is running is
|
||||||
|
faked (a real Traktor may be open on the machine running this).
|
||||||
|
|
||||||
|
What would fail SILENTLY, and matter at a gig:
|
||||||
|
|
||||||
|
* a merge touches nothing of the user's own: existing entries and playlists
|
||||||
|
render byte-identically, only new ENTRYs and the set's folder appear;
|
||||||
|
* a re-push of an unchanged set copies and writes nothing;
|
||||||
|
* the source wins: an edited cue or title reaches the pushed entry, and a
|
||||||
|
re-levelled copy is swapped in with the entry's size following;
|
||||||
|
* removal follows the set, but never takes a track another set holds, and a
|
||||||
|
rekordbox refusal keeps the track and reports it;
|
||||||
|
* the set's folder never takes over a folder of the user's with its name;
|
||||||
|
* overwrite leaves only this set, deleting the other sets' files;
|
||||||
|
* a running DJ app, the open library, and a failure mid-copy all leave the
|
||||||
|
library as it was.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import difflib
|
||||||
|
import hashlib
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
import warnings
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
warnings.filterwarnings("ignore")
|
||||||
|
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-push-appdata-")
|
||||||
|
os.environ.pop("KONDUKTOR_NML", None)
|
||||||
|
|
||||||
|
import av # noqa: E402
|
||||||
|
import numpy as np # noqa: E402
|
||||||
|
from fastapi.testclient import TestClient # noqa: E402
|
||||||
|
|
||||||
|
import konduktor.main as main # noqa: E402
|
||||||
|
from konduktor import history, local_push, paths, prefs # noqa: E402
|
||||||
|
from konduktor.adapters.traktor.adapter import TraktorAdapter # noqa: E402
|
||||||
|
from konduktor.adapters.traktor.locations import os_path_to_location # noqa: E402
|
||||||
|
from konduktor.adapters.traktor.store import TraktorStore # noqa: E402
|
||||||
|
from konduktor.core import apps_running # noqa: E402
|
||||||
|
|
||||||
|
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
|
||||||
|
ROOT = Path(tempfile.mkdtemp(prefix="konduktor-push-"))
|
||||||
|
AUDIO = ROOT / "Music" / "Konduktor"
|
||||||
|
failed = False
|
||||||
|
|
||||||
|
|
||||||
|
def check(label, cond, detail=""):
|
||||||
|
global failed
|
||||||
|
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
|
||||||
|
if not cond:
|
||||||
|
failed = True
|
||||||
|
|
||||||
|
|
||||||
|
def make_mp3(path: Path, seed: int) -> Path:
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
sr = 44100
|
||||||
|
t = np.arange(sr * 8) / sr
|
||||||
|
rng = np.random.default_rng(seed)
|
||||||
|
beat = (np.sin(2 * np.pi * 2 * t) > 0.6).astype(float)
|
||||||
|
x = np.vstack([0.3 * (0.5 * np.sin(2 * np.pi * 90 * t) * beat + 0.2 * rng.standard_normal(t.size))
|
||||||
|
for _ in range(2)]).astype(np.float32)
|
||||||
|
with av.open(str(path), "w", format="mp3") as c:
|
||||||
|
s = c.add_stream("libmp3lame", rate=sr, layout="stereo")
|
||||||
|
s.bit_rate = 192_000
|
||||||
|
for o in range(0, x.shape[1], 1152):
|
||||||
|
f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, o:o + 1152]), format="fltp", layout="stereo")
|
||||||
|
f.sample_rate, f.pts = sr, o
|
||||||
|
for p in s.encode(f):
|
||||||
|
c.mux(p)
|
||||||
|
for p in s.encode(None):
|
||||||
|
c.mux(p)
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
def source_library(n=5):
|
||||||
|
d = ROOT / "source"
|
||||||
|
d.mkdir(parents=True)
|
||||||
|
work = d / "collection.nml"
|
||||||
|
shutil.copy2(REAL, work)
|
||||||
|
st = TraktorStore(work)
|
||||||
|
entries = [e for e in st._nml.collection.entry if e.location and e.stems is None]
|
||||||
|
ids, files = [], []
|
||||||
|
for i, e in enumerate(entries[:n]):
|
||||||
|
path = make_mp3(d / "Music" / f"track{i}.mp3", seed=i)
|
||||||
|
e.location.volume, e.location.dir, e.location.file = os_path_to_location(path)
|
||||||
|
e.cue_v2 = []
|
||||||
|
e.title = f"Track {i}"
|
||||||
|
st._entry_by_key = {st._key_of(x): x for x in st._nml.collection.entry if x.location}
|
||||||
|
ids.append(st._key_of(e))
|
||||||
|
files.append(path)
|
||||||
|
st.save()
|
||||||
|
return work, ids, files
|
||||||
|
|
||||||
|
|
||||||
|
def sha(p: Path) -> str:
|
||||||
|
return hashlib.sha256(p.read_bytes()).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def wait(c, jid, timeout=300):
|
||||||
|
end = time.time() + timeout
|
||||||
|
while time.time() < end:
|
||||||
|
j = c.get(f"/api/jobs/{jid}").json()
|
||||||
|
if j["state"] != "running":
|
||||||
|
return j
|
||||||
|
time.sleep(0.05)
|
||||||
|
raise AssertionError("job did not finish")
|
||||||
|
|
||||||
|
|
||||||
|
def copy_of(source: Path) -> Path:
|
||||||
|
return AUDIO / local_push._rel_for(source)
|
||||||
|
|
||||||
|
|
||||||
|
def pushed(target: Path) -> dict[str, object]:
|
||||||
|
"""The target's entries that live in the shared audio folder, by file name."""
|
||||||
|
st = TraktorStore(target)
|
||||||
|
out = {}
|
||||||
|
for e in st._nml.collection.entry:
|
||||||
|
path = st.audio_path(st._key_of(e)) if e.location else None
|
||||||
|
if path and AUDIO in Path(path).parents:
|
||||||
|
out[Path(path).name] = e
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def top_level(target: Path) -> dict[str, object]:
|
||||||
|
ad = TraktorAdapter(target)
|
||||||
|
return {n.name: n for n in ad.playlist_tree()}
|
||||||
|
|
||||||
|
|
||||||
|
def removed_lines(before: str, after: str) -> list[str]:
|
||||||
|
return [l for l in difflib.unified_diff(before.splitlines(), after.splitlines(), lineterm="", n=0)
|
||||||
|
if l.startswith("-") and not l.startswith("---")]
|
||||||
|
|
||||||
|
|
||||||
|
src, ids, files = source_library()
|
||||||
|
target = ROOT / "laptop" / "Traktor 4.5.0" / "collection.nml"
|
||||||
|
target.parent.mkdir(parents=True)
|
||||||
|
shutil.copy2(REAL, target)
|
||||||
|
|
||||||
|
RUNNING: set[str] = set()
|
||||||
|
apps_running.running = lambda platforms: {p for p in platforms if p in RUNNING}
|
||||||
|
prefs.update_prefs({"localLibraries": {"traktor": str(target), "rekordbox": str(ROOT / "none" / "master.db")},
|
||||||
|
"localAudioRoot": str(AUDIO), "localNormalise": False})
|
||||||
|
|
||||||
|
with TestClient(main.app) as c:
|
||||||
|
r = c.post("/api/library/open", json={"path": str(src)})
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
adapter = main.STATE.adapter
|
||||||
|
|
||||||
|
print("== the local libraries ==")
|
||||||
|
libs = {l["platform"]: l for l in c.get("/api/local-libraries").json()["libraries"]}
|
||||||
|
check("Traktor is the configured collection, usable", libs["traktor"]["path"] == str(target)
|
||||||
|
and libs["traktor"]["blocked"] is None and not libs["traktor"]["detected"], str(libs["traktor"]))
|
||||||
|
check("a rekordbox library that is not there is not_found", libs["rekordbox"]["blocked"] == "not_found")
|
||||||
|
|
||||||
|
print("== a computer set ==")
|
||||||
|
r = c.post("/api/exports", json={"name": "Gig", "kind": "computer", "targets": ["onelibrary"]})
|
||||||
|
check("a stick format is not a push target", r.status_code == 422, r.text)
|
||||||
|
gig = c.post("/api/exports", json={"name": "Gig", "kind": "computer", "targets": ["traktor"]}).json()
|
||||||
|
check("created with no destination, mode merge", gig["kind"] == "computer" and gig["mode"] == "merge"
|
||||||
|
and gig["destination"] == "", str(gig))
|
||||||
|
pl = c.post("/api/playlists", json={"name": "Peak"}).json()["id"]
|
||||||
|
c.put(f"/api/playlists/{pl}/entries", json={"track_ids": ids[:2]})
|
||||||
|
c.post(f"/api/exports/{gig['id']}/add", json={"playlist_ids": [pl], "track_ids": [ids[2]]})
|
||||||
|
adapter.set_cue(ids[0], slot=0, start_sec=1.0, cue_type="cue", name="Drop")
|
||||||
|
adapter.replace_grid(ids[0], [(0.5, 120.0)])
|
||||||
|
check("an export route refuses a computer set",
|
||||||
|
c.post(f"/api/exports/{gig['id']}/preview", json={}).status_code == 400)
|
||||||
|
|
||||||
|
pv = c.post(f"/api/exports/{gig['id']}/push/preview", json={}).json()
|
||||||
|
t = pv["targets"][0]
|
||||||
|
check("the preview: three to add, nothing blocked", pv["blocked"] is None and pv["pushable"] == 3
|
||||||
|
and (t["add"], t["already"], t["remove"]) == (3, 0, 0), str(pv))
|
||||||
|
|
||||||
|
print("== the first push merges ==")
|
||||||
|
before = target.read_text()
|
||||||
|
j = wait(c, c.post(f"/api/exports/{gig['id']}/push", json={}).json()["id"])
|
||||||
|
check("the push runs", j["state"] == "done", str(j.get("error")))
|
||||||
|
check("each copy is its source, byte for byte",
|
||||||
|
all(copy_of(f).is_file() and sha(copy_of(f)) == sha(f) for f in files[:3]))
|
||||||
|
after = target.read_text()
|
||||||
|
gone = removed_lines(before, after)
|
||||||
|
check("nothing of the user's changed: only the entry count and the root folder's count",
|
||||||
|
all("<COLLECTION ENTRIES=" in l or "SUBNODES COUNT=" in l for l in gone), "\n".join(gone[:5]))
|
||||||
|
entries = pushed(target)
|
||||||
|
check("three entries in the shared folder", set(entries) == {"track0.mp3", "track1.mp3", "track2.mp3"},
|
||||||
|
str(list(entries)))
|
||||||
|
tree = top_level(target)
|
||||||
|
folder = tree.get("Gig")
|
||||||
|
names = {n.name for n in folder.children} if folder else set()
|
||||||
|
check("the set's folder holds its playlist and Other", names == {"Peak", "Other"}, str(names))
|
||||||
|
tk = TraktorAdapter(target)
|
||||||
|
tid = next(t.id for t in tk.tracks if t.title == "Track 0")
|
||||||
|
cues = tk.track_cues(tid)
|
||||||
|
check("the cue and grid crossed, the grid locked",
|
||||||
|
any(c_.slot == 0 and c_.name == "Drop" for c_ in cues.cues) and len(cues.grid_markers) == 1
|
||||||
|
and cues.grid_locked, str(cues))
|
||||||
|
check("the push is in the collection's version history",
|
||||||
|
len(history.list_history(target)) >= 2, str(history.list_history(target)))
|
||||||
|
|
||||||
|
print("== an unchanged re-push writes nothing ==")
|
||||||
|
stamp = target.stat().st_mtime_ns
|
||||||
|
inodes = {f.name: copy_of(f).stat().st_ino for f in files[:3]}
|
||||||
|
pv = c.post(f"/api/exports/{gig['id']}/push/preview", json={}).json()
|
||||||
|
check("the preview: three already there", (pv["targets"][0]["add"], pv["targets"][0]["already"]) == (0, 3)
|
||||||
|
and pv["unchanged"] == 3, str(pv))
|
||||||
|
j = wait(c, c.post(f"/api/exports/{gig['id']}/push", json={}).json()["id"])
|
||||||
|
check("nothing copied", j["state"] == "done" and j["result"]["copied"] == 0, str(j.get("result")))
|
||||||
|
check("…the same files, and the collection not saved",
|
||||||
|
{f.name: copy_of(f).stat().st_ino for f in files[:3]} == inodes and target.stat().st_mtime_ns == stamp)
|
||||||
|
|
||||||
|
print("== the source wins ==")
|
||||||
|
adapter.set_cue(ids[0], slot=1, start_sec=2.0, cue_type="cue", name="Break")
|
||||||
|
adapter.set_track_metadata(ids[1], {"title": "Track 1 (edit)"})
|
||||||
|
j = wait(c, c.post(f"/api/exports/{gig['id']}/push", json={}).json()["id"])
|
||||||
|
tk = TraktorAdapter(target)
|
||||||
|
cues = tk.track_cues(tid)
|
||||||
|
check("the new cue reached the pushed entry, the old one kept, no duplicates",
|
||||||
|
j["state"] == "done" and sorted((c_.slot, c_.name) for c_ in cues.cues if c_.slot is not None)
|
||||||
|
== [(0, "Drop"), (1, "Break")], str(cues.cues))
|
||||||
|
check("the new title too", any(t.title == "Track 1 (edit)" for t in tk.tracks))
|
||||||
|
check("…and only those two were updated", j["result"]["targets"][0]["updated"] == 2, str(j["result"]))
|
||||||
|
|
||||||
|
print("== a re-levelled copy is swapped in ==")
|
||||||
|
prefs.update_prefs({"localNormalise": True, "localLevel": {"measure": "lufs", "target": -6.0, "ceiling": -0.5}})
|
||||||
|
j = wait(c, c.post(f"/api/exports/{gig['id']}/push", json={}).json()["id"])
|
||||||
|
check("the push runs", j["state"] == "done", str(j.get("error")))
|
||||||
|
changed = [f for f in files[:3] if sha(copy_of(f)) != sha(f)]
|
||||||
|
check("the copies changed level", j["result"]["normalised"] > 0 and changed, str(j.get("result")))
|
||||||
|
entries = pushed(target)
|
||||||
|
check("each entry's FILESIZE follows its new copy",
|
||||||
|
all(entries[f.name].info.filesize == round(copy_of(f).stat().st_size / 1024) for f in files[:3]))
|
||||||
|
check("no temporary file left", not list(AUDIO.rglob("*.konduktor-partial")))
|
||||||
|
prefs.update_prefs({"localNormalise": False})
|
||||||
|
wait(c, c.post(f"/api/exports/{gig['id']}/push", json={}).json()["id"])
|
||||||
|
check("Normalise off: the source's own bytes back", all(sha(copy_of(f)) == sha(f) for f in files[:3]))
|
||||||
|
|
||||||
|
print("== a second set, sharing a track ==")
|
||||||
|
warm = c.post("/api/exports", json={"name": "Warmup", "kind": "computer", "targets": ["traktor"]}).json()
|
||||||
|
c.post(f"/api/exports/{warm['id']}/add", json={"track_ids": [ids[2], ids[3]]})
|
||||||
|
tk = TraktorAdapter(target)
|
||||||
|
tk.create_folder("Warmup") # the user's own folder, with the set's name
|
||||||
|
tk.save()
|
||||||
|
j = wait(c, c.post(f"/api/exports/{warm['id']}/push", json={}).json()["id"])
|
||||||
|
tree = top_level(target)
|
||||||
|
check("a user's folder with the set's name is left alone; the set's is suffixed",
|
||||||
|
j["state"] == "done" and "Warmup" in tree and "Warmup (Konduktor)" in tree
|
||||||
|
and not tree["Warmup"].children, str(list(tree)))
|
||||||
|
check("the shared track is one entry", sum(1 for n in pushed(target) if n == "track2.mp3") == 1
|
||||||
|
and len(pushed(target)) == 4, str(list(pushed(target))))
|
||||||
|
|
||||||
|
print("== removal follows the set ==")
|
||||||
|
c.post(f"/api/exports/{gig['id']}/remove", json={"track_ids": [ids[2]]})
|
||||||
|
c.put(f"/api/playlists/{pl}/entries", json={"track_ids": ids[:1]})
|
||||||
|
pv = c.post(f"/api/exports/{gig['id']}/push/preview", json={}).json()
|
||||||
|
check("the preview counts two to remove", pv["targets"][0]["remove"] == 2, str(pv["targets"]))
|
||||||
|
j = wait(c, c.post(f"/api/exports/{gig['id']}/push", json={}).json()["id"])
|
||||||
|
names = set(pushed(target))
|
||||||
|
check("track1 left the collection, track2 stays (Warmup holds it)",
|
||||||
|
j["state"] == "done" and "track1.mp3" not in names and "track2.mp3" in names, str(names))
|
||||||
|
check("track1's copy deleted, track2's kept",
|
||||||
|
not copy_of(files[1]).exists() and copy_of(files[2]).exists())
|
||||||
|
check("one removal reported", j["result"]["targets"][0]["removed"] == 1, str(j["result"]))
|
||||||
|
|
||||||
|
print("== a library missing on this computer is skipped, not a block ==")
|
||||||
|
# The set's targets are shared by every computer opening the library;
|
||||||
|
# this one has no rekordbox (its pref points at nothing).
|
||||||
|
c.patch(f"/api/exports/{gig['id']}", json={"targets": ["traktor", "rekordbox"]})
|
||||||
|
pv = c.post(f"/api/exports/{gig['id']}/push/preview", json={}).json()
|
||||||
|
by = {t["platform"]: t for t in pv["targets"]}
|
||||||
|
check("the preview runs, rekordbox skipped", pv["blocked"] is None and by["rekordbox"]["skipped"]
|
||||||
|
and by["rekordbox"]["blocked"] == "not_found" and not by["traktor"]["skipped"], str(pv))
|
||||||
|
RUNNING.add("rekordbox")
|
||||||
|
pv = c.post(f"/api/exports/{gig['id']}/push/preview", json={}).json()
|
||||||
|
check("a skipped library's app running blocks nothing", pv["blocked"] is None, str(pv))
|
||||||
|
RUNNING.clear()
|
||||||
|
j = wait(c, c.post(f"/api/exports/{gig['id']}/push", json={}).json()["id"])
|
||||||
|
check("the push runs into Traktor alone and names the skipped one", j["state"] == "done"
|
||||||
|
and [t["name"] for t in j["result"]["targets"]] == ["Traktor"]
|
||||||
|
and j["result"]["skipped_targets"] == ["Rekordbox"], str(j.get("error") or j["result"]))
|
||||||
|
c.patch(f"/api/exports/{gig['id']}", json={"targets": ["rekordbox"]})
|
||||||
|
pv = c.post(f"/api/exports/{gig['id']}/push/preview", json={}).json()
|
||||||
|
check("none of its libraries here blocks it", pv["blocked"] == "no_library_here", str(pv))
|
||||||
|
check("…and the run is refused", c.post(f"/api/exports/{gig['id']}/push", json={}).status_code == 409)
|
||||||
|
c.patch(f"/api/exports/{gig['id']}", json={"targets": ["traktor"]})
|
||||||
|
|
||||||
|
print("== refusals ==")
|
||||||
|
RUNNING.add("traktor")
|
||||||
|
pv = c.post(f"/api/exports/{gig['id']}/push/preview", json={}).json()
|
||||||
|
check("Traktor running blocks the push", pv["blocked"] == "app_running" and pv["targets"][0]["running"], str(pv))
|
||||||
|
check("…and the run is refused", c.post(f"/api/exports/{gig['id']}/push", json={}).status_code == 409)
|
||||||
|
RUNNING.clear()
|
||||||
|
prefs.update_prefs({"localLibraries": {"traktor": str(src)}})
|
||||||
|
libs = {l["platform"]: l for l in c.get("/api/local-libraries").json()["libraries"]}
|
||||||
|
check("the library open in Konduktor is never a target", libs["traktor"]["blocked"] == "open_in_konduktor",
|
||||||
|
str(libs["traktor"]))
|
||||||
|
wrong = ROOT / "not-a-collection.nml"
|
||||||
|
wrong.write_text("hello")
|
||||||
|
prefs.update_prefs({"localLibraries": {"traktor": str(wrong)}})
|
||||||
|
libs = {l["platform"]: l for l in c.get("/api/local-libraries").json()["libraries"]}
|
||||||
|
check("a file that is not a Traktor collection is unreadable", libs["traktor"]["blocked"] == "unreadable",
|
||||||
|
str(libs["traktor"]))
|
||||||
|
prefs.update_prefs({"localLibraries": {"traktor": str(target), "rekordbox": str(ROOT / "none" / "master.db")}})
|
||||||
|
|
||||||
|
print("== a failure mid-copy leaves the library and the folder as they were ==")
|
||||||
|
c.post(f"/api/exports/{gig['id']}/add", json={"track_ids": [ids[4]]})
|
||||||
|
real_write = local_push.write_copy
|
||||||
|
|
||||||
|
def broken(adapter_, planned, partial, handle, advance):
|
||||||
|
partial.write_bytes(b"half")
|
||||||
|
raise OSError("disk unplugged")
|
||||||
|
|
||||||
|
local_push.write_copy = broken
|
||||||
|
before = target.read_bytes()
|
||||||
|
j = wait(c, c.post(f"/api/exports/{gig['id']}/push", json={}).json()["id"])
|
||||||
|
local_push.write_copy = real_write
|
||||||
|
check("the push fails", j["state"] == "failed", str(j))
|
||||||
|
check("…the collection untouched, no file placed",
|
||||||
|
target.read_bytes() == before and not copy_of(files[4]).exists()
|
||||||
|
and not list(AUDIO.rglob("*.konduktor-partial")))
|
||||||
|
|
||||||
|
print("== overwrite ==")
|
||||||
|
c.patch(f"/api/exports/{warm['id']}", json={"mode": "overwrite"})
|
||||||
|
pv = c.post(f"/api/exports/{warm['id']}/push/preview", json={}).json()
|
||||||
|
check("the preview names the set it removes", pv["targets"][0]["wipes_sets"] == ["Gig"], str(pv["targets"]))
|
||||||
|
j = wait(c, c.post(f"/api/exports/{warm['id']}/push", json={}).json()["id"])
|
||||||
|
check("the overwrite runs", j["state"] == "done", str(j.get("error")))
|
||||||
|
st = TraktorStore(target)
|
||||||
|
check("the collection holds only Warmup's two tracks", len(st._nml.collection.entry) == 2
|
||||||
|
and set(pushed(target)) == {"track2.mp3", "track3.mp3"}, str(len(st._nml.collection.entry)))
|
||||||
|
tree = top_level(target)
|
||||||
|
check("…in its folder", set(tree) == {"Warmup"}, str(list(tree)))
|
||||||
|
check("Gig's own file is deleted, Warmup's kept",
|
||||||
|
not copy_of(files[0]).exists() and copy_of(files[2]).exists() and copy_of(files[3]).exists())
|
||||||
|
check("the replaced collection is in the version history",
|
||||||
|
len(history.list_history(target)) >= 3)
|
||||||
|
pv = c.post(f"/api/exports/{gig['id']}/push/preview", json={}).json()
|
||||||
|
check("Gig is forgotten there: every track to add again",
|
||||||
|
pv["targets"][0]["already"] == 0 and pv["targets"][0]["add"] == pv["pushable"], str(pv["targets"]))
|
||||||
|
c.patch(f"/api/exports/{warm['id']}", json={"mode": "merge"})
|
||||||
|
pv = c.post(f"/api/exports/{warm['id']}/push/preview", json={}).json()
|
||||||
|
check("a merge after the overwrite finds Warmup's tracks", pv["targets"][0]["already"] == 2, str(pv["targets"]))
|
||||||
|
|
||||||
|
# ---- rekordbox, when installed --------------------------------------------------
|
||||||
|
from konduktor.adapters.rekordbox import discovery as rb_discovery
|
||||||
|
|
||||||
|
found = rb_discovery.detect_libraries()
|
||||||
|
if not found:
|
||||||
|
print("== rekordbox: not installed here, skipped ==")
|
||||||
|
else:
|
||||||
|
from konduktor.adapters.rekordbox.adapter import RekordboxAdapter
|
||||||
|
from konduktor.core.adapter import Unsupported
|
||||||
|
|
||||||
|
print("== rekordbox: merge ==")
|
||||||
|
rb_dir = ROOT / "rekordbox"
|
||||||
|
rb_dir.mkdir()
|
||||||
|
real_db = Path(found[0]["path"])
|
||||||
|
for name in ("master.db", "masterPlaylists6.xml"):
|
||||||
|
if (real_db.parent / name).is_file():
|
||||||
|
shutil.copy2(real_db.parent / name, rb_dir / name)
|
||||||
|
rb = rb_dir / "master.db"
|
||||||
|
probe = RekordboxAdapter(rb)
|
||||||
|
synced, count = probe.capabilities().readonly_cause == "cloud_synced", len(probe.tracks)
|
||||||
|
probe.close()
|
||||||
|
if synced:
|
||||||
|
print(" (the local rekordbox library is cloud-synced: checking it is refused)")
|
||||||
|
prefs.update_prefs({"localLibraries": {"traktor": str(target), "rekordbox": str(rb)}})
|
||||||
|
rbset = c.post("/api/exports", json={"name": "RB Gig", "kind": "computer", "targets": ["rekordbox"]}).json()
|
||||||
|
c.post(f"/api/exports/{rbset['id']}/add", json={"track_ids": ids[:2]})
|
||||||
|
pv = c.post(f"/api/exports/{rbset['id']}/push/preview", json={}).json()
|
||||||
|
if synced:
|
||||||
|
check("a cloud-synced library is refused", pv["blocked"] == "target_unavailable"
|
||||||
|
and pv["targets"][0]["blocked"] == "cloud_synced", str(pv))
|
||||||
|
else:
|
||||||
|
j = wait(c, c.post(f"/api/exports/{rbset['id']}/push", json={}).json()["id"])
|
||||||
|
check("the push runs", j["state"] == "done", str(j.get("error")))
|
||||||
|
ad = RekordboxAdapter(rb)
|
||||||
|
mine = [t for t in ad.tracks if t.filepath and str(AUDIO) in t.filepath]
|
||||||
|
tree = {n.name: n for n in ad.playlist_tree()}
|
||||||
|
tid = next((t.id for t in mine if t.title == "Track 0"), None)
|
||||||
|
cues = ad.track_cues(tid) if tid else None
|
||||||
|
ad.close()
|
||||||
|
check("two tracks added beside the user's", len(mine) == 2, str([t.title for t in mine]))
|
||||||
|
check("the set's folder", "RB Gig" in tree, str(list(tree)))
|
||||||
|
check("the cues crossed", cues is not None and any(c_.slot == 0 for c_ in cues.cues), str(cues))
|
||||||
|
backups = list((paths.app_data_dir() / "local_push" / "backups" / "rekordbox").iterdir())
|
||||||
|
check("the library was backed up first", backups and (backups[0] / "master.db").is_file())
|
||||||
|
|
||||||
|
print("== rekordbox: a track it will not remove is kept and reported ==")
|
||||||
|
real_remove = RekordboxAdapter.remove_tracks
|
||||||
|
|
||||||
|
def refuse(self, track_ids):
|
||||||
|
raise Unsupported("“Track 1” is in a History list in Rekordbox")
|
||||||
|
|
||||||
|
RekordboxAdapter.remove_tracks = refuse
|
||||||
|
c.post(f"/api/exports/{rbset['id']}/remove", json={"track_ids": [ids[1]]})
|
||||||
|
j = wait(c, c.post(f"/api/exports/{rbset['id']}/push", json={}).json()["id"])
|
||||||
|
RekordboxAdapter.remove_tracks = real_remove
|
||||||
|
res = j.get("result") or {}
|
||||||
|
check("the push still completes, reporting the kept track",
|
||||||
|
j["state"] == "done" and res["targets"][0]["kept"], str(j.get("error") or res))
|
||||||
|
check("…whose file stays", copy_of(files[1]).exists())
|
||||||
|
j = wait(c, c.post(f"/api/exports/{rbset['id']}/push", json={}).json()["id"])
|
||||||
|
ad = RekordboxAdapter(rb)
|
||||||
|
left = [t for t in ad.tracks if t.filepath and str(AUDIO) in t.filepath]
|
||||||
|
ad.close()
|
||||||
|
check("the next push removes it", j["state"] == "done" and len(left) == 1, str([t.title for t in left]))
|
||||||
|
|
||||||
|
print("== rekordbox: overwrite ==")
|
||||||
|
(rb_dir / "master.db-wal").write_bytes(b"stale")
|
||||||
|
c.patch(f"/api/exports/{rbset['id']}", json={"mode": "overwrite"})
|
||||||
|
j = wait(c, c.post(f"/api/exports/{rbset['id']}/push", json={}).json()["id"])
|
||||||
|
check("the overwrite runs", j["state"] == "done", str(j.get("error")))
|
||||||
|
ad = RekordboxAdapter(rb)
|
||||||
|
titles = [t.title for t in ad.tracks]
|
||||||
|
tree = [n.name for n in ad.playlist_tree()]
|
||||||
|
ad.close()
|
||||||
|
check("the library holds only the set", titles == ["Track 0"], f"{count} -> {titles}")
|
||||||
|
check("…in its folder", tree == ["RB Gig"], str(tree))
|
||||||
|
check("the stale WAL is gone", not (rb_dir / "master.db-wal").exists())
|
||||||
|
|
||||||
|
print("== the ledger and sets survive as plain data ==")
|
||||||
|
sets = {s["name"]: s for s in c.get("/api/exports").json()}
|
||||||
|
check("kind and mode persist", sets["Warmup"]["kind"] == "computer" and sets["Warmup"]["mode"] == "merge")
|
||||||
|
|
||||||
|
shutil.rmtree(ROOT, ignore_errors=True)
|
||||||
|
print()
|
||||||
|
print("RESULT:", "SOME FAILED" if failed else "ALL PASSED")
|
||||||
|
raise SystemExit(1 if failed else 0)
|
||||||
@@ -204,6 +204,25 @@ check("an index past the end appends", after[-1] == more[1])
|
|||||||
check("capabilities say Traktor holds duplicates",
|
check("capabilities say Traktor holds duplicates",
|
||||||
client.get("/api/capabilities").json()["playlists"]["duplicates"] is True)
|
client.get("/api/capabilities").json()["playlists"]["duplicates"] is True)
|
||||||
|
|
||||||
|
before = [t["id"] for t in client.get(f"/api/playlists/{target}/tracks").json()]
|
||||||
|
outsider = next(t["id"] for t in client.get("/api/tracks", params={"limit": 50}).json()["items"]
|
||||||
|
if t["id"] not in before)
|
||||||
|
picked = [first[0], rest[0], outsider] # first[0] is in there twice
|
||||||
|
r = client.post(f"/api/playlists/{target}/remove",
|
||||||
|
json={"track_ids": picked, "dry_run": True}).json()
|
||||||
|
check("a dry-run remove counts tracks held and entries (both copies) and changes nothing",
|
||||||
|
r["tracks"] == 2 and r["removed"] == 3
|
||||||
|
and [t["id"] for t in client.get(f"/api/playlists/{target}/tracks").json()] == before)
|
||||||
|
r = client.post(f"/api/playlists/{target}/remove", json={"track_ids": picked}).json()
|
||||||
|
after = [t["id"] for t in client.get(f"/api/playlists/{target}/tracks").json()]
|
||||||
|
check("remove drops every copy and keeps the rest in order",
|
||||||
|
r["removed"] == 3 and r["count"] == len(before) - 3
|
||||||
|
and after == [t for t in before if t not in picked])
|
||||||
|
r = client.post(f"/api/playlists/{target}/remove", json={"track_ids": [outsider]}).json()
|
||||||
|
check("removing tracks it does not hold changes nothing", r["removed"] == 0 and r["count"] == len(after))
|
||||||
|
check("remove from an unknown playlist is a 404",
|
||||||
|
client.post("/api/playlists/nope/remove", json={"track_ids": picked}).status_code == 404)
|
||||||
|
|
||||||
box = client.post("/api/playlists/folders", json={"name": "Konduktor Drop Box"}).json()["id"]
|
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})
|
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)
|
check("move answers the playlist's id", r.status_code == 200 and r.json()["id"] == target)
|
||||||
|
|||||||
@@ -263,6 +263,34 @@ with tempfile.TemporaryDirectory() as d:
|
|||||||
check("set_analysed_grid pairs the marker with a companion",
|
check("set_analysed_grid pairs the marker with a companion",
|
||||||
cues.grid_markers[0].companion is not None)
|
cues.grid_markers[0].companion is not None)
|
||||||
|
|
||||||
|
# ---- replace_cues: a pushed track brought up to date ------------------------
|
||||||
|
print("== replace_cues makes the prep exactly the given one ==")
|
||||||
|
with tempfile.TemporaryDirectory() as d:
|
||||||
|
from konduktor.core.model import CuePoint, GridMarker, TrackCues # noqa: E402
|
||||||
|
|
||||||
|
work = Path(d) / "collection.nml"
|
||||||
|
shutil.copy2(REAL, work)
|
||||||
|
adapter = TraktorAdapter(work)
|
||||||
|
# A real entry carrying a grid WITH its white companion, hot cues and a lock.
|
||||||
|
tid = next(t.id for t in adapter.tracks
|
||||||
|
if t.grid_marker_count == 1 and t.hotcue_count >= 2
|
||||||
|
and adapter.track_cues(t.id).grid_markers[0].companion is not None)
|
||||||
|
want = TrackCues(
|
||||||
|
grid_markers=[GridMarker(start=0.25, bpm=124.0)], grid_locked=False,
|
||||||
|
cues=[CuePoint(start=4.0, length=0.0, slot=2, name="Drop"),
|
||||||
|
CuePoint(start=8.0, length=2.0, slot=3, type="loop"),
|
||||||
|
CuePoint(start=12.0, length=0.0, role="memory", name="Mem")])
|
||||||
|
got = adapter.replace_cues(tid, want)
|
||||||
|
check("the grid is exactly the new one, no companion invented",
|
||||||
|
[(m.start, m.bpm, m.companion) for m in got.grid_markers] == [(0.25, 124.0, None)],
|
||||||
|
str(got.grid_markers))
|
||||||
|
check("only the given cues remain, on their pads, the memory cue as one",
|
||||||
|
sorted((c.slot, c.role, c.name) for c in got.cues if c.slot is not None) == [(2, "hotcue", "Drop"), (3, "hotcue", None)]
|
||||||
|
and [c.name for c in got.cues if c.role == "memory"] == ["Mem"], str(got.cues))
|
||||||
|
again = adapter.replace_cues(tid, want)
|
||||||
|
check("replacing with the same prep is stable",
|
||||||
|
[(c.slot, c.start, c.role) for c in again.cues] == [(c.slot, c.start, c.role) for c in got.cues])
|
||||||
|
|
||||||
# ---- remap rebuilds the index (track ids change) --------------------------
|
# ---- remap rebuilds the index (track ids change) --------------------------
|
||||||
print("== a path remap rebuilds the projection, because track ids change ==")
|
print("== a path remap rebuilds the projection, because track ids change ==")
|
||||||
with tempfile.TemporaryDirectory() as d:
|
with tempfile.TemporaryDirectory() as d:
|
||||||
|
|||||||
@@ -0,0 +1,353 @@
|
|||||||
|
"""Traktor's own block inside an audio file — removed from every copy made for a
|
||||||
|
Traktor library, so Traktor cannot restore its stale grid over the entry's.
|
||||||
|
|
||||||
|
Measured in Traktor 4.5 (2026-10-24, see `adapters/traktor/file_block.py`): an
|
||||||
|
entry Konduktor wrote has no MODIFIED_DATE, so Traktor re-reads the file and
|
||||||
|
takes the block's BPM (`HBPM`) over the collection's, LOCK or not. With the
|
||||||
|
block removed from the copy, the entry's grid, lock, cues — and the art, which
|
||||||
|
Traktor still imports from the file's ordinary tags — all survive.
|
||||||
|
|
||||||
|
Self-contained: generated audio in each format carrying a block that says 175
|
||||||
|
while the library's grid says 176, and collections built from Konduktor's own
|
||||||
|
empty Traktor skeleton. Pins:
|
||||||
|
- `file_block`: each format's block found and removed, everything else in
|
||||||
|
the file kept (audio sample-identical, other tags, a foreign PRIV frame),
|
||||||
|
a file without one never rewritten, a garbage file refused quietly;
|
||||||
|
- export: every copy for a Traktor target loses the block, the SOURCE keeps
|
||||||
|
it, the manifest records `prepared`, a re-export rewrites nothing, a copy
|
||||||
|
kept from an export made before this (no `prepared`) is cleaned IN PLACE
|
||||||
|
rather than copied again, a target without the hook leaves the block, and
|
||||||
|
adding Traktor to such a set cleans the kept copies;
|
||||||
|
- local push: the shared folder's copies lose it, the ledger records it;
|
||||||
|
- import: a copied file loses it, a file added in place is never touched.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import struct
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-fileblock-appdata-")
|
||||||
|
os.environ.pop("KONDUKTOR_NML", None)
|
||||||
|
|
||||||
|
import av # noqa: E402
|
||||||
|
import numpy as np # noqa: E402
|
||||||
|
import soundfile as sf # noqa: E402
|
||||||
|
from mutagen import File as MutagenFile # noqa: E402
|
||||||
|
from mutagen.flac import FLAC # noqa: E402
|
||||||
|
from mutagen.id3 import APIC, ID3, PRIV, TIT2 # noqa: E402
|
||||||
|
from mutagen.mp4 import MP4, MP4Cover # noqa: E402
|
||||||
|
|
||||||
|
from konduktor import exporter, exports, importer, local_push, prefs # noqa: E402
|
||||||
|
from konduktor.adapters.traktor import file_block # noqa: E402
|
||||||
|
from konduktor.adapters.traktor.adapter import TraktorAdapter # noqa: E402
|
||||||
|
from konduktor.adapters.traktor.export import SKELETON # noqa: E402
|
||||||
|
from konduktor.app_state import STATE # noqa: E402
|
||||||
|
from konduktor.core import apps_running, pyav # noqa: E402
|
||||||
|
from konduktor.core import export as core_export # noqa: E402
|
||||||
|
from konduktor.core.export import ExportPayload, ExportTrack # noqa: E402
|
||||||
|
from konduktor.core.model import GridMarker, Track, TrackCues # noqa: E402
|
||||||
|
from konduktor.exporter import _read_manifest as read_manifest # noqa: E402
|
||||||
|
from konduktor.jobs import JOBS # noqa: E402
|
||||||
|
|
||||||
|
failed = False
|
||||||
|
ROOT = Path(tempfile.mkdtemp(prefix="konduktor-fileblock-"))
|
||||||
|
def _jpeg() -> bytes:
|
||||||
|
import io
|
||||||
|
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
buf = io.BytesIO()
|
||||||
|
Image.new("RGB", (8, 8), (200, 40, 90)).save(buf, "JPEG")
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
JPEG = _jpeg() # a real (tiny) cover, so the exporters read it
|
||||||
|
|
||||||
|
|
||||||
|
def check(label, cond, detail=""):
|
||||||
|
global failed
|
||||||
|
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
|
||||||
|
if not cond:
|
||||||
|
failed = True
|
||||||
|
|
||||||
|
|
||||||
|
# ---- generated audio, each carrying a block that says 175 BPM ------------------------
|
||||||
|
|
||||||
|
def block(bpm: float) -> bytes:
|
||||||
|
"""A minimal `DMRT` tree as Traktor writes it: reversed 4CCs, each chunk
|
||||||
|
= name + payload size + child count + payload."""
|
||||||
|
def chunk(name: str, payload: bytes, children: int = 0) -> bytes:
|
||||||
|
return name[::-1].encode() + struct.pack("<II", len(payload), children) + payload
|
||||||
|
data = chunk("DATA", chunk("HBPM", struct.pack("<f", bpm)), 1)
|
||||||
|
hdr = chunk("HDR ", chunk("VRSN", struct.pack("<I", 7)), 1)
|
||||||
|
return chunk("DMRT", hdr + data, 2)
|
||||||
|
|
||||||
|
|
||||||
|
def music(seconds=6, sr=44100, seed=0):
|
||||||
|
t = np.arange(int(sr * seconds)) / sr
|
||||||
|
rng = np.random.default_rng(seed)
|
||||||
|
beat = (np.sin(2 * np.pi * 2 * t) > 0.6).astype(float)
|
||||||
|
return np.vstack([0.3 * (0.5 * np.sin(2 * np.pi * 90 * t) * beat + 0.2 * rng.standard_normal(t.size))
|
||||||
|
for _ in range(2)]).astype(np.float32)
|
||||||
|
|
||||||
|
|
||||||
|
def encode(path: Path, fmt: str, codec: str, frame: int, seed: int):
|
||||||
|
x = music(seed=seed)
|
||||||
|
with av.open(str(path), "w", format=fmt) as c:
|
||||||
|
s = c.add_stream(codec, rate=44100, layout="stereo")
|
||||||
|
s.bit_rate = 192_000
|
||||||
|
for o in range(0, x.shape[1], frame):
|
||||||
|
f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, o:o + frame]), format="fltp", layout="stereo")
|
||||||
|
f.sample_rate, f.pts = 44100, o
|
||||||
|
for p in s.encode(f):
|
||||||
|
c.mux(p)
|
||||||
|
for p in s.encode(None):
|
||||||
|
c.mux(p)
|
||||||
|
|
||||||
|
|
||||||
|
def make(path: Path, seed: int, *, with_block: bool = True) -> Path:
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
ext = path.suffix
|
||||||
|
if ext == ".mp3":
|
||||||
|
encode(path, "mp3", "libmp3lame", 1152, seed)
|
||||||
|
tags = ID3()
|
||||||
|
tags.add(TIT2(encoding=3, text=path.stem))
|
||||||
|
tags.add(APIC(encoding=3, mime="image/jpeg", type=3, desc="", data=JPEG))
|
||||||
|
tags.add(PRIV(owner="SomeOtherApp", data=b"keep me"))
|
||||||
|
if with_block:
|
||||||
|
tags.add(PRIV(owner="TRAKTOR4", data=block(175.0)))
|
||||||
|
tags.save(path, v2_version=3)
|
||||||
|
elif ext == ".m4a":
|
||||||
|
encode(path, "ipod", "aac", 1024, seed)
|
||||||
|
m = MP4(path)
|
||||||
|
if m.tags is None:
|
||||||
|
m.add_tags()
|
||||||
|
m.tags["\xa9nam"] = [path.stem]
|
||||||
|
m.tags["covr"] = [MP4Cover(JPEG, imageformat=MP4Cover.FORMAT_JPEG)]
|
||||||
|
m.save()
|
||||||
|
if with_block:
|
||||||
|
m = MP4(path)
|
||||||
|
# As Traktor writes it: an atom mutagen cannot parse, kept raw.
|
||||||
|
m.tags._failed_atoms["NITR"] = [b"\x00\x00\x00\x08NTKB" + b"\x00" * 4 + block(175.0)]
|
||||||
|
m.save()
|
||||||
|
elif ext == ".flac":
|
||||||
|
sf.write(str(path), music(seed=seed).T, 44100, subtype="PCM_16")
|
||||||
|
f = FLAC(path)
|
||||||
|
f["title"] = path.stem
|
||||||
|
if with_block:
|
||||||
|
f["traktor4"] = base64.b64encode(block(175.0)).decode()
|
||||||
|
f.save()
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
def pcm(path: Path) -> list[np.ndarray]:
|
||||||
|
out = []
|
||||||
|
with pyav.open_input(str(path)) as c:
|
||||||
|
for s in c.streams.audio:
|
||||||
|
c.seek(0)
|
||||||
|
out.append(np.concatenate([f.to_ndarray().ravel() for f in c.decode(s)]))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def tag_keys(path: Path) -> set[str]:
|
||||||
|
tags = MutagenFile(path).tags
|
||||||
|
return set(tags.keys()) | set(getattr(tags, "_failed_atoms", {}))
|
||||||
|
|
||||||
|
|
||||||
|
print("== file_block on each format ==")
|
||||||
|
unit = ROOT / "unit"
|
||||||
|
for name in ("a.mp3", "b.m4a", "c.flac"):
|
||||||
|
src = make(unit / "src" / name, seed=1)
|
||||||
|
copy = unit / "copy" / (name + ".konduktor-partial") # as the runners strip it
|
||||||
|
copy.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copy2(src, copy)
|
||||||
|
before = tag_keys(copy)
|
||||||
|
check(f"{name}: the block is found", file_block.has_block(copy))
|
||||||
|
check(f"{name}: strip reports it removed one", file_block.strip(copy) is True)
|
||||||
|
check(f"{name}: none is left", not file_block.has_block(copy))
|
||||||
|
lost = before - tag_keys(copy)
|
||||||
|
check(f"{name}: only the block is gone from the tags",
|
||||||
|
len(lost) == 1 and ("TRAKTOR4" in next(iter(lost)) or next(iter(lost)) in ("NITR", "traktor4")),
|
||||||
|
str(lost))
|
||||||
|
check(f"{name}: the audio is sample-identical",
|
||||||
|
all(np.array_equal(a, b) for a, b in zip(pcm(src), pcm(copy))))
|
||||||
|
data, mtime = copy.read_bytes(), copy.stat().st_mtime_ns
|
||||||
|
check(f"{name}: a second strip changes nothing, and does not rewrite the file",
|
||||||
|
file_block.strip(copy) is False and copy.read_bytes() == data and copy.stat().st_mtime_ns == mtime)
|
||||||
|
mp3 = unit / "copy" / "a.mp3.konduktor-partial"
|
||||||
|
id3 = ID3(mp3)
|
||||||
|
check("mp3: a foreign PRIV frame and the cover stay", "PRIV:SomeOtherApp:keep me" in id3 and id3.getall("APIC"))
|
||||||
|
check("mp3: the file keeps its ID3 version (2.3)", id3.version[:2] == (2, 3))
|
||||||
|
check("m4a: the cover stays", "covr" in MP4(unit / "copy" / "b.m4a.konduktor-partial").tags)
|
||||||
|
clean = make(unit / "clean.mp3", seed=2, with_block=False)
|
||||||
|
data, mtime = clean.read_bytes(), clean.stat().st_mtime_ns
|
||||||
|
check("a file without a block is never rewritten",
|
||||||
|
file_block.strip(clean) is False and clean.read_bytes() == data and clean.stat().st_mtime_ns == mtime)
|
||||||
|
junk = unit / "junk.mp3"
|
||||||
|
junk.write_bytes(b"ID3" + b"\xff" * 64)
|
||||||
|
check("an unreadable file is refused quietly", file_block.strip(junk) is False and not file_block.has_block(junk))
|
||||||
|
|
||||||
|
|
||||||
|
# ---- a source library whose grids (176) disagree with the files' blocks (175) ---------
|
||||||
|
|
||||||
|
lib_root = ROOT / "MyMusic"
|
||||||
|
files = [make(lib_root / "DnB" / n, seed=i) for i, n in enumerate(("one.mp3", "two.m4a", "three.flac"))]
|
||||||
|
files.append(make(lib_root / "DnB" / "plain.mp3", seed=9, with_block=False))
|
||||||
|
seed = []
|
||||||
|
for i, path in enumerate(files):
|
||||||
|
track = Track(id=f"seed{i}", title=path.stem, artist="Test")
|
||||||
|
cues = TrackCues(grid_markers=[GridMarker(start=0.25, bpm=176.0)], grid_locked=True)
|
||||||
|
seed.append(ExportTrack(track=track, destination=path, cues=cues))
|
||||||
|
core_export.for_platform("traktor").write(
|
||||||
|
ExportPayload(name="Source", tracks=seed, playlists=[], root_folder=True), lib_root)
|
||||||
|
source_bytes = {p: p.read_bytes() for p in files}
|
||||||
|
STATE.open(lib_root / "collection.nml")
|
||||||
|
ad = STATE.adapter
|
||||||
|
LIB = STATE.library_id
|
||||||
|
ids = [t.id for t in ad.tracks]
|
||||||
|
check("the source library holds the four tracks", len(ids) == 4, str(ids))
|
||||||
|
|
||||||
|
|
||||||
|
def run_job(kind, fn):
|
||||||
|
job = JOBS.submit(kind, fn)
|
||||||
|
while not job.finished:
|
||||||
|
time.sleep(0.02)
|
||||||
|
assert job.error is None, job.error
|
||||||
|
return job.result
|
||||||
|
|
||||||
|
|
||||||
|
def copies(dest: Path) -> dict[str, Path]:
|
||||||
|
return {p.name: p for p in (dest / "Contents").rglob("*") if p.is_file() and not p.name.startswith(".")}
|
||||||
|
|
||||||
|
|
||||||
|
def records(dest: Path) -> dict[str, dict]:
|
||||||
|
return {Path(rel).name: r for rel, r in (read_manifest(dest).get("audio") or {}).items()}
|
||||||
|
|
||||||
|
|
||||||
|
def bpms(nml: Path) -> dict[str, float]:
|
||||||
|
a = TraktorAdapter(nml)
|
||||||
|
return {Path(a.audio_path(t.id)).name: a.track_cues(t.id).grid_markers[0].bpm for t in a.tracks}
|
||||||
|
|
||||||
|
|
||||||
|
print("== an export to Traktor ==")
|
||||||
|
dest = ROOT / "GIG"
|
||||||
|
gig = exports.create(LIB, name="GIG", targets=["traktor"], destination=str(dest))
|
||||||
|
exports.add(LIB, gig.id, track_ids=ids)
|
||||||
|
gig = exports.get(LIB, gig.id)
|
||||||
|
run_job("export", lambda h: exporter.run(ad, gig, exporter.plan(ad, gig), h))
|
||||||
|
out = copies(dest)
|
||||||
|
check("every track was copied", set(out) == {p.name for p in files}, str(sorted(out)))
|
||||||
|
check("no copy carries Traktor's block", not any(file_block.has_block(p) for p in out.values()))
|
||||||
|
check("the SOURCE files are untouched", all(p.read_bytes() == b for p, b in source_bytes.items()))
|
||||||
|
check("a file that had no block is copied byte for byte", out["plain.mp3"].read_bytes() == source_bytes[files[3]])
|
||||||
|
check("the covers are still in the copies",
|
||||||
|
ID3(out["one.mp3"]).getall("APIC") and "covr" in MP4(out["two.m4a"]).tags)
|
||||||
|
recs = records(dest)
|
||||||
|
check("the manifest records each copy as prepared for Traktor",
|
||||||
|
all(r.get("prepared") == ["traktor"] for r in recs.values()), str(recs))
|
||||||
|
check("and records the copy's size as it is now (after the strip)",
|
||||||
|
all(r["copy_size"] == out[n].stat().st_size for n, r in recs.items()))
|
||||||
|
check("the exported grids are the library's (176)", all(abs(b - 176.0) < 0.01 for b in bpms(dest / "collection.nml").values()))
|
||||||
|
|
||||||
|
print("== a re-export rewrites nothing ==")
|
||||||
|
stamp = {n: (p.stat().st_ino, p.stat().st_mtime_ns) for n, p in out.items()}
|
||||||
|
run_job("export", lambda h: exporter.run(ad, gig, exporter.plan(ad, gig), h))
|
||||||
|
check("every copy kept as it was (same inode, same mtime)",
|
||||||
|
{n: (p.stat().st_ino, p.stat().st_mtime_ns) for n, p in copies(dest).items()} == stamp)
|
||||||
|
|
||||||
|
print("== a copy kept from an export made before this fix is cleaned in place ==")
|
||||||
|
# Put the block back into one copy and drop `prepared`, as an older export's
|
||||||
|
# manifest and stick would be — the record matching the file, so it is kept.
|
||||||
|
old_copy = copies(dest)["one.mp3"]
|
||||||
|
tags = ID3(old_copy)
|
||||||
|
tags.add(PRIV(owner="TRAKTOR4", data=block(175.0)))
|
||||||
|
tags.save(old_copy, v2_version=3)
|
||||||
|
manifest = read_manifest(dest)
|
||||||
|
for rel, r in manifest["audio"].items():
|
||||||
|
r.pop("prepared", None)
|
||||||
|
if Path(rel).name == "one.mp3":
|
||||||
|
st = old_copy.stat()
|
||||||
|
r["copy_size"], r["copy_mtime_ns"] = st.st_size, st.st_mtime_ns
|
||||||
|
exporter.manifest_path(dest).write_text(json.dumps(manifest))
|
||||||
|
inode = old_copy.stat().st_ino
|
||||||
|
again = exporter.plan(ad, gig)
|
||||||
|
check("the old copy is planned as KEPT, not copied again",
|
||||||
|
next(t for t in again.exportable if t.destination.name == "one.mp3").reuse is not None)
|
||||||
|
run_job("export", lambda h: exporter.run(ad, gig, again, h))
|
||||||
|
cleaned = copies(dest)["one.mp3"]
|
||||||
|
check("its block is gone", not file_block.has_block(cleaned))
|
||||||
|
check("in place: the same file, not a new copy", cleaned.stat().st_ino == inode)
|
||||||
|
check("every record says prepared again", all(r.get("prepared") == ["traktor"] for r in records(dest).values()))
|
||||||
|
check("and the next export keeps it as it is",
|
||||||
|
next(t for t in exporter.plan(ad, gig).exportable if t.destination.name == "one.mp3").reuse is not None)
|
||||||
|
|
||||||
|
print("== a target without the hook leaves the block; adding Traktor cleans the kept copies ==")
|
||||||
|
pdest = ROOT / "PIONEER"
|
||||||
|
pio = exports.create(LIB, name="PIONEER", targets=["rekordbox_export"], destination=str(pdest))
|
||||||
|
exports.add(LIB, pio.id, track_ids=ids)
|
||||||
|
pio = exports.get(LIB, pio.id)
|
||||||
|
run_job("export", lambda h: exporter.run(ad, pio, exporter.plan(ad, pio), h))
|
||||||
|
pout = copies(pdest)
|
||||||
|
check("a Rekordbox Export's copies keep Traktor's block (none of its business)",
|
||||||
|
file_block.has_block(pout["one.mp3"]) and file_block.has_block(pout["two.m4a"]))
|
||||||
|
check("and are recorded as prepared by nobody", all(r.get("prepared") == [] for r in records(pdest).values()))
|
||||||
|
inodes = {n: p.stat().st_ino for n, p in pout.items()}
|
||||||
|
pio = exports.update(LIB, pio.id, targets=["rekordbox_export", "traktor"])
|
||||||
|
run_job("export", lambda h: exporter.run(ad, pio, exporter.plan(ad, pio), h))
|
||||||
|
pout = copies(pdest)
|
||||||
|
check("with Traktor added, no copy carries the block", not any(file_block.has_block(p) for p in pout.values()))
|
||||||
|
check("cleaned in place, none copied again", {n: p.stat().st_ino for n, p in pout.items()} == inodes)
|
||||||
|
check("recorded as prepared for Traktor", all(r.get("prepared") == ["traktor"] for r in records(pdest).values()))
|
||||||
|
|
||||||
|
print("== a local push into this computer's Traktor ==")
|
||||||
|
laptop = ROOT / "laptop" / "collection.nml"
|
||||||
|
laptop.parent.mkdir(parents=True)
|
||||||
|
laptop.write_text(SKELETON, encoding="utf-8")
|
||||||
|
AUDIO = ROOT / "LocalAudio"
|
||||||
|
apps_running.running = lambda platforms: set()
|
||||||
|
prefs.update_prefs({"localLibraries": {"traktor": str(laptop), "rekordbox": str(ROOT / "none" / "master.db")},
|
||||||
|
"localAudioRoot": str(AUDIO), "localNormalise": False})
|
||||||
|
push = exports.create(LIB, name="Push", targets=["traktor"], destination="", kind="computer", mode="merge")
|
||||||
|
exports.add(LIB, push.id, track_ids=ids)
|
||||||
|
push = exports.get(LIB, push.id)
|
||||||
|
built = local_push.plan(ad, push)
|
||||||
|
check("the push can run", built.blocked is None, str(built.blocked))
|
||||||
|
run_job("local-push", lambda h: local_push.run(ad, push, built, h))
|
||||||
|
pushed = {p.name: p for p in AUDIO.rglob("*") if p.is_file() and p.suffix in (".mp3", ".m4a", ".flac")}
|
||||||
|
check("every track's copy is in the shared folder", set(pushed) == {p.name for p in files}, str(sorted(pushed)))
|
||||||
|
check("none of them carries Traktor's block", not any(file_block.has_block(p) for p in pushed.values()))
|
||||||
|
ledger = local_push._read_ledger()["audio"][str(AUDIO)]
|
||||||
|
check("the ledger records them as prepared for Traktor",
|
||||||
|
all(r.get("prepared") == ["traktor"] for r in ledger.values()), str(ledger))
|
||||||
|
check("the laptop's collection has the library's grids (176)",
|
||||||
|
all(abs(b - 176.0) < 0.01 for b in bpms(laptop).values()), str(bpms(laptop)))
|
||||||
|
check("the SOURCE files are still untouched", all(p.read_bytes() == b for p, b in source_bytes.items()))
|
||||||
|
|
||||||
|
print("== an import into a Traktor collection ==")
|
||||||
|
into = ROOT / "into" / "collection.nml"
|
||||||
|
into.parent.mkdir(parents=True)
|
||||||
|
into.write_text(SKELETON, encoding="utf-8")
|
||||||
|
dest_ad = TraktorAdapter(into)
|
||||||
|
folder = ROOT / "into" / "Imported"
|
||||||
|
run_job("import", lambda h: importer.run(ad, dest_ad, importer.plan(ad, dest_ad, folder, track_ids=ids[:2]), h))
|
||||||
|
imported = [p for p in folder.rglob("*") if p.is_file()]
|
||||||
|
check("the copied files arrived", len(imported) == 2, str(imported))
|
||||||
|
check("and carry no block", imported and not any(file_block.has_block(p) for p in imported))
|
||||||
|
ref = ROOT / "ref" / "collection.nml"
|
||||||
|
ref.parent.mkdir(parents=True)
|
||||||
|
ref.write_text(SKELETON, encoding="utf-8")
|
||||||
|
ref_ad = TraktorAdapter(ref)
|
||||||
|
run_job("import", lambda h: importer.run(ad, ref_ad, importer.plan(ad, ref_ad, None, track_ids=ids[:2]), h,
|
||||||
|
reference=True))
|
||||||
|
check("a file added IN PLACE is never touched", all(p.read_bytes() == b for p, b in source_bytes.items()))
|
||||||
|
check("so it keeps its block (it is the user's file)", file_block.has_block(files[0]))
|
||||||
|
|
||||||
|
shutil.rmtree(ROOT, ignore_errors=True)
|
||||||
|
print("\nALL PASS" if not failed else "\nSOME CHECKS FAILED")
|
||||||
|
raise SystemExit(1 if failed else 0)
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "frontend",
|
"name": "frontend",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.3.3",
|
"version": "0.3.6",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
|
|||||||
@@ -368,6 +368,13 @@ export default function App() {
|
|||||||
nodes.flatMap((n) => [...(n.can_add_tracks ? [n] : []), ...walk(n.children)])
|
nodes.flatMap((n) => [...(n.can_add_tracks ? [n] : []), ...walk(n.children)])
|
||||||
return walk(playlists.data ?? [])
|
return walk(playlists.data ?? [])
|
||||||
}, [playlists.data])
|
}, [playlists.data])
|
||||||
|
// Every playlist Remove ▸ From playlist can take tracks out of: the same
|
||||||
|
// gate as removing from the open one (its entry list is rewritten).
|
||||||
|
const removablePlaylists = useMemo(() => {
|
||||||
|
const walk = (nodes: PlaylistNode[]): PlaylistNode[] =>
|
||||||
|
nodes.flatMap((n) => [...(n.can_reorder ? [n] : []), ...walk(n.children)])
|
||||||
|
return canEdit ? walk(playlists.data ?? []) : []
|
||||||
|
}, [playlists.data, canEdit])
|
||||||
|
|
||||||
// Export membership. Both are no-ops on the library itself, so neither dirties
|
// Export membership. Both are no-ops on the library itself, so neither dirties
|
||||||
// it nor touches version history — an export set is Konduktor's own data.
|
// it nor touches version history — an export set is Konduktor's own data.
|
||||||
@@ -1094,6 +1101,50 @@ export default function App() {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// Remove ▸ From playlist ▸ <name>: tracks picked anywhere leave a playlist
|
||||||
|
// that is not open — every copy of each. Counted first, so the dialog says
|
||||||
|
// how many of the selection it actually holds (and still answers at 0).
|
||||||
|
const confirmRemoveFromOther = async (p: PlaylistNode, ids: string[]) => {
|
||||||
|
let r
|
||||||
|
try {
|
||||||
|
r = await api.removeEntries(p.id, ids, true)
|
||||||
|
} catch (e) {
|
||||||
|
onError((e as Error).message)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const name = <span className="text-text">{p.name}</span>
|
||||||
|
const held = r.tracks
|
||||||
|
setConfirmReq({
|
||||||
|
title: 'Remove from playlist',
|
||||||
|
body: !held ? (
|
||||||
|
<p>
|
||||||
|
{ids.length === 1 ? <>{trackNoun(ids)} is not</> : <>None of these {ids.length} tracks are</>} in {name}.
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<p>
|
||||||
|
Remove {held === ids.length ? trackNoun(ids) : `${held} of the ${ids.length} selected tracks`} from {name}?
|
||||||
|
The {held === 1 ? 'track stays' : 'tracks stay'} in the collection.
|
||||||
|
</p>
|
||||||
|
{held < ids.length && (
|
||||||
|
<p className="text-faint">The other {nTracks(ids.length - held)} {ids.length - held === 1 ? 'is' : 'are'} not in it.</p>
|
||||||
|
)}
|
||||||
|
{r.removed > held && <p className="text-faint">Some are in it more than once; every copy goes.</p>}
|
||||||
|
</>
|
||||||
|
),
|
||||||
|
confirmLabel: held ? `Remove ${nTracks(held)}` : 'Remove',
|
||||||
|
confirmDisabled: !held,
|
||||||
|
onConfirm: () =>
|
||||||
|
guard(async () => {
|
||||||
|
const done = await api.removeEntries(p.id, ids)
|
||||||
|
qc.invalidateQueries({ queryKey: ['playlist', p.id] })
|
||||||
|
qc.invalidateQueries({ queryKey: ['playlists'] })
|
||||||
|
qc.invalidateQueries({ queryKey: ['state'] })
|
||||||
|
notify('success', `Removed ${nTracks(done.tracks)} from ${p.name}`)
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
const confirmRemoveFromExport = (exportId: string, ids: string[]) => {
|
const confirmRemoveFromExport = (exportId: string, ids: string[]) => {
|
||||||
const name = exportSets.data?.find((x) => x.id === exportId)?.name ?? 'this export'
|
const name = exportSets.data?.find((x) => x.id === exportId)?.name ?? 'this export'
|
||||||
setConfirmReq({
|
setConfirmReq({
|
||||||
@@ -1231,6 +1282,22 @@ export default function App() {
|
|||||||
...(playlistEditable
|
...(playlistEditable
|
||||||
? [{ label: 'From this playlist…', onClick: () => confirmRemoveFromPlaylist(ids) }]
|
? [{ label: 'From this playlist…', onClick: () => confirmRemoveFromPlaylist(ids) }]
|
||||||
: []),
|
: []),
|
||||||
|
// Any other editable playlist — "A minus B" is: open B, select all, here A.
|
||||||
|
...(() => {
|
||||||
|
// A device's ids mean nothing to the collection's playlists.
|
||||||
|
if (viewingDevice) return []
|
||||||
|
const lists = removablePlaylists.filter((p) => !(source.kind === 'playlist' && p.id === source.id))
|
||||||
|
return lists.length
|
||||||
|
? [{
|
||||||
|
label: 'From playlist',
|
||||||
|
submenu: lists.map((p) => ({
|
||||||
|
label: p.name,
|
||||||
|
hint: String(p.count),
|
||||||
|
onClick: () => void confirmRemoveFromOther(p, ids),
|
||||||
|
})),
|
||||||
|
}]
|
||||||
|
: []
|
||||||
|
})(),
|
||||||
// Only on the export's ROOT view. Inside a referenced playlist there is
|
// Only on the export's ROOT view. Inside a referenced playlist there is
|
||||||
// nothing to remove: the reference is live, and per-track removal would
|
// nothing to remove: the reference is live, and per-track removal would
|
||||||
// need an exclusion list — hidden state deciding what a future export
|
// need an exclusion list — hidden state deciding what a future export
|
||||||
|
|||||||
+91
-3
@@ -828,6 +828,13 @@ export interface SourceStatus {
|
|||||||
export interface ExportSet {
|
export interface ExportSet {
|
||||||
id: string
|
id: string
|
||||||
name: string
|
name: string
|
||||||
|
/** 'folder': exported into `destination`. 'computer': PUSHED into the DJ
|
||||||
|
* apps' own libraries on this computer (`targets` names the apps, there is
|
||||||
|
* no destination), `mode` saying how. */
|
||||||
|
kind: 'folder' | 'computer'
|
||||||
|
/** A push: 'merge' adds and updates only what this set put there;
|
||||||
|
* 'overwrite' replaces the whole library with this set. */
|
||||||
|
mode: 'merge' | 'overwrite'
|
||||||
/** Platform ids of the export TARGETS, e.g. ["traktor", "onelibrary"]. Never
|
/** Platform ids of the export TARGETS, e.g. ["traktor", "onelibrary"]. Never
|
||||||
* empty. They share one destination and ONE copy of the audio. */
|
* empty. They share one destination and ONE copy of the audio. */
|
||||||
targets: string[]
|
targets: string[]
|
||||||
@@ -896,6 +903,66 @@ export interface ExportPreview {
|
|||||||
to_measure: number
|
to_measure: number
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** One DJ app's library on this computer, as a push target. */
|
||||||
|
export interface LocalLibrary {
|
||||||
|
platform: string
|
||||||
|
name: string
|
||||||
|
path: string | null
|
||||||
|
/** Found by the platform's own detection (false: the user's setting). */
|
||||||
|
detected: boolean
|
||||||
|
/** A FACT; the UI words it. */
|
||||||
|
blocked: 'not_found' | 'open_in_konduktor' | 'cloud_synced' | 'unreadable' | null
|
||||||
|
running: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LocalLibraries {
|
||||||
|
libraries: LocalLibrary[]
|
||||||
|
/** The shared folder pushed audio lives in, and its default. */
|
||||||
|
audio_root: string
|
||||||
|
audio_root_default: string
|
||||||
|
/** The shared folder's Normalise level; null = off. */
|
||||||
|
level: NormalizeOptions | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PushTarget {
|
||||||
|
platform: string
|
||||||
|
name: string
|
||||||
|
path: string | null
|
||||||
|
blocked: LocalLibrary['blocked']
|
||||||
|
/** Not on this computer: the push passes it over instead of blocking. */
|
||||||
|
skipped: boolean
|
||||||
|
running: boolean
|
||||||
|
/** Tracks this set has not pushed here before. */
|
||||||
|
add: number
|
||||||
|
/** Tracks it has: kept, or brought up to date where changed. */
|
||||||
|
already: number
|
||||||
|
/** Tracks that left the set since the last push. */
|
||||||
|
remove: number
|
||||||
|
/** Overwrite: the other sets pushed here, which it removes. */
|
||||||
|
wipes_sets: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What a push would do now. Computed fresh every time. */
|
||||||
|
export interface PushPreview {
|
||||||
|
mode: 'merge' | 'overwrite'
|
||||||
|
tracks: number
|
||||||
|
pushable: number
|
||||||
|
/** Copies in the shared folder kept rather than copied again. */
|
||||||
|
unchanged: number
|
||||||
|
missing: string[]
|
||||||
|
playlists: string[]
|
||||||
|
total_bytes: number
|
||||||
|
audio_root: string
|
||||||
|
free_bytes: number | null
|
||||||
|
enough_space: boolean | null
|
||||||
|
normalised: number
|
||||||
|
level_counts: Record<string, number>
|
||||||
|
to_measure: number
|
||||||
|
targets: PushTarget[]
|
||||||
|
/** A FACT, not a sentence. Null when the push can run. */
|
||||||
|
blocked: 'no_target' | 'no_library_here' | 'nothing_to_push' | 'target_unavailable' | 'app_running' | null
|
||||||
|
}
|
||||||
|
|
||||||
/** The run dialog's options; each is remembered on the set. Omitted = the
|
/** The run dialog's options; each is remembered on the set. Omitted = the
|
||||||
* set's own answer. */
|
* set's own answer. */
|
||||||
export interface ExportRunOptions {
|
export interface ExportRunOptions {
|
||||||
@@ -1098,11 +1165,16 @@ export const api = {
|
|||||||
// All scoped to the LOADED library on the server, by its stable id, so
|
// All scoped to the LOADED library on the server, by its stable id, so
|
||||||
// nothing here has to carry which collection it means.
|
// nothing here has to carry which collection it means.
|
||||||
exports: () => getJSON<ExportSet[]>('/api/exports'),
|
exports: () => getJSON<ExportSet[]>('/api/exports'),
|
||||||
createExport: (body: { name: string; targets: string[]; destination: string }) =>
|
createExport: (body: {
|
||||||
send<ExportSet>('POST', '/api/exports', body),
|
name: string
|
||||||
|
targets: string[]
|
||||||
|
destination: string
|
||||||
|
kind?: ExportSet['kind']
|
||||||
|
mode?: ExportSet['mode']
|
||||||
|
}) => send<ExportSet>('POST', '/api/exports', body),
|
||||||
updateExport: (
|
updateExport: (
|
||||||
id: string,
|
id: string,
|
||||||
body: Partial<Pick<ExportSet, 'name' | 'targets' | 'destination' | 'lock_grids'>>,
|
body: Partial<Pick<ExportSet, 'name' | 'targets' | 'destination' | 'lock_grids' | 'mode'>>,
|
||||||
) =>
|
) =>
|
||||||
send<ExportSet>('PATCH', `/api/exports/${encodeURIComponent(id)}`, body),
|
send<ExportSet>('PATCH', `/api/exports/${encodeURIComponent(id)}`, body),
|
||||||
deleteExport: (id: string) =>
|
deleteExport: (id: string) =>
|
||||||
@@ -1138,6 +1210,14 @@ export const api = {
|
|||||||
// The run dialog's options travel with the click; the set remembers them.
|
// The run dialog's options travel with the click; the set remembers them.
|
||||||
runExport: (id: string, body: ExportRunOptions = {}) =>
|
runExport: (id: string, body: ExportRunOptions = {}) =>
|
||||||
send<JobStatus>('POST', `/api/exports/${encodeURIComponent(id)}/run`, body),
|
send<JobStatus>('POST', `/api/exports/${encodeURIComponent(id)}/run`, body),
|
||||||
|
// A "computer" set: pushed into this computer's Traktor / rekordbox. Only
|
||||||
|
// lock_grids and auto_gain apply — Normalise is the shared folder's, set in
|
||||||
|
// Settings → Local libraries (`localNormalise` / `localLevel` prefs).
|
||||||
|
localLibraries: () => getJSON<LocalLibraries>('/api/local-libraries'),
|
||||||
|
pushPreview: (id: string, body: ExportRunOptions = {}) =>
|
||||||
|
send<PushPreview>('POST', `/api/exports/${encodeURIComponent(id)}/push/preview`, body),
|
||||||
|
runPush: (id: string, body: ExportRunOptions = {}) =>
|
||||||
|
send<JobStatus>('POST', `/api/exports/${encodeURIComponent(id)}/push`, body),
|
||||||
|
|
||||||
// ---- path remapping (per-collection OS-path prefix translation) ----
|
// ---- path remapping (per-collection OS-path prefix translation) ----
|
||||||
getPathMapping: () => getJSON<PathMapping>('/api/library/path-mapping'),
|
getPathMapping: () => getJSON<PathMapping>('/api/library/path-mapping'),
|
||||||
@@ -1192,6 +1272,14 @@ export const api = {
|
|||||||
`/api/playlists/${encodeURIComponent(nodeId)}/add`,
|
`/api/playlists/${encodeURIComponent(nodeId)}/add`,
|
||||||
{ track_ids: trackIds, duplicates, index },
|
{ track_ids: trackIds, duplicates, index },
|
||||||
),
|
),
|
||||||
|
/** Remove every occurrence of these tracks. `dryRun` changes nothing and
|
||||||
|
* counts: `tracks` = how many of them it holds, `removed` = entries. */
|
||||||
|
removeEntries: (nodeId: string, trackIds: string[], dryRun = false) =>
|
||||||
|
send<{ status: 'removed' | 'counted'; tracks: number; removed: number; count: number }>(
|
||||||
|
'POST',
|
||||||
|
`/api/playlists/${encodeURIComponent(nodeId)}/remove`,
|
||||||
|
{ track_ids: trackIds, dry_run: dryRun },
|
||||||
|
),
|
||||||
/** Move a tree node to `index` among `parentId`'s children (null = top
|
/** Move a tree node to `index` among `parentId`'s children (null = top
|
||||||
* level), counted without it. Answers its id AFTER the move. */
|
* level), counted without it. Answers its id AFTER the move. */
|
||||||
movePlaylist: (nodeId: string, parentId: string | null, index: number) =>
|
movePlaylist: (nodeId: string, parentId: string | null, index: number) =>
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect, useRef, useState, type ReactNode } from 'react'
|
import { useEffect, useRef, useState, type ReactNode } from 'react'
|
||||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { api, isServerPath, type FolderAddPreview, type FolderAddRequest, type JobStatus, type TrackOrigin } from '../api'
|
import { api, isServerPath, type FolderAddPreview, type FolderAddRequest, type JobStatus, type TrackOrigin } from '../api'
|
||||||
import { useCaps } from '../lib/capabilities'
|
import { useCaps } from '../lib/capabilities'
|
||||||
import { placedAudioSummary } from '../lib/platformCopy'
|
import { placedAudioSummary } from '../lib/platformCopy'
|
||||||
import { FolderPicker } from './FolderPicker'
|
import { FolderPicker } from './FolderPicker'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Add browsed files to the collection — and, optionally, to a playlist or export.
|
* Add browsed files to the collection — and, optionally, to a playlist or export.
|
||||||
@@ -253,7 +253,7 @@ export function AddFilesDialog({ trackIds, target: requested, note, onClose, onD
|
|||||||
</label>
|
</label>
|
||||||
)
|
)
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<>
|
<>
|
||||||
{browsing && (
|
{browsing && (
|
||||||
<FolderPicker
|
<FolderPicker
|
||||||
@@ -267,10 +267,7 @@ export function AddFilesDialog({ trackIds, target: requested, note, onClose, onD
|
|||||||
onClose={() => setBrowsing(false)}
|
onClose={() => setBrowsing(false)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
<div
|
<Modal onDismiss={onClose} padding="p-4">
|
||||||
aria-modal="true"
|
|
||||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4 backdrop-blur-[3px]"
|
|
||||||
>
|
|
||||||
<div className="w-full max-w-lg glass-overlay">
|
<div className="w-full max-w-lg glass-overlay">
|
||||||
<div className="border-b border-line px-5 py-3">
|
<div className="border-b border-line px-5 py-3">
|
||||||
<h2 className="text-sm font-semibold text-text">{title}</h2>
|
<h2 className="text-sm font-semibold text-text">{title}</h2>
|
||||||
@@ -461,9 +458,8 @@ export function AddFilesDialog({ trackIds, target: requested, note, onClose, onD
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</Modal>
|
||||||
</>,
|
</>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect, useState, type ReactNode } from 'react'
|
import { useEffect, useState, type ReactNode } from 'react'
|
||||||
import { keepPreviousData, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { keepPreviousData, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { api, type AnalyzeOptions, type AnalyzePreview, type TrackOrigin } from '../api'
|
import { api, type AnalyzeOptions, type AnalyzePreview, type TrackOrigin } from '../api'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
/** The selected tracks. */
|
/** The selected tracks. */
|
||||||
@@ -100,12 +100,6 @@ export function AnalyzeDialog({ ids, origin, gridWhy, keyWhy, gainWhy, preset, o
|
|||||||
const nothingTicked = !!what && !(what.bpm || what.grid || what.key || what.loudness || what.gain)
|
const nothingTicked = !!what && !(what.bpm || what.grid || what.key || what.loudness || what.gain)
|
||||||
const count = nothingTicked ? 0 : (p?.tracks_to_analyze ?? 0)
|
const count = nothingTicked ? 0 : (p?.tracks_to_analyze ?? 0)
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && !busy && onClose()
|
|
||||||
window.addEventListener('keydown', onKey)
|
|
||||||
return () => window.removeEventListener('keydown', onKey)
|
|
||||||
}, [busy, onClose])
|
|
||||||
|
|
||||||
const run = async () => {
|
const run = async () => {
|
||||||
if (!opts || busy || count === 0) return
|
if (!opts || busy || count === 0) return
|
||||||
setBusy(true)
|
setBusy(true)
|
||||||
@@ -186,13 +180,9 @@ export function AnalyzeDialog({ ids, origin, gridWhy, keyWhy, gainWhy, preset, o
|
|||||||
if (p.grid_locked) gridLines.push(<div key="lk" className="text-faint">{plural(p.grid_locked, 'locked grid')} — skipped</div>)
|
if (p.grid_locked) gridLines.push(<div key="lk" className="text-faint">{plural(p.grid_locked, 'locked grid')} — skipped</div>)
|
||||||
}
|
}
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<div
|
<Modal onDismiss={busy ? null : onClose}>
|
||||||
aria-modal="true"
|
<div className="w-full max-w-sm overflow-hidden glass-overlay">
|
||||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6"
|
|
||||||
onClick={() => !busy && onClose()}
|
|
||||||
>
|
|
||||||
<div className="w-full max-w-sm overflow-hidden glass-overlay" onClick={(e) => e.stopPropagation()}>
|
|
||||||
<div className="border-b border-line px-5 py-4">
|
<div className="border-b border-line px-5 py-4">
|
||||||
<div className="text-[15px] font-semibold tracking-tight">Analyze</div>
|
<div className="text-[15px] font-semibold tracking-tight">Analyze</div>
|
||||||
<div className="text-xs text-muted">{plural(ids.length, 'track')} selected</div>
|
<div className="text-xs text-muted">{plural(ids.length, 'track')} selected</div>
|
||||||
@@ -265,7 +255,6 @@ export function AnalyzeDialog({ ids, origin, gridWhy, keyWhy, gainWhy, preset, o
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { api } from '../api'
|
import { api } from '../api'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Settings → Konduktor: preferences about the app itself rather than about a
|
* Settings → Konduktor: preferences about the app itself rather than about a
|
||||||
@@ -42,12 +42,6 @@ export function AppSettings({ onClose }: { onClose: () => void }) {
|
|||||||
const levelCeiling = useAppSetting('levelCeiling')
|
const levelCeiling = useAppSetting('levelCeiling')
|
||||||
const [error, setError] = useState<string | null>(null)
|
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>) => {
|
const set = async (patch: Partial<typeof APP_SETTING_DEFAULTS>) => {
|
||||||
setError(null)
|
setError(null)
|
||||||
try {
|
try {
|
||||||
@@ -57,13 +51,9 @@ export function AppSettings({ onClose }: { onClose: () => void }) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<div
|
<Modal onDismiss={onClose}>
|
||||||
aria-modal="true"
|
<div className="flex w-full max-w-md flex-col overflow-hidden glass-overlay">
|
||||||
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">
|
<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>
|
<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 onClick={onClose} className="rounded px-1.5 text-faint hover:text-text" aria-label="Close">
|
||||||
@@ -166,8 +156,7 @@ export function AppSettings({ onClose }: { onClose: () => void }) {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import {
|
import {
|
||||||
@@ -10,6 +9,7 @@ import {
|
|||||||
type Track,
|
type Track,
|
||||||
} from '../api'
|
} from '../api'
|
||||||
import { formatDuration } from '../lib/format'
|
import { formatDuration } from '../lib/format'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Auto Hotcues: bind each hotcue slot to a structural event plus an offset in
|
* Auto Hotcues: bind each hotcue slot to a structural event plus an offset in
|
||||||
@@ -109,14 +109,6 @@ export function AutoCueDialog(props: Props) {
|
|||||||
if (rows === null && (prefs.data || prefs.isError)) setRows(loadTemplate(prefs.data, slotCount))
|
if (rows === null && (prefs.data || prefs.isError)) setRows(loadTemplate(prefs.data, slotCount))
|
||||||
}, [prefs.data, prefs.isError, rows, slotCount])
|
}, [prefs.data, prefs.isError, rows, slotCount])
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const onKey = (e: KeyboardEvent) => {
|
|
||||||
if (e.key === 'Escape' && !busy) onClose()
|
|
||||||
}
|
|
||||||
window.addEventListener('keydown', onKey)
|
|
||||||
return () => window.removeEventListener('keydown', onKey)
|
|
||||||
}, [busy, onClose])
|
|
||||||
|
|
||||||
const setRow = (i: number, patch: Partial<Row>) =>
|
const setRow = (i: number, patch: Partial<Row>) =>
|
||||||
setRows((rs) => rs && rs.map((r, j) => (j === i ? { ...r, ...patch } : r)))
|
setRows((rs) => rs && rs.map((r, j) => (j === i ? { ...r, ...patch } : r)))
|
||||||
const nudge = (i: number, by: number) =>
|
const nudge = (i: number, by: number) =>
|
||||||
@@ -152,11 +144,10 @@ export function AutoCueDialog(props: Props) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<div aria-modal="true" className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6" onClick={() => !busy && onClose()}>
|
<Modal onDismiss={busy ? null : onClose}>
|
||||||
<div
|
<div
|
||||||
className="flex max-h-[85vh] w-full max-w-xl flex-col overflow-hidden glass-overlay"
|
className="flex max-h-[85vh] w-full max-w-xl flex-col overflow-hidden glass-overlay"
|
||||||
onClick={(e) => e.stopPropagation()}
|
|
||||||
>
|
>
|
||||||
<div className="border-b border-line px-5 py-4">
|
<div className="border-b border-line px-5 py-4">
|
||||||
<div className="text-[15px] font-semibold tracking-tight">Auto Hotcues</div>
|
<div className="text-[15px] font-semibold tracking-tight">Auto Hotcues</div>
|
||||||
@@ -294,7 +285,6 @@ export function AutoCueDialog(props: Props) {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect, useState, type ReactNode } from 'react'
|
import { useEffect, useState, type ReactNode } from 'react'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
export interface ConfirmRequest {
|
export interface ConfirmRequest {
|
||||||
title: string
|
title: string
|
||||||
@@ -14,6 +14,9 @@ export interface ConfirmRequest {
|
|||||||
* (e.g. "Add them again" next to "Add 6 new"). Enter still means confirm. */
|
* (e.g. "Add them again" next to "Add 6 new"). Enter still means confirm. */
|
||||||
altLabel?: string
|
altLabel?: string
|
||||||
onAlt?: () => void
|
onAlt?: () => void
|
||||||
|
/** Nothing to confirm (e.g. none of the tracks are there): the dialog
|
||||||
|
* still answers, with the confirm button — and Enter — off. */
|
||||||
|
confirmDisabled?: boolean
|
||||||
onConfirm: () => Promise<void> | void
|
onConfirm: () => Promise<void> | void
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,11 +26,11 @@ interface Props extends ConfirmRequest {
|
|||||||
|
|
||||||
/** A yes/no confirmation for destructive actions. Enter confirms and Esc
|
/** A yes/no confirmation for destructive actions. Enter confirms and Esc
|
||||||
* cancels, so a confirmed Delete key stays a two-keystroke action. */
|
* cancels, so a confirmed Delete key stays a two-keystroke action. */
|
||||||
export function ConfirmDialog({ title, body, confirmLabel, tone = 'danger', altLabel, onAlt, onConfirm, onClose }: Props) {
|
export function ConfirmDialog({ title, body, confirmLabel, tone = 'danger', altLabel, onAlt, confirmDisabled, onConfirm, onClose }: Props) {
|
||||||
const [busy, setBusy] = useState(false)
|
const [busy, setBusy] = useState(false)
|
||||||
|
|
||||||
const confirm = async () => {
|
const confirm = async () => {
|
||||||
if (busy) return
|
if (busy || confirmDisabled) return
|
||||||
setBusy(true)
|
setBusy(true)
|
||||||
try {
|
try {
|
||||||
await onConfirm()
|
await onConfirm()
|
||||||
@@ -39,7 +42,6 @@ export function ConfirmDialog({ title, body, confirmLabel, tone = 'danger', altL
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const onKey = (e: KeyboardEvent) => {
|
const onKey = (e: KeyboardEvent) => {
|
||||||
if (e.key === 'Escape' && !busy) onClose()
|
|
||||||
// A focused button handles its own Enter — otherwise tabbing to Cancel
|
// A focused button handles its own Enter — otherwise tabbing to Cancel
|
||||||
// and pressing Enter would run the destructive action.
|
// and pressing Enter would run the destructive action.
|
||||||
if (e.key === 'Enter' && !(e.target instanceof HTMLButtonElement)) {
|
if (e.key === 'Enter' && !(e.target instanceof HTMLButtonElement)) {
|
||||||
@@ -51,16 +53,9 @@ export function ConfirmDialog({ title, body, confirmLabel, tone = 'danger', altL
|
|||||||
return () => window.removeEventListener('keydown', onKey)
|
return () => window.removeEventListener('keydown', onKey)
|
||||||
})
|
})
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<div
|
<Modal onDismiss={busy ? null : onClose}>
|
||||||
aria-modal="true"
|
<div className="w-full max-w-sm overflow-hidden glass-overlay">
|
||||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6"
|
|
||||||
onClick={() => !busy && onClose()}
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
className="w-full max-w-sm overflow-hidden glass-overlay"
|
|
||||||
onClick={(e) => e.stopPropagation()}
|
|
||||||
>
|
|
||||||
<div className="border-b border-line px-5 py-4 text-[15px] font-semibold tracking-tight">
|
<div className="border-b border-line px-5 py-4 text-[15px] font-semibold tracking-tight">
|
||||||
{title}
|
{title}
|
||||||
</div>
|
</div>
|
||||||
@@ -87,7 +82,7 @@ export function ConfirmDialog({ title, body, confirmLabel, tone = 'danger', altL
|
|||||||
)}
|
)}
|
||||||
<button
|
<button
|
||||||
onClick={() => void confirm()}
|
onClick={() => void confirm()}
|
||||||
disabled={busy}
|
disabled={busy || confirmDisabled}
|
||||||
className={`rounded-full px-4 py-1.5 text-sm font-semibold disabled:opacity-50 ${
|
className={`rounded-full px-4 py-1.5 text-sm font-semibold disabled:opacity-50 ${
|
||||||
tone === 'primary'
|
tone === 'primary'
|
||||||
? 'btn-primary'
|
? 'btn-primary'
|
||||||
@@ -98,7 +93,6 @@ export function ConfirmDialog({ title, body, confirmLabel, tone = 'danger', altL
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect, useMemo, useState, type ReactNode } from 'react'
|
import { useEffect, useMemo, useState, type ReactNode } from 'react'
|
||||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import {
|
import {
|
||||||
@@ -12,6 +11,7 @@ import {
|
|||||||
import { FolderPicker } from './FolderPicker'
|
import { FolderPicker } from './FolderPicker'
|
||||||
import { useServerFolder } from './AddFilesDialog'
|
import { useServerFolder } from './AddFilesDialog'
|
||||||
import { useCaps } from '../lib/capabilities'
|
import { useCaps } from '../lib/capabilities'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Convert to Stems — one dialog (decided, see the stem-conversion discussion
|
* Convert to Stems — one dialog (decided, see the stem-conversion discussion
|
||||||
@@ -224,7 +224,7 @@ export function ConvertStemsDialog({ trackIds, onClose, onStarted, onDownloading
|
|||||||
)
|
)
|
||||||
|
|
||||||
const count = trackIds.length
|
const count = trackIds.length
|
||||||
return createPortal(
|
return (
|
||||||
<>
|
<>
|
||||||
{browsing && opts && (
|
{browsing && opts && (
|
||||||
<FolderPicker
|
<FolderPicker
|
||||||
@@ -239,11 +239,7 @@ export function ConvertStemsDialog({ trackIds, onClose, onStarted, onDownloading
|
|||||||
onClose={() => setBrowsing(false)}
|
onClose={() => setBrowsing(false)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
<div
|
<Modal onDismiss={starting ? null : onClose} padding="p-4">
|
||||||
aria-modal="true"
|
|
||||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4 backdrop-blur-[3px]"
|
|
||||||
onKeyDown={(e) => e.key === 'Escape' && !starting && onClose()}
|
|
||||||
>
|
|
||||||
<div className="flex max-h-[90vh] w-full max-w-lg flex-col overflow-hidden glass-overlay">
|
<div className="flex max-h-[90vh] w-full max-w-lg flex-col overflow-hidden glass-overlay">
|
||||||
<div className="border-b border-line px-5 py-3">
|
<div className="border-b border-line px-5 py-3">
|
||||||
<h2 className="text-sm font-semibold text-text">
|
<h2 className="text-sm font-semibold text-text">
|
||||||
@@ -477,8 +473,7 @@ export function ConvertStemsDialog({ trackIds, onClose, onStarted, onDownloading
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</Modal>
|
||||||
</>,
|
</>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useRef, useState } from 'react'
|
import { useRef, useState } from 'react'
|
||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { api, type Track } from '../api'
|
import { api, type Track } from '../api'
|
||||||
@@ -7,6 +6,7 @@ import { useCaps } from '../lib/capabilities'
|
|||||||
import { RatingStars } from './RatingStars'
|
import { RatingStars } from './RatingStars'
|
||||||
import { writeHint } from '../lib/platformCopy'
|
import { writeHint } from '../lib/platformCopy'
|
||||||
import { invalidateTrackLists } from '../lib/trackQueries'
|
import { invalidateTrackLists } from '../lib/trackQueries'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
track: Track
|
track: Track
|
||||||
@@ -96,14 +96,10 @@ export function EditTagsDialog({ track, onClose, onApplied, onError }: Props) {
|
|||||||
apply.mutate()
|
apply.mutate()
|
||||||
}
|
}
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<div
|
<Modal onDismiss={onClose}>
|
||||||
aria-modal="true" className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6"
|
|
||||||
onClick={onClose}
|
|
||||||
>
|
|
||||||
<div
|
<div
|
||||||
className="flex max-h-[85vh] w-full max-w-lg flex-col overflow-hidden glass-overlay"
|
className="flex max-h-[85vh] w-full max-w-lg flex-col overflow-hidden glass-overlay"
|
||||||
onClick={(e) => e.stopPropagation()}
|
|
||||||
>
|
>
|
||||||
<div className="border-b border-line px-5 py-4">
|
<div className="border-b border-line px-5 py-4">
|
||||||
<div className="text-[15px] font-semibold tracking-tight">Edit Tags</div>
|
<div className="text-[15px] font-semibold tracking-tight">Edit Tags</div>
|
||||||
@@ -240,7 +236,6 @@ export function EditTagsDialog({ track, onClose, onApplied, onError }: Props) {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,8 +1,9 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { api, type ExportSet } from '../api'
|
import { api, type ExportSet, type LocalLibrary } from '../api'
|
||||||
|
import { localLibraryProblem } from '../lib/platformCopy'
|
||||||
import { FolderPicker } from './FolderPicker'
|
import { FolderPicker } from './FolderPicker'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create or edit an export: its name, its target platforms and where it lands.
|
* Create or edit an export: its name, its target platforms and where it lands.
|
||||||
@@ -15,6 +16,13 @@ import { FolderPicker } from './FolderPicker'
|
|||||||
* detail deferred to export time. A Traktor `<LOCATION>` is a volume name plus
|
* detail deferred to export time. A Traktor `<LOCATION>` is a volume name plus
|
||||||
* a volume-relative path — both derived from where the export is written — so
|
* a volume-relative path — both derived from where the export is written — so
|
||||||
* the library file genuinely cannot be built until the destination is known.
|
* the library file genuinely cannot be built until the destination is known.
|
||||||
|
*
|
||||||
|
* Or the set goes to THIS COMPUTER: pushed straight into the Traktor collection
|
||||||
|
* and/or rekordbox library its DJ apps use (`local_push.py`), merging beside
|
||||||
|
* the user's own tracks or replacing the library. No destination is asked —
|
||||||
|
* which library each app uses, and the shared audio folder, are this
|
||||||
|
* computer's settings. The kind is chosen once, at creation: a push leaves
|
||||||
|
* records of what it put where, which a change of kind would orphan.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
@@ -29,6 +37,15 @@ export function ExportDialog({ editing, onClose, onSaved, onError }: Props) {
|
|||||||
const [name, setName] = useState(editing?.name ?? '')
|
const [name, setName] = useState(editing?.name ?? '')
|
||||||
const [chosen, setChosen] = useState<string[]>(editing?.targets ?? ['traktor'])
|
const [chosen, setChosen] = useState<string[]>(editing?.targets ?? ['traktor'])
|
||||||
const [destination, setDestination] = useState(editing?.destination ?? '')
|
const [destination, setDestination] = useState(editing?.destination ?? '')
|
||||||
|
const [kind, setKind] = useState<ExportSet['kind']>(editing?.kind ?? 'folder')
|
||||||
|
const [mode, setMode] = useState<ExportSet['mode']>(editing?.mode ?? 'merge')
|
||||||
|
const computer = kind === 'computer'
|
||||||
|
// A push's targets: this computer's DJ apps, each with why it cannot be used.
|
||||||
|
const locals = useQuery({
|
||||||
|
queryKey: ['local-libraries'],
|
||||||
|
queryFn: api.localLibraries,
|
||||||
|
enabled: computer,
|
||||||
|
})
|
||||||
const [browsing, setBrowsing] = useState(false)
|
const [browsing, setBrowsing] = useState(false)
|
||||||
const [busy, setBusy] = useState(false)
|
const [busy, setBusy] = useState(false)
|
||||||
|
|
||||||
@@ -68,15 +85,32 @@ export function ExportDialog({ editing, onClose, onSaved, onError }: Props) {
|
|||||||
on ? [...prev.filter((t) => t !== platform), platform] : prev.filter((t) => t !== platform),
|
on ? [...prev.filter((t) => t !== platform), platform] : prev.filter((t) => t !== platform),
|
||||||
)
|
)
|
||||||
|
|
||||||
const valid = name.trim() !== '' && destination.trim() !== '' && chosen.length > 0
|
// A set's targets are shared by every computer that opens this library (a
|
||||||
|
// remote's sets live on its server), so a library missing HERE can still be
|
||||||
|
// ticked or unticked — the push skips it on this computer. Anything else
|
||||||
|
// wrong with a library here can always be unticked, never newly ticked.
|
||||||
|
const lockedOut = (lib: LocalLibrary) =>
|
||||||
|
!!lib.blocked && lib.blocked !== 'not_found' && !chosen.includes(lib.platform)
|
||||||
|
const valid = computer
|
||||||
|
? name.trim() !== '' && chosen.length > 0
|
||||||
|
: name.trim() !== '' && destination.trim() !== '' && chosen.length > 0
|
||||||
|
|
||||||
|
const chooseKind = (next: ExportSet['kind']) => {
|
||||||
|
setKind(next)
|
||||||
|
// The two kinds offer different platforms: start from the obvious one.
|
||||||
|
setChosen(['traktor'])
|
||||||
|
}
|
||||||
|
|
||||||
const save = async () => {
|
const save = async () => {
|
||||||
setBusy(true)
|
setBusy(true)
|
||||||
try {
|
try {
|
||||||
const body = { name: name.trim(), targets: chosen, destination: destination.trim() }
|
|
||||||
const saved = editing
|
const saved = editing
|
||||||
? await api.updateExport(editing.id, body)
|
? await api.updateExport(editing.id, computer
|
||||||
: await api.createExport(body)
|
? { name: name.trim(), targets: chosen, mode }
|
||||||
|
: { name: name.trim(), targets: chosen, destination: destination.trim() })
|
||||||
|
: await api.createExport(computer
|
||||||
|
? { name: name.trim(), targets: chosen, destination: '', kind, mode }
|
||||||
|
: { name: name.trim(), targets: chosen, destination: destination.trim() })
|
||||||
onSaved(saved, !editing)
|
onSaved(saved, !editing)
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
onError((e as Error).message)
|
onError((e as Error).message)
|
||||||
@@ -85,7 +119,7 @@ export function ExportDialog({ editing, onClose, onSaved, onError }: Props) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<>
|
<>
|
||||||
{browsing && (
|
{browsing && (
|
||||||
<FolderPicker
|
<FolderPicker
|
||||||
@@ -94,11 +128,11 @@ export function ExportDialog({ editing, onClose, onSaved, onError }: Props) {
|
|||||||
onClose={() => setBrowsing(false)}
|
onClose={() => setBrowsing(false)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
<div aria-modal="true" className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-4">
|
<Modal onDismiss={onClose} padding="p-4">
|
||||||
<div className="w-full max-w-lg glass-overlay">
|
<div className="w-full max-w-lg glass-overlay">
|
||||||
<div className="border-b border-line px-5 py-3">
|
<div className="border-b border-line px-5 py-3">
|
||||||
<h2 className="text-sm font-semibold text-text">
|
<h2 className="text-sm font-semibold text-text">
|
||||||
{editing ? `Edit “${editing.name}”` : 'New export'}
|
{editing ? `Edit “${editing.name}”` : computer ? 'New push to this computer' : 'New export'}
|
||||||
</h2>
|
</h2>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -117,6 +151,101 @@ export function ExportDialog({ editing, onClose, onSaved, onError }: Props) {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{!editing && (
|
||||||
|
<div>
|
||||||
|
<span className="mb-1 block text-xs text-muted">Where</span>
|
||||||
|
<div className="grid grid-cols-2 gap-2">
|
||||||
|
{([
|
||||||
|
['folder', 'A folder or drive', 'Writes a library and a copy of the audio there — a USB stick for the gig.'],
|
||||||
|
['computer', 'This computer', 'Pushes into the Traktor or rekordbox you DJ with here.'],
|
||||||
|
] as const).map(([value, title, detail]) => (
|
||||||
|
<button
|
||||||
|
key={value}
|
||||||
|
onClick={() => chooseKind(value)}
|
||||||
|
aria-pressed={kind === value}
|
||||||
|
className={`rounded-lg px-3 py-2 text-left ${
|
||||||
|
kind === value ? 'is-selected well' : 'btn-glass'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<span className="block text-sm text-text">{title}</span>
|
||||||
|
<span className="mt-0.5 block text-[11px] leading-snug text-faint">{detail}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{computer ? (
|
||||||
|
<>
|
||||||
|
<div>
|
||||||
|
<span className="mb-1 block text-xs text-muted">Into</span>
|
||||||
|
<div className="space-y-1">
|
||||||
|
{(locals.data?.libraries ?? []).map((lib) => {
|
||||||
|
const missing = lib.blocked === 'not_found'
|
||||||
|
const problem = missing
|
||||||
|
? `${localLibraryProblem(lib)} — skipped when pushing from this computer`
|
||||||
|
: localLibraryProblem(lib)
|
||||||
|
const disabled = lockedOut(lib)
|
||||||
|
return (
|
||||||
|
<label
|
||||||
|
key={lib.platform}
|
||||||
|
className={`flex items-start gap-2 rounded-md px-2 py-1.5 ${
|
||||||
|
disabled ? 'cursor-not-allowed' : 'cursor-pointer hover:bg-ink-850'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
disabled={disabled}
|
||||||
|
checked={chosen.includes(lib.platform)}
|
||||||
|
onChange={(e) => toggle(lib.platform, e.target.checked)}
|
||||||
|
className="mt-0.5 accent-accent"
|
||||||
|
/>
|
||||||
|
<span className="min-w-0 flex-1">
|
||||||
|
<span className={problem ? 'text-faint' : 'text-text'}>{lib.name}</span>
|
||||||
|
<span
|
||||||
|
title={lib.path ?? undefined}
|
||||||
|
className="block truncate text-[11px] text-faint"
|
||||||
|
>
|
||||||
|
{problem ?? lib.path}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
<div className="mt-1 text-[11px] text-faint">
|
||||||
|
The audio is copied to{' '}
|
||||||
|
<span className="font-mono">{locals.data?.audio_root ?? '…'}</span>, shared by
|
||||||
|
every push. Change either in Settings → Local libraries.
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<span className="mb-1 block text-xs text-muted">How</span>
|
||||||
|
<div className="space-y-1">
|
||||||
|
{([
|
||||||
|
['merge', 'Merge', 'Adds and updates this set’s tracks, in a folder named after it. Your own tracks and playlists are never touched.'],
|
||||||
|
['overwrite', 'Overwrite', 'Replaces the WHOLE library with this set. Everything else in it — your own tracks, playlists and other pushes — is removed.'],
|
||||||
|
] as const).map(([value, title, detail]) => (
|
||||||
|
<label key={value} className="flex cursor-pointer items-start gap-2 rounded-md px-2 py-1.5 hover:bg-ink-850">
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="push-mode"
|
||||||
|
checked={mode === value}
|
||||||
|
onChange={() => setMode(value)}
|
||||||
|
className="mt-0.5 accent-accent"
|
||||||
|
/>
|
||||||
|
<span>
|
||||||
|
<span className={value === 'overwrite' ? 'text-pink' : 'text-text'}>{title}</span>
|
||||||
|
<span className="block text-[11px] leading-snug text-faint">{detail}</span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
<div>
|
<div>
|
||||||
<span className="mb-1 block text-xs text-muted">For</span>
|
<span className="mb-1 block text-xs text-muted">For</span>
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
@@ -187,6 +316,8 @@ export function ExportDialog({ editing, onClose, onSaved, onError }: Props) {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex justify-end gap-2 border-t border-line px-5 py-3">
|
<div className="flex justify-end gap-2 border-t border-line px-5 py-3">
|
||||||
@@ -205,8 +336,7 @@ export function ExportDialog({ editing, onClose, onSaved, onError }: Props) {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</Modal>
|
||||||
</>,
|
</>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect, useRef, useState } from 'react'
|
import { useEffect, useRef, useState } from 'react'
|
||||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { api, type ExportPreview, type ExportRunOptions, type ExportSet, type JobStatus, type NormalizeOptions } from '../api'
|
import { api, type ExportPreview, type ExportRunOptions, type ExportSet, type JobStatus, type NormalizeOptions } from '../api'
|
||||||
import { FolderPicker } from './FolderPicker'
|
import { FolderPicker } from './FolderPicker'
|
||||||
import { LevelInput, useAppSetting } from './AppSettings'
|
import { LevelInput, useAppSetting } from './AppSettings'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Run an export: confirm what is about to happen, then watch it happen.
|
* Run an export: confirm what is about to happen, then watch it happen.
|
||||||
@@ -175,7 +175,7 @@ export function ExportRunDialog({ set, onClose, onDone, onError }: Props) {
|
|||||||
: null
|
: null
|
||||||
const blocked = p?.blocked ?? null
|
const blocked = p?.blocked ?? null
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<>
|
<>
|
||||||
{browsing && (
|
{browsing && (
|
||||||
<FolderPicker
|
<FolderPicker
|
||||||
@@ -184,7 +184,7 @@ export function ExportRunDialog({ set, onClose, onDone, onError }: Props) {
|
|||||||
onClose={() => setBrowsing(false)}
|
onClose={() => setBrowsing(false)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
<div aria-modal="true" className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-4">
|
<Modal onDismiss={onClose} padding="p-4">
|
||||||
<div className="w-full max-w-lg glass-overlay">
|
<div className="w-full max-w-lg glass-overlay">
|
||||||
<div className="border-b border-line px-5 py-3">
|
<div className="border-b border-line px-5 py-3">
|
||||||
<h2 className="text-sm font-semibold text-text">Export “{set.name}”</h2>
|
<h2 className="text-sm font-semibold text-text">Export “{set.name}”</h2>
|
||||||
@@ -472,9 +472,8 @@ export function ExportRunDialog({ set, onClose, onDone, onError }: Props) {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</Modal>
|
||||||
</>,
|
</>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import type { AddTarget, ForeignOrigin } from './AddFilesDialog'
|
|||||||
import { useCaps } from '../lib/capabilities'
|
import { useCaps } from '../lib/capabilities'
|
||||||
import { ExportDialog } from './ExportDialog'
|
import { ExportDialog } from './ExportDialog'
|
||||||
import { ExportRunDialog } from './ExportRunDialog'
|
import { ExportRunDialog } from './ExportRunDialog'
|
||||||
|
import { PushRunDialog } from './PushRunDialog'
|
||||||
import type { Source } from './Sidebar'
|
import type { Source } from './Sidebar'
|
||||||
import { askConfirm } from '../lib/confirm'
|
import { askConfirm } from '../lib/confirm'
|
||||||
import { Icon } from '../lib/icons'
|
import { Icon } from '../lib/icons'
|
||||||
@@ -74,7 +75,16 @@ export function ExportsSection({ source, onSelect, onDone, onError, onAddForeign
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{running && (
|
{running?.kind === 'computer' && (
|
||||||
|
<PushRunDialog
|
||||||
|
set={running}
|
||||||
|
onClose={() => setRunning(null)}
|
||||||
|
onDone={onDone}
|
||||||
|
onError={onError}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{running && running.kind !== 'computer' && (
|
||||||
<ExportRunDialog
|
<ExportRunDialog
|
||||||
set={running}
|
set={running}
|
||||||
onClose={() => setRunning(null)}
|
onClose={() => setRunning(null)}
|
||||||
@@ -118,7 +128,9 @@ export function ExportsSection({ source, onSelect, onDone, onError, onAddForeign
|
|||||||
if (
|
if (
|
||||||
await askConfirm({
|
await askConfirm({
|
||||||
title: `Delete the export “${set.name}”?`,
|
title: `Delete the export “${set.name}”?`,
|
||||||
body: 'Nothing already exported is removed — the files in its folder stay where they are.',
|
body: set.kind === 'computer'
|
||||||
|
? 'Nothing already pushed is removed — its tracks and playlists stay in your DJ apps.'
|
||||||
|
: 'Nothing already exported is removed — the files in its folder stay where they are.',
|
||||||
confirmLabel: 'Delete export',
|
confirmLabel: 'Delete export',
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
@@ -257,8 +269,17 @@ function ExportRow({
|
|||||||
onClick={() => onSelect({ kind: 'export', id: set.id, name: set.name })}
|
onClick={() => onSelect({ kind: 'export', id: set.id, name: set.name })}
|
||||||
className="flex min-w-0 flex-1 items-center gap-2 py-1.5 text-left text-sm"
|
className="flex min-w-0 flex-1 items-center gap-2 py-1.5 text-left text-sm"
|
||||||
>
|
>
|
||||||
<span className="flex w-4 shrink-0 justify-center text-gold"><Icon name="export" size={14} /></span>
|
{/* A push into this computer's DJ apps reads differently from a
|
||||||
<span className="flex-1 truncate" title={set.destination}>
|
folder export at a glance: the target is this machine. */}
|
||||||
|
<span className="flex w-4 shrink-0 justify-center text-gold">
|
||||||
|
<Icon name={set.kind === 'computer' ? 'desktop' : 'export'} size={14} />
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
className="flex-1 truncate"
|
||||||
|
title={set.kind === 'computer'
|
||||||
|
? `Pushed into this computer’s ${set.targets.join(' and ')} (${set.mode})`
|
||||||
|
: set.destination}
|
||||||
|
>
|
||||||
{set.name}
|
{set.name}
|
||||||
</span>
|
</span>
|
||||||
<span className="shrink-0 text-[10px] tabular-nums text-faint">
|
<span className="shrink-0 text-[10px] tabular-nums text-faint">
|
||||||
@@ -266,7 +287,7 @@ function ExportRow({
|
|||||||
</span>
|
</span>
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
title="Edit name, platforms and destination"
|
title={set.kind === 'computer' ? 'Edit name, apps and how it pushes' : 'Edit name, platforms and destination'}
|
||||||
onClick={onEdit}
|
onClick={onEdit}
|
||||||
className="shrink-0 px-1 text-xs text-faint opacity-0 hover:text-text group-hover:opacity-100"
|
className="shrink-0 px-1 text-xs text-faint opacity-0 hover:text-text group-hover:opacity-100"
|
||||||
>
|
>
|
||||||
@@ -366,7 +387,7 @@ function ExportRow({
|
|||||||
style={{ marginLeft: 24 }}
|
style={{ marginLeft: 24 }}
|
||||||
className="mb-1 mt-1 rounded-full btn-primary px-2 py-1 text-xs font-semibold"
|
className="mb-1 mt-1 rounded-full btn-primary px-2 py-1 text-xs font-semibold"
|
||||||
>
|
>
|
||||||
Export {data.tracks} track{data.tracks === 1 ? '' : 's'}…
|
{set.kind === 'computer' ? 'Push' : 'Export'} {data.tracks} track{data.tracks === 1 ? '' : 's'}…
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { FileBrowser, useFsListing, type Listing } from './FileBrowser'
|
import { FileBrowser, useFsListing, type Listing } from './FileBrowser'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Pick a FOLDER, by browsing.
|
* Pick a FOLDER, by browsing.
|
||||||
@@ -33,8 +33,8 @@ export function FolderPicker({ value, onChange, onClose, listing = 'host' }: Pro
|
|||||||
onClose()
|
onClose()
|
||||||
}
|
}
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<div aria-modal="true" className="fixed inset-0 z-[60] flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-4">
|
<Modal onDismiss={onClose} layer="nested" padding="p-4">
|
||||||
<div className="flex h-[70vh] w-full max-w-2xl flex-col overflow-hidden glass-overlay">
|
<div className="flex h-[70vh] w-full max-w-2xl flex-col overflow-hidden glass-overlay">
|
||||||
<div className="border-b border-line px-5 py-3">
|
<div className="border-b border-line px-5 py-3">
|
||||||
<h2 className="text-sm font-semibold text-text">Choose a folder</h2>
|
<h2 className="text-sm font-semibold text-text">Choose a folder</h2>
|
||||||
@@ -84,7 +84,6 @@ export function FolderPicker({ value, onChange, onClose, listing = 'host' }: Pro
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { api, type HistoryEntry } from '../api'
|
import { api, type HistoryEntry } from '../api'
|
||||||
import { useCaps } from '../lib/capabilities'
|
import { useCaps } from '../lib/capabilities'
|
||||||
import { restoreWarning } from '../lib/platformCopy'
|
import { restoreWarning } from '../lib/platformCopy'
|
||||||
import type { ToastMsg } from './Toast'
|
import type { ToastMsg } from './Toast'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
onClose: () => void
|
onClose: () => void
|
||||||
@@ -79,14 +79,10 @@ export function HistoryPanel({ onClose, onNotify, onError }: Props) {
|
|||||||
|
|
||||||
const entries = history.data ?? []
|
const entries = history.data ?? []
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<div
|
<Modal onDismiss={onClose}>
|
||||||
aria-modal="true" className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6"
|
|
||||||
onClick={onClose}
|
|
||||||
>
|
|
||||||
<div
|
<div
|
||||||
className="flex max-h-[85vh] w-full max-w-xl flex-col overflow-hidden glass-overlay"
|
className="flex max-h-[85vh] w-full max-w-xl flex-col overflow-hidden glass-overlay"
|
||||||
onClick={(e) => e.stopPropagation()}
|
|
||||||
>
|
>
|
||||||
<div className="border-b border-line px-5 py-4">
|
<div className="border-b border-line px-5 py-4">
|
||||||
<div className="text-[15px] font-semibold tracking-tight">Version History</div>
|
<div className="text-[15px] font-semibold tracking-tight">Version History</div>
|
||||||
@@ -208,7 +204,6 @@ export function HistoryPanel({ onClose, onNotify, onError }: Props) {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect, useRef, useState } from 'react'
|
import { useEffect, useRef, useState } from 'react'
|
||||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { api, type ImportPreview, type JobStatus } from '../api'
|
import { api, type ImportPreview, type JobStatus } from '../api'
|
||||||
@@ -7,6 +6,7 @@ import { placedAudioSummary } from '../lib/platformCopy'
|
|||||||
import type { AddTarget } from './AddFilesDialog'
|
import type { AddTarget } from './AddFilesDialog'
|
||||||
import { FolderPicker } from './FolderPicker'
|
import { FolderPicker } from './FolderPicker'
|
||||||
import { useServerImportFolder, usePlaylistToggle } from './AddFilesDialog'
|
import { useServerImportFolder, usePlaylistToggle } from './AddFilesDialog'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Import a browsed device into the loaded collection.
|
* Import a browsed device into the loaded collection.
|
||||||
@@ -173,7 +173,7 @@ export function ImportDialog({ playlistId, trackIds, target: requested, deviceLa
|
|||||||
const finished = job != null && job.state !== 'running'
|
const finished = job != null && job.state !== 'running'
|
||||||
const pct = job && job.total > 0 ? Math.min(100, (job.done / job.total) * 100) : null
|
const pct = job && job.total > 0 ? Math.min(100, (job.done / job.total) * 100) : null
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<>
|
<>
|
||||||
{browsing && (
|
{browsing && (
|
||||||
<FolderPicker
|
<FolderPicker
|
||||||
@@ -187,7 +187,7 @@ export function ImportDialog({ playlistId, trackIds, target: requested, deviceLa
|
|||||||
onClose={() => setBrowsing(false)}
|
onClose={() => setBrowsing(false)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
<div aria-modal="true" className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-4">
|
<Modal onDismiss={onClose} padding="p-4">
|
||||||
<div className="w-full max-w-lg glass-overlay">
|
<div className="w-full max-w-lg glass-overlay">
|
||||||
<div className="border-b border-line px-5 py-3">
|
<div className="border-b border-line px-5 py-3">
|
||||||
<h2 className="text-sm font-semibold text-text">
|
<h2 className="text-sm font-semibold text-text">
|
||||||
@@ -373,8 +373,7 @@ export function ImportDialog({ playlistId, trackIds, target: requested, deviceLa
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</Modal>
|
||||||
</>,
|
</>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
import { useState } from 'react'
|
||||||
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { api, type NormalizeOptions } from '../api'
|
||||||
|
import { localLibraryProblem } from '../lib/platformCopy'
|
||||||
|
import { FolderPicker } from './FolderPicker'
|
||||||
|
import { LevelInput, useAppSetting } from './AppSettings'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Settings → Local libraries: where a "This computer" set is pushed.
|
||||||
|
*
|
||||||
|
* This computer's, not the set's: a remote library's sets are kept on its
|
||||||
|
* server, but which Traktor collection and rekordbox library a laptop DJs from,
|
||||||
|
* and where their audio goes, belong to the laptop. So they are prefs —
|
||||||
|
* `localLibraries` ({platform: path | null}, null = detected), `localAudioRoot`,
|
||||||
|
* `localNormalise` and `localLevel`.
|
||||||
|
*
|
||||||
|
* The audio folder is SHARED by every push, so a file has one level: Normalise
|
||||||
|
* lives here rather than on a set. A library is chosen by its FOLDER (the
|
||||||
|
* `Traktor 4.x` folder, rekordbox's), the file in it being the platform's own.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const LIBRARY_FILE: Record<string, string> = { traktor: 'collection.nml', rekordbox: 'master.db' }
|
||||||
|
|
||||||
|
export function LocalLibrariesSettings({ onClose }: { onClose: () => void }) {
|
||||||
|
const qc = useQueryClient()
|
||||||
|
const locals = useQuery({ queryKey: ['local-libraries'], queryFn: api.localLibraries })
|
||||||
|
const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs })
|
||||||
|
const defaultMeasure = useAppSetting('levelMeasure')
|
||||||
|
const defaultTarget = useAppSetting('levelTarget')
|
||||||
|
const defaultCeiling = useAppSetting('levelCeiling')
|
||||||
|
const [picking, setPicking] = useState<string | null>(null) // a platform, or 'audio'
|
||||||
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
|
||||||
|
const p = prefs.data ?? {}
|
||||||
|
const overrides = (p.localLibraries as Record<string, string | null> | undefined) ?? {}
|
||||||
|
const normalise = p.localNormalise === true
|
||||||
|
const stored = p.localLevel as Partial<NormalizeOptions> | undefined
|
||||||
|
const level: NormalizeOptions = {
|
||||||
|
measure: stored?.measure ?? defaultMeasure,
|
||||||
|
target: stored?.target ?? defaultTarget,
|
||||||
|
ceiling: stored?.ceiling ?? defaultCeiling,
|
||||||
|
}
|
||||||
|
|
||||||
|
const patch = async (body: Record<string, unknown>) => {
|
||||||
|
setError(null)
|
||||||
|
try {
|
||||||
|
qc.setQueryData(['prefs'], await api.patchPrefs(body))
|
||||||
|
qc.invalidateQueries({ queryKey: ['local-libraries'] })
|
||||||
|
qc.invalidateQueries({ queryKey: ['push-preview'] })
|
||||||
|
} catch (e) {
|
||||||
|
setError((e as Error).message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const choose = (folder: string) => {
|
||||||
|
if (picking === 'audio') {
|
||||||
|
patch({ localAudioRoot: folder })
|
||||||
|
} else if (picking) {
|
||||||
|
const sep = folder.includes('\\') && !folder.includes('/') ? '\\' : '/'
|
||||||
|
patch({ localLibraries: { ...overrides, [picking]: `${folder.replace(/[\\/]+$/, '')}${sep}${LIBRARY_FILE[picking]}` } })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const d = locals.data
|
||||||
|
const pickerValue =
|
||||||
|
picking === 'audio'
|
||||||
|
? d?.audio_root ?? ''
|
||||||
|
: (d?.libraries.find((l) => l.platform === picking)?.path ?? '').replace(/[\\/][^\\/]*$/, '')
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{picking && (
|
||||||
|
<FolderPicker value={pickerValue} onChange={choose} onClose={() => setPicking(null)} />
|
||||||
|
)}
|
||||||
|
<Modal onDismiss={onClose}>
|
||||||
|
<div className="flex max-h-full w-full max-w-lg flex-col overflow-hidden glass-overlay">
|
||||||
|
<div className="flex items-center justify-between border-b border-line px-5 py-3">
|
||||||
|
<h2 className="text-sm font-semibold text-text">Local libraries</h2>
|
||||||
|
<button onClick={onClose} className="rounded px-1.5 text-faint hover:text-text" aria-label="Close">
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="min-h-0 space-y-5 overflow-y-auto px-5 py-4 text-sm">
|
||||||
|
<p className="text-muted">
|
||||||
|
Where an export set made for <span className="text-text">This computer</span> is pushed:
|
||||||
|
the DJ apps you play from here, and one folder for their audio.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<section className="space-y-2">
|
||||||
|
<h3 className="text-[11px] uppercase tracking-wider text-faint">DJ apps</h3>
|
||||||
|
{(d?.libraries ?? []).map((lib) => {
|
||||||
|
const problem = lib.blocked === 'open_in_konduktor' ? null : localLibraryProblem(lib)
|
||||||
|
return (
|
||||||
|
<div key={lib.platform} className="rounded-md well px-3 py-2">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-text">{lib.name}</span>
|
||||||
|
<span className="text-[11px] text-faint">{lib.detected ? 'found automatically' : 'chosen'}</span>
|
||||||
|
<span className="ml-auto flex gap-1">
|
||||||
|
{!lib.detected && (
|
||||||
|
<button
|
||||||
|
onClick={() => patch({ localLibraries: { ...overrides, [lib.platform]: null } })}
|
||||||
|
className="btn-glass rounded-full px-2.5 py-0.5 text-xs text-muted hover:text-text"
|
||||||
|
>
|
||||||
|
Find automatically
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
onClick={() => setPicking(lib.platform)}
|
||||||
|
className="btn-glass rounded-full px-2.5 py-0.5 text-xs text-muted hover:text-text"
|
||||||
|
>
|
||||||
|
Change…
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div title={lib.path ?? undefined} className="mt-0.5 truncate font-mono text-[11px] text-faint">
|
||||||
|
{lib.path ?? '—'}
|
||||||
|
</div>
|
||||||
|
{problem && <div className="mt-0.5 text-[11px] text-pink">{problem}</div>}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="space-y-2">
|
||||||
|
<h3 className="text-[11px] uppercase tracking-wider text-faint">Audio folder</h3>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span title={d?.audio_root} dir="rtl"
|
||||||
|
className="min-w-0 flex-1 truncate rounded-md well px-2 py-1.5 text-left font-mono text-xs text-text">
|
||||||
|
{d?.audio_root ?? '…'}
|
||||||
|
</span>
|
||||||
|
{d && d.audio_root !== d.audio_root_default && (
|
||||||
|
<button onClick={() => patch({ localAudioRoot: null })}
|
||||||
|
className="shrink-0 btn-glass rounded-full px-2.5 py-1 text-xs text-muted hover:text-text">
|
||||||
|
Reset
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<button onClick={() => setPicking('audio')}
|
||||||
|
className="shrink-0 btn-glass rounded-full px-2.5 py-1 text-xs text-muted hover:text-text">
|
||||||
|
Change…
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p className="text-[11px] text-faint">
|
||||||
|
Every push copies its tracks here, once each, however many sets or apps use them. A
|
||||||
|
file no push uses any more is deleted. Changing the folder copies everything again
|
||||||
|
on the next push.
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="space-y-2">
|
||||||
|
<h3 className="text-[11px] uppercase tracking-wider text-faint">Level</h3>
|
||||||
|
<label className="flex cursor-pointer items-start gap-2.5">
|
||||||
|
<input type="checkbox" className="mt-0.5" checked={normalise}
|
||||||
|
onChange={(e) => patch({ localNormalise: e.target.checked })} />
|
||||||
|
<span>
|
||||||
|
<span className="block text-text">Normalise audio</span>
|
||||||
|
<span className="block text-xs text-faint">
|
||||||
|
Brings the copies to one level. Your own files are never changed.
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
{normalise && (
|
||||||
|
<div className="ml-6 space-y-1.5 text-xs">
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<span className="text-muted">Level by</span>
|
||||||
|
<select
|
||||||
|
className="rounded-lg well px-2 py-1 text-xs text-text outline-none"
|
||||||
|
value={level.measure}
|
||||||
|
onChange={(e) => patch({ localLevel: { ...level, measure: e.target.value } })}
|
||||||
|
>
|
||||||
|
<option value="lufs">LUFS</option>
|
||||||
|
<option value="rms">RMS (loudest sections)</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<span className="text-muted">Target</span>
|
||||||
|
<LevelInput value={level.target} unit={level.measure === 'lufs' ? 'LUFS' : 'dB'} min={-30} max={0}
|
||||||
|
onCommit={(v) => patch({ localLevel: { ...level, target: v } })} />
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<span className="text-muted" title="A raise stops here, so nothing clips">Peak ceiling</span>
|
||||||
|
<LevelInput value={level.ceiling} unit="dBTP" min={-12} max={0}
|
||||||
|
onCommit={(v) => patch({ localLevel: { ...level, ceiling: v } })} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
{error && <div className="text-xs text-pink">{error}</div>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
import { createPortal } from 'react-dom'
|
||||||
|
import { useEffect, useRef, useState, type AriaRole, type ReactNode } from 'react'
|
||||||
|
|
||||||
|
// Open modals by opening order (taken at first render, so a dialog opened
|
||||||
|
// from another always ranks above it). Esc is answered by the top one only.
|
||||||
|
const open = new Set<number>()
|
||||||
|
let opened = 0
|
||||||
|
|
||||||
|
const menuOpen = () => document.querySelector('[role="menu"]') != null
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
/** What Esc and a click on the backdrop do: the dialog's Cancel / Close.
|
||||||
|
* `null` while that is not available (a run in progress), so neither
|
||||||
|
* can close the dialog when its own Cancel could not. */
|
||||||
|
onDismiss: (() => void) | null
|
||||||
|
/** `false`: Esc only. For a dialog whose dismissal decides something a
|
||||||
|
* stray click should not (RelocateDialog). */
|
||||||
|
backdropDismiss?: boolean
|
||||||
|
/** `nested` for a dialog opened from a dialog or above every other one. */
|
||||||
|
layer?: 'dialog' | 'nested'
|
||||||
|
/** The backdrop's padding (default `p-6`). */
|
||||||
|
padding?: string
|
||||||
|
role?: AriaRole
|
||||||
|
'aria-label'?: string
|
||||||
|
'aria-labelledby'?: string
|
||||||
|
children: ReactNode
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The ONE modal container: portal, dimmed backdrop, Esc and outside click.
|
||||||
|
*
|
||||||
|
* An outside click closes only when the press AND the release are both on
|
||||||
|
* the backdrop. A `click` alone fires on the nearest common ancestor, so a
|
||||||
|
* text selection started inside the dialog and released outside it used to
|
||||||
|
* land on the backdrop and close the dialog. */
|
||||||
|
export function Modal({
|
||||||
|
onDismiss,
|
||||||
|
backdropDismiss = true,
|
||||||
|
layer = 'dialog',
|
||||||
|
padding = 'p-6',
|
||||||
|
role,
|
||||||
|
children,
|
||||||
|
...aria
|
||||||
|
}: Props) {
|
||||||
|
const [id] = useState(() => ++opened)
|
||||||
|
const dismissRef = useRef(onDismiss)
|
||||||
|
dismissRef.current = onDismiss
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
open.add(id)
|
||||||
|
const onKey = (e: KeyboardEvent) => {
|
||||||
|
if (e.key !== 'Escape' || e.defaultPrevented) return
|
||||||
|
if (id !== Math.max(...open)) return
|
||||||
|
// A menu over the dialog closes itself on Esc; the dialog stays.
|
||||||
|
if (menuOpen()) return
|
||||||
|
const dismiss = dismissRef.current
|
||||||
|
if (!dismiss) return
|
||||||
|
e.preventDefault()
|
||||||
|
dismiss()
|
||||||
|
}
|
||||||
|
window.addEventListener('keydown', onKey)
|
||||||
|
return () => {
|
||||||
|
open.delete(id)
|
||||||
|
window.removeEventListener('keydown', onKey)
|
||||||
|
}
|
||||||
|
}, [id])
|
||||||
|
|
||||||
|
const pressed = useRef(false)
|
||||||
|
const released = useRef(false)
|
||||||
|
|
||||||
|
return createPortal(
|
||||||
|
<div
|
||||||
|
aria-modal="true"
|
||||||
|
role={role}
|
||||||
|
{...aria}
|
||||||
|
className={`fixed inset-0 ${layer === 'nested' ? 'z-[60]' : 'z-50'} flex items-center justify-center bg-black/40 backdrop-blur-[3px] ${padding}`}
|
||||||
|
// React bubbles events through portals, so a nested dialog's or menu's
|
||||||
|
// pointer events reach here too; `target === currentTarget` keeps only
|
||||||
|
// the ones on THIS backdrop.
|
||||||
|
onPointerDown={(e) => {
|
||||||
|
// A press that closes an open menu closes only the menu.
|
||||||
|
pressed.current = e.target === e.currentTarget && e.button === 0 && !menuOpen()
|
||||||
|
released.current = false
|
||||||
|
}}
|
||||||
|
onPointerUp={(e) => {
|
||||||
|
released.current = e.target === e.currentTarget
|
||||||
|
}}
|
||||||
|
onClick={(e) => {
|
||||||
|
const outside = pressed.current && released.current && e.target === e.currentTarget
|
||||||
|
pressed.current = released.current = false
|
||||||
|
if (outside && backdropDismiss) dismissRef.current?.()
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</div>,
|
||||||
|
document.body,
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,30 +1,38 @@
|
|||||||
/**
|
/**
|
||||||
* The deck's two-way mode switch: two small stacked tabs in a well, the chosen
|
* The deck's two-way mode switch: two small stacked tabs in a well, the chosen
|
||||||
* one lit. BEAT / MAN (loops) and HOT / MEM (the cue bank) are both this.
|
* one lit. BEAT / MAN (loops) and HOT / MEM (the cue bank) are both this.
|
||||||
|
* With exactly two options a click anywhere on it flips to the other one;
|
||||||
|
* with more, each tab selects itself.
|
||||||
*/
|
*/
|
||||||
export function ModeSwitch<T extends string>({
|
export function ModeSwitch<T extends string>({
|
||||||
label,
|
label,
|
||||||
value,
|
value,
|
||||||
options,
|
options,
|
||||||
|
disabled = false,
|
||||||
onChange,
|
onChange,
|
||||||
}: {
|
}: {
|
||||||
/** Names the group for assistive tech ("Loop mode", "Cue bank"). */
|
/** Names the group for assistive tech ("Loop mode", "Cue bank"). */
|
||||||
label: string
|
label: string
|
||||||
value: T
|
value: T
|
||||||
options: { value: T; text: string; title: string }[]
|
options: { value: T; text: string; title: string }[]
|
||||||
|
disabled?: boolean
|
||||||
onChange: (value: T) => void
|
onChange: (value: T) => void
|
||||||
}) {
|
}) {
|
||||||
|
const other =
|
||||||
|
options.length === 2 && !disabled ? options.find((o) => o.value !== value) : undefined
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
role="group"
|
role="group"
|
||||||
aria-label={label}
|
aria-label={label}
|
||||||
className="well flex h-10 shrink-0 flex-col justify-center gap-0.5 rounded-[10px] p-0.5"
|
onClick={other ? () => onChange(other.value) : undefined}
|
||||||
|
className={`well ${other ? 'cursor-pointer ' : ''}${disabled ? 'opacity-40 ' : ''}flex h-10 shrink-0 flex-col justify-center gap-0.5 rounded-[10px] p-0.5`}
|
||||||
>
|
>
|
||||||
{options.map((o) => (
|
{options.map((o) => (
|
||||||
<button
|
<button
|
||||||
key={o.value}
|
key={o.value}
|
||||||
onClick={() => onChange(o.value)}
|
onClick={other ? undefined : () => onChange(o.value)}
|
||||||
title={o.title}
|
title={o.title}
|
||||||
|
disabled={disabled}
|
||||||
aria-pressed={value === o.value}
|
aria-pressed={value === o.value}
|
||||||
className={`h-[17px] rounded-[7px] px-[7px] text-[9px] font-bold tracking-[0.08em] transition-colors ${
|
className={`h-[17px] rounded-[7px] px-[7px] text-[9px] font-bold tracking-[0.08em] transition-colors ${
|
||||||
value === o.value ? 'btn-primary' : 'text-faint hover:text-text'
|
value === o.value ? 'btn-primary' : 'text-faint hover:text-text'
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect, useMemo, useState } from 'react'
|
import { useEffect, useMemo, useState } from 'react'
|
||||||
import { keepPreviousData, useQuery } from '@tanstack/react-query'
|
import { keepPreviousData, useQuery } from '@tanstack/react-query'
|
||||||
import { api, type NormalizeOptions, type NormalizePreview, type NormalizeRow } from '../api'
|
import { api, type NormalizeOptions, type NormalizePreview, type NormalizeRow } from '../api'
|
||||||
import { LevelInput, useAppSetting } from './AppSettings'
|
import { LevelInput, useAppSetting } from './AppSettings'
|
||||||
import { Icon } from '../lib/icons'
|
import { Icon } from '../lib/icons'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
ids: string[]
|
ids: string[]
|
||||||
@@ -58,12 +58,6 @@ export function NormalizeDialog({ ids, onRun, onClose, onError }: Props) {
|
|||||||
const p: NormalizePreview | undefined = preview.data
|
const p: NormalizePreview | undefined = preview.data
|
||||||
const count = p?.tracks_to_process ?? 0
|
const count = p?.tracks_to_process ?? 0
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && !busy && onClose()
|
|
||||||
window.addEventListener('keydown', onKey)
|
|
||||||
return () => window.removeEventListener('keydown', onKey)
|
|
||||||
}, [busy, onClose])
|
|
||||||
|
|
||||||
const summary = useMemo(() => {
|
const summary = useMemo(() => {
|
||||||
if (!p) return []
|
if (!p) return []
|
||||||
const rows = p.rows
|
const rows = p.rows
|
||||||
@@ -105,13 +99,9 @@ export function NormalizeDialog({ ids, onRun, onClose, onError }: Props) {
|
|||||||
|
|
||||||
const measureUnit = opts?.measure === 'rms' ? 'dB' : 'LUFS'
|
const measureUnit = opts?.measure === 'rms' ? 'dB' : 'LUFS'
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<div
|
<Modal onDismiss={busy ? null : onClose}>
|
||||||
aria-modal="true"
|
<div className="flex max-h-[80vh] w-full max-w-lg flex-col overflow-hidden glass-overlay">
|
||||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6"
|
|
||||||
onClick={() => !busy && onClose()}
|
|
||||||
>
|
|
||||||
<div className="flex max-h-[80vh] w-full max-w-lg flex-col overflow-hidden glass-overlay" onClick={(e) => e.stopPropagation()}>
|
|
||||||
<div className="border-b border-line px-5 py-4">
|
<div className="border-b border-line px-5 py-4">
|
||||||
<div className="text-[15px] font-semibold tracking-tight">Normalize</div>
|
<div className="text-[15px] font-semibold tracking-tight">Normalize</div>
|
||||||
<div className="text-xs text-muted">
|
<div className="text-xs text-muted">
|
||||||
@@ -198,7 +188,6 @@ export function NormalizeDialog({ ids, onRun, onClose, onError }: Props) {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect, useRef, useState } from 'react'
|
import { useEffect, useRef, useState } from 'react'
|
||||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { api, type RemapPreview } from '../api'
|
import { api, type RemapPreview } from '../api'
|
||||||
import type { ToastMsg } from './Toast'
|
import type { ToastMsg } from './Toast'
|
||||||
import { Icon } from '../lib/icons'
|
import { Icon } from '../lib/icons'
|
||||||
import { invalidateTrackLists } from '../lib/trackQueries'
|
import { invalidateTrackLists } from '../lib/trackQueries'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
onClose: () => void
|
onClose: () => void
|
||||||
@@ -107,14 +107,10 @@ export function PathMappingDialog({ onClose, onNotify, onError }: Props) {
|
|||||||
const collides = (preview?.collisions ?? 0) > 0
|
const collides = (preview?.collisions ?? 0) > 0
|
||||||
const canCommit = !!from.trim() && !!to.trim() && !collides
|
const canCommit = !!from.trim() && !!to.trim() && !collides
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<div
|
<Modal onDismiss={onClose}>
|
||||||
aria-modal="true" className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6"
|
|
||||||
onClick={onClose}
|
|
||||||
>
|
|
||||||
<div
|
<div
|
||||||
className="flex max-h-[85vh] w-full max-w-xl flex-col overflow-hidden glass-overlay"
|
className="flex max-h-[85vh] w-full max-w-xl flex-col overflow-hidden glass-overlay"
|
||||||
onClick={(e) => e.stopPropagation()}
|
|
||||||
>
|
>
|
||||||
<div className="border-b border-line px-5 py-4">
|
<div className="border-b border-line px-5 py-4">
|
||||||
<div className="text-[15px] font-semibold tracking-tight">Path Remapping</div>
|
<div className="text-[15px] font-semibold tracking-tight">Path Remapping</div>
|
||||||
@@ -264,8 +260,7 @@ export function PathMappingDialog({ onClose, onNotify, onError }: Props) {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1625,11 +1625,10 @@ export function PrepStrip({
|
|||||||
A container, so the row gives way in stages as the window narrows
|
A container, so the row gives way in stages as the window narrows
|
||||||
instead of the pads sliding under the tempo group: the pads drop
|
instead of the pads sliding under the tempo group: the pads drop
|
||||||
their names first (each pad queries its own width, see HotcueBar),
|
their names first (each pad queries its own width, see HotcueBar),
|
||||||
then below 77rem the tempo group folds into one BPM button, and below
|
then below 77rem the tempo group folds into one BPM button. That is
|
||||||
63rem the Grid toggle keeps only its icon. Those are the row's
|
the row's measured width just before the pad bank would hit its
|
||||||
measured widths just before the pad bank would hit its minimum (with
|
minimum (with a lockable grid's extra Lock button, and the Hot / Mem
|
||||||
a lockable grid's extra Lock button, and the Hot / Mem toggle's
|
toggle's ~3rem with its gap), so move it with the controls. */}
|
||||||
~3rem with its gap), so move them with the controls. */}
|
|
||||||
<div className="@container flex h-11 shrink-0 items-center gap-3">
|
<div className="@container flex h-11 shrink-0 items-center gap-3">
|
||||||
<button
|
<button
|
||||||
onClick={toggle}
|
onClick={toggle}
|
||||||
@@ -1752,31 +1751,26 @@ export function PrepStrip({
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{DIVIDER}
|
{DIVIDER}
|
||||||
<TempoControls {...tempoProps} className="@max-[77rem]:hidden" />
|
<ModeSwitch
|
||||||
<TempoFold locked={tempoProps.locked} className="hidden @max-[77rem]:flex">
|
label="Deck mode"
|
||||||
<TempoControls {...tempoProps} />
|
value={gridMode ? 'grid' : 'cues'}
|
||||||
</TempoFold>
|
options={[
|
||||||
<button
|
{ value: 'cues', text: 'CUES', title: 'Cues: the hotcue pads or memory cues' },
|
||||||
onClick={() => {
|
{ value: 'grid', text: 'GRID', title: 'Edit the beatgrid: markers, phase, reset' },
|
||||||
setGridMode((g) => !g)
|
]}
|
||||||
|
disabled={!track}
|
||||||
|
onChange={(m) => {
|
||||||
|
setGridMode(m === 'grid')
|
||||||
setPadMenu(null)
|
setPadMenu(null)
|
||||||
setRenamingSlot(null)
|
setRenamingSlot(null)
|
||||||
setMemoryMenu(null)
|
setMemoryMenu(null)
|
||||||
setRenamingMemory(null)
|
setRenamingMemory(null)
|
||||||
}}
|
}}
|
||||||
aria-pressed={gridMode}
|
/>
|
||||||
disabled={!track}
|
<TempoControls {...tempoProps} className="@max-[77rem]:hidden" />
|
||||||
title={gridMode ? 'Back to the hotcue pads' : 'Edit the beatgrid: markers, phase, reset'}
|
<TempoFold locked={tempoProps.locked} className="hidden @max-[77rem]:flex">
|
||||||
aria-label="Grid"
|
<TempoControls {...tempoProps} />
|
||||||
className={`flex h-10 shrink-0 items-center gap-1.5 rounded-xl px-3 text-xs font-semibold transition-colors disabled:opacity-40 @max-[63rem]:w-10 @max-[63rem]:justify-center @max-[63rem]:px-0 ${
|
</TempoFold>
|
||||||
gridMode
|
|
||||||
? 'bg-gold/15 text-gold shadow-[inset_0_0_0_1px_rgb(255_200_97/0.5),0_0_16px_-4px_rgb(255_200_97/0.6)]'
|
|
||||||
: 'btn-glass text-text'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<Icon name="grid" size={14} />
|
|
||||||
<span className="@max-[63rem]:hidden">Grid</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{memoryMenu && (
|
{memoryMenu && (
|
||||||
|
|||||||
@@ -0,0 +1,382 @@
|
|||||||
|
import { useEffect, useRef, useState } from 'react'
|
||||||
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { api, type ExportRunOptions, type ExportSet, type JobStatus, type PushPreview, type PushTarget } from '../api'
|
||||||
|
import { askConfirm } from '../lib/confirm'
|
||||||
|
import { localLibraryProblem } from '../lib/platformCopy'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Push a "computer" set into this computer's Traktor / rekordbox: confirm what
|
||||||
|
* is about to happen, then watch it happen. The sibling of `ExportRunDialog`,
|
||||||
|
* with the same rule — the preview takes the same body as the run, and is
|
||||||
|
* fetched fresh every time, never cached: the set's references are live.
|
||||||
|
*
|
||||||
|
* A running DJ app BLOCKS the push (Traktor writes its collection back when it
|
||||||
|
* quits, undoing it), and the preview re-checks every two seconds while it does,
|
||||||
|
* so quitting the app is all it takes. Overwrite is confirmed once more, naming
|
||||||
|
* the other pushes it removes. Normalise is not here: the pushed files are
|
||||||
|
* shared by every set, so their level is a setting (Settings → Local libraries).
|
||||||
|
*
|
||||||
|
* A library the set names that is not on THIS computer is skipped, not a block:
|
||||||
|
* a set's targets are shared by every computer that opens the library.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const POLL_MS = 300
|
||||||
|
|
||||||
|
function gb(bytes: number): string {
|
||||||
|
if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(1)} GB`
|
||||||
|
if (bytes >= 1e6) return `${(bytes / 1e6).toFixed(0)} MB`
|
||||||
|
return `${(bytes / 1e3).toFixed(0)} kB`
|
||||||
|
}
|
||||||
|
|
||||||
|
const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
set: ExportSet
|
||||||
|
onClose: () => void
|
||||||
|
onDone: (msg: string) => void
|
||||||
|
onError: (msg: string) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
interface TargetResult {
|
||||||
|
name: string
|
||||||
|
added: number
|
||||||
|
updated: number
|
||||||
|
removed: number
|
||||||
|
kept: string[]
|
||||||
|
replaced?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PushRunDialog({ set, onClose, onDone, onError }: Props) {
|
||||||
|
const qc = useQueryClient()
|
||||||
|
const [job, setJob] = useState<JobStatus | null>(null)
|
||||||
|
const [starting, setStarting] = useState(false)
|
||||||
|
// Remembered on the set, sent with the click, as an export's are.
|
||||||
|
const [lockGrids, setLockGrids] = useState(set.lock_grids ?? true)
|
||||||
|
const [autoGain, setAutoGain] = useState(set.auto_gain ?? true)
|
||||||
|
const pollRef = useRef<number | null>(null)
|
||||||
|
const options: ExportRunOptions = { lock_grids: lockGrids, auto_gain: autoGain }
|
||||||
|
const overwrite = set.mode === 'overwrite'
|
||||||
|
|
||||||
|
const preview = useQuery<PushPreview>({
|
||||||
|
queryKey: ['push-preview', set.id, options],
|
||||||
|
queryFn: () => api.pushPreview(set.id, options),
|
||||||
|
enabled: !job,
|
||||||
|
staleTime: 0,
|
||||||
|
gcTime: 0,
|
||||||
|
// Quitting the DJ app is the fix for the commonest block: notice it.
|
||||||
|
refetchInterval: (q) => (q.state.data?.blocked === 'app_running' ? 2000 : false),
|
||||||
|
})
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!job || job.state !== 'running') return
|
||||||
|
pollRef.current = window.setInterval(async () => {
|
||||||
|
try {
|
||||||
|
const next = await api.job(job.id)
|
||||||
|
setJob(next)
|
||||||
|
if (next.state !== 'running') {
|
||||||
|
if (pollRef.current) window.clearInterval(pollRef.current)
|
||||||
|
if (next.state === 'done') {
|
||||||
|
qc.invalidateQueries({ queryKey: ['local-libraries'] })
|
||||||
|
onDone(doneMessage(set.name, next.result))
|
||||||
|
} else if (next.state === 'failed') {
|
||||||
|
onError(next.error || 'Push failed')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
onError((e as Error).message)
|
||||||
|
if (pollRef.current) window.clearInterval(pollRef.current)
|
||||||
|
}
|
||||||
|
}, POLL_MS)
|
||||||
|
return () => {
|
||||||
|
if (pollRef.current) window.clearInterval(pollRef.current)
|
||||||
|
}
|
||||||
|
}, [job, qc, set.name, onDone, onError])
|
||||||
|
|
||||||
|
const p = preview.data
|
||||||
|
const blocked = p?.blocked ?? null
|
||||||
|
const active = p?.targets.filter((t) => !t.skipped) ?? []
|
||||||
|
|
||||||
|
const start = async () => {
|
||||||
|
if (overwrite && p) {
|
||||||
|
const wiped = active.flatMap((t) => t.wipes_sets)
|
||||||
|
const ok = await askConfirm({
|
||||||
|
title: `Replace ${active.map((t) => t.name).join(' and ')}’s library?`,
|
||||||
|
body:
|
||||||
|
`Everything in it is replaced by “${set.name}” — your own tracks and playlists too` +
|
||||||
|
(wiped.length ? `, and the pushes of ${wiped.map((n) => `“${n}”`).join(', ')}` : '') +
|
||||||
|
'. A backup is kept, but the DJ app will only show this set.',
|
||||||
|
confirmLabel: 'Replace',
|
||||||
|
})
|
||||||
|
if (!ok) return
|
||||||
|
}
|
||||||
|
setStarting(true)
|
||||||
|
try {
|
||||||
|
setJob(await api.runPush(set.id, options))
|
||||||
|
qc.invalidateQueries({ queryKey: ['exports'] })
|
||||||
|
} catch (e) {
|
||||||
|
onError((e as Error).message)
|
||||||
|
} finally {
|
||||||
|
setStarting(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const cancel = async () => {
|
||||||
|
if (!job) return
|
||||||
|
try {
|
||||||
|
await api.cancelJob(job.id)
|
||||||
|
} catch (e) {
|
||||||
|
onError((e as Error).message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const running = job?.state === 'running'
|
||||||
|
const finished = job != null && job.state !== 'running'
|
||||||
|
const pct =
|
||||||
|
job?.state === 'done' ? 100 : job && job.total > 0 ? Math.min(100, (job.done / job.total) * 100) : null
|
||||||
|
const results = ((job?.result as { targets?: TargetResult[] } | null)?.targets ?? [])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal onDismiss={onClose} padding="p-4">
|
||||||
|
<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">
|
||||||
|
{overwrite ? 'Replace with' : 'Push'} “{set.name}”
|
||||||
|
</h2>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-4 px-5 py-4 text-sm">
|
||||||
|
{!job && (
|
||||||
|
<>
|
||||||
|
{preview.isLoading && <div className="text-faint">Checking…</div>}
|
||||||
|
{preview.isError && <div className="text-pink">{(preview.error as Error).message}</div>}
|
||||||
|
|
||||||
|
{p && (
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
{p.targets.map((t) => (
|
||||||
|
<TargetLine key={t.platform} target={t} overwrite={overwrite} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{p && blocked !== 'nothing_to_push' && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="text-text">
|
||||||
|
{plural(p.pushable, 'track')}
|
||||||
|
{p.playlists.length > 0 && ` · ${plural(p.playlists.length, 'playlist')}`}
|
||||||
|
<span className="text-muted">
|
||||||
|
{p.unchanged > 0 && ` · ${p.unchanged} already copied`} · {gb(p.total_bytes)} to copy
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="text-xs text-faint">
|
||||||
|
Into <span className="font-mono">{p.audio_root}</span>
|
||||||
|
{p.free_bytes != null && (
|
||||||
|
<span className={p.enough_space === false ? 'text-pink' : ''}>
|
||||||
|
{' '}· {gb(p.free_bytes)} free{p.enough_space === false && ' — not enough space'}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{p.missing.length > 0 && (
|
||||||
|
<div className="rounded well px-3 py-2 text-xs text-pink">
|
||||||
|
{plural(p.missing.length, 'track')} will be skipped — the audio file is not on this disk:
|
||||||
|
<div className="mt-1 text-faint">{p.missing.slice(0, 4).join(', ')}</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{overwrite && active.some((t) => t.wipes_sets.length) && (
|
||||||
|
<div className="rounded well px-3 py-2 text-xs text-gold">
|
||||||
|
Also removes what{' '}
|
||||||
|
{[...new Set(active.flatMap((t) => t.wipes_sets))].map((n) => `“${n}”`).join(', ')}{' '}
|
||||||
|
pushed there, and deletes its files.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{active.some((t) => t.platform === 'traktor') && (
|
||||||
|
<label className="flex cursor-pointer items-start gap-2.5">
|
||||||
|
<input type="checkbox" className="mt-0.5" checked={lockGrids}
|
||||||
|
onChange={(e) => setLockGrids(e.target.checked)} />
|
||||||
|
<span className="min-w-0">
|
||||||
|
<span className="block text-sm text-text">Lock beatgrids</span>
|
||||||
|
<span className="block text-xs text-faint">
|
||||||
|
Stops Traktor re-analysing the tracks when they’re loaded, which can change the
|
||||||
|
BPM or move the grid.
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
<label className="flex cursor-pointer items-start gap-2.5">
|
||||||
|
<input type="checkbox" className="mt-0.5" checked={autoGain}
|
||||||
|
onChange={(e) => setAutoGain(e.target.checked)} />
|
||||||
|
<span className="min-w-0">
|
||||||
|
<span className="block text-sm text-text">Auto gain</span>
|
||||||
|
<span className="block text-xs text-faint">
|
||||||
|
Sets each track’s auto gain from its loudness, so tracks load at matching levels.
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
<div className="text-xs text-faint">
|
||||||
|
{p.normalised > 0
|
||||||
|
? `${plural(p.normalised, 'copy', 'copies')} brought to the shared level. `
|
||||||
|
: ''}
|
||||||
|
Normalising is set for all pushes in Settings → Local libraries.
|
||||||
|
</div>
|
||||||
|
{p.to_measure > 0 && (
|
||||||
|
<div className="text-xs text-faint">
|
||||||
|
{plural(p.to_measure, 'track')} measured first (about a second each).
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{blocked === 'app_running' && (
|
||||||
|
<div className="rounded border border-pink/40 bg-well px-3 py-2 text-xs text-pink">
|
||||||
|
Quit {active.filter((t) => t.running).map((t) => t.name).join(' and ')} to push —
|
||||||
|
it would overwrite the push when it next saves its library.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{blocked === 'target_unavailable' && (
|
||||||
|
<div className="rounded border border-pink/40 bg-well px-3 py-2 text-xs text-pink">
|
||||||
|
Konduktor can’t push into every library this set is for. Check Settings → Local
|
||||||
|
libraries, or edit the set.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{blocked === 'no_library_here' && p && (
|
||||||
|
<div className="rounded border border-pink/40 bg-well px-3 py-2 text-xs text-pink">
|
||||||
|
{p.targets.map((t) => t.name).join(' and ')}{' '}
|
||||||
|
{p.targets.length === 1 ? 'isn’t' : 'aren’t'} on this computer, so there’s nothing to
|
||||||
|
push into. Set {p.targets.length === 1 ? 'its' : 'their'} location in Settings → Local
|
||||||
|
libraries, or edit the set.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{blocked === 'nothing_to_push' && p && (
|
||||||
|
<div className={`rounded well px-3 py-2 text-xs ${p.tracks ? 'text-pink' : 'text-muted'}`}>
|
||||||
|
{p.tracks === 0
|
||||||
|
? 'There’s nothing to push yet — add some tracks or a playlist.'
|
||||||
|
: `None of the ${plural(p.tracks, 'track')} can be pushed — their audio files are not on this disk.`}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{job && (
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div className="text-text">{job.state === 'done' ? 'Pushed.' : job.message || 'Working…'}</div>
|
||||||
|
<div className="h-2 overflow-hidden rounded-full bg-well">
|
||||||
|
<div
|
||||||
|
className={`h-full transition-[width] duration-200 ${job.state === 'failed' ? 'bg-pink' : 'bg-accent'} ${
|
||||||
|
pct == null ? 'w-1/3 animate-pulse' : ''
|
||||||
|
}`}
|
||||||
|
style={pct == null ? undefined : { width: `${pct}%` }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{pct != null && running && job.unit === 'bytes' && (
|
||||||
|
<div className="text-xs text-faint">{gb(job.done)} of {gb(job.total)}</div>
|
||||||
|
)}
|
||||||
|
{job.state === 'cancelled' && (
|
||||||
|
<div className="text-xs text-muted">
|
||||||
|
Cancelled. A library already saved keeps the push; any other was left as it was.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{job.state === 'failed' && <div className="text-xs text-pink">{job.error}</div>}
|
||||||
|
{job.state === 'done' &&
|
||||||
|
results.map((r) => (
|
||||||
|
<div key={r.name} className="space-y-0.5 text-xs">
|
||||||
|
<div className="text-mint">{resultLine(r)}</div>
|
||||||
|
{r.kept.length > 0 && (
|
||||||
|
<div className="text-gold">
|
||||||
|
Left in {r.name}: {r.kept.slice(0, 4).join(', ')}
|
||||||
|
{r.kept.length > 4 && ` and ${r.kept.length - 4} more`} — {r.name} still lists
|
||||||
|
them in its History, Sampler or another list, so they stay. The next push tries
|
||||||
|
again.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex justify-end gap-2 border-t border-line px-5 py-3">
|
||||||
|
{running ? (
|
||||||
|
<>
|
||||||
|
<button onClick={cancel} className="btn-glass rounded-full px-3 py-1.5 text-sm text-muted hover:text-text">
|
||||||
|
Cancel push
|
||||||
|
</button>
|
||||||
|
<button onClick={onClose} className="rounded-md px-3 py-1.5 text-sm text-faint hover:text-text"
|
||||||
|
title="The push keeps running">
|
||||||
|
Hide
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<button onClick={onClose} className="btn-glass rounded-full px-3 py-1.5 text-sm text-muted hover:text-text">
|
||||||
|
{finished ? 'Close' : 'Cancel'}
|
||||||
|
</button>
|
||||||
|
{!finished && (
|
||||||
|
<button
|
||||||
|
disabled={starting || preview.isFetching || !p || !!blocked || p.enough_space === false}
|
||||||
|
onClick={start}
|
||||||
|
className="rounded-full btn-primary px-3 py-1.5 text-sm font-semibold disabled:opacity-40"
|
||||||
|
>
|
||||||
|
{starting ? 'Starting…' : overwrite ? 'Replace' : `Push ${p && !blocked ? p.pushable : ''}`.trim()}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function TargetLine({ target, overwrite }: { target: PushTarget; overwrite: boolean }) {
|
||||||
|
if (target.skipped) {
|
||||||
|
return (
|
||||||
|
<div className="rounded-md well px-3 py-2">
|
||||||
|
<div className="flex items-baseline gap-2">
|
||||||
|
<span className="text-faint">{target.name}</span>
|
||||||
|
<span className="ml-auto text-xs text-faint">not on this computer — skipped</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
const problem = localLibraryProblem({ ...target, detected: true })
|
||||||
|
const counts = overwrite
|
||||||
|
? 'replaced by this set'
|
||||||
|
: [
|
||||||
|
target.add && `${target.add} to add`,
|
||||||
|
target.already && `${target.already} already there`,
|
||||||
|
target.remove && `${target.remove} to remove`,
|
||||||
|
].filter(Boolean).join(' · ') || 'nothing to change'
|
||||||
|
return (
|
||||||
|
<div className="rounded-md well px-3 py-2">
|
||||||
|
<div className="flex items-baseline gap-2">
|
||||||
|
<span className="text-text">{target.name}</span>
|
||||||
|
<span className={`ml-auto text-xs ${problem || target.running ? 'text-pink' : 'text-muted'}`}>
|
||||||
|
{problem ?? (target.running ? 'running' : counts)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{target.path && (
|
||||||
|
<div title={target.path} dir="rtl" className="truncate text-left font-mono text-[11px] text-faint">
|
||||||
|
{target.path}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function resultLine(r: TargetResult): string {
|
||||||
|
if (r.replaced) return `${r.name}: replaced — ${plural(r.added, 'track')}`
|
||||||
|
const parts = [
|
||||||
|
r.added && `${r.added} added`,
|
||||||
|
r.updated && `${r.updated} updated`,
|
||||||
|
r.removed && `${r.removed} removed`,
|
||||||
|
].filter(Boolean)
|
||||||
|
return `${r.name}: ${parts.length ? parts.join(', ') : 'already up to date'}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function doneMessage(name: string, result: Record<string, unknown> | null): string {
|
||||||
|
const r = result as { targets?: TargetResult[]; skipped_targets?: string[] } | null
|
||||||
|
const targets = (r?.targets ?? []).map((t) => t.name)
|
||||||
|
const skipped = r?.skipped_targets ?? []
|
||||||
|
return `Pushed “${name}” into ${targets.join(' and ') || 'this computer'}` +
|
||||||
|
(skipped.length ? ` (${skipped.join(' and ')} skipped — not on this computer)` : '')
|
||||||
|
}
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect, useRef, useState } from 'react'
|
import { useEffect, useRef, useState } from 'react'
|
||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { api } from '../api'
|
import { api } from '../api'
|
||||||
import { flushPrefs } from '../lib/prefs'
|
import { flushPrefs } from '../lib/prefs'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ask before quitting with unsaved changes: Save · Discard · Cancel.
|
* Ask before quitting with unsaved changes: Save · Discard · Cancel.
|
||||||
@@ -99,21 +99,9 @@ export function QuitGuard() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!asking) return
|
|
||||||
const onKey = (e: KeyboardEvent) => {
|
|
||||||
if (e.key === 'Escape' && !busy) void cancel()
|
|
||||||
}
|
|
||||||
window.addEventListener('keydown', onKey)
|
|
||||||
return () => window.removeEventListener('keydown', onKey)
|
|
||||||
})
|
|
||||||
|
|
||||||
if (!asking) return null
|
if (!asking) return null
|
||||||
return createPortal(
|
return (
|
||||||
<div
|
<Modal onDismiss={busy ? null : () => void cancel()} layer="nested">
|
||||||
aria-modal="true"
|
|
||||||
className="fixed inset-0 z-[60] flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6"
|
|
||||||
>
|
|
||||||
<div className="w-full max-w-sm overflow-hidden glass-overlay">
|
<div className="w-full max-w-sm overflow-hidden glass-overlay">
|
||||||
<div className="border-b border-line px-5 py-4 text-[15px] font-semibold tracking-tight">
|
<div className="border-b border-line px-5 py-4 text-[15px] font-semibold tracking-tight">
|
||||||
Save changes before quitting?
|
Save changes before quitting?
|
||||||
@@ -147,7 +135,6 @@ export function QuitGuard() {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { createPortal } from 'react-dom'
|
import { useState } from 'react'
|
||||||
import { useEffect, useState } from 'react'
|
|
||||||
import { api, type PathMapping, type RelocationVolume } from '../api'
|
import { api, type PathMapping, type RelocationVolume } from '../api'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
volumes: RelocationVolume[]
|
volumes: RelocationVolume[]
|
||||||
@@ -51,21 +51,12 @@ export function RelocateDialog({ volumes, onAnswered, onOpenManual, onError }: P
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && !busy && answer([])
|
|
||||||
window.addEventListener('keydown', onKey)
|
|
||||||
return () => window.removeEventListener('keydown', onKey)
|
|
||||||
})
|
|
||||||
|
|
||||||
const set = (root: string, to: string | null) => setChoice((c) => ({ ...c, [root]: to }))
|
const set = (root: string, to: string | null) => setChoice((c) => ({ ...c, [root]: to }))
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
// No close on a backdrop click: dismissing lasts until the library is
|
// Esc is "Not now", but a backdrop click is not: dismissing lasts until
|
||||||
// reopened, which is too much for a stray click to decide.
|
// the library is reopened, which is too much for a stray click to decide.
|
||||||
<div
|
<Modal onDismiss={busy ? null : () => void answer([])} backdropDismiss={false}>
|
||||||
aria-modal="true"
|
|
||||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6"
|
|
||||||
>
|
|
||||||
<div className="flex max-h-[85vh] w-full max-w-xl flex-col overflow-hidden glass-overlay">
|
<div className="flex max-h-[85vh] w-full max-w-xl flex-col overflow-hidden glass-overlay">
|
||||||
<div className="border-b border-line px-5 py-4">
|
<div className="border-b border-line px-5 py-4">
|
||||||
<div className="text-[15px] font-semibold tracking-tight">Tracks not found</div>
|
<div className="text-[15px] font-semibold tracking-tight">Tracks not found</div>
|
||||||
@@ -116,8 +107,7 @@ export function RelocateDialog({ volumes, onAnswered, onOpenManual, onError }: P
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { createPortal } from 'react-dom'
|
import { useState } from 'react'
|
||||||
import { useEffect, useState } from 'react'
|
|
||||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { api } from '../api'
|
import { api } from '../api'
|
||||||
import { size } from './ConvertStemsDialog'
|
import { size } from './ConvertStemsDialog'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Settings → Remote audio: this computer's copies of a remote library's audio.
|
* Settings → Remote audio: this computer's copies of a remote library's audio.
|
||||||
@@ -21,12 +21,6 @@ export function RemoteCacheSettings({ onClose }: { onClose: () => void }) {
|
|||||||
const [busy, setBusy] = useState(false)
|
const [busy, setBusy] = useState(false)
|
||||||
const [error, setError] = useState<string | null>(null)
|
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 u = usage.data
|
const u = usage.data
|
||||||
const capGb = u ? Math.round(u.cap / 1024 ** 3) : null
|
const capGb = u ? Math.round(u.cap / 1024 ** 3) : null
|
||||||
|
|
||||||
@@ -54,13 +48,9 @@ export function RemoteCacheSettings({ onClose }: { onClose: () => void }) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<div
|
<Modal onDismiss={onClose}>
|
||||||
aria-modal="true"
|
<div className="flex w-full max-w-md flex-col overflow-hidden glass-overlay">
|
||||||
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">
|
<div className="flex items-center justify-between border-b border-line px-5 py-3">
|
||||||
<h2 className="text-sm font-semibold text-text">Remote audio</h2>
|
<h2 className="text-sm font-semibold text-text">Remote audio</h2>
|
||||||
<button onClick={onClose} className="rounded px-1.5 text-faint hover:text-text" aria-label="Close">
|
<button onClick={onClose} className="rounded px-1.5 text-faint hover:text-text" aria-label="Close">
|
||||||
@@ -107,7 +97,6 @@ export function RemoteCacheSettings({ onClose }: { onClose: () => void }) {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
import { useState, type ReactNode } from 'react'
|
import { useState, type ReactNode } from 'react'
|
||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import {
|
import {
|
||||||
api,
|
api,
|
||||||
@@ -14,6 +13,7 @@ import {
|
|||||||
import { askConfirm } from '../lib/confirm'
|
import { askConfirm } from '../lib/confirm'
|
||||||
import { Icon } from '../lib/icons'
|
import { Icon } from '../lib/icons'
|
||||||
import { remoteHolder } from '../lib/platformCopy'
|
import { remoteHolder } from '../lib/platformCopy'
|
||||||
|
import { Modal } from './Modal'
|
||||||
import { OptionCard } from './OptionCard'
|
import { OptionCard } from './OptionCard'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -329,12 +329,8 @@ function PendingEditsDialog({
|
|||||||
setBusy(false)
|
setBusy(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return createPortal(
|
return (
|
||||||
<div
|
<Modal onDismiss={busy ? null : () => void choose('later')}>
|
||||||
aria-modal="true"
|
|
||||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-6 backdrop-blur-[3px]"
|
|
||||||
onKeyDown={(e) => e.key === 'Escape' && !busy && void choose('later')}
|
|
||||||
>
|
|
||||||
<div className="w-full max-w-sm overflow-hidden glass-overlay">
|
<div className="w-full max-w-sm overflow-hidden glass-overlay">
|
||||||
<div className="border-b border-line px-5 py-4 text-[15px] font-semibold tracking-tight">
|
<div className="border-b border-line px-5 py-4 text-[15px] font-semibold tracking-tight">
|
||||||
Unsaved edits from {edits.machine || 'another computer'}
|
Unsaved edits from {edits.machine || 'another computer'}
|
||||||
@@ -369,7 +365,6 @@ function PendingEditsDialog({
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect, useRef, useState, type ReactNode } from 'react'
|
import { useEffect, useRef, useState, type ReactNode } from 'react'
|
||||||
import type { SortingState } from '@tanstack/react-table'
|
import type { SortingState } from '@tanstack/react-table'
|
||||||
import { maxPosition, moveToPosition } from '../lib/playlistOrder'
|
import { maxPosition, moveToPosition } from '../lib/playlistOrder'
|
||||||
import { COLUMN_MENU } from '../lib/trackColumns'
|
import { COLUMN_MENU } from '../lib/trackColumns'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
/** The playlist's full entry order — never the sorted or filtered view, so
|
/** The playlist's full entry order — never the sorted or filtered view, so
|
||||||
@@ -50,14 +50,6 @@ export function SetPositionDialog({ order, ids, sorting, onMove, onClose }: Prop
|
|||||||
onClose()
|
onClose()
|
||||||
}
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const onKey = (e: KeyboardEvent) => {
|
|
||||||
if (e.key === 'Escape') onClose()
|
|
||||||
}
|
|
||||||
window.addEventListener('keydown', onKey)
|
|
||||||
return () => window.removeEventListener('keydown', onKey)
|
|
||||||
}, [onClose])
|
|
||||||
|
|
||||||
const option = (value: 'playlist' | 'sorted', label: string, detail: ReactNode) => (
|
const option = (value: 'playlist' | 'sorted', label: string, detail: ReactNode) => (
|
||||||
<label
|
<label
|
||||||
className={`flex cursor-pointer gap-3 rounded-lg px-3 py-2 ${
|
className={`flex cursor-pointer gap-3 rounded-lg px-3 py-2 ${
|
||||||
@@ -80,15 +72,10 @@ export function SetPositionDialog({ order, ids, sorting, onMove, onClose }: Prop
|
|||||||
|
|
||||||
const span = (p: number) => (count > 1 ? `#${p}–${p + count - 1}` : `#${p}`)
|
const span = (p: number) => (count > 1 ? `#${p}–${p + count - 1}` : `#${p}`)
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<div
|
<Modal onDismiss={onClose}>
|
||||||
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
|
<form
|
||||||
className="w-full max-w-sm overflow-hidden glass-overlay"
|
className="w-full max-w-sm overflow-hidden glass-overlay"
|
||||||
onClick={(e) => e.stopPropagation()}
|
|
||||||
onSubmit={(e) => {
|
onSubmit={(e) => {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
submit()
|
submit()
|
||||||
@@ -152,7 +139,6 @@ export function SetPositionDialog({ order, ids, sorting, onMove, onClose }: Prop
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -3,6 +3,7 @@ import { useQuery } from '@tanstack/react-query'
|
|||||||
import { api } from '../api'
|
import { api } from '../api'
|
||||||
import { AppSettings } from './AppSettings'
|
import { AppSettings } from './AppSettings'
|
||||||
import { useCaps } from '../lib/capabilities'
|
import { useCaps } from '../lib/capabilities'
|
||||||
|
import { LocalLibrariesSettings } from './LocalLibrariesSettings'
|
||||||
import { RemoteCacheSettings } from './RemoteCacheSettings'
|
import { RemoteCacheSettings } from './RemoteCacheSettings'
|
||||||
import { ShortcutsDialog } from './ShortcutsDialog'
|
import { ShortcutsDialog } from './ShortcutsDialog'
|
||||||
import { StemsSettings } from './StemsSettings'
|
import { StemsSettings } from './StemsSettings'
|
||||||
@@ -22,6 +23,7 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
|
|||||||
const [showStems, setShowStems] = useState(false)
|
const [showStems, setShowStems] = useState(false)
|
||||||
const [showCache, setShowCache] = useState(false)
|
const [showCache, setShowCache] = useState(false)
|
||||||
const [showApp, setShowApp] = useState(false)
|
const [showApp, setShowApp] = useState(false)
|
||||||
|
const [showLocal, setShowLocal] = useState(false)
|
||||||
const ref = useRef<HTMLDivElement>(null)
|
const ref = useRef<HTMLDivElement>(null)
|
||||||
// Path remapping is a library on THIS computer's business; a remote's
|
// Path remapping is a library on THIS computer's business; a remote's
|
||||||
// mapping is its server's configuration.
|
// mapping is its server's configuration.
|
||||||
@@ -123,6 +125,16 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
|
|||||||
<span className="text-[11px] text-faint">This computer's copies of the server's tracks</span>
|
<span className="text-[11px] text-faint">This computer's copies of the server's tracks</span>
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
setShowLocal(true)
|
||||||
|
setOpen(false)
|
||||||
|
}}
|
||||||
|
className={item}
|
||||||
|
>
|
||||||
|
<span className="text-sm text-text">Local libraries…</span>
|
||||||
|
<span className="text-[11px] text-faint">The Traktor and rekordbox a set is pushed into</span>
|
||||||
|
</button>
|
||||||
<button
|
<button
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setShowStems(true)
|
setShowStems(true)
|
||||||
@@ -149,6 +161,7 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
|
|||||||
{showStems && <StemsSettings onClose={() => setShowStems(false)} />}
|
{showStems && <StemsSettings onClose={() => setShowStems(false)} />}
|
||||||
{showCache && <RemoteCacheSettings onClose={() => setShowCache(false)} />}
|
{showCache && <RemoteCacheSettings onClose={() => setShowCache(false)} />}
|
||||||
{showApp && <AppSettings onClose={() => setShowApp(false)} />}
|
{showApp && <AppSettings onClose={() => setShowApp(false)} />}
|
||||||
|
{showLocal && <LocalLibrariesSettings onClose={() => setShowLocal(false)} />}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react'
|
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react'
|
||||||
import { useCaps } from '../lib/capabilities'
|
import { useCaps } from '../lib/capabilities'
|
||||||
import { Icon } from '../lib/icons'
|
import { Icon } from '../lib/icons'
|
||||||
@@ -24,6 +23,7 @@ import {
|
|||||||
type Layer,
|
type Layer,
|
||||||
type MouseGesture,
|
type MouseGesture,
|
||||||
} from '../lib/shortcuts'
|
} from '../lib/shortcuts'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
onClose: () => void
|
onClose: () => void
|
||||||
@@ -162,15 +162,10 @@ export function ShortcutsDialog({ onClose }: Props) {
|
|||||||
onPick: pickLayer,
|
onPick: pickLayer,
|
||||||
}
|
}
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<div
|
<Modal onDismiss={onClose}>
|
||||||
aria-modal="true"
|
|
||||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6"
|
|
||||||
onClick={onClose}
|
|
||||||
>
|
|
||||||
<div
|
<div
|
||||||
className="flex max-h-full w-full max-w-[960px] flex-col overflow-hidden glass-overlay"
|
className="flex max-h-full w-full max-w-[960px] flex-col overflow-hidden glass-overlay"
|
||||||
onClick={(e) => e.stopPropagation()}
|
|
||||||
>
|
>
|
||||||
<div className="flex flex-wrap items-center gap-3 border-b border-line py-3.5 pl-5 pr-4">
|
<div className="flex flex-wrap items-center gap-3 border-b border-line py-3.5 pl-5 pr-4">
|
||||||
<div className="text-[15px] font-semibold tracking-tight">Keyboard Shortcuts</div>
|
<div className="text-[15px] font-semibold tracking-tight">Keyboard Shortcuts</div>
|
||||||
@@ -309,8 +304,7 @@ export function ShortcutsDialog({ onClose }: Props) {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -774,10 +774,26 @@ export function Sidebar({
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="mt-3 shrink-0 px-4">
|
<div className="mt-3 flex shrink-0 items-center justify-between px-4">
|
||||||
<span className="text-[11px] font-semibold uppercase tracking-wider text-faint">
|
<span className="text-[11px] font-semibold uppercase tracking-wider text-faint">
|
||||||
Playlists
|
Playlists
|
||||||
</span>
|
</span>
|
||||||
|
{/* The same choices as right-clicking below the rows: straight to a
|
||||||
|
new playlist where there is nothing else to create, else the
|
||||||
|
menu, opened under the button. */}
|
||||||
|
{canCreate && (
|
||||||
|
<button
|
||||||
|
title={foldersSupported ? 'New playlist or folder' : 'New playlist'}
|
||||||
|
onClick={(e) => {
|
||||||
|
if (!foldersSupported) return startDraft('playlist', null)
|
||||||
|
const r = e.currentTarget.getBoundingClientRect()
|
||||||
|
setMenu({ x: r.left, y: r.bottom + 4, items: createItems(null) })
|
||||||
|
}}
|
||||||
|
className="rounded px-1 text-sm text-faint hover:text-text"
|
||||||
|
>
|
||||||
|
+
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Right-click here (below the rows) creates at the top level; rows
|
{/* Right-click here (below the rows) creates at the top level; rows
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect } from 'react'
|
|
||||||
import type { StemBatchResult } from '../api'
|
import type { StemBatchResult } from '../api'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The Details behind a finished conversion's toast: every track that was
|
* The Details behind a finished conversion's toast: every track that was
|
||||||
@@ -8,24 +7,14 @@ import type { StemBatchResult } from '../api'
|
|||||||
* into a toast).
|
* into a toast).
|
||||||
*/
|
*/
|
||||||
export function StemReportDialog({ result, onClose }: { result: StemBatchResult; onClose: () => void }) {
|
export function StemReportDialog({ result, onClose }: { result: StemBatchResult; onClose: () => void }) {
|
||||||
useEffect(() => {
|
|
||||||
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
|
|
||||||
window.addEventListener('keydown', onKey)
|
|
||||||
return () => window.removeEventListener('keydown', onKey)
|
|
||||||
}, [onClose])
|
|
||||||
|
|
||||||
const rows = [
|
const rows = [
|
||||||
...result.failed.map((s) => ({ ...s, failed: true })),
|
...result.failed.map((s) => ({ ...s, failed: true })),
|
||||||
...result.skipped.map((s) => ({ ...s, failed: false })),
|
...result.skipped.map((s) => ({ ...s, failed: false })),
|
||||||
]
|
]
|
||||||
const n = result.converted.length
|
const n = result.converted.length
|
||||||
return createPortal(
|
return (
|
||||||
<div
|
<Modal onDismiss={onClose} padding="p-4">
|
||||||
aria-modal="true"
|
<div className="flex max-h-[80vh] w-full max-w-lg flex-col overflow-hidden glass-overlay">
|
||||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4 backdrop-blur-[3px]"
|
|
||||||
onClick={onClose}
|
|
||||||
>
|
|
||||||
<div className="flex max-h-[80vh] w-full max-w-lg flex-col overflow-hidden glass-overlay" onClick={(e) => e.stopPropagation()}>
|
|
||||||
<div className="border-b border-line px-5 py-3 text-sm font-semibold text-text">
|
<div className="border-b border-line px-5 py-3 text-sm font-semibold text-text">
|
||||||
{n} converted to stems · {result.skipped.length} skipped · {result.failed.length} failed
|
{n} converted to stems · {result.skipped.length} skipped · {result.failed.length} failed
|
||||||
</div>
|
</div>
|
||||||
@@ -49,7 +38,6 @@ export function StemReportDialog({ result, onClose }: { result: StemBatchResult;
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { api, type StemTarget } from '../api'
|
import { api, type StemTarget } from '../api'
|
||||||
import { askConfirm } from '../lib/confirm'
|
import { askConfirm } from '../lib/confirm'
|
||||||
import { FolderPicker } from './FolderPicker'
|
import { FolderPicker } from './FolderPicker'
|
||||||
import { size } from './ConvertStemsDialog'
|
import { size } from './ConvertStemsDialog'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Settings → Stems (decided contents): the engine (status, download, install
|
* Settings → Stems (decided contents): the engine (status, download, install
|
||||||
@@ -40,12 +40,6 @@ export function StemsSettings({ onClose }: Props) {
|
|||||||
}
|
}
|
||||||
}, [install.data, qc])
|
}, [install.data, qc])
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && !picking && onClose()
|
|
||||||
window.addEventListener('keydown', onKey)
|
|
||||||
return () => window.removeEventListener('keydown', onKey)
|
|
||||||
}, [onClose, picking])
|
|
||||||
|
|
||||||
const act = async (fn: () => Promise<unknown>) => {
|
const act = async (fn: () => Promise<unknown>) => {
|
||||||
setBusy(true)
|
setBusy(true)
|
||||||
setError(null)
|
setError(null)
|
||||||
@@ -72,7 +66,7 @@ export function StemsSettings({ onClose }: Props) {
|
|||||||
const targetLabel = (t: StemTarget) =>
|
const targetLabel = (t: StemTarget) =>
|
||||||
t === 'macos-arm64' ? 'Apple silicon (GPU)' : t === 'windows-x64-cuda' ? 'NVIDIA GPU' : 'processor only'
|
t === 'macos-arm64' ? 'Apple silicon (GPU)' : t === 'windows-x64-cuda' ? 'NVIDIA GPU' : 'processor only'
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<>
|
<>
|
||||||
{picking && (
|
{picking && (
|
||||||
<FolderPicker
|
<FolderPicker
|
||||||
@@ -81,14 +75,9 @@ export function StemsSettings({ onClose }: Props) {
|
|||||||
onClose={() => setPicking(null)}
|
onClose={() => setPicking(null)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
<div
|
<Modal onDismiss={onClose}>
|
||||||
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
|
<div
|
||||||
className="flex max-h-[85vh] w-full max-w-lg flex-col overflow-hidden glass-overlay"
|
className="flex max-h-[85vh] w-full max-w-lg 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">
|
<div className="flex items-center justify-between border-b border-line px-5 py-3">
|
||||||
<h2 className="text-sm font-semibold text-text">Stems</h2>
|
<h2 className="text-sm font-semibold text-text">Stems</h2>
|
||||||
@@ -241,8 +230,7 @@ export function StemsSettings({ onClose }: Props) {
|
|||||||
{error && <div className="text-xs text-pink">{error}</div>}
|
{error && <div className="text-xs text-pink">{error}</div>}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</Modal>
|
||||||
</>,
|
</>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
import { createPortal } from 'react-dom'
|
import { useState, type ReactNode } from 'react'
|
||||||
import { useEffect, useState, type ReactNode } from 'react'
|
|
||||||
import type { Track } from '../api'
|
import type { Track } from '../api'
|
||||||
import { formatBpm, formatDuration, keyColor } from '../lib/format'
|
import { formatBpm, formatDuration, keyColor } from '../lib/format'
|
||||||
import { useCaps } from '../lib/capabilities'
|
import { useCaps } from '../lib/capabilities'
|
||||||
import { Icon } from '../lib/icons'
|
import { Icon } from '../lib/icons'
|
||||||
import { RatingStars } from './RatingStars'
|
import { RatingStars } from './RatingStars'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
track: Track
|
track: Track
|
||||||
@@ -27,12 +27,6 @@ export function TrackInfoDialog({ track, artUrl, onClose, onEditTags }: Props) {
|
|||||||
const [artFailed, setArtFailed] = useState(false)
|
const [artFailed, setArtFailed] = useState(false)
|
||||||
const showArt = artUrl != null && !artFailed
|
const showArt = artUrl != null && !artFailed
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
|
|
||||||
window.addEventListener('keydown', onKey)
|
|
||||||
return () => window.removeEventListener('keydown', onKey)
|
|
||||||
}, [onClose])
|
|
||||||
|
|
||||||
const grid =
|
const grid =
|
||||||
track.grid_marker_count === 0
|
track.grid_marker_count === 0
|
||||||
? null
|
? null
|
||||||
@@ -60,17 +54,10 @@ export function TrackInfoDialog({ track, artUrl, onClose, onEditTags }: Props) {
|
|||||||
] as [string, ReactNode][]
|
] as [string, ReactNode][]
|
||||||
).filter(([, v]) => v != null && v !== '')
|
).filter(([, v]) => v != null && v !== '')
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<div
|
<Modal onDismiss={onClose} padding="p-4" role="dialog" aria-label={track.title ?? 'Track info'}>
|
||||||
aria-modal="true"
|
|
||||||
role="dialog"
|
|
||||||
aria-label={track.title ?? 'Track info'}
|
|
||||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4 backdrop-blur-[3px]"
|
|
||||||
onClick={onClose}
|
|
||||||
>
|
|
||||||
<div
|
<div
|
||||||
className="track-info-pop glass-overlay flex max-h-[90vh] w-full max-w-[860px] flex-col overflow-hidden sm:flex-row"
|
className="track-info-pop glass-overlay flex max-h-[90vh] w-full max-w-[860px] flex-col overflow-hidden sm:flex-row"
|
||||||
onClick={(e) => e.stopPropagation()}
|
|
||||||
>
|
>
|
||||||
{/* The sleeve, bled into the card behind everything: a soft wash of the
|
{/* The sleeve, bled into the card behind everything: a soft wash of the
|
||||||
art's own colours. `filter` on this leaf is safe — nothing can open
|
art's own colours. `filter` on this leaf is safe — nothing can open
|
||||||
@@ -166,8 +153,7 @@ export function TrackInfoDialog({ track, artUrl, onClose, onEditTags }: Props) {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,14 +1,16 @@
|
|||||||
import { createPortal } from 'react-dom'
|
|
||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { api } from '../api'
|
import { api } from '../api'
|
||||||
|
import { Modal } from './Modal'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Startup update check against GitHub Releases.
|
* Startup update check against GitHub Releases.
|
||||||
*
|
*
|
||||||
* Compares the running version (`__APP_VERSION__`, baked from package.json at
|
* Compares the running version (`__APP_VERSION__`, baked from package.json at
|
||||||
* build time) with the latest release's tag (`v<version>-b<N>` — only the
|
* build time) with release tags (`v<version>-b<N>` — only the semver part
|
||||||
* semver part counts, so a new build of the same version is NOT an update).
|
* counts, so a new build of the same version is NOT an update). The dialog
|
||||||
|
* lists the notes of EVERY release newer than the running one, not just the
|
||||||
|
* latest's.
|
||||||
* Failures are silent: an update check must never nag about itself.
|
* Failures are silent: an update check must never nag about itself.
|
||||||
* "Skip this version" persists `skippedUpdateVersion` to userprefs.json via
|
* "Skip this version" persists `skippedUpdateVersion` to userprefs.json via
|
||||||
* the prefs API, keyed by the semver part, so a later version re-triggers.
|
* the prefs API, keyed by the semver part, so a later version re-triggers.
|
||||||
@@ -36,22 +38,39 @@ interface GithubRelease {
|
|||||||
prerelease?: boolean
|
prerelease?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const MAX_PAGES = 5
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The newest APP release. Not `/releases/latest`: that is whichever release
|
* Every APP release newer than the running version, newest first — the first
|
||||||
* GitHub flags "latest", and the same repo also publishes the stem engine on
|
* is the one offered, and all of their notes are shown, so someone several
|
||||||
* its own `engine-v*` channel — one flagged latest by mistake would make this
|
* versions behind sees everything they are getting. Not `/releases/latest`:
|
||||||
* check go quiet (its tag does not parse as an app version) with no error. So
|
* that is whichever release GitHub flags "latest", and the same repo also
|
||||||
* list recent releases (newest first) and take the first app tag.
|
* publishes the stem engine on its own `engine-v*` channel — one flagged
|
||||||
|
* latest by mistake would make this check go quiet (its tag does not parse as
|
||||||
|
* an app version) with no error. So list releases (newest first) and keep the
|
||||||
|
* app tags, paging until one is not newer than the running version.
|
||||||
*/
|
*/
|
||||||
async function fetchLatestRelease(): Promise<GithubRelease> {
|
async function fetchNewerReleases(): Promise<GithubRelease[]> {
|
||||||
const res = await fetch(`https://api.github.com/repos/${REPO}/releases?per_page=30`, {
|
const current = parseVersion(__APP_VERSION__)
|
||||||
headers: { Accept: 'application/vnd.github+json' },
|
if (!current) return []
|
||||||
})
|
const newer: GithubRelease[] = []
|
||||||
|
for (let page = 1; page <= MAX_PAGES; page++) {
|
||||||
|
const res = await fetch(
|
||||||
|
`https://api.github.com/repos/${REPO}/releases?per_page=100&page=${page}`,
|
||||||
|
{ headers: { Accept: 'application/vnd.github+json' } },
|
||||||
|
)
|
||||||
if (!res.ok) throw new Error(`GitHub responded ${res.status}`)
|
if (!res.ok) throw new Error(`GitHub responded ${res.status}`)
|
||||||
const releases: GithubRelease[] = await res.json()
|
const releases: GithubRelease[] = await res.json()
|
||||||
const app = releases.find((r) => !r.draft && !r.prerelease && /^v\d/.test(r.tag_name))
|
for (const r of releases) {
|
||||||
if (!app) throw new Error('No app release found')
|
if (r.draft || r.prerelease) continue
|
||||||
return app
|
const v = parseVersion(r.tag_name)
|
||||||
|
if (!v || !r.tag_name.startsWith('v')) continue
|
||||||
|
if (!isNewer(v, current)) return newer
|
||||||
|
newer.push(r)
|
||||||
|
}
|
||||||
|
if (releases.length < 100) break
|
||||||
|
}
|
||||||
|
return newer
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The semver triple at the start of a version/tag string ("v0.1.2-b7" → [0,1,2]). */
|
/** The semver triple at the start of a version/tag string ("v0.1.2-b7" → [0,1,2]). */
|
||||||
@@ -163,9 +182,9 @@ export function UpdateCheck() {
|
|||||||
const [skipVersion, setSkipVersion] = useState(false)
|
const [skipVersion, setSkipVersion] = useState(false)
|
||||||
const [phase, setPhase] = useState<Phase>({ kind: 'offer' })
|
const [phase, setPhase] = useState<Phase>({ kind: 'offer' })
|
||||||
|
|
||||||
const release = useQuery({
|
const releases = useQuery({
|
||||||
queryKey: ['latestRelease'],
|
queryKey: ['newerReleases'],
|
||||||
queryFn: fetchLatestRelease,
|
queryFn: fetchNewerReleases,
|
||||||
staleTime: Infinity,
|
staleTime: Infinity,
|
||||||
retry: false,
|
retry: false,
|
||||||
})
|
})
|
||||||
@@ -195,11 +214,10 @@ export function UpdateCheck() {
|
|||||||
}
|
}
|
||||||
}, [phase.kind])
|
}, [phase.kind])
|
||||||
|
|
||||||
const latest = release.data
|
const newer = releases.data ?? []
|
||||||
const latestVer = latest ? parseVersion(latest.tag_name) : null
|
const latest = newer[0]
|
||||||
const currentVer = parseVersion(__APP_VERSION__)
|
const latestSemver = latest ? parseVersion(latest.tag_name)?.join('.') : undefined
|
||||||
const latestSemver = latestVer?.join('.')
|
const updateAvailable = !!latest
|
||||||
const updateAvailable = !!(latestVer && currentVer && isNewer(latestVer, currentVer))
|
|
||||||
const skipped = !!latestSemver && prefs.data?.skippedUpdateVersion === latestSemver
|
const skipped = !!latestSemver && prefs.data?.skippedUpdateVersion === latestSemver
|
||||||
const failedBefore = lastFailure.data ?? null
|
const failedBefore = lastFailure.data ?? null
|
||||||
const releasePage = latest?.html_url ?? `https://github.com/${REPO}/releases`
|
const releasePage = latest?.html_url ?? `https://github.com/${REPO}/releases`
|
||||||
@@ -262,16 +280,15 @@ export function UpdateCheck() {
|
|||||||
? "Update didn't install"
|
? "Update didn't install"
|
||||||
: 'Update available'
|
: 'Update available'
|
||||||
|
|
||||||
const changes = latest ? whatsChanged(latest.body) : []
|
// One section per release the user is skipping past, newest first; a heading
|
||||||
|
// only when there is more than one, so a one-step update reads as before.
|
||||||
|
const sections = newer.map((r) => ({ tag: r.tag_name, changes: whatsChanged(r.body) }))
|
||||||
|
const grouped = sections.length > 1
|
||||||
|
|
||||||
return createPortal(
|
return (
|
||||||
<div
|
<Modal onDismiss={busy ? null : close}>
|
||||||
aria-modal="true" className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6"
|
|
||||||
onClick={close}
|
|
||||||
>
|
|
||||||
<div
|
<div
|
||||||
className="flex max-h-[80vh] w-full max-w-md flex-col overflow-hidden glass-overlay"
|
className="flex max-h-[80vh] w-full max-w-md flex-col overflow-hidden glass-overlay"
|
||||||
onClick={(e) => e.stopPropagation()}
|
|
||||||
>
|
>
|
||||||
<div className="border-b border-line px-5 py-4">
|
<div className="border-b border-line px-5 py-4">
|
||||||
<div className="text-[15px] font-semibold tracking-tight">{title}</div>
|
<div className="text-[15px] font-semibold tracking-tight">{title}</div>
|
||||||
@@ -312,10 +329,18 @@ export function UpdateCheck() {
|
|||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<div className="mb-2 text-xs font-medium text-muted">What's changed</div>
|
<div className="mb-2 text-xs font-medium text-muted">
|
||||||
{changes.length ? (
|
What's changed{grouped ? ` since v${__APP_VERSION__}` : ''}
|
||||||
|
</div>
|
||||||
|
<div className="space-y-4">
|
||||||
|
{sections.map((s) => (
|
||||||
|
<section key={s.tag}>
|
||||||
|
{grouped && (
|
||||||
|
<div className="mb-1.5 text-xs font-semibold text-accent">{s.tag}</div>
|
||||||
|
)}
|
||||||
|
{s.changes.length ? (
|
||||||
<ul className="space-y-1.5">
|
<ul className="space-y-1.5">
|
||||||
{changes.map((line, i) => (
|
{s.changes.map((line, i) => (
|
||||||
<li key={i} className="flex gap-2 text-sm text-text">
|
<li key={i} className="flex gap-2 text-sm text-text">
|
||||||
<span className="text-faint">•</span>
|
<span className="text-faint">•</span>
|
||||||
<span className="min-w-0 break-words">
|
<span className="min-w-0 break-words">
|
||||||
@@ -327,6 +352,9 @@ export function UpdateCheck() {
|
|||||||
) : (
|
) : (
|
||||||
<div className="text-sm text-faint">No release notes.</div>
|
<div className="text-sm text-faint">No release notes.</div>
|
||||||
)}
|
)}
|
||||||
|
</section>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -386,7 +414,6 @@ export function UpdateCheck() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</Modal>
|
||||||
document.body,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -6,7 +6,7 @@
|
|||||||
* staying genuinely specific — the pre-save warning is a real, per-platform
|
* staying genuinely specific — the pre-save warning is a real, per-platform
|
||||||
* hazard and must not be watered down into something vague.
|
* hazard and must not be watered down into something vague.
|
||||||
*/
|
*/
|
||||||
import type { Capabilities, PlatformOption, SaveCapabilities } from '../api'
|
import type { Capabilities, LocalLibrary, PlatformOption, SaveCapabilities } from '../api'
|
||||||
|
|
||||||
export function saveLabel(save: SaveCapabilities): string {
|
export function saveLabel(save: SaveCapabilities): string {
|
||||||
return `Save to ${save.app_name}`
|
return `Save to ${save.app_name}`
|
||||||
@@ -155,3 +155,21 @@ export function remoteHolder(machine: string | null, since: string | null, batch
|
|||||||
const running = batch ? ` — ${what[batch] ?? 'a batch'} is running there, and taking over cancels it` : ''
|
const running = batch ? ` — ${what[batch] ?? 'a batch'} is running there, and taking over cancels it` : ''
|
||||||
return `${who}${when ? ` has had it open since ${when}` : ' has it open'}${running}.`
|
return `${who}${when ? ` has had it open since ${when}` : ' has it open'}${running}.`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Why a DJ app's library on this computer cannot be pushed into, or null. */
|
||||||
|
export function localLibraryProblem(lib: LocalLibrary): string | null {
|
||||||
|
switch (lib.blocked) {
|
||||||
|
case null:
|
||||||
|
return null
|
||||||
|
case 'not_found':
|
||||||
|
return lib.path
|
||||||
|
? `No ${lib.name} library at ${lib.path}`
|
||||||
|
: `No ${lib.name} library found on this computer`
|
||||||
|
case 'open_in_konduktor':
|
||||||
|
return `This is the library open in Konduktor — open another one to push into it`
|
||||||
|
case 'cloud_synced':
|
||||||
|
return `Synced with ${lib.name} Cloud, so Konduktor will not write to it`
|
||||||
|
case 'unreadable':
|
||||||
|
return `Konduktor cannot read this ${lib.name} library`
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user