mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
17b68c40bb | ||
|
|
cb76277016 | ||
|
|
24b9dfe49f | ||
|
|
513808a6d2 | ||
|
|
85f01f6723 | ||
|
|
2e04bcb9f6 | ||
|
|
bd425f8cd6 | ||
|
|
b9d43dd7ea | ||
|
|
a3747e887b | ||
|
|
8c875cb6cd | ||
|
|
ce06731dc8 | ||
|
|
c6aaded26d | ||
|
|
c1f121ae1d | ||
|
|
f1087b60fa | ||
|
|
394520c2cf | ||
|
|
642977e9bc | ||
|
|
9f299051fa | ||
|
|
738d04eada | ||
|
|
22f59c5c1e | ||
|
|
805d360907 | ||
|
|
46d3978580 | ||
|
|
0a9764ee89 | ||
|
|
f9497b391b | ||
|
|
be80e572e5 | ||
|
|
2810f24563 | ||
|
|
950352f7ec | ||
|
|
b4dc8949de | ||
|
|
0fd5d56a4e | ||
|
|
88737f2b08 | ||
|
|
efdd0f6203 | ||
|
|
d18db9566c | ||
|
|
76bf142fb4 | ||
|
|
73694fe532 | ||
|
|
532dc5d6ac | ||
|
|
b71436fad6 | ||
|
|
5909c704f4 | ||
|
|
07e85cfdc9 | ||
|
|
6c123e2597 | ||
|
|
46ce3db916 | ||
|
|
6cc73267a6 | ||
|
|
68e0b032b3 | ||
|
|
a5f995562f | ||
|
|
4aeb5d65d3 | ||
|
|
7160fa3978 | ||
|
|
805b95fe5e | ||
|
|
93ec2ef425 | ||
|
|
8d11acd783 | ||
|
|
a081a7a44d | ||
|
|
06137f5c99 | ||
|
|
36cfb96c05 | ||
|
|
ed9dfc9d6b | ||
|
|
ba3e7c251e | ||
|
|
0b38d4826f | ||
|
|
7b0d7e3a07 | ||
|
|
00dd3fe766 | ||
|
|
5aeb9956cd | ||
|
|
30065a94fe | ||
|
|
43e712afbd | ||
|
|
010f67cd2d | ||
|
|
4592e13228 | ||
|
|
6e24f5ef1d | ||
|
|
c9e85bbdb5 | ||
|
|
08c9b8121d | ||
|
|
dd97f27ac7 | ||
|
|
3f51444e2a | ||
|
|
73f7fc4282 | ||
|
|
b8b466b608 | ||
|
|
bd85d6794c | ||
|
|
ed2b72c749 | ||
|
|
f19a662bd3 | ||
|
|
41111c7c4c | ||
|
|
e8d2c66e06 |
No files matched your search
@@ -0,0 +1,635 @@
|
||||
# Discussion: Multi-platform library support (Traktor / Rekordbox / Serato)
|
||||
Date: 2026-09-17
|
||||
Status: Concluded
|
||||
|
||||
## Context
|
||||
Konduktor currently targets Traktor only (NML v20 via `traktor-nml-utils`), with a
|
||||
save path whose central guarantee is byte-exact fidelity: a no-op save is
|
||||
byte-identical, and only edited objects diff (`test_save_fidelity.py`).
|
||||
|
||||
Ben wants to extend to Rekordbox and Serato. Proposed shape:
|
||||
1. A generic library data structure that supports **all** features of **all**
|
||||
platforms ("full support is critical").
|
||||
2. Load any platform's library into that structure.
|
||||
3. Edit/prepare with Konduktor's existing features.
|
||||
4. Save back to the **original** library format.
|
||||
5. Ultimate goal: **convert** a library from one platform to another.
|
||||
|
||||
## Open Questions
|
||||
- [ ] **Command vocabulary for grids** (now evidenced): `set_grid(bpm, anchor_sec)`
|
||||
cannot express per-marker edits. Needs marker-level commands — add / move /
|
||||
set-BPM / delete marker — plus marker selection in `GridControls`. Design these.
|
||||
- [ ] Verification tests: write the per-platform "localized change" analogues —
|
||||
Rekordbox row-level table-dump diff, Serato byte diff excluding the patched GEOB
|
||||
frame + whole-file diff of crates.
|
||||
- [ ] Rekordbox `rb_local_usn` / update-sequence + cloud-sync columns: writing rows
|
||||
without maintaining these may corrupt RB's own sync state. Needs investigation.
|
||||
|
||||
## Decisions Made
|
||||
|
||||
### Write scope: full read/write for all three platforms
|
||||
- **Decision**: Konduktor must edit and save back into each platform's own live
|
||||
library — Traktor NML, Rekordbox (`master.db`), and Serato (binary crates +
|
||||
in-file GEOB tags). Not read-only, not export-only.
|
||||
- **Rationale**: The user's existing library on their chosen platform is the
|
||||
canonical source; Konduktor is a management tool for it, so it must be able to
|
||||
write back wherever the user actually works.
|
||||
- **Alternatives considered**: Traktor-write-only with read+export for the others
|
||||
(smaller, safer v1); Traktor+Serato write with Rekordbox read-only (avoids the
|
||||
encrypted/unsupported RB DB); read-all/export-only (no in-place editing at all).
|
||||
All rejected as too limited.
|
||||
- **Consequence**: Rekordbox and Serato writes carry materially higher risk than
|
||||
NML — both formats are reverse-engineered and neither has a fidelity guarantee
|
||||
equivalent to the current byte-exact NML save. Per-platform backup + verification
|
||||
strategy becomes a first-class requirement.
|
||||
|
||||
### End goal: canonical-library management + converted exports
|
||||
- **Decision**: The user's main platform library remains the canonical source of
|
||||
truth. Konduktor manages and edits it in place, and *additionally* can produce
|
||||
converted exports for other platforms.
|
||||
- **Rationale**: Keeps the user's existing workflow intact — they keep using their
|
||||
DJ software normally — while making conversion a deliberate, separate output.
|
||||
- **Alternatives considered**: one-shot migration only (too narrow); two-way sync
|
||||
between libraries (rejected — requires cross-platform track identity, change
|
||||
detection and conflict resolution; much larger project); Konduktor owning its own
|
||||
canonical library format with platforms as import/export only (rejected — changes
|
||||
the product's identity and displaces the user's real library).
|
||||
- **Consequence**: Two distinct write paths must coexist: a high-fidelity in-place
|
||||
*edit* path per platform, and a lossy-by-design *export* path. They have opposite
|
||||
requirements and should not share an implementation.
|
||||
|
||||
### Track identity: not needed — export always generates a fresh target library
|
||||
- **Decision**: An Export is a one-time conversion that generates a **fresh** target
|
||||
library. It never merges into an existing library on the target platform. The
|
||||
originally-loaded library remains canonical and is the only thing edited in place.
|
||||
- **Rationale**: Keeps the canonical-source model clean — edits go back to the source
|
||||
library, exports are disposable output. Removes the need for any cross-platform
|
||||
track-matching mechanism.
|
||||
- **Alternatives considered**: path-only matching (fails on relocation); path with
|
||||
artist/title/duration tag fallback (false positives); audio content hashing (robust,
|
||||
survives moves, but requires a full library scan); acoustic fingerprinting
|
||||
(Chromaprint/AcoustID — heavy, solves a problem this product doesn't have). All
|
||||
rejected as unnecessary given fresh-export-only.
|
||||
- **Consequence**: The existing `volume + dir + file` primary key remains sufficient.
|
||||
Cross-library identity is deferred indefinitely; it would only return if merge-style
|
||||
export were ever wanted.
|
||||
|
||||
### Serato backup: GEOB-frame sidecar, not full file copies
|
||||
- **Decision**: Before patching a Serato GEOB frame, snapshot the original frame bytes
|
||||
to a sidecar restore file. Do not copy whole audio files. Crate files are copied
|
||||
wholesale (tiny).
|
||||
- **Rationale**: Kilobytes instead of gigabytes per save, and a complete restore for
|
||||
everything Konduktor actually touches, since Konduktor only ever rewrites those frames.
|
||||
- **Alternatives considered**: full audio-file backups — rejected on cost (~1 GB for a
|
||||
100-track save).
|
||||
- **Risk accepted**: does not protect against the tag library corrupting an unrelated
|
||||
region of the audio file. This exposure already exists via `file_tags.py` cover-art
|
||||
writes; Serato support widens it from occasional to routine.
|
||||
|
||||
### Export = a new self-contained library, always including copied audio
|
||||
- **Decision**: An export/conversion always produces a whole new library at a
|
||||
user-chosen destination, complete with copies of the music files — for every target
|
||||
platform, not just Serato. Reference-in-place is not offered.
|
||||
- **Audio folder layout**: a **global, persistent export setting** with two options —
|
||||
**flat single folder (default)** or **mirror source directory structure**.
|
||||
*Rationale*: flat is predictable and simple for the common case; mirroring is there
|
||||
for users who want their original structure preserved. *Alternatives considered*:
|
||||
organised Artist/Album from metadata (clean but depends on metadata quality and needs
|
||||
sanitising); mirror playlist structure (legible on USB, but duplicates tracks that
|
||||
appear in multiple playlists).
|
||||
- **Rationale**: The export is self-contained and portable (USB drive, another machine,
|
||||
handing it to someone else). Consistent behaviour across targets.
|
||||
- **Alternatives considered**: copy only where the format forces it (Serato), letting
|
||||
Traktor/Rekordbox exports reference originals in place for a near-instant export;
|
||||
offering it as a per-export user choice. Both rejected in favour of one predictable
|
||||
behaviour.
|
||||
|
||||
### Export Sets: user-curated export scope
|
||||
- **Decision**: Introduce an **Export Set** (not "Crate" — see naming decision) — a named, persisted list of track and playlist
|
||||
*references* defining what a given export includes. Enables partial exports. Each
|
||||
crate belongs to a specific library, and crate data is persisted in Konduktor's own
|
||||
storage (not in the platform library).
|
||||
- **Flow**: open library → prep tracks → save back to the canonical library → create a
|
||||
crate → drag tracks/playlists into it → export crate (choose target platform +
|
||||
destination) → Konduktor writes the target library files and copies the audio.
|
||||
- **Rationale**: Users rarely want to convert an entire library; export scope needs to
|
||||
be curated and re-usable across repeat exports.
|
||||
- **Naming**: called **Export Set**, not "Crate". *Rationale*: "Crate" is Serato's own
|
||||
term for a playlist and Konduktor imports Serato crates — the collision would be
|
||||
confusing in a multi-platform tool. *Alternatives considered*: keeping "Crate"
|
||||
(familiar DJ vocabulary, but ambiguous); "Bundle"; "Package".
|
||||
- **Reference semantics: live**. An Export Set stores pointers to playlists; export
|
||||
resolves them at export time, so later additions to a playlist are picked up.
|
||||
*Alternatives considered*: snapshot-at-add (frozen and auditable, but stale);
|
||||
live-with-optional-freeze (more flexible, more UI + model complexity).
|
||||
*Consequence*: the export preview must be computed at export time, never stored.
|
||||
- **Storage: own store, keyed by stable library ID**. A dedicated Export Sets store,
|
||||
separate from `userprefs.json`, with each library assigned a stable generated ID so
|
||||
that moving or renaming the collection file does not orphan its export sets.
|
||||
*Alternatives considered*: keying by collection file path (simple, orphans on move);
|
||||
storing inside `userprefs.json` (best-effort I/O, no backup — inadequate for curated
|
||||
user work); a sidecar file next to the user's library (travels automatically, but
|
||||
writes Konduktor files into the user's Traktor/Serato folders).
|
||||
|
||||
### Export mechanics
|
||||
- **Flat-layout filename collisions: counter suffix.** Second and later collisions
|
||||
become `Xtal-2.mp3`, `Xtal-3.mp3`. *Rationale*: human-readable and predictable.
|
||||
*Alternatives considered*: metadata-based disambiguation (`Xtal (Aphex Twin).mp3` —
|
||||
most legible and stable, but depends on metadata quality and needs sanitising); short
|
||||
hash suffix (stable across re-exports regardless of order, but ugly).
|
||||
*Known consequence*: numbering depends on processing order, so repeat exports may
|
||||
assign different suffixes to the same tracks.
|
||||
- **Playlist folder structure: preserve where supported, flatten with path names
|
||||
otherwise.** Keep the tree on Traktor and Rekordbox; on flat targets, flatten to names
|
||||
encoding the path (e.g. `House / Peak Time`). *Rationale*: retains the structural
|
||||
information in readable form on every target and avoids name collisions between
|
||||
same-named playlists in different folders. *Alternatives considered*: flatten to bare
|
||||
names (cleaner, but collides); always flatten (uniform, but discards structure the
|
||||
target could represent).
|
||||
- **Re-export to an occupied destination: warn, then overwrite on confirm.** *Rationale*:
|
||||
the destination stays the single current copy, which is what re-export usually means,
|
||||
with a guard against accidental loss. *Alternatives considered*: always write a new
|
||||
timestamped folder (safe, but fills the drive with copies of a large collection);
|
||||
refuse and require an empty destination (tedious for a routine operation); incremental
|
||||
update in place (fast, but reintroduces target-library matching/diffing, which the
|
||||
fresh-export decision deliberately avoided).
|
||||
- **Whole-library export: an explicit "export entire library" action.** A separate
|
||||
action that skips export-set creation. *Rationale*: wholesale migration is a common
|
||||
real use case and shouldn't require busywork. *Alternatives considered*: export sets
|
||||
only (uniform, but forces a select-everything set); a select-all shortcut inside the
|
||||
export set editor (single code path, but less discoverable).
|
||||
|
||||
### Export set resolution and export UX
|
||||
- **Playlist resolution: auto-include, deduplicate, copy once.** Every track referenced
|
||||
by a playlist in the export set is included automatically; a track appearing in
|
||||
multiple playlists, or also added individually, is copied to disk exactly once.
|
||||
*Alternatives considered*: auto-include but surface the implied tracks in the UI (more
|
||||
transparent, more UI); require explicit inclusion (precise, but surprising).
|
||||
- **Missing audio files: pre-scan, report, let the user decide.** Verify every file
|
||||
exists before copying anything; present what's missing and let the user cancel or
|
||||
proceed without them. *Rationale*: fails fast rather than halfway through a multi-hour
|
||||
copy. *Alternatives considered*: skip silently (incomplete export the user never
|
||||
learns about — worse given the loss report was deferred); abort entirely (one
|
||||
unmounted drive blocks an otherwise fine export).
|
||||
- **Export UX: pre-check space, progress with cancel.** Estimate total size and verify
|
||||
the destination has room before starting; show per-file progress with a working
|
||||
cancel. *Alternatives considered*: cancel with rollback (destination never left
|
||||
half-finished, but deleting files from a user-chosen location needs care);
|
||||
progress-only with no pre-check (discovers a full drive after an hour of copying).
|
||||
*Known consequence*: cancelling leaves a partial export that must be cleaned up or
|
||||
clearly marked incomplete.
|
||||
|
||||
### Serato export copies the audio files
|
||||
- **Decision**: Exporting to Serato copies the original audio files to the export
|
||||
destination and writes the GEOB frames into the **copies**, leaving the canonical
|
||||
library's files untouched.
|
||||
- **Rationale**: Serato's prep data lives inside the audio files, so a Serato export
|
||||
cannot reference the originals without mutating them — and the originals belong to
|
||||
the canonical library.
|
||||
- **Open consequence**: creates an asymmetry with Traktor/Rekordbox exports, whose data
|
||||
lives in a library file and could reference originals in place. See Open Questions.
|
||||
|
||||
### Rekordbox open-app handling: warn and proceed
|
||||
- **Decision**: If Rekordbox appears to be running when the user saves, Konduktor
|
||||
**warns but allows the save to proceed** — it does not hard-refuse.
|
||||
- **Rationale**: Consistent with the existing Traktor behaviour (the user is warned to
|
||||
close Traktor before saving, not blocked).
|
||||
- **Alternatives considered**: detect-and-refuse (safer, but blocks the user on a
|
||||
detection heuristic that may be wrong).
|
||||
- **Risk accepted**: Rekordbox may hold `master.db` open and runs cloud sync, so a
|
||||
concurrent write is riskier than Traktor's overwrite-on-exit behaviour. The backup
|
||||
taken before the write is the mitigation.
|
||||
|
||||
### Backup/verification: same invariant, per-platform mechanism
|
||||
- **Decision**: Keep the existing invariant — *an edit changes only what it was
|
||||
supposed to change* — and implement a per-platform comparison mechanism for it:
|
||||
Traktor byte diff (existing), Rekordbox full table dump with row-level diff, Serato
|
||||
byte diff of the audio file excluding the patched GEOB frame plus whole-file diff of
|
||||
crate files. Backups: copy `collection.nml` / copy `master.db` (+ WAL/SHM) /
|
||||
Serato strategy TBD (see Open Questions).
|
||||
- **Rationale**: Generalizes `test_save_fidelity.py`'s guarantee to formats where a
|
||||
byte-identical whole-file comparison is meaningless.
|
||||
- **Alternatives considered**: dropping the fidelity guarantee for the non-Traktor
|
||||
platforms — rejected, it is the project's core safety property.
|
||||
|
||||
### Cue model: rich core cue, adapters collapse on write
|
||||
- **Decision**: Model a cue richly enough to cover all three platforms:
|
||||
`{ position_sec, length_sec?, role: hotcue|memory, slot?, type: cue|fade_in|fade_out|
|
||||
load|loop, color?, name? }`. Adapters collapse it per platform — Traktor rejects
|
||||
`role: memory`; Rekordbox and Serato have no `fade_in`/`fade_out`/`load` types;
|
||||
Serato keeps loops in a separate saved-loop bank rather than consuming a cue slot.
|
||||
- **Platform differences captured**: Traktor = 8 typed hotcue slots (loop is a cue
|
||||
*type*); Rekordbox = 8 hotcues A–H plus unlimited memory cues, colour per cue;
|
||||
Serato = 8 cues plus a separate saved-loop bank, colour per cue.
|
||||
- **Correction noted during discussion**: Traktor's `CueV2Type` *does* carry a `color`
|
||||
field, so NML supports cue colours — an earlier assumption to the contrary was wrong.
|
||||
**Lesson: establish capabilities empirically per format rather than assuming them.**
|
||||
|
||||
### Lossiness policy: degrade where sensible, drop otherwise
|
||||
- **Decision**: On export, data the target cannot represent is **degraded to the
|
||||
nearest equivalent where one exists, and dropped only where none does** — e.g. a
|
||||
Traktor fade-in cue becomes a plain cue in Serato; Rekordbox memory cues fill spare
|
||||
hotcue slots in Traktor until they run out.
|
||||
- **Rationale**: The project aims for as much feature parity across platforms as
|
||||
possible; silently discarding representable data works against that.
|
||||
- **Alternatives considered**: drop silently (clean output, but the user only discovers
|
||||
the loss on the gear); refuse to export when data would be lost (too rigid).
|
||||
- **No loss report for now**: an export summary of what was degraded or dropped was
|
||||
explicitly deferred ("not for now"). The adapters will know what they collapsed, so
|
||||
it remains cheap to add later.
|
||||
|
||||
### Proposed sequencing (not yet confirmed)
|
||||
1. Fix the flexible-grid bug standalone (small, independent, fixes a present-day data
|
||||
risk). Requires verifying the NML representation first.
|
||||
2. Refactor to generic model + adapter interface with **Traktor as the only adapter** —
|
||||
no new formats, all existing tests must still pass, so `test_save_fidelity.py` proves
|
||||
the projection+command split broke nothing. Takes the architectural risk where it is
|
||||
verifiable.
|
||||
3. Add the second platform — where a one-adapter abstraction gets tested for real.
|
||||
4. Export — only meaningful once two platforms exist.
|
||||
|
||||
### Sequencing: grid fix → Traktor-only refactor → Rekordbox → export
|
||||
- **Decision**:
|
||||
1. Fix the flexible-beatgrid handling as a **standalone change first** (small,
|
||||
independent, and currently writing inconsistent grids to real collections).
|
||||
2. Refactor to the generic model + adapter interface with **Traktor as the only
|
||||
adapter** — no new formats, every existing test must still pass, so
|
||||
`test_save_fidelity.py` proves the projection+command split changed nothing.
|
||||
3. Add **Rekordbox** as the second platform.
|
||||
4. Build the **export** path last (it only becomes meaningful once two platforms
|
||||
exist).
|
||||
- **Rationale**: takes the architectural risk where it is verifiable against existing
|
||||
invariants, before any unverifiable format is introduced. A one-adapter abstraction is
|
||||
always wrong in ways that only surface with the second adapter.
|
||||
- **Second platform — Rekordbox over Serato**: chosen despite the riskier write target
|
||||
(SQLCipher-encrypted DB, cloud sync, version-fragile schema) because `pyrekordbox` is
|
||||
the more mature library. *Alternative considered*: Serato second — no library-file
|
||||
risk, but writes go into users' audio files and the format is entirely
|
||||
reverse-engineered.
|
||||
- **Tauri packaging: dropped from scope for now.**
|
||||
- **CDJ/USB export (`export.pdb` + ANLZ files): explicitly OUT OF SCOPE.** Raised in a
|
||||
forked conversation and rejected as impractical to implement. Recorded here only so
|
||||
it is not rediscovered and re-proposed.
|
||||
- **Bulk metadata editing: dropped from scope for now.** Not built before the refactor;
|
||||
revisit after the adapter architecture exists so it only has to be written once.
|
||||
|
||||
### One library open at a time
|
||||
- **Decision**: `AppState` continues to hold exactly one loaded library. Export always
|
||||
reads the currently-open library.
|
||||
- **Rationale**: Simplest plumbing, no ambiguity about which library an edit or export
|
||||
targets, and the existing collection-picker flow is unchanged.
|
||||
- **Alternatives considered**: multiple loaded with one active (faster switching, but
|
||||
dirty-flag/save-bar/unsaved-changes state all become per-library); fully concurrent
|
||||
multi-library (powerful, but multiplies UI and state complexity and invites the
|
||||
merge/sync expectations already ruled out).
|
||||
|
||||
### Capability detection: version first, probe as fallback
|
||||
- **Decision**: Derive capabilities from the library's declared version where one
|
||||
exists (NML version, Rekordbox schema version); where no version is stamped — Serato
|
||||
— infer capabilities from the data actually present.
|
||||
- **Rationale**: Accurate per-library capability reporting without assuming a floor that
|
||||
denies users features their software actually has.
|
||||
- **Alternatives considered**: probe-only (uniform and empirical, but an empty or simple
|
||||
library under-reports); assume-newest-and-degrade-on-failure (least work, risks
|
||||
writing data older software can't read); static per-platform floor (trivial, but
|
||||
penalises users on current versions).
|
||||
- **Consequence**: each adapter needs its own version-detection story.
|
||||
- **Serato exception**: Serato has no version-stamped library file, so rather than
|
||||
probing the data, Konduktor simply **assumes the latest Serato version** and reports
|
||||
the full capability set. *Rationale*: keeps it simple, and probing under-reports on
|
||||
small or fresh libraries. *Risk accepted*: a user on an older Serato build could be
|
||||
written prep data their install cannot read; mitigated by Serato's aggressive
|
||||
auto-update and the relative stability of the GEOB tag format.
|
||||
|
||||
### Field mapping: normalise, but keep the native value alongside
|
||||
- **Implementation requirement**: this demands **per-field dirty tracking**. The rule
|
||||
"reuse the native value unless the user edited this field" needs to know *which
|
||||
fields* changed, not just which tracks — `PlaylistStore` currently tracks dirtiness at
|
||||
track level. It must exist from the start: retrofitted, it cannot distinguish
|
||||
edited-to-the-same-value from untouched. It pairs well with projection+command, since
|
||||
a command already names the field it changes, so the flag falls out of the command
|
||||
rather than requiring a diff.
|
||||
- **Decision**: Ratings, keys, colours and comments are stored in canonical form in the
|
||||
generic model (rating 0–5, key as canonical pitch-class + mode, colour as RGB), and
|
||||
**each field also retains its untouched native value**. On write-back the native value
|
||||
is reused unless the user actually edited that field, so untouched tracks round-trip
|
||||
exactly and only genuine edits go through conversion.
|
||||
- **Rationale**: Gets a clean, convertible canonical model without introducing
|
||||
round-trip drift on data the user never touched — consistent with the project's
|
||||
fidelity-first posture.
|
||||
- **Alternatives considered**: normalise-in/denormalise-out only (clean model, but
|
||||
round-tripping through a lossy scale shifts values); preserve native and convert only
|
||||
on export (zero round-trip risk, but every UI consumer must interpret
|
||||
platform-specific values).
|
||||
|
||||
### Prep UI: generic model with capability-gated controls
|
||||
- **Decision**: The prep UI (waveform, cues, grid) works purely off the generic model,
|
||||
with capability flags disabling or hiding the individual controls the loaded platform
|
||||
cannot persist (e.g. no memory-cue control on Traktor). No platform branching inside
|
||||
components.
|
||||
- **Rationale**: One UI to maintain, and users are never offered an edit that will
|
||||
silently vanish on save.
|
||||
- **Alternatives considered**: no gating, letting adapters silently collapse on write
|
||||
(simplest, but is precisely the failure mode the capability system exists to prevent);
|
||||
gate-plus-warn with controls left enabled (more discoverable, but risks nagging during
|
||||
normal prep work).
|
||||
|
||||
## Findings
|
||||
|
||||
### VERIFIED: Traktor flexible-grid representation in NML
|
||||
Checked against `All I Need` (Shiba San, Tim Baresko) in
|
||||
`/Users/ben/Documents/Native Instruments/Traktor 4.5.0/collection.nml`. A flexible grid
|
||||
is stored as **multiple `CUE_V2 TYPE="4"` markers, each with its own `<GRID BPM>`
|
||||
child**:
|
||||
|
||||
```
|
||||
TEMPO BPM="124.999908"
|
||||
CUE_V2 TYPE="4" NAME="AutoGrid" START="71.815535" GRID BPM="124.999908"
|
||||
CUE_V2 TYPE="4" NAME="Beat Marker" START="46151.849285" GRID BPM="62.499954"
|
||||
CUE_V2 TYPE="4" NAME="Beat Marker" START="76871.871785" GRID BPM="249.999817"
|
||||
```
|
||||
|
||||
- The first marker is named `AutoGrid`; subsequent ones are `Beat Marker`.
|
||||
- `TEMPO BPM` mirrors the **first** marker's BPM.
|
||||
- The half/double BPMs (62.5 / 250 against a base of 125) are genuine half-time and
|
||||
double-time sections.
|
||||
- A non-flexible track (`Cash Money`) has exactly one `TYPE="4"` marker — so the same
|
||||
structure covers both cases; a constant grid is just a marker list of length one.
|
||||
- Separately, tracks carry a `TYPE="0"` cue named `AutoGrid` in **hotcue slot 0** with
|
||||
`COLOR="#FFFFFF"`, positioned at almost (not exactly) the type-4 anchor's START.
|
||||
- `COLOR` is populated in practice, confirming Traktor does carry per-cue colour.
|
||||
|
||||
### Current `set_grid` is incorrect for flexible beatgrids (present-day bug risk)
|
||||
`PlaylistStore._grid_marker()` ([backend/konduktor/playlist_store.py:395](../../backend/konduktor/playlist_store.py#L395))
|
||||
returns only the **first** `CUE_V2` with a `grid` child. Consequences on a track with
|
||||
a flexible (multi-marker) grid:
|
||||
- `set_grid(bpm=X)` updates `TEMPO` and only the *first* marker's BPM, leaving
|
||||
subsequent markers at their old BPM → internally inconsistent grid written to disk.
|
||||
- `set_grid(anchor_sec=X)` moves only the first marker.
|
||||
- `delete_grid()` removes all grid markers, but **leaves the companion `TYPE="0"`
|
||||
`AutoGrid` hotcue-slot-0 cue behind** as debris, since it only strips cues with a
|
||||
`grid` child.
|
||||
- Concretely on `All I Need`: `set_grid(bpm=130)` would set `TEMPO` and the `AutoGrid`
|
||||
marker to 130 and leave the Beat Markers at 62.5 and 250 — a destroyed grid.
|
||||
- The frontend beatgrid drawing (`cues.ts`) is built around a single BPM + anchor, so
|
||||
a flexible grid would also render incorrectly.
|
||||
|
||||
CLAUDE.md describes the grid as "the grid marker (`CUE_V2` type 4 with a `<GRID BPM>`
|
||||
child)" — singular — so this assumption is baked into the docs as well as the code.
|
||||
|
||||
**Implication for step 1**: this is not a small bug fix. `set_grid(bpm, anchor_sec)`
|
||||
structurally cannot express per-marker edits, so the fix requires a new marker-level
|
||||
command vocabulary and marker selection in the `GridControls` UI.
|
||||
|
||||
## Next Steps
|
||||
1. **Design the grid marker command vocabulary** (plan mode, with
|
||||
`backend/konduktor/playlist_store.py` and `frontend/src/components/GridControls.tsx`
|
||||
open). `set_grid(bpm, anchor_sec)` must be replaced by marker-level commands, and
|
||||
`GridControls` needs marker selection.
|
||||
2. **Fix flexible-beatgrid handling** as a standalone change, including the
|
||||
`delete_grid` debris bug (the companion `TYPE="0"` `AutoGrid` hotcue-0 cue is left
|
||||
behind). Add a test fixture based on `All I Need` (three grid markers at 125 / 62.5 /
|
||||
250 BPM). Update CLAUDE.md, which documents the grid as singular.
|
||||
3. **Refactor to generic model + adapter interface, Traktor-only.** All existing tests
|
||||
must still pass unchanged — `test_save_fidelity.py` is the proof that the
|
||||
projection+command split changed nothing.
|
||||
4. **Add the Rekordbox adapter.** Research `rb_local_usn` / cloud-sync columns first.
|
||||
Write the Rekordbox verification test (row-level table-dump diff).
|
||||
5. **Add the Serato adapter.** GEOB-frame sidecar backups; write the Serato verification
|
||||
test (byte diff excluding the patched frame, plus whole-file crate diff).
|
||||
6. **Build the export path.** Only meaningful once two platforms exist.
|
||||
|
||||
### Command vocabulary: strictly generic, no adapter escape hatches
|
||||
- **Decision**: Every command is defined in generic-model terms and each adapter
|
||||
translates it. Adapters may not expose platform-specific commands.
|
||||
- **Rationale**: Keeps the UI fully platform-agnostic and forces genuine abstraction
|
||||
rather than letting platform specifics leak upward.
|
||||
- **Alternatives considered**: a generic core plus adapter escape hatches (pragmatic,
|
||||
but the hatch gets used and generic coverage quietly erodes); starting generic and
|
||||
adding hatches only on demonstrated need.
|
||||
- **Two-platform promotion rule** (resolves the single-platform-feature problem):
|
||||
- A feature that exists on only **one** platform is **preserved but not editable** —
|
||||
no command, no generic concept, no editing UI. Under projection+command it survives
|
||||
round-trip intact for free, because unmodelled native data never leaves the native
|
||||
model. The strictly-generic vocabulary therefore constrains what Konduktor can
|
||||
**edit**, not what it **preserves**.
|
||||
- A concept is **promoted into the core vocabulary once at least two platforms have
|
||||
it**, at which point there is real evidence of what the shared abstraction should
|
||||
be, rather than a concept invented to accommodate a single format.
|
||||
- *Rationale*: avoids both failure modes — inventing a fake abstraction to house a
|
||||
one-platform feature (e.g. a "performance sequence" concept only Serato ever uses),
|
||||
and opening an escape hatch that quietly erodes generic coverage.
|
||||
- *UI affordance*: show preserved-but-uneditable data as read-only, so users can see
|
||||
that e.g. their Serato Flip data is intact rather than assuming Konduktor discarded
|
||||
it. Makes the limitation honest instead of invisible.
|
||||
- *Consequence accepted*: conversion coverage is capped at what two or more platforms
|
||||
share — which matches the stated parity goal rather than compromising it.
|
||||
|
||||
### Save model: projection + command replay
|
||||
- **Decision**: The generic model is a **read projection**. Edits are expressed as
|
||||
commands and replayed by a per-platform adapter onto the **retained native model**,
|
||||
which remains the write target. Export is a separate, lossy path reading from the
|
||||
projection.
|
||||
- **Rationale**: It is the only model that matches how all three storage formats
|
||||
actually behave — Rekordbox `master.db` requires row `UPDATE`s (cannot be
|
||||
regenerated: internal IDs, FKs, ANLZ pointers, `rb_local_usn` sync columns), Serato
|
||||
requires patching individual GEOB frames inside audio files, and Traktor already
|
||||
deliberately avoids regeneration. It also preserves the byte-exact NML guarantee and
|
||||
`test_save_fidelity.py`, makes unknown native fields survive **for free** (they are
|
||||
never lifted out of the native model), and keeps edit *intent* explicit. Critically,
|
||||
Konduktor already implements this shape for Traktor: `CollectionService` is the read
|
||||
projection, `PlaylistStore` holds the native model with command methods, the HTTP API
|
||||
is already a command bus, and `replace_track()` is the projection refresh. This is a
|
||||
generalization, not a rewrite.
|
||||
- **Alternatives considered**: *Generic model as source of truth* — rejected: would
|
||||
lose unmodelled fields on real irreplaceable data, discards the byte-exact guarantee,
|
||||
cannot work for `master.db`, and its headline benefit (free conversion) is illusory
|
||||
since per-target serializers are needed either way; its only real prize is simpler UI
|
||||
mutation code. *Source of truth + diff-based writeback* — rejected: diffing destroys
|
||||
edit intent exactly where platforms disagree (grid phase-shift vs. retempo is
|
||||
indistinguishable in a marker-position diff), ordered-list diffs are fiddly, and it
|
||||
needs a full deep snapshot at load.
|
||||
- **Cost accepted**: an N×M adapter matrix (~15 commands × 3 platforms), plus careful
|
||||
choice of command altitude.
|
||||
|
||||
### Model shape: rich core + capability system
|
||||
- **Decision**: Model the union of *concepts* at full fidelity in the generic model —
|
||||
beatgrid is always a marker list, a cue always carries position/type/colour/role/slot
|
||||
— and build a per-platform **capability system** so the UI never offers an edit the
|
||||
loaded platform cannot persist.
|
||||
- **Rationale**: The conversion goal requires one shared vocabulary; anything parked in
|
||||
a platform-specific extension namespace cannot be converted. Ben confirmed
|
||||
willingness to build the capability UI.
|
||||
- **Alternatives considered**: *Union superset* — rejected, forces every UI consumer to
|
||||
branch on the loaded platform. *Core + per-platform extensions* — rejected, because
|
||||
the data that would land in extensions (Rekordbox memory cues, Serato saved loops) is
|
||||
central rather than exotic, and extensions do not convert.
|
||||
- **Note from Ben**: Traktor 3.4+ supports **flexible beatgrids**, so the marker-list
|
||||
model is right for all three platforms rather than being a Traktor-side compromise.
|
||||
This also means the current single-marker assumption in the codebase is already wrong
|
||||
(see Findings).
|
||||
|
||||
### Undo/redo: deferred but not precluded
|
||||
- **Decision**: Do not implement undo/redo now, but design the command layer so
|
||||
inverse commands can be added later.
|
||||
- **Rationale**: Keeps the adapter surface smaller for the initial build while
|
||||
retaining the option; the command model makes it cheap to add.
|
||||
- **Alternatives considered**: designing for inverses from day one (more discipline in
|
||||
every adapter method); ruling it out entirely (loses a strong safety feature).
|
||||
|
||||
### Format layers: reuse mature libraries
|
||||
- **Decision**: Use existing libraries for the Rekordbox and Serato format layers
|
||||
(e.g. `pyrekordbox` for `master.db`/SQLCipher/XML/ANLZ, an existing Serato
|
||||
crate+GEOB library), wrapped behind Konduktor's adapter interface.
|
||||
- **Rationale**: Fastest path to coverage; the project already accepts this class of
|
||||
dependency risk with `traktor-nml-utils`.
|
||||
- **Alternatives considered**: reuse for reading but own all write paths (more control
|
||||
over surgical patching and fidelity, more work); build everything in-house (maximum
|
||||
control, very large reverse-engineering effort); spike first and decide per platform.
|
||||
|
||||
## Agent Onboarding
|
||||
|
||||
### Summary
|
||||
Konduktor is today a Traktor-only tool whose defining property is **save fidelity**: it
|
||||
never regenerates `collection.nml`, it surgically patches a parsed dataclass model and
|
||||
renders through the library's own pipeline, so a no-op save is byte-identical and only
|
||||
edited objects diff (`test_save_fidelity.py`, CLAUDE.md gotcha 3).
|
||||
|
||||
Ben wants to extend it to Rekordbox and Serato, with library conversion as the ultimate
|
||||
payoff. His opening proposal was a generic data structure that all platforms load into,
|
||||
are edited through, and are saved back out of.
|
||||
|
||||
The central tension explored was that **"load into a generic model and serialize back
|
||||
out" would destroy the fidelity guarantee**. The discussion resolved it by establishing
|
||||
that for two of the three platforms, whole-model serialization is not even a coherent
|
||||
operation: Rekordbox's `master.db` is SQLite with internal IDs, FKs, ANLZ pointers and
|
||||
sync columns (you `UPDATE` rows, you cannot regenerate), and Serato's prep data lives as
|
||||
binary GEOB frames inside the audio files themselves (you patch a frame). Both are
|
||||
inherently mutation-oriented. This made **projection + command replay** the only model
|
||||
that generalizes — and, critically, Konduktor already implements exactly that shape for
|
||||
Traktor (`CollectionService` = read projection, `PlaylistStore` = native model + command
|
||||
methods, the HTTP API = command bus, `replace_track()` = projection refresh). The work is
|
||||
a generalization, not a rewrite.
|
||||
|
||||
A second thread established that the generic model should be **rich** (model the union
|
||||
of concepts at full fidelity, adapters collapse on write) rather than
|
||||
lowest-common-denominator or core-plus-extensions, because anything parked in a
|
||||
platform-specific namespace cannot be converted. This makes a **capability system**
|
||||
mandatory so the UI never offers an edit that silently won't persist.
|
||||
|
||||
A third thread covered **exports**: always a fresh, self-contained target library with
|
||||
copied audio, scoped by a user-curated **Export Set**. Because exports never merge into
|
||||
an existing target, cross-platform track identity is not needed at all — the existing
|
||||
path-based primary key suffices.
|
||||
|
||||
Along the way the discussion surfaced a **present-day bug**: Ben noted Traktor 3.4+
|
||||
supports flexible beatgrids, and verification against his real collection confirmed
|
||||
Traktor stores them as multiple `CUE_V2 TYPE="4"` markers each with its own `<GRID BPM>`.
|
||||
`PlaylistStore._grid_marker()` only ever reads the first, so `set_grid(bpm=X)` writes
|
||||
internally inconsistent grids to real collections today. This became step 1 of the plan,
|
||||
and it is bigger than a bug fix because the `set_grid(bpm, anchor_sec)` signature
|
||||
structurally cannot express per-marker edits.
|
||||
|
||||
Note: a "CDJ/USB export" requirement appeared in this log mid-discussion from a forked
|
||||
conversation. Ben confirmed it was rejected as impractical and had it removed. **Do not
|
||||
re-propose it.**
|
||||
|
||||
### If Continuing This Discussion
|
||||
All design questions are resolved. Three items remain, none of them decisions:
|
||||
- Grid marker command vocabulary — a design task for plan mode, not an open question.
|
||||
- Per-platform verification tests — implementation work landing with each adapter.
|
||||
- Rekordbox `rb_local_usn` / cloud-sync columns — research for the Rekordbox phase.
|
||||
|
||||
Deliberately deferred, do not reopen without Ben raising them: the export loss report
|
||||
("not for now"), bulk metadata editing, Tauri packaging, and CDJ/USB export (rejected).
|
||||
|
||||
### If Moving to Planning/Implementation
|
||||
|
||||
**Requirements**
|
||||
|
||||
1. **Save model — projection + command replay.** The generic model is a *read
|
||||
projection*. Edits are commands replayed by a per-platform adapter onto the
|
||||
**retained native model**, which stays the write target. Never serialize the generic
|
||||
model back over a native library. This preserves byte-exact NML saves and means
|
||||
unmodelled native fields survive for free.
|
||||
2. **Command vocabulary — strictly generic.** All commands are defined in generic-model
|
||||
terms; adapters translate. **No platform-specific escape hatches.** Single-platform
|
||||
features are *preserved but not editable*; a concept is promoted into the core
|
||||
vocabulary only once **two or more platforms have it**. Surface preserved-but-
|
||||
uneditable data as read-only in the UI.
|
||||
3. **Generic model — rich core.** Model the union of concepts at full fidelity.
|
||||
Beatgrid is **always a marker list** (a constant grid is a list of length one — this
|
||||
is correct for all three platforms, not a compromise). Cue shape:
|
||||
`{ position_sec, length_sec?, role: hotcue|memory, slot?, type: cue|fade_in|fade_out|
|
||||
load|loop, color?, name? }`.
|
||||
4. **Capability system — mandatory.** Capabilities are `f(platform, version)`, derived
|
||||
from the declared version where one exists; **Serato assumes the latest version** for
|
||||
simplicity. The prep UI works purely off the generic model with capability-gated
|
||||
controls — no platform branching inside components.
|
||||
5. **Field mapping — normalise, keep native alongside.** Canonical forms in the model
|
||||
(rating 0–5, canonical key, RGB colour) *plus* the untouched native value. On
|
||||
write-back, reuse the native value unless the user actually edited that field.
|
||||
**This requires per-field dirty tracking** — `PlaylistStore` is track-level today, and
|
||||
it must exist from the start because it cannot be retrofitted (edited-to-same-value
|
||||
becomes indistinguishable from untouched). It falls out of the command, which already
|
||||
names the field it changes.
|
||||
6. **Write scope — full read/write for all three platforms**, in place, to the user's
|
||||
canonical library. One library open at a time (`AppState` keeps holding exactly one).
|
||||
7. **Safety — same invariant, per-platform mechanism.** "An edit changes only what it
|
||||
was supposed to change." Traktor: byte diff (exists). Rekordbox: full table dump,
|
||||
row-level diff; back up `master.db` + WAL/SHM; **warn but proceed** if Rekordbox is
|
||||
running. Serato: byte diff of the audio file excluding the patched GEOB frame, plus
|
||||
whole-file crate diff; **back up GEOB frames to a sidecar, not whole audio files**
|
||||
(KB not GB; accepted risk: no protection if the tag library mangles an unrelated
|
||||
region — an exposure `file_tags.py` already carries).
|
||||
8. **Export — always a fresh, self-contained library** at a user-chosen destination,
|
||||
**including copied audio, for every target** (not just Serato). Never merges into an
|
||||
existing target library, so no cross-platform track identity is required.
|
||||
- Scoped by an **Export Set**: a named, persisted list of track and playlist
|
||||
references. **Live references** — resolved at export time, so the preview must be
|
||||
computed then, never stored. Playlist tracks auto-included, deduplicated, copied
|
||||
once.
|
||||
- Stored in Konduktor's own store (not `userprefs.json`), keyed by a stable library
|
||||
ID held in a **sidecar file next to the user's collection**.
|
||||
- Audio layout: a **global persistent setting** — flat single folder (**default**) or
|
||||
mirror source structure. Flat collisions get a **counter suffix** (`Xtal-2.mp3`).
|
||||
- Playlist folders preserved where the target supports them, otherwise flattened to
|
||||
**path-encoding names** (`House / Peak Time`).
|
||||
- **Pre-scan for missing audio files**, report, let the user decide. **Pre-check disk
|
||||
space**; progress with a working cancel (cancel leaves a partial export — clean up
|
||||
or mark clearly).
|
||||
- Re-export to an occupied destination: **warn, overwrite on confirm**.
|
||||
- Provide an explicit **"export entire library"** action that skips export-set creation.
|
||||
9. **Lossiness — degrade where sensible, drop otherwise.** Goal is maximum feature
|
||||
parity. No loss report for now (deferred, cheap to add later since adapters know what
|
||||
they collapsed).
|
||||
10. **Format layers — reuse mature libraries** (`pyrekordbox` for master.db/SQLCipher/
|
||||
XML/ANLZ; an existing Serato crate+GEOB library) behind Konduktor's adapter
|
||||
interface, consistent with the existing `traktor-nml-utils` dependency posture.
|
||||
11. **Undo/redo — not now, but do not preclude it.** Design commands so inverses can be
|
||||
added later.
|
||||
|
||||
**Sequencing** (see Next Steps for the actionable breakdown)
|
||||
Grid fix → Traktor-only refactor → Rekordbox → Serato → export. Rekordbox was chosen as
|
||||
the second platform over Serato because `pyrekordbox` is the more mature library, despite
|
||||
the riskier write target.
|
||||
|
||||
**Out of scope**: Tauri packaging, bulk metadata editing, CDJ/USB export
|
||||
(`export.pdb` + ANLZ — rejected as impractical), two-way sync, Konduktor owning its own
|
||||
canonical library format.
|
||||
|
||||
**Rejected alternatives worth not relitigating**
|
||||
- Generic model as source of truth, and source-of-truth + diff-based writeback — both
|
||||
rejected; see the save model decision. The claimed "free conversion" benefit is
|
||||
illusory (per-target serializers are needed either way), and diffing destroys edit
|
||||
intent exactly where platforms disagree.
|
||||
- Union superset and core-plus-extensions model shapes.
|
||||
- Cross-platform track matching by path/tags/content-hash/fingerprint — unnecessary
|
||||
given fresh-export-only.
|
||||
- Full audio-file backups for Serato writes.
|
||||
- Reference-in-place exports for non-Serato targets.
|
||||
|
||||
**Standing lesson from this discussion**: establish format capabilities **empirically**
|
||||
against real files rather than assuming them. An assumption that Traktor could not store
|
||||
cue colours was wrong (`CueV2Type` has a `color` field, populated in practice), and the
|
||||
flexible-grid assumption was only settled by reading Ben's actual collection.
|
||||
@@ -0,0 +1,221 @@
|
||||
# Handoff: the export feature
|
||||
|
||||
**For**: an agent picking up Konduktor with no prior context.
|
||||
**Task**: build library export — converting a curated slice of the loaded library
|
||||
into a **fresh, self-contained library for another platform**, with the audio
|
||||
files copied alongside.
|
||||
**Status of the plan**: the multi-platform work is done through the Rekordbox
|
||||
adapter. Export was originally sequenced *after* a Serato adapter; Ben has
|
||||
chosen to bring it forward, so **the only export targets that can exist today are
|
||||
Traktor and Rekordbox**.
|
||||
|
||||
Every *design* decision was settled in
|
||||
[`.claude/discussions/discuss-multi-platform-library-2026-09-17.md`](../discussions/discuss-multi-platform-library-2026-09-17.md)
|
||||
— read its **Export** sections and **"If Moving to Planning/Implementation"**
|
||||
before designing anything. This handoff is the current-state companion: what
|
||||
exists, what to build, and what will bite you. Where they disagree, the
|
||||
discussion doc wins on intent and this one on facts about the code.
|
||||
|
||||
The Rekordbox handoff ([`rekordbox-adapter.md`](rekordbox-adapter.md)) is worth
|
||||
skimming too — its §8 Findings are the format knowledge any Rekordbox *writer*
|
||||
will need, and its history is a good model of how this project verifies things.
|
||||
|
||||
---
|
||||
|
||||
## 1. Where the project is
|
||||
|
||||
Konduktor is a library-management and track-prep tool for DJ software, built on a
|
||||
**generic model + per-platform adapter** architecture. Two adapters exist:
|
||||
|
||||
- **Traktor** (`collection.nml`) — full read/write, byte-exact saves, version
|
||||
history.
|
||||
- **Rekordbox** (`master.db` + ANLZ analysis files) — read/write for metadata,
|
||||
playlists, hot cues and beatgrids. No version history (a deliberate, accepted
|
||||
scope decision). Gaps: cover art, `remap_locations`.
|
||||
|
||||
```
|
||||
backend/konduktor/
|
||||
core/ generic. MUST NOT import a native library type (test_layering.py)
|
||||
model.py Track, CuePoint, GridMarker, TrackCues, PlaylistNode…
|
||||
adapter.py LibraryAdapter / LibraryDriver protocols, SaveOutcome, errors
|
||||
capabilities.py what a loaded library can persist
|
||||
query.py TrackIndex: query/filter/sort/facets/stats
|
||||
registry.py adapter selection by can_open() probe
|
||||
adapters/traktor/ store.py (native model) adapter.py projection.py driver.py …
|
||||
adapters/rekordbox/ same shape; store.py owns the SQLCipher session + ANLZ
|
||||
app_state.py the one loaded library + version-history commits
|
||||
prefs.py userprefs.json in the per-OS app-data dir (paths.app_data_dir())
|
||||
main.py thin FastAPI routes, all under /api
|
||||
```
|
||||
|
||||
**Tests**: `cd backend && ./run_tests.sh` → 331 assertions across
|
||||
`test_layering.py`, `test_save_fidelity.py`, `test_traktor_adapter.py`,
|
||||
`test_rekordbox_adapter.py`, `test_rekordbox_fidelity.py`, `test_phase3.py`,
|
||||
`test_history.py`. Frontend: `npm run build && npm run test`.
|
||||
**The suite must be green at the end of every step** — that discipline is why a
|
||||
1,500-line refactor of the save path landed without a fidelity regression.
|
||||
|
||||
---
|
||||
|
||||
## 2. The one architectural gap, and it is not small
|
||||
|
||||
**No adapter can create a library from nothing.**
|
||||
|
||||
`LibraryDriver` is `can_open` / `open` / `detect` / `describe` / `restore`.
|
||||
`LibraryAdapter` is built entirely around *one already-open library* that commands
|
||||
are replayed onto. Export needs the opposite: **write a brand-new library at a
|
||||
path where nothing exists yet.**
|
||||
|
||||
This is the central design question of the whole feature, and the discussion doc
|
||||
does not settle it. Decide it deliberately and write down why. The obvious
|
||||
shapes:
|
||||
|
||||
1. **A separate `LibraryWriter` protocol** — `create(path)` returning something
|
||||
that accepts tracks, playlists and prep data, implemented per target. Keeps
|
||||
the edit path untouched, which matters because the edit path is the one with
|
||||
the fidelity guarantees. Some duplication with the adapters' write code.
|
||||
2. **Extend `LibraryDriver` with `create(path) -> LibraryAdapter`** — an empty
|
||||
library is then just a library, and the existing commands populate it. Elegant
|
||||
on paper; the risk is that "empty new file" and "the user's real library"
|
||||
start sharing code paths, and the *reason* the current architecture is safe is
|
||||
that the write target is always a retained native model that was parsed from a
|
||||
real file.
|
||||
3. **Target-specific exporters with no shared protocol** — fastest to a working
|
||||
Traktor export, and it will rot.
|
||||
|
||||
The discussion doc's strongest constraint bears on this: *"Two distinct write
|
||||
paths must coexist: a high-fidelity in-place edit path per platform, and a
|
||||
lossy-by-design export path. They have opposite requirements and should not
|
||||
share an implementation."* Read that as pointing at (1), but make the call
|
||||
yourself with the code in front of you.
|
||||
|
||||
---
|
||||
|
||||
## 3. What the design already settles
|
||||
|
||||
Do not relitigate these. They are decided, with rationale and rejected
|
||||
alternatives recorded in the discussion doc.
|
||||
|
||||
**Shape of an export**
|
||||
- Always a **fresh, self-contained library** at a user-chosen destination.
|
||||
**Never merges** into an existing target library. This is what removes any need
|
||||
for cross-platform track identity — there is nothing to match against.
|
||||
- **Always copies the audio files**, for every target, not just Serato.
|
||||
- Audio layout is a **global, persisted setting**: **flat single folder
|
||||
(default)** or **mirror the source directory structure**.
|
||||
- Flat-layout filename collisions get a **counter suffix** (`Xtal-2.mp3`).
|
||||
Known consequence: numbering depends on processing order, so repeat exports may
|
||||
assign different suffixes to the same tracks.
|
||||
- Playlist folders: **preserve where the target supports them**, otherwise
|
||||
flatten to path-encoding names (`House / Peak Time`).
|
||||
- Re-export to an occupied destination: **warn, overwrite on confirm.**
|
||||
- Provide an explicit **"export entire library"** action that skips export-set
|
||||
creation entirely.
|
||||
|
||||
**Export Sets** (the unit of curation)
|
||||
- A named, persisted list of **track and playlist references** scoping an export.
|
||||
Called an **Export Set**, never a "Crate" — Serato uses "crate" for a playlist
|
||||
and Konduktor will import those.
|
||||
- **References are LIVE**: an export set stores pointers, and export resolves
|
||||
them at export time, so later additions to a playlist are picked up.
|
||||
**Consequence: the export preview must be computed at export time, never
|
||||
stored.**
|
||||
- Playlist resolution **auto-includes** referenced tracks, **deduplicates**, and
|
||||
copies each file **exactly once**.
|
||||
- Stored in **Konduktor's own store**, not in the platform library and not in
|
||||
`userprefs.json`, keyed by a **stable library ID**.
|
||||
|
||||
**Running an export**
|
||||
- **Pre-scan for missing audio files**, report them, let the user cancel or
|
||||
proceed without them — fail fast rather than halfway through a multi-hour copy.
|
||||
- **Pre-check disk space** before starting.
|
||||
- **Progress with a working cancel.** Known consequence: cancelling leaves a
|
||||
partial export, which must be cleaned up or clearly marked incomplete.
|
||||
|
||||
**Lossiness**
|
||||
- **Degrade to the nearest equivalent where one exists, drop only where none
|
||||
does.** A Traktor fade-in cue becomes a plain cue on a target without them;
|
||||
Rekordbox memory cues fill spare hot cue slots until they run out.
|
||||
- **No loss report for now** — explicitly deferred. Adapters know what they
|
||||
collapsed, so it stays cheap to add.
|
||||
|
||||
---
|
||||
|
||||
## 4. Landmines, earned
|
||||
|
||||
**There is no stable library ID.** Export sets are specified as keyed by one,
|
||||
held in a sidecar next to the user's collection — and nothing like it exists.
|
||||
Today everything keys off the library's **OS path**: `prefs.get_path_mapping`,
|
||||
`prefs.get_last_collection`, and `history`'s repo directory (a hash of the
|
||||
resolved path). Moving a collection silently orphans all of it. Building export
|
||||
sets on the path would inherit that; building the sidecar is the decided design
|
||||
but is genuinely new work. Do it first — retrofitting an ID once sets exist means
|
||||
migrating them.
|
||||
|
||||
**The lossiness rule needs capabilities the target does not have loaded.**
|
||||
`Capabilities` describes *the currently open library*, via an adapter instance
|
||||
built from a real file. Export needs to know what a target platform can hold
|
||||
*before* any such library exists. Either capabilities must become derivable from
|
||||
a platform alone (not an instance), or exporters must carry their own static
|
||||
declaration. This is exactly where a "what can the target represent?" question
|
||||
will first bite, and `capabilities_for()` in each adapter currently takes a
|
||||
`path`.
|
||||
|
||||
**The two-platform promotion rule still applies.** A concept enters the generic
|
||||
vocabulary only once **two or more** platforms have it. Export will tempt you to
|
||||
add target-specific knobs to generic types; don't. Single-platform concepts stay
|
||||
*preserved but not editable* — for instance Rekordbox **memory cues** are
|
||||
projected and displayed and never written.
|
||||
|
||||
**Rekordbox as an export TARGET is much harder than Traktor.** A Traktor export
|
||||
is one XML file Konduktor already renders byte-exactly. A Rekordbox export needs
|
||||
a `master.db` — SQLCipher, foreign keys into lookup tables, USN bookkeeping — plus
|
||||
per-track ANLZ analysis files containing the beatgrid, plus `masterPlaylists6.xml`.
|
||||
Worse, `.DAT`/`.EXT` analysis files can currently only be *modified*, never
|
||||
created: `beatgrid.write_pqtz()` rebuilds the `PQTZ` tag **inside an existing
|
||||
file**. Generating ANLZ from scratch is unexplored, and `PQT2` (the extended
|
||||
grid) is undecoded — `pyrekordbox` names its per-beat field `unkown`.
|
||||
**Strongly consider shipping Traktor as the only export target first.**
|
||||
|
||||
**CDJ/USB export (`export.pdb` + ANLZ) is rejected as impractical.** It has been
|
||||
re-proposed twice. Do not raise it again.
|
||||
|
||||
---
|
||||
|
||||
## 5. Working agreements
|
||||
|
||||
- **`./run_tests.sh` green at the end of every step.**
|
||||
- **`schemas.py` and `api.ts` land in the same commit** — one contract in two
|
||||
languages.
|
||||
- **Verify against reality, do not infer.** The project's standing lesson, and it
|
||||
has been proved right four times: Traktor cue colours, flexible grid marker
|
||||
naming, whether Rekordbox reads `PQTZ` or `PQT2`, and the hot cue slot
|
||||
encoding. That last one cost two rounds of wrong theory built on three
|
||||
incidental data points; one deliberate probe across the full range settled it.
|
||||
For export the equivalent is: **write an export, then open it in the real DJ
|
||||
software** before believing it works.
|
||||
- **Ben's Rekordbox library is a disposable test library** — write to it directly,
|
||||
no backups needed. **His Traktor collection is real, irreplaceable data**
|
||||
(8,485 entries): always work against copies. `./dev-sandbox.sh` already
|
||||
encodes exactly this split and refuses to start if another server holds the
|
||||
ports.
|
||||
- **Capability-gate every control.** The UI must never offer an edit — or an
|
||||
export target — that cannot actually be produced. This has failed twice and
|
||||
both times it was a stale flag, not missing machinery.
|
||||
|
||||
## 6. Suggested first steps
|
||||
|
||||
1. **Decide the writer architecture** (§2) and record the decision and its
|
||||
rejected alternatives, in the style of the discussion doc.
|
||||
2. **Build the stable library ID sidecar** (§4) — everything else keys off it.
|
||||
3. **Export Sets: model, store, API, UI.** Live references; preview computed at
|
||||
export time.
|
||||
4. **A Traktor exporter end to end**, with the audio copy, the pre-scan, the
|
||||
space check and cancellable progress.
|
||||
5. **Open the result in Traktor.** Not "the tests pass" — actually open it.
|
||||
6. Only then consider a Rekordbox exporter, knowing §4's warning.
|
||||
|
||||
Bulk metadata editing also remains unbuilt and unblocked; it is far smaller than
|
||||
this and was deferred specifically until the adapter architecture existed. If a
|
||||
shippable win is wanted sooner, that is the alternative — confirm with Ben rather
|
||||
than assuming.
|
||||
File diff suppressed because it is too large.
Load diff
+4
-1
@@ -18,11 +18,14 @@ frontend/dist-ssr/
|
||||
# The collection is personal, large, and irreplaceable — don't commit it.
|
||||
# Remove this if you deliberately want to version a sample .nml.
|
||||
*.nml
|
||||
# Backups Konduktor will create before any write (Phase 3+).
|
||||
# Legacy pre-git backups (superseded by version history; left ignored so any
|
||||
# old .bak files on disk stay out of git).
|
||||
*.nml.bak
|
||||
*.nml.backup
|
||||
*.nml.*.bak
|
||||
backups/
|
||||
# Version-history git repos, if a dev points KONDUKTOR_DATA_DIR inside the repo.
|
||||
history/
|
||||
|
||||
# ---- Editor / OS ----
|
||||
.vscode/
|
||||
|
||||
@@ -158,10 +158,20 @@ The installers land in `frontend\src-tauri\target\release\bundle\` (an `.msi` an
|
||||
an NSIS `-setup.exe`). See [BUILDING-WINDOWS.md](BUILDING-WINDOWS.md) for the full
|
||||
walkthrough and Windows-specific notes.
|
||||
|
||||
> **Note:** builds are currently **unsigned**, so the first launch is flagged by
|
||||
> the OS — on macOS right-click → **Open** to get past Gatekeeper; on Windows
|
||||
> click **More info → Run anyway** past SmartScreen. The macOS `.dmg` is
|
||||
> Apple-Silicon (`aarch64`) only.
|
||||
> **First launch — getting past the OS security prompt.** Builds are
|
||||
> **ad-hoc signed, not notarized** (no paid Apple/Windows developer cert yet), so
|
||||
> the OS flags them the first time. This is expected — the app isn't damaged.
|
||||
>
|
||||
> - **macOS:** right-click the app → **Open** → **Open** (or System Settings →
|
||||
> Privacy & Security → **Open Anyway** after the first blocked attempt). If it
|
||||
> still refuses — common for a `.dmg` downloaded via a browser, which macOS
|
||||
> quarantines — clear the quarantine flag once from Terminal:
|
||||
> ```bash
|
||||
> xattr -cr /Applications/Konduktor.app
|
||||
> ```
|
||||
> - **Windows:** click **More info → Run anyway** past SmartScreen.
|
||||
>
|
||||
> The macOS `.dmg` is Apple-Silicon (`aarch64`) only.
|
||||
|
||||
> **Faster local builds:** `npx tauri build --debug --bundles app` skips the
|
||||
> optimizer and the installer, giving you a runnable app in seconds — handy while
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
"""Benchmark beatgrid detection against grids a DJ platform already analysed.
|
||||
|
||||
NOT part of `run_tests.sh`: it needs real audio, and the answer is a score to
|
||||
compare rather than a pass/fail. Every open is read-only — nothing is saved.
|
||||
|
||||
python bench_grid_detect.py # the local Rekordbox library
|
||||
python bench_grid_detect.py path/to/collection.nml path/to/master.db
|
||||
python bench_grid_detect.py --legacy # score the old librosa beat_track
|
||||
|
||||
The reference is each track's own grid, and only single-marker grids are used:
|
||||
a multi-marker grid is either a real tempo change (which a constant-tempo
|
||||
detector cannot match by design) or a hand edit, and neither is ground truth
|
||||
for "what is this track's tempo".
|
||||
|
||||
Per track it reports:
|
||||
- BPM error, and whether it is an octave error (half/double tempo);
|
||||
- PHASE error at 30 s in and 30 s before the end — the distance between the
|
||||
detected grid's nearest beat and the reference's, in ms. Measuring at two
|
||||
ends is what separates "anchor wrong" (both off by the same amount) from
|
||||
"BPM wrong" (error grows along the track), which one number would conflate.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
os.environ.setdefault("KONDUKTOR_DATA_DIR", tempfile.mkdtemp(prefix="konduktor-bench-"))
|
||||
|
||||
import konduktor.adapters # noqa: E402,F401 — registers the drivers
|
||||
from konduktor.core import registry # noqa: E402
|
||||
|
||||
BPM_OK = 0.02 # a grid this close drifts < 1/50 beat per minute...
|
||||
PHASE_OK_MS = 10.0 # roughly where a DJ starts to hear flamming
|
||||
|
||||
|
||||
def _phase_error_ms(t: float, ref: tuple[float, float], det: tuple[float, float]) -> float:
|
||||
"""Signed distance (ms) from the reference's nearest beat at ``t`` to the
|
||||
detected grid's nearest beat, wrapped to half the reference beat."""
|
||||
r0, rb = ref
|
||||
d0, db = det
|
||||
rp, dp = 60.0 / rb, 60.0 / db
|
||||
ref_beat = r0 + round((t - r0) / rp) * rp
|
||||
det_beat = d0 + round((ref_beat - d0) / dp) * dp
|
||||
e = det_beat - ref_beat
|
||||
e = (e + rp / 2) % rp - rp / 2
|
||||
return e * 1000.0
|
||||
|
||||
|
||||
def _octave(det: float, ref: float) -> str:
|
||||
for k, name in ((2.0, "x2"), (0.5, "/2"), (1.5, "x1.5"), (2 / 3, "/1.5")):
|
||||
if abs(det - ref * k) < 0.5:
|
||||
return name
|
||||
return ""
|
||||
|
||||
|
||||
def legacy_detect(audio_path: str):
|
||||
"""The detector `core/grid_detect.py` replaced (librosa ``beat_track``), kept
|
||||
here so the two can still be compared on the same references."""
|
||||
import librosa
|
||||
import numpy as np
|
||||
from konduktor.core.grid_detect import GridResult
|
||||
|
||||
y, sr = librosa.load(audio_path, sr=22050, mono=True)
|
||||
tempo, beats = librosa.beat.beat_track(y=y, sr=sr, trim=False)
|
||||
return GridResult(float(np.ravel(tempo)[0]), float(librosa.frames_to_time(beats, sr=sr)[0]), len(y) / sr)
|
||||
|
||||
|
||||
def references(paths: list[Path]) -> list[tuple[str, Path, float, float]]:
|
||||
out = []
|
||||
for p in paths:
|
||||
a = registry.open_library(p)
|
||||
try:
|
||||
for t in a.tracks:
|
||||
cues = a.track_cues(t.id)
|
||||
if cues is None or len(cues.grid_markers) != 1:
|
||||
continue
|
||||
audio = a.audio_path(t.id)
|
||||
if audio is None or not audio.exists():
|
||||
continue
|
||||
m = cues.grid_markers[0]
|
||||
out.append((f"{t.artist or ''} - {t.title or audio.stem}".strip(" -"), audio, m.start, m.bpm))
|
||||
finally:
|
||||
close = getattr(a, "close", None)
|
||||
if close:
|
||||
close()
|
||||
# One row per audio file: the same file in two libraries would count twice.
|
||||
seen, uniq = set(), []
|
||||
for r in out:
|
||||
if r[1] not in seen:
|
||||
seen.add(r[1])
|
||||
uniq.append(r)
|
||||
return uniq
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("libraries", nargs="*", type=Path)
|
||||
ap.add_argument("--legacy", action="store_true", help="score the old librosa beat_track detector")
|
||||
args = ap.parse_args()
|
||||
|
||||
libs = args.libraries or [Path.home() / "Library/Pioneer/rekordbox/master.db"]
|
||||
refs = references(libs)
|
||||
if not refs:
|
||||
print("No single-marker reference grids with reachable audio.")
|
||||
return 1
|
||||
|
||||
if args.legacy:
|
||||
detect = legacy_detect
|
||||
else:
|
||||
from konduktor.core.grid_detect import detect_grid as detect
|
||||
|
||||
rows = []
|
||||
for name, audio, r0, rb in refs:
|
||||
t0 = time.perf_counter()
|
||||
try:
|
||||
res = detect(str(audio))
|
||||
except Exception as ex: # a failure is a data point, not a crash
|
||||
print(f" FAIL {name[:48]:48} {ex}")
|
||||
rows.append(None)
|
||||
continue
|
||||
dt = time.perf_counter() - t0
|
||||
bpm, first = res.bpm, res.anchor
|
||||
import soundfile as sf
|
||||
try:
|
||||
dur = sf.info(str(audio)).duration
|
||||
except Exception:
|
||||
dur = res.duration
|
||||
early = _phase_error_ms(min(30.0, dur / 3), (r0, rb), (first, bpm))
|
||||
late = _phase_error_ms(max(dur - 30.0, 2 * dur / 3), (r0, rb), (first, bpm))
|
||||
oct_ = _octave(bpm, rb) if abs(bpm - rb) >= 0.5 else ""
|
||||
ok = abs(bpm - rb) <= BPM_OK and abs(early) <= PHASE_OK_MS and abs(late) <= PHASE_OK_MS
|
||||
lossy = audio.suffix.lower() not in (".wav", ".aif", ".aiff", ".flac")
|
||||
rows.append((abs(bpm - rb), early, late, oct_, ok, dt, lossy))
|
||||
conf = f"{res.drift_ms:5.1f}" if res.drift_ms is not None else " -"
|
||||
print(
|
||||
f" {'ok ' if ok else 'BAD '} {name[:48]:48} ref {rb:7.3f} got {bpm:8.3f} {oct_:5}"
|
||||
f" phase {early:+7.1f} / {late:+7.1f} ms drift {conf} ms {dt:4.1f}s"
|
||||
)
|
||||
|
||||
good = [r for r in rows if r]
|
||||
n = len(rows)
|
||||
same_octave = [r for r in good if not r[3]]
|
||||
print()
|
||||
print(f"tracks {n}")
|
||||
print(f"all correct {sum(r[4] for r in good)}/{n}")
|
||||
print(f"BPM within {BPM_OK} {sum(r[0] <= BPM_OK for r in good)}/{n}")
|
||||
print(f"octave errors {sum(bool(r[3]) for r in good)}/{n}")
|
||||
if same_octave:
|
||||
import statistics as st
|
||||
print(f"median |phase| early {st.median(abs(r[1]) for r in same_octave):.1f} ms")
|
||||
print(f"median |phase| late {st.median(abs(r[2]) for r in same_octave):.1f} ms")
|
||||
print(f"phase within {PHASE_OK_MS:.0f} ms "
|
||||
f"{sum(abs(r[1]) <= PHASE_OK_MS and abs(r[2]) <= PHASE_OK_MS for r in same_octave)}/{n}")
|
||||
print(f"mean time per track {sum(r[5] for r in good) / max(1, len(good)):.2f} s")
|
||||
|
||||
# A platform's MP3/AAC time base can differ from the decoded audio's by a
|
||||
# constant (Rekordbox: ~+26 ms, the decoder delay it does not trim). That
|
||||
# is not detection error, and it would swamp it — so report the constant
|
||||
# per format, and how tightly the tracks sit around it.
|
||||
import statistics as st
|
||||
print()
|
||||
for label, want in (("lossless", False), ("lossy", True)):
|
||||
grp = [r for r in same_octave if r[6] == want and r[0] <= BPM_OK]
|
||||
if len(grp) < 2:
|
||||
continue
|
||||
offs = [(r[1] + r[2]) / 2 for r in grp]
|
||||
med = st.median(offs)
|
||||
spread = [abs(o - med) for o in offs]
|
||||
within = sum(abs(r[1] - med) <= PHASE_OK_MS and abs(r[2] - med) <= PHASE_OK_MS for r in grp)
|
||||
print(f"{label:9} n={len(grp):2} constant offset {med:+6.1f} ms "
|
||||
f"|deviation| median {st.median(spread):4.1f} max {max(spread):5.1f} ms "
|
||||
f"within {PHASE_OK_MS:.0f} ms of it: {within}/{len(grp)}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,133 @@
|
||||
"""Benchmark Auto Hotcues' structure events against Rekordbox's phrase analysis.
|
||||
|
||||
NOT part of `run_tests.sh`: it needs real audio and a Rekordbox library whose
|
||||
tracks were analysed with phrase analysis on (the `PSSI` tag in each `.EXT`).
|
||||
Read-only — nothing is saved.
|
||||
|
||||
python bench_structure.py # the local Rekordbox library
|
||||
python bench_structure.py -v # per-track events, detected vs reference
|
||||
|
||||
The reference is Rekordbox's own analysis, not ground truth, and it is only
|
||||
comparable on "High"-mood tracks, whose labels map onto what a DJ cues:
|
||||
Intro / Up (build) / Down (breakdown) / Chorus (drop) / Outro. "Mid" tracks are
|
||||
labelled Verse / Chorus / Bridge and are reported separately for that reason.
|
||||
Tracks whose detected BPM is a different octave from Rekordbox's are skipped:
|
||||
their bars are not the same bars.
|
||||
|
||||
Events are compared in bars from each side's own first downbeat:
|
||||
- drop_n = start of the n-th Chorus run;
|
||||
- breakdown_n = end of the n-th drop, when another drop follows;
|
||||
- build_n = the Up run right before drop_n (Rekordbox's Up usually spans the
|
||||
whole pre-drop groove, so this one is indicative at best);
|
||||
- outro = start of the Outro.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
os.environ.setdefault("KONDUKTOR_DATA_DIR", tempfile.mkdtemp(prefix="konduktor-bench-"))
|
||||
|
||||
import konduktor.adapters # noqa: E402,F401 — registers the drivers
|
||||
from konduktor.core import grid_detect, registry, structure # noqa: E402
|
||||
|
||||
DROP = {1: 5, 2: 9} # PSSI kind of a Chorus, by mood (1 = High, 2 = Mid)
|
||||
OUTRO = {1: 6, 2: 10}
|
||||
UP = {1: 2}
|
||||
|
||||
|
||||
def references(db: Path) -> list[dict]:
|
||||
from pyrekordbox.anlz import AnlzFile
|
||||
|
||||
a = registry.open_library(db)
|
||||
out = []
|
||||
try:
|
||||
st = a._store
|
||||
for t in a.tracks:
|
||||
path = a.audio_path(t.id)
|
||||
rel = getattr(st.content(t.id), "AnalysisDataPath", None)
|
||||
if not path or not path.exists() or not rel:
|
||||
continue
|
||||
base = st.path.parent / "share" / str(rel).lstrip("/\\")
|
||||
ext = base.with_suffix(".EXT")
|
||||
if not (base.is_file() and ext.is_file()):
|
||||
continue
|
||||
rec = {"path": str(path), "title": t.title or path.stem}
|
||||
for tag in AnlzFile.parse_file(str(base)).tags:
|
||||
if tag.type == "PQTZ" and len(tag.content.entries): # one-shots have none
|
||||
e = tag.content.entries
|
||||
rec["bpm"] = e[0].tempo / 100
|
||||
rec["first_down"] = next(i for i, x in enumerate(e) if x.beat == 1)
|
||||
for tag in AnlzFile.parse_file(str(ext)).tags:
|
||||
if tag.type == "PSSI":
|
||||
rec["mood"] = tag.content.mood
|
||||
rec["phrases"] = [(x.beat, x.kind) for x in tag.content.entries]
|
||||
if "phrases" in rec and "bpm" in rec:
|
||||
out.append(rec)
|
||||
finally:
|
||||
a.close()
|
||||
return out
|
||||
|
||||
|
||||
def truth(rec: dict) -> dict[str, int]:
|
||||
runs: list[tuple[int, int]] = []
|
||||
for beat, kind in rec["phrases"]:
|
||||
bar = round((beat - 1 - rec["first_down"]) / 4)
|
||||
if not runs or runs[-1][1] != kind:
|
||||
runs.append((bar, kind))
|
||||
m, ev = rec["mood"], {}
|
||||
drops = [i for i, (_, k) in enumerate(runs) if k == DROP.get(m)]
|
||||
for n, i in enumerate(drops, start=1):
|
||||
ev[f"drop_{n}"] = runs[i][0]
|
||||
if n < len(drops) and i + 1 < len(runs):
|
||||
ev[f"breakdown_{n}"] = runs[i + 1][0]
|
||||
if m in UP and i > 0 and runs[i - 1][1] == UP[m]:
|
||||
ev[f"build_{n}"] = runs[i - 1][0]
|
||||
outro = [b for b, k in runs if k == OUTRO.get(m)]
|
||||
if outro:
|
||||
ev["outro"] = outro[0]
|
||||
return ev
|
||||
|
||||
|
||||
def main() -> int:
|
||||
verbose = "-v" in sys.argv
|
||||
args = [a for a in sys.argv[1:] if not a.startswith("-")]
|
||||
db = Path(args[0]) if args else Path.home() / "Library/Pioneer/rekordbox/master.db"
|
||||
refs = references(db)
|
||||
if not refs:
|
||||
print("No tracks with Rekordbox phrase analysis and reachable audio.")
|
||||
return 1
|
||||
|
||||
for mood, label in ((1, "High"), (2, "Mid")):
|
||||
stats: dict[str, list[int]] = {}
|
||||
for rec in (r for r in refs if r["mood"] == mood):
|
||||
g = grid_detect.detect_grid(rec["path"])
|
||||
if abs(g.bpm - rec["bpm"]) >= 1:
|
||||
continue # a different octave: not the same bars
|
||||
st = structure.analyse(rec["path"], [(g.anchor, g.bpm)])
|
||||
det = {k: (v - st.bar0) // 4 for k, v in st.events.items()}
|
||||
tru = truth(rec)
|
||||
if verbose:
|
||||
print(f" {rec['title'][:28]:28} ref {tru}\n {'':28} got { {k: det[k] for k in tru if k in det} }")
|
||||
for e, bar in tru.items():
|
||||
key = e if e in ("drop_1", "drop_2", "breakdown_1", "build_1", "build_2", "outro") else e.split("_")[0] + "_n"
|
||||
s = stats.setdefault(key, [0, 0, 0])
|
||||
s[0] += 1
|
||||
if e in det:
|
||||
s[1] += det[e] == bar
|
||||
s[2] += abs(det[e] - bar) <= 4
|
||||
if not stats:
|
||||
continue
|
||||
print(f"== {label}-mood tracks")
|
||||
for k in sorted(stats):
|
||||
n, exact, near = stats[k]
|
||||
print(f" {k:12} n={n:2} exact bar {exact:2} ({exact / n:4.0%}) within 4 bars {near:2} ({near / n:4.0%})")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -11,6 +11,15 @@ PY="${PY:-.venv/bin/python}"
|
||||
"$PY" -m PyInstaller --noconfirm --clean konduktor-sidecar.spec
|
||||
echo "Built: $ROOT/dist/konduktor-sidecar"
|
||||
|
||||
# NOTE: do NOT re-codesign this binary. PyInstaller already ad-hoc signs the
|
||||
# one-file bootloader AND its packed libraries (Python.framework, etc.) with a
|
||||
# matching identity. Re-signing only the outer bootloader (e.g. `codesign -s -`)
|
||||
# desyncs the Team IDs, so at runtime dlopen of the extracted Python framework
|
||||
# fails with "different Team IDs" and the sidecar dies on launch (which makes
|
||||
# the Tauri app panic: "backend sidecar did not report a port"). The app bundle
|
||||
# is ad-hoc signed separately via tauri.conf.json `bundle.macOS.signingIdentity`,
|
||||
# which seals this binary without re-signing it.
|
||||
|
||||
# Stage for Tauri: the sidecar must be named with the host target triple so the
|
||||
# shell plugin can resolve it in both dev and bundle. (rustc must be on PATH.)
|
||||
if command -v rustc >/dev/null 2>&1; then
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
placeholder
|
||||
@@ -0,0 +1 @@
|
||||
placeholder
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,58 @@
|
||||
# OneLibrary fixture drive
|
||||
|
||||
A real OneLibrary USB export, trimmed to the size of a test fixture. This is the
|
||||
drive `test_onelibrary_adapter.py` runs against, so the suite needs no USB stick
|
||||
plugged in and gives the same answer on every machine.
|
||||
|
||||
Produced by rekordbox 7.2.18 exporting a two-track playlist to an exFAT stick.
|
||||
**Nothing in the database was written or edited by Konduktor** — it is the bytes
|
||||
rekordbox itself wrote, which is the whole point of a fixture whose job is to
|
||||
prove we read the real format correctly.
|
||||
|
||||
## What was changed
|
||||
|
||||
Only the analysis files, and only by deleting whole tags:
|
||||
|
||||
| File | Original | Here |
|
||||
|---|---|---|
|
||||
| `ANLZ0000.DAT` | 4,972 B | 2,812 B |
|
||||
| `ANLZ0000.EXT` | 85,602 B | 732 B |
|
||||
|
||||
`PPTH`, `PQTZ`, `PCOB` and `PCO2` — the path, the beatgrid and the two cue lists,
|
||||
i.e. everything the adapter reads — are kept **byte for byte**. The waveform tags
|
||||
(`PWAV`, `PWV2`–`PWV5`) are dropped, which is where ~99% of the `.EXT` went, and
|
||||
the `.2EX` files are omitted entirely.
|
||||
|
||||
The trim is byte-level tag surgery, rewriting only the `PMAI` header's file
|
||||
length: `pyrekordbox` cannot rebuild a file containing cue tags, so re-serialising
|
||||
was not an option.
|
||||
|
||||
The two `.mp3` files are **placeholders**, not audio. The adapter resolves paths
|
||||
and never opens them; carrying 12 MB of demo tracks in the repo to prove that
|
||||
would be silly.
|
||||
|
||||
## What is in it
|
||||
|
||||
- 2 tracks, one of which (`Demo Track 1`) carries a **flexible multi-tempo grid**
|
||||
(128.00 BPM to 60 s, then 90.00 BPM) — the awkward case, deliberately.
|
||||
- 4 hot cues plus a looped memory cue on that track, including one on pad **D**,
|
||||
which is the cue that lives only in the `.EXT` and that a reader looking at the
|
||||
`.DAT` alone would lose.
|
||||
- 1 playlist, `demos`, holding both tracks in order.
|
||||
|
||||
`Demo Track 1`'s title still reads `[KONDUKTOR WROTE THIS]` because the grid and
|
||||
title were written into `master.db` by Konduktor before the export. That is
|
||||
incidental to the fixture, but it does record that the whole chain — Konduktor →
|
||||
`master.db` → rekordbox's OneLibrary export → this file — preserved them.
|
||||
|
||||
## schema.sql
|
||||
|
||||
The complete `CREATE TABLE` set for a OneLibrary database, all 22 tables,
|
||||
extracted from Traktor Pro 4.5's binary, which embeds the DDL it uses to create
|
||||
one. AlphaTheta publishes no specification, so this is the closest thing to one:
|
||||
a second vendor's independent implementation of the same schema. It was verified
|
||||
by building an empty database from it and having `pyrekordbox`'s ORM — a third
|
||||
implementation — open and write to it.
|
||||
|
||||
Not loaded by the tests; kept as documentation, and as the starting point if
|
||||
Konduktor ever needs to create a drive from nothing.
|
||||
@@ -0,0 +1,208 @@
|
||||
CREATE TABLE IF NOT EXISTS "content" (
|
||||
"content_id" integer primary key not null,
|
||||
"title" varchar,
|
||||
"titleForSearch" varchar,
|
||||
"subtitle" varchar,
|
||||
"bpmx100" int,
|
||||
"length" int,
|
||||
"trackNo" int,
|
||||
"discNo" int,
|
||||
"artist_id_artist" int,
|
||||
"artist_id_remixer" int,
|
||||
"artist_id_originalArtist" int,
|
||||
"artist_id_composer" int,
|
||||
"artist_id_lyricist" int,
|
||||
"album_id" int,
|
||||
"genre_id" int,
|
||||
"label_id" int,
|
||||
"key_id" int,
|
||||
"color_id" int,
|
||||
"image_id" int,
|
||||
"djComment" varchar,
|
||||
"rating" int,
|
||||
"releaseYear" int,
|
||||
"releaseDate" varchar,
|
||||
"dateAdded" varchar,
|
||||
"dateCreated" varchar,
|
||||
"path" varchar,
|
||||
"fileName" varchar,
|
||||
"fileSize" int,
|
||||
"fileType" int,
|
||||
"bitrate" int,
|
||||
"bitDepth" int,
|
||||
"samplingRate" int,
|
||||
"isrc" varchar,
|
||||
"djPlayCount" int,
|
||||
"isHotCueAutoLoadOn" int,
|
||||
"isKuvoDeliverStatusOn" int,
|
||||
"kuvoDeliveryComment" varchar,
|
||||
"masterDbId" int not null,
|
||||
"masterContentId" int not null,
|
||||
"analysisDataFilePath" varchar,
|
||||
"analysedBits" int,
|
||||
"contentLink" int,
|
||||
"hasModified" int,
|
||||
"cueUpdateCount" int,
|
||||
"analysisDataUpdateCount" int,
|
||||
"informationUpdateCount" int
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "genre" (
|
||||
"genre_id" integer primary key not null,
|
||||
"name" varchar
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "artist" (
|
||||
"artist_id" integer primary key not null,
|
||||
"name" varchar,
|
||||
"nameForSearch" varchar
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "album" (
|
||||
"album_id" integer primary key not null,
|
||||
"name" varchar not null,
|
||||
"artist_id" int,
|
||||
"image_id" int,
|
||||
"isComplation" int,
|
||||
"nameForSearch" varchar
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "label" (
|
||||
"label_id" integer primary key not null,
|
||||
"name" varchar
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "key" (
|
||||
"key_id" integer primary key not null,
|
||||
"name" varchar
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "color" (
|
||||
"color_id" integer primary key not null,
|
||||
"name" varchar
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "playlist" (
|
||||
"playlist_id" integer primary key not null,
|
||||
"sequenceNo" int,
|
||||
"name" varchar,
|
||||
"image_id" int,
|
||||
"attribute" int,
|
||||
"playlist_id_parent" int
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "playlist_content" (
|
||||
"playlist_id" int not null,
|
||||
"content_id" int not null,
|
||||
"sequenceNo" int not null
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "history" (
|
||||
"history_id" integer primary key not null,
|
||||
"sequenceNo" int,
|
||||
"name" varchar,
|
||||
"attribute" int,
|
||||
"history_id_parent" int
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "history_content" (
|
||||
"history_id" int,
|
||||
"content_id" int,
|
||||
"sequenceNo" int
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "image" (
|
||||
"image_id" integer primary key not null,
|
||||
"path" varchar
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "menuItem" (
|
||||
"menuItem_id" integer primary key not null,
|
||||
"kind" int,
|
||||
"name" varchar
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "category" (
|
||||
"category_id" integer primary key not null,
|
||||
"menuItem_id" int,
|
||||
"sequenceNo" int,
|
||||
"isVisible" int
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "sort" (
|
||||
"sort_id" integer primary key not null,
|
||||
"menuItem_id" int,
|
||||
"sequenceNo" int,
|
||||
"isVisible" int,
|
||||
"isSelectedAsSubColumn" int
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "property" (
|
||||
"deviceName" varchar,
|
||||
"dbVersion" varchar,
|
||||
"numberOfContents" int,
|
||||
"createdDate" varchar,
|
||||
"backGroundColorType" int,
|
||||
"myTagMasterDBID" int
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "hotCueBankList" (
|
||||
"hotCueBankList_id" integer primary key not null,
|
||||
"sequenceNo" int,
|
||||
"name" varchar,
|
||||
"image_id" int,
|
||||
"attribute" int,
|
||||
"hotCueBankList_id_parent" int
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "hotCueBankList_cue" (
|
||||
"hotCueBankList_id" int not null,
|
||||
"cue_id" int not null,
|
||||
"sequenceNo" int not null
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "cue" (
|
||||
"cue_id" integer primary key not null,
|
||||
"content_id" int not null,
|
||||
"kind" int not null,
|
||||
"colorTableIndex" int,
|
||||
"cueComment" varchar,
|
||||
"isActiveLoop" int not null,
|
||||
"beatLoopNumerator" int,
|
||||
"beatLoopDenominator" int,
|
||||
"inUsec" int not null,
|
||||
"outUsec" int,
|
||||
"in150FramePerSec" int not null,
|
||||
"out150FramePerSec" int,
|
||||
"inMpegFrameNumber" int,
|
||||
"outMpegFrameNumber" int,
|
||||
"inMpegAbs" int,
|
||||
"outMpegAbs" int,
|
||||
"inDecodingStartFramePosition" int,
|
||||
"outDecodingStartFramePosition" int,
|
||||
"inFileOffsetInBlock" int,
|
||||
"outFileOffsetInBlock" int,
|
||||
"inNumberOfSampleInBlock" int,
|
||||
"outNumberOfSampleInBlock" int
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "recommendedLike" (
|
||||
"content_id_1" int not null,
|
||||
"content_id_2" int not null,
|
||||
"rating" int,
|
||||
"createdDate" datetime
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "myTag" (
|
||||
"myTag_id" integer primary key not null,
|
||||
"sequenceNo" int,
|
||||
"name" varchar,
|
||||
"attribute" int,
|
||||
"myTag_id_parent" int
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "myTag_content" (
|
||||
"myTag_id" int not null,
|
||||
"content_id" int not null
|
||||
);
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
# `master.db` schema
|
||||
|
||||
`schema.sql` is the DDL of a real Rekordbox 7 library — 47 tables and 288
|
||||
indexes — used by the Rekordbox **exporter** to create a database from nothing.
|
||||
|
||||
**It contains no user data.** Table and index definitions only, extracted with
|
||||
`SELECT sql FROM sqlite_master`.
|
||||
|
||||
## Why this, and not pyrekordbox's models
|
||||
|
||||
`Base.metadata.create_all()` looked like the obvious way to build the schema, and
|
||||
it is wrong in two ways that matter:
|
||||
|
||||
- it models **37 tables**, not 47;
|
||||
- it marks columns **NOT NULL that Rekordbox leaves nullable**. `agentRegistry
|
||||
.id_1` is the one that caught it: a real library has NULL there, and a database
|
||||
built from the ORM refuses the row Rekordbox itself writes.
|
||||
|
||||
So the DDL is the authority and the models are not. Regenerate with the snippet
|
||||
in the export handoff if a future Rekordbox version changes the schema.
|
||||
@@ -0,0 +1,344 @@
|
||||
-- master.db schema, extracted from a real Rekordbox 7 library.
|
||||
--
|
||||
-- NOT generated from pyrekordbox's SQLAlchemy models: `create_all()` marks
|
||||
-- columns NOT NULL that Rekordbox itself leaves nullable (agentRegistry.id_1
|
||||
-- is the one that caught this), so a database built from the ORM rejects rows
|
||||
-- Rekordbox writes every day. The DDL is the authority; the models are not.
|
||||
--
|
||||
-- Contains no user data — table and index definitions only.
|
||||
|
||||
CREATE TABLE `agentNotification` (`ID` BIGINT PRIMARY KEY, `graphic_area` TINYINT(1) DEFAULT 0, `text_area` TINYINT(1) DEFAULT 0, `os_notification` TINYINT(1) DEFAULT 0, `start_datetime` DATETIME DEFAULT NULL, `end_datetime` DATETIME DEFAULT NULL, `display_datetime` DATETIME DEFAULT NULL, `interval` INTEGER DEFAULT 0, `category` VARCHAR(255) DEFAULT NULL, `category_color` VARCHAR(255) DEFAULT NULL, `title` TEXT DEFAULT NULL, `description` TEXT DEFAULT NULL, `url` VARCHAR(255) DEFAULT NULL, `image` VARCHAR(255) DEFAULT NULL, `image_path` VARCHAR(255) DEFAULT NULL, `read_status` INTEGER DEFAULT 0, `last_displayed_datetime` DATETIME DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `agentNotificationLog` (`ID` INTEGER PRIMARY KEY AUTOINCREMENT, `gigya_uid` VARCHAR(255) DEFAULT NULL, `event_date` INTEGER DEFAULT NULL, `reported_datetime` DATETIME DEFAULT NULL, `kind` INTEGER DEFAULT NULL, `value` INTEGER DEFAULT NULL, `notification_id` BIGINT DEFAULT NULL, `link` VARCHAR(255) DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `agentRegistry` (`registry_id` VARCHAR(255) PRIMARY KEY, `id_1` VARCHAR(255) DEFAULT NULL, `id_2` VARCHAR(255) DEFAULT NULL, `int_1` BIGINT DEFAULT NULL, `int_2` BIGINT DEFAULT NULL, `str_1` VARCHAR(255) DEFAULT NULL, `str_2` VARCHAR(255) DEFAULT NULL, `date_1` DATETIME DEFAULT NULL, `date_2` DATETIME DEFAULT NULL, `text_1` TEXT DEFAULT NULL, `text_2` TEXT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `cloudAgentRegistry` (`ID` VARCHAR(255) PRIMARY KEY, `int_1` BIGINT DEFAULT NULL, `int_2` BIGINT DEFAULT NULL, `str_1` VARCHAR(255) DEFAULT NULL, `str_2` VARCHAR(255) DEFAULT NULL, `date_1` DATETIME DEFAULT NULL, `date_2` DATETIME DEFAULT NULL, `text_1` TEXT DEFAULT NULL, `text_2` TEXT DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `contentActiveCensor` (`ID` VARCHAR(255) PRIMARY KEY, `ContentID` VARCHAR(255) DEFAULT NULL, `ActiveCensors` TEXT DEFAULT NULL, `rb_activecensor_count` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `contentCue` (`ID` VARCHAR(255) PRIMARY KEY, `ContentID` VARCHAR(255) DEFAULT NULL, `Cues` TEXT DEFAULT NULL, `rb_cue_count` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `contentFile` (`ID` VARCHAR(255) PRIMARY KEY, `ContentID` VARCHAR(255) DEFAULT NULL, `Path` VARCHAR(255) DEFAULT NULL, `Hash` VARCHAR(255) DEFAULT NULL, `Size` INTEGER DEFAULT NULL, `rb_local_path` VARCHAR(255) DEFAULT NULL, `rb_insync_hash` VARCHAR(255) DEFAULT NULL, `rb_insync_local_usn` BIGINT DEFAULT NULL, `rb_file_hash_dirty` INTEGER DEFAULT 0, `rb_local_file_status` INTEGER DEFAULT 0, `rb_in_progress` TINYINT(1) DEFAULT 0, `rb_process_type` INTEGER DEFAULT 0, `rb_temp_path` VARCHAR(255) DEFAULT NULL, `rb_priority` INTEGER DEFAULT 50, `rb_file_size_dirty` INTEGER DEFAULT 0, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdActiveCensor` (`ID` VARCHAR(255) PRIMARY KEY, `ContentID` VARCHAR(255) DEFAULT NULL, `InMsec` INTEGER DEFAULT NULL, `OutMsec` INTEGER DEFAULT NULL, `Info` INTEGER DEFAULT NULL, `ParameterList` TEXT DEFAULT NULL, `ContentUUID` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdAlbum` (`ID` VARCHAR(255) PRIMARY KEY, `Name` VARCHAR(255) DEFAULT NULL, `AlbumArtistID` VARCHAR(255) DEFAULT NULL, `ImagePath` VARCHAR(255) DEFAULT NULL, `Compilation` INTEGER DEFAULT NULL, `SearchStr` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdArtist` (`ID` VARCHAR(255) PRIMARY KEY, `Name` VARCHAR(255) DEFAULT NULL, `SearchStr` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdCategory` (`ID` VARCHAR(255) PRIMARY KEY, `MenuItemID` VARCHAR(255) DEFAULT NULL, `Seq` INTEGER DEFAULT NULL, `Disable` INTEGER DEFAULT NULL, `InfoOrder` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdCloudExportPlaylist` (`ID` VARCHAR(255) PRIMARY KEY, `Seq` INTEGER DEFAULT NULL, `Name` VARCHAR(255) DEFAULT NULL, `ImagePath` VARCHAR(255) DEFAULT NULL, `Attribute` INTEGER DEFAULT NULL, `ParentID` VARCHAR(255) DEFAULT NULL, `SmartList` TEXT DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdCloudExportSongPlaylist` (`ID` VARCHAR(255) PRIMARY KEY, `CloudExportPlaylistID` VARCHAR(255) DEFAULT NULL, `ContentID` VARCHAR(255) DEFAULT NULL, `TrackNo` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdCloudFilterPlaylist` (`ID` VARCHAR(255) PRIMARY KEY, `PlaylistUUID` VARCHAR(255) DEFAULT NULL, `Seq` INTEGER DEFAULT 0, `ParentID` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdCloudProperty` (`ID` VARCHAR(255) PRIMARY KEY, `Reserved1` TEXT DEFAULT NULL, `Reserved2` TEXT DEFAULT NULL, `Reserved3` TEXT DEFAULT NULL, `Reserved4` TEXT DEFAULT NULL, `Reserved5` TEXT DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdColor` (`ID` VARCHAR(255) PRIMARY KEY, `ColorCode` INTEGER DEFAULT NULL, `SortKey` INTEGER DEFAULT NULL, `Commnt` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdContent` (`ID` VARCHAR(255) PRIMARY KEY, `FolderPath` VARCHAR(255) DEFAULT NULL, `FileNameL` VARCHAR(255) DEFAULT NULL, `FileNameS` VARCHAR(255) DEFAULT NULL, `Title` VARCHAR(255) DEFAULT NULL, `ArtistID` VARCHAR(255) DEFAULT NULL, `AlbumID` VARCHAR(255) DEFAULT NULL, `GenreID` VARCHAR(255) DEFAULT NULL, `BPM` INTEGER DEFAULT NULL, `Length` INTEGER DEFAULT NULL, `TrackNo` INTEGER DEFAULT NULL, `BitRate` INTEGER DEFAULT NULL, `BitDepth` INTEGER DEFAULT NULL, `Commnt` TEXT DEFAULT NULL, `FileType` INTEGER DEFAULT NULL, `Rating` INTEGER DEFAULT NULL, `ReleaseYear` INTEGER DEFAULT NULL, `RemixerID` VARCHAR(255) DEFAULT NULL, `LabelID` VARCHAR(255) DEFAULT NULL, `OrgArtistID` VARCHAR(255) DEFAULT NULL, `KeyID` VARCHAR(255) DEFAULT NULL, `StockDate` VARCHAR(255) DEFAULT NULL, `ColorID` VARCHAR(255) DEFAULT NULL, `DJPlayCount` INTEGER DEFAULT NULL, `ImagePath` VARCHAR(255) DEFAULT NULL, `MasterDBID` VARCHAR(255) DEFAULT NULL, `MasterSongID` VARCHAR(255) DEFAULT NULL, `AnalysisDataPath` VARCHAR(255) DEFAULT NULL, `SearchStr` VARCHAR(255) DEFAULT NULL, `FileSize` INTEGER DEFAULT NULL, `DiscNo` INTEGER DEFAULT NULL, `ComposerID` VARCHAR(255) DEFAULT NULL, `Subtitle` VARCHAR(255) DEFAULT NULL, `SampleRate` INTEGER DEFAULT NULL, `DisableQuantize` INTEGER DEFAULT NULL, `Analysed` INTEGER DEFAULT NULL, `ReleaseDate` VARCHAR(255) DEFAULT NULL, `DateCreated` VARCHAR(255) DEFAULT NULL, `ContentLink` INTEGER DEFAULT NULL, `Tag` VARCHAR(255) DEFAULT NULL, `ModifiedByRBM` VARCHAR(255) DEFAULT NULL, `HotCueAutoLoad` VARCHAR(255) DEFAULT NULL, `DeliveryControl` VARCHAR(255) DEFAULT NULL, `DeliveryComment` VARCHAR(255) DEFAULT NULL, `CueUpdated` VARCHAR(255) DEFAULT NULL, `AnalysisUpdated` VARCHAR(255) DEFAULT NULL, `TrackInfoUpdated` VARCHAR(255) DEFAULT NULL, `Lyricist` VARCHAR(255) DEFAULT NULL, `ISRC` VARCHAR(255) DEFAULT NULL, `SamplerTrackInfo` INTEGER DEFAULT NULL, `SamplerPlayOffset` INTEGER DEFAULT NULL, `SamplerGain` FLOAT DEFAULT NULL, `VideoAssociate` VARCHAR(255) DEFAULT NULL, `LyricStatus` INTEGER DEFAULT NULL, `ServiceID` INTEGER DEFAULT NULL, `OrgFolderPath` VARCHAR(255) DEFAULT NULL, `Reserved1` TEXT DEFAULT NULL, `Reserved2` TEXT DEFAULT NULL, `Reserved3` TEXT DEFAULT NULL, `Reserved4` TEXT DEFAULT NULL, `ExtInfo` TEXT DEFAULT NULL, `rb_file_id` VARCHAR(255) DEFAULT NULL, `DeviceID` VARCHAR(255) DEFAULT NULL, `rb_LocalFolderPath` VARCHAR(255) DEFAULT NULL, `SrcID` VARCHAR(255) DEFAULT NULL, `SrcTitle` VARCHAR(255) DEFAULT NULL, `SrcArtistName` VARCHAR(255) DEFAULT NULL, `SrcAlbumName` VARCHAR(255) DEFAULT NULL, `SrcLength` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdCue` (`ID` VARCHAR(255) PRIMARY KEY, `ContentID` VARCHAR(255) DEFAULT NULL, `InMsec` INTEGER DEFAULT NULL, `InFrame` INTEGER DEFAULT NULL, `InMpegFrame` INTEGER DEFAULT NULL, `InMpegAbs` INTEGER DEFAULT NULL, `OutMsec` INTEGER DEFAULT NULL, `OutFrame` INTEGER DEFAULT NULL, `OutMpegFrame` INTEGER DEFAULT NULL, `OutMpegAbs` INTEGER DEFAULT NULL, `Kind` INTEGER DEFAULT NULL, `Color` INTEGER DEFAULT NULL, `ColorTableIndex` INTEGER DEFAULT NULL, `ActiveLoop` INTEGER DEFAULT NULL, `Comment` VARCHAR(255) DEFAULT NULL, `BeatLoopSize` INTEGER DEFAULT NULL, `CueMicrosec` INTEGER DEFAULT NULL, `InPointSeekInfo` VARCHAR(255) DEFAULT NULL, `OutPointSeekInfo` VARCHAR(255) DEFAULT NULL, `ContentUUID` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdDevice` (`ID` VARCHAR(255) PRIMARY KEY, `MasterDBID` VARCHAR(255) DEFAULT NULL, `Name` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdGenre` (`ID` VARCHAR(255) PRIMARY KEY, `Name` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdHistory` (`ID` VARCHAR(255) PRIMARY KEY, `Seq` INTEGER DEFAULT NULL, `Name` VARCHAR(255) DEFAULT NULL, `Attribute` INTEGER DEFAULT NULL, `ParentID` VARCHAR(255) DEFAULT NULL, `DateCreated` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdHotCueBanklist` (`ID` VARCHAR(255) PRIMARY KEY, `Seq` INTEGER DEFAULT NULL, `Name` VARCHAR(255) DEFAULT NULL, `ImagePath` VARCHAR(255) DEFAULT NULL, `Attribute` INTEGER DEFAULT NULL, `ParentID` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdKey` (`ID` VARCHAR(255) PRIMARY KEY, `ScaleName` VARCHAR(255) DEFAULT NULL, `Seq` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdLabel` (`ID` VARCHAR(255) PRIMARY KEY, `Name` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdMenuItems` (`ID` VARCHAR(255) PRIMARY KEY, `Class` INTEGER DEFAULT NULL, `Name` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdMixerParam` (`ID` VARCHAR(255) PRIMARY KEY, `ContentID` VARCHAR(255) DEFAULT NULL, `GainHigh` INTEGER DEFAULT NULL, `GainLow` INTEGER DEFAULT NULL, `PeakHigh` INTEGER DEFAULT NULL, `PeakLow` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdMyTag` (`ID` VARCHAR(255) PRIMARY KEY, `Seq` INTEGER DEFAULT NULL, `Name` VARCHAR(255) DEFAULT NULL, `Attribute` INTEGER DEFAULT NULL, `ParentID` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdPlaylist` (`ID` VARCHAR(255) PRIMARY KEY, `Seq` INTEGER DEFAULT NULL, `Name` VARCHAR(255) DEFAULT NULL, `ImagePath` VARCHAR(255) DEFAULT NULL, `Attribute` INTEGER DEFAULT NULL, `ParentID` VARCHAR(255) DEFAULT NULL, `SmartList` TEXT DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdProperty` (`DBID` VARCHAR(255) PRIMARY KEY, `DBVersion` VARCHAR(255) DEFAULT NULL, `BaseDBDrive` VARCHAR(255) DEFAULT NULL, `CurrentDBDrive` VARCHAR(255) DEFAULT NULL, `DeviceID` VARCHAR(255) DEFAULT NULL, `Reserved1` TEXT DEFAULT NULL, `Reserved2` TEXT DEFAULT NULL, `Reserved3` TEXT DEFAULT NULL, `Reserved4` TEXT DEFAULT NULL, `Reserved5` TEXT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdRecommendLike` (`ID` VARCHAR(255) PRIMARY KEY, `ContentID1` VARCHAR(255) DEFAULT NULL, `ContentID2` VARCHAR(255) DEFAULT NULL, `LikeRate` INTEGER DEFAULT NULL, `DataCreatedH` INTEGER DEFAULT NULL, `DataCreatedL` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdRelatedTracks` (`ID` VARCHAR(255) PRIMARY KEY, `Seq` INTEGER DEFAULT NULL, `Name` VARCHAR(255) DEFAULT NULL, `Attribute` INTEGER DEFAULT NULL, `ParentID` VARCHAR(255) DEFAULT NULL, `Criteria` TEXT DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdSampler` (`ID` VARCHAR(255) PRIMARY KEY, `Seq` INTEGER DEFAULT NULL, `Name` VARCHAR(255) DEFAULT NULL, `Attribute` INTEGER DEFAULT NULL, `ParentID` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdSharedPlaylist` (`ID` VARCHAR(255) PRIMARY KEY, `data_selection` TINYINT DEFAULT 0, `edited_at` DATETIME DEFAULT NULL, `int_1` INTEGER DEFAULT NULL, `int_2` INTEGER DEFAULT NULL, `str_1` VARCHAR(255) DEFAULT NULL, `str_2` VARCHAR(255) DEFAULT NULL, `text_1` TEXT DEFAULT NULL, `text_2` TEXT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdSharedPlaylistUser` (`ID` VARCHAR(255) NOT NULL, `member_type` TINYINT DEFAULT 0, `member_id` VARCHAR(255) NOT NULL, `status` TINYINT DEFAULT 0, `invitation_expires_at` DATETIME DEFAULT NULL, `invited_at` DATETIME DEFAULT NULL, `joined_at` DATETIME DEFAULT NULL, `int_1` INTEGER DEFAULT NULL, `int_2` INTEGER DEFAULT NULL, `str_1` VARCHAR(255) DEFAULT NULL, `str_2` VARCHAR(255) DEFAULT NULL, `text_1` TEXT DEFAULT NULL, `text_2` TEXT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL, PRIMARY KEY (`ID`, `member_id`));
|
||||
CREATE TABLE `djmdSongHistory` (`ID` VARCHAR(255) PRIMARY KEY, `HistoryID` VARCHAR(255) DEFAULT NULL, `ContentID` VARCHAR(255) DEFAULT NULL, `TrackNo` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdSongHotCueBanklist` (`ID` VARCHAR(255) PRIMARY KEY, `HotCueBanklistID` VARCHAR(255) DEFAULT NULL, `ContentID` VARCHAR(255) DEFAULT NULL, `TrackNo` INTEGER DEFAULT NULL, `CueID` VARCHAR(255) DEFAULT NULL, `InMsec` INTEGER DEFAULT NULL, `InFrame` INTEGER DEFAULT NULL, `InMpegFrame` INTEGER DEFAULT NULL, `InMpegAbs` INTEGER DEFAULT NULL, `OutMsec` INTEGER DEFAULT NULL, `OutFrame` INTEGER DEFAULT NULL, `OutMpegFrame` INTEGER DEFAULT NULL, `OutMpegAbs` INTEGER DEFAULT NULL, `Color` INTEGER DEFAULT NULL, `ColorTableIndex` INTEGER DEFAULT NULL, `ActiveLoop` INTEGER DEFAULT NULL, `Comment` VARCHAR(255) DEFAULT NULL, `BeatLoopSize` INTEGER DEFAULT NULL, `CueMicrosec` INTEGER DEFAULT NULL, `InPointSeekInfo` VARCHAR(255) DEFAULT NULL, `OutPointSeekInfo` VARCHAR(255) DEFAULT NULL, `HotCueBanklistUUID` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdSongMyTag` (`ID` VARCHAR(255) PRIMARY KEY, `MyTagID` VARCHAR(255) DEFAULT NULL, `ContentID` VARCHAR(255) DEFAULT NULL, `TrackNo` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdSongPlaylist` (`ID` VARCHAR(255) PRIMARY KEY, `PlaylistID` VARCHAR(255) DEFAULT NULL, `ContentID` VARCHAR(255) DEFAULT NULL, `TrackNo` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdSongRelatedTracks` (`ID` VARCHAR(255) PRIMARY KEY, `RelatedTracksID` VARCHAR(255) DEFAULT NULL, `ContentID` VARCHAR(255) DEFAULT NULL, `TrackNo` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdSongRequestList` (`ID` VARCHAR(255) PRIMARY KEY, `ContentID` VARCHAR(255) DEFAULT NULL, `TrackNo` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdSongSampler` (`ID` VARCHAR(255) PRIMARY KEY, `SamplerID` VARCHAR(255) DEFAULT NULL, `ContentID` VARCHAR(255) DEFAULT NULL, `TrackNo` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdSongTagList` (`ID` VARCHAR(255) PRIMARY KEY, `ContentID` VARCHAR(255) DEFAULT NULL, `TrackNo` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdSort` (`ID` VARCHAR(255) PRIMARY KEY, `MenuItemID` VARCHAR(255) DEFAULT NULL, `Seq` INTEGER DEFAULT NULL, `Disable` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `hotCueBanklistCue` (`ID` VARCHAR(255) PRIMARY KEY, `HotCueBanklistID` VARCHAR(255) DEFAULT NULL, `Cues` TEXT DEFAULT NULL, `rb_cue_count` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `imageFile` (`ID` VARCHAR(255) PRIMARY KEY, `TableName` VARCHAR(255) DEFAULT NULL, `TargetUUID` VARCHAR(255) DEFAULT NULL, `TargetID` VARCHAR(255) DEFAULT NULL, `Path` VARCHAR(255) DEFAULT NULL, `Hash` VARCHAR(255) DEFAULT NULL, `Size` INTEGER DEFAULT NULL, `rb_local_path` VARCHAR(255) DEFAULT NULL, `rb_insync_hash` VARCHAR(255) DEFAULT NULL, `rb_insync_local_usn` BIGINT DEFAULT NULL, `rb_file_hash_dirty` INTEGER DEFAULT 0, `rb_local_file_status` INTEGER DEFAULT 0, `rb_in_progress` TINYINT(1) DEFAULT 0, `rb_process_type` INTEGER DEFAULT 0, `rb_temp_path` VARCHAR(255) DEFAULT NULL, `rb_priority` INTEGER DEFAULT 50, `rb_file_size_dirty` INTEGER DEFAULT 0, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `settingFile` (`ID` VARCHAR(255) PRIMARY KEY, `Path` VARCHAR(255) DEFAULT NULL, `Hash` VARCHAR(255) DEFAULT NULL, `Size` INTEGER DEFAULT NULL, `rb_local_path` VARCHAR(255) DEFAULT NULL, `rb_insync_hash` VARCHAR(255) DEFAULT NULL, `rb_insync_local_usn` BIGINT DEFAULT NULL, `rb_file_hash_dirty` INTEGER DEFAULT 0, `rb_file_size_dirty` INTEGER DEFAULT 0, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `uuidIDMap` (`ID` VARCHAR(255) PRIMARY KEY, `TableName` VARCHAR(255) DEFAULT NULL, `TargetUUID` VARCHAR(255) DEFAULT NULL, `CurrentID` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE INDEX `agent_notification_log_gigya_uid_event_date_kind_notification_id` ON `agentNotificationLog` (`gigya_uid`, `event_date`, `kind`, `notification_id`);
|
||||
CREATE INDEX `agent_notification_log_reported_datetime_event_date` ON `agentNotificationLog` (`reported_datetime`, `event_date`);
|
||||
CREATE INDEX `agent_notification_start_datetime_end_datetime` ON `agentNotification` (`start_datetime`, `end_datetime`);
|
||||
CREATE INDEX `agent_registry_id_1_id_2` ON `agentRegistry` (`id_1`, `id_2`);
|
||||
CREATE INDEX `cloud_agent_registry__u_u_i_d` ON `cloudAgentRegistry` (`UUID`);
|
||||
CREATE INDEX `cloud_agent_registry_rb_data_status` ON `cloudAgentRegistry` (`rb_data_status`);
|
||||
CREATE INDEX `cloud_agent_registry_rb_local_data_status` ON `cloudAgentRegistry` (`rb_local_data_status`);
|
||||
CREATE INDEX `cloud_agent_registry_rb_local_deleted` ON `cloudAgentRegistry` (`rb_local_deleted`);
|
||||
CREATE INDEX `cloud_agent_registry_rb_local_usn__i_d` ON `cloudAgentRegistry` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `content_active_censor__content_i_d` ON `contentActiveCensor` (`ContentID`);
|
||||
CREATE INDEX `content_active_censor__u_u_i_d` ON `contentActiveCensor` (`UUID`);
|
||||
CREATE INDEX `content_active_censor_rb_data_status` ON `contentActiveCensor` (`rb_data_status`);
|
||||
CREATE INDEX `content_active_censor_rb_local_data_status` ON `contentActiveCensor` (`rb_local_data_status`);
|
||||
CREATE INDEX `content_active_censor_rb_local_deleted` ON `contentActiveCensor` (`rb_local_deleted`);
|
||||
CREATE INDEX `content_active_censor_rb_local_usn__i_d` ON `contentActiveCensor` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `content_cue__content_i_d` ON `contentCue` (`ContentID`);
|
||||
CREATE INDEX `content_cue__u_u_i_d` ON `contentCue` (`UUID`);
|
||||
CREATE INDEX `content_cue_rb_cue_count` ON `contentCue` (`rb_cue_count`);
|
||||
CREATE INDEX `content_cue_rb_data_status` ON `contentCue` (`rb_data_status`);
|
||||
CREATE INDEX `content_cue_rb_local_data_status` ON `contentCue` (`rb_local_data_status`);
|
||||
CREATE INDEX `content_cue_rb_local_deleted` ON `contentCue` (`rb_local_deleted`);
|
||||
CREATE INDEX `content_cue_rb_local_usn__i_d` ON `contentCue` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `content_file__content_i_d` ON `contentFile` (`ContentID`);
|
||||
CREATE INDEX `content_file__u_u_i_d` ON `contentFile` (`UUID`);
|
||||
CREATE INDEX `content_file_rb_data_status` ON `contentFile` (`rb_data_status`);
|
||||
CREATE INDEX `content_file_rb_file_hash_dirty` ON `contentFile` (`rb_file_hash_dirty`);
|
||||
CREATE INDEX `content_file_rb_file_size_dirty` ON `contentFile` (`rb_file_size_dirty`);
|
||||
CREATE INDEX `content_file_rb_local_data_status` ON `contentFile` (`rb_local_data_status`);
|
||||
CREATE INDEX `content_file_rb_local_deleted` ON `contentFile` (`rb_local_deleted`);
|
||||
CREATE INDEX `content_file_rb_local_deleted_rb_in_progress_rb_local_file_status_rb_process_type_rb_priority` ON `contentFile` (`rb_local_deleted`, `rb_in_progress`, `rb_local_file_status`, `rb_process_type`, `rb_priority`);
|
||||
CREATE INDEX `content_file_rb_local_usn__i_d` ON `contentFile` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_active_censor__content_i_d` ON `djmdActiveCensor` (`ContentID`);
|
||||
CREATE INDEX `djmd_active_censor__content_u_u_i_d` ON `djmdActiveCensor` (`ContentUUID`);
|
||||
CREATE INDEX `djmd_active_censor__u_u_i_d` ON `djmdActiveCensor` (`UUID`);
|
||||
CREATE INDEX `djmd_active_censor_rb_data_status` ON `djmdActiveCensor` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_active_censor_rb_local_data_status` ON `djmdActiveCensor` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_active_censor_rb_local_deleted` ON `djmdActiveCensor` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_active_censor_rb_local_usn__i_d` ON `djmdActiveCensor` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_album__album_artist_i_d` ON `djmdAlbum` (`AlbumArtistID`);
|
||||
CREATE INDEX `djmd_album__name` ON `djmdAlbum` (`Name`);
|
||||
CREATE INDEX `djmd_album__u_u_i_d` ON `djmdAlbum` (`UUID`);
|
||||
CREATE INDEX `djmd_album_rb_data_status` ON `djmdAlbum` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_album_rb_local_data_status` ON `djmdAlbum` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_album_rb_local_deleted` ON `djmdAlbum` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_album_rb_local_usn__i_d` ON `djmdAlbum` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_artist__name` ON `djmdArtist` (`Name`);
|
||||
CREATE INDEX `djmd_artist__u_u_i_d` ON `djmdArtist` (`UUID`);
|
||||
CREATE INDEX `djmd_artist_rb_data_status` ON `djmdArtist` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_artist_rb_local_data_status` ON `djmdArtist` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_artist_rb_local_deleted` ON `djmdArtist` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_artist_rb_local_usn__i_d` ON `djmdArtist` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_category__u_u_i_d` ON `djmdCategory` (`UUID`);
|
||||
CREATE INDEX `djmd_category_rb_data_status` ON `djmdCategory` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_category_rb_local_data_status` ON `djmdCategory` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_category_rb_local_deleted` ON `djmdCategory` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_category_rb_local_usn__i_d` ON `djmdCategory` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_cloud_export_playlist__attribute` ON `djmdCloudExportPlaylist` (`Attribute`);
|
||||
CREATE INDEX `djmd_cloud_export_playlist__name` ON `djmdCloudExportPlaylist` (`Name`);
|
||||
CREATE INDEX `djmd_cloud_export_playlist__parent_i_d` ON `djmdCloudExportPlaylist` (`ParentID`);
|
||||
CREATE INDEX `djmd_cloud_export_playlist__seq` ON `djmdCloudExportPlaylist` (`Seq`);
|
||||
CREATE INDEX `djmd_cloud_export_playlist__u_u_i_d` ON `djmdCloudExportPlaylist` (`UUID`);
|
||||
CREATE INDEX `djmd_cloud_export_playlist_rb_data_status` ON `djmdCloudExportPlaylist` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_cloud_export_playlist_rb_local_data_status` ON `djmdCloudExportPlaylist` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_cloud_export_playlist_rb_local_deleted` ON `djmdCloudExportPlaylist` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_cloud_export_playlist_rb_local_usn__i_d` ON `djmdCloudExportPlaylist` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_cloud_export_song_playlist__cloud_export_playlist_i_d__i_d` ON `djmdCloudExportSongPlaylist` (`CloudExportPlaylistID`, `ID`);
|
||||
CREATE INDEX `djmd_cloud_export_song_playlist__content_i_d_rb_local_deleted` ON `djmdCloudExportSongPlaylist` (`ContentID`, `rb_local_deleted`);
|
||||
CREATE INDEX `djmd_cloud_export_song_playlist__u_u_i_d` ON `djmdCloudExportSongPlaylist` (`UUID`);
|
||||
CREATE INDEX `djmd_cloud_export_song_playlist_rb_data_status` ON `djmdCloudExportSongPlaylist` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_cloud_export_song_playlist_rb_local_data_status` ON `djmdCloudExportSongPlaylist` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_cloud_export_song_playlist_rb_local_deleted` ON `djmdCloudExportSongPlaylist` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_cloud_export_song_playlist_rb_local_usn__i_d` ON `djmdCloudExportSongPlaylist` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_cloud_filter_playlist__u_u_i_d` ON `djmdCloudFilterPlaylist` (`UUID`);
|
||||
CREATE INDEX `djmd_cloud_filter_playlist_rb_data_status` ON `djmdCloudFilterPlaylist` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_cloud_filter_playlist_rb_local_data_status` ON `djmdCloudFilterPlaylist` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_cloud_filter_playlist_rb_local_deleted` ON `djmdCloudFilterPlaylist` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_cloud_filter_playlist_rb_local_usn__i_d` ON `djmdCloudFilterPlaylist` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_cloud_property__u_u_i_d` ON `djmdCloudProperty` (`UUID`);
|
||||
CREATE INDEX `djmd_cloud_property_rb_data_status` ON `djmdCloudProperty` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_cloud_property_rb_local_data_status` ON `djmdCloudProperty` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_cloud_property_rb_local_deleted` ON `djmdCloudProperty` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_cloud_property_rb_local_usn__i_d` ON `djmdCloudProperty` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_color__u_u_i_d` ON `djmdColor` (`UUID`);
|
||||
CREATE INDEX `djmd_color_rb_data_status` ON `djmdColor` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_color_rb_local_data_status` ON `djmdColor` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_color_rb_local_deleted` ON `djmdColor` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_color_rb_local_usn__i_d` ON `djmdColor` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_content__album_i_d` ON `djmdContent` (`AlbumID`);
|
||||
CREATE INDEX `djmd_content__artist_i_d` ON `djmdContent` (`ArtistID`);
|
||||
CREATE INDEX `djmd_content__composer_i_d` ON `djmdContent` (`ComposerID`);
|
||||
CREATE INDEX `djmd_content__genre_i_d` ON `djmdContent` (`GenreID`);
|
||||
CREATE INDEX `djmd_content__key_i_d` ON `djmdContent` (`KeyID`);
|
||||
CREATE INDEX `djmd_content__label_i_d` ON `djmdContent` (`LabelID`);
|
||||
CREATE INDEX `djmd_content__master_d_b_i_d__master_song_i_d` ON `djmdContent` (`MasterDBID`, `MasterSongID`);
|
||||
CREATE INDEX `djmd_content__org_artist_i_d` ON `djmdContent` (`OrgArtistID`);
|
||||
CREATE INDEX `djmd_content__remixer_i_d` ON `djmdContent` (`RemixerID`);
|
||||
CREATE INDEX `djmd_content__u_u_i_d` ON `djmdContent` (`UUID`);
|
||||
CREATE INDEX `djmd_content_rb_data_status` ON `djmdContent` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_content_rb_local_data_status` ON `djmdContent` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_content_rb_local_deleted` ON `djmdContent` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_content_rb_local_deleted__bit_depth` ON `djmdContent` (`rb_local_deleted`, `BitDepth`);
|
||||
CREATE INDEX `djmd_content_rb_local_deleted__bit_rate` ON `djmdContent` (`rb_local_deleted`, `BitRate`);
|
||||
CREATE INDEX `djmd_content_rb_local_deleted__file_type` ON `djmdContent` (`rb_local_deleted`, `FileType`);
|
||||
CREATE INDEX `djmd_content_rb_local_deleted__service_i_d` ON `djmdContent` (`rb_local_deleted`, `ServiceID`);
|
||||
CREATE INDEX `djmd_content_rb_local_usn__i_d` ON `djmdContent` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_cue__content_i_d_rb_local_deleted` ON `djmdCue` (`ContentID`, `rb_local_deleted`);
|
||||
CREATE INDEX `djmd_cue__content_u_u_i_d` ON `djmdCue` (`ContentUUID`);
|
||||
CREATE INDEX `djmd_cue__u_u_i_d` ON `djmdCue` (`UUID`);
|
||||
CREATE INDEX `djmd_cue_rb_data_status` ON `djmdCue` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_cue_rb_local_data_status` ON `djmdCue` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_cue_rb_local_deleted` ON `djmdCue` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_cue_rb_local_usn__i_d` ON `djmdCue` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_device__u_u_i_d` ON `djmdDevice` (`UUID`);
|
||||
CREATE INDEX `djmd_device_rb_data_status` ON `djmdDevice` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_device_rb_local_data_status` ON `djmdDevice` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_device_rb_local_deleted` ON `djmdDevice` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_device_rb_local_usn__i_d` ON `djmdDevice` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_genre__name` ON `djmdGenre` (`Name`);
|
||||
CREATE INDEX `djmd_genre__u_u_i_d` ON `djmdGenre` (`UUID`);
|
||||
CREATE INDEX `djmd_genre_rb_data_status` ON `djmdGenre` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_genre_rb_local_data_status` ON `djmdGenre` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_genre_rb_local_deleted` ON `djmdGenre` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_genre_rb_local_usn__i_d` ON `djmdGenre` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_history__name` ON `djmdHistory` (`Name`);
|
||||
CREATE INDEX `djmd_history__parent_i_d` ON `djmdHistory` (`ParentID`);
|
||||
CREATE INDEX `djmd_history__u_u_i_d` ON `djmdHistory` (`UUID`);
|
||||
CREATE INDEX `djmd_history_rb_data_status` ON `djmdHistory` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_history_rb_local_data_status` ON `djmdHistory` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_history_rb_local_deleted` ON `djmdHistory` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_history_rb_local_usn__i_d` ON `djmdHistory` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_hot_cue_banklist__name` ON `djmdHotCueBanklist` (`Name`);
|
||||
CREATE INDEX `djmd_hot_cue_banklist__parent_i_d` ON `djmdHotCueBanklist` (`ParentID`);
|
||||
CREATE INDEX `djmd_hot_cue_banklist__u_u_i_d` ON `djmdHotCueBanklist` (`UUID`);
|
||||
CREATE INDEX `djmd_hot_cue_banklist_rb_data_status` ON `djmdHotCueBanklist` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_hot_cue_banklist_rb_local_data_status` ON `djmdHotCueBanklist` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_hot_cue_banklist_rb_local_deleted` ON `djmdHotCueBanklist` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_hot_cue_banklist_rb_local_usn__i_d` ON `djmdHotCueBanklist` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_key__scale_name` ON `djmdKey` (`ScaleName`);
|
||||
CREATE INDEX `djmd_key__u_u_i_d` ON `djmdKey` (`UUID`);
|
||||
CREATE INDEX `djmd_key_rb_data_status` ON `djmdKey` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_key_rb_local_data_status` ON `djmdKey` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_key_rb_local_deleted` ON `djmdKey` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_key_rb_local_usn__i_d` ON `djmdKey` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_label__name` ON `djmdLabel` (`Name`);
|
||||
CREATE INDEX `djmd_label__u_u_i_d` ON `djmdLabel` (`UUID`);
|
||||
CREATE INDEX `djmd_label_rb_data_status` ON `djmdLabel` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_label_rb_local_data_status` ON `djmdLabel` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_label_rb_local_deleted` ON `djmdLabel` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_label_rb_local_usn__i_d` ON `djmdLabel` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_menu_items__u_u_i_d` ON `djmdMenuItems` (`UUID`);
|
||||
CREATE INDEX `djmd_menu_items_rb_data_status` ON `djmdMenuItems` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_menu_items_rb_local_data_status` ON `djmdMenuItems` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_menu_items_rb_local_deleted` ON `djmdMenuItems` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_menu_items_rb_local_usn__i_d` ON `djmdMenuItems` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_mixer_param__content_i_d_rb_local_deleted` ON `djmdMixerParam` (`ContentID`, `rb_local_deleted`);
|
||||
CREATE INDEX `djmd_mixer_param__u_u_i_d` ON `djmdMixerParam` (`UUID`);
|
||||
CREATE INDEX `djmd_mixer_param_rb_data_status` ON `djmdMixerParam` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_mixer_param_rb_local_data_status` ON `djmdMixerParam` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_mixer_param_rb_local_deleted` ON `djmdMixerParam` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_mixer_param_rb_local_usn__i_d` ON `djmdMixerParam` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_my_tag__parent_i_d` ON `djmdMyTag` (`ParentID`);
|
||||
CREATE INDEX `djmd_my_tag__seq` ON `djmdMyTag` (`Seq`);
|
||||
CREATE INDEX `djmd_my_tag__u_u_i_d` ON `djmdMyTag` (`UUID`);
|
||||
CREATE INDEX `djmd_my_tag_rb_data_status` ON `djmdMyTag` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_my_tag_rb_local_data_status` ON `djmdMyTag` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_my_tag_rb_local_deleted` ON `djmdMyTag` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_my_tag_rb_local_usn__i_d` ON `djmdMyTag` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_playlist__attribute` ON `djmdPlaylist` (`Attribute`);
|
||||
CREATE INDEX `djmd_playlist__name` ON `djmdPlaylist` (`Name`);
|
||||
CREATE INDEX `djmd_playlist__parent_i_d` ON `djmdPlaylist` (`ParentID`);
|
||||
CREATE INDEX `djmd_playlist__seq` ON `djmdPlaylist` (`Seq`);
|
||||
CREATE INDEX `djmd_playlist__u_u_i_d` ON `djmdPlaylist` (`UUID`);
|
||||
CREATE INDEX `djmd_playlist_rb_data_status` ON `djmdPlaylist` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_playlist_rb_local_data_status` ON `djmdPlaylist` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_playlist_rb_local_deleted` ON `djmdPlaylist` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_playlist_rb_local_usn__i_d` ON `djmdPlaylist` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_recommend_like__content_i_d1__content_i_d2` ON `djmdRecommendLike` (`ContentID1`, `ContentID2`);
|
||||
CREATE INDEX `djmd_recommend_like__content_i_d2` ON `djmdRecommendLike` (`ContentID2`);
|
||||
CREATE INDEX `djmd_recommend_like__u_u_i_d` ON `djmdRecommendLike` (`UUID`);
|
||||
CREATE INDEX `djmd_recommend_like_rb_data_status` ON `djmdRecommendLike` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_recommend_like_rb_local_data_status` ON `djmdRecommendLike` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_recommend_like_rb_local_deleted` ON `djmdRecommendLike` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_recommend_like_rb_local_usn__i_d` ON `djmdRecommendLike` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_related_tracks__name` ON `djmdRelatedTracks` (`Name`);
|
||||
CREATE INDEX `djmd_related_tracks__parent_i_d` ON `djmdRelatedTracks` (`ParentID`);
|
||||
CREATE INDEX `djmd_related_tracks__seq` ON `djmdRelatedTracks` (`Seq`);
|
||||
CREATE INDEX `djmd_related_tracks__u_u_i_d` ON `djmdRelatedTracks` (`UUID`);
|
||||
CREATE INDEX `djmd_related_tracks_rb_data_status` ON `djmdRelatedTracks` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_related_tracks_rb_local_data_status` ON `djmdRelatedTracks` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_related_tracks_rb_local_deleted` ON `djmdRelatedTracks` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_related_tracks_rb_local_usn__i_d` ON `djmdRelatedTracks` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_sampler__name` ON `djmdSampler` (`Name`);
|
||||
CREATE INDEX `djmd_sampler__parent_i_d` ON `djmdSampler` (`ParentID`);
|
||||
CREATE INDEX `djmd_sampler__seq` ON `djmdSampler` (`Seq`);
|
||||
CREATE INDEX `djmd_sampler__u_u_i_d` ON `djmdSampler` (`UUID`);
|
||||
CREATE INDEX `djmd_sampler_rb_data_status` ON `djmdSampler` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_sampler_rb_local_data_status` ON `djmdSampler` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_sampler_rb_local_deleted` ON `djmdSampler` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_sampler_rb_local_usn__i_d` ON `djmdSampler` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_song_history__content_i_d_rb_local_deleted` ON `djmdSongHistory` (`ContentID`, `rb_local_deleted`);
|
||||
CREATE INDEX `djmd_song_history__history_i_d` ON `djmdSongHistory` (`HistoryID`);
|
||||
CREATE INDEX `djmd_song_history__u_u_i_d` ON `djmdSongHistory` (`UUID`);
|
||||
CREATE INDEX `djmd_song_history_rb_data_status` ON `djmdSongHistory` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_song_history_rb_local_data_status` ON `djmdSongHistory` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_song_history_rb_local_deleted` ON `djmdSongHistory` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_song_history_rb_local_usn__i_d` ON `djmdSongHistory` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_song_hot_cue_banklist__content_i_d` ON `djmdSongHotCueBanklist` (`ContentID`);
|
||||
CREATE INDEX `djmd_song_hot_cue_banklist__hot_cue_banklist_i_d` ON `djmdSongHotCueBanklist` (`HotCueBanklistID`);
|
||||
CREATE INDEX `djmd_song_hot_cue_banklist__hot_cue_banklist_u_u_i_d` ON `djmdSongHotCueBanklist` (`HotCueBanklistUUID`);
|
||||
CREATE INDEX `djmd_song_hot_cue_banklist__u_u_i_d` ON `djmdSongHotCueBanklist` (`UUID`);
|
||||
CREATE INDEX `djmd_song_hot_cue_banklist_rb_data_status` ON `djmdSongHotCueBanklist` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_song_hot_cue_banklist_rb_local_data_status` ON `djmdSongHotCueBanklist` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_song_hot_cue_banklist_rb_local_deleted` ON `djmdSongHotCueBanklist` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_song_hot_cue_banklist_rb_local_usn__i_d` ON `djmdSongHotCueBanklist` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_song_my_tag__content_i_d_rb_local_deleted` ON `djmdSongMyTag` (`ContentID`, `rb_local_deleted`);
|
||||
CREATE INDEX `djmd_song_my_tag__my_tag_i_d_rb_local_deleted__i_d` ON `djmdSongMyTag` (`MyTagID`, `rb_local_deleted`, `ID`);
|
||||
CREATE INDEX `djmd_song_my_tag__u_u_i_d` ON `djmdSongMyTag` (`UUID`);
|
||||
CREATE INDEX `djmd_song_my_tag_rb_data_status` ON `djmdSongMyTag` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_song_my_tag_rb_local_data_status` ON `djmdSongMyTag` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_song_my_tag_rb_local_deleted` ON `djmdSongMyTag` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_song_my_tag_rb_local_usn__i_d` ON `djmdSongMyTag` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_song_playlist__content_i_d_rb_local_deleted` ON `djmdSongPlaylist` (`ContentID`, `rb_local_deleted`);
|
||||
CREATE INDEX `djmd_song_playlist__playlist_i_d__i_d` ON `djmdSongPlaylist` (`PlaylistID`, `ID`);
|
||||
CREATE INDEX `djmd_song_playlist__u_u_i_d` ON `djmdSongPlaylist` (`UUID`);
|
||||
CREATE INDEX `djmd_song_playlist_rb_data_status` ON `djmdSongPlaylist` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_song_playlist_rb_local_data_status` ON `djmdSongPlaylist` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_song_playlist_rb_local_deleted` ON `djmdSongPlaylist` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_song_playlist_rb_local_usn__i_d` ON `djmdSongPlaylist` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_song_related_tracks__content_i_d` ON `djmdSongRelatedTracks` (`ContentID`);
|
||||
CREATE INDEX `djmd_song_related_tracks__related_tracks_i_d` ON `djmdSongRelatedTracks` (`RelatedTracksID`);
|
||||
CREATE INDEX `djmd_song_related_tracks__u_u_i_d` ON `djmdSongRelatedTracks` (`UUID`);
|
||||
CREATE INDEX `djmd_song_related_tracks_rb_data_status` ON `djmdSongRelatedTracks` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_song_related_tracks_rb_local_data_status` ON `djmdSongRelatedTracks` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_song_related_tracks_rb_local_deleted` ON `djmdSongRelatedTracks` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_song_related_tracks_rb_local_usn__i_d` ON `djmdSongRelatedTracks` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_song_request_list__content_i_d` ON `djmdSongRequestList` (`ContentID`);
|
||||
CREATE INDEX `djmd_song_request_list__u_u_i_d` ON `djmdSongRequestList` (`UUID`);
|
||||
CREATE INDEX `djmd_song_request_list_rb_data_status` ON `djmdSongRequestList` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_song_request_list_rb_local_data_status` ON `djmdSongRequestList` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_song_request_list_rb_local_deleted` ON `djmdSongRequestList` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_song_request_list_rb_local_usn__i_d` ON `djmdSongRequestList` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_song_sampler__content_i_d` ON `djmdSongSampler` (`ContentID`);
|
||||
CREATE INDEX `djmd_song_sampler__sampler_i_d` ON `djmdSongSampler` (`SamplerID`);
|
||||
CREATE INDEX `djmd_song_sampler__u_u_i_d` ON `djmdSongSampler` (`UUID`);
|
||||
CREATE INDEX `djmd_song_sampler_rb_data_status` ON `djmdSongSampler` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_song_sampler_rb_local_data_status` ON `djmdSongSampler` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_song_sampler_rb_local_deleted` ON `djmdSongSampler` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_song_sampler_rb_local_usn__i_d` ON `djmdSongSampler` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_song_tag_list__content_i_d` ON `djmdSongTagList` (`ContentID`);
|
||||
CREATE INDEX `djmd_song_tag_list__u_u_i_d` ON `djmdSongTagList` (`UUID`);
|
||||
CREATE INDEX `djmd_song_tag_list_rb_data_status` ON `djmdSongTagList` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_song_tag_list_rb_local_data_status` ON `djmdSongTagList` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_song_tag_list_rb_local_deleted` ON `djmdSongTagList` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_song_tag_list_rb_local_usn__i_d` ON `djmdSongTagList` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_sort__u_u_i_d` ON `djmdSort` (`UUID`);
|
||||
CREATE INDEX `djmd_sort_rb_data_status` ON `djmdSort` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_sort_rb_local_data_status` ON `djmdSort` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_sort_rb_local_deleted` ON `djmdSort` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_sort_rb_local_usn__i_d` ON `djmdSort` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `hot_cue_banklist_cue__hot_cue_banklist_i_d` ON `hotCueBanklistCue` (`HotCueBanklistID`);
|
||||
CREATE INDEX `hot_cue_banklist_cue__u_u_i_d` ON `hotCueBanklistCue` (`UUID`);
|
||||
CREATE INDEX `hot_cue_banklist_cue_rb_cue_count` ON `hotCueBanklistCue` (`rb_cue_count`);
|
||||
CREATE INDEX `hot_cue_banklist_cue_rb_data_status` ON `hotCueBanklistCue` (`rb_data_status`);
|
||||
CREATE INDEX `hot_cue_banklist_cue_rb_local_data_status` ON `hotCueBanklistCue` (`rb_local_data_status`);
|
||||
CREATE INDEX `hot_cue_banklist_cue_rb_local_deleted` ON `hotCueBanklistCue` (`rb_local_deleted`);
|
||||
CREATE INDEX `hot_cue_banklist_cue_rb_local_usn__i_d` ON `hotCueBanklistCue` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `image_file__table_name__target_i_d` ON `imageFile` (`TableName`, `TargetID`);
|
||||
CREATE INDEX `image_file__table_name__target_u_u_i_d__i_d` ON `imageFile` (`TableName`, `TargetUUID`, `ID`);
|
||||
CREATE INDEX `image_file__u_u_i_d` ON `imageFile` (`UUID`);
|
||||
CREATE INDEX `image_file_rb_data_status` ON `imageFile` (`rb_data_status`);
|
||||
CREATE INDEX `image_file_rb_file_hash_dirty` ON `imageFile` (`rb_file_hash_dirty`);
|
||||
CREATE INDEX `image_file_rb_file_size_dirty` ON `imageFile` (`rb_file_size_dirty`);
|
||||
CREATE INDEX `image_file_rb_local_data_status` ON `imageFile` (`rb_local_data_status`);
|
||||
CREATE INDEX `image_file_rb_local_deleted` ON `imageFile` (`rb_local_deleted`);
|
||||
CREATE INDEX `image_file_rb_local_deleted_rb_in_progress_rb_local_file_status_rb_process_type_rb_priority` ON `imageFile` (`rb_local_deleted`, `rb_in_progress`, `rb_local_file_status`, `rb_process_type`, `rb_priority`);
|
||||
CREATE INDEX `image_file_rb_local_usn__i_d` ON `imageFile` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `setting_file__u_u_i_d` ON `settingFile` (`UUID`);
|
||||
CREATE INDEX `setting_file_rb_data_status` ON `settingFile` (`rb_data_status`);
|
||||
CREATE INDEX `setting_file_rb_file_hash_dirty` ON `settingFile` (`rb_file_hash_dirty`);
|
||||
CREATE INDEX `setting_file_rb_file_size_dirty` ON `settingFile` (`rb_file_size_dirty`);
|
||||
CREATE INDEX `setting_file_rb_local_data_status` ON `settingFile` (`rb_local_data_status`);
|
||||
CREATE INDEX `setting_file_rb_local_deleted` ON `settingFile` (`rb_local_deleted`);
|
||||
CREATE INDEX `setting_file_rb_local_usn__i_d` ON `settingFile` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `uuid_i_d_map__u_u_i_d` ON `uuidIDMap` (`UUID`);
|
||||
CREATE INDEX `uuid_i_d_map_rb_data_status` ON `uuidIDMap` (`rb_data_status`);
|
||||
CREATE INDEX `uuid_i_d_map_rb_local_data_status` ON `uuidIDMap` (`rb_local_data_status`);
|
||||
CREATE INDEX `uuid_i_d_map_rb_local_deleted` ON `uuidIDMap` (`rb_local_deleted`);
|
||||
CREATE INDEX `uuid_i_d_map_rb_local_usn__i_d` ON `uuidIDMap` (`rb_local_usn`, `ID`);
|
||||
@@ -0,0 +1,88 @@
|
||||
-- Rekordbox's own scaffolding rows, needed before any track can be added:
|
||||
-- `add_content` looks up djmdMenuItems('TRACK') and fails on an empty table.
|
||||
--
|
||||
-- Static UI data only — menu items, colours, categories, sort options.
|
||||
-- djmdDevice and djmdProperty are DELIBERATELY absent: they carry the
|
||||
-- machine's name and UUIDs, so the exporter generates those fresh instead.
|
||||
|
||||
-- djmdMenuItems: 27 rows
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('1', -128, 'GENRE', '1', 0, 0, 0, 0, NULL, 10, '2026-09-17 20:53:21.658 +00:00', '2026-09-17 20:53:21.658 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('2', -127, 'ARTIST', '2', 0, 0, 0, 0, NULL, 11, '2026-09-17 20:53:21.658 +00:00', '2026-09-17 20:53:21.658 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('3', -126, 'ALBUM', '3', 0, 0, 0, 0, NULL, 12, '2026-09-17 20:53:21.658 +00:00', '2026-09-17 20:53:21.658 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('4', -125, 'TRACK', '4', 0, 0, 0, 0, NULL, 13, '2026-09-17 20:53:21.658 +00:00', '2026-09-17 20:53:21.658 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('5', -123, 'BPM', '5', 0, 0, 0, 0, NULL, 14, '2026-09-17 20:53:21.658 +00:00', '2026-09-17 20:53:21.658 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('6', -122, 'RATING', '6', 0, 0, 0, 0, NULL, 15, '2026-09-17 20:53:21.659 +00:00', '2026-09-17 20:53:21.659 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('7', -121, 'YEAR', '7', 0, 0, 0, 0, NULL, 16, '2026-09-17 20:53:21.659 +00:00', '2026-09-17 20:53:21.659 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('8', -120, 'REMIXER', '8', 0, 0, 0, 0, NULL, 17, '2026-09-17 20:53:21.659 +00:00', '2026-09-17 20:53:21.659 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('9', -119, 'LABEL', '9', 0, 0, 0, 0, NULL, 18, '2026-09-17 20:53:21.659 +00:00', '2026-09-17 20:53:21.659 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('10', -118, 'ORIGINAL ARTIST', '10', 0, 0, 0, 0, NULL, 19, '2026-09-17 20:53:21.659 +00:00', '2026-09-17 20:53:21.659 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('11', -117, 'KEY', '11', 0, 0, 0, 0, NULL, 20, '2026-09-17 20:53:21.659 +00:00', '2026-09-17 20:53:21.659 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('12', -115, 'CUE', '12', 0, 0, 0, 0, NULL, 21, '2026-09-17 20:53:21.659 +00:00', '2026-09-17 20:53:21.659 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('13', -114, 'COLOR', '13', 0, 0, 0, 0, NULL, 22, '2026-09-17 20:53:21.659 +00:00', '2026-09-17 20:53:21.659 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('14', -110, 'TIME', '14', 0, 0, 0, 0, NULL, 23, '2026-09-17 20:53:21.660 +00:00', '2026-09-17 20:53:21.660 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('15', -109, 'BITRATE', '15', 0, 0, 0, 0, NULL, 24, '2026-09-17 20:53:21.660 +00:00', '2026-09-17 20:53:21.660 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('16', -108, 'FILE NAME', '16', 0, 0, 0, 0, NULL, 25, '2026-09-17 20:53:21.660 +00:00', '2026-09-17 20:53:21.660 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('17', -124, 'PLAYLIST', '17', 0, 0, 0, 0, NULL, 26, '2026-09-17 20:53:21.660 +00:00', '2026-09-17 20:53:21.660 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('18', -104, 'HOT CUE BANK', '18', 0, 0, 0, 0, NULL, 27, '2026-09-17 20:53:21.660 +00:00', '2026-09-17 20:53:21.660 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('19', -107, 'HISTORY', '19', 0, 0, 0, 0, NULL, 28, '2026-09-17 20:53:21.660 +00:00', '2026-09-17 20:53:21.660 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('20', -111, 'SEARCH', '20', 0, 0, 0, 0, NULL, 29, '2026-09-17 20:53:21.660 +00:00', '2026-09-17 20:53:21.660 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('21', -106, 'COMMENTS', '21', 0, 0, 0, 0, NULL, 30, '2026-09-17 20:53:21.660 +00:00', '2026-09-17 20:53:21.660 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('22', -116, 'DATE ADDED', '22', 0, 0, 0, 0, NULL, 31, '2026-09-17 20:53:21.660 +00:00', '2026-09-17 20:53:21.660 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('23', -105, 'DJ PLAY COUNT', '23', 0, 0, 0, 0, NULL, 32, '2026-09-17 20:53:21.661 +00:00', '2026-09-17 20:53:21.661 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('24', -112, 'FOLDER', '24', 0, 0, 0, 0, NULL, 33, '2026-09-17 20:53:21.661 +00:00', '2026-09-17 20:53:21.661 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('25', -95, 'DEFAULT', '25', 0, 0, 0, 0, NULL, 34, '2026-09-17 20:53:21.661 +00:00', '2026-09-17 20:53:21.661 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('26', -94, 'ALPHABET', '26', 0, 0, 0, 0, NULL, 35, '2026-09-17 20:53:21.661 +00:00', '2026-09-17 20:53:21.661 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('27', -86, 'MATCHING', '27', 0, 0, 0, 0, NULL, 36, '2026-09-17 20:53:21.661 +00:00', '2026-09-17 20:53:21.661 +00:00');
|
||||
|
||||
-- djmdColor: 8 rows
|
||||
INSERT INTO "djmdColor" ("ID", "ColorCode", "SortKey", "Commnt", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('1', NULL, 1, 'Pink', '1', 0, 0, 0, 0, NULL, 2, '2026-09-17 20:53:21.657 +00:00', '2026-09-17 20:53:21.657 +00:00');
|
||||
INSERT INTO "djmdColor" ("ID", "ColorCode", "SortKey", "Commnt", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('2', NULL, 2, 'Red', '2', 0, 0, 0, 0, NULL, 3, '2026-09-17 20:53:21.657 +00:00', '2026-09-17 20:53:21.657 +00:00');
|
||||
INSERT INTO "djmdColor" ("ID", "ColorCode", "SortKey", "Commnt", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('3', NULL, 3, 'Orange', '3', 0, 0, 0, 0, NULL, 4, '2026-09-17 20:53:21.657 +00:00', '2026-09-17 20:53:21.657 +00:00');
|
||||
INSERT INTO "djmdColor" ("ID", "ColorCode", "SortKey", "Commnt", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('4', NULL, 4, 'Yellow', '4', 0, 0, 0, 0, NULL, 5, '2026-09-17 20:53:21.657 +00:00', '2026-09-17 20:53:21.657 +00:00');
|
||||
INSERT INTO "djmdColor" ("ID", "ColorCode", "SortKey", "Commnt", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('5', NULL, 5, 'Green', '5', 0, 0, 0, 0, NULL, 6, '2026-09-17 20:53:21.657 +00:00', '2026-09-17 20:53:21.657 +00:00');
|
||||
INSERT INTO "djmdColor" ("ID", "ColorCode", "SortKey", "Commnt", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('6', NULL, 6, 'Aqua', '6', 0, 0, 0, 0, NULL, 7, '2026-09-17 20:53:21.657 +00:00', '2026-09-17 20:53:21.657 +00:00');
|
||||
INSERT INTO "djmdColor" ("ID", "ColorCode", "SortKey", "Commnt", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('7', NULL, 7, 'Blue', '7', 0, 0, 0, 0, NULL, 8, '2026-09-17 20:53:21.658 +00:00', '2026-09-17 20:53:21.658 +00:00');
|
||||
INSERT INTO "djmdColor" ("ID", "ColorCode", "SortKey", "Commnt", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('8', NULL, 8, 'Purple', '8', 0, 0, 0, 0, NULL, 9, '2026-09-17 20:53:21.658 +00:00', '2026-09-17 20:53:21.658 +00:00');
|
||||
|
||||
-- djmdCategory: 22 rows
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('1', '1', 0, 1, 99, '1', 0, 0, 0, 0, NULL, 37, '2026-09-17 20:53:25.758 +00:00', '2026-09-17 20:53:25.758 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('2', '2', 1, 0, 2, '2', 0, 0, 0, 0, NULL, 38, '2026-09-17 20:53:25.769 +00:00', '2026-09-17 20:53:25.769 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('3', '3', 2, 0, 3, '3', 0, 0, 0, 0, NULL, 39, '2026-09-17 20:53:25.774 +00:00', '2026-09-17 20:53:25.774 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('4', '4', 3, 0, 1, '4', 0, 0, 0, 0, NULL, 40, '2026-09-17 20:53:25.780 +00:00', '2026-09-17 20:53:25.780 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('5', '17', 5, 0, 99, '5', 0, 0, 0, 0, NULL, 41, '2026-09-17 20:53:25.786 +00:00', '2026-09-17 20:53:25.786 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('6', '5', 0, 1, 5, '6', 0, 0, 0, 0, NULL, 42, '2026-09-17 20:53:25.793 +00:00', '2026-09-17 20:53:25.793 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('7', '6', 0, 1, 99, '7', 0, 0, 0, 0, NULL, 43, '2026-09-17 20:53:25.799 +00:00', '2026-09-17 20:53:25.799 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('8', '7', 0, 1, 99, '8', 0, 0, 0, 0, NULL, 44, '2026-09-17 20:53:25.804 +00:00', '2026-09-17 20:53:25.804 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('9', '8', 0, 1, 99, '9', 0, 0, 0, 0, NULL, 45, '2026-09-17 20:53:25.811 +00:00', '2026-09-17 20:53:25.811 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('10', '9', 0, 1, 99, '10', 0, 0, 0, 0, NULL, 46, '2026-09-17 20:53:25.817 +00:00', '2026-09-17 20:53:25.817 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('11', '10', 0, 1, 99, '11', 0, 0, 0, 0, NULL, 47, '2026-09-17 20:53:25.823 +00:00', '2026-09-17 20:53:25.823 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('12', '11', 4, 0, 99, '12', 0, 0, 0, 0, NULL, 48, '2026-09-17 20:53:25.829 +00:00', '2026-09-17 20:53:25.829 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('15', '13', 0, 1, 99, '15', 0, 0, 0, 0, NULL, 49, '2026-09-17 20:53:25.836 +00:00', '2026-09-17 20:53:25.836 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('17', '24', 9, 0, 99, '17', 0, 0, 0, 0, NULL, 50, '2026-09-17 20:53:25.842 +00:00', '2026-09-17 20:53:25.842 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('18', '20', 7, 0, 99, '18', 0, 0, 0, 0, NULL, 51, '2026-09-17 20:53:25.848 +00:00', '2026-09-17 20:53:25.848 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('19', '14', 0, 1, 4, '19', 0, 0, 0, 0, NULL, 52, '2026-09-17 20:53:25.854 +00:00', '2026-09-17 20:53:25.854 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('20', '15', 0, 1, 6, '20', 0, 0, 0, 0, NULL, 53, '2026-09-17 20:53:25.860 +00:00', '2026-09-17 20:53:25.860 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('21', '16', 0, 1, 99, '21', 0, 0, 0, 0, NULL, 54, '2026-09-17 20:53:25.865 +00:00', '2026-09-17 20:53:25.865 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('22', '19', 6, 0, 99, '22', 0, 0, 0, 0, NULL, 55, '2026-09-17 20:53:25.870 +00:00', '2026-09-17 20:53:25.870 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('23', '18', 0, 1, 99, '23', 0, 0, 0, 0, NULL, 56, '2026-09-17 20:53:25.875 +00:00', '2026-09-17 20:53:25.875 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('26', '27', 8, 2, 99, '26', 0, 0, 0, 0, NULL, 57, '2026-09-17 20:53:25.881 +00:00', '2026-09-17 20:53:25.881 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('27', '22', 10, 0, 99, '27', 0, 0, 0, 0, NULL, 58, '2026-09-17 20:53:25.886 +00:00', '2026-09-17 20:53:25.886 +00:00');
|
||||
|
||||
-- djmdSort: 17 rows
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('0', '25', 1, 0, '0', 0, 0, 0, 0, NULL, 59, '2026-09-17 20:53:25.893 +00:00', '2026-09-17 20:53:25.893 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('1', '26', 2, 0, '1', 0, 0, 0, 0, NULL, 60, '2026-09-17 20:53:25.900 +00:00', '2026-09-17 20:53:25.900 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('2', '2', 3, 0, '2', 0, 0, 0, 0, NULL, 61, '2026-09-17 20:53:25.907 +00:00', '2026-09-17 20:53:25.907 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('3', '3', 4, 0, '3', 0, 0, 0, 0, NULL, 62, '2026-09-17 20:53:25.913 +00:00', '2026-09-17 20:53:25.913 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('4', '5', 5, 0, '4', 0, 0, 0, 0, NULL, 63, '2026-09-17 20:53:25.920 +00:00', '2026-09-17 20:53:25.920 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('5', '6', 6, 0, '5', 0, 0, 0, 0, NULL, 64, '2026-09-17 20:53:25.925 +00:00', '2026-09-17 20:53:25.925 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('6', '1', 0, 1, '6', 0, 0, 0, 0, NULL, 65, '2026-09-17 20:53:25.931 +00:00', '2026-09-17 20:53:25.931 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('7', '21', 0, 1, '7', 0, 0, 0, 0, NULL, 66, '2026-09-17 20:53:25.937 +00:00', '2026-09-17 20:53:25.937 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('8', '14', 0, 1, '8', 0, 0, 0, 0, NULL, 67, '2026-09-17 20:53:25.943 +00:00', '2026-09-17 20:53:25.943 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('9', '8', 0, 1, '9', 0, 0, 0, 0, NULL, 68, '2026-09-17 20:53:25.950 +00:00', '2026-09-17 20:53:25.950 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('10', '9', 0, 1, '10', 0, 0, 0, 0, NULL, 69, '2026-09-17 20:53:25.957 +00:00', '2026-09-17 20:53:25.957 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('11', '10', 0, 1, '11', 0, 0, 0, 0, NULL, 70, '2026-09-17 20:53:25.963 +00:00', '2026-09-17 20:53:25.963 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('12', '11', 7, 0, '12', 0, 0, 0, 0, NULL, 71, '2026-09-17 20:53:25.971 +00:00', '2026-09-17 20:53:25.971 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('13', '15', 0, 1, '13', 0, 0, 0, 0, NULL, 72, '2026-09-17 20:53:25.978 +00:00', '2026-09-17 20:53:25.978 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('15', '13', 0, 1, '15', 0, 0, 0, 0, NULL, 73, '2026-09-17 20:53:25.985 +00:00', '2026-09-17 20:53:25.985 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('16', '23', 0, 1, '16', 0, 0, 0, 0, NULL, 74, '2026-09-17 20:53:25.992 +00:00', '2026-09-17 20:53:25.992 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('17', '22', 0, 1, '17', 0, 0, 0, 0, NULL, 75, '2026-09-17 20:53:25.998 +00:00', '2026-09-17 20:53:25.998 +00:00');
|
||||
@@ -8,6 +8,8 @@
|
||||
# - traktor-nml-utils parses/serializes via xsdata, which discovers plugins at
|
||||
# runtime → collect_submodules('xsdata')
|
||||
# - python-multipart is imported as `multipart` by starlette → hidden import
|
||||
# - dulwich (version-history backups) imports git backends dynamically →
|
||||
# collect_submodules('dulwich')
|
||||
from PyInstaller.utils.hooks import collect_submodules, collect_all
|
||||
|
||||
hiddenimports = []
|
||||
@@ -15,7 +17,7 @@ datas = []
|
||||
binaries = []
|
||||
|
||||
# Dynamically-imported subpackages.
|
||||
for pkg in ("uvicorn", "xsdata"):
|
||||
for pkg in ("uvicorn", "xsdata", "dulwich"):
|
||||
hiddenimports += collect_submodules(pkg)
|
||||
|
||||
# Native standard extras — grab modules + shared libs + any data.
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Per-platform adapters. Each owns a native library model and translates the
|
||||
generic commands onto it; nothing outside an adapter package sees a native type.
|
||||
|
||||
Importing this package registers every adapter. Order matters only for the
|
||||
registry's ``can_open()`` probe, and the probes are mutually exclusive: Traktor
|
||||
requires an NML header, Rekordbox an encrypted database with its own schema, and
|
||||
OneLibrary a drive laid out around ``PIONEER/rekordbox/exportLibrary.db``. The
|
||||
two encrypted databases cannot be confused for one another — they use different
|
||||
SQLCipher keys, so each driver's decrypt fails outright on the other's file.
|
||||
"""
|
||||
from . import onelibrary # noqa: F401 — registers the OneLibrary driver
|
||||
from . import rekordbox # noqa: F401 — registers the Rekordbox driver
|
||||
from . import traktor # noqa: F401 — registers the Traktor driver
|
||||
@@ -0,0 +1,16 @@
|
||||
"""The OneLibrary adapter: the cross-vendor USB export format.
|
||||
|
||||
Importing this package registers the platform for READING (a plugged-in drive)
|
||||
and as an export TARGET (writing a fresh drive). Two registries, because opening
|
||||
a library and creating one from nothing are different capabilities.
|
||||
"""
|
||||
from ...core import export as core_export
|
||||
from ...core import registry
|
||||
from .driver import OneLibraryDriver
|
||||
from .export import OneLibraryExporter
|
||||
|
||||
ONELIBRARY = OneLibraryDriver()
|
||||
registry.register(ONELIBRARY)
|
||||
|
||||
ONELIBRARY_EXPORTER = OneLibraryExporter()
|
||||
core_export.register(ONELIBRARY_EXPORTER)
|
||||
@@ -0,0 +1,311 @@
|
||||
"""The OneLibrary adapter: owns the drive's database and the generic projection.
|
||||
|
||||
Mirrors `adapters.rekordbox.adapter`. It holds:
|
||||
|
||||
* a ``OneLibraryStore`` — the retained NATIVE model (the open drive),
|
||||
* a ``TrackIndex`` — the generic READ projection built from it.
|
||||
|
||||
**Read-only.** Every command is refused and `capabilities.writable` is False with
|
||||
cause `platform_incomplete`, so the UI never offers an edit in the first place;
|
||||
the raises here are the backstop, not the mechanism.
|
||||
|
||||
That scope is deliberate rather than provisional. The purpose of this adapter is
|
||||
to make a OneLibrary drive a readable SOURCE — the half an import into another
|
||||
library needs — and every genuinely unknown part of the format sits on the write
|
||||
side: the `cue` table's eight MPEG frame/offset columns, whose values a player
|
||||
needs to seek accurately in a VBR file; the waveform tags a CDJ draws from; and
|
||||
the update counters a drive uses to reconcile edits made on hardware. None of
|
||||
those has to be guessed at to read a drive, and none of them should be guessed at
|
||||
at all.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from ...core.adapter import Unsupported
|
||||
from ...core.capabilities import Capabilities
|
||||
from ...core.model import HotcueChip, PlaylistNode, Track, TrackCues
|
||||
from ...core.pathmap import PathMapping, common_dir_prefix
|
||||
from ...core.query import TrackIndex
|
||||
from . import capabilities as caps
|
||||
from . import projection
|
||||
from .store import OneLibraryStore
|
||||
|
||||
# `playlist.attribute`, from pyrekordbox's own enum. A drive carries no smart
|
||||
# playlists — rekordbox resolves them to static lists on export, because a CDJ
|
||||
# cannot evaluate rules — but the value is handled rather than assumed absent.
|
||||
ATTRIBUTE_PLAYLIST = 0
|
||||
ATTRIBUTE_FOLDER = 1
|
||||
ATTRIBUTE_SMART = 4
|
||||
|
||||
|
||||
class OneLibraryAdapter:
|
||||
platform = "onelibrary"
|
||||
|
||||
def __init__(self, path: Path):
|
||||
self.path = Path(path)
|
||||
self._store = OneLibraryStore(self.path)
|
||||
self._index = TrackIndex()
|
||||
self._rebuild()
|
||||
|
||||
# ---- projection maintenance -----------------------------------------
|
||||
def _rebuild(self) -> None:
|
||||
self._index.rebuild(
|
||||
[
|
||||
projection.to_track(row, self._drive_path(row))
|
||||
for row in self._store.iter_content()
|
||||
]
|
||||
)
|
||||
|
||||
def _drive_path(self, row) -> str | None:
|
||||
resolved = self._store.layout.resolve(getattr(row, "path", None))
|
||||
return str(resolved) if resolved is not None else None
|
||||
|
||||
def close(self) -> None:
|
||||
"""Release the database and its file handle.
|
||||
|
||||
More than housekeeping here: the library is on a removable drive, and a
|
||||
held handle is what stops it ejecting.
|
||||
"""
|
||||
self._store.close()
|
||||
|
||||
def reload(self) -> None:
|
||||
self._store._load()
|
||||
self._rebuild()
|
||||
|
||||
# ---- identity --------------------------------------------------------
|
||||
def capabilities(self) -> Capabilities:
|
||||
return caps.capabilities_for(
|
||||
device_name=self._store.device_name,
|
||||
version=self._store.db_version,
|
||||
)
|
||||
|
||||
# ---- read ------------------------------------------------------------
|
||||
@property
|
||||
def tracks(self) -> list[Track]:
|
||||
return self._index.tracks
|
||||
|
||||
@property
|
||||
def by_key(self) -> dict[str, Track]:
|
||||
return self._index.by_key
|
||||
|
||||
def track(self, track_id: str) -> Track | None:
|
||||
return self._index.get(track_id)
|
||||
|
||||
def query_tracks(self, **kw):
|
||||
return self._index.query_tracks(**kw)
|
||||
|
||||
def facets(self):
|
||||
return self._index.facets()
|
||||
|
||||
def stats(self, playlist_count: int):
|
||||
return self._index.stats(playlist_count)
|
||||
|
||||
def playlist_count(self) -> int:
|
||||
return self._store.count_playlists()
|
||||
|
||||
def track_cues(self, track_id: str) -> TrackCues | None:
|
||||
"""A track's cues and beatgrid — and where the approximate counts get fixed.
|
||||
|
||||
`projection.to_track` cannot afford the track's analysis files at open
|
||||
(~23 ms each for the `.EXT`), so it reports no cues and a guessed marker
|
||||
count. This is the moment the real numbers exist, so the projected track
|
||||
is corrected here rather than being left disagreeing with the deck.
|
||||
"""
|
||||
if self._index.get(track_id) is None:
|
||||
return None
|
||||
cues = self._store.cues(track_id)
|
||||
grid = self._store.anlz_grid(track_id)
|
||||
from . import beatgrid
|
||||
|
||||
markers = beatgrid.markers_from_beats(*grid) if grid is not None else []
|
||||
result = projection.to_track_cues(cues, markers)
|
||||
|
||||
track = self._index.get(track_id)
|
||||
if track is not None:
|
||||
track.grid_marker_count = len(result.grid_markers)
|
||||
track.cue_count = len(result.cues)
|
||||
track.hotcues = sorted(
|
||||
(
|
||||
HotcueChip(slot=c.slot, type=c.type, color=c.color)
|
||||
for c in result.cues
|
||||
if c.role == "hotcue" and c.slot is not None
|
||||
),
|
||||
key=lambda chip: chip.slot,
|
||||
)
|
||||
track.hotcue_count = len(track.hotcues)
|
||||
return result
|
||||
|
||||
# ---- playlists -------------------------------------------------------
|
||||
def playlist_tree(self) -> list[PlaylistNode]:
|
||||
"""The drive's playlist tree: a flat table with `playlist_id_parent` links.
|
||||
|
||||
A root node's parent is 0, not NULL — so "no parent" is a value here
|
||||
rather than an absence, and treating 0 as a real id would orphan every
|
||||
top-level playlist.
|
||||
"""
|
||||
rows = self._store.playlists()
|
||||
nodes: dict[str, PlaylistNode] = {}
|
||||
parents: dict[str, str] = {}
|
||||
|
||||
for r in rows:
|
||||
attribute = int(getattr(r, "attribute", 0) or 0)
|
||||
if attribute == ATTRIBUTE_FOLDER:
|
||||
kind = "folder"
|
||||
elif attribute == ATTRIBUTE_SMART:
|
||||
kind = "smart"
|
||||
else:
|
||||
kind = "playlist"
|
||||
node_id = str(getattr(r, "playlist_id", ""))
|
||||
nodes[node_id] = PlaylistNode(
|
||||
id=node_id,
|
||||
name=getattr(r, "name", "") or "",
|
||||
kind=kind,
|
||||
count=(0 if kind == "folder" else len(self._store.playlist_song_ids(node_id))),
|
||||
children=[],
|
||||
selectable=kind == "playlist",
|
||||
# Read-only: every per-node flag is False, and
|
||||
# `capabilities.writable` tells the UI why, once.
|
||||
can_add_tracks=False,
|
||||
can_reorder=False,
|
||||
can_rename=False,
|
||||
can_delete=False,
|
||||
can_contain_children=kind == "folder",
|
||||
)
|
||||
parent = str(getattr(r, "playlist_id_parent", 0) or 0)
|
||||
parents[node_id] = "root" if parent in ("0", "", "None") else parent
|
||||
|
||||
roots: list[PlaylistNode] = []
|
||||
for node_id, node in nodes.items():
|
||||
parent = nodes.get(parents.get(node_id, "root"))
|
||||
if parent is None:
|
||||
roots.append(node)
|
||||
else:
|
||||
parent.children.append(node)
|
||||
return roots
|
||||
|
||||
def playlist_entries(self, node_id: str) -> list[str] | None:
|
||||
ids = self._store.playlist_song_ids(node_id)
|
||||
return ids if ids or self._is_playlist(node_id) else None
|
||||
|
||||
def playlist_tracks(self, node_id: str) -> list[Track] | None:
|
||||
keys = self.playlist_entries(node_id)
|
||||
if keys is None:
|
||||
return None
|
||||
return [t for k in keys if (t := self._index.get(k)) is not None]
|
||||
|
||||
def _is_playlist(self, node_id: str) -> bool:
|
||||
return any(str(getattr(r, "playlist_id", "")) == str(node_id) for r in self._store.playlists())
|
||||
|
||||
# ---- audio / paths ----------------------------------------------------
|
||||
def audio_path(self, track_id: str):
|
||||
return self._store.audio_path(track_id)
|
||||
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None:
|
||||
"""Ignored: a drive's paths are relative to wherever it is mounted.
|
||||
|
||||
Path remapping exists because a desktop library stores absolute paths
|
||||
that go stale when music moves. A OneLibrary drive stores everything
|
||||
relative to its own root, so it is self-contained by construction and
|
||||
there is nothing for a mapping to fix.
|
||||
"""
|
||||
return None
|
||||
|
||||
def path_prefix_suggestions(self) -> dict:
|
||||
paths = self._store.all_audio_paths()
|
||||
primary = common_dir_prefix(paths)
|
||||
return {
|
||||
"primary": primary,
|
||||
"groups": [{"prefix": primary, "count": len(paths)}] if primary else [],
|
||||
}
|
||||
|
||||
def remap_preview(self, mapping: PathMapping) -> dict:
|
||||
paths = [Path(p) for p in self._store.all_audio_paths()]
|
||||
return {"total": len(paths), "matched": 0, "existing": 0, "samples": []}
|
||||
|
||||
def remap_locations(self, mapping: PathMapping) -> dict[str, str]:
|
||||
raise Unsupported(self._readonly_reason("Rewriting stored paths"))
|
||||
|
||||
# ---- save -------------------------------------------------------------
|
||||
@property
|
||||
def dirty(self) -> bool:
|
||||
return False
|
||||
|
||||
def save(self):
|
||||
raise Unsupported(self._readonly_reason("Saving"))
|
||||
|
||||
def snapshot(self) -> bytes:
|
||||
raise Unsupported("OneLibrary drives are not versioned by Konduktor")
|
||||
|
||||
# ---- commands: all refused -------------------------------------------
|
||||
def _readonly_reason(self, what: str) -> str:
|
||||
return f"{what} is not supported yet for OneLibrary drives."
|
||||
|
||||
def _refuse(self, what: str):
|
||||
raise Unsupported(self._readonly_reason(what))
|
||||
|
||||
def add_tracks(self, items: list) -> list[str]:
|
||||
self._refuse("Adding tracks")
|
||||
|
||||
def remove_tracks(self, track_ids: list[str]) -> int:
|
||||
self._refuse("Removing tracks")
|
||||
|
||||
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None:
|
||||
self._refuse("Editing track metadata")
|
||||
|
||||
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
|
||||
self._refuse("Editing cover art")
|
||||
|
||||
def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
|
||||
return None
|
||||
|
||||
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
|
||||
self._refuse("Creating playlists")
|
||||
|
||||
def create_folder(self, name: str, parent_id: str | None = None) -> str:
|
||||
self._refuse("Creating playlist folders")
|
||||
|
||||
def rename_playlist(self, node_id: str, name: str) -> None:
|
||||
self._refuse("Renaming playlists")
|
||||
|
||||
def delete_playlist(self, node_id: str) -> None:
|
||||
self._refuse("Deleting playlists")
|
||||
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
|
||||
self._refuse("Editing playlists")
|
||||
|
||||
def set_cue(self, track_id: str, **kw) -> TrackCues:
|
||||
self._refuse("Editing cues")
|
||||
|
||||
def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> TrackCues:
|
||||
self._refuse("Editing cues")
|
||||
|
||||
def delete_cue(self, track_id: str, slot: int) -> TrackCues:
|
||||
self._refuse("Deleting cues")
|
||||
|
||||
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues:
|
||||
self._refuse("Placing cues")
|
||||
|
||||
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> TrackCues:
|
||||
self._refuse("Editing the beatgrid")
|
||||
|
||||
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> TrackCues:
|
||||
self._refuse("Editing the beatgrid")
|
||||
|
||||
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> TrackCues:
|
||||
self._refuse("Editing the beatgrid")
|
||||
|
||||
def delete_grid_marker(self, track_id: str, index: int) -> TrackCues:
|
||||
self._refuse("Editing the beatgrid")
|
||||
|
||||
def replace_grid(self, track_id: str, markers: list) -> TrackCues:
|
||||
self._refuse("Editing the beatgrid")
|
||||
|
||||
def set_analysed_grid(self, track_id: str, markers: list) -> TrackCues:
|
||||
self._refuse("Editing the beatgrid")
|
||||
|
||||
def delete_grid(self, track_id: str) -> TrackCues:
|
||||
self._refuse("Deleting the beatgrid")
|
||||
|
||||
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues:
|
||||
raise Unsupported("OneLibrary has no beatgrid lock")
|
||||
@@ -0,0 +1,62 @@
|
||||
"""A OneLibrary beatgrid -> the generic marker list.
|
||||
|
||||
**The beatgrid is not in the database.** `exportLibrary.db` has no grid table at
|
||||
all — `content.bpmx100` is a single display tempo — and the real grid is the
|
||||
`PQTZ` tag of the track's ANLZ `.DAT`, holding EVERY BEAT explicitly. That is the
|
||||
same arrangement, and the same tag, as a desktop Rekordbox library: a drive is
|
||||
exported from one, and rekordbox regenerates the analysis files rather than
|
||||
inventing a new format for them.
|
||||
|
||||
Verified end to end on a track whose flexible grid Konduktor itself had written
|
||||
into `master.db`: exporting it to a OneLibrary drive preserved both tempo
|
||||
segments exactly (128.00 BPM to 60 s, then 90.00 BPM), so multi-tempo grids
|
||||
survive the whole chain and the marker list is the right generic shape.
|
||||
|
||||
The collapse rule is shared with the Rekordbox adapter deliberately rather than
|
||||
copied. Two implementations of "when is this a new marker?" would be free to
|
||||
drift apart by a rounding tolerance, and a drifting grid is a silent corruption
|
||||
rather than a visible bug. If a third AlphaTheta-format adapter ever appears,
|
||||
this and `rekordbox.beatgrid` should be promoted to one shared ANLZ module; the
|
||||
import direction here is the cheapest way to stay honest until then.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from ...core.model import GridMarker
|
||||
from ..rekordbox.beatgrid import BPM_EPSILON, markers_from_beats # noqa: F401
|
||||
|
||||
__all__ = ["BPM_EPSILON", "markers_from_beats", "beats_from_pqtz", "markers_from_anlz"]
|
||||
|
||||
|
||||
def beats_from_pqtz(anlz) -> tuple[list[float], list[float]] | None:
|
||||
"""Per-beat ``(times_sec, bpms)`` from a parsed ANLZ file's `PQTZ` tag.
|
||||
|
||||
Returns None when the file has no `PQTZ` — which is a real state, not an
|
||||
error: rekordbox analyses one-shot samples too, and gives them an analysis
|
||||
file with no beatgrid in it.
|
||||
|
||||
`PQTZ` stores time in milliseconds and tempo in hundredths of a BPM.
|
||||
"""
|
||||
for tag in getattr(anlz, "tags", []):
|
||||
if tag.type != "PQTZ":
|
||||
continue
|
||||
entries = getattr(getattr(tag.struct, "content", None), "entries", None)
|
||||
if not entries:
|
||||
return None
|
||||
times: list[float] = []
|
||||
bpms: list[float] = []
|
||||
for e in entries:
|
||||
try:
|
||||
times.append(int(e.time) / 1000.0)
|
||||
bpms.append(int(e.tempo) / 100.0)
|
||||
except (AttributeError, TypeError, ValueError):
|
||||
continue
|
||||
return (times, bpms) if times else None
|
||||
return None
|
||||
|
||||
|
||||
def markers_from_anlz(anlz) -> list[GridMarker]:
|
||||
"""The generic marker list for a parsed ANLZ file."""
|
||||
grid = beats_from_pqtz(anlz)
|
||||
if grid is None:
|
||||
return []
|
||||
return markers_from_beats(*grid)
|
||||
@@ -0,0 +1,95 @@
|
||||
"""What a OneLibrary drive can persist: nothing, for now.
|
||||
|
||||
`writable` is False with cause `platform_incomplete`. That is the distinction the
|
||||
capability system exists to draw — this is a ROADMAP GAP, not a refusal. A
|
||||
cloud-synced Rekordbox library is refused permanently to protect the user's other
|
||||
machines; a OneLibrary drive simply has no write path yet, and the UI must word
|
||||
those two very differently.
|
||||
|
||||
The per-feature flags below still report what the FORMAT supports rather than
|
||||
being blanked to false, because that is what `writable=False` is for: the UI can
|
||||
show a drive's cues and grid honestly, and say once, in one place, that the whole
|
||||
library is read-only. Blanking them would claim OneLibrary has no hot cues.
|
||||
|
||||
Two answers are worth recording now, while the evidence is in front of us, since
|
||||
getting them wrong later would be a silent data bug rather than a missing
|
||||
feature:
|
||||
|
||||
* cue colour is **free RGB**, not a palette index. The `PCO2` tag stores three
|
||||
bytes per cue, and the reference drive held #4D00FF, #33FF00, #00C4FF and
|
||||
#FF8C00. This differs from the desktop Rekordbox adapter, which reports
|
||||
"palette" because `djmdCue` stores an index into a built-in table — the same
|
||||
vendor, two genuinely different representations.
|
||||
* a loop is a cue with an out-point, so ``loops="cue_type"`` — the same answer
|
||||
as Traktor and Rekordbox, and NOT the `separate_bank` the original
|
||||
multi-platform plan assumed.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from ...core.capabilities import (
|
||||
Capabilities,
|
||||
CueCapabilities,
|
||||
GridCapabilities,
|
||||
PlaylistCapabilities,
|
||||
SaveCapabilities,
|
||||
TrackCapabilities,
|
||||
)
|
||||
|
||||
# Pads A-H. Unlike `djmdCue.Kind`, the ANLZ slot number is a dense 1-based index,
|
||||
# so the bank really is 1..8 (see `cues.py`).
|
||||
HOTCUE_SLOTS = 8
|
||||
|
||||
|
||||
def capabilities_for(device_name: str | None = None, version: str | None = None) -> Capabilities:
|
||||
return Capabilities(
|
||||
platform="onelibrary",
|
||||
version=version,
|
||||
# A roadmap gap, not a protective refusal — the UI words the two
|
||||
# differently, which is the whole reason `readonly_cause` exists.
|
||||
writable=False,
|
||||
readonly_cause="platform_incomplete",
|
||||
cues=CueCapabilities(
|
||||
editable=False,
|
||||
hotcue_slots=HOTCUE_SLOTS,
|
||||
slot_labels="letter",
|
||||
# OneLibrary carries memory cues, as Rekordbox does. They are
|
||||
# projected and preserved; nothing here is editable anyway.
|
||||
memory_cues=True,
|
||||
max_memory_cues=None,
|
||||
types=["cue", "loop"],
|
||||
color="free", # PCO2 stores RGB per cue, not a palette index
|
||||
palette=[],
|
||||
named=True, # PCO2 carries a per-cue comment
|
||||
loops="cue_type",
|
||||
),
|
||||
# The grid is the ANLZ `PQTZ` tag, per beat, and multi-tempo grids do
|
||||
# survive an export — so the format is flexible even though Konduktor
|
||||
# does not write it here.
|
||||
grid=GridCapabilities(editable=False, flexible=True, lockable=False),
|
||||
tracks=TrackCapabilities(
|
||||
rating_max=5, # stored 0-5 directly, as in master.db
|
||||
editable_fields=[],
|
||||
media_kinds=["audio"],
|
||||
# The drive has an `image` table and an Artwork folder, but nothing
|
||||
# is wired up to read them yet.
|
||||
artwork=False,
|
||||
artwork_note=None,
|
||||
),
|
||||
playlists=PlaylistCapabilities(
|
||||
folders=True, # `playlist.attribute` 1, nested via playlist_id_parent
|
||||
# A drive carries no smart playlists: rekordbox resolves them to
|
||||
# static lists on export, because a CDJ cannot evaluate rules.
|
||||
smart="none",
|
||||
reorder=False,
|
||||
),
|
||||
save=SaveCapabilities(
|
||||
app_name="OneLibrary",
|
||||
library_label=device_name or "exportLibrary.db",
|
||||
# Nothing is written, so nothing can be overwritten by another app.
|
||||
overwrite_risk="none",
|
||||
# A drive is a database plus N analysis files plus the audio itself,
|
||||
# so there is no single blob that IS the library — the same reason
|
||||
# Rekordbox libraries are not versioned.
|
||||
history=False,
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,188 @@
|
||||
"""OneLibrary cues: read from the ANLZ analysis files, not the database.
|
||||
|
||||
**The `cue` table is not where a drive's cues are.** It exists in the schema —
|
||||
and has columns for everything a cue needs — but rekordbox exports an empty one
|
||||
and puts the cues in the track's ANLZ file instead. Measured on a real rekordbox
|
||||
7 export of a track carrying four hot cues and a looped memory cue: the `cue`
|
||||
table held zero rows and every cue was present in the analysis files. The table
|
||||
appears to be for hardware writing edits BACK to the drive, which is a different
|
||||
direction than this adapter reads.
|
||||
|
||||
Two tags carry cues, and they are not equivalent:
|
||||
|
||||
* **`PCOB`** is the original list, and it is SPLIT BY PAD. The `.DAT` holds
|
||||
only hot cues 1-3 — the three pads the earliest CDJs had — and the `.EXT`
|
||||
holds 4 and up. Reading only the `.DAT` silently loses pads D-H.
|
||||
* **`PCO2`** is the extended list in the `.EXT`, and it holds the COMPLETE set
|
||||
in one tag plus three things `PCOB` has nowhere to put: an RGB colour, a
|
||||
comment, and the loop length expressed in BEATS.
|
||||
|
||||
So `PCO2` is preferred and `PCOB` is the fallback for a drive old enough not to
|
||||
have one. Both are merged across files before that choice is made, because "the
|
||||
complete list" must not depend on which file happened to be read.
|
||||
|
||||
**Slot numbering differs from `master.db` and this is the trap.** In the desktop
|
||||
database a hot cue's `djmdCue.Kind` is a sparse bank that SKIPS 4 (`1,2,3,5,…`
|
||||
for pads A-H). In ANLZ, `hot_cue` is a plain dense 1-based index (1=A, 2=B, …),
|
||||
and `0` means the cue is a memory cue rather than a pad. The two were aligned
|
||||
against each other on one track: `Kind` 1/2/3/5 at 40.000 s, 18.773 s, 90.667 s
|
||||
and 120.000 s came out as `hot_cue` 1/2/3/4 at exactly the same times. Carry the
|
||||
Rekordbox adapter's mapping over here unchanged and every cue from pad D onward
|
||||
lands one pad too far along.
|
||||
|
||||
Times are MILLISECONDS here, where the desktop database counts frames at 150 fps.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from ...core.model import CuePoint
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
# `loop_time` when a cue is not a loop. Stored as an unsigned 32-bit -1 rather
|
||||
# than 0, so a plain falsiness test would read it as "a loop ending at zero".
|
||||
NO_LOOP = 0xFFFFFFFF
|
||||
|
||||
# `hot_cue` for a cue that sits in no pad bank, i.e. a memory cue.
|
||||
MEMORY_SLOT = 0
|
||||
|
||||
# PCO2/PCOB entry kinds. The value is the same in both tags; PCOB exposes it as
|
||||
# a construct enum and PCO2 as a plain int, so both are normalised to an int.
|
||||
ENTRY_CUE = 1
|
||||
ENTRY_LOOP = 2
|
||||
|
||||
|
||||
def _entry_kind(value) -> int:
|
||||
"""PCOB gives an enum, PCO2 an int — one number out of either."""
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
return ENTRY_CUE
|
||||
|
||||
|
||||
def _color(entry) -> str | None:
|
||||
"""A cue's colour as ``#RRGGBB``, when the tag carries one.
|
||||
|
||||
Only `PCO2` stores RGB. A cue with no colour set stores 0,0,0 — which is a
|
||||
real black in principle, but rekordbox uses it as "unset" and shows such a
|
||||
cue in the default colour, so it is reported as no colour rather than as
|
||||
black. Memory cues in the reference export are exactly this case.
|
||||
"""
|
||||
try:
|
||||
r, g, b = int(entry.color_red), int(entry.color_green), int(entry.color_blue)
|
||||
except (AttributeError, TypeError, ValueError):
|
||||
return None
|
||||
if (r, g, b) == (0, 0, 0):
|
||||
return None
|
||||
return f"#{r:02X}{g:02X}{b:02X}"
|
||||
|
||||
|
||||
def _to_cue(entry, *, with_color: bool) -> CuePoint | None:
|
||||
"""One ANLZ cue entry as a generic `CuePoint`, or None if unreadable."""
|
||||
try:
|
||||
hot_cue = int(entry.hot_cue)
|
||||
start_ms = int(entry.time)
|
||||
except (AttributeError, TypeError, ValueError):
|
||||
return None
|
||||
|
||||
loop_ms = getattr(entry, "loop_time", NO_LOOP)
|
||||
try:
|
||||
loop_ms = int(loop_ms)
|
||||
except (TypeError, ValueError):
|
||||
loop_ms = NO_LOOP
|
||||
|
||||
is_loop = _entry_kind(getattr(entry, "type", ENTRY_CUE)) == ENTRY_LOOP
|
||||
length = 0.0
|
||||
if is_loop and loop_ms != NO_LOOP and loop_ms > start_ms:
|
||||
length = (loop_ms - start_ms) / 1000.0
|
||||
|
||||
# hot_cue 0 is the memory list; 1..N are the pads, dense and 1-based, so the
|
||||
# generic 0-based slot is simply one less.
|
||||
role = "memory" if hot_cue == MEMORY_SLOT else "hotcue"
|
||||
slot = None if role == "memory" else hot_cue - 1
|
||||
|
||||
comment = getattr(entry, "comment", None)
|
||||
return CuePoint(
|
||||
name=(str(comment) or None) if comment else None,
|
||||
type="loop" if length > 0 else "cue",
|
||||
role=role,
|
||||
start=start_ms / 1000.0,
|
||||
length=length,
|
||||
slot=slot,
|
||||
color=_color(entry) if with_color else None,
|
||||
# A OneLibrary drive is read-only in Konduktor, so no cue accepts a
|
||||
# command. `capabilities.writable` is what the UI actually gates on;
|
||||
# this keeps the per-cue answer consistent with it.
|
||||
editable=False,
|
||||
readonly_reason="platform_managed",
|
||||
grid_marker=None,
|
||||
)
|
||||
|
||||
|
||||
def _entries(anlz, tag_type: str) -> list:
|
||||
"""Every entry of every `tag_type` tag in one parsed ANLZ file.
|
||||
|
||||
A file carries the tag twice — once for hot cues and once for memory cues —
|
||||
so both are collected and the entry's own `hot_cue` decides which it is.
|
||||
That is more robust than trusting the container's type field, which is
|
||||
absent on some tags in real files.
|
||||
"""
|
||||
out: list = []
|
||||
for tag in getattr(anlz, "tags", []):
|
||||
if tag.type != tag_type:
|
||||
continue
|
||||
content = getattr(tag.struct, "content", None)
|
||||
out.extend(getattr(content, "entries", None) or [])
|
||||
return out
|
||||
|
||||
|
||||
def cues_from_anlz(dat, ext) -> list[CuePoint]:
|
||||
"""The track's complete cue list, from its parsed `.DAT` and `.EXT`.
|
||||
|
||||
Either may be None — a drive can carry a `.DAT` with no `.EXT` — and a track
|
||||
with no cues at all yields an empty list rather than an error.
|
||||
"""
|
||||
files = [f for f in (dat, ext) if f is not None]
|
||||
if not files:
|
||||
return []
|
||||
|
||||
# PCO2 first: it is the complete list and the only one with colour, comment
|
||||
# and beat-denominated loops. It lives only in the .EXT.
|
||||
pco2: list = []
|
||||
for f in files:
|
||||
pco2.extend(_entries(f, "PCO2"))
|
||||
if pco2:
|
||||
cues = [c for e in pco2 if (c := _to_cue(e, with_color=True)) is not None]
|
||||
else:
|
||||
# Fallback: merge PCOB across BOTH files. The .DAT holds pads 1-3 and the
|
||||
# .EXT the rest, so either alone is an incomplete bank.
|
||||
pcob: list = []
|
||||
for f in files:
|
||||
pcob.extend(_entries(f, "PCOB"))
|
||||
cues = [c for e in pcob if (c := _to_cue(e, with_color=False)) is not None]
|
||||
|
||||
return _dedupe(cues)
|
||||
|
||||
|
||||
def _dedupe(cues: list[CuePoint]) -> list[CuePoint]:
|
||||
"""Collapse the same cue appearing in more than one tag or file.
|
||||
|
||||
Identity is (role, slot, start) rather than the whole cue: the same pad can
|
||||
be described by both `PCOB` and `PCO2`, and by both files, and those copies
|
||||
agree on position while differing in how much detail they carry. The first
|
||||
one wins, which — given PCO2 is read first — is the richest.
|
||||
|
||||
Ordered by position, then by slot, so the projection is stable across reads
|
||||
regardless of the order the tags happened to store.
|
||||
"""
|
||||
seen: set[tuple[str, int | None, int]] = set()
|
||||
out: list[CuePoint] = []
|
||||
for c in cues:
|
||||
key = (c.role, c.slot, round(c.start * 1000))
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
out.append(c)
|
||||
out.sort(key=lambda c: (c.start, c.slot if c.slot is not None else -1))
|
||||
return out
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Find OneLibrary drives that are plugged in right now.
|
||||
|
||||
This is the one platform whose libraries have no fixed location: Traktor and
|
||||
Rekordbox each keep theirs at a known per-OS path, but a OneLibrary library is
|
||||
whatever USB stick happens to be mounted. So detection scans mount points rather
|
||||
than probing a list of known paths, and what it finds legitimately changes
|
||||
between two calls a second apart.
|
||||
|
||||
Only the mount ROOTS are scanned, never their contents recursively. A drive can
|
||||
hold tens of thousands of files, the database is at a fixed place within it, and
|
||||
walking a slow USB stick at startup is exactly the kind of thing that makes an
|
||||
app feel broken.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
# Where this OS mounts drives is not adapter knowledge — the file browser needs
|
||||
# the same answer, and two scanners would drift. It grew here because this is
|
||||
# the platform whose libraries ARE drives; it lives in core now.
|
||||
from ...core.places import mount_points as _mount_points
|
||||
from .layout import DriveLayout
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def describe(path: Path) -> dict:
|
||||
"""A candidate record for a drive or database path, shaped for the picker."""
|
||||
path = Path(path)
|
||||
layout = DriveLayout.locate(path)
|
||||
database = layout.database if layout is not None else path
|
||||
exists = False
|
||||
try:
|
||||
exists = database.is_file()
|
||||
except OSError:
|
||||
pass
|
||||
# The drive's name is what a person recognises — "Hardy", not
|
||||
# "exportLibrary.db" — so the mount point supplies the label.
|
||||
root_name = layout.root.name if layout is not None else path.name
|
||||
return {
|
||||
"path": str(database),
|
||||
"label": f"OneLibrary — {root_name}" if root_name else "OneLibrary",
|
||||
"version": None,
|
||||
"modified": (database.stat().st_mtime if exists else None),
|
||||
"exists": exists,
|
||||
}
|
||||
|
||||
|
||||
def detect_libraries() -> list[dict]:
|
||||
"""Every mounted drive that carries a OneLibrary database, newest first."""
|
||||
found: list[dict] = []
|
||||
seen: set[str] = set()
|
||||
for root in _mount_points():
|
||||
layout = DriveLayout.locate(root)
|
||||
if layout is None:
|
||||
continue
|
||||
try:
|
||||
key = str(layout.database.resolve())
|
||||
except OSError:
|
||||
continue
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
found.append(describe(layout.root))
|
||||
found.sort(key=lambda c: c["modified"] or 0.0, reverse=True)
|
||||
return found
|
||||
@@ -0,0 +1,105 @@
|
||||
"""Opening OneLibrary drives: recognition and discovery."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
from . import discovery
|
||||
from .adapter import OneLibraryAdapter
|
||||
from .layout import DriveLayout
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class OneLibraryDriver:
|
||||
platform = "onelibrary"
|
||||
display_name = "OneLibrary"
|
||||
# This platform's libraries live on plugged-in drives rather than at a
|
||||
# fixed path, so `detect()` genuinely changes between calls and the app
|
||||
# offers them as IMPORT SOURCES. Declared rather than inferred from the
|
||||
# platform name, so a future Serato-on-a-stick needs no change upstream.
|
||||
removable = True
|
||||
suffixes = (".db",)
|
||||
library_label = "exportLibrary.db"
|
||||
# What a user PICKS is the mount point, not the database buried three levels
|
||||
# down inside it — `DriveLayout.locate()` accepts either, but only one of
|
||||
# them is a thing anybody browses to. The file browser reads this to offer
|
||||
# folders rather than files.
|
||||
selects = "directory"
|
||||
|
||||
def can_open(self, path: Path) -> bool:
|
||||
"""Recognise a OneLibrary drive, by layout and then by schema.
|
||||
|
||||
Both halves are needed. The layout check alone would accept any file
|
||||
called ``exportLibrary.db``; the schema check alone cannot run on a
|
||||
directory, and a drive is what a user actually picks.
|
||||
|
||||
It must also not collide with the Rekordbox driver, which probes for
|
||||
`master.db`. It cannot: both files are SQLCipher databases with no
|
||||
readable header, but they use DIFFERENT keys, so each driver's decrypt
|
||||
simply fails on the other's file. The table probe then makes it explicit
|
||||
rather than leaving the two relying on a key mismatch.
|
||||
"""
|
||||
layout = DriveLayout.locate(Path(path))
|
||||
if layout is None:
|
||||
return False
|
||||
return self._has_onelibrary_schema(layout.database)
|
||||
|
||||
@staticmethod
|
||||
def _has_onelibrary_schema(path: Path) -> bool:
|
||||
try:
|
||||
import sqlcipher3.dbapi2 as sqlcipher
|
||||
from pyrekordbox.devicelib_plus.database import BLOB
|
||||
from pyrekordbox.utils import deobfuscate
|
||||
except ImportError: # pragma: no cover — dependency missing
|
||||
return False
|
||||
con = None
|
||||
try:
|
||||
con = sqlcipher.connect(str(path))
|
||||
con.execute(f"PRAGMA key='{deobfuscate(BLOB)}'")
|
||||
# `content` is too generic a name to trust on its own, so the probe
|
||||
# asks for a pair only this schema has together.
|
||||
rows = con.execute(
|
||||
"SELECT name FROM sqlite_master WHERE type='table' "
|
||||
"AND name IN ('content','hotCueBankList')"
|
||||
).fetchall()
|
||||
return len(rows) == 2
|
||||
except Exception: # noqa: BLE001 — wrong key or not a database
|
||||
return False
|
||||
finally:
|
||||
if con is not None:
|
||||
try:
|
||||
con.close()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
def open(self, path: Path) -> OneLibraryAdapter:
|
||||
return OneLibraryAdapter(path)
|
||||
|
||||
def detect(self) -> list[dict]:
|
||||
return discovery.detect_libraries()
|
||||
|
||||
def describe(self, path: Path) -> dict:
|
||||
return discovery.describe(path)
|
||||
|
||||
def display_name_for(self, path: Path) -> str:
|
||||
"""What to call this library on screen: the DRIVE's name.
|
||||
|
||||
The filename is not a stable answer here. A OneLibrary library can be
|
||||
opened by its mount point OR by the database three levels inside it —
|
||||
`DriveLayout.locate()` accepts both on purpose — so the same stick would
|
||||
be "Hardy" opened one way and "exportLibrary.db" opened the other.
|
||||
"""
|
||||
layout = DriveLayout.locate(Path(path))
|
||||
return layout.root.name if layout is not None else Path(path).name
|
||||
|
||||
def restore(self, path: Path, data: bytes) -> None:
|
||||
"""Not supported: a drive is a database plus analysis files plus audio.
|
||||
|
||||
`capabilities.save.history` is False for the same reason, so nothing
|
||||
should reach this.
|
||||
"""
|
||||
raise NotImplementedError(
|
||||
"Konduktor does not version OneLibrary drives: the library is a "
|
||||
"database, N analysis files and the audio itself."
|
||||
)
|
||||
@@ -0,0 +1,321 @@
|
||||
"""Writing a OneLibrary USB drive from nothing.
|
||||
|
||||
The export target that matters most for a DJ: a stick CDJ-class hardware reads.
|
||||
|
||||
## What a drive is
|
||||
|
||||
The destination folder IS the drive root. Three things go in it:
|
||||
|
||||
<root>/PIONEER/rekordbox/exportLibrary.db the library (SQLCipher)
|
||||
<root>/PIONEER/USBANLZ/P0xx/xxxxxxxx/ANLZ0000.{DAT,EXT} per-track analysis
|
||||
<root>/… the audio, already copied
|
||||
|
||||
Audio is already on disk when this runs, laid out by the runner mirroring the
|
||||
source tree. Every path the database stores is **drive-relative with a leading
|
||||
slash** — `/House/track.mp3` — which is not a host path, and the reader's
|
||||
`DriveLayout.resolve()` is what joins it back to a mount point.
|
||||
|
||||
## What could not be reused, and why
|
||||
|
||||
`master.db`'s schema comes free from `pyrekordbox`'s ORM. This one has no ORM, so
|
||||
the DDL is the checked-in `fixtures/onelibrary/schema.sql` — 22 tables extracted
|
||||
from a real rekordbox 7 export, which is also what the read tests run against.
|
||||
|
||||
Cues are **not** in the `cue` table: rekordbox exports it empty and puts them in
|
||||
the analysis files. So `anlz_writer` builds those, with ANLZ's own **dense
|
||||
1-based** `hot_cue` numbering — not `master.db`'s sparse bank that skips 4.
|
||||
|
||||
## Deliberately not written
|
||||
|
||||
`PWAV`/`PWV2`-`PWV7` waveform tags, and the `cue` table's eight MPEG seek
|
||||
columns. Both are documented unknowns (see the OneLibrary handoff §7): a CDJ
|
||||
draws its waveform from those tags and seeks VBR MP3s with those columns, and
|
||||
whether their absence is unplayable, ugly or fine has never been measured. A
|
||||
guess here fails in a club rather than at a desk, so they are left out and said
|
||||
so rather than invented.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
|
||||
from ..rekordbox import anlz_writer as W
|
||||
from ..rekordbox.beatgrid import beats_from_markers
|
||||
from ..rekordbox.projection import render_key
|
||||
from .capabilities import capabilities_for
|
||||
from .layout import DB_SUBPATH
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
SCHEMA = Path(__file__).resolve().parents[3] / "fixtures" / "onelibrary" / "schema.sql"
|
||||
|
||||
#: rekordbox writes this in `property.dbVersion` on a real export.
|
||||
DB_VERSION = "1000"
|
||||
#: Seen on every track of a real export; semantics undocumented, copied as-is.
|
||||
ANALYSED_BITS = 41
|
||||
|
||||
OTHER_PLAYLIST = "Other"
|
||||
|
||||
|
||||
def _drive_relative(path: Path, root: Path) -> str:
|
||||
"""`/House/track.mp3` — drive-relative, WITH the leading slash.
|
||||
|
||||
The slash is not a host root. Joining one of these naively discards the
|
||||
mount point and silently yields a path that looks like an empty drive.
|
||||
"""
|
||||
return "/" + path.relative_to(root).as_posix()
|
||||
|
||||
|
||||
def _anlz_dir(drive_relative: str) -> str:
|
||||
"""`/PIONEER/USBANLZ/P0xx/xxxxxxxx` for a track.
|
||||
|
||||
rekordbox derives these two levels from a hash whose algorithm is not
|
||||
published. It does not need to match: the database stores the resulting path
|
||||
in `content.analysisDataFilePath` and that column is what a player follows.
|
||||
So this derives its own stable value in the same SHAPE, which keeps a drive
|
||||
recognisable to a human without pretending to reproduce rekordbox's scheme.
|
||||
"""
|
||||
digest = hashlib.sha1(drive_relative.encode("utf-8")).hexdigest().upper()
|
||||
return f"/PIONEER/USBANLZ/P0{digest[:2]}/{digest[2:10]}"
|
||||
|
||||
|
||||
class OneLibraryExporter:
|
||||
platform = "onelibrary"
|
||||
#: Relative to the drive root, which is what the destination folder is.
|
||||
library_filename = str(Path("PIONEER") / DB_SUBPATH)
|
||||
|
||||
def capabilities(self):
|
||||
"""What a drive can hold — no device, no path, no library to read.
|
||||
|
||||
`writable` is overridden to True. The adapter's own set says False
|
||||
because Konduktor cannot EDIT a plugged-in drive in place; an export
|
||||
target is a different question, and it is one Konduktor can now answer
|
||||
yes to. Leaving the adapter's answer here would have the UI report that
|
||||
the thing it just wrote cannot be written.
|
||||
"""
|
||||
return capabilities_for().model_copy(
|
||||
update={"writable": True, "readonly_cause": None}
|
||||
)
|
||||
|
||||
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
|
||||
import sqlcipher3.dbapi2 as sqlcipher
|
||||
from pyrekordbox.devicelib_plus.database import BLOB
|
||||
from pyrekordbox.utils import deobfuscate
|
||||
|
||||
root = Path(destination)
|
||||
library = root / "PIONEER" / DB_SUBPATH
|
||||
library.parent.mkdir(parents=True, exist_ok=True)
|
||||
if library.exists():
|
||||
library.unlink() # SQLCipher will not re-key an existing file
|
||||
|
||||
extra: list[Path] = []
|
||||
con = sqlcipher.connect(str(library))
|
||||
try:
|
||||
# The same universal key every vendor's drive uses — a OneLibrary
|
||||
# stick is readable by any of them, which is the point of it.
|
||||
con.execute(f"PRAGMA key='{deobfuscate(BLOB)}'")
|
||||
con.executescript(SCHEMA.read_text())
|
||||
extra += self._fill(con, payload, root)
|
||||
con.commit()
|
||||
finally:
|
||||
con.close()
|
||||
return WrittenLibrary(library=library, extra=extra)
|
||||
|
||||
# ---- the database --------------------------------------------------------
|
||||
|
||||
def _fill(self, con, payload: ExportPayload, root: Path) -> list[Path]:
|
||||
lookups = {name: {} for name in ("artist", "album", "genre", "label", "key")}
|
||||
written: list[Path] = []
|
||||
by_source: dict[str, int] = {}
|
||||
|
||||
for n, item in enumerate(payload.tracks, start=1):
|
||||
by_source[item.source_id] = n
|
||||
written += self._write_track(con, n, item, root, lookups)
|
||||
|
||||
self._write_playlists(con, payload, by_source)
|
||||
con.execute(
|
||||
"INSERT INTO property (deviceName, dbVersion, numberOfContents, "
|
||||
"createdDate, backGroundColorType, myTagMasterDBID) VALUES (?,?,?,?,?,?)",
|
||||
(payload.name, DB_VERSION, len(payload.tracks),
|
||||
date.today().isoformat(), 0, 0),
|
||||
)
|
||||
return written
|
||||
|
||||
@staticmethod
|
||||
def _lookup(con, table: str, cache: dict, name: str | None) -> int | None:
|
||||
"""Find-or-create a row in one of the name tables."""
|
||||
if not name:
|
||||
return None
|
||||
if name in cache:
|
||||
return cache[name]
|
||||
column = f"{table}_id"
|
||||
row = con.execute(f"SELECT {column} FROM {table} WHERE name = ?", (name,)).fetchone()
|
||||
if row:
|
||||
cache[name] = row[0]
|
||||
return row[0]
|
||||
cur = con.execute(f"INSERT INTO {table} (name) VALUES (?)", (name,))
|
||||
cache[name] = cur.lastrowid
|
||||
return cur.lastrowid
|
||||
|
||||
def _write_track(self, con, content_id: int, item: ExportTrack,
|
||||
root: Path, lookups: dict) -> list[Path]:
|
||||
track = item.track
|
||||
rel = _drive_relative(item.destination, root)
|
||||
anlz_rel = f"{_anlz_dir(rel)}/ANLZ0000.DAT"
|
||||
|
||||
try:
|
||||
size = item.destination.stat().st_size
|
||||
except OSError:
|
||||
size = 0
|
||||
|
||||
con.execute(
|
||||
"INSERT INTO content (content_id, title, titleForSearch, bpmx100, length, "
|
||||
"trackNo, artist_id_artist, album_id, genre_id, label_id, key_id, "
|
||||
"djComment, rating, releaseDate, dateAdded, path, fileName, fileSize, "
|
||||
"fileType, bitrate, samplingRate, isHotCueAutoLoadOn, "
|
||||
"isKuvoDeliverStatusOn, masterDbId, masterContentId, "
|
||||
"analysisDataFilePath, analysedBits, hasModified, cueUpdateCount, "
|
||||
"analysisDataUpdateCount, informationUpdateCount) "
|
||||
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
|
||||
(
|
||||
content_id, track.title, (track.title or "").lower(),
|
||||
int(round((track.bpm or 0) * 100)) or None, track.length,
|
||||
None,
|
||||
self._lookup(con, "artist", lookups["artist"], track.artist),
|
||||
self._lookup(con, "album", lookups["album"], track.album),
|
||||
self._lookup(con, "genre", lookups["genre"], track.genre),
|
||||
self._lookup(con, "label", lookups["label"], track.label),
|
||||
# NOT `track.key` — that is the SOURCE platform's notation, and
|
||||
# writing Traktor's "10m" into a Pioneer library shows "10m"
|
||||
# where the deck expects "Cm". Rendered from the parsed wheel.
|
||||
self._lookup(con, "key", lookups["key"],
|
||||
render_key(track.key_wheel, track.key_mode)),
|
||||
track.comment, track.rating or 0, track.release_date,
|
||||
date.today().isoformat(), rel, item.destination.name, size,
|
||||
1, track.bitrate, None, 1, 1, 0, content_id,
|
||||
anlz_rel, ANALYSED_BITS, 0, 0, 0, 0,
|
||||
),
|
||||
)
|
||||
return self._write_anlz(item, rel, root / anlz_rel.lstrip("/"))
|
||||
|
||||
# ---- the analysis files --------------------------------------------------
|
||||
|
||||
def _write_anlz(self, item: ExportTrack, rel: str, dat: Path) -> list[Path]:
|
||||
"""The `.DAT` and, when there are cues beyond pad C, the `.EXT`.
|
||||
|
||||
Always both when there are any cues: `PCO2` lives only in the `.EXT` and
|
||||
is the complete list, which is what the reader prefers.
|
||||
"""
|
||||
cues = self._cue_dicts(item)
|
||||
beats = self._beats(item)
|
||||
|
||||
tags = [W.path_tag(rel)]
|
||||
if beats:
|
||||
tags.append(W.beatgrid_tag(beats))
|
||||
tags += W.cue_tags(cues, extended=False)
|
||||
written = [W.write_anlz(dat, tags)]
|
||||
|
||||
if cues:
|
||||
written.append(
|
||||
W.write_anlz(dat.with_suffix(".EXT"),
|
||||
[W.path_tag(rel), *W.cue_tags(cues, extended=True)])
|
||||
)
|
||||
return written
|
||||
|
||||
@staticmethod
|
||||
def _beats(item: ExportTrack) -> list[tuple[int, float, float]]:
|
||||
"""Every beat, expanded from the generic marker list.
|
||||
|
||||
A Pioneer grid has no tempo markers — it is a flat list of beats — so a
|
||||
flexible multi-tempo grid crosses by expansion here and is collapsed
|
||||
back by `markers_from_beats` on read. Both directions share one
|
||||
definition of where a tempo change starts.
|
||||
"""
|
||||
cues = item.cues
|
||||
if not cues or not cues.grid_markers:
|
||||
return []
|
||||
duration = float(item.track.length or 0) or (cues.grid_markers[-1].start + 60.0)
|
||||
nums, bpms, times = beats_from_markers(cues.grid_markers, duration)
|
||||
return list(zip(nums, bpms, times))
|
||||
|
||||
@staticmethod
|
||||
def _cue_dicts(item: ExportTrack) -> list[dict]:
|
||||
"""Generic cues in the shape `anlz_writer` packs.
|
||||
|
||||
Slot numbering is ANLZ's own: **dense 1-based**, 0 for a memory cue.
|
||||
The generic model's `slot` is 0-based, so every hot cue is +1. Reuse
|
||||
`master.db`'s sparse bank here and every cue from pad D lands one pad
|
||||
too far along.
|
||||
"""
|
||||
out: list[dict] = []
|
||||
for cue in (item.cues.cues if item.cues else []):
|
||||
is_loop = cue.type == "loop" or cue.length > 0
|
||||
out.append({
|
||||
"hot_cue": 0 if cue.role == "memory" or cue.slot is None else cue.slot + 1,
|
||||
"kind": 2 if is_loop else 1,
|
||||
"time_ms": int(round(cue.start * 1000)),
|
||||
"loop_ms": int(round((cue.start + cue.length) * 1000)) if is_loop else None,
|
||||
"rgb": _rgb(cue.color),
|
||||
"beats": None,
|
||||
})
|
||||
return out
|
||||
|
||||
# ---- playlists -----------------------------------------------------------
|
||||
|
||||
def _write_playlists(self, con, payload: ExportPayload, by_source: dict) -> None:
|
||||
"""One folder named after the export, with the tree preserved under it.
|
||||
|
||||
`playlist` is a flat table with `playlist_id_parent`, so folders and
|
||||
playlists are the same row kind told apart by `attribute` (1 = folder).
|
||||
"""
|
||||
next_id = [0]
|
||||
|
||||
def add(name: str, parent: int | None, *, folder: bool) -> int:
|
||||
next_id[0] += 1
|
||||
con.execute(
|
||||
"INSERT INTO playlist (playlist_id, sequenceNo, name, attribute, "
|
||||
"playlist_id_parent) VALUES (?,?,?,?,?)",
|
||||
(next_id[0], next_id[0], name, 1 if folder else 0, parent),
|
||||
)
|
||||
return next_id[0]
|
||||
|
||||
root = add(payload.name, None, folder=True)
|
||||
folders: dict[tuple[str, ...], int] = {(): root}
|
||||
|
||||
for playlist in payload.playlists:
|
||||
parent = root
|
||||
for depth in range(1, len(playlist.folders) + 1):
|
||||
branch = tuple(playlist.folders[:depth])
|
||||
if branch not in folders:
|
||||
folders[branch] = add(branch[-1], folders[branch[:-1]], folder=True)
|
||||
parent = folders[branch]
|
||||
self._fill_playlist(con, add(playlist.name, parent, folder=False),
|
||||
playlist.track_ids, by_source)
|
||||
|
||||
claimed = {t for p in payload.playlists for t in p.track_ids}
|
||||
loose = [t.source_id for t in payload.tracks if t.source_id not in claimed]
|
||||
if loose:
|
||||
self._fill_playlist(con, add(OTHER_PLAYLIST, root, folder=False),
|
||||
loose, by_source)
|
||||
|
||||
@staticmethod
|
||||
def _fill_playlist(con, playlist_id: int, track_ids: list[str], by_source: dict) -> None:
|
||||
for seq, source_id in enumerate(track_ids, start=1):
|
||||
content_id = by_source.get(source_id)
|
||||
if content_id is not None:
|
||||
con.execute(
|
||||
"INSERT INTO playlist_content (playlist_id, content_id, sequenceNo) "
|
||||
"VALUES (?,?,?)", (playlist_id, content_id, seq)
|
||||
)
|
||||
|
||||
|
||||
def _rgb(color: str | None) -> tuple[int, int, int] | None:
|
||||
if not color or not color.startswith("#") or len(color) != 7:
|
||||
return None
|
||||
try:
|
||||
return (int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16))
|
||||
except ValueError:
|
||||
return None
|
||||
@@ -0,0 +1,103 @@
|
||||
"""Where things live on a OneLibrary drive.
|
||||
|
||||
A OneLibrary library is a **removable drive**, not a file, and that is the one
|
||||
structural fact that separates this adapter from every other one. Everything the
|
||||
library refers to — the audio, the analysis files, the artwork — is stored
|
||||
DRIVE-RELATIVE (``/Contents/Loopmasters/Demo Track 1.mp3``), because the same
|
||||
stick must resolve on a CDJ, on macOS and on Windows, where it is mounted at
|
||||
three different places. Nothing inside the database is an absolute host path.
|
||||
|
||||
So resolving a stored path means joining it to the mount point, and that is what
|
||||
this module exists to do. It is kept separate from the store because it is also
|
||||
the knowledge a future *export* would need to lay a drive out from nothing.
|
||||
|
||||
Two layout details are measured from a real rekordbox 7 export rather than
|
||||
assumed:
|
||||
|
||||
* the database is at ``PIONEER/rekordbox/exportLibrary.db``, alongside — not
|
||||
instead of — the legacy ``export.pdb``. Both formats coexist on one drive,
|
||||
and newer players prefer OneLibrary when they find it.
|
||||
* analysis files sit under ``PIONEER/USBANLZ/P0<xx>/<8 hex>/ANLZ0000.*``,
|
||||
where the two directory levels are a hash of the track's path. Konduktor
|
||||
never has to compute that hash to READ, because ``content.analysisDataFilePath``
|
||||
stores the resulting path outright — it would only matter for writing.
|
||||
|
||||
``.PIONEER`` is accepted as well as ``PIONEER``. Traktor's own OneLibrary writer
|
||||
looks for both, so a drive written by it may use the dot-prefixed (hidden) form.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
# In preference order: a drive may legitimately carry either spelling, and the
|
||||
# visible one is what rekordbox itself writes.
|
||||
PIONEER_DIRS = ("PIONEER", ".PIONEER")
|
||||
DB_SUBPATH = Path("rekordbox") / "exportLibrary.db"
|
||||
|
||||
# The analysis file the database points at is the `.DAT`; its siblings differ
|
||||
# only by extension. `.EXT` carries the complete cue list and the colour
|
||||
# waveforms, `.2EX` the newer high-resolution ones.
|
||||
ANLZ_EXTENDED = ".EXT"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DriveLayout:
|
||||
"""A located OneLibrary drive: its mount point and its database."""
|
||||
|
||||
root: Path
|
||||
database: Path
|
||||
|
||||
@classmethod
|
||||
def locate(cls, path: Path) -> "DriveLayout | None":
|
||||
"""Find the layout for `path`, or None if it is not a OneLibrary drive.
|
||||
|
||||
Accepts either end of the drive deliberately: the MOUNT POINT, which is
|
||||
what discovery finds and what a user picks in a file browser, or the
|
||||
``exportLibrary.db`` ITSELF, which is what someone reaches by drilling
|
||||
into the folder or by re-opening a remembered path. Both name the same
|
||||
library, and refusing one of them would make the picker and the
|
||||
last-opened shortcut disagree about what a valid library is.
|
||||
"""
|
||||
path = Path(path)
|
||||
try:
|
||||
if path.is_file():
|
||||
# .../PIONEER/rekordbox/exportLibrary.db -> the drive is 3 up.
|
||||
if path.name.lower() != "exportLibrary.db".lower():
|
||||
return None
|
||||
root = path.parent.parent.parent
|
||||
if path.parent.parent.name not in PIONEER_DIRS:
|
||||
return None
|
||||
return cls(root=root, database=path)
|
||||
if path.is_dir():
|
||||
for pioneer in PIONEER_DIRS:
|
||||
db = path / pioneer / DB_SUBPATH
|
||||
if db.is_file():
|
||||
return cls(root=path, database=db)
|
||||
except OSError:
|
||||
return None
|
||||
return None
|
||||
|
||||
def resolve(self, drive_relative: str | None) -> Path | None:
|
||||
"""A stored drive-relative path as a real path on this host.
|
||||
|
||||
Stored paths are POSIX-style and lead with a slash. That leading slash is
|
||||
NOT a host root — treating it as one is the mistake this method exists to
|
||||
prevent, since ``Path('/Volumes/X') / '/Contents/a.mp3'`` silently
|
||||
discards the mount point and yields ``/Contents/a.mp3``.
|
||||
"""
|
||||
if not drive_relative:
|
||||
return None
|
||||
relative = str(drive_relative).replace("\\", "/").lstrip("/")
|
||||
if not relative:
|
||||
return None
|
||||
return self.root / relative
|
||||
|
||||
def extended_anlz(self, dat_path: Path) -> Path:
|
||||
"""The `.EXT` beside a given `.DAT`.
|
||||
|
||||
Cues are read from the `.EXT`, not the `.DAT` the database points at:
|
||||
see `cues.py` for why that distinction is load-bearing rather than a
|
||||
preference.
|
||||
"""
|
||||
return dat_path.with_suffix(ANLZ_EXTENDED)
|
||||
@@ -0,0 +1,118 @@
|
||||
"""OneLibrary rows -> the generic projection.
|
||||
|
||||
The only place a ``devicelib_plus`` ORM object becomes a generic `Track` /
|
||||
`TrackCues`. Everything above this file sees generic types exclusively.
|
||||
|
||||
Field conventions are read off a real rekordbox 7 export rather than guessed:
|
||||
|
||||
* ``bpmx100`` is the tempo in hundredths, and it is a DISPLAY value — the real
|
||||
grid is per-beat in the ANLZ file, and a variable-tempo track stores only its
|
||||
first tempo here.
|
||||
* ``rating`` is 0-5 directly, like `master.db` and unlike Traktor's /51.
|
||||
* ``length`` is whole seconds.
|
||||
* ``path`` is drive-relative with a leading slash; the store resolves it.
|
||||
* dates arrive as `datetime` from the ORM, not as strings.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from ...core.model import GridMarker, Track, TrackCues
|
||||
from ..rekordbox.projection import parse_key
|
||||
|
||||
|
||||
def _name_of(related) -> str | None:
|
||||
"""A joined lookup row's display name, or None when unset."""
|
||||
if related is None:
|
||||
return None
|
||||
value = getattr(related, "name", None)
|
||||
return str(value) if value else None
|
||||
|
||||
|
||||
def _iso_date(value) -> str | None:
|
||||
"""`YYYY-MM-DD` from whatever the column holds.
|
||||
|
||||
The ORM converts the stored strings to `datetime`, so this takes the date
|
||||
part of one — but a drive written by another vendor's software may well
|
||||
store a plain string, and passing that through unchanged is better than
|
||||
losing it.
|
||||
"""
|
||||
if not value:
|
||||
return None
|
||||
date = getattr(value, "date", None)
|
||||
if callable(date):
|
||||
try:
|
||||
return date().isoformat()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
text = str(value).strip()
|
||||
return text.split(" ")[0] if text else None
|
||||
|
||||
|
||||
def _bpm(row) -> float | None:
|
||||
raw = getattr(row, "bpmx100", None)
|
||||
if not raw:
|
||||
return None
|
||||
return round(int(raw) / 100.0, 2)
|
||||
|
||||
|
||||
def to_track(row, drive_path: str | None = None) -> Track:
|
||||
"""Project one ``Content`` row.
|
||||
|
||||
**The three count fields are approximations here**, and deliberately so. Cues
|
||||
and the beatgrid both live in the track's ANLZ files, and parsing a track's
|
||||
`.EXT` costs ~23 ms — ~23 s for a 1,000-track drive if done at open. So a
|
||||
track that has an analysis file and a tempo is reported as having one grid
|
||||
marker (constant tempo, true for all but a fraction of a percent of tracks)
|
||||
and no cues, and all three are corrected the moment the track's cues are
|
||||
actually read. `adapter.track_cues` is where that happens.
|
||||
|
||||
Reporting zero cues rather than a guess is the honest direction to be wrong
|
||||
in: a count that appears from nowhere on selection reads as the detail
|
||||
arriving, whereas one that shrinks reads as data being lost.
|
||||
"""
|
||||
key_name = _name_of(getattr(row, "key", None))
|
||||
wheel, mode = parse_key(key_name)
|
||||
has_analysis = bool(getattr(row, "analysisDataFilePath", None))
|
||||
bpm = _bpm(row)
|
||||
return Track(
|
||||
id=str(getattr(row, "path", "") or ""),
|
||||
artist=_name_of(getattr(row, "artist", None)),
|
||||
title=getattr(row, "title", None),
|
||||
album=_name_of(getattr(row, "album", None)),
|
||||
genre=_name_of(getattr(row, "genre", None)),
|
||||
label=_name_of(getattr(row, "label", None)),
|
||||
remixer=_name_of(getattr(row, "remixer", None)),
|
||||
# OneLibrary has `composer` and `lyricist`, neither of which is Traktor's
|
||||
# "producer" or "mix", so nothing is mapped onto them approximately.
|
||||
producer=None,
|
||||
mix=None,
|
||||
comment=getattr(row, "djComment", None),
|
||||
bpm=bpm,
|
||||
key=key_name,
|
||||
key_wheel=wheel,
|
||||
key_mode=mode,
|
||||
rating=max(0, min(5, int(getattr(row, "rating", 0) or 0))),
|
||||
playcount=getattr(row, "djPlayCount", None),
|
||||
length=getattr(row, "length", None),
|
||||
bitrate=getattr(row, "bitrate", None),
|
||||
import_date=_iso_date(getattr(row, "dateAdded", None)),
|
||||
last_played=None, # the drive records history as playlists, not per track
|
||||
release_date=_iso_date(getattr(row, "releaseDate", None))
|
||||
or (str(getattr(row, "releaseYear", "") or "") or None),
|
||||
filepath=drive_path,
|
||||
cue_count=0,
|
||||
hotcue_count=0,
|
||||
grid_marker_count=1 if (bpm and has_analysis) else 0,
|
||||
grid_locked=False, # OneLibrary has no grid lock
|
||||
media_kind="audio",
|
||||
)
|
||||
|
||||
|
||||
def to_track_cues(cues: list, grid_markers: list[GridMarker]) -> TrackCues:
|
||||
"""Project a track's cues and beatgrid.
|
||||
|
||||
`cues` are already generic — see `store.cues` for why that boundary sits
|
||||
where it does — so this is the assembly point rather than a translation.
|
||||
Nothing here is editable: a OneLibrary drive is read-only in Konduktor, and
|
||||
`capabilities.writable` says so at the library level.
|
||||
"""
|
||||
return TrackCues(grid_markers=grid_markers, grid_locked=False, cues=list(cues))
|
||||
@@ -0,0 +1,248 @@
|
||||
"""The retained native model for a OneLibrary drive.
|
||||
|
||||
Owns the open ``exportLibrary.db`` and the drive layout around it, and is the
|
||||
only place a ``pyrekordbox.devicelib_plus`` row or an ANLZ tag is touched.
|
||||
|
||||
The database is SQLCipher-encrypted SQLite, like Rekordbox's ``master.db``, but
|
||||
with a **different and universal key**: every OneLibrary drive from every vendor
|
||||
is encrypted with the same one, which is what makes the format readable across
|
||||
brands at all. `pyrekordbox` carries it, so nothing here needs to know it.
|
||||
|
||||
**Analysis files are parsed lazily, and that is a measurement, not a
|
||||
preference.** The beatgrid and the cues both live in the per-track ANLZ files,
|
||||
and parsing one costs ~2 ms for the `.DAT` but ~23 ms for the `.EXT`, which
|
||||
carries the colour waveforms as well. Reading every track's `.EXT` at open would
|
||||
cost ~23 s on a 1,000-track drive — so it happens on demand and is cached, the
|
||||
same bargain the Rekordbox adapter strikes for its grids. The visible
|
||||
consequence is that cue and marker counts are approximate in the library table
|
||||
until a track's cues are actually read; see `projection.to_track`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
from ...core.adapter import LibraryNotSupported, NotFound
|
||||
from ...core.model import CuePoint
|
||||
from . import beatgrid, cues as cue_reader
|
||||
from .layout import DriveLayout
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class OneLibraryStore:
|
||||
def __init__(self, path: Path):
|
||||
layout = DriveLayout.locate(Path(path))
|
||||
if layout is None:
|
||||
raise LibraryNotSupported(f"No OneLibrary database found at {path}")
|
||||
self.layout = layout
|
||||
self.path = layout.database
|
||||
self._db = None
|
||||
# Parsed ANLZ, keyed by track id. Two caches because the two files cost
|
||||
# an order of magnitude apart: a grid read must not drag in the .EXT.
|
||||
self._dat_cache: dict[str, object | None] = {}
|
||||
self._ext_cache: dict[str, object | None] = {}
|
||||
self._content_cache: list | None = None
|
||||
self._by_id: dict[str, object] | None = None
|
||||
self._load()
|
||||
|
||||
# ---- open / close ----------------------------------------------------
|
||||
def _load(self) -> None:
|
||||
try:
|
||||
from pyrekordbox.devicelib_plus import DeviceLibraryPlus
|
||||
except ImportError as ex: # pragma: no cover — dependency missing
|
||||
raise LibraryNotSupported(
|
||||
"Reading OneLibrary drives needs pyrekordbox with devicelib_plus"
|
||||
) from ex
|
||||
try:
|
||||
self._db = DeviceLibraryPlus(str(self.path))
|
||||
except Exception as ex: # noqa: BLE001 — surfaced as a clean 4xx
|
||||
raise LibraryNotSupported(f"Could not open OneLibrary database: {ex}") from ex
|
||||
self._dat_cache.clear()
|
||||
self._ext_cache.clear()
|
||||
self._content_cache = None
|
||||
self._by_id = None
|
||||
|
||||
def close(self) -> None:
|
||||
"""Release the database AND the underlying file handle.
|
||||
|
||||
Disposing the engine matters more here than anywhere else: the library
|
||||
is on a REMOVABLE drive, and a lingering handle is what makes a stick
|
||||
refuse to eject. `DeviceLibraryPlus.close()` only ends the session, so
|
||||
the engine is disposed explicitly — the same gap the Rekordbox store
|
||||
had to close for `master.db`.
|
||||
"""
|
||||
db, self._db = self._db, None
|
||||
if db is None:
|
||||
return
|
||||
try:
|
||||
db.close()
|
||||
except Exception: # noqa: BLE001 — closing must not raise
|
||||
log.debug("OneLibrary session close failed", exc_info=True)
|
||||
engine = getattr(db, "engine", None)
|
||||
if engine is not None:
|
||||
try:
|
||||
engine.dispose()
|
||||
except Exception: # noqa: BLE001
|
||||
log.debug("OneLibrary engine dispose failed", exc_info=True)
|
||||
|
||||
def _require_db(self):
|
||||
if self._db is None:
|
||||
raise LibraryNotSupported("The OneLibrary database is closed")
|
||||
return self._db
|
||||
|
||||
# ---- identity --------------------------------------------------------
|
||||
@property
|
||||
def device_name(self) -> str | None:
|
||||
"""The drive's own name, which is NOT the volume label.
|
||||
|
||||
Stored in `property.deviceName` and often blank — rekordbox leaves it
|
||||
empty unless the user names the device — so the mount point's name is
|
||||
the fallback a person will actually recognise.
|
||||
"""
|
||||
try:
|
||||
row = self._require_db().get_property().first()
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
name = (getattr(row, "deviceName", "") or "").strip() if row is not None else ""
|
||||
return name or self.layout.root.name or None
|
||||
|
||||
@property
|
||||
def db_version(self) -> str | None:
|
||||
try:
|
||||
row = self._require_db().get_property().first()
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
value = getattr(row, "dbVersion", None) if row is not None else None
|
||||
return str(value) if value else None
|
||||
|
||||
# ---- tracks ----------------------------------------------------------
|
||||
def iter_content(self) -> list:
|
||||
"""Every track row, cached for the life of the open library."""
|
||||
if self._content_cache is None:
|
||||
rows = list(self._require_db().get_content())
|
||||
self._content_cache = rows
|
||||
self._by_id = {self.track_id(r): r for r in rows}
|
||||
return self._content_cache
|
||||
|
||||
@staticmethod
|
||||
def track_id(row) -> str:
|
||||
"""A track's stable id: its DRIVE-RELATIVE path.
|
||||
|
||||
Not `content_id`, which is a row number rekordbox reassigns from 1 every
|
||||
time it rewrites the drive — so it would change under a user who merely
|
||||
re-exported, breaking every playlist reference Konduktor had remembered.
|
||||
The path is stable, unique on the drive, and is also the key a future
|
||||
import would match against a Traktor collection, so it is the honest
|
||||
identity here.
|
||||
"""
|
||||
return str(getattr(row, "path", "") or f"content:{getattr(row, 'content_id', '')}")
|
||||
|
||||
def content(self, track_id: str):
|
||||
self.iter_content()
|
||||
row = (self._by_id or {}).get(str(track_id))
|
||||
if row is None:
|
||||
raise NotFound(f"No track {track_id!r} on this OneLibrary drive")
|
||||
return row
|
||||
|
||||
def audio_path(self, track_id: str) -> Path | None:
|
||||
return self.layout.resolve(getattr(self.content(track_id), "path", None))
|
||||
|
||||
def all_audio_paths(self) -> list[str]:
|
||||
out: list[str] = []
|
||||
for row in self.iter_content():
|
||||
resolved = self.layout.resolve(getattr(row, "path", None))
|
||||
if resolved is not None:
|
||||
out.append(str(resolved))
|
||||
return out
|
||||
|
||||
# ---- analysis files --------------------------------------------------
|
||||
def _anlz(self, track_id: str, *, extended: bool):
|
||||
"""The parsed `.DAT` or `.EXT` for a track, or None if unreadable.
|
||||
|
||||
A missing or corrupt analysis file is a normal state on a real drive —
|
||||
an unanalysed track has none — so it is cached as None and never raised.
|
||||
"""
|
||||
cache = self._ext_cache if extended else self._dat_cache
|
||||
key = str(track_id)
|
||||
if key in cache:
|
||||
return cache[key]
|
||||
|
||||
cache[key] = None
|
||||
row = self.content(track_id)
|
||||
dat = self.layout.resolve(getattr(row, "analysisDataFilePath", None))
|
||||
if dat is None:
|
||||
return None
|
||||
target = self.layout.extended_anlz(dat) if extended else dat
|
||||
try:
|
||||
if not target.is_file():
|
||||
return None
|
||||
from pyrekordbox.anlz import AnlzFile
|
||||
|
||||
cache[key] = AnlzFile.parse_file(str(target))
|
||||
except Exception: # noqa: BLE001 — a bad file must not break browsing
|
||||
log.debug("Could not parse ANLZ %s", target, exc_info=True)
|
||||
return None
|
||||
return cache[key]
|
||||
|
||||
def anlz_grid(self, track_id: str) -> tuple[list[float], list[float]] | None:
|
||||
"""The per-beat ``(times, bpms)`` from the track's `PQTZ` tag.
|
||||
|
||||
`PQTZ` is in the `.DAT`, which is the cheap file — a grid read does not
|
||||
pay for the `.EXT`'s waveforms.
|
||||
"""
|
||||
anlz = self._anlz(track_id, extended=False)
|
||||
if anlz is None:
|
||||
return None
|
||||
return beatgrid.beats_from_pqtz(anlz)
|
||||
|
||||
def cues(self, track_id: str) -> list[CuePoint]:
|
||||
"""The track's cues, already generic.
|
||||
|
||||
Unusually for a store, this returns generic types rather than native
|
||||
rows: the native shape is a pair of parsed tag containers whose entries
|
||||
only mean anything once merged across two files, and handing that to the
|
||||
projection would put ANLZ knowledge on both sides of the boundary.
|
||||
"""
|
||||
return cue_reader.cues_from_anlz(
|
||||
self._anlz(track_id, extended=False),
|
||||
self._anlz(track_id, extended=True),
|
||||
)
|
||||
|
||||
# ---- playlists -------------------------------------------------------
|
||||
def playlists(self) -> list:
|
||||
return list(self._require_db().get_playlist())
|
||||
|
||||
def count_playlists(self) -> int:
|
||||
try:
|
||||
return self._require_db().get_playlist().count()
|
||||
except Exception: # noqa: BLE001
|
||||
return 0
|
||||
|
||||
def playlist_song_ids(self, node_id: str) -> list[str]:
|
||||
"""Track ids in a playlist, in the order the drive stores them.
|
||||
|
||||
`playlist_content` joins on `content_id`, but Konduktor's track id is the
|
||||
path (see `track_id`), so the row numbers are translated here rather than
|
||||
leaking a second notion of identity upward.
|
||||
"""
|
||||
try:
|
||||
pid = int(node_id)
|
||||
except (TypeError, ValueError):
|
||||
return []
|
||||
self.iter_content()
|
||||
by_content_id = {
|
||||
int(getattr(r, "content_id", -1)): self.track_id(r) for r in self.iter_content()
|
||||
}
|
||||
rows = [
|
||||
r
|
||||
for r in self._require_db().get_playlist_content()
|
||||
if int(getattr(r, "playlist_id", -1)) == pid
|
||||
]
|
||||
rows.sort(key=lambda r: int(getattr(r, "sequenceNo", 0) or 0))
|
||||
out: list[str] = []
|
||||
for r in rows:
|
||||
track_id = by_content_id.get(int(getattr(r, "content_id", -1)))
|
||||
if track_id is not None:
|
||||
out.append(track_id)
|
||||
return out
|
||||
@@ -0,0 +1,17 @@
|
||||
"""The Rekordbox adapter: ``master.db`` (SQLCipher) via ``pyrekordbox``.
|
||||
|
||||
Importing this package registers the platform for READING and editing a library
|
||||
in place, and as an export TARGET for writing a fresh one. Two registries,
|
||||
because opening a library and creating one from nothing are different
|
||||
capabilities.
|
||||
"""
|
||||
from ...core import export as core_export
|
||||
from ...core import registry
|
||||
from .driver import RekordboxDriver
|
||||
from .export import RekordboxExporter
|
||||
|
||||
REKORDBOX = RekordboxDriver()
|
||||
registry.register(REKORDBOX)
|
||||
|
||||
REKORDBOX_EXPORTER = RekordboxExporter()
|
||||
core_export.register(REKORDBOX_EXPORTER)
|
||||
@@ -0,0 +1,414 @@
|
||||
"""The Rekordbox adapter: owns the native database and the generic projection.
|
||||
|
||||
Mirrors `adapters.traktor.adapter`. It holds:
|
||||
|
||||
* a ``RekordboxStore`` — the retained NATIVE model (the open ``master.db``),
|
||||
* a ``TrackIndex`` — the generic READ projection built from it.
|
||||
|
||||
**Track metadata and playlists are writable; cues and the beatgrid are not
|
||||
yet.** Those two are separate native stores (two DB tables kept consistent, and
|
||||
the per-track ANLZ analysis files), so they keep refusing until milestone 3 —
|
||||
and `capabilities.cues.editable` / `grid.editable` say so, which is what the UI
|
||||
actually gates on. The raise is the backstop, not the mechanism.
|
||||
|
||||
Writes are refused entirely, and permanently, on a **cloud-synced** library:
|
||||
propagating a bad sync state to the user's other machines is not something
|
||||
version history can undo — especially here, where there is no version history at
|
||||
all. That check lives at the top of every command path so no future command can
|
||||
forget it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from ...core.adapter import Unsupported
|
||||
from ...core.capabilities import Capabilities
|
||||
from ...core.model import GridMarker, PlaylistNode, Track, TrackCues
|
||||
from ...core.pathmap import PathMapping, common_dir_prefix
|
||||
from ...core.query import TrackIndex
|
||||
from . import capabilities as caps
|
||||
from . import projection
|
||||
from .store import RekordboxStore
|
||||
|
||||
|
||||
class RekordboxAdapter:
|
||||
platform = "rekordbox"
|
||||
|
||||
def __init__(self, path: Path):
|
||||
self.path = Path(path)
|
||||
self._store = RekordboxStore(self.path)
|
||||
self._index = TrackIndex()
|
||||
self._cloud_synced = self._store.cloud_synced
|
||||
self._rebuild()
|
||||
|
||||
# ---- projection maintenance -----------------------------------------
|
||||
def _rebuild(self) -> None:
|
||||
kinds = self._store.cue_kinds()
|
||||
self._index.rebuild(
|
||||
[
|
||||
projection.to_track(row, kinds.get(str(row.ID), ()))
|
||||
for row in self._store.iter_content()
|
||||
]
|
||||
)
|
||||
|
||||
def _refresh_cues(self, track_id: str) -> TrackCues:
|
||||
"""Re-project a track AND return its fresh cues.
|
||||
|
||||
Every mutating cue/grid command ends here: the contract is that a command
|
||||
returns the refreshed projection, so a route can never serve a stale one.
|
||||
"""
|
||||
self._refresh(track_id)
|
||||
return self.track_cues(track_id) or TrackCues()
|
||||
|
||||
def _refresh(self, track_id: str) -> None:
|
||||
"""Re-project one track after a command, so the UI cannot go stale.
|
||||
|
||||
Every mutating command must end in this — a forgotten refresh is a
|
||||
silently stale projection that no byte- or row-level test would catch.
|
||||
"""
|
||||
kinds = self._store.cue_kinds()
|
||||
row = self._store.content(track_id)
|
||||
self._index.replace(projection.to_track(row, kinds.get(str(row.ID), ())))
|
||||
|
||||
def close(self) -> None:
|
||||
"""Release the database connection.
|
||||
|
||||
Rekordbox's library is a live SQLite file, not a document parsed into
|
||||
memory: leaving the connection open keeps a file handle (and possibly a
|
||||
`-wal`) around, so an adapter that is being replaced must be closed.
|
||||
"""
|
||||
self._store.close()
|
||||
|
||||
def reload(self) -> None:
|
||||
self._store._load()
|
||||
self._cloud_synced = self._store.cloud_synced
|
||||
self._rebuild()
|
||||
|
||||
# ---- identity --------------------------------------------------------
|
||||
def capabilities(self) -> Capabilities:
|
||||
return caps.capabilities_for(
|
||||
self.path,
|
||||
cloud_synced=self._cloud_synced,
|
||||
editable_fields=sorted(RekordboxStore.EDITABLE_FIELDS),
|
||||
)
|
||||
|
||||
@property
|
||||
def cloud_synced(self) -> bool:
|
||||
return self._cloud_synced
|
||||
|
||||
# ---- read ------------------------------------------------------------
|
||||
@property
|
||||
def tracks(self) -> list[Track]:
|
||||
return self._index.tracks
|
||||
|
||||
@property
|
||||
def by_key(self) -> dict[str, Track]:
|
||||
return self._index.by_key
|
||||
|
||||
def track(self, track_id: str) -> Track | None:
|
||||
return self._index.get(track_id)
|
||||
|
||||
def query_tracks(self, **kw):
|
||||
return self._index.query_tracks(**kw)
|
||||
|
||||
def facets(self):
|
||||
return self._index.facets()
|
||||
|
||||
def stats(self, playlist_count: int):
|
||||
return self._index.stats(playlist_count)
|
||||
|
||||
def playlist_count(self) -> int:
|
||||
return self._store.count_playlists()
|
||||
|
||||
def track_cues(self, track_id: str) -> TrackCues | None:
|
||||
if self._index.get(track_id) is None:
|
||||
return None
|
||||
cues = projection.to_track_cues(
|
||||
self._store.cues(track_id), self._store.anlz_grid(track_id)
|
||||
)
|
||||
# The track projection carries an APPROXIMATE grid_marker_count until the
|
||||
# grid is actually read (see projection.to_track). This is that moment —
|
||||
# correct it, so the library table stops showing the guess.
|
||||
track = self._index.get(track_id)
|
||||
if track is not None:
|
||||
track.grid_marker_count = len(cues.grid_markers)
|
||||
return cues
|
||||
|
||||
# ---- playlists -------------------------------------------------------
|
||||
def playlist_tree(self) -> list[PlaylistNode]:
|
||||
"""Rekordbox stores the tree as a flat table with ``ParentID`` links."""
|
||||
from pyrekordbox.masterdb import models as tables
|
||||
|
||||
rows = self._store.playlists()
|
||||
folder = int(tables.PlaylistType.FOLDER)
|
||||
smart = int(tables.PlaylistType.SMART_PLAYLIST)
|
||||
writable = not self._cloud_synced
|
||||
|
||||
nodes: dict[str, PlaylistNode] = {}
|
||||
parents: dict[str, str] = {}
|
||||
for r in rows:
|
||||
attribute = int(r.Attribute or 0)
|
||||
kind = "folder" if attribute == folder else ("smart" if attribute == smart else "playlist")
|
||||
node_id = str(r.ID)
|
||||
nodes[node_id] = PlaylistNode(
|
||||
id=node_id,
|
||||
name=r.Name or "",
|
||||
kind=kind,
|
||||
count=(0 if kind == "folder" else len(self._store.playlist_song_ids(node_id))),
|
||||
children=[],
|
||||
# A smart playlist has no static entry list; a folder has no tracks.
|
||||
selectable=kind == "playlist",
|
||||
# Rekordbox's own working lists are filtered out by the store, so
|
||||
# everything reaching here is the user's and may be edited — as
|
||||
# long as the library itself is writable at all.
|
||||
can_add_tracks=writable and kind == "playlist",
|
||||
can_reorder=writable and kind == "playlist",
|
||||
can_rename=writable,
|
||||
can_delete=writable,
|
||||
can_contain_children=kind == "folder",
|
||||
)
|
||||
parent = str(r.ParentID or "root")
|
||||
parents[node_id] = "root" if parent in ("0", "", "root", "None") else parent
|
||||
|
||||
roots: list[PlaylistNode] = []
|
||||
for node_id, node in nodes.items():
|
||||
parent_id = parents.get(node_id, "root")
|
||||
parent = nodes.get(parent_id)
|
||||
if parent is None:
|
||||
roots.append(node)
|
||||
else:
|
||||
parent.children.append(node)
|
||||
return roots
|
||||
|
||||
def playlist_entries(self, node_id: str) -> list[str] | None:
|
||||
ids = self._store.playlist_song_ids(node_id)
|
||||
return ids if ids or self._is_playlist(node_id) else None
|
||||
|
||||
def playlist_tracks(self, node_id: str) -> list[Track] | None:
|
||||
keys = self.playlist_entries(node_id)
|
||||
if keys is None:
|
||||
return None
|
||||
return [t for k in keys if (t := self._index.get(k)) is not None]
|
||||
|
||||
def _is_playlist(self, node_id: str) -> bool:
|
||||
return any(str(r.ID) == str(node_id) for r in self._store.playlists())
|
||||
|
||||
# ---- audio / paths ----------------------------------------------------
|
||||
def audio_path(self, track_id: str):
|
||||
return self._store.audio_path(track_id)
|
||||
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None:
|
||||
self._store.set_path_mapping(mapping)
|
||||
|
||||
def path_prefix_suggestions(self) -> dict:
|
||||
paths = self._store.all_audio_paths()
|
||||
primary = common_dir_prefix(paths)
|
||||
return {"primary": primary, "groups": [{"prefix": primary, "count": len(paths)}] if primary else []}
|
||||
|
||||
def remap_preview(self, mapping: PathMapping) -> dict:
|
||||
paths = [Path(p) for p in self._store.all_audio_paths()]
|
||||
matched = [p for p in paths if mapping.matches(p)]
|
||||
samples = []
|
||||
for p in matched[:5]:
|
||||
target = mapping.apply(p)
|
||||
samples.append({"from": str(p), "to": str(target), "exists": target.exists()})
|
||||
existing = sum(1 for p in matched if mapping.apply(p).exists())
|
||||
return {
|
||||
"total": len(paths),
|
||||
"matched": len(matched),
|
||||
"existing": existing,
|
||||
"samples": samples,
|
||||
}
|
||||
|
||||
def remap_locations(self, mapping: PathMapping) -> dict[str, str]:
|
||||
raise Unsupported(self._readonly_reason("Rewriting stored paths"))
|
||||
|
||||
# ---- commands: track metadata ----------------------------------------
|
||||
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None:
|
||||
self._require_writable("Editing track metadata")
|
||||
self._store.set_track_metadata(track_id, fields)
|
||||
self._refresh(track_id)
|
||||
return self._index.get(track_id)
|
||||
|
||||
# ---- commands: playlists ----------------------------------------------
|
||||
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
|
||||
self._require_writable("Creating playlists")
|
||||
return self._store.create_playlist(name, parent_id)
|
||||
|
||||
def create_folder(self, name: str, parent_id: str | None = None) -> str:
|
||||
self._require_writable("Creating playlist folders")
|
||||
return self._store.create_folder(name, parent_id)
|
||||
|
||||
def rename_playlist(self, node_id: str, name: str) -> None:
|
||||
self._require_writable("Renaming playlists")
|
||||
self._store.rename_playlist(node_id, name)
|
||||
|
||||
def delete_playlist(self, node_id: str) -> None:
|
||||
self._require_writable("Deleting playlists")
|
||||
self._store.delete_playlist(node_id)
|
||||
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
|
||||
self._require_writable("Editing playlists")
|
||||
return self._store.set_playlist_entries(node_id, track_ids)
|
||||
|
||||
# ---- commands: cues ---------------------------------------------------
|
||||
def _check_cue_type(self, cue_type: str) -> None:
|
||||
if cue_type not in caps.WRITABLE_CUE_TYPES:
|
||||
raise Unsupported(f"Rekordbox has no cue type {cue_type!r}")
|
||||
|
||||
def set_cue(
|
||||
self,
|
||||
track_id: str,
|
||||
*,
|
||||
slot: int,
|
||||
start_sec: float,
|
||||
cue_type: str,
|
||||
length_sec: float = 0.0,
|
||||
role: str = "hotcue",
|
||||
name: str | None = None,
|
||||
) -> TrackCues:
|
||||
self._require_writable("Editing cues")
|
||||
if role != "hotcue":
|
||||
# Rekordbox is the ONLY platform with memory cues, so under the
|
||||
# two-platform promotion rule they stay preserved-but-uneditable:
|
||||
# they are projected and shown, never written.
|
||||
raise Unsupported(
|
||||
"Memory cues are shown but cannot be edited — only hot cues are writable"
|
||||
)
|
||||
self._check_cue_type(cue_type)
|
||||
self._store.set_cue(
|
||||
track_id, slot=slot, start_sec=start_sec, cue_type=cue_type,
|
||||
length_sec=length_sec, name=name,
|
||||
)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> TrackCues:
|
||||
self._require_writable("Editing cues")
|
||||
self._check_cue_type(cue_type)
|
||||
self._store.set_cue_type(track_id, slot, cue_type)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def delete_cue(self, track_id: str, slot: int) -> TrackCues:
|
||||
self._require_writable("Deleting cues")
|
||||
self._store.delete_cue(track_id, slot)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues:
|
||||
self._require_writable("Placing cues")
|
||||
for cue in cues:
|
||||
self._check_cue_type(getattr(cue, "type", "cue"))
|
||||
self._store.place_cues(track_id, cues, overwrite=overwrite)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
# ---- commands: beatgrid -----------------------------------------------
|
||||
def _markers_from(self, markers: list) -> list:
|
||||
"""Accept either GridMarkers or the (start, bpm) tuples routes send."""
|
||||
out = []
|
||||
for m in markers:
|
||||
if isinstance(m, GridMarker):
|
||||
out.append(m)
|
||||
else:
|
||||
start, bpm = m
|
||||
out.append(GridMarker(start=float(start), bpm=float(bpm)))
|
||||
return out
|
||||
|
||||
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> TrackCues:
|
||||
self._require_writable("Editing the beatgrid")
|
||||
self._store.add_grid_marker(track_id, start_sec, bpm)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> TrackCues:
|
||||
self._require_writable("Editing the beatgrid")
|
||||
self._store.move_grid_marker(track_id, index, start_sec)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> TrackCues:
|
||||
self._require_writable("Editing the beatgrid")
|
||||
self._store.set_grid_marker_bpm(track_id, index, bpm)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def delete_grid_marker(self, track_id: str, index: int) -> TrackCues:
|
||||
self._require_writable("Editing the beatgrid")
|
||||
self._store.delete_grid_marker(track_id, index)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def replace_grid(self, track_id: str, markers: list) -> TrackCues:
|
||||
self._require_writable("Editing the beatgrid")
|
||||
self._store.replace_grid(track_id, self._markers_from(markers))
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def set_analysed_grid(self, track_id: str, markers: list) -> TrackCues:
|
||||
"""Write an analysis result the way Rekordbox's own analyser would.
|
||||
|
||||
Rekordbox pairs nothing with a grid marker — the companion cue is a
|
||||
Traktor convention — so this is just a replace.
|
||||
"""
|
||||
return self.replace_grid(track_id, markers)
|
||||
|
||||
def delete_grid(self, track_id: str) -> TrackCues:
|
||||
self._require_writable("Deleting the beatgrid")
|
||||
self._store.delete_grid(track_id)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
# ---- save -------------------------------------------------------------
|
||||
@property
|
||||
def dirty(self) -> bool:
|
||||
return self._store.dirty
|
||||
|
||||
def save(self):
|
||||
self._require_writable("Saving")
|
||||
return self._store.save()
|
||||
|
||||
def snapshot(self) -> bytes:
|
||||
"""The library's bytes, for version history.
|
||||
|
||||
`master.db` alone is NOT a complete snapshot of a Rekordbox library (the
|
||||
beatgrids live in separate ANLZ files, and restoring the database
|
||||
wholesale would also roll back Rekordbox's own auth and sampler state),
|
||||
which is why `capabilities.save.history` is False. Nothing should be
|
||||
calling this.
|
||||
"""
|
||||
raise Unsupported("Rekordbox libraries are not versioned by Konduktor")
|
||||
|
||||
# ---- commands: all refused in this milestone -------------------------
|
||||
def _readonly_reason(self, what: str) -> str:
|
||||
if self._cloud_synced:
|
||||
return (
|
||||
f"{what} is not possible: this Rekordbox library is synced with "
|
||||
"Rekordbox Cloud, and Konduktor will not write to a cloud-synced "
|
||||
"library."
|
||||
)
|
||||
return f"{what} is not supported yet for Rekordbox libraries."
|
||||
|
||||
def _refuse(self, what: str):
|
||||
raise Unsupported(self._readonly_reason(what))
|
||||
|
||||
def _require_writable(self, what: str) -> None:
|
||||
"""Every write passes through here, so the cloud-sync refusal cannot be
|
||||
forgotten by a command added later."""
|
||||
if self._cloud_synced:
|
||||
raise Unsupported(self._readonly_reason(what))
|
||||
|
||||
def add_tracks(self, items: list) -> list[str]:
|
||||
# Not a refusal in principle — Rekordbox could receive imported
|
||||
# tracks — but adding one means a djmdContent row, its lookup-table
|
||||
# foreign keys, a USN, and an ANLZ file built from scratch, which
|
||||
# is unexplored (see the export handoff). Traktor is the only
|
||||
# import target for now.
|
||||
self._refuse("Adding tracks")
|
||||
|
||||
def remove_tracks(self, track_ids: list[str]) -> int:
|
||||
# Same shape as adding: a track is a djmdContent row plus its cues,
|
||||
# playlist rows, contentCue/contentFile mirrors and ANLZ files, and
|
||||
# which of those Rekordbox expects to be deleted together is unmeasured.
|
||||
self._refuse("Removing tracks")
|
||||
|
||||
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
|
||||
self._refuse("Editing cover art")
|
||||
|
||||
def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
|
||||
return self._store.cover_art(track_id)
|
||||
|
||||
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues:
|
||||
# Rekordbox has no per-track grid lock; capabilities.grid.lockable says so.
|
||||
raise Unsupported("Rekordbox has no beatgrid lock")
|
||||
@@ -0,0 +1,176 @@
|
||||
"""Building ANLZ analysis files from nothing.
|
||||
|
||||
Lives here rather than in the OneLibrary adapter because the format is Pioneer's,
|
||||
not one product's: a `master.db` track and a USB drive track carry the same tags.
|
||||
OneLibrary borrows it, the same direction it already borrows `beatgrid`.
|
||||
|
||||
The read path parses these with `pyrekordbox`; writing needs the inverse, and
|
||||
two things stand in the way of simply reusing its `construct` structs.
|
||||
|
||||
**`AnlzTag.content` is a Switch**, so a tag is built by handing it the parsed
|
||||
STRUCTURE rather than bytes. Fine once known, surprising until then.
|
||||
|
||||
**The cue-entry structs cannot be built at all.** `AnlzCuePoint` and
|
||||
`AnlzCuePoint2` each declare `"type"` twice — once as a `Const` magic string
|
||||
(`PCPT`/`PCP2`) and once as the cue's kind. Parsing works because the second
|
||||
silently overwrites the first in the result; BUILDING is impossible, because
|
||||
`construct` reads one value out of the dict for both and no single value can
|
||||
satisfy a string `Const` and an integer field. So cue entries are packed here by
|
||||
hand, to the layout `pyrekordbox`'s own structs document:
|
||||
|
||||
PCP2: 4s magic · I len_header · I len_entry · I hot_cue · B kind · 3x
|
||||
I time · I loop_time · B color_id · 7x · H loop_num · H loop_den
|
||||
I len_comment · {n}s comment(utf-16-be) · 4B colour · {pad}x
|
||||
|
||||
Everything is verified by parsing the result back through `pyrekordbox`, which is
|
||||
the only check that matters: the reader is the thing that has to accept it.
|
||||
|
||||
Slot numbering here is ANLZ's own — a **dense 1-based** `hot_cue` where 0 means a
|
||||
memory cue. That is NOT `master.db`'s sparse `Kind` bank, which skips 4.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import struct
|
||||
from pathlib import Path
|
||||
|
||||
from construct import Container, ListContainer
|
||||
from pyrekordbox.anlz import structs
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
NO_LOOP = 0xFFFFFFFF
|
||||
#: `len_entry` rekordbox itself writes for a comment-less PCP2 entry.
|
||||
PCP2_ENTRY_LEN = 88
|
||||
PCPT_ENTRY_LEN = 56
|
||||
|
||||
#: Copied from a rekordbox-written file; zeros here would be a guess.
|
||||
FILE_HEADER_U1, FILE_HEADER_U2, FILE_HEADER_U3 = 1, 0x10000, 0x10000
|
||||
|
||||
|
||||
#: The three fields every tag starts with: magic, len_header, len_tag.
|
||||
_TAG_PREFIX = 12
|
||||
|
||||
|
||||
#: Each tag counts a different number of its leading CONTENT fields as part of
|
||||
#: its header. Read off `pyrekordbox`'s own tag classes rather than guessed.
|
||||
_LEN_HEADER = {"PPTH": 16, "PQTZ": 24, "PCOB": 24, "PCO2": 20}
|
||||
|
||||
|
||||
def _wrap(kind: str, body: bytes) -> bytes:
|
||||
"""An AnlzTag around already-built content bytes.
|
||||
|
||||
Returns BYTES, not a tag object. `AnlzFile.build()` cannot be used on the
|
||||
write side at all: it re-builds every tag from its parsed struct, which puts
|
||||
the cue tags straight back through the unbuildable duplicate-`type` structs.
|
||||
So the whole file is assembled here and `pyrekordbox` is used only to read
|
||||
the result back — which is the direction that has to work anyway.
|
||||
"""
|
||||
return struct.pack(">4sII", kind.encode("ascii"), _LEN_HEADER[kind],
|
||||
_TAG_PREFIX + len(body)) + body
|
||||
|
||||
|
||||
def path_tag(drive_relative: str) -> bytes:
|
||||
"""`PPTH` — the track's own path, as the drive stores it."""
|
||||
raw_len = (len(drive_relative) + 1) * 2
|
||||
body = structs.PPTH.build(Container(len_path=raw_len, path=drive_relative))
|
||||
return _wrap("PPTH", body)
|
||||
|
||||
|
||||
def beatgrid_tag(beats: list[tuple[int, float, float]]) -> bytes:
|
||||
"""`PQTZ` — EVERY beat, as (beat-in-bar 1-4, bpm, seconds).
|
||||
|
||||
The grid is per-beat here, not per-marker: a OneLibrary/Rekordbox grid has
|
||||
no concept of a tempo marker, so the generic marker list is expanded into
|
||||
individual beats on the way out and collapsed back on the way in.
|
||||
"""
|
||||
entries = ListContainer([
|
||||
Container(beat=beat, tempo=int(round(bpm * 100)), time=int(round(sec * 1000)))
|
||||
for beat, bpm, sec in beats
|
||||
])
|
||||
body = structs.PQTZ.build(Container(entry_count=len(entries), entries=entries))
|
||||
return _wrap("PQTZ", body)
|
||||
|
||||
|
||||
def _pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
|
||||
rgb: tuple[int, int, int] | None, beats: int | None) -> bytes:
|
||||
comment = b""
|
||||
red, green, blue = rgb or (0, 0, 0)
|
||||
return struct.pack(
|
||||
">4sIIIB3xIIB7xHHI",
|
||||
b"PCP2", 16, PCP2_ENTRY_LEN, hot_cue, kind,
|
||||
int(time_ms), NO_LOOP if loop_ms is None else int(loop_ms),
|
||||
0, beats or 0, 1 if beats else 0, len(comment),
|
||||
) + comment + struct.pack(">4B", 0, red, green, blue) + bytes(
|
||||
PCP2_ENTRY_LEN - 48 - len(comment)
|
||||
)
|
||||
|
||||
|
||||
def _pcpt_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
|
||||
first: int, last: int) -> bytes:
|
||||
return struct.pack(
|
||||
">4sIIIIIHHBxHII",
|
||||
b"PCPT", 12, PCPT_ENTRY_LEN, hot_cue,
|
||||
4 if loop_ms is not None else 4, # status: 4 = active, as rekordbox writes
|
||||
0x10000, first, last, kind, 1000,
|
||||
int(time_ms), NO_LOOP if loop_ms is None else int(loop_ms),
|
||||
) + bytes(16)
|
||||
|
||||
|
||||
def cue_tags(cues: list[dict], *, extended: bool) -> list[bytes]:
|
||||
"""`PCOB` (+ `PCO2` in the .EXT) for one track's cues.
|
||||
|
||||
`PCOB` is **split by pad**: the `.DAT` carries hot cues 1-3 and the `.EXT`
|
||||
carries 4 and up, which is why the reader merges across both files. Memory
|
||||
cues go in their own `PCOB` with `cue_type` 0. `PCO2` is the complete list
|
||||
and only exists in the `.EXT`.
|
||||
"""
|
||||
hot = [c for c in cues if c["hot_cue"]]
|
||||
memory = [c for c in cues if not c["hot_cue"]]
|
||||
tags: list[bytes] = []
|
||||
|
||||
# PCOB, one per kind, filtered to the pads this file is responsible for.
|
||||
for cue_type, group in ((0, memory), (1, hot)):
|
||||
chosen = [
|
||||
c for c in group
|
||||
if not c["hot_cue"] or ((c["hot_cue"] > 3) == extended)
|
||||
] if cue_type == 1 else (group if not extended else [])
|
||||
if not chosen:
|
||||
continue
|
||||
blob = b"".join(
|
||||
_pcpt_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
|
||||
loop_ms=c["loop_ms"],
|
||||
first=0xFFFF if i == 0 else i,
|
||||
last=i + 1 if i + 1 < len(chosen) else 0xFFFF)
|
||||
for i, c in enumerate(chosen)
|
||||
)
|
||||
# cue_type is Int32ub (an Enum over it), NOT Int16 — getting this wrong
|
||||
# shifts every following field and the reader sees garbage.
|
||||
header = struct.pack(">IHHi", cue_type, 0, len(chosen), len(chosen))
|
||||
tags.append(_wrap("PCOB", header + blob))
|
||||
|
||||
if extended and cues:
|
||||
blob = b"".join(
|
||||
_pcp2_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
|
||||
loop_ms=c["loop_ms"], rgb=c.get("rgb"), beats=c.get("beats"))
|
||||
for c in cues
|
||||
)
|
||||
header = struct.pack(">IHH", 1 if hot else 0, len(cues), 0)
|
||||
tags.append(_wrap("PCO2", header + blob))
|
||||
return tags
|
||||
|
||||
|
||||
#: `PMAI` + len_header + len_file + four unknowns.
|
||||
_FILE_HEADER_LEN = 28
|
||||
|
||||
|
||||
def write_anlz(path: Path, tags: list[bytes]) -> Path:
|
||||
"""Assemble and write an ANLZ file from built tag bytes."""
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
body = b"".join(tags)
|
||||
header = struct.pack(
|
||||
">4sIIIIII", b"PMAI", _FILE_HEADER_LEN, _FILE_HEADER_LEN + len(body),
|
||||
FILE_HEADER_U1, FILE_HEADER_U2, FILE_HEADER_U3, 0,
|
||||
)
|
||||
path.write_bytes(header + body)
|
||||
return path
|
||||
@@ -0,0 +1,128 @@
|
||||
"""Rekordbox's beatgrid <-> the generic marker list.
|
||||
|
||||
**Rekordbox does not store markers.** There is no beatgrid table in
|
||||
``master.db`` at all; the grid lives in the track's ANLZ analysis file as a
|
||||
``PQTZ`` tag holding EVERY BEAT explicitly — beat-number-in-bar, BPM and time,
|
||||
one entry per beat (a 4-minute track is ~500 entries).
|
||||
|
||||
Konduktor's generic model is a marker list, so this module is the projection
|
||||
between the two:
|
||||
|
||||
* read — collapse runs of equal BPM into one marker each, so a constant-tempo
|
||||
track becomes a list of length one and a variable-tempo track becomes one
|
||||
marker per tempo change. This is exactly the shape ``core.model.GridMarker``
|
||||
describes.
|
||||
* write — expand a marker list back into a full beat list (milestone 2; the
|
||||
read direction is what a read-only adapter needs).
|
||||
|
||||
BPMs are compared with a tolerance because Rekordbox stores them as hundredths
|
||||
and floating-point division reintroduces noise; two beats within `BPM_EPSILON`
|
||||
are the same tempo and must not produce a spurious marker.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from ...core.model import GridMarker
|
||||
|
||||
BPM_EPSILON = 0.005 # half of the 0.01 BPM Rekordbox can actually represent
|
||||
|
||||
|
||||
def markers_from_beats(
|
||||
times: list[float], bpms: list[float], beats: list[int] | None = None
|
||||
) -> list[GridMarker]:
|
||||
"""Collapse a per-beat grid into the generic marker list.
|
||||
|
||||
`times` are seconds, `bpms` the tempo in force at each beat. A marker is
|
||||
emitted for the first beat and wherever the tempo changes.
|
||||
"""
|
||||
if not times or not bpms:
|
||||
return []
|
||||
out: list[GridMarker] = []
|
||||
last_bpm: float | None = None
|
||||
for i, (t, bpm) in enumerate(zip(times, bpms)):
|
||||
if last_bpm is None or abs(bpm - last_bpm) > BPM_EPSILON:
|
||||
out.append(GridMarker(start=float(t), bpm=float(bpm), name=None, companion=None))
|
||||
last_bpm = float(bpm)
|
||||
return out
|
||||
|
||||
|
||||
def beats_from_markers(
|
||||
markers: list[GridMarker], duration_sec: float
|
||||
) -> tuple[list[int], list[float], list[float]]:
|
||||
"""Expand a marker list into the per-beat arrays Rekordbox stores.
|
||||
|
||||
Each marker governs until the next one; the last runs to `duration_sec`.
|
||||
Returns ``(beat_in_bar, bpms, times)`` with beat numbers cycling 1-4 from
|
||||
each marker, which is how Rekordbox numbers bars.
|
||||
|
||||
Not used by the read-only adapter, but it is the inverse of
|
||||
`markers_from_beats` and belongs beside it.
|
||||
"""
|
||||
beat_nums: list[int] = []
|
||||
bpms: list[float] = []
|
||||
times: list[float] = []
|
||||
if not markers:
|
||||
return beat_nums, bpms, times
|
||||
ordered = sorted(markers, key=lambda m: m.start)
|
||||
for i, m in enumerate(ordered):
|
||||
if m.bpm <= 0:
|
||||
continue
|
||||
end = ordered[i + 1].start if i + 1 < len(ordered) else duration_sec
|
||||
step = 60.0 / m.bpm
|
||||
t = m.start
|
||||
n = 1
|
||||
# Guard against a zero/negative span producing an endless loop.
|
||||
while t < end - 1e-9 and step > 0:
|
||||
beat_nums.append(n)
|
||||
bpms.append(m.bpm)
|
||||
times.append(t)
|
||||
n = n % 4 + 1
|
||||
t += step
|
||||
return beat_nums, bpms, times
|
||||
|
||||
|
||||
# ---- writing the analysis file ----------------------------------------------
|
||||
#
|
||||
# The grid lives in the ANLZ files, and only `.DAT`'s `PQTZ` tag is written here.
|
||||
# `.EXT` carries a second, "extended" grid (`PQT2`) whose per-beat byte and `u3`
|
||||
# field are NOT decoded — `pyrekordbox` itself calls the field `unkown` — so
|
||||
# rewriting it would mean guessing at bytes in real user data that has no version
|
||||
# history. Leaving it alone is the only safe option until it is decoded.
|
||||
#
|
||||
# `.DAT`/`.EXT` round-trip byte-identically through parse -> build (verified
|
||||
# across a whole library), which is what makes this checkable at all: a rebuild
|
||||
# must differ ONLY inside the tag we touched.
|
||||
|
||||
|
||||
def write_pqtz(path, beat_nums, bpms, times) -> bool:
|
||||
"""Replace the beat grid in an ANLZ `.DAT`, in place. True if written.
|
||||
|
||||
`pyrekordbox`'s own `PQTZAnlzTag.set*()` refuse to change the NUMBER of
|
||||
beats ("only values of existing beats can be set"), and every real grid edit
|
||||
changes it — so the entry list is rebuilt directly and the tag's own
|
||||
`update_len()` recomputes `len_tag`. `check_parse()` then asserts the
|
||||
declared count and the list agree before anything is written.
|
||||
"""
|
||||
import construct
|
||||
from pyrekordbox.anlz import AnlzFile
|
||||
|
||||
anlz = AnlzFile.parse_file(str(path))
|
||||
tag = next((t for t in anlz.tags if t.type == "PQTZ"), None)
|
||||
if tag is None:
|
||||
return False
|
||||
entries = construct.ListContainer()
|
||||
for beat, bpm, t in zip(beat_nums, bpms, times):
|
||||
entries.append(
|
||||
construct.Container(
|
||||
beat=int(beat),
|
||||
tempo=int(round(bpm * 100)), # BPM is stored x100
|
||||
time=int(round(t * 1000)), # seconds -> ms
|
||||
)
|
||||
)
|
||||
tag.struct.content.entries = entries
|
||||
tag.struct.content.entry_count = len(entries)
|
||||
tag.update_len()
|
||||
tag.check_parse()
|
||||
data = anlz.build()
|
||||
with open(path, "wb") as fh:
|
||||
fh.write(data)
|
||||
return True
|
||||
@@ -0,0 +1,102 @@
|
||||
"""What a Rekordbox library can persist.
|
||||
|
||||
**Track metadata and playlists are writable; cues and the beatgrid are not.**
|
||||
The spike verified that Rekordbox accepts writes which maintain its USN columns
|
||||
(see the handoff's Findings), and those two write paths use `pyrekordbox`, which
|
||||
maintains them. Cues and the grid are separate hand-written stores and stay
|
||||
false until milestone 3 — the capability system exists precisely so the UI never
|
||||
offers an edit that will not persist.
|
||||
|
||||
A **cloud-synced** library reports `writable=False` regardless: Konduktor will
|
||||
not write one at all.
|
||||
|
||||
Two facts are already known and encoded, because getting them wrong later would
|
||||
be a silent data bug rather than a missing feature:
|
||||
|
||||
* a saved loop is a cue with an out-point, NOT a separate bank, so
|
||||
``loops="cue_type"`` — the same answer as Traktor, and NOT the
|
||||
``separate_bank`` the original plan assumed;
|
||||
* cue colour is a PALETTE index (``djmdCue.ColorTableIndex``), not free RGB,
|
||||
and the palette is a built-in table — `djmdColor` is the *track* colour
|
||||
palette and is unrelated.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from ...core.capabilities import (
|
||||
Capabilities,
|
||||
CueCapabilities,
|
||||
GridCapabilities,
|
||||
PlaylistCapabilities,
|
||||
SaveCapabilities,
|
||||
TrackCapabilities,
|
||||
)
|
||||
from .cue_types import WRITABLE_CUE_TYPES
|
||||
|
||||
# Rekordbox's addressable hot cue bank. The pads are labelled A-H; the stored
|
||||
# slot number is NOT a plain letter index (see cue_types), so the adapter keeps
|
||||
# slots numeric and lets the UI label them.
|
||||
HOTCUE_SLOTS = 8
|
||||
|
||||
|
||||
def capabilities_for(
|
||||
path,
|
||||
version: str | None = None,
|
||||
*,
|
||||
cloud_synced: bool = False,
|
||||
editable_fields: list[str] | None = None,
|
||||
) -> Capabilities:
|
||||
# A cloud-synced library is refused PERMANENTLY, not pending a milestone:
|
||||
# a local edit the server did not issue could propagate a broken sync state
|
||||
# to the user's other machines, which version history cannot undo.
|
||||
return Capabilities(
|
||||
platform="rekordbox",
|
||||
version=version,
|
||||
writable=not cloud_synced,
|
||||
readonly_cause="cloud_synced" if cloud_synced else None,
|
||||
cues=CueCapabilities(
|
||||
# Hot cues are writable: djmdCue rows plus the contentCue JSON
|
||||
# mirror, kept in step. MEMORY cues stay preserved-but-uneditable —
|
||||
# Rekordbox is the only platform that has them, and the two-platform
|
||||
# promotion rule says a one-platform concept does not become an
|
||||
# editing feature.
|
||||
editable=True,
|
||||
hotcue_slots=HOTCUE_SLOTS,
|
||||
slot_labels="letter",
|
||||
# Rekordbox is the only platform with memory cues, so they are
|
||||
# projected and PRESERVED but not editable (two-platform rule).
|
||||
memory_cues=True,
|
||||
max_memory_cues=None, # unlimited
|
||||
# Both cue types write; Rekordbox has no fade/load types.
|
||||
types=WRITABLE_CUE_TYPES,
|
||||
color="palette",
|
||||
palette=[], # TODO milestone 2: the built-in cue colour table
|
||||
named=True, # djmdCue.Comment
|
||||
loops="cue_type",
|
||||
),
|
||||
# The grid is written into the track's ANLZ .DAT (PQTZ). Verified:
|
||||
# Rekordbox reads the grid and its BPM readout from there, and leaves a
|
||||
# Konduktor-written file alone. It has no per-track grid lock.
|
||||
grid=GridCapabilities(editable=True, flexible=True, lockable=False),
|
||||
tracks=TrackCapabilities(
|
||||
rating_max=5, # Rekordbox stores 0-5 directly, unlike Traktor's /51
|
||||
# Narrower than Traktor's: `producer` and `mix` have no Rekordbox
|
||||
# column (its Composer is a different field), so they are absent
|
||||
# rather than mapped onto something approximate.
|
||||
editable_fields=sorted(editable_fields or []),
|
||||
media_kinds=["audio"],
|
||||
artwork=False,
|
||||
artwork_note=None,
|
||||
),
|
||||
playlists=PlaylistCapabilities(folders=True, smart="read_only", reorder=True),
|
||||
save=SaveCapabilities(
|
||||
app_name="Rekordbox",
|
||||
library_label="master.db",
|
||||
# Rekordbox holds master.db open while running and cloud-syncs it,
|
||||
# so a concurrent write is riskier than Traktor's overwrite-on-exit.
|
||||
overwrite_risk="while_running",
|
||||
# The artefact set is master.db + N ANLZ files + masterPlaylists6.xml,
|
||||
# and history.py tracks a single blob. Also, restoring master.db
|
||||
# wholesale would roll back Rekordbox's auth token and sampler state.
|
||||
history=False,
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,103 @@
|
||||
"""Rekordbox's ``djmdCue.Kind`` encoding <-> the generic cue vocabulary.
|
||||
|
||||
The only place these integers are given meaning. Verified against a real
|
||||
library (see the handoff's Findings section):
|
||||
|
||||
* ``Kind == 0`` -> a MEMORY cue: no bank slot, and Rekordbox allows any
|
||||
number of them.
|
||||
* ``Kind >= 1`` -> a HOT CUE.
|
||||
|
||||
**``Kind`` is 1-based AND it skips 4.** Konduktor's generic model numbers bank
|
||||
slots from zero — slot 0 is the pad the UI labels "A", which is also how Traktor
|
||||
stores its ``HOTCUE`` attribute. Rekordbox's first pad is ``Kind=1``, and the
|
||||
value ``4`` is reserved: the bank runs 1, 2, 3, 5, 6, 7, 8, 9.
|
||||
|
||||
Measured, not guessed. A loop was written at every ``Kind`` from 1 to 8, ten
|
||||
seconds apart, and read off a real deck:
|
||||
|
||||
Kind 1 2 3 4 5 6 7 8 9
|
||||
pad A B C - D E F G H
|
||||
|
||||
``Kind=4`` appears on no pad at all; Rekordbox shows such a cue as a memory cue.
|
||||
That one gap explains two earlier puzzles: a Rekordbox-authored loop on pad F
|
||||
stored ``Kind=7``, and a Konduktor cue written as ``Kind=4`` vanished from the
|
||||
bank. Getting this wrong silently moves cues to the wrong pad — or loses them
|
||||
from the bank entirely.
|
||||
|
||||
**``Kind`` is treated as an opaque slot id.** Setting cues on pads A and C
|
||||
stored 1 and 3, but the pad in the 6th position stored 7, so the slot -> letter
|
||||
mapping is NOT a plain index and has not been pinned down. Nothing here depends
|
||||
on it: the adapter addresses cues by slot number and the UI labels them, which
|
||||
is what ``capabilities.cues.slot_labels`` is for.
|
||||
|
||||
Loop-ness is NOT carried by ``Kind``. A loop is an ordinary cue row that also
|
||||
has an out-point, so a loop can sit in a hot cue slot or be a memory cue.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
MEMORY_KIND = 0
|
||||
|
||||
# Rekordbox has no fade-in/fade-out/load cues; those are Traktor-only.
|
||||
CUE_TYPES = ["cue", "loop"]
|
||||
|
||||
# What Konduktor will write. Loops were disabled for a while because a loop
|
||||
# written at `Kind=4` disappeared from the bank — which turned out to be the
|
||||
# reserved-Kind gap above, not anything to do with loops. Both types write.
|
||||
WRITABLE_CUE_TYPES = ["cue", "loop"]
|
||||
|
||||
|
||||
# The Kind value that is not a bank slot. Everything at or above it is shifted
|
||||
# by one relative to the pad index.
|
||||
RESERVED_KIND = 4
|
||||
|
||||
|
||||
def role_and_slot(kind: int | None) -> tuple[str, int | None]:
|
||||
"""(role, 0-based slot) for a native ``Kind``.
|
||||
|
||||
A cue at `RESERVED_KIND` occupies no pad, so it is projected as a memory cue
|
||||
— which is how Rekordbox itself displays one.
|
||||
"""
|
||||
if kind is None or kind == MEMORY_KIND or int(kind) == RESERVED_KIND:
|
||||
return "memory", None
|
||||
kind = int(kind)
|
||||
return "hotcue", kind - 1 if kind < RESERVED_KIND else kind - 2
|
||||
|
||||
|
||||
def kind_for(role: str, slot: int | None) -> int:
|
||||
"""The native ``Kind`` for a generic (role, 0-based slot).
|
||||
|
||||
Inverse of `role_and_slot`; skips `RESERVED_KIND`.
|
||||
"""
|
||||
if role == "memory":
|
||||
return MEMORY_KIND
|
||||
if slot is None:
|
||||
raise ValueError("a hot cue needs a slot")
|
||||
slot = int(slot)
|
||||
if slot < 0:
|
||||
raise ValueError(f"a hot cue slot cannot be negative, got {slot}")
|
||||
return slot + 1 if slot < RESERVED_KIND - 1 else slot + 2
|
||||
|
||||
|
||||
def cue_type(out_msec: int | None) -> str:
|
||||
"""A cue with a real out-point is a loop; everything else is a plain cue.
|
||||
|
||||
Rekordbox writes ``OutMsec = -1`` for a non-loop.
|
||||
"""
|
||||
return "loop" if out_msec is not None and out_msec > 0 else "cue"
|
||||
|
||||
|
||||
def beat_loop_size(beats: int) -> int:
|
||||
"""Encode a loop's musical length.
|
||||
|
||||
``BeatLoopSize = (beats << 16) | 1`` — verified against two real loops at
|
||||
different tempos (1 beat @125 BPM = 0x10001, 4 beats @120 BPM = 0x40001),
|
||||
each agreeing with the measured millisecond span.
|
||||
"""
|
||||
return (int(beats) << 16) | 1
|
||||
|
||||
|
||||
def beats_in_loop(beat_loop_size: int | None) -> int | None:
|
||||
"""Decode `beat_loop_size`. None when unset."""
|
||||
if not beat_loop_size:
|
||||
return None
|
||||
return beat_loop_size >> 16
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Locate Rekordbox libraries in their default install locations.
|
||||
|
||||
Rekordbox keeps one library per install, at a fixed per-OS path:
|
||||
|
||||
macOS ~/Library/Pioneer/rekordbox/master.db
|
||||
Windows %APPDATA%/Pioneer/rekordbox/master.db
|
||||
|
||||
``pyrekordbox`` already resolves this (including the v6/v7 split and any
|
||||
non-default location recorded in Rekordbox's own settings), so that is the
|
||||
primary source and the hard-coded paths are the fallback.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
_RELATIVE = Path("Pioneer") / "rekordbox" / "master.db"
|
||||
|
||||
|
||||
def _configured_paths() -> list[Path]:
|
||||
"""Library paths pyrekordbox finds from Rekordbox's own configuration."""
|
||||
out: list[Path] = []
|
||||
try:
|
||||
from pyrekordbox.config import get_config
|
||||
except Exception: # noqa: BLE001 — never let discovery break startup
|
||||
return out
|
||||
for version in ("rekordbox7", "rekordbox6"):
|
||||
try:
|
||||
conf = get_config(version)
|
||||
except Exception: # noqa: BLE001
|
||||
continue
|
||||
if not conf:
|
||||
continue
|
||||
p = conf.get("db_path")
|
||||
if p:
|
||||
out.append(Path(p))
|
||||
return out
|
||||
|
||||
|
||||
def _default_paths() -> list[Path]:
|
||||
home = Path.home()
|
||||
return [
|
||||
home / "Library" / _RELATIVE, # macOS
|
||||
home / "AppData" / "Roaming" / _RELATIVE, # Windows
|
||||
]
|
||||
|
||||
|
||||
def describe(path: Path) -> dict:
|
||||
"""A candidate record for a master.db path, shaped like the picker wants."""
|
||||
path = Path(path)
|
||||
exists = path.is_file()
|
||||
# The version Rekordbox itself is, not a schema version stamped in the file:
|
||||
# master.db carries no version field, so the folder is the best label there is.
|
||||
return {
|
||||
"path": str(path),
|
||||
"label": "Rekordbox",
|
||||
"version": None,
|
||||
"modified": (path.stat().st_mtime if exists else None),
|
||||
"exists": exists,
|
||||
}
|
||||
|
||||
|
||||
def detect_libraries() -> list[dict]:
|
||||
"""Every Rekordbox master.db found in a default location, newest first."""
|
||||
seen: set[str] = set()
|
||||
found: list[dict] = []
|
||||
for p in _configured_paths() + _default_paths():
|
||||
try:
|
||||
if not p.is_file():
|
||||
continue
|
||||
except OSError:
|
||||
continue
|
||||
key = str(p.resolve())
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
found.append(describe(p))
|
||||
found.sort(key=lambda c: c["modified"] or 0.0, reverse=True)
|
||||
return found
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Opening Rekordbox libraries: recognition, discovery and restore."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
from . import discovery
|
||||
from .adapter import RekordboxAdapter
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
_SQLITE_MAGIC = b"SQLite format 3\x00"
|
||||
|
||||
|
||||
class RekordboxDriver:
|
||||
platform = "rekordbox"
|
||||
display_name = "Rekordbox"
|
||||
suffixes = (".db",)
|
||||
library_label = "master.db"
|
||||
selects = "file"
|
||||
|
||||
def can_open(self, path: Path) -> bool:
|
||||
"""Recognise an encrypted Rekordbox database.
|
||||
|
||||
Extension is not enough — plenty of things are called ``.db`` — and a
|
||||
SQLCipher file has no readable header at all (its first page is
|
||||
encrypted, so it does NOT start with the SQLite magic). So the probe
|
||||
decrypts just far enough to look for a table only Rekordbox has. That is
|
||||
one page read, and it is the only way to answer honestly.
|
||||
"""
|
||||
try:
|
||||
if not path.is_file() or path.suffix.lower() != ".db":
|
||||
return False
|
||||
with path.open("rb") as fh:
|
||||
if fh.read(len(_SQLITE_MAGIC)) == _SQLITE_MAGIC:
|
||||
return False # a plain, unencrypted SQLite file
|
||||
except OSError:
|
||||
return False
|
||||
return self._has_rekordbox_schema(path)
|
||||
|
||||
@staticmethod
|
||||
def _has_rekordbox_schema(path: Path) -> bool:
|
||||
try:
|
||||
import sqlcipher3.dbapi2 as sqlcipher
|
||||
from pyrekordbox.masterdb.database import BLOB
|
||||
from pyrekordbox.utils import deobfuscate
|
||||
except ImportError: # pragma: no cover — dependency missing
|
||||
return False
|
||||
con = None
|
||||
try:
|
||||
con = sqlcipher.connect(str(path))
|
||||
con.execute(f"PRAGMA key='{deobfuscate(BLOB)}'")
|
||||
row = con.execute(
|
||||
"SELECT name FROM sqlite_master WHERE type='table' AND name='djmdContent'"
|
||||
).fetchone()
|
||||
return row is not None
|
||||
except Exception: # noqa: BLE001 — wrong key or not a database
|
||||
return False
|
||||
finally:
|
||||
if con is not None:
|
||||
try:
|
||||
con.close()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
def open(self, path: Path) -> RekordboxAdapter:
|
||||
return RekordboxAdapter(path)
|
||||
|
||||
def detect(self) -> list[dict]:
|
||||
return discovery.detect_libraries()
|
||||
|
||||
def describe(self, path: Path) -> dict:
|
||||
return discovery.describe(path)
|
||||
|
||||
def restore(self, path: Path, data: bytes) -> None:
|
||||
"""Not supported: a Rekordbox library is more than one file.
|
||||
|
||||
`master.db` carries neither the beatgrids (ANLZ files) nor the playlist
|
||||
XML, and putting an old database back would also revert Rekordbox's auth
|
||||
token and sampler state. `capabilities.save.history` is False for the
|
||||
same reason, so nothing should reach this.
|
||||
"""
|
||||
raise NotImplementedError(
|
||||
"Konduktor does not version Rekordbox libraries: a restore would need "
|
||||
"the analysis files and would roll back Rekordbox's own app state."
|
||||
)
|
||||
@@ -0,0 +1,365 @@
|
||||
"""Writing a fresh Rekordbox `master.db` from nothing.
|
||||
|
||||
## The shape, and why it is not a hand-built schema
|
||||
|
||||
The handoff expected this to be the hard target — "a from-scratch SQLCipher
|
||||
master.db, lookup-table FKs, USN bookkeeping". Most of that turned out to be
|
||||
available:
|
||||
|
||||
* the **schema** is the checked-in DDL of a real Rekordbox 7 library,
|
||||
`fixtures/rekordbox/schema.sql`. NOT `Base.metadata.create_all()`, which was
|
||||
the plan until it failed: the ORM models 37 tables where the real thing has
|
||||
47, and marks columns NOT NULL that Rekordbox leaves nullable — a database
|
||||
built from the models refuses `agentRegistry` rows Rekordbox writes daily;
|
||||
* the **key** is the same one reading uses, `deobfuscate(BLOB)`, so an
|
||||
exported database is readable by any Rekordbox that reads the user's own;
|
||||
* `add_content`, `create_playlist`, `create_playlist_folder` and
|
||||
`add_to_playlist` already exist and assign the ids, UUIDs and USNs.
|
||||
|
||||
So this fills a new database through the library's own API rather than inventing
|
||||
row shapes — the same "create, then use the ordinary write path" the Traktor
|
||||
exporter uses, for the same reason: a second definition would drift from the one
|
||||
the read path is tested against.
|
||||
|
||||
## What is genuinely written here
|
||||
|
||||
**Cue rows and their JSON mirror.** Rekordbox keeps cues in `djmdCue` AND in a
|
||||
`contentCue.Cues` mirror that must agree; leaving the mirror stale is this
|
||||
platform's version of Traktor's companion-cue desync. Field conventions are the
|
||||
adapter's, not guessed: positions in frames at **150 fps**, `ContentUUID` is the
|
||||
TRACK's UUID, an uncoloured cue is `Color=-1`, a loop is `Color=255` with
|
||||
`BeatLoopSize = (beats << 16) | 1`, and `Kind` is the **sparse** bank
|
||||
`1,2,3,5,6,7,8,9` that skips 4 — taken from `cue_types.kind_for`, not
|
||||
redefined, because two copies of a mapping that subtle would drift.
|
||||
|
||||
**Analysis files.** The grid lives in a per-track ANLZ `PQTZ` tag, not in the
|
||||
database, so each track gets one built by the shared `anlz_writer` and pointed
|
||||
at by `djmdContent.AnalysisDataPath`. Rekordbox derives that path from the
|
||||
track's UUID — `/PIONEER/USBANLZ/<first 3>/<rest>/ANLZ0000.DAT` — which is
|
||||
reproduced here because the column and the file have to agree. That path is
|
||||
rooted at a **`share/` directory beside `master.db`**, not at the library root.
|
||||
|
||||
## The catch worth knowing
|
||||
|
||||
`djmdContent.FolderPath` is an **absolute host path**, unlike Traktor's
|
||||
volume-relative LOCATION and OneLibrary's drive-relative path. A Rekordbox
|
||||
export is therefore NOT portable to another machine by copying the folder: it
|
||||
describes files where they are right now. Swapping it into a Rekordbox install
|
||||
on the same machine works; carrying it to a gig does not.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import uuid as uuidlib
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
|
||||
from . import anlz_writer as W
|
||||
from .beatgrid import beats_from_markers
|
||||
from .capabilities import capabilities_for
|
||||
from .cue_types import kind_for
|
||||
from .projection import render_key
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
#: A real Rekordbox 7 library's DDL. See the fixture's README for why the ORM's
|
||||
#: `create_all()` is not used.
|
||||
_FIXTURES = Path(__file__).resolve().parents[3] / "fixtures" / "rekordbox"
|
||||
SCHEMA = _FIXTURES / "schema.sql"
|
||||
#: Rekordbox's own scaffolding rows — menu items, colours, categories, sort
|
||||
#: options. Not optional: `add_content` looks up djmdMenuItems('TRACK') and
|
||||
#: raises on an empty table. Carries no user data and no machine identity;
|
||||
#: `djmdDevice`/`djmdProperty` are generated per export instead.
|
||||
SEED = _FIXTURES / "seed.sql"
|
||||
|
||||
#: Rekordbox counts cue positions in frames at 150 fps, not milliseconds.
|
||||
FRAMES_PER_SECOND = 150
|
||||
OTHER_PLAYLIST = "Other"
|
||||
|
||||
|
||||
class RekordboxExporter:
|
||||
platform = "rekordbox"
|
||||
library_filename = "master.db"
|
||||
|
||||
def capabilities(self):
|
||||
"""What a Rekordbox library can hold, with no library to read.
|
||||
|
||||
`capabilities_for` normally takes the loaded library's version and cloud
|
||||
state; a brand-new one has no version and is definitionally not synced.
|
||||
"""
|
||||
return capabilities_for(
|
||||
None,
|
||||
editable_fields=[
|
||||
"title", "artist", "album", "genre", "label", "remixer",
|
||||
"release_date", "comment", "rating",
|
||||
],
|
||||
)
|
||||
|
||||
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
|
||||
# `masterdb`'s OWN key blob. `devicelib_plus` has a different one — a
|
||||
# OneLibrary drive uses a universal key shared across vendors, and
|
||||
# master.db does not. Mixing them up produces a database Rekordbox
|
||||
# cannot open, and pyrekordbox rejects the wrong one outright.
|
||||
import sqlcipher3.dbapi2 as sqlcipher
|
||||
from pyrekordbox.masterdb import MasterDatabase, models
|
||||
from pyrekordbox.masterdb.database import BLOB
|
||||
from pyrekordbox.utils import deobfuscate
|
||||
|
||||
root = Path(destination)
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
library = root / self.library_filename
|
||||
if library.exists():
|
||||
library.unlink() # SQLCipher will not re-key an existing file
|
||||
|
||||
key = deobfuscate(BLOB)
|
||||
con = sqlcipher.connect(str(library))
|
||||
try:
|
||||
con.execute(f"PRAGMA key='{key}'")
|
||||
con.executescript(SCHEMA.read_text())
|
||||
con.executescript(SEED.read_text())
|
||||
con.commit()
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
db = MasterDatabase(path=str(library), key=key)
|
||||
extra: list[Path] = []
|
||||
ids: dict[str, str] = {}
|
||||
try:
|
||||
self._seed_registry(db, models)
|
||||
self._seed_device(db, payload)
|
||||
rows = {}
|
||||
for item in payload.tracks:
|
||||
content = self._add_track(db, item)
|
||||
rows[item.source_id] = content
|
||||
ids[item.source_id] = str(content.ID)
|
||||
extra += self._write_anlz(item, content, root, db)
|
||||
self._write_playlists(db, payload, rows)
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
self._replay_cues(library, payload, ids)
|
||||
return WrittenLibrary(library=library, extra=extra)
|
||||
|
||||
@staticmethod
|
||||
def _replay_cues(library: Path, payload: ExportPayload, ids: dict) -> None:
|
||||
"""Write the cues through the ORDINARY adapter, not by hand.
|
||||
|
||||
Same reason the Traktor exporter replays commands: `set_cue` already
|
||||
owns every convention a cue row needs — the sparse `Kind` bank, frames
|
||||
at 150 fps, the loop encoding, and `_sync_content_cue`, which rebuilds
|
||||
the `contentCue` JSON mirror the rows must agree with. Writing those
|
||||
again here would be a second definition of all of it, untested, and a
|
||||
stale mirror is this platform's version of a desynced companion cue.
|
||||
"""
|
||||
from .adapter import RekordboxAdapter
|
||||
|
||||
adapter = RekordboxAdapter(library)
|
||||
try:
|
||||
for item in payload.tracks:
|
||||
track_id = ids.get(item.source_id)
|
||||
if track_id is None or not item.cues:
|
||||
continue
|
||||
for cue in item.cues.cues:
|
||||
# Memory cues are a Rekordbox-only concept the generic model
|
||||
# preserves but never writes; a cue with no slot has no pad
|
||||
# to land on.
|
||||
if cue.role != "hotcue" or cue.slot is None:
|
||||
continue
|
||||
adapter.set_cue(
|
||||
track_id,
|
||||
slot=cue.slot,
|
||||
start_sec=cue.start,
|
||||
cue_type=cue.type,
|
||||
length_sec=cue.length,
|
||||
name=cue.name,
|
||||
)
|
||||
adapter.save()
|
||||
finally:
|
||||
adapter.close()
|
||||
|
||||
# ---- rows -----------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _seed_registry(db, models) -> None:
|
||||
"""`agentRegistry.localUpdateCount` is where Rekordbox's USNs come from.
|
||||
|
||||
A database with no row there has nothing for the library's own
|
||||
bookkeeping to increment, so it is created before anything else.
|
||||
"""
|
||||
existing = db.query(models.AgentRegistry).filter_by(
|
||||
registry_id="localUpdateCount").first()
|
||||
if existing is not None:
|
||||
return
|
||||
# Inserted with raw SQL, NOT the ORM. `AgentRegistry`'s DateTime columns
|
||||
# bind through a processor that calls `.astimezone()` unconditionally,
|
||||
# so a NULL `date_1` — which is exactly what a real Rekordbox library
|
||||
# has — raises on INSERT. Reading such a row works; writing one does
|
||||
# not. Raw SQL sidesteps the processor and stores what Rekordbox stores.
|
||||
now = datetime.now().isoformat(sep=" ", timespec="milliseconds")
|
||||
db.session.execute(
|
||||
text('INSERT INTO "agentRegistry" (registry_id, int_1, created_at, '
|
||||
"updated_at) VALUES (:k, 1, :now, :now)"),
|
||||
{"k": "localUpdateCount", "now": now},
|
||||
)
|
||||
db.flush()
|
||||
|
||||
@staticmethod
|
||||
def _seed_device(db, payload: ExportPayload) -> None:
|
||||
"""This library's own identity — a fresh device and DB id per export.
|
||||
|
||||
Deliberately NOT copied from the fixture: a real `djmdDevice` row holds
|
||||
the machine's NAME and UUIDs, which have no business in a repo or in
|
||||
somebody else's exported library. Rekordbox stamps content rows with
|
||||
`MasterDBID`, so the value has to exist; it just has to be ours.
|
||||
"""
|
||||
now = datetime.now().isoformat(sep=" ", timespec="milliseconds")
|
||||
device_id = str(uuidlib.uuid4())
|
||||
db_id = str(uuidlib.uuid4().int % 2_147_483_647)
|
||||
db.session.execute(
|
||||
text('INSERT INTO "djmdProperty" (DBID, DBVersion, DeviceID, '
|
||||
"created_at, updated_at) VALUES (:db, '6000', :dev, :now, :now)"),
|
||||
{"db": db_id, "dev": device_id, "now": now},
|
||||
)
|
||||
db.session.execute(
|
||||
text('INSERT INTO "djmdDevice" (ID, MasterDBID, Name, UUID, '
|
||||
"rb_local_usn, created_at, updated_at) "
|
||||
"VALUES (:dev, :db, :name, :uuid, 1, :now, :now)"),
|
||||
{"dev": device_id, "db": db_id, "name": payload.name,
|
||||
"uuid": str(uuidlib.uuid4()), "now": now},
|
||||
)
|
||||
db.flush()
|
||||
|
||||
def _add_track(self, db, item: ExportTrack):
|
||||
"""One `djmdContent` row, through pyrekordbox's own helper."""
|
||||
track = item.track
|
||||
content = db.add_content(
|
||||
str(item.destination),
|
||||
Title=track.title,
|
||||
BPM=int(round((track.bpm or 0) * 100)) or None,
|
||||
Length=track.length,
|
||||
Rating=track.rating or 0,
|
||||
Commnt=track.comment,
|
||||
ReleaseDate=track.release_date,
|
||||
)
|
||||
# Lookups are foreign keys; pyrekordbox's add_* RAISES on an existing
|
||||
# name, so every one is find-or-create — the same rule the in-place
|
||||
# adapter follows.
|
||||
content.ArtistID = self._lookup(db, "artist", track.artist)
|
||||
content.AlbumID = self._lookup(db, "album", track.album)
|
||||
content.GenreID = self._lookup(db, "genre", track.genre)
|
||||
content.LabelID = self._lookup(db, "label", track.label)
|
||||
# NOT `track.key`: that is the SOURCE platform's notation, so a Traktor
|
||||
# export would put "10m" where Rekordbox shows "Cm".
|
||||
content.KeyID = self._lookup(db, "key", render_key(track.key_wheel, track.key_mode))
|
||||
db.flush()
|
||||
return content
|
||||
|
||||
@staticmethod
|
||||
def _lookup(db, kind: str, name: str | None):
|
||||
"""Find-or-create a lookup row, returning its id.
|
||||
|
||||
`djmdKey` is the odd one out twice over: its name column is `ScaleName`,
|
||||
not `Name`, and pyrekordbox has no `add_key`. So keys are inserted
|
||||
directly, with a `Seq` that keeps them in wheel order in Rekordbox's UI.
|
||||
"""
|
||||
if not name:
|
||||
return None
|
||||
if kind == "key":
|
||||
found = db.get_key(ScaleName=name).first()
|
||||
if found is not None:
|
||||
return found.ID
|
||||
return _insert_key(db, name)
|
||||
found = {"artist": db.get_artist, "album": db.get_album,
|
||||
"genre": db.get_genre, "label": db.get_label}[kind](Name=name).first()
|
||||
if found is not None:
|
||||
return found.ID
|
||||
created = {"artist": db.add_artist, "album": db.add_album,
|
||||
"genre": db.add_genre, "label": db.add_label}[kind](name)
|
||||
db.flush()
|
||||
return created.ID
|
||||
|
||||
# ---- analysis ---------------------------------------------------------------
|
||||
|
||||
def _write_anlz(self, item: ExportTrack, content, root: Path, db) -> list[Path]:
|
||||
"""The ANLZ file carrying this track's grid, and the column pointing at it.
|
||||
|
||||
Rekordbox derives the path from the track's UUID, and the database column
|
||||
and the file on disk have to agree — so the same derivation is used here
|
||||
rather than a path of our own choosing.
|
||||
"""
|
||||
track_uuid = str(content.UUID)
|
||||
# Rekordbox derives these two levels from the track's UUID, and the
|
||||
# column and the file have to agree — so the same derivation is used.
|
||||
rel = f"/PIONEER/USBANLZ/{track_uuid[:3]}/{track_uuid[3:]}/ANLZ0000.DAT"
|
||||
content.AnalysisDataPath = rel
|
||||
content.Analysed = 105 # what a rekordbox-analysed track carries
|
||||
content.AnalysisUpdated = 1
|
||||
db.flush()
|
||||
|
||||
tags = [W.path_tag(str(item.destination))]
|
||||
markers = item.cues.grid_markers if item.cues else []
|
||||
if markers:
|
||||
duration = float(item.track.length or 0) or (markers[-1].start + 60.0)
|
||||
nums, bpms, times = beats_from_markers(markers, duration)
|
||||
if nums:
|
||||
tags.append(W.beatgrid_tag(list(zip(nums, bpms, times))))
|
||||
# AnalysisDataPath is rooted at a `share` directory BESIDE master.db,
|
||||
# not at the library root — the read path joins it that way, and writing
|
||||
# it anywhere else produces a track whose grid silently reads as empty.
|
||||
return [W.write_anlz(root / "share" / rel.lstrip("/"), tags)]
|
||||
|
||||
# ---- playlists ---------------------------------------------------------------
|
||||
|
||||
def _write_playlists(self, db, payload: ExportPayload, rows: dict) -> None:
|
||||
"""The tree, under one folder named after the export."""
|
||||
root = db.create_playlist_folder(payload.name)
|
||||
db.flush()
|
||||
folders: dict[tuple[str, ...], object] = {(): root}
|
||||
|
||||
for playlist in payload.playlists:
|
||||
parent = root
|
||||
for depth in range(1, len(playlist.folders) + 1):
|
||||
branch = tuple(playlist.folders[:depth])
|
||||
if branch not in folders:
|
||||
folders[branch] = db.create_playlist_folder(
|
||||
branch[-1], parent=folders[branch[:-1]])
|
||||
db.flush()
|
||||
parent = folders[branch]
|
||||
self._fill(db, db.create_playlist(playlist.name, parent=parent),
|
||||
playlist.track_ids, rows)
|
||||
|
||||
claimed = {t for p in payload.playlists for t in p.track_ids}
|
||||
loose = [t.source_id for t in payload.tracks if t.source_id not in claimed]
|
||||
if loose:
|
||||
self._fill(db, db.create_playlist(OTHER_PLAYLIST, parent=root), loose, rows)
|
||||
|
||||
@staticmethod
|
||||
def _fill(db, playlist, track_ids: list[str], rows: dict) -> None:
|
||||
db.flush()
|
||||
for source_id in track_ids:
|
||||
content = rows.get(source_id)
|
||||
if content is not None:
|
||||
db.add_to_playlist(playlist, content)
|
||||
db.flush()
|
||||
|
||||
|
||||
def _insert_key(db, name: str) -> str:
|
||||
"""A `djmdKey` row. Raw SQL for the same reason the registry row is: the
|
||||
ORM's DateTime binder raises on the NULLs a real row carries."""
|
||||
from pyrekordbox.masterdb import models
|
||||
|
||||
now = datetime.now().isoformat(sep=" ", timespec="milliseconds")
|
||||
seq = (db.query(models.DjmdKey).count() or 0) + 1
|
||||
key_id = str(uuidlib.uuid4().int % 2_147_483_647)
|
||||
db.session.execute(
|
||||
text('INSERT INTO "djmdKey" (ID, ScaleName, Seq, UUID, created_at, '
|
||||
"updated_at) VALUES (:id, :name, :seq, :uuid, :now, :now)"),
|
||||
{"id": key_id, "name": name, "seq": seq,
|
||||
"uuid": str(uuidlib.uuid4()), "now": now},
|
||||
)
|
||||
db.flush()
|
||||
return key_id
|
||||
@@ -0,0 +1,218 @@
|
||||
"""Rekordbox native rows -> the generic projection.
|
||||
|
||||
The only place a ``pyrekordbox`` ORM object becomes a generic `Track` /
|
||||
`TrackCues`. Everything above this file sees generic types exclusively.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
|
||||
from . import beatgrid
|
||||
from .cue_types import cue_type, role_and_slot
|
||||
|
||||
# Rekordbox names keys musically ("Abm", "F", "Ebm") rather than in Camelot or
|
||||
# Open Key notation. Parsing that is platform knowledge and belongs here.
|
||||
_KEY_RE = re.compile(r"^([A-G])([#b]?)(m?)$", re.I)
|
||||
|
||||
# Camelot wheel position for each pitch class, per mode.
|
||||
_CAMELOT_MINOR = {
|
||||
"A": 8, "E": 9, "B": 10, "F#": 11, "Gb": 11, "C#": 12, "Db": 12,
|
||||
"G#": 1, "Ab": 1, "D#": 2, "Eb": 2, "A#": 3, "Bb": 3,
|
||||
"F": 4, "C": 5, "G": 6, "D": 7,
|
||||
}
|
||||
_CAMELOT_MAJOR = {
|
||||
"C": 8, "G": 9, "D": 10, "A": 11, "E": 12, "B": 1, "F#": 2, "Gb": 2,
|
||||
"C#": 3, "Db": 3, "G#": 4, "Ab": 4, "D#": 5, "Eb": 5, "A#": 6, "Bb": 6,
|
||||
"F": 7,
|
||||
}
|
||||
|
||||
|
||||
def parse_key(key: str | None) -> tuple[int | None, str | None]:
|
||||
"""(Camelot wheel position 1-12, mode) for a Rekordbox key name."""
|
||||
if not key:
|
||||
return None, None
|
||||
m = _KEY_RE.match(key.strip())
|
||||
if not m:
|
||||
return None, None
|
||||
letter, accidental, minor = m.group(1).upper(), m.group(2), m.group(3)
|
||||
pitch = letter + (accidental.replace("B", "b") if accidental else "")
|
||||
table = _CAMELOT_MINOR if minor else _CAMELOT_MAJOR
|
||||
n = table.get(pitch)
|
||||
return (n, "minor" if minor else "major") if n else (None, None)
|
||||
|
||||
|
||||
# The inverse, for EXPORT. A track arriving from Traktor carries `key` as
|
||||
# Traktor's own display string ("10m") and `key_wheel`/`key_mode` as the parsed
|
||||
# position — so writing the string verbatim into a Pioneer library would show
|
||||
# "10m" where the deck expects "Abm". Rendering from the wheel is the only
|
||||
# correct crossing. Shared with the OneLibrary exporter: same vendor, same
|
||||
# notation, and two tables would drift.
|
||||
_MINOR_NAMES = {v: k for k, v in reversed(list(_CAMELOT_MINOR.items()))}
|
||||
_MAJOR_NAMES = {v: k for k, v in reversed(list(_CAMELOT_MAJOR.items()))}
|
||||
|
||||
|
||||
def render_key(wheel: int | None, mode: str | None) -> str | None:
|
||||
"""A Pioneer-style key name ("Abm", "F") for a Camelot position + mode.
|
||||
|
||||
Returns None when the position is unknown, which is honest: a made-up key is
|
||||
worse than a blank one, and Pioneer software shows blanks without complaint.
|
||||
"""
|
||||
if not wheel or not (1 <= wheel <= 12):
|
||||
return None
|
||||
if mode == "minor":
|
||||
name = _MINOR_NAMES.get(wheel)
|
||||
return f"{name}m" if name else None
|
||||
return _MAJOR_NAMES.get(wheel)
|
||||
|
||||
|
||||
def _iso_date(value) -> str | None:
|
||||
"""Rekordbox already stores ISO-ish 'YYYY-MM-DD'; blanks become None."""
|
||||
if not value:
|
||||
return None
|
||||
s = str(value).strip()
|
||||
return s or None
|
||||
|
||||
|
||||
def _bpm(row) -> float | None:
|
||||
"""``djmdContent.BPM`` is the tempo x100, and 0 means 'not known'.
|
||||
|
||||
It is a display value only — the real grid is in the ANLZ file — and it is
|
||||
genuinely 0 for analysed tracks in real libraries.
|
||||
"""
|
||||
raw = getattr(row, "BPM", None)
|
||||
if not raw:
|
||||
return None
|
||||
return round(raw / 100.0, 2)
|
||||
|
||||
|
||||
def _name_of(related) -> str | None:
|
||||
"""A joined lookup row's display name, or None when unset."""
|
||||
if related is None:
|
||||
return None
|
||||
for attr in ("Name", "ScaleName"):
|
||||
value = getattr(related, attr, None)
|
||||
if value:
|
||||
return str(value)
|
||||
return None
|
||||
|
||||
|
||||
def to_track(row, cue_kinds=()) -> Track:
|
||||
"""Project one ``DjmdContent`` row.
|
||||
|
||||
`cue_kinds` is this track's ``(Kind, OutMsec)`` pairs from the store's single
|
||||
query — passed in rather than read off the row, which would be a per-track
|
||||
round trip. "Is this a hot cue, and on which pad?" is `role_and_slot`, the
|
||||
same definition `to_track_cues` uses, so the table's count and dots agree
|
||||
with the pads shown in the deck (it also rules out the reserved Kind).
|
||||
|
||||
**`grid_marker_count` is an approximation here**: the real count needs the
|
||||
track's ANLZ file, which is far too slow to read for every track at open
|
||||
(~12 s on a library of 8,500). A track with a BPM is reported as 1 (constant
|
||||
tempo, true for all but a fraction of a percent of real tracks) and the value
|
||||
is corrected the moment the track's grid is actually read.
|
||||
|
||||
BPM — not the presence of an analysis file — is the signal, because Rekordbox
|
||||
analyses one-shot samples too and gives them an ANLZ with no beatgrid at all.
|
||||
On the reference library the two sets agree exactly: all 22 tracks with no
|
||||
BPM are precisely the 22 with no grid.
|
||||
"""
|
||||
chips: list[HotcueChip] = []
|
||||
for kind, out_msec in cue_kinds:
|
||||
role, slot = role_and_slot(kind)
|
||||
if role == "hotcue" and slot is not None:
|
||||
# Rekordbox's colour is a palette index nobody has decoded yet (see
|
||||
# `_cue_color`), so no colour is claimed and the UI uses the type's.
|
||||
chips.append(HotcueChip(slot=slot, type=cue_type(out_msec), color=None))
|
||||
chips.sort(key=lambda chip: chip.slot)
|
||||
key_name = _name_of(getattr(row, "Key", None))
|
||||
wheel, mode = parse_key(key_name)
|
||||
return Track(
|
||||
id=str(row.ID),
|
||||
artist=_name_of(getattr(row, "Artist", None)),
|
||||
title=getattr(row, "Title", None),
|
||||
album=_name_of(getattr(row, "Album", None)),
|
||||
genre=_name_of(getattr(row, "Genre", None)),
|
||||
label=_name_of(getattr(row, "Label", None)),
|
||||
remixer=_name_of(getattr(row, "Remixer", None)),
|
||||
producer=None, # Rekordbox has Composer, which is not the same field
|
||||
mix=None,
|
||||
comment=getattr(row, "Commnt", None),
|
||||
bpm=_bpm(row),
|
||||
key=key_name,
|
||||
key_wheel=wheel,
|
||||
key_mode=mode,
|
||||
# Rekordbox stores 0-5 stars directly — no /51 conversion, unlike Traktor.
|
||||
rating=max(0, min(5, int(getattr(row, "Rating", 0) or 0))),
|
||||
playcount=getattr(row, "DJPlayCount", None),
|
||||
length=getattr(row, "Length", None),
|
||||
bitrate=getattr(row, "BitRate", None),
|
||||
import_date=_iso_date(getattr(row, "StockDate", None)),
|
||||
last_played=None, # not modelled as a date in master.db
|
||||
release_date=_iso_date(getattr(row, "ReleaseDate", None)),
|
||||
filepath=str(getattr(row, "FolderPath", "") or "") or None,
|
||||
cue_count=len(cue_kinds),
|
||||
hotcue_count=len(chips),
|
||||
hotcues=chips,
|
||||
grid_marker_count=1 if (_bpm(row) and getattr(row, "AnalysisDataPath", None)) else 0,
|
||||
grid_locked=False, # Rekordbox has no per-track grid lock
|
||||
media_kind="audio",
|
||||
)
|
||||
|
||||
|
||||
def to_track_cues(cue_rows: list, grid: tuple[list[float], list[float]] | None) -> TrackCues:
|
||||
"""Project a track's cues and beatgrid.
|
||||
|
||||
`grid` is the per-beat ``(times, bpms)`` from the ANLZ file, collapsed here
|
||||
into the generic marker list. Rekordbox pairs nothing with a grid marker, so
|
||||
`companion` is always None — that is a Traktor convention.
|
||||
|
||||
`editable` says whether the adapter will accept a command on THIS cue, which
|
||||
is the only thing the UI gates on. Every hot cue is editable, loops included.
|
||||
|
||||
**Memory cues are not**: Rekordbox is the only platform that has them, so
|
||||
under the two-platform promotion rule they are shown and never written. A cue
|
||||
sitting on the reserved `Kind` occupies no pad and is projected the same way,
|
||||
because that is how Rekordbox itself displays one.
|
||||
"""
|
||||
markers: list[GridMarker] = []
|
||||
if grid is not None:
|
||||
times, bpms = grid
|
||||
markers = beatgrid.markers_from_beats(times, bpms)
|
||||
|
||||
cues: list[CuePoint] = []
|
||||
for c in cue_rows:
|
||||
role, slot = role_and_slot(getattr(c, "Kind", None))
|
||||
out_msec = getattr(c, "OutMsec", None)
|
||||
in_msec = getattr(c, "InMsec", 0) or 0
|
||||
kind = cue_type(out_msec)
|
||||
length = 0.0
|
||||
if out_msec is not None and out_msec > 0:
|
||||
length = max(0.0, (out_msec - in_msec) / 1000.0)
|
||||
editable = role == "hotcue"
|
||||
cues.append(
|
||||
CuePoint(
|
||||
name=(getattr(c, "Comment", None) or None),
|
||||
type=kind,
|
||||
role=role,
|
||||
start=in_msec / 1000.0,
|
||||
length=length,
|
||||
slot=slot,
|
||||
color=_cue_color(c),
|
||||
editable=editable,
|
||||
readonly_reason=None if editable else "platform_managed",
|
||||
grid_marker=None,
|
||||
)
|
||||
)
|
||||
return TrackCues(grid_markers=markers, grid_locked=False, cues=cues)
|
||||
|
||||
|
||||
def _cue_color(row) -> str | None:
|
||||
"""Rekordbox stores a PALETTE INDEX, not an RGB value.
|
||||
|
||||
The generic model carries ``#RRGGBB``, and the built-in palette that index
|
||||
refers to is not yet known, so no colour is claimed rather than a wrong one
|
||||
being invented. `capabilities.cues.color` already says "palette", so the UI
|
||||
knows not to offer a free colour picker.
|
||||
"""
|
||||
return None
|
||||
@@ -0,0 +1,905 @@
|
||||
"""The retained native model for Rekordbox: the open ``master.db`` session.
|
||||
|
||||
This is the only module that knows ``pyrekordbox`` exists. It owns the decrypted
|
||||
SQLCipher session, the ANLZ analysis files, and the caches the projection reads.
|
||||
|
||||
**Writes cover track metadata and playlists.** Cues and the beatgrid are
|
||||
deliberately absent rather than stubbed — they are separate stores (two DB tables
|
||||
kept consistent, and the ANLZ analysis files) and a store that cannot write them
|
||||
cannot half-write them.
|
||||
|
||||
Edits accumulate in the SQLAlchemy session and are only made permanent by
|
||||
`save()`, which maps exactly onto Konduktor's "edit in memory, Save writes to
|
||||
disk" model. `pyrekordbox`'s `commit()` is what assigns Rekordbox's update
|
||||
sequence numbers, and a real Rekordbox was verified to accept and continue from
|
||||
the result — see the handoff's Findings.
|
||||
|
||||
Two things here are not obvious and are load-bearing:
|
||||
|
||||
* **ANLZ is read LAZILY.** The beatgrid lives in a per-track analysis file, not
|
||||
in the database, and parsing them all costs ~1.4 ms each — about 12 seconds
|
||||
for a library the size of the project's Traktor collection. So grids are
|
||||
parsed on demand and cached, and `Track.grid_marker_count` carries a
|
||||
documented approximation until a track's grid is actually read.
|
||||
* **Cue counts come from ONE aggregate query**, not from walking each track's
|
||||
relationship, which would be a per-track round trip at open.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import func, select, text
|
||||
from sqlalchemy.exc import OperationalError
|
||||
from sqlalchemy.orm import joinedload
|
||||
|
||||
from ...core.adapter import InvalidCommand, LibraryNotSupported, NotFound, SaveOutcome
|
||||
from ...core.edit_journal import EditJournal
|
||||
from ...core.pathmap import PathMapping
|
||||
from .cue_types import beat_loop_size, kind_for, role_and_slot
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _iso_stamp(value) -> str:
|
||||
"""Rekordbox writes timestamps in the JSON mirror as ISO-8601 with a
|
||||
+00:00 offset and millisecond precision (e.g. 2026-09-17T20:55:13.862+00:00).
|
||||
"""
|
||||
if isinstance(value, datetime):
|
||||
return value.strftime("%Y-%m-%dT%H:%M:%S.") + f"{value.microsecond // 1000:03d}+00:00"
|
||||
return str(value)
|
||||
|
||||
|
||||
class RekordboxStore:
|
||||
"""One open Rekordbox library."""
|
||||
|
||||
def __init__(self, path: Path):
|
||||
self.path = Path(path)
|
||||
self._mapping = PathMapping()
|
||||
self._grid_cache: dict[str, tuple[list[float], list[float]] | None] = {}
|
||||
self._journal = EditJournal()
|
||||
# Grid edits buffered until save(): ANLZ files are written to disk, so
|
||||
# applying them at command time would break the save contract.
|
||||
self._pending_grids: dict[str, tuple[list, list, list]] = {}
|
||||
self._load()
|
||||
|
||||
# ---- open ------------------------------------------------------------
|
||||
def _load(self) -> None:
|
||||
from pyrekordbox.masterdb import MasterDatabase
|
||||
from pyrekordbox.masterdb import models as tables
|
||||
|
||||
self._tables = tables
|
||||
try:
|
||||
self._db = MasterDatabase(path=str(self.path), unlock=True)
|
||||
except Exception as ex: # noqa: BLE001 — surfaced as a clean 4xx
|
||||
raise LibraryNotSupported(f"Could not open Rekordbox library: {ex}") from ex
|
||||
self._grid_cache.clear()
|
||||
self._content_cache: list | None = None
|
||||
self._by_id: dict[str, object] | None = None
|
||||
|
||||
def close(self) -> None:
|
||||
"""Release the session AND the pooled connection.
|
||||
|
||||
`pyrekordbox`'s own `close()` only closes the SQLAlchemy session, which
|
||||
returns the connection to the engine's pool — the OS file handle stays
|
||||
open. Disposing the engine is what actually releases `master.db`, and
|
||||
without it the file cannot be replaced (a restore, or a test copying a
|
||||
fresh library over it) on any platform that locks open files.
|
||||
"""
|
||||
try:
|
||||
self._db.close()
|
||||
except Exception: # noqa: BLE001 — closing must never raise
|
||||
pass
|
||||
try:
|
||||
self._db.engine.dispose()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
# ---- identity --------------------------------------------------------
|
||||
@property
|
||||
def cloud_synced(self) -> bool:
|
||||
"""True when this library participates in Rekordbox's Cloud Library Sync.
|
||||
|
||||
Konduktor REFUSES to write a cloud-synced library: a local edit that the
|
||||
server did not issue could propagate a corrupt sync state to the user's
|
||||
other machines, which version history cannot undo. Detection is the
|
||||
presence of a server-issued sequence number (`usn`) on any row, or a
|
||||
populated cloud registry.
|
||||
"""
|
||||
t = self._tables
|
||||
with self._db.session.no_autoflush:
|
||||
for table in (t.DjmdContent, t.DjmdPlaylist, t.DjmdCue):
|
||||
n = self._db.session.execute(
|
||||
select(func.count()).select_from(table).where(table.usn.isnot(None))
|
||||
).scalar()
|
||||
if n:
|
||||
return True
|
||||
# pyrekordbox does not model every cloud table, so the rest is a
|
||||
# raw probe: any row carrying a server-issued usn means synced.
|
||||
for table_name in ("cloudAgentRegistry", "djmdCloudProperty"):
|
||||
try:
|
||||
n = self._db.session.execute(
|
||||
text(f'SELECT COUNT(*) FROM "{table_name}" WHERE usn IS NOT NULL')
|
||||
).scalar()
|
||||
except Exception: # noqa: BLE001 — table may be absent
|
||||
continue
|
||||
if n:
|
||||
return True
|
||||
return False
|
||||
|
||||
@property
|
||||
def local_usn(self) -> int | None:
|
||||
"""Rekordbox's global local update counter (for diagnostics/tests)."""
|
||||
try:
|
||||
return self._db.get_local_usn()
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
|
||||
# ---- content ---------------------------------------------------------
|
||||
def iter_content(self) -> list:
|
||||
"""Every track, with the lookup tables eagerly joined.
|
||||
|
||||
Without `joinedload` each track's artist/album/genre/key would be a
|
||||
separate query — thousands of round trips on a real library.
|
||||
"""
|
||||
if self._content_cache is None:
|
||||
t = self._tables
|
||||
q = (
|
||||
self._db.session.query(t.DjmdContent)
|
||||
.options(
|
||||
joinedload(t.DjmdContent.Artist),
|
||||
joinedload(t.DjmdContent.Album),
|
||||
joinedload(t.DjmdContent.Genre),
|
||||
joinedload(t.DjmdContent.Key),
|
||||
joinedload(t.DjmdContent.Label),
|
||||
joinedload(t.DjmdContent.Remixer),
|
||||
)
|
||||
.filter(t.DjmdContent.rb_local_deleted == 0)
|
||||
)
|
||||
self._content_cache = list(q)
|
||||
self._by_id = {str(c.ID): c for c in self._content_cache}
|
||||
return self._content_cache
|
||||
|
||||
def content(self, track_id: str):
|
||||
self.iter_content()
|
||||
assert self._by_id is not None
|
||||
row = self._by_id.get(str(track_id))
|
||||
if row is None:
|
||||
raise NotFound(f"No track {track_id!r}")
|
||||
return row
|
||||
|
||||
def cue_kinds(self) -> dict[str, list[tuple[int | None, int | None]]]:
|
||||
"""``{track_id: [(Kind, OutMsec), ...]}`` for every live cue, in one query.
|
||||
|
||||
Just enough per cue for the library table's count and hotcue dots,
|
||||
without a per-track round trip. What a ``Kind`` means is decided in the
|
||||
projection, by the same `role_and_slot` the deck's cues use, so the
|
||||
table and the pads cannot disagree.
|
||||
"""
|
||||
t = self._tables
|
||||
rows = self._db.session.execute(
|
||||
select(t.DjmdCue.ContentID, t.DjmdCue.Kind, t.DjmdCue.OutMsec)
|
||||
.where(t.DjmdCue.rb_local_deleted == 0)
|
||||
).all()
|
||||
out: dict[str, list[tuple[int | None, int | None]]] = {}
|
||||
for content_id, kind, out_msec in rows:
|
||||
out.setdefault(str(content_id), []).append((kind, out_msec))
|
||||
return out
|
||||
|
||||
def cues(self, track_id: str) -> list:
|
||||
"""A track's cue rows, ordered by position."""
|
||||
t = self._tables
|
||||
return list(
|
||||
self._db.session.query(t.DjmdCue)
|
||||
.filter(t.DjmdCue.ContentID == str(track_id))
|
||||
.filter(t.DjmdCue.rb_local_deleted == 0)
|
||||
.order_by(t.DjmdCue.InMsec)
|
||||
)
|
||||
|
||||
# ---- playlists -------------------------------------------------------
|
||||
def playlists(self) -> list:
|
||||
"""User playlists, excluding Rekordbox's own internal ones.
|
||||
|
||||
Rekordbox keeps working lists ("CUE Analysis Playlist", "Cloud Library
|
||||
Sync") in the same table at reserved ids. They are not the user's and
|
||||
showing them in the sidebar would be noise.
|
||||
"""
|
||||
from pyrekordbox.masterdb.database import SPECIAL_PLAYLIST_IDS
|
||||
|
||||
t = self._tables
|
||||
return [
|
||||
p
|
||||
for p in self._db.session.query(t.DjmdPlaylist)
|
||||
.filter(t.DjmdPlaylist.rb_local_deleted == 0)
|
||||
.order_by(t.DjmdPlaylist.Seq)
|
||||
if str(p.ID) not in SPECIAL_PLAYLIST_IDS
|
||||
]
|
||||
|
||||
def playlist_song_ids(self, playlist_id: str) -> list[str]:
|
||||
t = self._tables
|
||||
rows = (
|
||||
self._db.session.query(t.DjmdSongPlaylist.ContentID)
|
||||
.filter(t.DjmdSongPlaylist.PlaylistID == str(playlist_id))
|
||||
.filter(t.DjmdSongPlaylist.rb_local_deleted == 0)
|
||||
.order_by(t.DjmdSongPlaylist.TrackNo)
|
||||
)
|
||||
return [str(r[0]) for r in rows]
|
||||
|
||||
def count_playlists(self) -> int:
|
||||
"""Playlists the user has, for the status bar — folders excluded."""
|
||||
folder = int(self._tables.PlaylistType.FOLDER)
|
||||
return sum(1 for p in self.playlists() if int(p.Attribute or 0) != folder)
|
||||
|
||||
# ---- analysis files (the beatgrid) -----------------------------------
|
||||
def anlz_grid(self, track_id: str) -> tuple[list[float], list[float]] | None:
|
||||
"""``(times_sec, bpms)`` per beat for a track, or None if unanalysed.
|
||||
|
||||
Parsed on demand and cached — see the module docstring for why this is
|
||||
not done eagerly.
|
||||
"""
|
||||
key = str(track_id)
|
||||
if key in self._grid_cache:
|
||||
return self._grid_cache[key]
|
||||
result = self._read_anlz_grid(key)
|
||||
self._grid_cache[key] = result
|
||||
return result
|
||||
|
||||
def _read_anlz_grid(self, track_id: str):
|
||||
row = self.content(track_id)
|
||||
rel = getattr(row, "AnalysisDataPath", None)
|
||||
if not rel:
|
||||
return None
|
||||
# AnalysisDataPath is rooted at the library's `share` directory and is
|
||||
# stored with a leading slash.
|
||||
path = self.path.parent / "share" / str(rel).lstrip("/\\")
|
||||
if not path.is_file():
|
||||
return None
|
||||
try:
|
||||
from pyrekordbox.anlz import AnlzFile
|
||||
|
||||
anlz = AnlzFile.parse_file(str(path))
|
||||
except Exception as ex: # noqa: BLE001 — a bad ANLZ must not break a read
|
||||
log.debug("ANLZ parse failed for %s: %s", track_id, ex)
|
||||
return None
|
||||
for tag in anlz.tags:
|
||||
# Never treat AnlzFile as a Mapping: keys()/len() recurse forever in
|
||||
# pyrekordbox 0.4.4.
|
||||
if tag.type == "PQTZ":
|
||||
try:
|
||||
return [float(t) for t in tag.times], [float(b) for b in tag.bpms]
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
return None
|
||||
|
||||
def has_analysis(self, track_id: str) -> bool:
|
||||
return bool(getattr(self.content(track_id), "AnalysisDataPath", None))
|
||||
|
||||
# ---- paths -----------------------------------------------------------
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None:
|
||||
self._mapping = mapping or PathMapping()
|
||||
|
||||
@property
|
||||
def path_mapping(self) -> PathMapping:
|
||||
return self._mapping
|
||||
|
||||
def audio_path(self, track_id: str) -> Path | None:
|
||||
"""The track's audio file on THIS machine, after any path remap."""
|
||||
folder = getattr(self.content(track_id), "FolderPath", None)
|
||||
if not folder:
|
||||
return None
|
||||
return self._mapping.apply(Path(str(folder)))
|
||||
|
||||
def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
|
||||
"""The art embedded in the audio file, else Rekordbox's own copy.
|
||||
|
||||
The file comes first because it is what Traktor reads too, so one track
|
||||
shows the same art on both platforms. Rekordbox's copy (`ImagePath`,
|
||||
rooted at `share/` like `AnalysisDataPath`) covers files it cannot be
|
||||
read from — a WAV, or a drive that is not mounted.
|
||||
"""
|
||||
from ...core import audio_tags
|
||||
|
||||
path = self.audio_path(track_id)
|
||||
if path is not None and path.is_file():
|
||||
art = audio_tags.read_cover(path)
|
||||
if art:
|
||||
return art
|
||||
rel = getattr(self.content(track_id), "ImagePath", None)
|
||||
if not rel:
|
||||
return None
|
||||
image = self.path.parent / "share" / str(rel).lstrip("/\\")
|
||||
try:
|
||||
data = image.read_bytes()
|
||||
except OSError:
|
||||
return None
|
||||
return data, "image/png" if image.suffix.lower() == ".png" else "image/jpeg"
|
||||
|
||||
def all_audio_paths(self) -> list[str]:
|
||||
return [
|
||||
str(c.FolderPath) for c in self.iter_content() if getattr(c, "FolderPath", None)
|
||||
]
|
||||
|
||||
# ---- writes: track metadata -----------------------------------------
|
||||
#
|
||||
# Deliberately NOT editable: the file path (it is the track's identity),
|
||||
# BPM and key (audio/grid territory), and Rekordbox's own read-only
|
||||
# bookkeeping. `producer` and `mix` are Traktor concepts with no Rekordbox
|
||||
# column — Rekordbox has a Composer, which is not the same field — so they
|
||||
# are simply absent from the set rather than mapped to something close.
|
||||
_DIRECT_FIELDS = {
|
||||
"title": "Title",
|
||||
"comment": "Commnt",
|
||||
"release_date": "ReleaseDate",
|
||||
}
|
||||
# Fields stored as a foreign key into a lookup table, which must be
|
||||
# found-or-created: `add_*` in pyrekordbox RAISES on an existing name.
|
||||
_LOOKUP_FIELDS = {
|
||||
"artist": ("DjmdArtist", "ArtistID", "add_artist"),
|
||||
"album": ("DjmdAlbum", "AlbumID", "add_album"),
|
||||
"genre": ("DjmdGenre", "GenreID", "add_genre"),
|
||||
"label": ("DjmdLabel", "LabelID", "add_label"),
|
||||
# A remixer IS an artist in Rekordbox — same table, different column.
|
||||
"remixer": ("DjmdArtist", "RemixerID", "add_artist"),
|
||||
}
|
||||
EDITABLE_FIELDS = set(_DIRECT_FIELDS) | set(_LOOKUP_FIELDS) | {"rating"}
|
||||
|
||||
def _lookup_id(self, table_name: str, adder: str, name: str) -> str | None:
|
||||
"""The id of the lookup row called `name`, creating it if needed."""
|
||||
if not name:
|
||||
return None
|
||||
table = getattr(self._tables, table_name)
|
||||
existing = self._db.session.query(table).filter_by(Name=name).first()
|
||||
if existing is not None:
|
||||
return str(existing.ID)
|
||||
row = getattr(self._db, adder)(name)
|
||||
return str(row.ID)
|
||||
|
||||
def set_track_metadata(self, track_id: str, fields: dict) -> None:
|
||||
row = self.content(track_id)
|
||||
for key, value in fields.items():
|
||||
if key not in self.EDITABLE_FIELDS:
|
||||
continue # unknown/!safe fields are ignored, never guessed at
|
||||
if key == "rating":
|
||||
try:
|
||||
stars = int(value or 0)
|
||||
except (TypeError, ValueError):
|
||||
raise InvalidCommand(f"Rating must be a number, got {value!r}") from None
|
||||
if not 0 <= stars <= 5:
|
||||
raise InvalidCommand(f"Rating must be 0-5, got {stars}")
|
||||
before, new = row.Rating, stars
|
||||
row.Rating = stars
|
||||
elif key in self._DIRECT_FIELDS:
|
||||
column = self._DIRECT_FIELDS[key]
|
||||
before = getattr(row, column)
|
||||
new = (value or None) if isinstance(value, str) else value
|
||||
setattr(row, column, new)
|
||||
else:
|
||||
table_name, column, adder = self._LOOKUP_FIELDS[key]
|
||||
before = getattr(row, column)
|
||||
new = self._lookup_id(table_name, adder, (value or "").strip())
|
||||
setattr(row, column, new)
|
||||
self._journal.record("track", "set", track_id, key, before, new)
|
||||
# Artist/album/genre/label are FOREIGN KEYS. Setting the id does not move
|
||||
# the ORM's cached relationship, so re-projecting the row immediately
|
||||
# would read the OLD name back and report a successful edit as a no-op.
|
||||
# Flush pushes the ids into the transaction; expiring the row makes the
|
||||
# next attribute access reload the joined rows with them.
|
||||
self._db.flush()
|
||||
self._db.session.expire(row)
|
||||
|
||||
# ---- writes: playlists ------------------------------------------------
|
||||
def _playlist(self, node_id: str):
|
||||
t = self._tables
|
||||
row = (
|
||||
self._db.session.query(t.DjmdPlaylist)
|
||||
.filter(t.DjmdPlaylist.ID == str(node_id))
|
||||
.first()
|
||||
)
|
||||
if row is None:
|
||||
raise NotFound(f"No playlist {node_id!r}")
|
||||
return row
|
||||
|
||||
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
|
||||
name = (name or "").strip()
|
||||
if not name:
|
||||
raise InvalidCommand("A playlist needs a name")
|
||||
parent = self._playlist(parent_id) if parent_id else None
|
||||
if parent is not None and int(parent.Attribute or 0) != int(
|
||||
self._tables.PlaylistType.FOLDER
|
||||
):
|
||||
raise InvalidCommand("A playlist can only be created inside a folder")
|
||||
row = self._db.create_playlist(name, parent=parent)
|
||||
self._journal.record("playlist", "create", name)
|
||||
return str(row.ID)
|
||||
|
||||
def create_folder(self, name: str, parent_id: str | None = None) -> str:
|
||||
name = (name or "").strip()
|
||||
if not name:
|
||||
raise InvalidCommand("A folder needs a name")
|
||||
parent = self._playlist(parent_id) if parent_id else None
|
||||
if parent is not None and int(parent.Attribute or 0) != int(
|
||||
self._tables.PlaylistType.FOLDER
|
||||
):
|
||||
raise InvalidCommand("A folder can only be created inside a folder")
|
||||
row = self._db.create_playlist_folder(name, parent=parent)
|
||||
self._journal.record("playlist", "create-folder", name)
|
||||
return str(row.ID)
|
||||
|
||||
def rename_playlist(self, node_id: str, name: str) -> None:
|
||||
name = (name or "").strip()
|
||||
if not name:
|
||||
raise InvalidCommand("A playlist needs a name")
|
||||
row = self._playlist(node_id)
|
||||
self._db.rename_playlist(row, name)
|
||||
self._journal.record("playlist", "rename", name)
|
||||
|
||||
def delete_playlist(self, node_id: str) -> None:
|
||||
row = self._playlist(node_id)
|
||||
name = row.Name
|
||||
self._db.delete_playlist(row)
|
||||
self._journal.record("playlist", "delete", name)
|
||||
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
|
||||
"""Replace a playlist's contents, in the given order.
|
||||
|
||||
Rekordbox keys order by `DjmdSongPlaylist.TrackNo`, and there is no
|
||||
bulk reorder — so this clears the list and re-adds it. `add_to_playlist`
|
||||
is used one row at a time because it is what maintains Rekordbox's own
|
||||
USN ordering for these rows.
|
||||
"""
|
||||
t = self._tables
|
||||
playlist = self._playlist(node_id)
|
||||
if int(playlist.Attribute or 0) != int(t.PlaylistType.PLAYLIST):
|
||||
raise InvalidCommand("Only a plain playlist has an editable track list")
|
||||
known = {tid for tid in track_ids if self._by_id and str(tid) in self._by_id}
|
||||
unknown = [tid for tid in track_ids if tid not in known]
|
||||
if unknown:
|
||||
raise NotFound(f"Unknown track(s): {', '.join(map(str, unknown[:3]))}")
|
||||
existing = (
|
||||
self._db.session.query(t.DjmdSongPlaylist)
|
||||
.filter(t.DjmdSongPlaylist.PlaylistID == str(node_id))
|
||||
.all()
|
||||
)
|
||||
for song in existing:
|
||||
self._db.remove_from_playlist(playlist, song)
|
||||
for n, track_id in enumerate(track_ids, start=1):
|
||||
self._db.add_to_playlist(playlist, str(track_id), track_no=n)
|
||||
self._journal.record("playlist", "entries", playlist.Name, after=len(track_ids))
|
||||
return len(track_ids)
|
||||
|
||||
# ---- save --------------------------------------------------------------
|
||||
@property
|
||||
def dirty(self) -> bool:
|
||||
return self._journal.dirty
|
||||
|
||||
def edited_fields(self, track_id: str) -> set[str]:
|
||||
return self._journal.fields_for(track_id)
|
||||
|
||||
def save(self) -> SaveOutcome:
|
||||
"""Make the session's edits permanent.
|
||||
|
||||
`commit(autoinc=True)` is what assigns Rekordbox's update sequence
|
||||
numbers — one increment per change, stamped onto each changed row. A real
|
||||
Rekordbox was verified to accept a library written this way and to carry
|
||||
on from the counter it was left at.
|
||||
|
||||
`snapshot` is None: a Rekordbox library is `master.db` plus its analysis
|
||||
files plus a playlist XML, so there is no single blob to version, and
|
||||
`capabilities.save.history` says so.
|
||||
"""
|
||||
summary = self._journal.summary()
|
||||
# Files first: if an analysis file cannot be written, nothing should have
|
||||
# been committed to the database either.
|
||||
self._flush_grids()
|
||||
self._commit()
|
||||
self._journal.clear()
|
||||
# Reads go through the same session, so nothing needs re-projecting from
|
||||
# scratch — but the grid cache is keyed by track and survives a save.
|
||||
return SaveOutcome(summary=summary, snapshot=None, tag_results=[])
|
||||
|
||||
def _commit(self) -> None:
|
||||
"""Commit, warning rather than refusing if Rekordbox is running.
|
||||
|
||||
`pyrekordbox.commit()` raises outright when it sees a Rekordbox process.
|
||||
That is not Konduktor's behaviour: the settled decision is to **warn but
|
||||
proceed**, matching how Traktor is handled — the user is told, not
|
||||
blocked on a detection heuristic. The check is also process-wide rather
|
||||
than per-file, so it would refuse to write a temp copy of a library while
|
||||
Rekordbox had an entirely different one open, which makes tests depend on
|
||||
whether the app happens to be running.
|
||||
|
||||
The veto is suppressed by neutralising the process probe for the duration
|
||||
of the call, so every other thing `commit()` does — the USN
|
||||
auto-increment, the session commit, and keeping `masterPlaylists6.xml`'s
|
||||
timestamps in step — still runs as the library intends. Duplicating that
|
||||
body here would silently drift from it on upgrade.
|
||||
"""
|
||||
from pyrekordbox.masterdb import database as rb_database
|
||||
|
||||
if rb_database.get_rekordbox_pid():
|
||||
log.warning(
|
||||
"Rekordbox appears to be running; saving anyway. It may overwrite "
|
||||
"or re-sync the library while it is open."
|
||||
)
|
||||
original = rb_database.get_rekordbox_pid
|
||||
rb_database.get_rekordbox_pid = lambda *a, **kw: 0
|
||||
try:
|
||||
self._db.commit(autoinc=True)
|
||||
except OperationalError as ex:
|
||||
# Suppressing pyrekordbox's veto does not remove SQLite's own lock:
|
||||
# a running Rekordbox really does hold the database, and the raw
|
||||
# error is an unhelpful 500. Say what happened and what to do.
|
||||
if "locked" not in str(ex).lower():
|
||||
raise
|
||||
raise InvalidCommand(
|
||||
"Rekordbox has the library open, so it cannot be written right "
|
||||
"now. Close Rekordbox and save again — your changes are still here."
|
||||
) from ex
|
||||
finally:
|
||||
rb_database.get_rekordbox_pid = original
|
||||
|
||||
@property
|
||||
def app_running(self) -> bool:
|
||||
"""Whether a Rekordbox process is up — for warning the user, not blocking."""
|
||||
try:
|
||||
from pyrekordbox.masterdb import database as rb_database
|
||||
|
||||
return bool(rb_database.get_rekordbox_pid())
|
||||
except Exception: # noqa: BLE001 — detection must never break a save
|
||||
return False
|
||||
|
||||
# ---- writes: cues -----------------------------------------------------
|
||||
#
|
||||
# Rekordbox keeps cues in TWO places that must agree: normalized `djmdCue`
|
||||
# rows, and a denormalized JSON mirror in `contentCue.Cues` alongside a
|
||||
# `rb_cue_count`. Every mutation here ends in `_sync_content_cue()`.
|
||||
#
|
||||
# Field conventions below are read off a real library (see the handoff's
|
||||
# Findings), not guessed:
|
||||
# * `Kind` is the bank slot; 0 means a memory cue.
|
||||
# * a loop is an ordinary cue row with `OutMsec` > 0 plus `BeatLoopSize`.
|
||||
# * `InFrame`/`OutFrame` are the position in frames at 150 fps.
|
||||
# * an uncoloured cue is `Color=-1, ColorTableIndex=NULL`; Rekordbox writes
|
||||
# `Color=255, ColorTableIndex=0` on the loops and auto-cues it creates.
|
||||
|
||||
_FPS = 150 # Rekordbox stores cue positions in frames as well as ms
|
||||
|
||||
@staticmethod
|
||||
def _frames(msec: int) -> int:
|
||||
return int(msec * RekordboxStore._FPS / 1000)
|
||||
|
||||
def _cue_row(self, track_id: str, slot: int):
|
||||
"""The hot cue occupying the 0-based generic `slot`, or None."""
|
||||
t = self._tables
|
||||
return (
|
||||
self._db.session.query(t.DjmdCue)
|
||||
.filter(t.DjmdCue.ContentID == str(track_id))
|
||||
.filter(t.DjmdCue.Kind == kind_for("hotcue", slot))
|
||||
.filter(t.DjmdCue.rb_local_deleted == 0)
|
||||
.first()
|
||||
)
|
||||
|
||||
def _loop_beats(self, track_id: str, start_sec: float, length_sec: float) -> int | None:
|
||||
"""Musical length of a loop, from the track's own tempo at that point."""
|
||||
if length_sec <= 0:
|
||||
return None
|
||||
bpm = None
|
||||
grid = self.anlz_grid(track_id)
|
||||
if grid:
|
||||
times, bpms = grid
|
||||
for t, b in zip(times, bpms):
|
||||
if t <= start_sec:
|
||||
bpm = b
|
||||
else:
|
||||
break
|
||||
if bpm is None and bpms:
|
||||
bpm = bpms[0]
|
||||
if not bpm:
|
||||
raw = getattr(self.content(track_id), "BPM", 0) or 0
|
||||
bpm = raw / 100.0 if raw else None
|
||||
if not bpm:
|
||||
return None
|
||||
beats = round(length_sec / (60.0 / bpm))
|
||||
return max(1, int(beats))
|
||||
|
||||
def set_cue(
|
||||
self,
|
||||
track_id: str,
|
||||
*,
|
||||
slot: int,
|
||||
start_sec: float,
|
||||
cue_type: str,
|
||||
length_sec: float = 0.0,
|
||||
name: str | None = None,
|
||||
) -> None:
|
||||
"""Create or replace the cue in `slot`. A loop is a cue with a length."""
|
||||
if start_sec < 0:
|
||||
raise InvalidCommand("A cue cannot be before the start of the track")
|
||||
if int(slot) < 0:
|
||||
raise InvalidCommand(f"Hot cue slot cannot be negative, got {slot}")
|
||||
row = self.content(track_id)
|
||||
in_ms = int(round(start_sec * 1000))
|
||||
is_loop = cue_type == "loop" and length_sec > 0
|
||||
out_ms = int(round((start_sec + length_sec) * 1000)) if is_loop else -1
|
||||
|
||||
kind = kind_for("hotcue", slot)
|
||||
existing = self._cue_row(track_id, slot)
|
||||
op = "add" if existing is None else "modify"
|
||||
cue = existing
|
||||
if cue is None:
|
||||
t = self._tables
|
||||
cue = t.DjmdCue.create(
|
||||
ID=str(self._db.generate_unused_id(t.DjmdCue)),
|
||||
ContentID=str(track_id),
|
||||
# Verified: a cue's ContentUUID is the TRACK's UUID, which is also
|
||||
# the id of its contentCue mirror row.
|
||||
ContentUUID=str(row.UUID),
|
||||
UUID=str(uuid.uuid4()),
|
||||
Kind=kind,
|
||||
rb_data_status=0,
|
||||
rb_local_data_status=0,
|
||||
rb_local_deleted=0,
|
||||
rb_local_synced=0,
|
||||
)
|
||||
self._db.add(cue)
|
||||
|
||||
cue.InMsec = in_ms
|
||||
cue.InFrame = self._frames(in_ms)
|
||||
cue.InMpegFrame = 0
|
||||
cue.InMpegAbs = 0
|
||||
cue.OutMsec = out_ms
|
||||
cue.OutFrame = self._frames(out_ms) if is_loop else 0
|
||||
cue.OutMpegFrame = 0
|
||||
cue.OutMpegAbs = 0
|
||||
cue.Kind = kind
|
||||
if is_loop:
|
||||
beats = self._loop_beats(track_id, start_sec, length_sec)
|
||||
cue.BeatLoopSize = beat_loop_size(beats) if beats else None
|
||||
cue.ActiveLoop = 0
|
||||
cue.CueMicrosec = 0
|
||||
cue.Color = 255
|
||||
cue.ColorTableIndex = 0
|
||||
else:
|
||||
cue.BeatLoopSize = None
|
||||
cue.ActiveLoop = None
|
||||
cue.CueMicrosec = None
|
||||
cue.Color = -1
|
||||
cue.ColorTableIndex = None
|
||||
cue.Comment = name or None
|
||||
|
||||
self._db.flush()
|
||||
self._sync_content_cue(track_id)
|
||||
self._journal.record("cue", op, track_id, f"slot:{slot}")
|
||||
|
||||
def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> None:
|
||||
cue = self._cue_row(track_id, slot)
|
||||
if cue is None:
|
||||
raise NotFound(f"No cue in slot {slot}")
|
||||
start = (cue.InMsec or 0) / 1000.0
|
||||
length = 0.0
|
||||
if cue_type == "loop":
|
||||
if cue.OutMsec and cue.OutMsec > 0:
|
||||
length = (cue.OutMsec - (cue.InMsec or 0)) / 1000.0
|
||||
else:
|
||||
raise InvalidCommand(
|
||||
"Turning a cue into a loop needs a length — set the loop first"
|
||||
)
|
||||
self.set_cue(
|
||||
track_id, slot=slot, start_sec=start, cue_type=cue_type,
|
||||
length_sec=length, name=cue.Comment,
|
||||
)
|
||||
|
||||
def delete_cue(self, track_id: str, slot: int) -> None:
|
||||
cue = self._cue_row(track_id, slot)
|
||||
if cue is None:
|
||||
raise NotFound(f"No cue in slot {slot}")
|
||||
self._db.delete(cue)
|
||||
self._db.flush()
|
||||
self._sync_content_cue(track_id)
|
||||
self._journal.record("cue", "delete", track_id, f"slot:{slot}")
|
||||
|
||||
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> None:
|
||||
"""Batch placement (Auto Hotcues). Fills empty slots unless overwriting."""
|
||||
for cue in cues:
|
||||
slot = int(getattr(cue, "slot"))
|
||||
if not overwrite and self._cue_row(track_id, slot) is not None:
|
||||
continue
|
||||
self.set_cue(
|
||||
track_id,
|
||||
slot=slot,
|
||||
start_sec=float(getattr(cue, "start", 0.0)),
|
||||
cue_type=getattr(cue, "type", "cue"),
|
||||
length_sec=float(getattr(cue, "length", 0.0) or 0.0),
|
||||
name=getattr(cue, "name", None),
|
||||
)
|
||||
|
||||
def _sync_content_cue(self, track_id: str) -> None:
|
||||
"""Rebuild the denormalized `contentCue` mirror for a track.
|
||||
|
||||
Rekordbox keeps a JSON copy of every cue alongside a count, and stamps
|
||||
its USN on THAT row rather than on the individual cue rows — it is the
|
||||
sync unit. Leaving it stale after editing `djmdCue` would make the two
|
||||
disagree, which is this platform's version of Traktor's companion-cue
|
||||
trap.
|
||||
|
||||
Keys whose value is NULL are omitted, which is what Rekordbox's own
|
||||
serializer does in every row observed.
|
||||
"""
|
||||
t = self._tables
|
||||
row = self.content(track_id)
|
||||
cues = (
|
||||
self._db.session.query(t.DjmdCue)
|
||||
.filter(t.DjmdCue.ContentID == str(track_id))
|
||||
.filter(t.DjmdCue.rb_local_deleted == 0)
|
||||
.order_by(t.DjmdCue.InMsec)
|
||||
.all()
|
||||
)
|
||||
fields = (
|
||||
"ID", "ContentID", "ContentUUID", "InMsec", "InFrame", "InMpegFrame",
|
||||
"InMpegAbs", "OutMsec", "OutFrame", "OutMpegFrame", "OutMpegAbs",
|
||||
"Kind", "Color", "ColorTableIndex", "ActiveLoop", "Comment",
|
||||
"BeatLoopSize", "CueMicrosec", "UUID",
|
||||
)
|
||||
records = []
|
||||
for cue in cues:
|
||||
rec = {}
|
||||
for field in fields:
|
||||
value = getattr(cue, field, None)
|
||||
if value is None:
|
||||
continue
|
||||
rec[field] = value
|
||||
for stamp in ("created_at", "updated_at"):
|
||||
value = getattr(cue, stamp, None)
|
||||
if value is not None:
|
||||
rec[stamp] = _iso_stamp(value)
|
||||
records.append(rec)
|
||||
|
||||
mirror = (
|
||||
self._db.session.query(t.ContentCue)
|
||||
.filter(t.ContentCue.ContentID == str(track_id))
|
||||
.first()
|
||||
)
|
||||
if mirror is None:
|
||||
if not records:
|
||||
return
|
||||
mirror = t.ContentCue.create(
|
||||
# Verified: the mirror's id IS the track's UUID.
|
||||
ID=str(row.UUID),
|
||||
ContentID=str(track_id),
|
||||
UUID=str(uuid.uuid4()),
|
||||
rb_data_status=0,
|
||||
rb_local_data_status=0,
|
||||
rb_local_deleted=0,
|
||||
rb_local_synced=0,
|
||||
)
|
||||
self._db.add(mirror)
|
||||
mirror.Cues = json.dumps(records, ensure_ascii=False)
|
||||
mirror.rb_cue_count = len(records)
|
||||
self._db.flush()
|
||||
|
||||
# ---- writes: the beatgrid ---------------------------------------------
|
||||
#
|
||||
# The grid lives in the track's ANLZ `.DAT` (`PQTZ`), not in the database.
|
||||
# Verified in Rekordbox 7: it reads the grid and the deck's BPM readout from
|
||||
# `PQTZ`, leaves a rewritten `.DAT` exactly as Konduktor wrote it, ignores
|
||||
# the stale extended grid in `.EXT` — and does NOT reconcile
|
||||
# `djmdContent.BPM`, which stayed at the old tempo while the deck showed the
|
||||
# new one. So that column is Konduktor's to maintain.
|
||||
#
|
||||
# Edits are BUFFERED and the files are written on save(), so the grid obeys
|
||||
# the same "edit in memory, Save writes to disk" contract as everything else
|
||||
# — an unsaved grid change must not already be on disk.
|
||||
|
||||
def current_markers(self, track_id: str) -> list:
|
||||
"""The track's grid as a generic marker list (pending edits included)."""
|
||||
from . import beatgrid as grid_math
|
||||
|
||||
grid = self.anlz_grid(track_id)
|
||||
if grid is None:
|
||||
return []
|
||||
times, bpms = grid
|
||||
return grid_math.markers_from_beats(times, bpms)
|
||||
|
||||
def track_duration(self, track_id: str) -> float:
|
||||
"""Seconds, for expanding markers back into beats."""
|
||||
length = getattr(self.content(track_id), "Length", None)
|
||||
if length:
|
||||
return float(length)
|
||||
grid = self.anlz_grid(track_id)
|
||||
if grid and grid[0]:
|
||||
return float(grid[0][-1]) + 1.0
|
||||
return 0.0
|
||||
|
||||
def replace_grid(self, track_id: str, markers: list) -> None:
|
||||
"""Set the grid to exactly these markers. The one primitive; every
|
||||
marker-level command is expressed as a read-modify-replace on top."""
|
||||
from . import beatgrid as grid_math
|
||||
|
||||
for m in markers:
|
||||
if m.bpm <= 0:
|
||||
raise InvalidCommand(f"A beatgrid marker needs a positive tempo, got {m.bpm}")
|
||||
if m.start < 0:
|
||||
raise InvalidCommand("A beatgrid marker cannot be before the track starts")
|
||||
ordered = sorted(markers, key=lambda m: m.start)
|
||||
duration = self.track_duration(track_id)
|
||||
beat_nums, bpms, times = grid_math.beats_from_markers(ordered, duration)
|
||||
# Buffer as the same (times, bpms) shape the reader returns, so the
|
||||
# projection needs no special case for an unsaved grid.
|
||||
self._pending_grids[str(track_id)] = (beat_nums, bpms, times)
|
||||
self._grid_cache[str(track_id)] = (times, bpms) if times else None
|
||||
# TEMPO mirrors the first marker, exactly as Traktor's <TEMPO> does —
|
||||
# Rekordbox will not do it for us.
|
||||
row = self.content(track_id)
|
||||
row.BPM = int(round(ordered[0].bpm * 100)) if ordered else 0
|
||||
self._journal.record("grid", "replace" if ordered else "delete", track_id)
|
||||
|
||||
def delete_grid(self, track_id: str) -> None:
|
||||
self.replace_grid(track_id, [])
|
||||
|
||||
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> None:
|
||||
from ...core.model import GridMarker
|
||||
|
||||
markers = self.current_markers(track_id)
|
||||
if bpm is None:
|
||||
# Inherit the tempo governing this point, like Traktor's add does.
|
||||
governing = [m for m in markers if m.start <= start_sec]
|
||||
bpm = governing[-1].bpm if governing else (markers[0].bpm if markers else None)
|
||||
if not bpm:
|
||||
raise InvalidCommand("The first marker on an ungridded track needs a tempo")
|
||||
if any(abs(m.start - start_sec) < 0.001 for m in markers):
|
||||
raise InvalidCommand("There is already a marker here")
|
||||
markers.append(GridMarker(start=float(start_sec), bpm=float(bpm)))
|
||||
self.replace_grid(track_id, markers)
|
||||
|
||||
def _marker_at(self, track_id: str, index: int) -> tuple[list, int]:
|
||||
markers = self.current_markers(track_id)
|
||||
if not 0 <= index < len(markers):
|
||||
raise NotFound(f"No grid marker {index}")
|
||||
return markers, index
|
||||
|
||||
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> None:
|
||||
markers, i = self._marker_at(track_id, index)
|
||||
# Clamp between neighbours so the list cannot reorder under the caller.
|
||||
low = markers[i - 1].start + 0.001 if i > 0 else 0.0
|
||||
high = markers[i + 1].start - 0.001 if i + 1 < len(markers) else None
|
||||
target = max(low, float(start_sec))
|
||||
if high is not None:
|
||||
target = min(target, high)
|
||||
markers[i] = markers[i].model_copy(update={"start": target})
|
||||
self.replace_grid(track_id, markers)
|
||||
|
||||
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> None:
|
||||
markers, i = self._marker_at(track_id, index)
|
||||
if bpm <= 0:
|
||||
raise InvalidCommand(f"A tempo must be positive, got {bpm}")
|
||||
markers[i] = markers[i].model_copy(update={"bpm": float(bpm)})
|
||||
self.replace_grid(track_id, markers)
|
||||
|
||||
def delete_grid_marker(self, track_id: str, index: int) -> None:
|
||||
markers, i = self._marker_at(track_id, index)
|
||||
del markers[i]
|
||||
self.replace_grid(track_id, markers)
|
||||
|
||||
def _flush_grids(self) -> None:
|
||||
"""Write buffered grids into their ANLZ files. Called by save().
|
||||
|
||||
Only `.DAT`'s `PQTZ` is written — `.EXT`'s extended grid carries
|
||||
undecoded bytes, and Rekordbox was verified to read the grid from
|
||||
`PQTZ` and to be untroubled by the other being stale.
|
||||
"""
|
||||
from . import beatgrid as grid_math
|
||||
|
||||
for track_id, (beat_nums, bpms, times) in list(self._pending_grids.items()):
|
||||
rel = getattr(self.content(track_id), "AnalysisDataPath", None)
|
||||
if not rel:
|
||||
raise InvalidCommand(
|
||||
"This track has no analysis file, so it has nowhere to store a beatgrid"
|
||||
)
|
||||
path = self.path.parent / "share" / str(rel).lstrip("/\\")
|
||||
if not path.is_file():
|
||||
raise InvalidCommand(f"Analysis file is missing: {path}")
|
||||
grid_math.write_pqtz(path, beat_nums, bpms, times)
|
||||
self._pending_grids.clear()
|
||||
@@ -0,0 +1,17 @@
|
||||
"""The Traktor adapter: NML v20 (Traktor Pro 4) via ``traktor-nml-utils``.
|
||||
|
||||
Importing this package registers the platform, so ``core.registry`` can find it
|
||||
without knowing it exists — and registers it as an export TARGET, which is a
|
||||
separate registry because opening a library and creating one from nothing are
|
||||
different capabilities: Rekordbox has the first and not the second.
|
||||
"""
|
||||
from ...core import export as core_export
|
||||
from ...core import registry
|
||||
from .driver import TraktorDriver
|
||||
from .export import TraktorExporter
|
||||
|
||||
TRAKTOR = TraktorDriver()
|
||||
registry.register(TRAKTOR)
|
||||
|
||||
TRAKTOR_EXPORTER = TraktorExporter()
|
||||
core_export.register(TRAKTOR_EXPORTER)
|
||||
@@ -0,0 +1,403 @@
|
||||
"""The Traktor adapter: owns the native NML model and the generic projection.
|
||||
|
||||
This is the object the app talks to. It holds:
|
||||
|
||||
* a ``TraktorStore`` — the retained NATIVE model, which is the write target.
|
||||
Commands are replayed onto it; it is never regenerated from the projection.
|
||||
* a ``TrackIndex`` — the generic READ projection, rebuilt from the store.
|
||||
|
||||
Only one parse happens per open, and the projection is refreshed from the same
|
||||
object graph the commands mutate — so the two cannot drift.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
from ...core.adapter import InvalidCommand, NotFound, Unsupported
|
||||
from ...core.capabilities import Capabilities
|
||||
from ...core.model import PlaylistNode, Track, TrackCues
|
||||
from ...core.pathmap import PathMapping
|
||||
from ...core.query import TrackIndex
|
||||
from . import capabilities as caps
|
||||
from . import projection
|
||||
from .cue_types import CUE_TYPE_TO_NATIVE
|
||||
from .store import PlaylistError, TraktorStore
|
||||
|
||||
|
||||
|
||||
|
||||
class TraktorAdapter:
|
||||
platform = "traktor"
|
||||
|
||||
def __init__(self, path: Path):
|
||||
self.path = Path(path)
|
||||
self._store = TraktorStore(self.path)
|
||||
self._index = TrackIndex()
|
||||
self._rebuild()
|
||||
|
||||
# ---- projection maintenance ----------------------------------------
|
||||
def _rebuild(self) -> None:
|
||||
"""Re-project every track. Needed after a save or a path remap, where
|
||||
track ids themselves change and a per-track patch is impossible."""
|
||||
self._index.rebuild([projection.to_track(e) for e in self._store.iter_entries()])
|
||||
|
||||
def _refresh(self, track_id: str) -> TrackCues:
|
||||
"""Re-project one track after a command, and return its fresh cues."""
|
||||
entry = self._store.model_entry(track_id)
|
||||
if entry is None:
|
||||
return TrackCues()
|
||||
self._index.replace(projection.to_track(entry))
|
||||
return projection.to_track_cues(entry)
|
||||
|
||||
# ---- read ------------------------------------------------------------
|
||||
@property
|
||||
def tracks(self) -> list[Track]:
|
||||
return self._index.tracks
|
||||
|
||||
@property
|
||||
def by_key(self) -> dict[str, Track]:
|
||||
return self._index.by_key
|
||||
|
||||
def track(self, track_id: str) -> Track | None:
|
||||
return self._index.get(track_id)
|
||||
|
||||
def query_tracks(self, **kw):
|
||||
return self._index.query_tracks(**kw)
|
||||
|
||||
def facets(self):
|
||||
return self._index.facets()
|
||||
|
||||
def stats(self, playlist_count: int):
|
||||
return self._index.stats(playlist_count)
|
||||
|
||||
def track_cues(self, track_id: str) -> TrackCues | None:
|
||||
entry = self._store.model_entry(track_id)
|
||||
return projection.to_track_cues(entry) if entry is not None else None
|
||||
|
||||
# ---- transitional shims --------------------------------------------
|
||||
# main.py still drives the store directly and calls replace_track after each
|
||||
# command; both go away when the routes move onto the protocol (step 7).
|
||||
@property
|
||||
def store(self) -> TraktorStore:
|
||||
return self._store
|
||||
|
||||
def entries_for(self, track_ids: list[str]) -> list[tuple[str, str]]:
|
||||
return self._store.entries_for(track_ids)
|
||||
|
||||
def replace_track(self, track_id: str, entry=None) -> None:
|
||||
self._refresh(track_id)
|
||||
|
||||
def reload(self) -> None:
|
||||
self._store._load()
|
||||
self._rebuild()
|
||||
|
||||
def playlist_count(self) -> int:
|
||||
return self._store.count_playlists()
|
||||
|
||||
def capabilities(self) -> Capabilities:
|
||||
return caps.capabilities_for(self.path, sorted(TraktorStore.EDITABLE_FIELDS))
|
||||
|
||||
# ---- playlists -------------------------------------------------------
|
||||
def playlist_tree(self) -> list[PlaylistNode]:
|
||||
return self._store.tree()
|
||||
|
||||
def playlist_entries(self, node_id: str) -> list[str] | None:
|
||||
return self._store.entry_keys(node_id)
|
||||
|
||||
def playlist_tracks(self, node_id: str) -> list[Track] | None:
|
||||
keys = self._store.entry_keys(node_id)
|
||||
if keys is None:
|
||||
return None
|
||||
return [t for k in keys if (t := self._index.get(k)) is not None]
|
||||
|
||||
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
|
||||
with _translate():
|
||||
return self._store.create_playlist(name, parent_id)
|
||||
|
||||
def create_folder(self, name: str, parent_id: str | None = None) -> str:
|
||||
with _translate():
|
||||
return self._store.create_folder(name, parent_id)
|
||||
|
||||
def rename_playlist(self, node_id: str, name: str) -> None:
|
||||
with _translate():
|
||||
self._store.rename_playlist(node_id, name)
|
||||
|
||||
def delete_playlist(self, node_id: str) -> None:
|
||||
with _translate():
|
||||
self._store.delete_playlist(node_id)
|
||||
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
|
||||
"""Replace a playlist's contents. The adapter resolves each id to its
|
||||
native entry kind, so callers never see Traktor's STEM/TRACK split."""
|
||||
entries = self._store.entries_for(track_ids)
|
||||
with _translate():
|
||||
self._store.set_entries(node_id, entries)
|
||||
return len(entries)
|
||||
|
||||
# ---- metadata / art --------------------------------------------------
|
||||
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None:
|
||||
with _translate():
|
||||
self._store.set_track_metadata(track_id, fields)
|
||||
self._refresh(track_id)
|
||||
return self._index.get(track_id)
|
||||
|
||||
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
|
||||
with _translate():
|
||||
self._store.set_track_art(track_id, data, mime)
|
||||
|
||||
def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
|
||||
return self._store.cover_art(track_id)
|
||||
|
||||
# ---- removing tracks ---------------------------------------------------
|
||||
def remove_tracks(self, track_ids: list[str]) -> int:
|
||||
with _translate():
|
||||
n = self._store.remove_entries(track_ids)
|
||||
if n:
|
||||
# Rebuilt rather than patched: an entry sharing a removed key went
|
||||
# too, and the index would otherwise still hold its projection.
|
||||
self._rebuild()
|
||||
return n
|
||||
|
||||
# ---- adding tracks ----------------------------------------------------
|
||||
def add_tracks(self, items: list) -> list[str]:
|
||||
"""Add tracks that came from somewhere else, with their prep.
|
||||
|
||||
Two steps, and the split is the point. The store creates a bare ENTRY —
|
||||
the only genuinely new code — and then the track's cues and grid are
|
||||
written by **replaying the ordinary commands** onto it. So an imported
|
||||
track's beatgrid goes in through the same `replace_grid` that the deck's
|
||||
Reset button uses, and inherits its companion-cue handling, its TEMPO
|
||||
mirroring and its tests, rather than growing a second implementation
|
||||
that would drift.
|
||||
|
||||
Lossiness follows the settled rule — degrade to the nearest equivalent,
|
||||
drop only where none exists:
|
||||
|
||||
* **Memory cues become hot cues in spare slots.** Traktor has no
|
||||
memory cues, and every Traktor cue occupies a slot. Filling the
|
||||
leftovers preserves the positions a DJ actually marked; when the
|
||||
bank is full the rest are dropped, because there is nowhere left.
|
||||
* **Cue colour is dropped.** Traktor derives a cue's colour from its
|
||||
type, so a free RGB value has nowhere to go.
|
||||
|
||||
Returns the new track ids, in the order the items were given.
|
||||
"""
|
||||
added: list[str] = []
|
||||
for item in items:
|
||||
audio = Path(item.audio_path)
|
||||
if not audio.is_file():
|
||||
raise InvalidCommand(f"No audio file at {audio}")
|
||||
with _translate():
|
||||
track_id = self._store.add_entry(item.track, audio)
|
||||
# Into the projection BEFORE the cues are replayed: those go through
|
||||
# the ordinary commands, and those look the track up by id.
|
||||
entry = self._store.model_entry(track_id)
|
||||
self._index.add(projection.to_track(entry))
|
||||
added.append(track_id)
|
||||
if item.cues is not None:
|
||||
self._apply_imported_cues(track_id, item.cues)
|
||||
self._refresh(track_id)
|
||||
return added
|
||||
|
||||
def _apply_imported_cues(self, track_id: str, cues) -> None:
|
||||
"""Replay a generic TrackCues onto a freshly added entry."""
|
||||
markers = [(m.start, m.bpm) for m in (cues.grid_markers or [])]
|
||||
if markers:
|
||||
# `replace_grid`, NOT `set_analysed_grid`. The latter also places
|
||||
# Traktor's beat-1 companion cue, and that is wrong twice over here:
|
||||
# it invents a cue the source never had (companions are a Traktor
|
||||
# convention, and the project's rule is to follow them but never
|
||||
# invent one outside Auto Grid), and it occupies pad A — which
|
||||
# silently displaced the imported track's own pad A cue.
|
||||
self.replace_grid(track_id, markers)
|
||||
|
||||
slots = self.capabilities().cues.hotcue_slots
|
||||
taken = {c.slot for c in self.track_cues(track_id).cues if c.slot is not None}
|
||||
hotcues = [c for c in (cues.cues or []) if c.role == "hotcue" and c.slot is not None]
|
||||
|
||||
# Hot cues keep the pad they were on wherever that pad is free, because
|
||||
# muscle memory is most of what a hot cue layout IS.
|
||||
displaced: list = []
|
||||
for cue in sorted(hotcues, key=lambda c: c.slot):
|
||||
if cue.slot in taken or not (0 <= cue.slot < slots):
|
||||
displaced.append(cue)
|
||||
continue
|
||||
self._place_imported_cue(track_id, cue.slot, cue)
|
||||
taken.add(cue.slot)
|
||||
|
||||
# Everything without a pad of its own competes for what is left: memory
|
||||
# cues, which Traktor has no equivalent for, and any hot cue whose pad
|
||||
# was already occupied. Earliest first, so that when the bank runs out
|
||||
# it is the late cues that are lost rather than an arbitrary set — and
|
||||
# a displaced hot cue is moved rather than dropped, because losing one
|
||||
# silently is much worse than having it turn up on the wrong pad.
|
||||
leftovers = displaced + [c for c in (cues.cues or []) if c.role != "hotcue"]
|
||||
spare = (s for s in range(slots) if s not in taken)
|
||||
for cue in sorted(leftovers, key=lambda c: c.start):
|
||||
slot = next(spare, None)
|
||||
if slot is None:
|
||||
break # bank full: the rest are dropped, per the lossiness rule
|
||||
self._place_imported_cue(track_id, slot, cue)
|
||||
|
||||
def _place_imported_cue(self, track_id: str, slot: int, cue) -> None:
|
||||
cue_type = "loop" if getattr(cue, "length", 0) else "cue"
|
||||
if cue_type not in CUE_TYPE_TO_NATIVE:
|
||||
return
|
||||
self.set_cue(
|
||||
track_id,
|
||||
slot=slot,
|
||||
start_sec=cue.start,
|
||||
cue_type=cue_type,
|
||||
length_sec=getattr(cue, "length", 0.0) or 0.0,
|
||||
name=getattr(cue, "name", None),
|
||||
)
|
||||
|
||||
# ---- cues -------------------------------------------------------------
|
||||
def _native_cue_type(self, cue_type: str) -> int:
|
||||
native = CUE_TYPE_TO_NATIVE.get(cue_type)
|
||||
if native is None:
|
||||
raise Unsupported(f"Traktor has no cue type {cue_type!r}")
|
||||
return native
|
||||
|
||||
def set_cue(
|
||||
self,
|
||||
track_id: str,
|
||||
*,
|
||||
slot: int,
|
||||
start_sec: float,
|
||||
cue_type: str,
|
||||
length_sec: float = 0.0,
|
||||
role: str = "hotcue",
|
||||
name: str | None = None,
|
||||
) -> TrackCues:
|
||||
if role != "hotcue":
|
||||
# Memory cues are a Rekordbox concept; every Traktor cue holds a slot.
|
||||
raise Unsupported("Traktor cues always occupy a hotcue slot")
|
||||
with _translate():
|
||||
self._store.set_hotcue(
|
||||
track_id, slot, start_sec, self._native_cue_type(cue_type), length_sec, name
|
||||
)
|
||||
return self._refresh(track_id)
|
||||
|
||||
def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> TrackCues:
|
||||
with _translate():
|
||||
self._store.set_hotcue_type(track_id, slot, self._native_cue_type(cue_type))
|
||||
return self._refresh(track_id)
|
||||
|
||||
def delete_cue(self, track_id: str, slot: int) -> TrackCues:
|
||||
with _translate():
|
||||
self._store.delete_hotcue(track_id, slot)
|
||||
return self._refresh(track_id)
|
||||
|
||||
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues:
|
||||
native = [
|
||||
SimpleNamespace(
|
||||
slot=c.slot,
|
||||
start=c.start,
|
||||
name=c.name,
|
||||
type=self._native_cue_type(getattr(c, "type", "cue")),
|
||||
length=getattr(c, "length", 0.0),
|
||||
)
|
||||
for c in cues
|
||||
]
|
||||
with _translate():
|
||||
self._store.place_hotcues(track_id, native, overwrite=overwrite)
|
||||
return self._refresh(track_id)
|
||||
|
||||
# ---- beatgrid ---------------------------------------------------------
|
||||
def add_grid_marker(self, track_id, start_sec, bpm=None) -> TrackCues:
|
||||
with _translate():
|
||||
self._store.add_grid_marker(track_id, start_sec, bpm)
|
||||
return self._refresh(track_id)
|
||||
|
||||
def move_grid_marker(self, track_id, index, start_sec) -> TrackCues:
|
||||
with _translate():
|
||||
self._store.move_grid_marker(track_id, index, start_sec)
|
||||
return self._refresh(track_id)
|
||||
|
||||
def set_grid_marker_bpm(self, track_id, index, bpm) -> TrackCues:
|
||||
with _translate():
|
||||
self._store.set_grid_marker_bpm(track_id, index, bpm)
|
||||
return self._refresh(track_id)
|
||||
|
||||
def delete_grid_marker(self, track_id, index) -> TrackCues:
|
||||
with _translate():
|
||||
self._store.delete_grid_marker(track_id, index)
|
||||
return self._refresh(track_id)
|
||||
|
||||
def replace_grid(self, track_id, markers: list[tuple[float, float]]) -> TrackCues:
|
||||
"""Set exactly these markers and nothing else (the deck's Reset)."""
|
||||
with _translate():
|
||||
self._store.replace_grid(track_id, markers)
|
||||
return self._refresh(track_id)
|
||||
|
||||
def set_analysed_grid(self, track_id, markers: list[tuple[float, float]]) -> TrackCues:
|
||||
"""Write an analysis result the way this platform's own analyser would.
|
||||
|
||||
Traktor pairs its first grid marker with a white beat-1 cue, so a grid it
|
||||
wrote looks different from one merely assigned. Keeping that as a
|
||||
separate intent is what lets the companion convention stay inside this
|
||||
adapter instead of leaking into the generic vocabulary.
|
||||
"""
|
||||
with _translate():
|
||||
self._store.replace_grid(track_id, markers)
|
||||
self._store.place_grid_companion(track_id, 0, prefer_slot=0)
|
||||
return self._refresh(track_id)
|
||||
|
||||
def delete_grid(self, track_id) -> TrackCues:
|
||||
with _translate():
|
||||
self._store.delete_grid(track_id)
|
||||
return self._refresh(track_id)
|
||||
|
||||
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues:
|
||||
with _translate():
|
||||
self._store.set_lock(track_id, locked)
|
||||
return self._refresh(track_id)
|
||||
|
||||
# ---- audio / paths ----------------------------------------------------
|
||||
def audio_path(self, track_id: str):
|
||||
return self._store.audio_path(track_id)
|
||||
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None:
|
||||
self._store.set_path_mapping(mapping)
|
||||
|
||||
def path_prefix_suggestions(self) -> dict:
|
||||
return self._store.path_prefix_suggestions()
|
||||
|
||||
def remap_preview(self, mapping: PathMapping) -> dict:
|
||||
return self._store.remap_preview(mapping)
|
||||
|
||||
def remap_locations(self, mapping: PathMapping) -> dict[str, str]:
|
||||
with _translate():
|
||||
moved = self._store.remap_locations(mapping)
|
||||
# A remap rewrites LOCATIONs, so track ids themselves change — there is
|
||||
# no per-track patch that could express this.
|
||||
self._rebuild()
|
||||
return moved
|
||||
|
||||
# ---- save --------------------------------------------------------------
|
||||
@property
|
||||
def dirty(self) -> bool:
|
||||
return self._store.dirty
|
||||
|
||||
def save(self):
|
||||
outcome = self._store.save()
|
||||
self._rebuild() # save() re-parses, so every object identity changed
|
||||
return outcome
|
||||
|
||||
def snapshot(self) -> bytes:
|
||||
return self._store._render()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _translate():
|
||||
"""Map the store's native error onto the generic one the HTTP layer maps."""
|
||||
try:
|
||||
yield
|
||||
except PlaylistError as ex:
|
||||
msg = str(ex)
|
||||
if "not found" in msg.lower():
|
||||
raise NotFound(msg) from ex
|
||||
raise InvalidCommand(msg) from ex
|
||||
@@ -0,0 +1,117 @@
|
||||
"""The beatgrid model: an ORDERED LIST of grid markers.
|
||||
|
||||
A Traktor beatgrid is not "a BPM and an anchor" — it is a list of `CUE_V2
|
||||
TYPE="4"` markers, each carrying its own `<GRID BPM>` child. Marker *i*'s tempo
|
||||
governs from its position until marker *i+1*. Traktor has stored grids this way
|
||||
since 3.4 (flexible beatgrids); a constant-tempo track is simply a list of
|
||||
length one, which is why this model is right for every track rather than a
|
||||
special case for flexible ones.
|
||||
|
||||
`<TEMPO BPM>` mirrors the FIRST marker by START.
|
||||
|
||||
Verified against the 8485-entry reference collection:
|
||||
* markers per entry: {1: 7966, 0: 517, 2: 2}
|
||||
* TEMPO.bpm == markers[0].grid.bpm in 7968/7968 entries with both
|
||||
* CUE_V2 is ascending by START in 8485/8485 entries
|
||||
* 53 entries have a TEMPO but no marker -> deleting a grid must KEEP TEMPO
|
||||
|
||||
Two rules that are easy to get wrong:
|
||||
|
||||
1. **Marker NAME is not a discriminator.** In the reference collection TYPE=4
|
||||
markers are named "AutoGrid" x7888, "n.n." x64, "Beat Marker" x14 and
|
||||
"Unnamed" x4. Identify a marker by having a `<GRID>` child, and order the
|
||||
list by START — never by name, never by document order.
|
||||
|
||||
2. **Companion cues are conventional, not structural.** Traktor usually writes a
|
||||
white TYPE=0 cue alongside each grid marker, at the same position, occupying
|
||||
a real hotcue slot. 7910 of 7970 markers have one; 60 do not, and one track
|
||||
has a companion on its first marker but not its second. So we follow them
|
||||
where they exist, keep them in sync, and NEVER invent one.
|
||||
|
||||
This module is pure and imports nothing else from the package, so it can be the
|
||||
single shared definition used by the store, the API projection and the read
|
||||
model — which previously each had their own and disagreed about BPM.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from traktor_nml_utils.models.collection import CueV2Type, Entrytype
|
||||
|
||||
# How close a cue must sit to a marker to be considered its companion. Traktor
|
||||
# writes them at the identical START; 71 markers in the reference collection are
|
||||
# a fraction of a millisecond off, which this absorbs.
|
||||
COMPANION_EPS_MS = 1.0
|
||||
|
||||
# Companions are always white. This test is LOAD-BEARING: 49 uncoloured cues and
|
||||
# 18 LOOPS also sit within 1 ms of a marker in the reference collection. Drop the
|
||||
# colour check and the marker commands would start dragging and deleting the
|
||||
# user's own loops.
|
||||
COMPANION_COLOR = "#FFFFFF"
|
||||
|
||||
|
||||
def grid_markers(entry: Entrytype) -> list[CueV2Type]:
|
||||
"""Every grid marker on `entry`, ordered by START.
|
||||
|
||||
Sorting is not cosmetic: the first marker by START is the one `<TEMPO BPM>`
|
||||
mirrors, and marker indices are the identity used by the edit commands.
|
||||
"""
|
||||
markers = [c for c in (entry.cue_v2 or []) if getattr(c, "grid", None) is not None]
|
||||
markers.sort(key=lambda c: c.start or 0.0)
|
||||
return markers
|
||||
|
||||
|
||||
def first_marker(entry: Entrytype) -> CueV2Type | None:
|
||||
"""The marker `<TEMPO BPM>` mirrors, or None when the track has no grid."""
|
||||
markers = grid_markers(entry)
|
||||
return markers[0] if markers else None
|
||||
|
||||
|
||||
def effective_bpm(entry: Entrytype) -> float | None:
|
||||
"""The tempo the grid actually starts at.
|
||||
|
||||
Prefers the first marker's `<GRID BPM>` and falls back to `<TEMPO BPM>` so
|
||||
the 53 gridless-but-tempo'd entries still report a BPM. Routing both the
|
||||
library table and the prep deck through this makes them structurally
|
||||
incapable of disagreeing.
|
||||
"""
|
||||
marker = first_marker(entry)
|
||||
if marker is not None and marker.grid is not None and marker.grid.bpm:
|
||||
return marker.grid.bpm
|
||||
return entry.tempo.bpm if entry.tempo else None
|
||||
|
||||
|
||||
def companions(entry: Entrytype) -> dict[int, CueV2Type]:
|
||||
"""Map marker index -> the companion cue paired with it, where one exists.
|
||||
|
||||
Greedy nearest-unclaimed matching, so two markers close together can never
|
||||
both claim the same cue.
|
||||
"""
|
||||
markers = grid_markers(entry)
|
||||
if not markers:
|
||||
return {}
|
||||
pool = [
|
||||
c
|
||||
for c in (entry.cue_v2 or [])
|
||||
if getattr(c, "grid", None) is None
|
||||
and c.type == 0
|
||||
and c.color == COMPANION_COLOR
|
||||
and c.hotcue is not None
|
||||
and c.hotcue >= 0
|
||||
]
|
||||
out: dict[int, CueV2Type] = {}
|
||||
claimed: set[int] = set()
|
||||
for i, m in enumerate(markers):
|
||||
m_start = m.start or 0.0
|
||||
best = min(
|
||||
(c for c in pool if id(c) not in claimed),
|
||||
key=lambda c: abs((c.start or 0.0) - m_start),
|
||||
default=None,
|
||||
)
|
||||
if best is not None and abs((best.start or 0.0) - m_start) <= COMPANION_EPS_MS:
|
||||
out[i] = best
|
||||
claimed.add(id(best))
|
||||
return out
|
||||
|
||||
|
||||
def is_companion(entry: Entrytype, cue: CueV2Type) -> bool:
|
||||
"""True when `cue` is some grid marker's companion on this entry."""
|
||||
return any(c is cue for c in companions(entry).values())
|
||||
@@ -0,0 +1,81 @@
|
||||
"""What Traktor can persist.
|
||||
|
||||
Derived from the NML version where one is declared, which is the accurate way to
|
||||
report capabilities rather than assuming a floor that denies users features their
|
||||
install actually has. NML v19 (Traktor 3) and v20 (Traktor 4) are equivalent for
|
||||
everything Konduktor edits; flexible beatgrids arrived in Traktor 3.4, which is
|
||||
older than any NML version we can open, so the flag is unconditional.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from ...core.capabilities import (
|
||||
Capabilities,
|
||||
CueCapabilities,
|
||||
GridCapabilities,
|
||||
PlaylistCapabilities,
|
||||
SaveCapabilities,
|
||||
TrackCapabilities,
|
||||
)
|
||||
|
||||
_VERSION_RE = re.compile(rb'<NML\s+VERSION="(\d+)"')
|
||||
|
||||
# Traktor's cue vocabulary, in generic terms. The integer encoding lives in
|
||||
# projection.py / store.py and never leaves this package.
|
||||
CUE_TYPES = ["cue", "fade_in", "fade_out", "load", "loop"]
|
||||
|
||||
|
||||
def nml_version(path: Path) -> str | None:
|
||||
"""The NML VERSION attribute, read from the file head without parsing it."""
|
||||
try:
|
||||
with path.open("rb") as fh:
|
||||
m = _VERSION_RE.search(fh.read(4096))
|
||||
return m.group(1).decode() if m else None
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
|
||||
return Capabilities(
|
||||
platform="traktor",
|
||||
version=nml_version(path),
|
||||
writable=True,
|
||||
cues=CueCapabilities(
|
||||
editable=True,
|
||||
hotcue_slots=8,
|
||||
slot_labels="number",
|
||||
# Traktor has no memory cues — every cue occupies a bank slot.
|
||||
memory_cues=False,
|
||||
types=CUE_TYPES,
|
||||
color="free",
|
||||
named=True,
|
||||
# A saved loop is a cue TYPE in Traktor, not a separate bank.
|
||||
loops="cue_type",
|
||||
),
|
||||
grid=GridCapabilities(editable=True, flexible=True, lockable=True),
|
||||
tracks=TrackCapabilities(
|
||||
rating_max=5,
|
||||
editable_fields=sorted(editable_fields),
|
||||
media_kinds=["audio", "stem"],
|
||||
removable=True,
|
||||
# `.mp4` covers stem files (`.stem.mp4`). Traktor also reads WMA,
|
||||
# but only on Windows, and a file added on one OS must play on both.
|
||||
audio_formats=[".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a", ".mp4", ".ogg"],
|
||||
artwork=True,
|
||||
artwork_note=(
|
||||
"Traktor caches its own cover thumbnail, so a replaced image may "
|
||||
"need a manual Import Cover Art to show up."
|
||||
),
|
||||
),
|
||||
playlists=PlaylistCapabilities(folders=True, smart="read_only", reorder=True),
|
||||
save=SaveCapabilities(
|
||||
app_name="Traktor",
|
||||
library_label="collection.nml",
|
||||
# Traktor rewrites collection.nml when it quits, so an edit made
|
||||
# while it is running is lost on exit.
|
||||
overwrite_risk="on_exit",
|
||||
history=True,
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Traktor's CUE_V2 TYPE encoding <-> the generic cue vocabulary.
|
||||
|
||||
The only place these integers are given meaning. Type 4 is a grid marker, not a
|
||||
cue, so it has no generic name — grid markers are projected as beatgrid markers
|
||||
and never appear in a track's cue list.
|
||||
|
||||
Lives in its own module so the projection and the adapter can both use it
|
||||
without importing each other.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
CUE_TYPE_TO_NATIVE = {"cue": 0, "fade_in": 1, "fade_out": 2, "load": 3, "loop": 5}
|
||||
NATIVE_TO_CUE_TYPE = {v: k for k, v in CUE_TYPE_TO_NATIVE.items()}
|
||||
File renamed without changes.
@@ -0,0 +1,41 @@
|
||||
"""Opening Traktor libraries: recognition, discovery and restore."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from . import discovery
|
||||
from .adapter import TraktorAdapter
|
||||
|
||||
|
||||
class TraktorDriver:
|
||||
platform = "traktor"
|
||||
display_name = "Traktor"
|
||||
suffixes = (".nml",)
|
||||
library_label = "collection.nml"
|
||||
selects = "file"
|
||||
|
||||
def can_open(self, path: Path) -> bool:
|
||||
"""Recognise an NML without parsing 14 MB of it."""
|
||||
if not path.is_file() or path.suffix.lower() != ".nml":
|
||||
return False
|
||||
try:
|
||||
with path.open("rb") as fh:
|
||||
head = fh.read(4096)
|
||||
except OSError:
|
||||
return False
|
||||
return b"<NML" in head and b"VERSION=" in head
|
||||
|
||||
def open(self, path: Path) -> TraktorAdapter:
|
||||
return TraktorAdapter(path)
|
||||
|
||||
def detect(self) -> list[dict]:
|
||||
return discovery.detect_collections()
|
||||
|
||||
def describe(self, path: Path) -> dict:
|
||||
return discovery.describe(path)
|
||||
|
||||
def restore(self, path: Path, data: bytes) -> None:
|
||||
"""Write a history snapshot back over the library, atomically."""
|
||||
tmp = path.with_suffix(path.suffix + ".tmp")
|
||||
tmp.write_bytes(data)
|
||||
tmp.replace(path)
|
||||
@@ -0,0 +1,145 @@
|
||||
"""Writing a fresh Traktor `collection.nml` from nothing.
|
||||
|
||||
## How it works, and why it is not a second writer
|
||||
|
||||
The obvious shape — build an `Nml` object graph by hand and render it — would
|
||||
mean a SECOND definition of "generic Track plus cues plus grid becomes a Traktor
|
||||
ENTRY", living beside `TraktorStore.add_entry` and the cue/grid commands. Two
|
||||
definitions drift, and the new one would inherit none of `test_save_fidelity`'s
|
||||
coverage, none of `replace_grid`'s companion-cue handling, and none of the
|
||||
lossiness rules the import feature already settled.
|
||||
|
||||
So instead: **write an empty but valid collection, open it, and replay the
|
||||
ordinary commands onto it.** The skeleton below is the smallest NML Traktor
|
||||
accepts, verified against a real Traktor Pro 4 file.
|
||||
|
||||
That is a deliberate amendment to the original design note, which said an
|
||||
exporter should not "create then replay commands". Its stated reason was that
|
||||
doing so would make "an empty new file" and "the user's real library" share code
|
||||
paths, when the safety of the architecture rests on the write target always
|
||||
being a retained native model parsed from a real file. Here that invariant holds
|
||||
literally: the write target IS parsed from a real file — a skeleton Konduktor
|
||||
wrote a moment earlier — and the import feature has already proved the approach
|
||||
end to end in Traktor 4.5. The exporter still owns everything genuinely new: the
|
||||
skeleton, the playlist tree, and the `$ROOT` wrapper.
|
||||
|
||||
## The skeleton
|
||||
|
||||
Read off Ben's own collection rather than assumed. Note there is **no
|
||||
`<MUSICFOLDERS>` element at all**, so it is not required, and `<PLAYLISTS>` must
|
||||
wrap a `$ROOT` FOLDER node — playlists cannot sit at the top level.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
from ...core.adapter import NewTrack
|
||||
from ...core.export import ExportPayload, WrittenLibrary
|
||||
from .adapter import TraktorAdapter
|
||||
from .capabilities import capabilities_for
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
#: The smallest collection Traktor Pro 4 accepts. `PROGRAM` names the writer;
|
||||
#: Traktor itself writes "Traktor Pro 4" here and does not appear to care, but
|
||||
#: claiming to BE Traktor would be dishonest in a file a user may inspect.
|
||||
SKELETON = (
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>\n'
|
||||
'<NML VERSION="20"><HEAD COMPANY="www.native-instruments.com" '
|
||||
'PROGRAM="Konduktor"></HEAD>\n'
|
||||
'<COLLECTION ENTRIES="0"></COLLECTION>\n'
|
||||
'<SETS ENTRIES="0"></SETS>\n'
|
||||
'<PLAYLISTS><NODE TYPE="FOLDER" NAME="$ROOT"><SUBNODES COUNT="0">'
|
||||
"</SUBNODES>\n</NODE>\n</PLAYLISTS>\n"
|
||||
'<INDEXING><SORTING_INFO PATH="$COLLECTION"></SORTING_INFO>\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:
|
||||
platform = "traktor"
|
||||
library_filename = "collection.nml"
|
||||
|
||||
def capabilities(self):
|
||||
"""What a Traktor library can hold — answered with no library to read.
|
||||
|
||||
`editable_fields` is the full safe set: an exported collection is
|
||||
brand new, so nothing about it is read-only.
|
||||
"""
|
||||
return capabilities_for(
|
||||
Path(self.library_filename),
|
||||
[
|
||||
"title", "artist", "album", "genre", "label", "remixer",
|
||||
"producer", "mix", "release_date", "comment", "rating",
|
||||
],
|
||||
)
|
||||
|
||||
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
|
||||
destination = Path(destination)
|
||||
destination.mkdir(parents=True, exist_ok=True)
|
||||
library = destination / self.library_filename
|
||||
library.write_text(SKELETON, encoding="utf-8")
|
||||
|
||||
adapter = TraktorAdapter(library)
|
||||
|
||||
# The tracks, with their cues and grids, through the ordinary command
|
||||
# path — so an exported beatgrid is written by the same `replace_grid`
|
||||
# the deck's Reset uses.
|
||||
new_ids = adapter.add_tracks(
|
||||
[NewTrack(track=t.track, audio_path=t.destination, cues=t.cues)
|
||||
for t in payload.tracks]
|
||||
)
|
||||
# Source id -> the id it got here. Both are Traktor primary keys derived
|
||||
# from a LOCATION, and the location changed, so they are never equal.
|
||||
moved = {t.source_id: new_id for t, new_id in zip(payload.tracks, new_ids)}
|
||||
|
||||
self._write_playlists(adapter, payload, moved)
|
||||
adapter.save()
|
||||
# One file; nothing else to report.
|
||||
return WrittenLibrary(library=library)
|
||||
|
||||
def _write_playlists(self, adapter, payload: ExportPayload, moved: dict) -> None:
|
||||
"""Recreate the tree under one folder named after the export.
|
||||
|
||||
Nested under the export's own name for the same reason import nests a
|
||||
drive's playlists under the drive's name: a collection swapped onto
|
||||
another machine should say where its playlists came from.
|
||||
"""
|
||||
root = adapter.create_folder(payload.name)
|
||||
folders: dict[tuple[str, ...], str] = {(): root}
|
||||
|
||||
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) -> str:
|
||||
"""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,71 @@
|
||||
"""Traktor LOCATION <-> OS path conversion.
|
||||
|
||||
A Traktor ``<LOCATION>`` is a ``(VOLUME, DIR, FILE)`` triple using ``/:`` as its
|
||||
directory separator, with the boot volume spelled ``Macintosh HD``. These two
|
||||
functions are exact inverses of each other and are the only place that
|
||||
convention is encoded — keep them together, and keep them out of ``core``.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
_WIN_DRIVE = re.compile(r"^([A-Za-z]:)[\\/](.*)$")
|
||||
_MAC_VOLUME = re.compile(r"^/Volumes/([^/]+)/(.*)$")
|
||||
|
||||
|
||||
def resolve_path(volume: str | None, dir_: str | None, file: str | None) -> Path:
|
||||
"""Map a Traktor LOCATION to an OS path.
|
||||
|
||||
Paths are trusted (per project decision): boot volume 'Macintosh HD' -> '/',
|
||||
a Windows drive like 'X:' stays a drive path, other volumes -> /Volumes/<v>.
|
||||
"""
|
||||
d = (dir_ or "").replace("/:", "/")
|
||||
name = file or ""
|
||||
vol = volume or ""
|
||||
if vol.endswith(":"): # Windows drive letter, e.g. "X:"
|
||||
return Path(vol + d + name)
|
||||
if vol and vol != "Macintosh HD": # other mounted volume (macOS/*nix)
|
||||
return Path("/Volumes") / vol / (d.lstrip("/") + name)
|
||||
return Path(d + name) # boot volume
|
||||
|
||||
|
||||
def _traktor_dir(posix_body: str) -> str:
|
||||
"""Convert a POSIX directory body (leading+trailing '/', e.g. '/Music/')
|
||||
to Traktor's '/:'-segmented form ('/:Music/:')."""
|
||||
return posix_body.replace("/", "/:")
|
||||
|
||||
|
||||
def os_path_to_location(os_path: Path) -> tuple[str, str, str]:
|
||||
"""Inverse of ``file_tags.resolve_path``: build a Traktor
|
||||
``(volume, dir, file)`` from an OS path, for the platform implied by the
|
||||
path's shape. Round-trips with ``resolve_path``.
|
||||
|
||||
Used by write-back only; the produced LOCATION is valid for the OS whose
|
||||
path shape it matches (Windows drive, macOS ``/Volumes`` mount, or a POSIX
|
||||
boot path -> ``Macintosh HD``).
|
||||
"""
|
||||
# Derive the filename from the string (not Path.name) so a Windows-style
|
||||
# path is handled even when this runs on a POSIX host, and vice-versa.
|
||||
s = str(os_path)
|
||||
|
||||
m = _WIN_DRIVE.match(s)
|
||||
if m:
|
||||
volume = m.group(1) # e.g. "E:"
|
||||
body = m.group(2).replace("\\", "/") # "Music/x.mp3"
|
||||
name = body.rsplit("/", 1)[-1]
|
||||
dir_body = "/" + body[: len(body) - len(name)] # "/Music/"
|
||||
return volume, _traktor_dir(dir_body), name
|
||||
|
||||
m = _MAC_VOLUME.match(s)
|
||||
if m:
|
||||
volume = m.group(1) # mounted volume name
|
||||
body = m.group(2) # "Music/x.mp3"
|
||||
name = body.rsplit("/", 1)[-1]
|
||||
dir_body = "/" + body[: len(body) - len(name)] # "/Music/"
|
||||
return volume, _traktor_dir(dir_body), name
|
||||
|
||||
# POSIX boot volume, e.g. "/Users/you/Music/x.mp3".
|
||||
name = s.rsplit("/", 1)[-1]
|
||||
dir_body = s[: len(s) - len(name)] # "/Users/you/Music/"
|
||||
return "Macintosh HD", _traktor_dir(dir_body), name
|
||||
@@ -0,0 +1,179 @@
|
||||
"""Traktor native model -> the generic projection.
|
||||
|
||||
The only place an NML dataclass is turned into a generic `Track`/`TrackCues`.
|
||||
Everything above this file sees generic types exclusively.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
|
||||
from . import beatgrid
|
||||
from .cue_types import NATIVE_TO_CUE_TYPE
|
||||
|
||||
# Traktor displays keys in Open Key ("10m" / "8d") or Camelot ("8A" / "8B"),
|
||||
# depending on a user preference — so the library can contain either. Parsing
|
||||
# notation is platform knowledge and belongs here, not in the UI.
|
||||
_OPEN_KEY = re.compile(r"^(\d{1,2})\s*([md])$", re.I)
|
||||
_CAMELOT = re.compile(r"^(\d{1,2})\s*([ab])$", re.I)
|
||||
_DATE = re.compile(r"^(\d{4})/(\d{1,2})/(\d{1,2})$")
|
||||
|
||||
|
||||
def parse_key(key: str | None) -> tuple[int | None, str | None]:
|
||||
"""(Camelot wheel position 1-12, mode) for a Traktor display key.
|
||||
|
||||
Open Key numbers the wheel seven semitones round from Camelot, so
|
||||
Open Key 1 == Camelot 8 (both are C major / A minor).
|
||||
"""
|
||||
if not key:
|
||||
return None, None
|
||||
k = key.strip()
|
||||
if m := _CAMELOT.match(k):
|
||||
n = int(m.group(1))
|
||||
if 1 <= n <= 12:
|
||||
return n, "minor" if m.group(2).lower() == "a" else "major"
|
||||
if m := _OPEN_KEY.match(k):
|
||||
n = int(m.group(1))
|
||||
if 1 <= n <= 12:
|
||||
return ((n + 6) % 12) + 1, "minor" if m.group(2).lower() == "m" else "major"
|
||||
return None, None
|
||||
|
||||
|
||||
def iso_date(value: str | None) -> str | None:
|
||||
"""Traktor writes dates as "YYYY/M/D"; the model carries ISO-8601."""
|
||||
if not value:
|
||||
return None
|
||||
m = _DATE.match(value.strip())
|
||||
if not m:
|
||||
return value
|
||||
y, mo, d = m.groups()
|
||||
return f"{y}-{int(mo):02d}-{int(d):02d}"
|
||||
|
||||
|
||||
def primary_key(location) -> str:
|
||||
"""Reconstruct the Traktor primary key used by playlist entries."""
|
||||
vol = location.volume or ""
|
||||
d = location.dir or ""
|
||||
f = location.file or ""
|
||||
return f"{vol}{d}{f}"
|
||||
|
||||
|
||||
def _display_path(location) -> str:
|
||||
"""Human-readable OS-ish path from Traktor's '/:'-separated dir."""
|
||||
d = (location.dir or "").replace("/:", "/")
|
||||
f = location.file or ""
|
||||
return f"{d}{f}"
|
||||
|
||||
|
||||
def _rating_stars(ranking) -> int:
|
||||
if not ranking:
|
||||
return 0
|
||||
return max(0, min(5, round(ranking / 51)))
|
||||
|
||||
|
||||
def to_track(e) -> Track:
|
||||
info = e.info
|
||||
loc = e.location
|
||||
# "Is this a cue?" must mean the same here as in `to_track_cues`, which
|
||||
# skips grid markers — a marker is projected as a beatgrid marker, not a
|
||||
# cue. Counting the raw CUE_V2 list instead made the library table report
|
||||
# every track as having one more cue than the deck showed, and made the
|
||||
# "has cues: no" filter match nothing, since a gridded track always had at
|
||||
# least one. The same class of bug as the Rekordbox hotcue miscount: one
|
||||
# question, two answers.
|
||||
markers = beatgrid.grid_markers(e)
|
||||
cues = [c for c in (e.cue_v2 or []) if getattr(c, "grid", None) is None]
|
||||
# The same "is this in the bank" test as `to_track_cues`' slot, so the
|
||||
# table's dots and the deck's pads cannot disagree.
|
||||
chips = sorted(
|
||||
(
|
||||
HotcueChip(
|
||||
slot=c.hotcue,
|
||||
type=NATIVE_TO_CUE_TYPE.get(c.type, "cue"),
|
||||
color=c.color or None,
|
||||
)
|
||||
for c in cues
|
||||
if c.hotcue is not None and c.hotcue >= 0
|
||||
),
|
||||
key=lambda chip: chip.slot,
|
||||
)
|
||||
wheel, mode = parse_key(info.key if info else None)
|
||||
return Track(
|
||||
id=primary_key(loc) if loc else (e.title or ""),
|
||||
artist=e.artist,
|
||||
title=e.title,
|
||||
album=e.album.title if e.album else None,
|
||||
genre=info.genre if info else None,
|
||||
label=info.label if info else None,
|
||||
remixer=info.remixer if info else None,
|
||||
producer=info.producer if info else None,
|
||||
mix=info.mix if info else None,
|
||||
comment=info.comment if info else None,
|
||||
bpm=beatgrid.effective_bpm(e),
|
||||
key=info.key if info else None,
|
||||
key_wheel=wheel,
|
||||
key_mode=mode,
|
||||
rating=_rating_stars(info.ranking if info else None),
|
||||
playcount=info.playcount if info else None,
|
||||
length=info.playtime if info else None,
|
||||
bitrate=info.bitrate if info else None,
|
||||
import_date=iso_date(info.import_date if info else None),
|
||||
last_played=iso_date(info.last_played if info else None),
|
||||
release_date=iso_date(info.release_date if info else None),
|
||||
filepath=_display_path(loc) if loc else None,
|
||||
cue_count=len(cues),
|
||||
hotcue_count=len(chips),
|
||||
hotcues=chips,
|
||||
grid_marker_count=len(markers),
|
||||
grid_locked=bool(e.lock),
|
||||
media_kind="stem" if getattr(e, "stems", None) is not None else "audio",
|
||||
)
|
||||
|
||||
|
||||
def to_track_cues(entry) -> TrackCues:
|
||||
"""Project an ENTRY's beatgrid + cues.
|
||||
|
||||
The beatgrid is the FULL ordered marker list — a constant grid is a list of
|
||||
length one. Grid markers themselves are not cues; their companion cues are,
|
||||
because they occupy real hotcue slots. Each is tagged with the marker it sits
|
||||
on, but is an ordinary, editable hotcue: Traktor 4 keeps a beatgrid without
|
||||
one, so nothing depends on it staying put.
|
||||
"""
|
||||
markers = beatgrid.grid_markers(entry)
|
||||
comps = beatgrid.companions(entry)
|
||||
marker_of = {id(c): i for i, c in comps.items()}
|
||||
grid_markers = [
|
||||
GridMarker(
|
||||
start=(m.start or 0.0) / 1000.0, # Traktor stores START in ms
|
||||
bpm=m.grid.bpm if m.grid and m.grid.bpm else 0.0,
|
||||
name=m.name,
|
||||
companion=comps[i].hotcue if i in comps else None,
|
||||
)
|
||||
for i, m in enumerate(markers)
|
||||
]
|
||||
cues = []
|
||||
for c in entry.cue_v2 or []:
|
||||
if getattr(c, "grid", None) is not None:
|
||||
continue # a grid marker is projected as a beatgrid marker, not a cue
|
||||
marker = marker_of.get(id(c))
|
||||
slot = c.hotcue if c.hotcue is not None and c.hotcue >= 0 else None
|
||||
cues.append(
|
||||
CuePoint(
|
||||
name=c.name,
|
||||
# An unknown TYPE is projected as a plain cue rather than dropped:
|
||||
# preserving a cue we cannot name beats hiding it from the user.
|
||||
type=NATIVE_TO_CUE_TYPE.get(c.type, "cue"),
|
||||
# Every Traktor cue lives in the hotcue bank.
|
||||
role="hotcue",
|
||||
start=(c.start or 0.0) / 1000.0,
|
||||
length=(c.len or 0.0) / 1000.0,
|
||||
slot=slot,
|
||||
color=c.color,
|
||||
editable=True,
|
||||
readonly_reason=None,
|
||||
grid_marker=marker,
|
||||
)
|
||||
)
|
||||
return TrackCues(
|
||||
grid_markers=grid_markers, grid_locked=bool(entry.lock), cues=cues
|
||||
)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,163 @@
|
||||
"""The loaded library, and the version-history bookkeeping around saving it.
|
||||
|
||||
Exactly one library is open **for editing** at a time: that keeps every edit and
|
||||
every save unambiguous about what it targets, and it is why the adapter can own
|
||||
its own projection without anyone asking which library a command meant.
|
||||
|
||||
A **source** may be open alongside it, and only alongside it. A source is a
|
||||
library being read FROM — a plugged-in OneLibrary stick whose tracks are about to
|
||||
be imported — and it is deliberately not symmetrical with the loaded library:
|
||||
|
||||
* it is **never written**, so no command can be ambiguous about its target;
|
||||
* it is **never saved**, so version history has nothing to disambiguate;
|
||||
* it is **never the fallback** when nothing is loaded — a source with no
|
||||
destination is a browser, not a library, and the routes say so.
|
||||
|
||||
That asymmetry is what keeps "exactly one library is open" true in the sense that
|
||||
mattered: there is still exactly one thing a command can mean.
|
||||
|
||||
Version history lives here rather than in the adapter. An adapter's job is to
|
||||
write its own format faithfully; knowing that Konduktor keeps a git-backed
|
||||
history of each library is app-level knowledge, and an adapter reaching up for it
|
||||
would invert the dependency. So the adapter returns the bytes it wrote and a
|
||||
human summary, and this module versions them.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from . import __version__, adapters, history, library_id, prefs # noqa: F401 — registers adapters
|
||||
from .core import registry
|
||||
from .core.adapter import LibraryAdapter
|
||||
from .core.pathmap import PathMapping
|
||||
|
||||
|
||||
class AppState:
|
||||
"""Holds the currently-loaded library (selectable at runtime)."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.path: Path | None = None
|
||||
self.adapter: LibraryAdapter | None = None
|
||||
# This library's stable identity, which survives it being moved. What
|
||||
# export sets are keyed by; see `library_id.py` for why a path is not
|
||||
# good enough for curated user work.
|
||||
self.library_id: str | None = None
|
||||
# The library being read FROM, if any. Read-only by contract; see the
|
||||
# module docstring for why it is not symmetrical with `adapter`.
|
||||
self.source_path: Path | None = None
|
||||
self.source: LibraryAdapter | None = None
|
||||
|
||||
@property
|
||||
def loaded(self) -> bool:
|
||||
return self.adapter is not None
|
||||
|
||||
@property
|
||||
def source_loaded(self) -> bool:
|
||||
return self.source is not None
|
||||
|
||||
# ---- the source library ---------------------------------------------
|
||||
def open_source(self, path: Path) -> None:
|
||||
"""Open a library to read from, alongside the loaded one.
|
||||
|
||||
Refuses a source that is not read-only. Nothing downstream sends it a
|
||||
command, but "this is only ever read" is the assumption the whole slot
|
||||
rests on, and an adapter is the thing that knows whether it is true —
|
||||
so it is asserted here rather than assumed everywhere else.
|
||||
"""
|
||||
adapter = registry.open_library(path)
|
||||
if adapter.capabilities().writable:
|
||||
if hasattr(adapter, "close"):
|
||||
try:
|
||||
adapter.close()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
raise ValueError(
|
||||
f"{path} is a writable library; only read-only sources "
|
||||
"(such as a OneLibrary drive) can be opened as a source"
|
||||
)
|
||||
self.close_source()
|
||||
self.source_path, self.source = path, adapter
|
||||
|
||||
def close_source(self) -> None:
|
||||
"""Release the source. Load-bearing: a source lives on a REMOVABLE drive,
|
||||
and a held file handle is what stops a stick ejecting."""
|
||||
previous, self.source = self.source, None
|
||||
self.source_path = None
|
||||
if previous is not None and hasattr(previous, "close"):
|
||||
try:
|
||||
previous.close()
|
||||
except Exception: # noqa: BLE001 — a failed close must not block
|
||||
pass
|
||||
|
||||
def open(self, path: Path) -> None:
|
||||
# The registry picks the adapter by probing the file, not by extension —
|
||||
# a Rekordbox library is a .db and a Serato one is a directory. Raises on
|
||||
# an unrecognised or unparseable file; only commit once it has parsed.
|
||||
# One parse: the adapter builds its read projection from the same object
|
||||
# graph the commands mutate.
|
||||
adapter = registry.open_library(path)
|
||||
# Release the previous library first. A file-backed platform (Rekordbox
|
||||
# holds master.db open) would otherwise leak a handle — and a lingering
|
||||
# write-ahead log beside a file another process replaces is how a SQLite
|
||||
# library gets corrupted. Only close once the new one has parsed, so a
|
||||
# failed open leaves the current library intact.
|
||||
previous = self.adapter
|
||||
if previous is not None and hasattr(previous, "close"):
|
||||
try:
|
||||
previous.close()
|
||||
except Exception: # noqa: BLE001 — a failed close must not block the open
|
||||
pass
|
||||
# Apply this library's saved OS-path remapping (per-machine, keyed by the
|
||||
# library's local path) so runtime translation is live on open.
|
||||
saved = prefs.get_path_mapping(str(path))
|
||||
if saved:
|
||||
adapter.set_path_mapping(PathMapping.make(saved["from"], saved["to"]))
|
||||
self.path, self.adapter = path, adapter
|
||||
caps = adapter.capabilities()
|
||||
# No sidecar beside a removable library: writing to a user's USB stick to
|
||||
# satisfy Konduktor's own bookkeeping is not a trade worth making. Those
|
||||
# get a path-derived id instead, which `is_durable()` reports honestly.
|
||||
driver = next(
|
||||
(d for d in registry.drivers() if d.platform == caps.platform), None
|
||||
)
|
||||
self.library_id = library_id.for_path(
|
||||
path,
|
||||
platform=caps.platform,
|
||||
label=Path(str(path)).name,
|
||||
sidecar=not getattr(driver, "removable", False),
|
||||
)
|
||||
# Version history: record an "as I found it" baseline (deduped, so
|
||||
# re-opening an unchanged library is a no-op). Best-effort.
|
||||
history.ensure_baseline(path)
|
||||
|
||||
def save(self):
|
||||
"""Write the library, then record the saved bytes in version history.
|
||||
|
||||
Returns ``(outcome, commit_sha | None)``. Every path that saves must come
|
||||
through here — a save that skips it leaves a gap in the history the user
|
||||
cannot restore from.
|
||||
"""
|
||||
assert self.adapter is not None and self.path is not None
|
||||
outcome = self.adapter.save()
|
||||
# Not every platform is versioned. A library that is more than one file
|
||||
# has no single blob that IS the library, and it says so through its
|
||||
# capabilities rather than this module knowing which platforms those are.
|
||||
versioned = self.adapter.capabilities().save.history
|
||||
commit = None
|
||||
if versioned and outcome.snapshot is not None:
|
||||
commit = history.commit(
|
||||
self.path, outcome.snapshot, outcome.summary, __version__
|
||||
)
|
||||
return outcome, commit
|
||||
|
||||
|
||||
STATE = AppState()
|
||||
|
||||
# Optional auto-load for dev/tests.
|
||||
_env_nml = os.environ.get("KONDUKTOR_NML")
|
||||
if _env_nml and Path(_env_nml).exists():
|
||||
try:
|
||||
STATE.open(Path(_env_nml))
|
||||
except Exception: # noqa: BLE001 — bad env path shouldn't crash startup
|
||||
pass
|
||||
@@ -1,201 +0,0 @@
|
||||
"""Auto Hotcues — structural boundary detection for DJ cue placement.
|
||||
|
||||
Detection uses the McFee & Ellis (2014) Laplacian structural segmentation as
|
||||
implemented on top of librosa: beat-synchronous CQT features → a
|
||||
sequence-augmented recurrence Laplacian → spectral clustering of beats into
|
||||
section *types* → boundaries at type changes. This is repetition/homogeneity
|
||||
aware (unlike a raw energy-novelty curve), so boundaries land on real musical
|
||||
transitions. Validated on real house tracks: clean, phrase-scale boundaries in
|
||||
~1.5s each; pure-Python (~150MB), no torch/native build; runs on Python 3.14.
|
||||
|
||||
The module is split so the DSP (`detect_boundaries`, needs the audio) is
|
||||
separate from the placement logic (`select_hotcues`, pure arithmetic on the
|
||||
beatgrid) — the latter is unit-testable without audio.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
|
||||
# Traktor's hotcue bank. Parameterised (not hardcoded at call sites) so it can
|
||||
# grow if a future Traktor allows more than 8 triggerable hotcues.
|
||||
MAX_HOTCUES = 8
|
||||
|
||||
_SR = 22050
|
||||
_N_EIGENVECTORS = 6 # section-type clusters for the Laplacian embedding
|
||||
|
||||
|
||||
def detect_boundaries(audio_path: str, sr: int = _SR) -> tuple[list[tuple[float, float]], float]:
|
||||
"""Detect structural boundaries in a track.
|
||||
|
||||
Returns ``(boundaries, duration)`` where ``boundaries`` is a list of
|
||||
``(time_sec, energy)`` pairs — one per detected section start — and
|
||||
``energy`` is that section's mean RMS normalised to 0..1 across the track
|
||||
(used downstream for positional naming). Sorted by time.
|
||||
"""
|
||||
import librosa
|
||||
from scipy.ndimage import median_filter
|
||||
from scipy.sparse.csgraph import laplacian as csgraph_laplacian
|
||||
from scipy.linalg import eigh
|
||||
import sklearn.cluster
|
||||
|
||||
y, sr = librosa.load(audio_path, sr=sr, mono=True)
|
||||
duration = len(y) / sr
|
||||
if duration < 1.0:
|
||||
return [], duration
|
||||
|
||||
# Beat-synchronous CQT — the harmonic/timbre backbone of the method.
|
||||
cqt = librosa.amplitude_to_db(np.abs(librosa.cqt(y=y, sr=sr)), ref=np.max)
|
||||
_, beats = librosa.beat.beat_track(y=y, sr=sr, trim=False)
|
||||
if len(beats) < 4:
|
||||
return [], duration
|
||||
csync = librosa.util.sync(cqt, beats, aggregate=np.median)
|
||||
beat_times = librosa.frames_to_time(beats, sr=sr)
|
||||
|
||||
# Sequence-augmented recurrence Laplacian (McFee & Ellis 2014):
|
||||
# a repetition graph (which beats sound alike) blended with a local path
|
||||
# graph (consecutive-beat timbral continuity).
|
||||
rec = librosa.segment.recurrence_matrix(csync, width=3, mode="affinity", sym=True)
|
||||
rec = median_filter(rec, size=(1, 7))
|
||||
mfcc = librosa.feature.mfcc(y=y, sr=sr)
|
||||
msync = librosa.util.sync(mfcc, beats)
|
||||
path_dist = np.sum(np.diff(msync, axis=1) ** 2, axis=0)
|
||||
path_sim = np.exp(-path_dist / (np.median(path_dist) + 1e-9))
|
||||
path = np.diag(path_sim, 1) + np.diag(path_sim, -1)
|
||||
deg_path, deg_rec = path.sum(1), rec.sum(1)
|
||||
denom = np.sum((deg_path + deg_rec) ** 2) + 1e-9
|
||||
mu = deg_path.dot(deg_path + deg_rec) / denom
|
||||
graph = mu * rec + (1 - mu) * path
|
||||
|
||||
# Symmetric-normalised Laplacian → eigenvectors → k-means over beats.
|
||||
lap = csgraph_laplacian(graph, normed=True)
|
||||
_, evecs = eigh(lap)
|
||||
evecs = median_filter(evecs, size=(9, 1))
|
||||
k = min(_N_EIGENVECTORS, evecs.shape[1])
|
||||
x = librosa.util.normalize(evecs[:, :k], norm=2, axis=1)
|
||||
ids = sklearn.cluster.KMeans(n_clusters=k, n_init=10, random_state=0).fit_predict(x)
|
||||
|
||||
# Boundaries = beats where the section-type label changes (plus the start).
|
||||
bound_beats = [0] + [i for i in range(1, len(ids)) if ids[i] != ids[i - 1]]
|
||||
|
||||
# Per-section mean RMS (energy) for positional naming, normalised 0..1.
|
||||
rms = librosa.feature.rms(y=y)[0]
|
||||
rms_t = librosa.times_like(rms, sr=sr)
|
||||
rms_max = float(rms.max()) or 1.0
|
||||
out: list[tuple[float, float]] = []
|
||||
for j, bi in enumerate(bound_beats):
|
||||
t = float(beat_times[min(bi, len(beat_times) - 1)])
|
||||
t_next = (
|
||||
float(beat_times[min(bound_beats[j + 1], len(beat_times) - 1)])
|
||||
if j + 1 < len(bound_beats)
|
||||
else duration
|
||||
)
|
||||
seg = rms[(rms_t >= t) & (rms_t < max(t_next, t + 1e-3))]
|
||||
energy = float(seg.mean() / rms_max) if len(seg) else 0.0
|
||||
out.append((t, energy))
|
||||
return out, duration
|
||||
|
||||
|
||||
def detect_grid(audio_path: str, sr: int = _SR) -> tuple[float, float]:
|
||||
"""Detect a track's tempo and the time of its first beat.
|
||||
|
||||
Returns ``(bpm, first_beat_sec)`` for building a Traktor beatgrid (BPM +
|
||||
anchor). Uses librosa beat tracking. Half/double-tempo octave errors are
|
||||
left for the user to fix with the ×2 / ÷2 controls (per product decision).
|
||||
"""
|
||||
import librosa
|
||||
|
||||
y, sr = librosa.load(audio_path, sr=sr, mono=True)
|
||||
tempo, beats = librosa.beat.beat_track(y=y, sr=sr, trim=False)
|
||||
bpm = float(np.ravel(tempo)[0])
|
||||
if bpm <= 0 or len(beats) == 0:
|
||||
raise ValueError("Could not detect a tempo/beat")
|
||||
first_beat = float(librosa.frames_to_time(beats, sr=sr)[0])
|
||||
return bpm, first_beat
|
||||
|
||||
|
||||
def select_hotcues(
|
||||
boundaries: list[tuple[float, float]],
|
||||
*,
|
||||
bpm: float,
|
||||
anchor: float,
|
||||
duration: float,
|
||||
free_slots: list[int],
|
||||
existing_times: list[float],
|
||||
max_cues: int = MAX_HOTCUES,
|
||||
phrase_bars: int = 16,
|
||||
) -> list[dict]:
|
||||
"""Turn raw boundaries into hotcue specs, phrase-snapped to the beatgrid.
|
||||
|
||||
Snaps each boundary to the nearest ``phrase_bars``-bar grid point (which
|
||||
also merges near-duplicates), drops any coinciding with an existing hotcue,
|
||||
caps to the free slots (down-sampling evenly if there are too many), and
|
||||
assigns positional names. Returns dicts with slot/start/name/type/length.
|
||||
"""
|
||||
if not boundaries or not free_slots or bpm <= 0:
|
||||
return []
|
||||
|
||||
beat = 60.0 / bpm
|
||||
phrase = phrase_bars * 4 * beat # seconds per phrase
|
||||
|
||||
# Snap to phrase grid; dedupe (keep the strongest energy seen at each point).
|
||||
snapped: dict[float, float] = {}
|
||||
for t, energy in boundaries:
|
||||
p = anchor + round((t - anchor) / phrase) * phrase
|
||||
p = max(0.0, min(p, duration - beat))
|
||||
snapped[p] = max(snapped.get(p, 0.0), energy)
|
||||
|
||||
# Drop points that collide with an existing (hand-placed) hotcue.
|
||||
def near_existing(t: float) -> bool:
|
||||
return any(abs(t - e) < beat for e in existing_times)
|
||||
|
||||
points = sorted((t, e) for t, e in snapped.items() if not near_existing(t))
|
||||
if not points:
|
||||
return []
|
||||
|
||||
# If more candidates than free slots, down-sample evenly across the track
|
||||
# (keeps intro..outro coverage rather than just the first N).
|
||||
n = min(len(free_slots), max_cues)
|
||||
if len(points) > n:
|
||||
idx = np.linspace(0, len(points) - 1, n).round().astype(int)
|
||||
points = [points[i] for i in sorted(set(idx))]
|
||||
|
||||
names = _name_positionally([t for t, _ in points], [e for _, e in points], duration)
|
||||
slots = sorted(free_slots)[: len(points)]
|
||||
return [
|
||||
{"slot": slot, "start": round(t, 3), "name": name, "type": 0, "length": 0.0}
|
||||
for slot, (t, _), name in zip(slots, points, names)
|
||||
]
|
||||
|
||||
|
||||
def _name_positionally(times: list[float], energies: list[float], duration: float) -> list[str]:
|
||||
"""Positional-hint names from track position + energy trend (not true
|
||||
structural classification — the names are hints; value is the position)."""
|
||||
if not times:
|
||||
return []
|
||||
med = float(np.median(energies))
|
||||
raw: list[str] = []
|
||||
n = len(times)
|
||||
for i, (t, e) in enumerate(zip(times, energies)):
|
||||
frac = t / duration if duration else 0.0
|
||||
prev = energies[i - 1] if i > 0 else e
|
||||
if i == 0 or frac < 0.08:
|
||||
name = "Intro"
|
||||
elif i == n - 1 or frac > 0.85:
|
||||
name = "Outro"
|
||||
elif e - prev > 0.12 and e >= med:
|
||||
name = "Drop"
|
||||
elif prev - e > 0.12:
|
||||
name = "Break"
|
||||
elif e > prev:
|
||||
name = "Build"
|
||||
else:
|
||||
name = "Mid"
|
||||
raw.append(name)
|
||||
# De-duplicate repeated labels with ordinals (Drop, Drop 2, ...).
|
||||
counts: dict[str, int] = {}
|
||||
out: list[str] = []
|
||||
for name in raw:
|
||||
counts[name] = counts.get(name, 0) + 1
|
||||
out.append(name if counts[name] == 1 else f"{name} {counts[name]}")
|
||||
return out
|
||||
@@ -1,316 +0,0 @@
|
||||
"""Loads a Traktor collection and serves query-friendly views of it.
|
||||
|
||||
Phase 1 is read-only. The service parses the .nml once into memory, builds a
|
||||
flat list of Track objects, a primary-key index (so playlist entries can be
|
||||
joined to full track metadata), and the playlist tree.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from traktor_nml_utils import TraktorCollection
|
||||
|
||||
from .schemas import (
|
||||
Facets,
|
||||
GenreCount,
|
||||
PlaylistNode,
|
||||
Stats,
|
||||
Track,
|
||||
TrackPage,
|
||||
)
|
||||
|
||||
|
||||
def _primary_key(location) -> str:
|
||||
"""Reconstruct the Traktor primary key used by playlist entries."""
|
||||
vol = location.volume or ""
|
||||
d = location.dir or ""
|
||||
f = location.file or ""
|
||||
return f"{vol}{d}{f}"
|
||||
|
||||
|
||||
def _display_path(location) -> str:
|
||||
"""Human-readable OS-ish path from Traktor's '/:'-separated dir."""
|
||||
d = (location.dir or "").replace("/:", "/")
|
||||
f = location.file or ""
|
||||
return f"{d}{f}"
|
||||
|
||||
|
||||
def _rating_stars(ranking) -> int:
|
||||
if not ranking:
|
||||
return 0
|
||||
return max(0, min(5, round(ranking / 51)))
|
||||
|
||||
|
||||
class CollectionService:
|
||||
def __init__(self, nml_path: Path):
|
||||
self.nml_path = Path(nml_path)
|
||||
self._lock = threading.Lock()
|
||||
self.tracks: list[Track] = []
|
||||
self.by_key: dict[str, Track] = {}
|
||||
self.stem_keys: set[str] = set()
|
||||
self._playlist_entries: dict[str, list[str]] = {} # id -> ordered primary keys
|
||||
self._tree: list[PlaylistNode] = []
|
||||
self._playlist_count = 0
|
||||
self.load()
|
||||
|
||||
# ---- loading -------------------------------------------------------
|
||||
def load(self) -> None:
|
||||
with self._lock:
|
||||
collection = TraktorCollection(path=self.nml_path)
|
||||
self.tracks = [self._to_track(e) for e in collection.nml.collection.entry]
|
||||
self.by_key = {t.id: t for t in self.tracks}
|
||||
# Tracks with stems use PRIMARYKEY TYPE="STEM" in playlists (verified
|
||||
# 945/945 against the real collection); all others use "TRACK".
|
||||
self.stem_keys = {
|
||||
_primary_key(e.location)
|
||||
for e in collection.nml.collection.entry
|
||||
if e.location and getattr(e, "stems", None) is not None
|
||||
}
|
||||
self._playlist_entries = {}
|
||||
self._playlist_count = 0
|
||||
counter = {"n": 0}
|
||||
root = collection.nml.playlists.node if collection.nml.playlists else None
|
||||
self._tree = self._build_tree(root, counter) if root else []
|
||||
|
||||
def _to_track(self, e) -> Track:
|
||||
info = e.info
|
||||
loc = e.location
|
||||
cues = e.cue_v2 or []
|
||||
hotcues = sum(
|
||||
1 for c in cues if c.hotcue is not None and c.hotcue >= 0
|
||||
)
|
||||
has_grid = any(getattr(c, "grid", None) is not None for c in cues)
|
||||
return Track(
|
||||
id=_primary_key(loc) if loc else (e.title or ""),
|
||||
artist=e.artist,
|
||||
title=e.title,
|
||||
album=e.album.title if e.album else None,
|
||||
genre=info.genre if info else None,
|
||||
label=info.label if info else None,
|
||||
remixer=info.remixer if info else None,
|
||||
producer=info.producer if info else None,
|
||||
mix=info.mix if info else None,
|
||||
comment=info.comment if info else None,
|
||||
bpm=e.tempo.bpm if e.tempo else None,
|
||||
key=info.key if info else None,
|
||||
rating=_rating_stars(info.ranking if info else None),
|
||||
playcount=info.playcount if info else None,
|
||||
length=info.playtime if info else None,
|
||||
bitrate=info.bitrate if info else None,
|
||||
import_date=info.import_date if info else None,
|
||||
last_played=info.last_played if info else None,
|
||||
release_date=info.release_date if info else None,
|
||||
filepath=_display_path(loc) if loc else None,
|
||||
cue_count=len(cues),
|
||||
hotcue_count=hotcues,
|
||||
has_grid=has_grid,
|
||||
is_stem=getattr(e, "stems", None) is not None,
|
||||
)
|
||||
|
||||
def _build_tree(self, node, counter, is_root=True) -> list[PlaylistNode]:
|
||||
"""Return the children of the $ROOT folder as the top-level tree."""
|
||||
if node is None:
|
||||
return []
|
||||
# Root ($ROOT) is a wrapper folder; expose its children as top level.
|
||||
if is_root and node.subnodes:
|
||||
out = []
|
||||
for child in node.subnodes.node:
|
||||
out.append(self._node_to_model(child, counter))
|
||||
return out
|
||||
return [self._node_to_model(node, counter)]
|
||||
|
||||
def _node_to_model(self, node, counter) -> PlaylistNode:
|
||||
ntype = node.type or "FOLDER"
|
||||
if ntype == "PLAYLIST" or (node.playlist is not None):
|
||||
nid = f"pl-{counter['n']}"
|
||||
counter["n"] += 1
|
||||
self._playlist_count += 1
|
||||
keys = []
|
||||
if node.playlist and node.playlist.entry:
|
||||
for en in node.playlist.entry:
|
||||
if en.primarykey and en.primarykey.key:
|
||||
keys.append(en.primarykey.key)
|
||||
self._playlist_entries[nid] = keys
|
||||
return PlaylistNode(
|
||||
id=nid,
|
||||
name=node.name or "(unnamed)",
|
||||
type="PLAYLIST",
|
||||
uuid=node.playlist.uuid if node.playlist else None,
|
||||
count=len(keys),
|
||||
)
|
||||
if ntype == "SMARTLIST" or getattr(node, "smartlist", None) is not None:
|
||||
# Smart playlists are dynamic (rule-based); no static entry list.
|
||||
nid = f"sl-{counter['n']}"
|
||||
counter["n"] += 1
|
||||
return PlaylistNode(id=nid, name=node.name or "(smart)", type="SMARTLIST")
|
||||
# FOLDER
|
||||
nid = f"fld-{counter['n']}"
|
||||
counter["n"] += 1
|
||||
children = []
|
||||
if node.subnodes:
|
||||
for child in node.subnodes.node:
|
||||
children.append(self._node_to_model(child, counter))
|
||||
return PlaylistNode(
|
||||
id=nid, name=node.name or "(folder)", type="FOLDER", children=children
|
||||
)
|
||||
|
||||
# ---- queries -------------------------------------------------------
|
||||
_SORT_KEYS = {
|
||||
"artist": lambda t: (t.artist or "").lower(),
|
||||
"title": lambda t: (t.title or "").lower(),
|
||||
"album": lambda t: (t.album or "").lower(),
|
||||
"genre": lambda t: (t.genre or "").lower(),
|
||||
"key": lambda t: (t.key or ""),
|
||||
"bpm": lambda t: (t.bpm if t.bpm is not None else -1),
|
||||
"rating": lambda t: t.rating,
|
||||
"playcount": lambda t: (t.playcount or 0),
|
||||
"import_date": lambda t: (t.import_date or ""),
|
||||
"length": lambda t: (t.length or 0),
|
||||
}
|
||||
|
||||
def query_tracks(
|
||||
self,
|
||||
q: str | None = None,
|
||||
genre: str | None = None,
|
||||
key: str | None = None,
|
||||
bpm_min: float | None = None,
|
||||
bpm_max: float | None = None,
|
||||
rating_min: int | None = None,
|
||||
has_cues: bool | None = None,
|
||||
sort: str = "artist",
|
||||
order: str = "asc",
|
||||
limit: int = 100,
|
||||
offset: int = 0,
|
||||
) -> TrackPage:
|
||||
items = self.tracks
|
||||
if q:
|
||||
ql = q.lower()
|
||||
items = [
|
||||
t
|
||||
for t in items
|
||||
if (t.artist and ql in t.artist.lower())
|
||||
or (t.title and ql in t.title.lower())
|
||||
or (t.album and ql in t.album.lower())
|
||||
]
|
||||
if genre:
|
||||
items = [t for t in items if t.genre == genre]
|
||||
if key:
|
||||
items = [t for t in items if t.key == key]
|
||||
if bpm_min is not None:
|
||||
items = [t for t in items if t.bpm is not None and t.bpm >= bpm_min]
|
||||
if bpm_max is not None:
|
||||
items = [t for t in items if t.bpm is not None and t.bpm <= bpm_max]
|
||||
if rating_min is not None:
|
||||
items = [t for t in items if t.rating >= rating_min]
|
||||
if has_cues is not None:
|
||||
items = [t for t in items if (t.cue_count > 0) == has_cues]
|
||||
|
||||
keyfn = self._SORT_KEYS.get(sort, self._SORT_KEYS["artist"])
|
||||
items = sorted(items, key=keyfn, reverse=(order == "desc"))
|
||||
|
||||
total = len(items)
|
||||
page = items[offset : offset + limit]
|
||||
return TrackPage(total=total, offset=offset, limit=limit, items=page)
|
||||
|
||||
def facets(self) -> Facets:
|
||||
genres: dict[str, int] = {}
|
||||
keys: dict[str, int] = {}
|
||||
bpms = []
|
||||
for t in self.tracks:
|
||||
if t.genre:
|
||||
genres[t.genre] = genres.get(t.genre, 0) + 1
|
||||
if t.key:
|
||||
keys[t.key] = keys.get(t.key, 0) + 1
|
||||
if t.bpm is not None:
|
||||
bpms.append(t.bpm)
|
||||
return Facets(
|
||||
genres=[
|
||||
GenreCount(name=k, count=v)
|
||||
for k, v in sorted(genres.items(), key=lambda x: -x[1])
|
||||
],
|
||||
keys=[
|
||||
GenreCount(name=k, count=v)
|
||||
for k, v in sorted(keys.items(), key=lambda x: -x[1])
|
||||
],
|
||||
bpm_min=min(bpms) if bpms else None,
|
||||
bpm_max=max(bpms) if bpms else None,
|
||||
total_tracks=len(self.tracks),
|
||||
)
|
||||
|
||||
def replace_track(self, track_id: str, entry) -> None:
|
||||
"""Refresh the read projection for one track from its (edited) model
|
||||
entry, mutating the existing Track object in place so both `tracks` and
|
||||
`by_key` reflect it. Bridges the store (edit model) and this read model
|
||||
until they're consolidated."""
|
||||
old = self.by_key.get(track_id)
|
||||
if old is None:
|
||||
return
|
||||
new = self._to_track(entry)
|
||||
for field in type(new).model_fields:
|
||||
setattr(old, field, getattr(new, field))
|
||||
|
||||
def entries_for(self, track_ids: list[str]) -> list[tuple[str, str]]:
|
||||
"""Map track ids to (key, PRIMARYKEY-type) pairs for playlist writing.
|
||||
Unknown ids are skipped (can't reference a track not in the collection)."""
|
||||
out = []
|
||||
for tid in track_ids:
|
||||
if tid in self.by_key:
|
||||
out.append((tid, "STEM" if tid in self.stem_keys else "TRACK"))
|
||||
return out
|
||||
|
||||
def stats(self, playlist_count: int | None = None) -> Stats:
|
||||
rating_breakdown = {i: 0 for i in range(6)}
|
||||
genres: dict[str, int] = {}
|
||||
bpm_buckets: dict[str, int] = {}
|
||||
rated = missing_key = missing_genre = missing_bpm = no_cues = 0
|
||||
for t in self.tracks:
|
||||
rating_breakdown[t.rating] += 1
|
||||
if t.rating > 0:
|
||||
rated += 1
|
||||
if not t.key:
|
||||
missing_key += 1
|
||||
if not t.genre:
|
||||
missing_genre += 1
|
||||
else:
|
||||
genres[t.genre] = genres.get(t.genre, 0) + 1
|
||||
if t.bpm is None:
|
||||
missing_bpm += 1
|
||||
else:
|
||||
lo = int(t.bpm // 10 * 10)
|
||||
bucket = f"{lo}-{lo + 10}"
|
||||
bpm_buckets[bucket] = bpm_buckets.get(bucket, 0) + 1
|
||||
if t.cue_count == 0:
|
||||
no_cues += 1
|
||||
total = len(self.tracks)
|
||||
histogram = [
|
||||
{"bucket": b, "count": c}
|
||||
for b, c in sorted(bpm_buckets.items(), key=lambda x: int(x[0].split("-")[0]))
|
||||
]
|
||||
top = sorted(genres.items(), key=lambda x: -x[1])[:10]
|
||||
return Stats(
|
||||
total_tracks=total,
|
||||
total_playlists=self._playlist_count if playlist_count is None else playlist_count,
|
||||
rated=rated,
|
||||
unrated=total - rated,
|
||||
missing_key=missing_key,
|
||||
missing_genre=missing_genre,
|
||||
missing_bpm=missing_bpm,
|
||||
no_cues=no_cues,
|
||||
rating_breakdown=rating_breakdown,
|
||||
bpm_histogram=histogram,
|
||||
top_genres=[GenreCount(name=k, count=v) for k, v in top],
|
||||
)
|
||||
|
||||
def playlist_tree(self) -> list[PlaylistNode]:
|
||||
return self._tree
|
||||
|
||||
def playlist_tracks(self, playlist_id: str) -> list[Track] | None:
|
||||
if playlist_id not in self._playlist_entries:
|
||||
return None
|
||||
out = []
|
||||
for k in self._playlist_entries[playlist_id]:
|
||||
t = self.by_key.get(k)
|
||||
if t is not None:
|
||||
out.append(t)
|
||||
return out
|
||||
@@ -0,0 +1,7 @@
|
||||
"""Platform-independent core: the generic model, the query/projection layer and
|
||||
the format-agnostic helpers.
|
||||
|
||||
Nothing in here may import ``traktor_nml_utils`` or ``konduktor.adapters`` —
|
||||
``test_layering.py`` enforces that. This package is what a Rekordbox or Serato
|
||||
adapter will be written against.
|
||||
"""
|
||||
@@ -0,0 +1,218 @@
|
||||
"""The adapter contract: what the app needs from a DJ library, generically.
|
||||
|
||||
Konduktor's save model is **projection + command replay**. The generic model is
|
||||
a READ PROJECTION; edits are commands an adapter replays onto its RETAINED
|
||||
NATIVE MODEL, which stays the write target. The generic model is never
|
||||
serialized back over a library — that is what preserves byte-exact saves, and
|
||||
it is also the only model that works for formats you cannot regenerate at all
|
||||
(a Rekordbox SQLite row, a Serato tag inside an audio file).
|
||||
|
||||
Two rules keep this honest:
|
||||
|
||||
* **No native type appears in any signature here.** If a concept cannot be
|
||||
expressed generically it does not belong on the protocol.
|
||||
* **Every mutating command returns its refreshed projection.** That makes the
|
||||
refresh an adapter-internal invariant rather than something each route has
|
||||
to remember; a forgotten refresh is a silently stale UI that no byte-level
|
||||
test would catch.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Protocol, runtime_checkable
|
||||
|
||||
from .capabilities import Capabilities
|
||||
from .model import Facets, PlaylistNode, Stats, Track, TrackCues, TrackPage
|
||||
from .pathmap import PathMapping
|
||||
|
||||
|
||||
@dataclass
|
||||
class SaveOutcome:
|
||||
"""What a save produced, in terms every platform can answer.
|
||||
|
||||
Promoted here once a second adapter needed it (the two-platform rule). The
|
||||
fields are deliberately optional because platforms differ in kind, not just
|
||||
in detail:
|
||||
|
||||
* `snapshot` is the exact bytes written, for the version-history commit —
|
||||
and it is None on a platform Konduktor does not version. A Rekordbox
|
||||
library is `master.db` plus ~200 analysis files plus a playlist XML, so
|
||||
there is no single blob that *is* the library, and restoring the database
|
||||
alone would roll back the app's own auth and sampler state.
|
||||
* `tag_results` reports embedded audio-file tag writes, which only a
|
||||
platform that does them will populate.
|
||||
"""
|
||||
|
||||
summary: str # human-readable edit summary, for the version-history message
|
||||
snapshot: bytes | None = None
|
||||
tag_results: list = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class NewTrack:
|
||||
"""A track to ADD to a library, described generically.
|
||||
|
||||
Import is the first operation that puts a track into a library that never
|
||||
had one, so it needs a way to say "here is a track" without naming a
|
||||
platform. That is all this is: the generic projection of a track, plus the
|
||||
audio file it should point at.
|
||||
|
||||
* `track` carries the metadata. **Its `id` is ignored** — an id belongs to
|
||||
the library that holds the track, and this one comes from somewhere
|
||||
else. The receiving adapter assigns its own and returns it.
|
||||
* `cues` is optional because a track can be imported without prep, and
|
||||
because a platform may hold the track but not (yet) its cues.
|
||||
* `audio_path` is a path on THIS machine that must already exist. Copying
|
||||
the audio is the caller's job, deliberately: an adapter's business is
|
||||
the library, and a file copy that failed halfway is not something a
|
||||
library write should be discovering.
|
||||
"""
|
||||
|
||||
track: Track
|
||||
audio_path: Path
|
||||
cues: TrackCues | None = None
|
||||
|
||||
|
||||
class AdapterError(Exception):
|
||||
"""Base for every failure an adapter reports to the HTTP layer."""
|
||||
|
||||
|
||||
class LibraryNotSupported(AdapterError):
|
||||
"""No driver can open this path, or it failed to parse."""
|
||||
|
||||
|
||||
class NotFound(AdapterError):
|
||||
"""Unknown track, playlist or marker index."""
|
||||
|
||||
|
||||
class InvalidCommand(AdapterError):
|
||||
"""Well-formed request the library cannot accept (bad slot, BPM <= 0, ...)."""
|
||||
|
||||
|
||||
class Unsupported(AdapterError):
|
||||
"""The platform cannot represent this edit at all."""
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class LibraryAdapter(Protocol):
|
||||
"""One open library. Stateful; exactly one is loaded at a time."""
|
||||
|
||||
platform: str
|
||||
path: Path
|
||||
|
||||
# ---- identity -------------------------------------------------------
|
||||
def capabilities(self) -> Capabilities: ...
|
||||
def reload(self) -> None: ...
|
||||
|
||||
# ---- read projection -------------------------------------------------
|
||||
@property
|
||||
def tracks(self) -> list[Track]: ...
|
||||
def track(self, track_id: str) -> Track | None: ...
|
||||
def query_tracks(self, **kw) -> TrackPage: ...
|
||||
def facets(self) -> Facets: ...
|
||||
def stats(self, playlist_count: int) -> Stats: ...
|
||||
def playlist_tree(self) -> list[PlaylistNode]: ...
|
||||
def playlist_entries(self, node_id: str) -> list[str] | None: ...
|
||||
def playlist_tracks(self, node_id: str) -> list[Track] | None: ...
|
||||
def track_cues(self, track_id: str) -> TrackCues | None: ...
|
||||
|
||||
# ---- commands: playlists --------------------------------------------
|
||||
def create_playlist(self, name: str, parent_id: str | None = None) -> str: ...
|
||||
# Folders are a separate verb rather than a flag on create_playlist: a
|
||||
# platform can support one and not the other, and `capabilities.playlists
|
||||
# .folders` is what the UI gates on.
|
||||
def create_folder(self, name: str, parent_id: str | None = None) -> str: ...
|
||||
def rename_playlist(self, node_id: str, name: str) -> None: ...
|
||||
def delete_playlist(self, node_id: str) -> None: ...
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: ...
|
||||
|
||||
# ---- commands: adding tracks ----------------------------------------
|
||||
# The ONLY command that creates a track rather than editing one, and the
|
||||
# one place the "retained native model" rule is stretched: everywhere else
|
||||
# the write target was parsed from a real file, which is what makes the
|
||||
# fidelity guarantee hold. A new entry has no parsed original, so the rule
|
||||
# becomes "an added entry must not perturb any existing one" — which is
|
||||
# what `test_save_fidelity.py` checks rather than taking on trust.
|
||||
def add_tracks(self, items: list["NewTrack"]) -> list[str]: ...
|
||||
|
||||
# Remove tracks from the library — and so from every playlist, since an
|
||||
# entry naming a track the library no longer has is a dangling reference.
|
||||
# Never touches audio files. Returns how many were removed; gated on
|
||||
# `capabilities().tracks.removable`.
|
||||
def remove_tracks(self, track_ids: list[str]) -> int: ...
|
||||
|
||||
# ---- commands: track metadata / art ---------------------------------
|
||||
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None: ...
|
||||
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None: ...
|
||||
def cover_art(self, track_id: str) -> tuple[bytes, str] | None: ...
|
||||
|
||||
# ---- commands: cues --------------------------------------------------
|
||||
def set_cue(
|
||||
self,
|
||||
track_id: str,
|
||||
*,
|
||||
slot: int,
|
||||
start_sec: float,
|
||||
cue_type: str,
|
||||
length_sec: float = 0.0,
|
||||
role: str = "hotcue",
|
||||
name: str | None = None,
|
||||
) -> TrackCues: ...
|
||||
def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> TrackCues: ...
|
||||
def delete_cue(self, track_id: str, slot: int) -> TrackCues: ...
|
||||
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues: ...
|
||||
|
||||
# ---- commands: beatgrid ---------------------------------------------
|
||||
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> TrackCues: ...
|
||||
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> TrackCues: ...
|
||||
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> TrackCues: ...
|
||||
def delete_grid_marker(self, track_id: str, index: int) -> TrackCues: ...
|
||||
def replace_grid(self, track_id: str, markers: list[tuple[float, float]]) -> TrackCues: ...
|
||||
def set_analysed_grid(self, track_id: str, markers: list[tuple[float, float]]) -> TrackCues: ...
|
||||
def delete_grid(self, track_id: str) -> TrackCues: ...
|
||||
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues: ...
|
||||
|
||||
# ---- audio / paths ---------------------------------------------------
|
||||
def audio_path(self, track_id: str) -> Path | None: ...
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None: ...
|
||||
def path_prefix_suggestions(self) -> dict: ...
|
||||
def remap_preview(self, mapping: PathMapping) -> dict: ...
|
||||
# {old track id: new track id}; ids may change because a Traktor id IS its path.
|
||||
def remap_locations(self, mapping: PathMapping) -> dict[str, str]: ...
|
||||
|
||||
# ---- save -------------------------------------------------------------
|
||||
@property
|
||||
def dirty(self) -> bool: ...
|
||||
def save(self): ...
|
||||
def snapshot(self) -> bytes: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class LibraryDriver(Protocol):
|
||||
"""Opens libraries of one platform. Stateless; one instance per platform."""
|
||||
|
||||
platform: str
|
||||
display_name: str
|
||||
suffixes: tuple[str, ...]
|
||||
# True when this platform's libraries live on plugged-in media rather than at
|
||||
# a fixed path — so `detect()` genuinely changes between calls, and the app
|
||||
# can offer them as import SOURCES. Optional, and False for a platform that
|
||||
# does not set it, because most keep one library in a known place.
|
||||
removable: bool
|
||||
# Whether a user picks a FILE or a DIRECTORY for this platform. Both exist:
|
||||
# Traktor's library is `collection.nml`, OneLibrary's is the drive, and
|
||||
# Serato's will be a `_Serato_` folder. The file browser and the open route
|
||||
# both read this rather than assuming everything is a file. Defaults to
|
||||
# "file" for a driver that does not set it.
|
||||
selects: str
|
||||
|
||||
def can_open(self, path: Path) -> bool: ...
|
||||
def open(self, path: Path) -> LibraryAdapter: ...
|
||||
# OPTIONAL. What to call an opened library on screen. Only the adapter can
|
||||
# answer for a platform where one library has more than one valid path —
|
||||
# the filename is otherwise assumed, and that assumption is wrong for a
|
||||
# library that is a drive. Omitted means "the path's own name".
|
||||
def display_name_for(self, path: Path) -> str: ...
|
||||
def detect(self) -> list: ...
|
||||
def describe(self, path: Path) -> object: ...
|
||||
@@ -1,6 +1,6 @@
|
||||
"""Write track metadata into audio files' embedded tags (best-effort).
|
||||
|
||||
Konduktor's source of truth is the `.nml`; this module additionally syncs the
|
||||
Konduktor's source of truth is the library file; this module additionally syncs the
|
||||
safe metadata fields into the audio file itself so the data travels with the
|
||||
file (portability to other apps). It is best-effort: if the file isn't present
|
||||
(e.g. the drive isn't mounted) or the format doesn't support a field, it reports
|
||||
@@ -14,7 +14,12 @@ from __future__ import annotations
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
# The safe, editable metadata we sync to files (mirrors PlaylistStore.EDITABLE_FIELDS).
|
||||
# Whose POPM frame we claim when writing an ID3 rating. The frame is per-owner,
|
||||
# so writing under the DJ app's own email is what makes the rating visible there.
|
||||
# The *51 scaling below is the POPM convention itself, not a platform quirk.
|
||||
DEFAULT_POPM_EMAIL = "no@email"
|
||||
|
||||
# The safe, editable metadata we sync to files (the adapter's editable field set).
|
||||
# rating is 0–5 stars.
|
||||
TagMeta = dict # keys: title, artist, album, genre, label, remixer, producer,
|
||||
# comment, mix, release_date, rating
|
||||
@@ -27,22 +32,6 @@ class TagResult:
|
||||
detail: str = ""
|
||||
|
||||
|
||||
def resolve_path(volume: str | None, dir_: str | None, file: str | None) -> Path:
|
||||
"""Map a Traktor LOCATION to an OS path.
|
||||
|
||||
Paths are trusted (per project decision): boot volume 'Macintosh HD' -> '/',
|
||||
a Windows drive like 'X:' stays a drive path, other volumes -> /Volumes/<v>.
|
||||
"""
|
||||
d = (dir_ or "").replace("/:", "/")
|
||||
name = file or ""
|
||||
vol = volume or ""
|
||||
if vol.endswith(":"): # Windows drive letter, e.g. "X:"
|
||||
return Path(vol + d + name)
|
||||
if vol and vol != "Macintosh HD": # other mounted volume (macOS/*nix)
|
||||
return Path("/Volumes") / vol / (d.lstrip("/") + name)
|
||||
return Path(d + name) # boot volume
|
||||
|
||||
|
||||
def read_cover(path: Path) -> tuple[bytes, str] | None:
|
||||
"""Return (image_bytes, mime) of the file's embedded front cover, or None."""
|
||||
if not path.exists():
|
||||
@@ -148,15 +137,17 @@ def _clean(v) -> str | None:
|
||||
return s or None
|
||||
|
||||
|
||||
def write_tags(path: Path, meta: TagMeta) -> TagResult:
|
||||
def write_tags(
|
||||
path: Path, meta: TagMeta, *, popm_email: str = DEFAULT_POPM_EMAIL
|
||||
) -> TagResult:
|
||||
if not path.exists():
|
||||
return TagResult(False, "file-not-found", str(path))
|
||||
ext = path.suffix.lower()
|
||||
try:
|
||||
if ext == ".mp3":
|
||||
_write_id3(path, meta, id3_only=False)
|
||||
_write_id3(path, meta, id3_only=False, popm_email=popm_email)
|
||||
elif ext in (".aif", ".aiff"):
|
||||
_write_aiff(path, meta)
|
||||
_write_aiff(path, meta, popm_email=popm_email)
|
||||
elif ext in (".m4a", ".mp4") or path.name.lower().endswith(".stem.m4a"):
|
||||
_write_mp4(path, meta)
|
||||
elif ext == ".flac":
|
||||
@@ -170,7 +161,7 @@ def write_tags(path: Path, meta: TagMeta) -> TagResult:
|
||||
|
||||
|
||||
# ---- ID3 (mp3 / aiff) --------------------------------------------------
|
||||
def _apply_id3(id3, meta: TagMeta) -> None:
|
||||
def _apply_id3(id3, meta: TagMeta, popm_email: str = DEFAULT_POPM_EMAIL) -> None:
|
||||
from mutagen.id3 import (
|
||||
COMM,
|
||||
POPM,
|
||||
@@ -217,31 +208,33 @@ def _apply_id3(id3, meta: TagMeta) -> None:
|
||||
if stars > 0:
|
||||
id3.add(
|
||||
POPM(
|
||||
email="traktor@native-instruments.de",
|
||||
email=popm_email,
|
||||
rating=max(0, min(5, stars)) * 51,
|
||||
count=0,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _write_id3(path: Path, meta: TagMeta, id3_only: bool) -> None:
|
||||
def _write_id3(
|
||||
path: Path, meta: TagMeta, id3_only: bool, popm_email: str = DEFAULT_POPM_EMAIL
|
||||
) -> None:
|
||||
from mutagen.id3 import ID3, ID3NoHeaderError
|
||||
|
||||
try:
|
||||
id3 = ID3(path)
|
||||
except ID3NoHeaderError:
|
||||
id3 = ID3()
|
||||
_apply_id3(id3, meta)
|
||||
_apply_id3(id3, meta, popm_email)
|
||||
id3.save(path)
|
||||
|
||||
|
||||
def _write_aiff(path: Path, meta: TagMeta) -> None:
|
||||
def _write_aiff(path: Path, meta: TagMeta, popm_email: str = DEFAULT_POPM_EMAIL) -> None:
|
||||
from mutagen.aiff import AIFF
|
||||
|
||||
audio = AIFF(path)
|
||||
if audio.tags is None:
|
||||
audio.add_tags()
|
||||
_apply_id3(audio.tags, meta)
|
||||
_apply_id3(audio.tags, meta, popm_email)
|
||||
audio.save()
|
||||
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
"""Auto Hotcues: resolve a slot template against a track's structure.
|
||||
|
||||
The user binds each hotcue slot to an EVENT ("first drop", "start of the second
|
||||
breakdown", …) plus an offset in beats ("16 beats before the first drop"). The
|
||||
events come from `core/structure.py`; this module is the pure part — which
|
||||
slots get a cue, where, called what, and why a slot got nothing — so it is
|
||||
testable without audio.
|
||||
|
||||
Offsets are counted along the grid's own beats, not in seconds, so a -16 on a
|
||||
flexible grid lands 16 BEATS earlier even across a tempo change.
|
||||
|
||||
Each slot reports an outcome rather than silently dropping, because a template
|
||||
names specific events and "no second drop in this track" is an answer the user
|
||||
needs, not a cue that quietly failed to appear.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .structure import EVENTS, Structure
|
||||
|
||||
LABELS: dict[str, str] = {
|
||||
"first_beat": "First Beat",
|
||||
"intro_end": "Intro End",
|
||||
"build_1": "Build 1",
|
||||
"drop_1": "Drop 1",
|
||||
"breakdown_1": "Breakdown 1",
|
||||
"build_2": "Build 2",
|
||||
"drop_2": "Drop 2",
|
||||
"breakdown_2": "Breakdown 2",
|
||||
"build_3": "Build 3",
|
||||
"drop_3": "Drop 3",
|
||||
"breakdown_3": "Breakdown 3",
|
||||
"outro": "Outro",
|
||||
"last_beat": "Last Beat",
|
||||
}
|
||||
assert set(LABELS) == set(EVENTS)
|
||||
|
||||
# Outcomes a slot can report.
|
||||
PLACED = "placed"
|
||||
NOT_FOUND = "not_found" # the track has no such event (e.g. no third drop)
|
||||
OUT_OF_RANGE = "out_of_range" # the offset moves it before the start / past the end
|
||||
OCCUPIED = "occupied" # the slot holds a cue and overwrite was not asked for
|
||||
PROTECTED = "protected" # the slot holds a cue the adapter will not replace
|
||||
DUPLICATE = "duplicate" # another cue (kept, or new in a lower slot) is on this beat
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SlotRequest:
|
||||
slot: int
|
||||
event: str
|
||||
offset_beats: int = 0
|
||||
overwrite: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExistingCue:
|
||||
"""A hotcue already in the bank, before this run."""
|
||||
|
||||
editable: bool
|
||||
start: float # seconds
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SlotOutcome:
|
||||
slot: int
|
||||
event: str
|
||||
status: str
|
||||
start: float | None = None
|
||||
name: str | None = None
|
||||
duplicate_of: int | None = None # the slot that got this beat, for DUPLICATE
|
||||
|
||||
|
||||
def cue_name(event: str, offset_beats: int) -> str:
|
||||
"""The label a placed cue carries, e.g. ``Drop 1`` or ``Drop 1 -16``."""
|
||||
label = LABELS[event]
|
||||
return f"{label} {offset_beats:+d}" if offset_beats else label
|
||||
|
||||
|
||||
def _beat_of(structure: Structure, t: float) -> int | None:
|
||||
"""The grid beat a cue at ``t`` sits on, or None if it is between beats.
|
||||
|
||||
A quarter-beat tolerance: a hand-placed cue is rarely sample-exact on the
|
||||
grid, and one a DJ put on the half-beat on purpose is a different beat.
|
||||
"""
|
||||
b = structure.beats
|
||||
i = int(np.clip(np.searchsorted(b, t), 1, len(b) - 1))
|
||||
i = i if abs(b[i] - t) < abs(b[i - 1] - t) else i - 1
|
||||
step = b[min(i + 1, len(b) - 1)] - b[max(i - 1, 0)]
|
||||
step = step / 2 if step > 0 else 0.5
|
||||
return i if abs(b[i] - t) <= step / 4 else None
|
||||
|
||||
|
||||
def plan(
|
||||
structure: Structure,
|
||||
requests: list[SlotRequest],
|
||||
existing: dict[int, ExistingCue],
|
||||
) -> list[SlotOutcome]:
|
||||
"""Decide every requested slot.
|
||||
|
||||
``existing`` is the bank before this run. A non-editable cue (a Traktor grid
|
||||
marker's companion) is never replaced, even when overwrite is ticked,
|
||||
because the adapter would refuse it anyway.
|
||||
|
||||
**One cue per beat.** A slot whose position is on a beat that already has a
|
||||
cue — one this run is placing in a LOWER slot, or one that was in the bank
|
||||
before and stays there (the grid cue, a hand-placed cue) — is skipped as a
|
||||
duplicate of that slot: a second pad on the same beat is a wasted pad. New
|
||||
cues are decided in slot order, so "lower wins" holds whatever order the
|
||||
request lists them in.
|
||||
|
||||
A cue being REPLACED frees its beat only if its replacement is actually
|
||||
placed; a replacement that is itself skipped leaves the old cue — and its
|
||||
claim on the beat — where they were. That is circular (whether slot 3's old
|
||||
cue survives decides slot 5, and slot 5 may be what slot 3 collides with),
|
||||
so the plan is recomputed until the set of surviving cues stops changing;
|
||||
each pass can only add survivors, so it ends within one pass per slot.
|
||||
"""
|
||||
requested = {r.slot: r for r in requests}
|
||||
# Old cues whose replacement was not placed, found by the previous pass.
|
||||
surviving_overwritten: set[int] = set()
|
||||
while True:
|
||||
claims: dict[int, int] = {} # beat index -> slot of the cue on it
|
||||
for slot, cue in sorted(existing.items()):
|
||||
replaced = slot in requested and requested[slot].overwrite and cue.editable
|
||||
if replaced and slot not in surviving_overwritten:
|
||||
continue
|
||||
beat = _beat_of(structure, cue.start)
|
||||
if beat is not None:
|
||||
claims.setdefault(beat, slot)
|
||||
out = _decide(structure, requests, existing, claims)
|
||||
now = {
|
||||
o.slot for o in out
|
||||
if o.slot in existing and requested[o.slot].overwrite
|
||||
and existing[o.slot].editable and o.status != PLACED
|
||||
}
|
||||
if now <= surviving_overwritten:
|
||||
return out
|
||||
surviving_overwritten |= now
|
||||
|
||||
|
||||
def _decide(structure, requests, existing, claims) -> list[SlotOutcome]:
|
||||
out: list[SlotOutcome] = []
|
||||
taken = dict(claims)
|
||||
for r in sorted(requests, key=lambda r: r.slot):
|
||||
cue = existing.get(r.slot)
|
||||
if cue is not None and not cue.editable:
|
||||
out.append(SlotOutcome(r.slot, r.event, PROTECTED))
|
||||
continue
|
||||
if cue is not None and not r.overwrite:
|
||||
out.append(SlotOutcome(r.slot, r.event, OCCUPIED))
|
||||
continue
|
||||
beat = structure.events.get(r.event)
|
||||
if beat is None:
|
||||
out.append(SlotOutcome(r.slot, r.event, NOT_FOUND))
|
||||
continue
|
||||
index = beat + r.offset_beats
|
||||
t = structure.beat_time(index)
|
||||
if t < 0 or t >= structure.duration:
|
||||
out.append(SlotOutcome(r.slot, r.event, OUT_OF_RANGE))
|
||||
continue
|
||||
if index in taken:
|
||||
out.append(SlotOutcome(r.slot, r.event, DUPLICATE, duplicate_of=taken[index]))
|
||||
continue
|
||||
taken[index] = r.slot
|
||||
out.append(SlotOutcome(r.slot, r.event, PLACED, round(t, 4), cue_name(r.event, r.offset_beats)))
|
||||
return out
|
||||
@@ -0,0 +1,111 @@
|
||||
"""What a loaded library can actually do.
|
||||
|
||||
Capabilities are ``f(platform, version)``: the UI reads them and disables or
|
||||
hides the controls the loaded platform cannot persist, so a user is never
|
||||
offered an edit that will silently vanish on save. No component branches on the
|
||||
platform name — that is the whole point.
|
||||
|
||||
With a single adapter most of these are constants, and several keys exist purely
|
||||
so the second adapter has somewhere to answer. That is deliberate: the shape is
|
||||
cheap now and expensive to retrofit once components depend on it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
# Why a library cannot be edited. A FACT, not a sentence — the UI composes the
|
||||
# wording (lib/platformCopy.ts), and the two causes need very different ones:
|
||||
# "Konduktor cannot write this platform YET" is a roadmap gap the user should
|
||||
# expect to close, whereas "this library is synced with Rekordbox Cloud" is a
|
||||
# permanent refusal protecting their other machines.
|
||||
# `not_in_library` is a folder of loose files being browsed: nothing there is a
|
||||
# library to write to, and the way to edit one is to add it to the collection.
|
||||
ReadonlyCause = Literal["platform_incomplete", "cloud_synced", "not_in_library"]
|
||||
|
||||
CueType = Literal["cue", "fade_in", "fade_out", "load", "loop"]
|
||||
CueRole = Literal["hotcue", "memory"]
|
||||
MediaKind = Literal["audio", "stem", "video"]
|
||||
PlaylistKind = Literal["folder", "playlist", "smart"]
|
||||
|
||||
|
||||
class CueCapabilities(BaseModel):
|
||||
# Whether cues can be CREATED/CHANGED. Symmetric with GridCapabilities —
|
||||
# a platform can be writable overall while its cue store is not yet
|
||||
# implemented, which is exactly the Rekordbox milestone-2 state.
|
||||
editable: bool = False
|
||||
hotcue_slots: int = 8 # size of the addressable bank; 0 = no bank
|
||||
slot_labels: Literal["number", "letter"] = "number"
|
||||
# Memory cues are Rekordbox-only today, so they are modelled and PRESERVED
|
||||
# but not editable anywhere yet (the two-platform promotion rule).
|
||||
memory_cues: bool = False
|
||||
max_memory_cues: int | None = None
|
||||
types: list[CueType] = ["cue"]
|
||||
color: Literal["none", "free", "palette"] = "none"
|
||||
palette: list[str] = []
|
||||
named: bool = False
|
||||
# Where a saved loop lives: a cue type (Traktor) or its own bank (Serato).
|
||||
loops: Literal["none", "cue_type", "separate_bank"] = "none"
|
||||
loop_slots: int | None = None
|
||||
|
||||
|
||||
class GridCapabilities(BaseModel):
|
||||
editable: bool = False
|
||||
flexible: bool = False # multi-marker (variable-tempo) grids can be written
|
||||
lockable: bool = False # a per-track grid/analysis lock exists
|
||||
|
||||
|
||||
class TrackCapabilities(BaseModel):
|
||||
rating_max: int = 5
|
||||
editable_fields: list[str] = []
|
||||
media_kinds: list[MediaKind] = ["audio"]
|
||||
# Tracks can be removed from the library (and so from its playlists). The
|
||||
# audio file is never touched either way.
|
||||
removable: bool = False
|
||||
# The audio files this library can hold, as lower-case suffixes. What a
|
||||
# browsed folder offers to add — a file the library would refuse, or that
|
||||
# the DJ app cannot play, is not worth listing as addable.
|
||||
audio_formats: list[str] = [".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a"]
|
||||
artwork: bool = False
|
||||
artwork_note: str | None = None
|
||||
|
||||
|
||||
class PlaylistCapabilities(BaseModel):
|
||||
folders: bool = False
|
||||
smart: Literal["none", "read_only"] = "none"
|
||||
reorder: bool = False
|
||||
|
||||
|
||||
class SaveCapabilities(BaseModel):
|
||||
"""Structured facts, never finished sentences.
|
||||
|
||||
The warning a user needs before saving is genuinely per-platform, so the
|
||||
adapter supplies the facts and the UI composes the wording — which keeps the
|
||||
copy (and any future translation) in the UI without making it vague.
|
||||
"""
|
||||
|
||||
app_name: str
|
||||
library_label: str
|
||||
overwrite_risk: Literal["none", "on_exit", "while_running"] = "none"
|
||||
history: bool = True
|
||||
|
||||
|
||||
class Capabilities(BaseModel):
|
||||
platform: str
|
||||
version: str | None = None
|
||||
# Whether ANY edit can be persisted to this library.
|
||||
#
|
||||
# This is deliberately NOT the same as every individual capability being
|
||||
# false. "The platform has no such feature" and "this library cannot be
|
||||
# written at all" look identical to a UI that only sees the per-feature
|
||||
# flags, and the second one needs saying out loud — silently inert controls
|
||||
# read as a bug. When this is false the per-feature flags are still reported
|
||||
# honestly, so the UI can show what the platform *would* support.
|
||||
writable: bool = True
|
||||
readonly_cause: ReadonlyCause | None = None
|
||||
cues: CueCapabilities = CueCapabilities()
|
||||
grid: GridCapabilities = GridCapabilities()
|
||||
tracks: TrackCapabilities = TrackCapabilities()
|
||||
playlists: PlaylistCapabilities = PlaylistCapabilities()
|
||||
save: SaveCapabilities
|
||||
@@ -0,0 +1,211 @@
|
||||
"""What changed this session, at field resolution.
|
||||
|
||||
Three things need to know about an edit, and they need different views of it:
|
||||
|
||||
* the file-tag sync wants *which metadata fields* of which track changed, so it
|
||||
writes only those and leaves everything else in the file alone;
|
||||
* the version history wants a human sentence;
|
||||
* a future undo wants the value a field held before.
|
||||
|
||||
The journal records one `Change` per command and derives all three. Recording it
|
||||
at field resolution has to happen from the start: reconstructed afterwards by
|
||||
diffing, an edit that set a field back to its original value is indistinguishable
|
||||
from one that never happened — which is exactly the case where rewriting the
|
||||
field would lose the platform's own formatting of it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Change:
|
||||
scope: str # "track" | "cue" | "grid" | "lock" | "playlist" | "library"
|
||||
op: str # "set" | "add" | "delete" | "modify" | "create" | "rename" | ...
|
||||
target: str | None = None # track id, or a playlist's name
|
||||
detail: str | None = None # field name, "slot:3", "marker:1", "art", ...
|
||||
before: Any = None
|
||||
after: Any = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class EditJournal:
|
||||
changes: list[Change] = field(default_factory=list)
|
||||
|
||||
# ---- recording --------------------------------------------------------
|
||||
def record(
|
||||
self,
|
||||
scope: str,
|
||||
op: str,
|
||||
target: str | None = None,
|
||||
detail: str | None = None,
|
||||
before: Any = None,
|
||||
after: Any = None,
|
||||
) -> None:
|
||||
self.changes.append(Change(scope, op, target, detail, before, after))
|
||||
|
||||
def clear(self) -> None:
|
||||
self.changes.clear()
|
||||
|
||||
@property
|
||||
def dirty(self) -> bool:
|
||||
return bool(self.changes)
|
||||
|
||||
# ---- views ------------------------------------------------------------
|
||||
def fields_for(self, track_id: str) -> set[str]:
|
||||
"""Metadata field names edited on this track (drives the file-tag sync)."""
|
||||
return {
|
||||
c.detail
|
||||
for c in self.changes
|
||||
if c.scope == "track" and c.op == "set" and c.target == track_id and c.detail
|
||||
}
|
||||
|
||||
def edited_tracks(self) -> set[str]:
|
||||
"""Tracks whose metadata or artwork changed.
|
||||
|
||||
Excludes tracks that were ADDED. They are not edits: nothing about them
|
||||
changed, they simply did not exist before. Counting them here would both
|
||||
mislabel the version-history message and drag them through the file-tag
|
||||
sync, which has nothing to write for a track whose fields were never
|
||||
touched. Excludes tracks REMOVED from the library for the same reason:
|
||||
"edited 40 tracks" would describe a deletion as an edit.
|
||||
"""
|
||||
removed = self.removed_tracks()
|
||||
return {
|
||||
c.target
|
||||
for c in self.changes
|
||||
if c.scope == "track" and c.target and c.op not in ("add", "remove")
|
||||
and c.target not in removed
|
||||
}
|
||||
|
||||
def removed_tracks(self) -> set[str]:
|
||||
"""Tracks taken out of the library this session."""
|
||||
return {
|
||||
c.target for c in self.changes if c.scope == "track" and c.op == "remove" and c.target
|
||||
}
|
||||
|
||||
def added_tracks(self) -> set[str]:
|
||||
"""Tracks put into the library that it did not previously hold."""
|
||||
return {
|
||||
c.target for c in self.changes if c.scope == "track" and c.op == "add" and c.target
|
||||
}
|
||||
|
||||
def retarget(self, old_id: str, new_id: str) -> None:
|
||||
"""Follow a track whose id changed (a path remap rewrites LOCATIONs, and
|
||||
the id is derived from the location). Without this, edits made earlier in
|
||||
the session would silently stop syncing to the file."""
|
||||
if old_id == new_id:
|
||||
return
|
||||
for i, c in enumerate(self.changes):
|
||||
if c.target == old_id and c.scope in ("track", "cue", "grid", "lock"):
|
||||
self.changes[i] = Change(c.scope, c.op, new_id, c.detail, c.before, c.after)
|
||||
|
||||
# ---- the version-history message --------------------------------------
|
||||
def summary(self, extra_tracks: set[str] | None = None) -> str:
|
||||
"""A one-line, human-readable summary of this session's edits, used as the
|
||||
version-history commit message (e.g. "Edited 3 tracks; renamed playlist
|
||||
'House'; added 6 hotcues; edited beatgrid on 2 tracks").
|
||||
|
||||
Prep edits are collapsed to meaningful aggregates rather than raw op
|
||||
counts: hotcues report their NET change (created − removed), and beatgrid/
|
||||
lock edits report how many distinct tracks were affected — so tweaking one
|
||||
grid ten times reads as "1 track", not "10 edits".
|
||||
"""
|
||||
parts: list[str] = []
|
||||
|
||||
def tracks(n: int) -> str:
|
||||
return f"{n} track{'' if n == 1 else 's'}"
|
||||
|
||||
# --- tracks added to the library (import) ---
|
||||
# First, because it is the largest-grained thing that can have happened:
|
||||
# "added 52 tracks" is the headline, and the cue/grid counts that follow
|
||||
# are mostly describing those same tracks' imported prep.
|
||||
n_added = len(self.added_tracks())
|
||||
if n_added:
|
||||
parts.append(f"added {tracks(n_added)}")
|
||||
n_removed = len(self.removed_tracks())
|
||||
if n_removed:
|
||||
parts.append(f"removed {tracks(n_removed)} from the collection")
|
||||
|
||||
# --- track metadata + cover art (already counted per-track) ---
|
||||
n_meta = len(self.edited_tracks() | (extra_tracks or set()))
|
||||
if n_meta:
|
||||
parts.append(f"edited {tracks(n_meta)}")
|
||||
|
||||
# --- playlists (name-bearing) ---
|
||||
pl_names: dict[str, list[str]] = {}
|
||||
for c in self.changes:
|
||||
if c.scope == "playlist" and c.target:
|
||||
pl_names.setdefault(c.op, []).append(c.target)
|
||||
# A folder is its own op so the message does not call it a playlist —
|
||||
# "created playlists 'Hardy', 'demos'" reads as two playlists when one is
|
||||
# the folder the other went into.
|
||||
for op, verb, noun in (
|
||||
("create", "created", "playlist"),
|
||||
("create-folder", "created", "folder"),
|
||||
("rename", "renamed", "playlist"),
|
||||
("delete", "deleted", "playlist"),
|
||||
("entries", "reordered", "playlist"),
|
||||
):
|
||||
names = pl_names.get(op, [])
|
||||
if not names:
|
||||
continue
|
||||
if len(names) <= 2:
|
||||
joined = ", ".join(f"'{n}'" for n in names)
|
||||
parts.append(f"{verb} {noun}{'' if len(names) == 1 else 's'} {joined}")
|
||||
else:
|
||||
parts.append(f"{verb} {len(names)} {noun}s")
|
||||
|
||||
# --- hotcues: net change in count, scoped by how many tracks were touched ---
|
||||
hc_add = hc_del = 0
|
||||
hc_tracks: set[str] = set()
|
||||
grid_edit: set[str] = set()
|
||||
grid_del: set[str] = set()
|
||||
lock_on: set[str] = set()
|
||||
lock_off: set[str] = set()
|
||||
for c in self.changes:
|
||||
if c.scope == "cue":
|
||||
if c.target:
|
||||
hc_tracks.add(c.target)
|
||||
if c.op == "add":
|
||||
hc_add += 1
|
||||
elif c.op == "delete":
|
||||
hc_del += 1
|
||||
elif c.scope == "grid":
|
||||
# "delete" is the ONLY deletion op. Everything else — including
|
||||
# ops added later — counts as an edit, because mis-labelling an
|
||||
# edit as a deletion in the history summary is the damaging direction.
|
||||
(grid_del if c.op == "delete" else grid_edit).add(c.target or "")
|
||||
elif c.scope == "lock":
|
||||
(lock_on if c.op == "on" else lock_off).add(c.target or "")
|
||||
|
||||
if hc_tracks:
|
||||
net = hc_add - hc_del
|
||||
scope = f" across {tracks(len(hc_tracks))}" if len(hc_tracks) > 1 else ""
|
||||
if net > 0:
|
||||
parts.append(f"added {net} hotcue{'' if net == 1 else 's'}{scope}")
|
||||
elif net < 0:
|
||||
parts.append(f"removed {-net} hotcue{'' if -net == 1 else 's'}{scope}")
|
||||
else: # net zero but there was activity (moves / retypes / add-then-delete)
|
||||
parts.append(f"adjusted hotcues{scope}")
|
||||
|
||||
# --- beatgrids & lock: per-track counts ---
|
||||
if grid_edit:
|
||||
parts.append(f"edited beatgrid on {tracks(len(grid_edit))}")
|
||||
if grid_del:
|
||||
parts.append(f"deleted beatgrid on {tracks(len(grid_del))}")
|
||||
if lock_on:
|
||||
parts.append(f"locked {tracks(len(lock_on))}")
|
||||
if lock_off:
|
||||
parts.append(f"unlocked {tracks(len(lock_off))}")
|
||||
|
||||
# --- path remap ---
|
||||
for c in self.changes:
|
||||
if c.scope == "library" and c.op == "remap" and c.after:
|
||||
parts.append(f"remapped {c.after} file paths")
|
||||
|
||||
if not parts:
|
||||
return "Saved changes"
|
||||
summary = "; ".join(parts)
|
||||
return summary[0].upper() + summary[1:]
|
||||
@@ -0,0 +1,150 @@
|
||||
"""Writing a BRAND NEW library for another platform.
|
||||
|
||||
The contract an exporter is written against, and the payload it consumes. Both
|
||||
are strictly generic: an exporter is handed `Track`s, `TrackCues` and playlist
|
||||
names, never a native type from whatever library the user happens to have open.
|
||||
That is what makes "the source is whatever is loaded" free — a Rekordbox
|
||||
collection exports to Traktor with no exporter knowing Rekordbox exists.
|
||||
|
||||
## Why this is not `LibraryDriver`
|
||||
|
||||
A driver OPENS a library that already exists; an exporter CREATES one where
|
||||
nothing does. Keeping them apart keeps the edit path — the one carrying the
|
||||
byte-fidelity guarantees — out of reach of a lossy-by-design export.
|
||||
|
||||
An exporter also declares **static** capabilities. It has no instance and no
|
||||
path, because the library it describes does not exist yet, which is exactly the
|
||||
question "what can the target represent?" needs answering before any of it is
|
||||
written.
|
||||
|
||||
## Who does what
|
||||
|
||||
`core` plans and copies; the exporter only writes the library file. Layout,
|
||||
collision and dedup rules are platform-independent and must not drift between
|
||||
targets — and the exporter could not write a Traktor `<LOCATION>` before the
|
||||
destination path is known anyway, so every `ExportTrack` arrives carrying its
|
||||
FINAL audio path.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Protocol, runtime_checkable
|
||||
|
||||
from .capabilities import Capabilities
|
||||
from .model import Track, TrackCues
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExportTrack:
|
||||
"""One track, with its prep, and where its audio now lives."""
|
||||
|
||||
track: Track
|
||||
#: Where the copy ALREADY IS. The exporter never copies; by the time it runs
|
||||
#: the file is on disk, because a half-copied file is not something a library
|
||||
#: write should be discovering.
|
||||
destination: Path
|
||||
cues: TrackCues | None = None
|
||||
|
||||
@property
|
||||
def source_id(self) -> str:
|
||||
"""Its id in the SOURCE library, for joining playlists to tracks."""
|
||||
return self.track.id
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExportPlaylist:
|
||||
"""A playlist to recreate in the exported library.
|
||||
|
||||
`folders` is the path of folder names to nest it under, outermost first, so
|
||||
a target that supports folders can preserve the user's tree and one that
|
||||
cannot may flatten the same information into a name.
|
||||
"""
|
||||
|
||||
name: str
|
||||
track_ids: list[str] = field(default_factory=list) # SOURCE ids
|
||||
folders: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExportPayload:
|
||||
"""Everything an exporter needs, and nothing platform-specific."""
|
||||
|
||||
tracks: list[ExportTrack] = field(default_factory=list)
|
||||
playlists: list[ExportPlaylist] = field(default_factory=list)
|
||||
#: The export's name, used for the folder its playlists are nested under.
|
||||
name: str = "Export"
|
||||
|
||||
|
||||
@dataclass
|
||||
class WrittenLibrary:
|
||||
"""What an exporter put on disk.
|
||||
|
||||
A list rather than one path because a library is not always one file: a
|
||||
Traktor export is a single `collection.nml`, but Rekordbox and OneLibrary
|
||||
each write a database PLUS a per-track analysis file. The runner records all
|
||||
of them in its manifest, and a re-export clears exactly that list — so an
|
||||
exporter that under-reports leaves orphans behind that the next export
|
||||
cannot clean up.
|
||||
"""
|
||||
|
||||
#: The library file itself, for the manifest and for telling the user.
|
||||
library: Path
|
||||
#: Everything else written, e.g. analysis files. Excludes `library`.
|
||||
extra: list[Path] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def all_paths(self) -> list[Path]:
|
||||
return [self.library, *self.extra]
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class LibraryExporter(Protocol):
|
||||
"""Writes one platform's library, from nothing. Stateless."""
|
||||
|
||||
platform: str
|
||||
#: What the written library file is called, e.g. "collection.nml".
|
||||
library_filename: str
|
||||
|
||||
def capabilities(self) -> Capabilities:
|
||||
"""What this target can represent — STATIC, with no library to read."""
|
||||
...
|
||||
|
||||
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
|
||||
"""Write a complete library into `destination`; report what it wrote.
|
||||
|
||||
The destination exists and already holds the copied audio. Raises rather
|
||||
than writing something partial: a library file is the last thing an
|
||||
export produces, so its absence is what marks an export unfinished.
|
||||
|
||||
Everything written must be reported, not just the library — the runner's
|
||||
manifest is what lets a re-export clear its own output and nothing else.
|
||||
"""
|
||||
...
|
||||
|
||||
|
||||
_EXPORTERS: list[LibraryExporter] = []
|
||||
|
||||
|
||||
def register(exporter: LibraryExporter) -> None:
|
||||
"""Register a target. Called once per adapter package, at import."""
|
||||
if not any(e.platform == exporter.platform for e in _EXPORTERS):
|
||||
_EXPORTERS.append(exporter)
|
||||
|
||||
|
||||
def exporters() -> list[LibraryExporter]:
|
||||
return list(_EXPORTERS)
|
||||
|
||||
|
||||
def for_platform(platform: str) -> LibraryExporter | None:
|
||||
"""The exporter for a platform, or None when it cannot be a target.
|
||||
|
||||
Deliberately narrower than `registry.driver_for`: reading a library and
|
||||
creating one from nothing are different capabilities, and a platform can
|
||||
have the first without the second.
|
||||
"""
|
||||
return next((e for e in _EXPORTERS if e.platform == platform), None)
|
||||
|
||||
|
||||
def targets() -> set[str]:
|
||||
return {e.platform for e in _EXPORTERS}
|
||||
@@ -0,0 +1,200 @@
|
||||
"""A folder of loose audio files, read as if it were a (read-only) library.
|
||||
|
||||
The sidebar's Files trees browse any drive, and selecting a folder shows the
|
||||
audio in it in the ordinary track table and deck. Projecting the folder into the
|
||||
generic `Track` model is what makes that cheap: the table, the deck, the
|
||||
read-only gating and the importer all already speak it, so none of them needs to
|
||||
learn what a folder is.
|
||||
|
||||
Deliberately NOT a registered driver. `can_open()` on "any directory" would make
|
||||
every folder a library to the picker, and the collection picker offering
|
||||
`~/Downloads` as a library is exactly the confusion the registry exists to avoid.
|
||||
This is opened by the folder routes and nothing else.
|
||||
|
||||
Three rules:
|
||||
|
||||
* **This folder only.** Subfolders are not scanned — the tree is how you get to
|
||||
them — so a click on a drive root never walks the whole drive.
|
||||
* **A track id is the file's absolute path.** It is the one identity a loose
|
||||
file has, and it is what the audio route checks a request against.
|
||||
* **Tags are read once per folder state.** Reading tags opens every file, which
|
||||
on a slow stick is the whole cost; the result is cached until the folder's
|
||||
own mtime changes (a file added, removed or renamed).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from .capabilities import Capabilities, SaveCapabilities, TrackCapabilities
|
||||
from .model import PlaylistNode, Track, TrackCues
|
||||
from .places import is_hidden
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _first(tags, key: str) -> str | None:
|
||||
try:
|
||||
values = tags.get(key)
|
||||
except (KeyError, ValueError):
|
||||
return None
|
||||
if not values:
|
||||
return None
|
||||
value = str(values[0]).strip()
|
||||
return value or None
|
||||
|
||||
|
||||
def _bpm(tags) -> float | None:
|
||||
raw = _first(tags, "bpm")
|
||||
if raw is None:
|
||||
return None
|
||||
try:
|
||||
bpm = float(raw)
|
||||
except ValueError:
|
||||
return None
|
||||
return bpm if 20 <= bpm <= 400 else None
|
||||
|
||||
|
||||
def read_track(path: Path) -> Track:
|
||||
"""Project one audio file. Never raises: an unreadable tag is an untitled track."""
|
||||
track = Track(id=str(path), title=path.stem, filepath=str(path))
|
||||
try:
|
||||
import mutagen
|
||||
|
||||
audio = mutagen.File(path, easy=True)
|
||||
except Exception: # noqa: BLE001 — a corrupt file must not hide the folder
|
||||
log.debug("could not read tags from %s", path, exc_info=True)
|
||||
return track
|
||||
if audio is None:
|
||||
return track
|
||||
tags = audio.tags or {}
|
||||
track.title = _first(tags, "title") or path.stem
|
||||
track.artist = _first(tags, "artist")
|
||||
track.album = _first(tags, "album")
|
||||
track.genre = _first(tags, "genre")
|
||||
track.label = _first(tags, "organization")
|
||||
track.bpm = _bpm(tags)
|
||||
info = getattr(audio, "info", None)
|
||||
if info is not None:
|
||||
length = getattr(info, "length", None)
|
||||
track.length = int(round(length)) if length else None
|
||||
bitrate = getattr(info, "bitrate", None)
|
||||
track.bitrate = int(bitrate) if bitrate else None
|
||||
# Key is left out on purpose: tagged keys arrive in every notation there is
|
||||
# ("Am", "8A", "1m", "A minor"), and passing one through to a library would
|
||||
# write a string its own analysis never would.
|
||||
return track
|
||||
|
||||
|
||||
def audio_files(folder: Path, formats: list[str]) -> list[Path]:
|
||||
"""The visible audio files directly inside `folder`, sorted by name."""
|
||||
wanted = {f.lower() for f in formats}
|
||||
out: list[Path] = []
|
||||
try:
|
||||
with os.scandir(folder) as it:
|
||||
for entry in it:
|
||||
try:
|
||||
if not entry.is_file() or is_hidden(entry):
|
||||
continue
|
||||
except OSError:
|
||||
continue
|
||||
if Path(entry.name).suffix.lower() in wanted:
|
||||
out.append(Path(entry.path))
|
||||
except OSError:
|
||||
return []
|
||||
return sorted(out, key=lambda p: p.name.lower())
|
||||
|
||||
|
||||
def capabilities_for(folder: Path) -> Capabilities:
|
||||
return Capabilities(
|
||||
platform="folder",
|
||||
writable=False,
|
||||
readonly_cause="not_in_library",
|
||||
tracks=TrackCapabilities(editable_fields=[], artwork=False),
|
||||
save=SaveCapabilities(
|
||||
app_name="Files",
|
||||
library_label=folder.name or str(folder),
|
||||
overwrite_risk="none",
|
||||
history=False,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class FolderSource:
|
||||
"""The read half of the adapter protocol, over one folder's audio files.
|
||||
|
||||
Only what the table, the deck and the importer ask a source for. There are
|
||||
no commands at all: nothing here can be written, so nothing here pretends
|
||||
it could.
|
||||
"""
|
||||
|
||||
def __init__(self, folder: Path, tracks: list[Track]):
|
||||
self.path = folder
|
||||
self._tracks = tracks
|
||||
self._by_id = {t.id: t for t in tracks}
|
||||
|
||||
@property
|
||||
def tracks(self) -> list[Track]:
|
||||
return self._tracks
|
||||
|
||||
def track(self, track_id: str) -> Track | None:
|
||||
return self._by_id.get(track_id)
|
||||
|
||||
def track_cues(self, track_id: str) -> TrackCues | None:
|
||||
return TrackCues(cues=[], grid_markers=[]) if track_id in self._by_id else None
|
||||
|
||||
def audio_path(self, track_id: str) -> Path | None:
|
||||
return Path(track_id) if track_id in self._by_id else None
|
||||
|
||||
def playlist_tree(self) -> list[PlaylistNode]:
|
||||
return []
|
||||
|
||||
def playlist_tracks(self, node_id: str) -> list[Track] | None:
|
||||
return None
|
||||
|
||||
def capabilities(self) -> Capabilities:
|
||||
return capabilities_for(self.path)
|
||||
|
||||
|
||||
class FolderScanner:
|
||||
"""Scans folders on request, caching each until its contents change.
|
||||
|
||||
Also the gatekeeper for streaming: `source_for_file` answers only for a file
|
||||
found by a scan, so the audio route cannot be used to read an arbitrary path
|
||||
off the disk — only audio the user has browsed to.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._lock = threading.Lock()
|
||||
self._cache: dict[str, tuple[float, tuple[str, ...], FolderSource]] = {}
|
||||
|
||||
def scan(self, folder: Path, formats: list[str]) -> FolderSource:
|
||||
folder = Path(folder)
|
||||
try:
|
||||
mtime = folder.stat().st_mtime
|
||||
except OSError:
|
||||
mtime = -1.0
|
||||
key = str(folder)
|
||||
fmts = tuple(sorted(f.lower() for f in formats))
|
||||
with self._lock:
|
||||
hit = self._cache.get(key)
|
||||
if hit is not None and hit[0] == mtime and hit[1] == fmts:
|
||||
return hit[2]
|
||||
source = FolderSource(folder, [read_track(p) for p in audio_files(folder, formats)])
|
||||
with self._lock:
|
||||
self._cache[key] = (mtime, fmts, source)
|
||||
return source
|
||||
|
||||
def source_for_file(self, track_id: str) -> FolderSource | None:
|
||||
folder = str(Path(track_id).parent)
|
||||
with self._lock:
|
||||
hit = self._cache.get(folder)
|
||||
if hit is None or hit[2].track(track_id) is None:
|
||||
return None
|
||||
return hit[2]
|
||||
|
||||
def clear(self) -> None:
|
||||
with self._lock:
|
||||
self._cache.clear()
|
||||
@@ -0,0 +1,387 @@
|
||||
"""Beatgrid detection: one constant tempo + anchor, fitted to the whole track.
|
||||
|
||||
Why not a beat tracker. The previous detector was ``librosa.beat.beat_track``,
|
||||
and it could not be right: its tempo comes from an autocorrelation over
|
||||
~23 ms frames, so it can only return ``60 / (k * 23 ms)`` — between 115 and
|
||||
140 BPM the ONLY values it can produce are 117.45, 123.05, 129.20 and 136.00.
|
||||
A 125 BPM track came back as 123.05 and drifted ~2 beats per minute, and its
|
||||
first beat carried the onset curve's own ~23 ms lag. Against 29 grids
|
||||
Rekordbox analysed (``bench_grid_detect.py``) it got 1 BPM and 0 grids right.
|
||||
|
||||
Dance music makes a much stronger assumption available, the one Traktor's and
|
||||
Rekordbox's analysers make: the tempo is CONSTANT. So instead of tracking
|
||||
beats, this fits one pulse train to every onset in the track:
|
||||
|
||||
1. **Onset curves at 1 kHz from zero-phase band filters** (``sosfiltfilt``
|
||||
adds no group delay): a kick band, a mid band and the full signal.
|
||||
2. **Tempo from the whole track's spectrum.** A pulse train at ``f`` Hz has
|
||||
energy at ``f, 2f, 3f …``; the onset spectrum's magnitude summed over those
|
||||
harmonics peaks at the tempo, as finely as ``1 / track length`` allows,
|
||||
then parabolic refinement goes further.
|
||||
3. **Octave by comb score**: a comb at half the tempo hits every kick too, so
|
||||
the FASTEST candidate scoring nearly as well as the best wins, inside
|
||||
``bpm_range``. Halftime genres stay genuinely ambiguous — ×2 / ÷2 exist.
|
||||
4. **Phase from attacks that are followed by low end.** Timing comes from a
|
||||
1–8 kHz attack band, whose onset is sharp (a kick's low end swells for ~25 ms after
|
||||
its attack, so the kick band alone lands late). Which attack is the beat is
|
||||
decided by whether low end follows it: that rejects the off-beat hat (no low
|
||||
end) and the syncopated bassline (no attack), each of which won a benchmark
|
||||
track when judged by one band alone.
|
||||
5. **Round BPMs are snapped** only if the round tempo keeps every section of
|
||||
the track on the beat — a direct test, rather than a score ratio.
|
||||
|
||||
Positions are in the DECODED audio's time base — the one Konduktor's deck
|
||||
plays (libsndfile and macOS CoreAudio agree to the sample on MP3). A platform
|
||||
may disagree for lossy files: Rekordbox's grids sit a constant ~25 ms later on
|
||||
every MP3/AAC in the benchmark (the decoder delay it does not trim) and at 0 on
|
||||
WAV. That is a platform time-base difference, not a detection error, and it is
|
||||
deliberately not corrected here.
|
||||
|
||||
``drift_ms`` reports how far the fitted grid strays from the beat in its
|
||||
worst section — the number that says a slowly wandering tempo is not being
|
||||
described by one marker. A sudden tempo change is out of its reach (that is
|
||||
flexible-grid detection, not built).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
|
||||
_SR = 22050 # plenty for a kick; halves decode + filter cost vs 44.1k
|
||||
_FR = 1000 # onset-curve frame rate (Hz) — 1 ms timing resolution
|
||||
_TEMPO_FR = 250 # the tempo spectrum only needs content up to ~15 Hz
|
||||
_HARMONICS = 8 # pulse-train harmonics summed for the tempo score
|
||||
|
||||
# The band an attack's timing is read from. A kick's beater click reaches well
|
||||
# above 1 kHz; a bass note's leakage does not, which is what stops a
|
||||
# syncopated bassline (whose low end is as loud as the kick's) from posing as
|
||||
# one. The hat lives here too, but has no low end to follow it.
|
||||
_ATTACK_LO_HZ = 1000.0
|
||||
_ATTACK_HI_HZ = 8000.0
|
||||
# How long after an attack a kick's low end is looked for (ms).
|
||||
_KICK_FOLLOW_MS = 45
|
||||
# Measured, not derived: on WAV loops that start exactly on the beat, the
|
||||
# mid-band onset peak lands this far before the true attack (the centred
|
||||
# smoothing's leading edge). Added back so the grid sits ON the transient.
|
||||
_ONSET_BIAS_S = 0.002
|
||||
|
||||
# The detected range. Anything outside is folded in by octaves, which is where
|
||||
# half/double-tempo answers come from — and what ×2 / ÷2 are for.
|
||||
DEFAULT_BPM_RANGE = (70.0, 180.0)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class GridResult:
|
||||
bpm: float
|
||||
anchor: float # seconds: the first beat at or after the music starts
|
||||
duration: float # seconds
|
||||
# Worst distance between the grid and the beat over any ~30 s section with
|
||||
# a clear beat. A few ms on a produced track; tens of ms means the tempo
|
||||
# wanders (a live drummer, a vinyl rip). A sudden tempo CHANGE is not seen.
|
||||
drift_ms: float | None = None
|
||||
|
||||
|
||||
# ---- onset curves -------------------------------------------------------------
|
||||
def _band_env(
|
||||
y: np.ndarray, sr: int, lo: float | None, hi: float | None, smooth_ms: int = 11
|
||||
) -> np.ndarray:
|
||||
"""Log-energy envelope of one band at ``_FR`` Hz, zero-phase throughout."""
|
||||
from scipy.signal import butter, sosfiltfilt
|
||||
|
||||
if lo and hi:
|
||||
sos = butter(4, [lo, hi], btype="bandpass", fs=sr, output="sos")
|
||||
elif hi:
|
||||
sos = butter(4, hi, btype="lowpass", fs=sr, output="sos")
|
||||
elif lo:
|
||||
sos = butter(4, lo, btype="highpass", fs=sr, output="sos")
|
||||
else:
|
||||
sos = None
|
||||
x = sosfiltfilt(sos, y) if sos is not None else y
|
||||
hop = sr / _FR
|
||||
n = int(len(x) / hop)
|
||||
# Block energy on a fractional hop, so frame i is centred on time i / _FR.
|
||||
edges = np.round(np.arange(n + 1) * hop).astype(np.int64)
|
||||
c = np.concatenate(([0.0], np.cumsum(x.astype(np.float64) ** 2)))
|
||||
e = (c[edges[1:]] - c[edges[:-1]]) / np.maximum(1, np.diff(edges))
|
||||
# A centred smooth removes a band's carrier ripple (a 50 Hz kick needs
|
||||
# ~10 ms) without moving anything in time.
|
||||
if smooth_ms > 1:
|
||||
e = np.convolve(e, np.ones(smooth_ms) / smooth_ms, mode="same")
|
||||
return np.log1p(e / (np.percentile(e, 90) + 1e-12) * 100.0)
|
||||
|
||||
|
||||
def _onset(env: np.ndarray) -> np.ndarray:
|
||||
"""Positive slope of a log envelope, centred so a peak sits ON the attack."""
|
||||
d = np.zeros_like(env)
|
||||
d[1:-1] = (env[2:] - env[:-2]) / 2
|
||||
d = np.maximum(d, 0.0)
|
||||
# Remove a slowly varying floor so long crescendos don't read as onsets.
|
||||
from scipy.ndimage import uniform_filter1d
|
||||
d = np.maximum(d - uniform_filter1d(d, size=_FR // 4), 0.0)
|
||||
return d / (d.max() + 1e-12)
|
||||
|
||||
|
||||
# ---- tempo --------------------------------------------------------------------
|
||||
def _decimate(o: np.ndarray, factor: int) -> np.ndarray:
|
||||
n = len(o) // factor
|
||||
return o[: n * factor].reshape(n, factor).sum(axis=1)
|
||||
|
||||
|
||||
def _dft(o: np.ndarray, fr: float, freqs: np.ndarray) -> np.ndarray:
|
||||
"""|DFT| of ``o`` at arbitrary frequencies (Hz), chunked to bound memory."""
|
||||
t = np.arange(len(o)) / fr
|
||||
out = np.empty(len(freqs))
|
||||
step = max(1, 4_000_000 // max(1, len(o)))
|
||||
for i in range(0, len(freqs), step):
|
||||
f = freqs[i : i + step, None]
|
||||
out[i : i + step] = np.abs(np.exp(-2j * np.pi * f * t) @ o)
|
||||
return out
|
||||
|
||||
|
||||
def _harmonic_score(o: np.ndarray, fr: float, bpms: np.ndarray, n_harm: int = _HARMONICS) -> np.ndarray:
|
||||
f0 = bpms / 60.0
|
||||
return sum(_dft(o, fr, f0 * k) for k in range(1, n_harm + 1))
|
||||
|
||||
|
||||
def _coarse_candidates(o_t: np.ndarray, lo: float, hi: float) -> list[float]:
|
||||
"""Local maxima of the harmonic tempo score over [lo/2, hi*2] BPM."""
|
||||
n = 1 << int(np.ceil(np.log2(len(o_t) * 8)))
|
||||
spec = np.abs(np.fft.rfft(o_t - o_t.mean(), n))
|
||||
df = _TEMPO_FR / n
|
||||
bpms = np.arange(lo / 2, hi * 2, 0.05)
|
||||
score = np.zeros_like(bpms)
|
||||
for k in range(1, _HARMONICS + 1):
|
||||
idx = np.round(bpms / 60.0 * k / df).astype(np.int64)
|
||||
idx = idx[idx < len(spec)]
|
||||
score[: len(idx)] += spec[idx]
|
||||
from scipy.signal import find_peaks
|
||||
peaks, _ = find_peaks(score, distance=int(1.0 / 0.05))
|
||||
peaks = peaks[np.argsort(score[peaks])[::-1][:8]]
|
||||
return [float(bpms[p]) for p in peaks]
|
||||
|
||||
|
||||
def _refine(o_t: np.ndarray, bpm: float, width: float, step: float) -> tuple[float, float]:
|
||||
grid = np.arange(bpm - width, bpm + width + step / 2, step)
|
||||
s = _harmonic_score(o_t, _TEMPO_FR, grid)
|
||||
i = int(np.argmax(s))
|
||||
# Parabolic interpolation between the three samples around the max.
|
||||
if 0 < i < len(s) - 1:
|
||||
a, b, c = s[i - 1], s[i], s[i + 1]
|
||||
den = a - 2 * b + c
|
||||
off = 0.5 * (a - c) / den if den != 0 else 0.0
|
||||
return float(grid[i] + off * step), float(b)
|
||||
return float(grid[i]), float(s[i])
|
||||
|
||||
|
||||
def _fold(o: np.ndarray, period_s: float, smooth_ms: int = 11, start: int = 0) -> np.ndarray:
|
||||
"""Onset curve folded onto one period: mean strength at each phase (1 ms bins).
|
||||
|
||||
``start`` is the frame ``o`` begins at, so a slice of the track folds onto
|
||||
the same phase axis as the whole of it.
|
||||
"""
|
||||
bins = max(8, int(round(period_s * _FR)))
|
||||
t = (np.arange(len(o)) + start) / _FR
|
||||
ph = ((t / period_s) % 1.0 * bins).astype(np.int64) % bins
|
||||
h = np.bincount(ph, weights=o, minlength=bins)
|
||||
cnt = np.bincount(ph, minlength=bins)
|
||||
h = h / np.maximum(cnt, 1)
|
||||
# Circular triangle smoothing, centred, so one jittery frame cannot win.
|
||||
w = np.bartlett(smooth_ms + 2)[1:-1]
|
||||
w /= w.sum()
|
||||
kern = np.roll(np.pad(w, (0, bins - len(w))), -(len(w) // 2))
|
||||
return np.real(np.fft.ifft(np.fft.fft(h) * np.fft.fft(kern)))
|
||||
|
||||
|
||||
def _comb(o: np.ndarray, bpm: float) -> float:
|
||||
"""Peak of the folded onset curve: the mean onset strength ON the beat."""
|
||||
return float(_fold(o, 60.0 / bpm).max())
|
||||
|
||||
|
||||
def _in_range(bpm: float, lo: float, hi: float) -> float:
|
||||
while bpm < lo:
|
||||
bpm *= 2
|
||||
while bpm >= hi:
|
||||
bpm /= 2
|
||||
return bpm
|
||||
|
||||
|
||||
# ---- entry point --------------------------------------------------------------
|
||||
def detect_grid(
|
||||
audio_path: str,
|
||||
bpm_range: tuple[float, float] = DEFAULT_BPM_RANGE,
|
||||
*,
|
||||
y: np.ndarray | None = None,
|
||||
sr: int = _SR,
|
||||
) -> GridResult:
|
||||
"""Detect a track's constant tempo and first beat.
|
||||
|
||||
``y``/``sr`` let a caller (or a test) pass decoded mono audio directly.
|
||||
Raises ``ValueError`` when there is no pulse to fit (silence, a one-shot).
|
||||
"""
|
||||
if y is None:
|
||||
import librosa
|
||||
y, sr = librosa.load(audio_path, sr=sr, mono=True)
|
||||
y = np.asarray(y, dtype=np.float32)
|
||||
duration = len(y) / sr
|
||||
if duration < 1.5:
|
||||
raise ValueError("Track is too short to detect a tempo")
|
||||
|
||||
lo, hi = bpm_range
|
||||
low = _onset(_band_env(y, sr, 30.0, 150.0))
|
||||
mid = _onset(_band_env(y, sr, 150.0, 4000.0, smooth_ms=3))
|
||||
attack = _onset(_band_env(y, sr, _ATTACK_LO_HZ, _ATTACK_HI_HZ, smooth_ms=3))
|
||||
full = _onset(_band_env(y, sr, None, None, smooth_ms=3))
|
||||
o_tempo = low + mid + 0.5 * full
|
||||
if not np.isfinite(o_tempo).all() or o_tempo.max() <= 0:
|
||||
raise ValueError("No onsets found")
|
||||
|
||||
o_t = _decimate(o_tempo, _FR // _TEMPO_FR)
|
||||
cands = _coarse_candidates(o_t, lo, hi)
|
||||
if not cands:
|
||||
raise ValueError("Could not detect a tempo")
|
||||
|
||||
# Refine every coarse candidate, fold each into the range, and score it
|
||||
# with the comb (onset strength on the beat, best phase).
|
||||
refined: dict[float, tuple[float, float]] = {}
|
||||
for c in cands:
|
||||
b, _ = _refine(o_t, c, 0.1, 0.01)
|
||||
b = _in_range(b, lo, hi)
|
||||
key = round(b, 1)
|
||||
if key not in refined:
|
||||
refined[key] = (b, _comb(o_tempo, b))
|
||||
best = max(s for _, s in refined.values())
|
||||
# Octave rule: prefer the FASTEST tempo that explains the onsets nearly as
|
||||
# well as the best — a slower comb hits a subset of the same beats.
|
||||
viable = [(b, s) for b, s in refined.values() if s >= 0.9 * best]
|
||||
bpm = max(viable)[0]
|
||||
|
||||
# Final refinement at full precision around the chosen tempo.
|
||||
bpm, _ = _refine(o_t, bpm, 0.02, 0.001)
|
||||
phase = _phase(low, attack, 60.0 / bpm)
|
||||
drift = _drift(attack, bpm, phase)
|
||||
bpm, phase, drift = _snap_round(low, attack, bpm, phase, drift, duration)
|
||||
|
||||
period = 60.0 / bpm
|
||||
return GridResult(
|
||||
bpm=round(bpm, 4),
|
||||
anchor=round(_first_beat(low + attack, phase, period), 4),
|
||||
duration=duration,
|
||||
drift_ms=round(drift * 1000.0, 1),
|
||||
)
|
||||
|
||||
|
||||
def _peaks(f: np.ndarray, k: int, min_sep: int) -> list[int]:
|
||||
"""The ``k`` highest local maxima of a circular curve, ``min_sep`` apart."""
|
||||
n = len(f)
|
||||
is_max = (f >= np.roll(f, 1)) & (f >= np.roll(f, -1))
|
||||
out: list[int] = []
|
||||
for i in np.flatnonzero(is_max)[np.argsort(f[is_max])[::-1]]:
|
||||
if all(min(abs(i - j), n - abs(i - j)) >= min_sep for j in out):
|
||||
out.append(int(i))
|
||||
if len(out) == k:
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
def _phase(low: np.ndarray, attack: np.ndarray, period: float) -> float:
|
||||
"""Seconds into the beat period at which the beat lands.
|
||||
|
||||
Timing comes from the attack band, whose onset is sharp; the kick band's
|
||||
is not — a kick's low end swells for tens of ms after its attack. But the
|
||||
loudest attack is not always the beat (an off-beat hat), and the loudest
|
||||
low-band onset is not always the kick (a bassline note between beats). So
|
||||
each sharp attack is scored by whether LOW END FOLLOWS it: a kick has both,
|
||||
a hat has no low end, a bass note has no attack.
|
||||
"""
|
||||
fine = _fold(attack, period, smooth_ms=3)
|
||||
low_f = _fold(low, period)
|
||||
n = len(fine)
|
||||
floor = 0.1 * low_f.max() # a track with no kick still picks its best attack
|
||||
|
||||
def score(c: int) -> float:
|
||||
follow = max(low_f[(c + d) % n] for d in range(-5, _KICK_FOLLOW_MS + 1))
|
||||
return float(fine[c] * (floor + follow))
|
||||
|
||||
best = max(_peaks(fine, 6, 20), key=score)
|
||||
return (best / n * period + _ONSET_BIAS_S) % period
|
||||
|
||||
|
||||
def _segment_offsets(attack: np.ndarray, period: float, phase: float) -> list[float]:
|
||||
"""Where the beat lands in each ~30 s section, relative to ``phase`` (s).
|
||||
|
||||
Only sections with a clear attack within 40 ms of the grid count. That
|
||||
makes this a measure of SLOW drift — a fit a few hundredths of a BPM out,
|
||||
which is what the round-BPM snap must judge. It cannot see a tempo change
|
||||
(a section whose beat is far off the grid looks the same as a kickless
|
||||
breakdown with hats over it, and on real music treating those as drift
|
||||
reported 100–250 ms on tracks whose grid was right end to end). Detecting
|
||||
tempo changes is flexible-grid detection, and a different job.
|
||||
"""
|
||||
n = len(attack)
|
||||
seg = min(30 * _FR, n // 4)
|
||||
if seg < 6 * _FR:
|
||||
return []
|
||||
out = []
|
||||
for s0 in range(0, n - seg + 1, seg):
|
||||
f = _fold(attack[s0 : s0 + seg], period, smooth_ms=3, start=s0)
|
||||
bins = len(f)
|
||||
c = int(round(phase / period * bins)) % bins
|
||||
i = max(((c + d) % bins for d in range(-40, 41)), key=lambda j: f[j])
|
||||
if f[i] < 2.0 * np.median(f):
|
||||
continue
|
||||
d = (i - c + bins / 2) % bins - bins / 2
|
||||
out.append(d / bins * period)
|
||||
return out
|
||||
|
||||
|
||||
def _drift(attack: np.ndarray, bpm: float, phase: float) -> float:
|
||||
"""Distance (s) between the grid and the beat in the worst section but one.
|
||||
|
||||
One section is allowed to disagree: an intro whose nearest attack is not
|
||||
the kick shows up as a single ~30 ms outlier on otherwise flat tracks, and
|
||||
blocked two round-BPM snaps on the benchmark. Real drift cannot hide behind
|
||||
that — it grows with distance from the anchor, so it is at both ends.
|
||||
"""
|
||||
offs = sorted((abs(o) for o in _segment_offsets(attack, 60.0 / bpm, phase)), reverse=True)
|
||||
if len(offs) >= 4:
|
||||
offs = offs[1:]
|
||||
return offs[0] if offs else 0.0
|
||||
|
||||
|
||||
def _snap_round(low, attack, bpm: float, phase: float, drift: float, duration: float):
|
||||
"""Snap to a round (or half) BPM if it keeps the whole track on the beat.
|
||||
|
||||
The test is the thing that matters, not a score ratio: at the round tempo,
|
||||
does every section of the track stay within a few ms of its onsets? A real
|
||||
124.01 BPM track snapped to 124 would drift ~30 ms over six minutes and
|
||||
fails; a 124.0 track whose fit came out at 124.012 passes.
|
||||
|
||||
How far to look scales with 1/duration, because so does the fit's
|
||||
precision: the window is the tempo error that would move the LAST beat by
|
||||
10 ms, floored at 0.05 BPM. A four-bar loop gets a wide one; a track that
|
||||
is long enough to have a precise fit relies on the drift test instead.
|
||||
"""
|
||||
tol = max(0.05, 0.01 * bpm / max(duration, 1.0))
|
||||
for r in (float(round(bpm)), round(bpm * 2) / 2):
|
||||
if abs(bpm - r) < tol:
|
||||
ph = _phase(low, attack, 60.0 / r)
|
||||
dr = _drift(attack, r, ph)
|
||||
if dr <= max(drift, 0.004) + 0.003:
|
||||
return r, ph, dr
|
||||
return bpm, phase, drift
|
||||
|
||||
|
||||
def _first_beat(o: np.ndarray, phase: float, period: float) -> float:
|
||||
"""The first grid beat at which the music has started.
|
||||
|
||||
A grid anchored in the silence before a track is still correct, but a DJ
|
||||
reads the first marker as "the track starts here", as Traktor draws it.
|
||||
"""
|
||||
pos = o[o > 0]
|
||||
thr = 0.15 * np.percentile(pos, 99) if len(pos) else 0.0
|
||||
hits = np.flatnonzero(o > thr)
|
||||
start = hits[0] / _FR if len(hits) else 0.0
|
||||
# The beat nearest the music's first onset, never before the track starts.
|
||||
n = round((start - phase) / period)
|
||||
return max(phase + n * period, phase % period)
|
||||
@@ -0,0 +1,236 @@
|
||||
"""The generic model — Konduktor's platform-independent read projection.
|
||||
|
||||
Every adapter projects its native library into these types, and the HTTP layer
|
||||
serves them directly. Nothing here may reference a platform's own encodings: a
|
||||
value that only makes sense for one format belongs in that adapter, not here.
|
||||
|
||||
`AutoHotcue` is the one command-input type that lives alongside them, because it
|
||||
is the shape a batch cue placement takes in generic terms.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from .capabilities import CueRole, CueType, MediaKind, PlaylistKind
|
||||
|
||||
|
||||
class HotcueChip(BaseModel):
|
||||
"""One occupied hotcue slot, as the library table previews it.
|
||||
|
||||
Deliberately far smaller than a `CuePoint`: it rides on every `Track` in the
|
||||
whole-library fetch, and a row only needs enough to draw a coloured dot.
|
||||
"""
|
||||
|
||||
slot: int
|
||||
type: CueType = "cue"
|
||||
color: str | None = None # "#RRGGBB" as the platform stored it
|
||||
|
||||
|
||||
class Track(BaseModel):
|
||||
"""A single track in the library, as the app sees it."""
|
||||
|
||||
id: str # the adapter's stable track key; opaque above the adapter
|
||||
artist: str | None = None
|
||||
title: str | None = None
|
||||
album: str | None = None
|
||||
genre: str | None = None
|
||||
label: str | None = None
|
||||
remixer: str | None = None
|
||||
producer: str | None = None
|
||||
mix: str | None = None
|
||||
comment: str | None = None
|
||||
bpm: float | None = None
|
||||
# The platform's own display string, shown verbatim ("10m", "8A", "Am").
|
||||
key: str | None = None
|
||||
# Camelot wheel position 1-12 + mode, parsed BY THE ADAPTER — notation is
|
||||
# platform knowledge. None when the key is absent or unparseable.
|
||||
key_wheel: int | None = None
|
||||
key_mode: Literal["major", "minor"] | None = None
|
||||
rating: int = 0 # 0-5 stars (derived from RANKING/51)
|
||||
playcount: int | None = None
|
||||
length: int | None = None # seconds
|
||||
bitrate: int | None = None
|
||||
# ISO-8601 "YYYY-MM-DD", normalised by the adapter.
|
||||
import_date: str | None = None
|
||||
last_played: str | None = None
|
||||
release_date: str | None = None
|
||||
filepath: str | None = None # human-readable OS path
|
||||
cue_count: int = 0
|
||||
hotcue_count: int = 0
|
||||
# The occupied hotcue slots, ordered by slot. Where cues are parsed lazily
|
||||
# (OneLibrary) this is empty until `track_cues()` corrects it, exactly like
|
||||
# `hotcue_count` — the two must always agree.
|
||||
hotcues: list[HotcueChip] = Field(default_factory=list)
|
||||
# 0 = no beatgrid, 1 = constant tempo, >1 = a flexible (multi-tempo) grid.
|
||||
grid_marker_count: int = 0
|
||||
grid_locked: bool = False
|
||||
media_kind: MediaKind = "audio"
|
||||
|
||||
|
||||
class TrackPage(BaseModel):
|
||||
total: int # total matching the filter (before pagination)
|
||||
offset: int
|
||||
limit: int
|
||||
items: list[Track]
|
||||
|
||||
|
||||
class GenreCount(BaseModel):
|
||||
name: str
|
||||
count: int
|
||||
|
||||
|
||||
class Facets(BaseModel):
|
||||
"""Distinct values available for building filter UI."""
|
||||
|
||||
genres: list[GenreCount]
|
||||
keys: list[GenreCount]
|
||||
bpm_min: float | None
|
||||
bpm_max: float | None
|
||||
total_tracks: int
|
||||
|
||||
|
||||
class Stats(BaseModel):
|
||||
total_tracks: int
|
||||
total_playlists: int
|
||||
rated: int
|
||||
unrated: int
|
||||
missing_key: int
|
||||
missing_genre: int
|
||||
missing_bpm: int
|
||||
no_cues: int
|
||||
rating_breakdown: dict[int, int] # stars -> count
|
||||
bpm_histogram: list[dict] # [{bucket: "120-130", count: n}]
|
||||
top_genres: list[GenreCount]
|
||||
|
||||
|
||||
class PlaylistNode(BaseModel):
|
||||
"""A node in the playlist tree.
|
||||
|
||||
`id` is OPAQUE: the adapter mints it and decodes it, and the UI never
|
||||
constructs, parses or prefixes one. `kind` is for choosing an icon — every
|
||||
behavioural question is answered by the flags, so the UI never has to infer
|
||||
what a node can do from what it is called.
|
||||
"""
|
||||
|
||||
id: str
|
||||
name: str
|
||||
kind: PlaylistKind = "playlist"
|
||||
count: int = 0 # track count (for playlists)
|
||||
children: list["PlaylistNode"] = []
|
||||
|
||||
selectable: bool = False # has a static, listable entry set
|
||||
can_add_tracks: bool = False
|
||||
can_reorder: bool = False
|
||||
can_rename: bool = False
|
||||
can_delete: bool = False
|
||||
can_contain_children: bool = False # a valid parent for a new playlist
|
||||
|
||||
|
||||
PlaylistNode.model_rebuild()
|
||||
|
||||
|
||||
# ---- write request bodies ----
|
||||
|
||||
|
||||
class CuePoint(BaseModel):
|
||||
name: str | None = None
|
||||
type: CueType = "cue"
|
||||
# "memory" cues have no bank slot. Only Rekordbox has them, so they are
|
||||
# modelled and preserved but not yet editable anywhere.
|
||||
role: CueRole = "hotcue"
|
||||
start: float # seconds
|
||||
length: float # seconds (>0 for loops)
|
||||
slot: int | None = None # bank slot; None for a cue not in a bank
|
||||
color: str | None = None # "#RRGGBB" as the platform stored it
|
||||
# False when the adapter refuses commands on this cue — the UI gates on THIS
|
||||
# rather than on any platform-specific reason.
|
||||
editable: bool = True
|
||||
readonly_reason: Literal["platform_managed"] | None = None
|
||||
# Index of the grid marker this cue mirrors, where the platform pairs them.
|
||||
# A display hint only; None on platforms that do not.
|
||||
grid_marker: int | None = None
|
||||
|
||||
|
||||
class GridMarker(BaseModel):
|
||||
"""One beatgrid marker. Its position in the list IS its index/identity."""
|
||||
|
||||
start: float # seconds
|
||||
bpm: float # governs from this marker until the next one
|
||||
name: str | None = None # Traktor's label — display only, NOT a discriminator
|
||||
companion: int | None = None # hotcue slot of the paired white cue, if any
|
||||
|
||||
|
||||
class TrackCues(BaseModel):
|
||||
# THE beatgrid, ordered by start. Empty = no grid; one marker = constant
|
||||
# tempo. There is deliberately no scalar bpm/anchor here: a single "the BPM"
|
||||
# is what made flexible grids render and edit wrongly.
|
||||
grid_markers: list[GridMarker] = []
|
||||
grid_locked: bool = False
|
||||
cues: list[CuePoint] = [] # cue/loop markers (grid markers themselves excluded)
|
||||
|
||||
|
||||
class AutoHotcue(BaseModel):
|
||||
"""One cue in a batch placement (Auto Hotcues)."""
|
||||
|
||||
slot: int
|
||||
start: float # seconds
|
||||
name: str | None = None # positional label (e.g. "Drop")
|
||||
type: CueType = "cue"
|
||||
length: float = 0.0 # seconds (>0 for a loop cue)
|
||||
|
||||
|
||||
class LibraryInfo(BaseModel):
|
||||
"""Identity of the loaded library, for display and for composing copy."""
|
||||
|
||||
platform: str
|
||||
name: str # the DJ app's name, e.g. "Traktor"
|
||||
library_label: str # what the user thinks of the artefact as, e.g. "collection.nml"
|
||||
path: str
|
||||
display_name: str # short label for the status bar
|
||||
version: str | None = None
|
||||
|
||||
|
||||
class PlatformOption(BaseModel):
|
||||
"""A platform the picker can offer before any library is open.
|
||||
|
||||
Facts only, never finished sentences: `lib/platformCopy.ts` composes the
|
||||
wording. The distinction that matters is `removable` — a platform with no
|
||||
library found is "not installed" for Traktor and "nothing plugged in" for
|
||||
OneLibrary, and only the driver knows which of those is true.
|
||||
"""
|
||||
|
||||
platform: str
|
||||
name: str
|
||||
library_label: str
|
||||
selects: Literal["file", "directory"] = "file"
|
||||
installed: bool = False
|
||||
#: How many libraries this platform has right now; `installed` is `found > 0`.
|
||||
found: int = 0
|
||||
#: The library lives on a plugged-in drive, so `found` changes between calls.
|
||||
removable: bool = False
|
||||
|
||||
|
||||
class RemapSample(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
from_: str = Field(alias="from")
|
||||
to: str
|
||||
exists: bool
|
||||
|
||||
|
||||
class RemapPreview(BaseModel):
|
||||
total: int # tracks with a resolvable location
|
||||
matched: int # how many match the `from` prefix
|
||||
existing: int # of matched, how many exist at the `to` target
|
||||
samples: list[RemapSample] = []
|
||||
|
||||
|
||||
class PrefixGroup(BaseModel):
|
||||
prefix: str # common directory prefix of a group of tracks
|
||||
count: int # tracks sharing it
|
||||
|
||||
|
||||
class PrefixSuggestions(BaseModel):
|
||||
primary: str # best guess for the `from` prefix (largest group)
|
||||
groups: list[PrefixGroup] = [] # alternatives, ranked by count
|
||||
@@ -13,12 +13,9 @@ step this composes with.
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
_WIN_DRIVE = re.compile(r"^([A-Za-z]:)[\\/](.*)$")
|
||||
_MAC_VOLUME = re.compile(r"^/Volumes/([^/]+)/(.*)$")
|
||||
|
||||
|
||||
def _norm(prefix: str | None) -> str:
|
||||
@@ -84,44 +81,3 @@ def common_dir_prefix(paths: list[str]) -> str:
|
||||
else:
|
||||
break
|
||||
return "/".join(common)
|
||||
|
||||
|
||||
def _traktor_dir(posix_body: str) -> str:
|
||||
"""Convert a POSIX directory body (leading+trailing '/', e.g. '/Music/')
|
||||
to Traktor's '/:'-segmented form ('/:Music/:')."""
|
||||
return posix_body.replace("/", "/:")
|
||||
|
||||
|
||||
def os_path_to_location(os_path: Path) -> tuple[str, str, str]:
|
||||
"""Inverse of ``file_tags.resolve_path``: build a Traktor
|
||||
``(volume, dir, file)`` from an OS path, for the platform implied by the
|
||||
path's shape. Round-trips with ``resolve_path``.
|
||||
|
||||
Used by write-back only; the produced LOCATION is valid for the OS whose
|
||||
path shape it matches (Windows drive, macOS ``/Volumes`` mount, or a POSIX
|
||||
boot path -> ``Macintosh HD``).
|
||||
"""
|
||||
# Derive the filename from the string (not Path.name) so a Windows-style
|
||||
# path is handled even when this runs on a POSIX host, and vice-versa.
|
||||
s = str(os_path)
|
||||
|
||||
m = _WIN_DRIVE.match(s)
|
||||
if m:
|
||||
volume = m.group(1) # e.g. "E:"
|
||||
body = m.group(2).replace("\\", "/") # "Music/x.mp3"
|
||||
name = body.rsplit("/", 1)[-1]
|
||||
dir_body = "/" + body[: len(body) - len(name)] # "/Music/"
|
||||
return volume, _traktor_dir(dir_body), name
|
||||
|
||||
m = _MAC_VOLUME.match(s)
|
||||
if m:
|
||||
volume = m.group(1) # mounted volume name
|
||||
body = m.group(2) # "Music/x.mp3"
|
||||
name = body.rsplit("/", 1)[-1]
|
||||
dir_body = "/" + body[: len(body) - len(name)] # "/Music/"
|
||||
return volume, _traktor_dir(dir_body), name
|
||||
|
||||
# POSIX boot volume, e.g. "/Users/you/Music/x.mp3".
|
||||
name = s.rsplit("/", 1)[-1]
|
||||
dir_body = s[: len(s) - len(name)] # "/Users/you/Music/"
|
||||
return "Macintosh HD", _traktor_dir(dir_body), name
|
||||
@@ -0,0 +1,294 @@
|
||||
"""Where a person keeps things on this computer.
|
||||
|
||||
Two jobs, both of them "ask the OS rather than assume":
|
||||
|
||||
* **Mounted volumes.** Where a drive appears is per-OS and nothing else in the
|
||||
app can work it out. This lives here rather than in the OneLibrary adapter —
|
||||
which is where it grew, because that is the platform whose libraries ARE
|
||||
drives — because "where does this OS mount things" is not adapter knowledge.
|
||||
The file browser needs the same answer, and two scanners would drift.
|
||||
|
||||
* **The user's own folders.** `platformdirs` answers these, and hardcoding
|
||||
them would be wrong on every OS in a different way: `~/Videos` is `Movies`
|
||||
on macOS, Linux's are XDG user-dirs which are user-configurable AND
|
||||
localised, and Windows Known Folders are routinely **relocated by OneDrive**
|
||||
so Documents and Desktop are often not under the home directory at all.
|
||||
|
||||
A place that does not exist is never returned. A file browser offering a Music
|
||||
folder that is not there reads as breakage, whereas its absence reads as an
|
||||
accurate description of the machine.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import string
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import platformdirs
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
#: Entries an OS writes into a volume or folder BY ITSELF — on mount, on
|
||||
#: indexing, or when Finder/Explorer merely browses it. They say nothing about
|
||||
#: whether a person keeps things there, so "is this folder empty?" must not
|
||||
#: count them: a freshly formatted stick mounted once on a Mac is not empty to
|
||||
#: `iterdir()`, and treating it as occupied made its root unexportable.
|
||||
#: Compared case-insensitively — Windows' names are, and FAT/exFAT sticks are.
|
||||
OS_HOUSEKEEPING = frozenset(
|
||||
name.lower()
|
||||
for name in (
|
||||
# macOS
|
||||
".Spotlight-V100", ".fseventsd", ".Trashes", ".TemporaryItems",
|
||||
".DocumentRevisions-V100", ".DS_Store", ".apdisk",
|
||||
".com.apple.timemachine.donotpresent",
|
||||
# Windows
|
||||
"System Volume Information", "$RECYCLE.BIN", "desktop.ini", "Thumbs.db",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def is_os_housekeeping(name: str) -> bool:
|
||||
"""Whether a directory entry is the OS's bookkeeping rather than the user's.
|
||||
|
||||
`._*` are AppleDouble files: macOS writes one beside every file it touches
|
||||
on a volume that cannot hold extended attributes (FAT, exFAT).
|
||||
"""
|
||||
return name.lower() in OS_HOUSEKEEPING or name.startswith("._")
|
||||
|
||||
|
||||
def mount_points() -> list[Path]:
|
||||
"""Every mounted volume's root directory, for this OS.
|
||||
|
||||
Only the ROOTS: a drive can hold tens of thousands of files, and walking a
|
||||
slow USB stick to answer "what is plugged in" is exactly the kind of thing
|
||||
that makes an app feel broken.
|
||||
"""
|
||||
bases: list[Path] = []
|
||||
if sys.platform == "darwin":
|
||||
bases.append(Path("/Volumes"))
|
||||
elif sys.platform.startswith("linux"):
|
||||
bases.extend([Path("/media"), Path("/mnt"), Path("/run/media")])
|
||||
user = os.environ.get("USER")
|
||||
if user:
|
||||
bases.append(Path("/media") / user)
|
||||
bases.append(Path("/run/media") / user)
|
||||
|
||||
roots: list[Path] = []
|
||||
for base in bases:
|
||||
try:
|
||||
if not base.is_dir():
|
||||
continue
|
||||
roots.extend(p for p in base.iterdir() if p.is_dir())
|
||||
except OSError:
|
||||
continue
|
||||
|
||||
if sys.platform == "win32":
|
||||
# No mount-point directory to list: check the drive letters directly.
|
||||
for letter in string.ascii_uppercase:
|
||||
drive = Path(f"{letter}:\\")
|
||||
try:
|
||||
if drive.is_dir():
|
||||
roots.append(drive)
|
||||
except OSError:
|
||||
continue
|
||||
return roots
|
||||
|
||||
|
||||
def _boot_device() -> int | None:
|
||||
try:
|
||||
return Path("/").stat().st_dev
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def is_boot_volume(path: Path) -> bool:
|
||||
"""Whether `path` is the volume the OS itself booted from.
|
||||
|
||||
macOS lists the startup disk in `/Volumes` alongside real removable media,
|
||||
so a "Drives" list that does not filter it leads with a path back to where
|
||||
the user already is. Compared by DEVICE id rather than by name, because
|
||||
`Macintosh HD` is only the default name and is freely renamed.
|
||||
"""
|
||||
boot = _boot_device()
|
||||
if boot is None:
|
||||
return False
|
||||
try:
|
||||
return path.stat().st_dev == boot
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def volumes(*, include_boot: bool = False) -> list[Path]:
|
||||
"""Mounted volumes, newest-mounted order not guaranteed. Sorted by name."""
|
||||
found = [v for v in mount_points() if include_boot or not is_boot_volume(v)]
|
||||
return sorted(set(found), key=lambda p: p.name.lower())
|
||||
|
||||
|
||||
# The user's own folders, in the order a file browser should show them. Music
|
||||
# sits high because this is a DJ app: it is the likeliest destination by far.
|
||||
_USER_DIRS: tuple[tuple[str, str, str], ...] = (
|
||||
("home", "Home", ""),
|
||||
("music", "Music", "user_music_dir"),
|
||||
("desktop", "Desktop", "user_desktop_dir"),
|
||||
("documents", "Documents", "user_documents_dir"),
|
||||
("downloads", "Downloads", "user_downloads_dir"),
|
||||
)
|
||||
|
||||
|
||||
def user_places() -> list[dict]:
|
||||
"""The user's own folders that actually exist on this machine."""
|
||||
out: list[dict] = []
|
||||
seen: set[str] = set()
|
||||
for kind, name, getter in _USER_DIRS:
|
||||
try:
|
||||
path = Path.home() if not getter else Path(getattr(platformdirs, getter)())
|
||||
if not path.is_dir():
|
||||
continue
|
||||
key = str(path)
|
||||
# Windows can resolve two Known Folders to one place; listing it
|
||||
# twice under different names would just look like a bug.
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
out.append({"kind": kind, "name": name, "path": key})
|
||||
except (OSError, AttributeError):
|
||||
continue
|
||||
return out
|
||||
|
||||
|
||||
def volume_places() -> list[dict]:
|
||||
"""Mounted drives, named as the user sees them."""
|
||||
out: list[dict] = []
|
||||
for vol in volumes():
|
||||
try:
|
||||
out.append({"kind": "volume", "name": vol.name or str(vol), "path": str(vol)})
|
||||
except OSError:
|
||||
continue
|
||||
return out
|
||||
|
||||
|
||||
# ---- local vs external drives -------------------------------------------------
|
||||
#
|
||||
# Only the boot disk is identifiable everywhere. Whether ANOTHER volume is an
|
||||
# internal SSD or a USB stick needs the OS's own answer, and where that answer is
|
||||
# not available (or not trustworthy — Windows reports most USB SSDs as "fixed")
|
||||
# a volume is filed as EXTERNAL. Guessing "local" wrongly would present a stick
|
||||
# that is about to be unplugged as a permanent home for referenced tracks.
|
||||
|
||||
# Keyed by (path, st_dev): a volume's answer does not change while it is mounted,
|
||||
# and `diskutil` is a subprocess — too slow to run for every drive on every poll.
|
||||
_mac_info_cache: dict[tuple[str, int], dict] = {}
|
||||
|
||||
|
||||
def _mac_info(path: Path) -> dict:
|
||||
import plistlib
|
||||
import subprocess
|
||||
|
||||
try:
|
||||
key = (str(path), path.stat().st_dev)
|
||||
except OSError:
|
||||
return {}
|
||||
if key not in _mac_info_cache:
|
||||
try:
|
||||
out = subprocess.run(
|
||||
["diskutil", "info", "-plist", str(path)],
|
||||
capture_output=True, timeout=5, check=True,
|
||||
).stdout
|
||||
_mac_info_cache[key] = plistlib.loads(out)
|
||||
except (OSError, subprocess.SubprocessError, plistlib.InvalidFileException, ValueError):
|
||||
_mac_info_cache[key] = {}
|
||||
return _mac_info_cache[key]
|
||||
|
||||
|
||||
def is_internal(path: Path) -> bool:
|
||||
"""Whether a non-boot volume is a drive built into this computer."""
|
||||
if sys.platform != "darwin":
|
||||
return False
|
||||
info = _mac_info(path)
|
||||
return (
|
||||
bool(info.get("Internal"))
|
||||
and not info.get("Ejectable")
|
||||
and not info.get("RemovableMediaOrExternalDevice")
|
||||
and not info.get("RemovableMedia")
|
||||
)
|
||||
|
||||
|
||||
def _is_disk_image(path: Path) -> bool:
|
||||
"""A mounted .dmg (an installer, usually) — a mount, but not a drive."""
|
||||
return sys.platform == "darwin" and _mac_info(path).get("BusProtocol") == "Disk Image"
|
||||
|
||||
|
||||
def drives() -> list[dict]:
|
||||
"""Every drive, split into `local` (boot + internal) and `external`.
|
||||
|
||||
The boot disk's path is the filesystem root, not its `/Volumes` alias: on
|
||||
macOS `/Volumes/Macintosh HD` is a link back to `/`, and browsing through it
|
||||
would show every path twice over.
|
||||
"""
|
||||
out: list[dict] = []
|
||||
boot_seen = False
|
||||
for vol in sorted(set(mount_points()), key=lambda p: p.name.lower()):
|
||||
try:
|
||||
if is_boot_volume(vol):
|
||||
if boot_seen:
|
||||
continue
|
||||
boot_seen = True
|
||||
root = Path(vol.anchor) if sys.platform == "win32" else Path("/")
|
||||
out.append({"name": vol.name or str(vol), "path": str(root), "kind": "local"})
|
||||
continue
|
||||
if _is_disk_image(vol):
|
||||
continue
|
||||
kind = "local" if is_internal(vol) else "external"
|
||||
out.append({"name": vol.name or str(vol), "path": str(vol), "kind": kind})
|
||||
except OSError:
|
||||
continue
|
||||
if not boot_seen and sys.platform != "win32":
|
||||
# Linux mounts nothing for the root filesystem under /media.
|
||||
out.insert(0, {"name": "Computer", "path": "/", "kind": "local"})
|
||||
return out
|
||||
|
||||
|
||||
# ---- what a folder listing should show ----------------------------------------
|
||||
|
||||
_UF_HIDDEN = 0x8000 # macOS/BSD `chflags hidden`: /usr, /bin, /Volumes, …
|
||||
_WIN_HIDDEN = 0x2 | 0x4 # FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM
|
||||
|
||||
|
||||
def is_hidden(entry: os.DirEntry | Path) -> bool:
|
||||
"""Whether a file browser should leave this entry out.
|
||||
|
||||
macOS hides its system folders by FLAG, not by name, so a list of names to
|
||||
skip would be both incomplete and wrong on a renamed volume. The flag is what
|
||||
Finder itself reads.
|
||||
"""
|
||||
name = entry.name
|
||||
if name.startswith(".") or is_os_housekeeping(name):
|
||||
return True
|
||||
try:
|
||||
st = entry.stat(follow_symlinks=False) if isinstance(entry, os.DirEntry) else entry.lstat()
|
||||
except OSError:
|
||||
return True
|
||||
if getattr(st, "st_flags", 0) & _UF_HIDDEN:
|
||||
return True
|
||||
if getattr(st, "st_file_attributes", 0) & _WIN_HIDDEN:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def subfolders(path: Path) -> list[Path]:
|
||||
"""The visible folders directly inside `path`, sorted as Finder would."""
|
||||
out: list[Path] = []
|
||||
try:
|
||||
with os.scandir(path) as it:
|
||||
for entry in it:
|
||||
try:
|
||||
if entry.is_dir(follow_symlinks=True) and not is_hidden(entry):
|
||||
out.append(Path(entry.path))
|
||||
except OSError:
|
||||
continue
|
||||
except OSError:
|
||||
return []
|
||||
return sorted(out, key=lambda p: p.name.lower())
|
||||
@@ -0,0 +1,195 @@
|
||||
"""Query, facet and statistics layer over the generic model.
|
||||
|
||||
This is deliberately platform-independent: it reads nothing but `Track`
|
||||
attributes. Keeping it in `core` rather than per-adapter is what stops "sort by
|
||||
artist" quietly meaning different things on different platforms behind one UI —
|
||||
if a filter needs something the projection cannot express, the fix is to add the
|
||||
field to the projection, where every adapter must then answer for it.
|
||||
|
||||
An adapter owns its `TrackIndex` instance and refreshes it after each command.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
|
||||
from .model import Facets, GenreCount, Stats, Track, TrackPage
|
||||
|
||||
|
||||
class TrackIndex:
|
||||
"""An ordered list of projected tracks plus a primary-key index."""
|
||||
|
||||
def __init__(self, tracks: list[Track] | None = None):
|
||||
self._lock = threading.Lock()
|
||||
self.tracks: list[Track] = []
|
||||
self.by_key: dict[str, Track] = {}
|
||||
if tracks is not None:
|
||||
self.rebuild(tracks)
|
||||
|
||||
def rebuild(self, tracks: list[Track]) -> None:
|
||||
"""Replace the whole projection — after a save or a path remap, where
|
||||
track ids themselves may have changed."""
|
||||
with self._lock:
|
||||
self.tracks = tracks
|
||||
self.by_key = {t.id: t for t in tracks}
|
||||
|
||||
def all(self) -> list[Track]:
|
||||
return self.tracks
|
||||
|
||||
def get(self, track_id: str) -> Track | None:
|
||||
return self.by_key.get(track_id)
|
||||
|
||||
def add(self, track: Track) -> None:
|
||||
"""Put a track the projection has never seen into it.
|
||||
|
||||
`replace` deliberately ignores an unknown id — it exists to refresh, and
|
||||
silently inventing a track would hide a bug. Adding is a different
|
||||
intent and needs saying out loud, which is why importing a track needs
|
||||
this rather than being able to reuse `replace`.
|
||||
|
||||
An id that is already present is refreshed instead of duplicated:
|
||||
`by_key` could not represent two, so appending would desynchronise it
|
||||
from `tracks`.
|
||||
"""
|
||||
with self._lock:
|
||||
if track.id in self.by_key:
|
||||
self.replace(track)
|
||||
return
|
||||
self.tracks.append(track)
|
||||
self.by_key[track.id] = track
|
||||
|
||||
def replace(self, track: Track) -> None:
|
||||
"""Refresh one track's projection in place.
|
||||
|
||||
Mutating the existing object rather than replacing it keeps `tracks`,
|
||||
`by_key` and any list a caller is already holding consistent.
|
||||
"""
|
||||
old = self.by_key.get(track.id)
|
||||
if old is None:
|
||||
return
|
||||
for field in type(track).model_fields:
|
||||
setattr(old, field, getattr(track, field))
|
||||
|
||||
_SORT_KEYS = {
|
||||
"artist": lambda t: (t.artist or "").lower(),
|
||||
"title": lambda t: (t.title or "").lower(),
|
||||
"album": lambda t: (t.album or "").lower(),
|
||||
"genre": lambda t: (t.genre or "").lower(),
|
||||
"key": lambda t: (t.key or ""),
|
||||
"bpm": lambda t: (t.bpm if t.bpm is not None else -1),
|
||||
"rating": lambda t: t.rating,
|
||||
"playcount": lambda t: (t.playcount or 0),
|
||||
"import_date": lambda t: (t.import_date or ""),
|
||||
"length": lambda t: (t.length or 0),
|
||||
}
|
||||
|
||||
def query_tracks(
|
||||
self,
|
||||
q: str | None = None,
|
||||
genre: str | None = None,
|
||||
key: str | None = None,
|
||||
bpm_min: float | None = None,
|
||||
bpm_max: float | None = None,
|
||||
rating_min: int | None = None,
|
||||
has_cues: bool | None = None,
|
||||
sort: str = "artist",
|
||||
order: str = "asc",
|
||||
limit: int = 100,
|
||||
offset: int = 0,
|
||||
) -> TrackPage:
|
||||
items = self.tracks
|
||||
if q:
|
||||
ql = q.lower()
|
||||
items = [
|
||||
t
|
||||
for t in items
|
||||
if (t.artist and ql in t.artist.lower())
|
||||
or (t.title and ql in t.title.lower())
|
||||
or (t.album and ql in t.album.lower())
|
||||
]
|
||||
if genre:
|
||||
items = [t for t in items if t.genre == genre]
|
||||
if key:
|
||||
items = [t for t in items if t.key == key]
|
||||
if bpm_min is not None:
|
||||
items = [t for t in items if t.bpm is not None and t.bpm >= bpm_min]
|
||||
if bpm_max is not None:
|
||||
items = [t for t in items if t.bpm is not None and t.bpm <= bpm_max]
|
||||
if rating_min is not None:
|
||||
items = [t for t in items if t.rating >= rating_min]
|
||||
if has_cues is not None:
|
||||
items = [t for t in items if (t.cue_count > 0) == has_cues]
|
||||
|
||||
keyfn = self._SORT_KEYS.get(sort, self._SORT_KEYS["artist"])
|
||||
items = sorted(items, key=keyfn, reverse=(order == "desc"))
|
||||
|
||||
total = len(items)
|
||||
page = items[offset : offset + limit]
|
||||
return TrackPage(total=total, offset=offset, limit=limit, items=page)
|
||||
|
||||
def facets(self) -> Facets:
|
||||
genres: dict[str, int] = {}
|
||||
keys: dict[str, int] = {}
|
||||
bpms = []
|
||||
for t in self.tracks:
|
||||
if t.genre:
|
||||
genres[t.genre] = genres.get(t.genre, 0) + 1
|
||||
if t.key:
|
||||
keys[t.key] = keys.get(t.key, 0) + 1
|
||||
if t.bpm is not None:
|
||||
bpms.append(t.bpm)
|
||||
return Facets(
|
||||
genres=[
|
||||
GenreCount(name=k, count=v)
|
||||
for k, v in sorted(genres.items(), key=lambda x: -x[1])
|
||||
],
|
||||
keys=[
|
||||
GenreCount(name=k, count=v)
|
||||
for k, v in sorted(keys.items(), key=lambda x: -x[1])
|
||||
],
|
||||
bpm_min=min(bpms) if bpms else None,
|
||||
bpm_max=max(bpms) if bpms else None,
|
||||
total_tracks=len(self.tracks),
|
||||
)
|
||||
|
||||
def stats(self, playlist_count: int) -> Stats:
|
||||
rating_breakdown = {i: 0 for i in range(6)}
|
||||
genres: dict[str, int] = {}
|
||||
bpm_buckets: dict[str, int] = {}
|
||||
rated = missing_key = missing_genre = missing_bpm = no_cues = 0
|
||||
for t in self.tracks:
|
||||
rating_breakdown[t.rating] += 1
|
||||
if t.rating > 0:
|
||||
rated += 1
|
||||
if not t.key:
|
||||
missing_key += 1
|
||||
if not t.genre:
|
||||
missing_genre += 1
|
||||
else:
|
||||
genres[t.genre] = genres.get(t.genre, 0) + 1
|
||||
if t.bpm is None:
|
||||
missing_bpm += 1
|
||||
else:
|
||||
lo = int(t.bpm // 10 * 10)
|
||||
bucket = f"{lo}-{lo + 10}"
|
||||
bpm_buckets[bucket] = bpm_buckets.get(bucket, 0) + 1
|
||||
if t.cue_count == 0:
|
||||
no_cues += 1
|
||||
total = len(self.tracks)
|
||||
histogram = [
|
||||
{"bucket": b, "count": c}
|
||||
for b, c in sorted(bpm_buckets.items(), key=lambda x: int(x[0].split("-")[0]))
|
||||
]
|
||||
top = sorted(genres.items(), key=lambda x: -x[1])[:10]
|
||||
return Stats(
|
||||
total_tracks=total,
|
||||
total_playlists=playlist_count,
|
||||
rated=rated,
|
||||
unrated=total - rated,
|
||||
missing_key=missing_key,
|
||||
missing_genre=missing_genre,
|
||||
missing_bpm=missing_bpm,
|
||||
no_cues=no_cues,
|
||||
rating_breakdown=rating_breakdown,
|
||||
bpm_histogram=histogram,
|
||||
top_genres=[GenreCount(name=k, count=v) for k, v in top],
|
||||
)
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Which adapter can open a given path.
|
||||
|
||||
Selection is a ``can_open()`` probe, not an extension match. That matters as soon
|
||||
as a second platform exists: Rekordbox's library is a SQLite file called
|
||||
``master.db`` and Serato's is a ``_Serato_`` *directory*, so neither can be
|
||||
recognised by suffix alone, and a probe lets an adapter be as specific as it
|
||||
needs to be (Traktor's reads 4 KB and looks for the NML header).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from .adapter import LibraryDriver, LibraryNotSupported
|
||||
|
||||
_DRIVERS: list[LibraryDriver] = []
|
||||
|
||||
|
||||
def register(driver: LibraryDriver) -> None:
|
||||
"""Register a platform. Called once per adapter package, at import."""
|
||||
if not any(d.platform == driver.platform for d in _DRIVERS):
|
||||
_DRIVERS.append(driver)
|
||||
|
||||
|
||||
def drivers() -> list[LibraryDriver]:
|
||||
return list(_DRIVERS)
|
||||
|
||||
|
||||
def driver_by_platform(platform: str) -> LibraryDriver:
|
||||
"""The driver for a platform name, e.g. ``"traktor"``."""
|
||||
for d in _DRIVERS:
|
||||
if d.platform == platform:
|
||||
return d
|
||||
raise LibraryNotSupported(f"No adapter registered for platform {platform!r}")
|
||||
|
||||
|
||||
def driver_for(path: Path) -> LibraryDriver:
|
||||
"""The first registered driver that recognises `path`."""
|
||||
for d in _DRIVERS:
|
||||
try:
|
||||
if d.can_open(path):
|
||||
return d
|
||||
except OSError:
|
||||
continue
|
||||
raise LibraryNotSupported(f"No DJ library Konduktor recognises at {path}")
|
||||
|
||||
|
||||
def open_library(path: Path):
|
||||
return driver_for(path).open(path)
|
||||
|
||||
|
||||
def describe(path: Path) -> dict:
|
||||
"""Describe a library path using whichever adapter recognises it.
|
||||
|
||||
Used for the picker's "last opened" shortcut, which must still render when
|
||||
the file has since been moved or deleted — so an unrecognised path gets a
|
||||
plain description with ``exists`` false rather than an error.
|
||||
"""
|
||||
try:
|
||||
return driver_for(path).describe(path)
|
||||
except (LibraryNotSupported, OSError):
|
||||
pass
|
||||
try:
|
||||
exists = path.is_file()
|
||||
except OSError:
|
||||
exists = False
|
||||
return {
|
||||
"path": str(path),
|
||||
"label": path.name,
|
||||
"version": None,
|
||||
"modified": None,
|
||||
"exists": exists,
|
||||
}
|
||||
|
||||
|
||||
def detect_for(platform: str) -> list:
|
||||
"""Every library one platform has right now, best first.
|
||||
|
||||
The picker asks which platform FIRST, so detection is scoped to the answer.
|
||||
Unscoped detection (``detect_all``) concatenates drivers in registration
|
||||
order, which made "the best candidate" mean "whatever the first-registered
|
||||
driver found" — with a removable drive registered first, a plugged-in stick
|
||||
could be offered as the user's collection.
|
||||
"""
|
||||
try:
|
||||
return driver_by_platform(platform).detect()
|
||||
except (LibraryNotSupported, OSError):
|
||||
return []
|
||||
|
||||
|
||||
def detect_all() -> list:
|
||||
"""Every library found in the platforms' default install locations."""
|
||||
out: list = []
|
||||
for d in _DRIVERS:
|
||||
try:
|
||||
out.extend(d.detect())
|
||||
except OSError:
|
||||
continue
|
||||
return out
|
||||
|
||||
|
||||
def browsable_suffixes(platform: str | None = None) -> tuple[str, ...]:
|
||||
"""File extensions the in-app browser should show, for one platform or all.
|
||||
|
||||
A platform that selects a DIRECTORY contributes nothing, even though it has
|
||||
suffixes: its libraries are not the thing a user picks, so listing them
|
||||
would offer a file the browser's Open cannot act on.
|
||||
"""
|
||||
try:
|
||||
targets = [driver_by_platform(platform)] if platform else _DRIVERS
|
||||
except LibraryNotSupported:
|
||||
targets = []
|
||||
seen: list[str] = []
|
||||
for d in targets:
|
||||
if getattr(d, "selects", "file") != "file":
|
||||
continue
|
||||
for suffix in d.suffixes:
|
||||
if suffix not in seen:
|
||||
seen.append(suffix)
|
||||
return tuple(seen)
|
||||
@@ -0,0 +1,302 @@
|
||||
"""Track structure on a KNOWN beatgrid: sections, and the events a DJ cues.
|
||||
|
||||
This is what Auto Hotcues resolves its slots against ("first drop", "start of
|
||||
the second breakdown", …). It replaced a librosa Laplacian segmentation that
|
||||
ran its own beat tracker and ignored the track's grid; against Rekordbox's
|
||||
phrase analysis its cues scored WORSE than placing one every 16 bars.
|
||||
|
||||
Why it is built the way it is — each choice was measured against the phrase
|
||||
analysis Rekordbox stores for 20 local tracks (PSSI; see the Auto Hotcues
|
||||
section of CLAUDE.md for the numbers):
|
||||
|
||||
- **Everything is per BAR, on the track's own grid.** Bar 1 is the grid's first
|
||||
marker (Traktor's convention: a marker is beat 1). Detecting the bar start
|
||||
from audio was tried and never beat that rule — DJ tracks start on a
|
||||
downbeat — so a wrong bar 1 is fixed by moving the marker, not second-guessed.
|
||||
- **The features are the ones a DJ hears**: is the kick in, is the bass in,
|
||||
how loud and bright is it — plus timbre (MFCC), for changes that keep the
|
||||
level (a lead swapping out). Timbre-only novelty scored below this: the
|
||||
sections that get cued are defined by energy, not by chord changes.
|
||||
- **Sections are an optimal segmentation, and the boundary price depends on
|
||||
where it falls**: cheap on a multiple of 8 bars, dearer on 4, very dear
|
||||
anywhere else. That is the phrase bias, built into the objective rather than
|
||||
applied as a snap afterwards — a snap can only move a boundary, never decide
|
||||
that an off-phrase change was not worth a boundary at all.
|
||||
- **A drop is a high section that follows a low one** — not merely a loud one.
|
||||
A house intro is often as loud as its drop (the full groove, for mixing), and
|
||||
what makes the drop is the breakdown before it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
import numpy as np
|
||||
|
||||
_SR = 22050
|
||||
_FR = 100 # envelope frame rate for per-bar levels (Hz)
|
||||
|
||||
# Boundary cost multipliers by bar position (x the variance of ~4 bars).
|
||||
_LAMBDA_8 = 0.2
|
||||
_LAMBDA_4 = 1.0
|
||||
_LAMBDA_OTHER = 12.0
|
||||
_MIN_SECTION = 4 # bars
|
||||
_HIGH_DB = 4.0 # a section within this of the track's loud parts is "high"
|
||||
_TIMBRE_WEIGHT = 1.0
|
||||
_OUTRO_BARS = 16 # the outro is looked for this far before the music ends
|
||||
_BUILD_MAX = 16 # a longer low stretch is not all build: take its last 8 bars
|
||||
|
||||
# The events a slot can be bound to, in the order the dialog lists them.
|
||||
EVENTS: tuple[str, ...] = (
|
||||
"first_beat", "intro_end",
|
||||
"build_1", "drop_1", "breakdown_1",
|
||||
"build_2", "drop_2", "breakdown_2",
|
||||
"build_3", "drop_3", "breakdown_3",
|
||||
"outro", "last_beat",
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Section:
|
||||
start: int # bar index (0 = the grid's first marker)
|
||||
end: int # exclusive
|
||||
high: bool
|
||||
|
||||
|
||||
@dataclass
|
||||
class Structure:
|
||||
beats: np.ndarray # every grid beat time (s), including before the first marker
|
||||
bar0: int # index into `beats` of bar 1's downbeat
|
||||
n_bars: int
|
||||
duration: float
|
||||
sections: list[Section] = field(default_factory=list)
|
||||
events: dict[str, int] = field(default_factory=dict) # event -> BEAT index
|
||||
|
||||
def beat_of_bar(self, bar: int) -> int:
|
||||
return self.bar0 + 4 * bar
|
||||
|
||||
def beat_time(self, index: int) -> float:
|
||||
"""Time of beat ``index``, extrapolated past either end at the local tempo."""
|
||||
b = self.beats
|
||||
if 0 <= index < len(b):
|
||||
return float(b[index])
|
||||
if index < 0:
|
||||
step = b[1] - b[0] if len(b) > 1 else 0.5
|
||||
return float(b[0] + index * step)
|
||||
step = b[-1] - b[-2] if len(b) > 1 else 0.5
|
||||
return float(b[-1] + (index - len(b) + 1) * step)
|
||||
|
||||
|
||||
# ---- the grid -----------------------------------------------------------------
|
||||
def grid_beats(markers: list[tuple[float, float]], duration: float) -> tuple[np.ndarray, int]:
|
||||
"""Every beat of a (possibly flexible) grid, and the index of the first marker.
|
||||
|
||||
Each marker's tempo governs until the next marker, as the deck draws it;
|
||||
beats before the first marker are extrapolated back to the track start.
|
||||
"""
|
||||
markers = sorted(markers)
|
||||
start0, bpm0 = markers[0]
|
||||
step0 = 60.0 / bpm0
|
||||
before = np.arange(start0 - step0, -1e-9, -step0)[::-1]
|
||||
beats = list(before)
|
||||
bar0 = len(beats)
|
||||
for i, (start, bpm) in enumerate(markers):
|
||||
end = markers[i + 1][0] if i + 1 < len(markers) else duration
|
||||
beats.extend(np.arange(start, end - 1e-6, 60.0 / bpm))
|
||||
return np.asarray(beats, dtype=np.float64), bar0
|
||||
|
||||
|
||||
# ---- per-bar features ----------------------------------------------------------
|
||||
def _power_env(y: np.ndarray, lo: float | None, hi: float | None) -> np.ndarray:
|
||||
from scipy.signal import butter, sosfiltfilt
|
||||
|
||||
if lo and hi:
|
||||
sos = butter(4, [lo, hi], btype="bandpass", fs=_SR, output="sos")
|
||||
elif hi:
|
||||
sos = butter(4, hi, btype="lowpass", fs=_SR, output="sos")
|
||||
else:
|
||||
sos = butter(4, lo, btype="highpass", fs=_SR, output="sos")
|
||||
x = sosfiltfilt(sos, y) ** 2
|
||||
h = _SR // _FR
|
||||
n = len(x) // h
|
||||
return x[: n * h].reshape(n, h).mean(axis=1)
|
||||
|
||||
|
||||
def _db(x):
|
||||
return 10.0 * np.log10(np.asarray(x) + 1e-10)
|
||||
|
||||
|
||||
def _bar_features(y: np.ndarray, beats: np.ndarray, bar0: int, n_bars: int):
|
||||
"""``(D, T)``: per-bar [kick, bass, mid, high, loud] and mean MFCC.
|
||||
|
||||
Levels are dB BELOW the track's own 90th percentile, so every track is on
|
||||
the same scale whatever its mastering; kick is 0..~1 of the track's usual.
|
||||
"""
|
||||
import librosa
|
||||
|
||||
from . import grid_detect
|
||||
|
||||
bass = _power_env(y, 30.0, 120.0)
|
||||
mid = _power_env(y, 200.0, 2000.0)
|
||||
high = _power_env(y, 5000.0, None)
|
||||
full = _power_env(y, 20.0, 10000.0)
|
||||
# The kick is read as the grid detector reads it: the sharp low-band onset,
|
||||
# peaked within ±15 ms of each beat. Comparing on-beat to off-beat ENERGY
|
||||
# does not work: a house bassline lives on the off-beat.
|
||||
kick_on = grid_detect._onset(grid_detect._band_env(y, _SR, 30.0, 150.0))
|
||||
S = np.abs(librosa.stft(y, n_fft=2048, hop_length=512))
|
||||
mel = librosa.power_to_db(librosa.feature.melspectrogram(S=S**2, sr=_SR, n_mels=40))
|
||||
mfcc = librosa.feature.mfcc(S=mel, n_mfcc=13)
|
||||
mfcc_t = librosa.frames_to_time(np.arange(mfcc.shape[1]), sr=_SR, hop_length=512)
|
||||
|
||||
rows, timbre = [], []
|
||||
for b in range(n_bars):
|
||||
i = bar0 + 4 * b
|
||||
t0, t1 = beats[i], beats[i + 4]
|
||||
ks = []
|
||||
for k in range(4):
|
||||
c = int(round(beats[i + k] * 1000))
|
||||
seg = kick_on[max(0, c - 15) : c + 16]
|
||||
ks.append(float(seg.max()) if len(seg) else 0.0)
|
||||
a, z = int(t0 * _FR), max(int(t1 * _FR), int(t0 * _FR) + 1)
|
||||
rows.append([
|
||||
float(np.median(ks)),
|
||||
_db(bass[a:z].mean()), _db(mid[a:z].mean()), _db(high[a:z].mean()), _db(full[a:z].mean()),
|
||||
])
|
||||
ia, iz = np.searchsorted(mfcc_t, t0), np.searchsorted(mfcc_t, t1)
|
||||
timbre.append(mfcc[:, ia : max(iz, ia + 1)].mean(axis=1))
|
||||
D = np.asarray(rows)
|
||||
D[:, 0] /= np.percentile(D[:, 0], 90) + 1e-9
|
||||
D[:, 1:] -= np.percentile(D[:, 1:], 90, axis=0)
|
||||
D[:, 1:] = np.maximum(D[:, 1:], -30.0) # silence is only "very quiet"
|
||||
return D, np.asarray(timbre), _db(full)
|
||||
|
||||
|
||||
# ---- segmentation ---------------------------------------------------------------
|
||||
def _segment(F: np.ndarray, penalty: np.ndarray) -> list[int]:
|
||||
"""Section start bars minimising squared deviation from each section's mean
|
||||
plus a price per boundary (exact dynamic programme; n is ~100–250 bars)."""
|
||||
n = len(F)
|
||||
cs = np.vstack([np.zeros(F.shape[1]), np.cumsum(F, axis=0)])
|
||||
cs2 = np.r_[0.0, np.cumsum((F**2).sum(axis=1))]
|
||||
|
||||
def cost(i: int, j: int) -> float:
|
||||
s = cs[j] - cs[i]
|
||||
return float(cs2[j] - cs2[i] - (s @ s) / (j - i))
|
||||
|
||||
best = np.full(n + 1, np.inf)
|
||||
best[0] = 0.0
|
||||
arg = np.zeros(n + 1, dtype=np.int64)
|
||||
for j in range(1, n + 1):
|
||||
for i in range(0, j):
|
||||
# every section is at least _MIN_SECTION long, except a short tail
|
||||
if j - i < _MIN_SECTION and j != n:
|
||||
continue
|
||||
if 0 < i < _MIN_SECTION:
|
||||
continue
|
||||
v = best[i] + cost(i, j) + (penalty[i] if i else 0.0)
|
||||
if v < best[j]:
|
||||
best[j], arg[j] = v, i
|
||||
starts, j = [], n
|
||||
while j > 0:
|
||||
starts.append(int(arg[j]))
|
||||
j = int(arg[j])
|
||||
return sorted(set(starts))
|
||||
|
||||
|
||||
def _sections(D: np.ndarray, T: np.ndarray) -> list[Section]:
|
||||
Z = np.column_stack([D[:, 0] * 10, D[:, 1] / 3, D[:, 4] / 3, D[:, 3] / 6, D[:, 2] / 6])
|
||||
Tz = (T - T.mean(axis=0)) / (T.std(axis=0) + 1e-9) * _TIMBRE_WEIGHT
|
||||
F = np.column_stack([Z, Tz])
|
||||
n = len(F)
|
||||
idx = np.arange(n)
|
||||
scale = float(F.var(axis=0).sum()) * 4.0
|
||||
penalty = scale * np.where(idx % 8 == 0, _LAMBDA_8, np.where(idx % 4 == 0, _LAMBDA_4, _LAMBDA_OTHER))
|
||||
starts = _segment(F, penalty)
|
||||
out = []
|
||||
for k, s in enumerate(starts):
|
||||
e = starts[k + 1] if k + 1 < len(starts) else n
|
||||
d = D[s:e].mean(axis=0)
|
||||
# High = near the track's loud parts on BOTH bass and loudness. The kick
|
||||
# is deliberately not required: drum & bass has no kick on every beat.
|
||||
out.append(Section(s, e, bool(d[1] > -_HIGH_DB and d[4] > -_HIGH_DB)))
|
||||
return out
|
||||
|
||||
|
||||
# ---- events ----------------------------------------------------------------------
|
||||
def _events(secs: list[Section], music_end_bar: int) -> dict[str, int]:
|
||||
"""Event -> BAR. Drops are high sections entered from a low one."""
|
||||
ev: dict[str, int] = {}
|
||||
drops: list[int] = []
|
||||
seen_low = False
|
||||
for i, s in enumerate(secs):
|
||||
if s.high:
|
||||
if seen_low and (i == 0 or not secs[i - 1].high):
|
||||
drops.append(i)
|
||||
else:
|
||||
seen_low = True
|
||||
|
||||
def run_end(i: int) -> int:
|
||||
while i + 1 < len(secs) and secs[i + 1].high:
|
||||
i += 1
|
||||
return i
|
||||
|
||||
for n, di in enumerate(drops, start=1):
|
||||
ev[f"drop_{n}"] = secs[di].start
|
||||
prev = secs[di - 1]
|
||||
ev[f"build_{n}"] = prev.start if prev.end - prev.start <= _BUILD_MAX else secs[di].start - 8
|
||||
# A breakdown is the end of a drop that ANOTHER drop follows; the end of
|
||||
# the last one is the outro's business.
|
||||
if n < len(drops):
|
||||
ev[f"breakdown_{n}"] = secs[run_end(di) + 1].start
|
||||
|
||||
if len(secs) > 1:
|
||||
ev["intro_end"] = secs[1].start
|
||||
after = drops[-1] if drops else 0
|
||||
cands = [s.start for s in secs[after + 1 :]] or [s.start for s in secs[1:]]
|
||||
if cands:
|
||||
ev["outro"] = min(cands, key=lambda b: abs(b - (music_end_bar - _OUTRO_BARS)))
|
||||
return ev
|
||||
|
||||
|
||||
# ---- entry point ---------------------------------------------------------------
|
||||
def analyse(
|
||||
audio_path: str,
|
||||
markers: list[tuple[float, float]],
|
||||
*,
|
||||
y: np.ndarray | None = None,
|
||||
) -> Structure:
|
||||
"""Sections and cue events for a track, on its own beatgrid.
|
||||
|
||||
``markers`` is the grid as ``[(start_sec, bpm), …]``. Raises ``ValueError``
|
||||
when there is no grid or too little music to have a structure.
|
||||
"""
|
||||
if not markers:
|
||||
raise ValueError("Set a beatgrid first")
|
||||
if y is None:
|
||||
import librosa
|
||||
y, _ = librosa.load(audio_path, sr=_SR, mono=True)
|
||||
y = np.asarray(y, dtype=np.float32)
|
||||
duration = len(y) / _SR
|
||||
beats, bar0 = grid_beats(markers, duration)
|
||||
n_bars = max(0, (len(beats) - bar0 - 1) // 4)
|
||||
if n_bars < 2 * _MIN_SECTION:
|
||||
raise ValueError("Track is too short to find a structure")
|
||||
|
||||
D, T, full_db = _bar_features(y, beats, bar0, n_bars)
|
||||
st = Structure(beats=beats, bar0=bar0, n_bars=n_bars, duration=duration)
|
||||
st.sections = _sections(D, T)
|
||||
|
||||
# Where the music starts and ends: the first/last beat within 30 dB of the
|
||||
# track's loud parts, so a silent lead-in or tail is not cued.
|
||||
loud = full_db >= np.percentile(full_db, 90) - 30.0
|
||||
frames = np.flatnonzero(loud)
|
||||
t_first = frames[0] / _FR if len(frames) else 0.0
|
||||
t_last = frames[-1] / _FR if len(frames) else duration
|
||||
first_beat = int(np.searchsorted(beats, t_first - 0.05))
|
||||
last_beat = max(first_beat, int(np.searchsorted(beats, t_last, side="right")) - 1)
|
||||
music_end_bar = min(n_bars, max(0, (last_beat - bar0) // 4))
|
||||
|
||||
st.events = {k: st.beat_of_bar(b) for k, b in _events(st.sections, music_end_bar).items()}
|
||||
st.events["first_beat"] = first_beat
|
||||
st.events["last_beat"] = last_beat
|
||||
return st
|
||||
@@ -0,0 +1,403 @@
|
||||
"""Running an export: plan it, copy the audio, write the library.
|
||||
|
||||
App-level, like `importer.py`, and for the same reason — it coordinates a source
|
||||
library, a destination folder and an exporter, and none of those should know
|
||||
about the others.
|
||||
|
||||
**`core` plans and copies; the exporter only writes the library file.** Layout,
|
||||
collision and dedup rules are platform-independent and must not drift between
|
||||
targets, and the exporter cannot write a Traktor `<LOCATION>` before the
|
||||
destination path is known anyway.
|
||||
|
||||
## Ordering is the safety property
|
||||
|
||||
Audio is copied FIRST and the library written LAST, so a cancel during the long
|
||||
part leaves no library file — its absence is what marks an export unfinished —
|
||||
and everything copied is removed on the way out. The rollback tracks files
|
||||
BEFORE each write, not after: cleaning up only COMPLETED copies leaves the
|
||||
in-flight one behind, which is a bug the import feature had and was fixed there.
|
||||
|
||||
## Konduktor only deletes what Konduktor wrote
|
||||
|
||||
A re-export clears its destination first, which combined with "the user picks
|
||||
the destination" is a folder-deletion hazard: point an export at `~/Documents`
|
||||
and a confirm dialog is the only thing between a click and real loss. So every
|
||||
export writes a **manifest** of what it put there, and a destination that is
|
||||
non-empty without one is REFUSED rather than confirmed. Clearing then removes
|
||||
exactly the manifest's files — anything the user added themselves survives.
|
||||
|
||||
## Mirror layout
|
||||
|
||||
Audio is laid out mirroring the source tree, relative to the deepest folder all
|
||||
the tracks share (`common_dir_prefix`). Mirroring absolute paths would put the
|
||||
user's home directory on the stick; mirroring relative to the common root keeps
|
||||
the structure recognisable and makes filename collisions impossible, since two
|
||||
distinct source paths cannot share a relative path.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from . import exports
|
||||
from .core.export import ExportPayload, ExportPlaylist, ExportTrack, for_platform
|
||||
from .core.pathmap import common_dir_prefix
|
||||
from .core.places import is_os_housekeeping
|
||||
from .importer import SPACE_HEADROOM, copy_file, free_bytes
|
||||
from .jobs import JobHandle
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
MANIFEST_NAME = ".konduktor-export.json"
|
||||
|
||||
#: Why an export cannot run. The UI words these; they are facts, not sentences.
|
||||
BLOCKED_OCCUPIED = "destination_not_empty"
|
||||
BLOCKED_EMPTY = "nothing_to_export"
|
||||
BLOCKED_NO_TARGET = "unsupported_target"
|
||||
|
||||
|
||||
@dataclass
|
||||
class PlannedTrack:
|
||||
track_id: str
|
||||
title: str
|
||||
source_path: Path | None
|
||||
destination: Path | None
|
||||
size: int = 0
|
||||
missing: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExportPlan:
|
||||
tracks: list[PlannedTrack] = field(default_factory=list)
|
||||
playlists: list[ExportPlaylist] = field(default_factory=list)
|
||||
destination: Path | None = None
|
||||
#: One of the BLOCKED_* facts, or None when the export can run.
|
||||
blocked: str | None = None
|
||||
#: Whether the destination already holds a Konduktor export to replace.
|
||||
replacing: bool = False
|
||||
|
||||
@property
|
||||
def exportable(self) -> list[PlannedTrack]:
|
||||
return [t for t in self.tracks if not t.missing]
|
||||
|
||||
@property
|
||||
def total_bytes(self) -> int:
|
||||
return sum(t.size for t in self.exportable)
|
||||
|
||||
def as_dict(self, free: int | None = None) -> dict:
|
||||
return {
|
||||
"tracks": len(self.tracks),
|
||||
"exportable": len(self.exportable),
|
||||
"missing": [t.title for t in self.tracks if t.missing],
|
||||
"playlists": [p.name for p in self.playlists],
|
||||
"total_bytes": self.total_bytes,
|
||||
"destination": str(self.destination) if self.destination else None,
|
||||
"free_bytes": free,
|
||||
"enough_space": (
|
||||
None if free is None else free >= self.total_bytes + SPACE_HEADROOM
|
||||
),
|
||||
"blocked": self.blocked,
|
||||
"replacing": self.replacing,
|
||||
}
|
||||
|
||||
|
||||
# ---- the destination ---------------------------------------------------------
|
||||
|
||||
|
||||
def manifest_path(destination: Path) -> Path:
|
||||
return Path(destination) / MANIFEST_NAME
|
||||
|
||||
|
||||
def is_ours(destination: Path) -> bool:
|
||||
"""Whether this folder holds an export Konduktor wrote."""
|
||||
try:
|
||||
return manifest_path(destination).is_file()
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def destination_blocked(destination: Path) -> str | None:
|
||||
"""Why this folder cannot be exported into, or None.
|
||||
|
||||
A folder that does not exist yet, or is empty, or carries our manifest, is
|
||||
fine. Anything else is REFUSED — not confirmed — because an export clears
|
||||
its destination and Konduktor must never delete what it did not write.
|
||||
"Empty" ignores what the OS writes by itself (`.Spotlight-V100`, `.Trashes`,
|
||||
…), or a stick's root would be refused the moment it was first mounted.
|
||||
"""
|
||||
destination = Path(destination)
|
||||
try:
|
||||
if not destination.exists():
|
||||
return None
|
||||
if not destination.is_dir():
|
||||
return BLOCKED_OCCUPIED
|
||||
if is_ours(destination):
|
||||
return None
|
||||
occupied = any(not is_os_housekeeping(p.name) for p in destination.iterdir())
|
||||
return BLOCKED_OCCUPIED if occupied else None
|
||||
except OSError:
|
||||
return BLOCKED_OCCUPIED
|
||||
|
||||
|
||||
def _clear(destination: Path) -> None:
|
||||
"""Remove the previous export, and only it.
|
||||
|
||||
Driven by the manifest rather than by wiping the folder: the manifest lists
|
||||
everything the last export wrote, so anything the user put there themselves
|
||||
survives. Empty directories are pruned afterwards so a re-export does not
|
||||
inherit the last one's folder skeleton.
|
||||
"""
|
||||
data = _read_manifest(destination)
|
||||
for name in data.get("files", []):
|
||||
try:
|
||||
(destination / name).unlink()
|
||||
except OSError:
|
||||
pass
|
||||
for name in (data.get("library"), MANIFEST_NAME):
|
||||
if name:
|
||||
try:
|
||||
(destination / name).unlink()
|
||||
except OSError:
|
||||
pass
|
||||
_prune_empty(destination)
|
||||
|
||||
|
||||
def _prune_empty(root: Path) -> None:
|
||||
try:
|
||||
for folder in sorted(
|
||||
(p for p in root.rglob("*") if p.is_dir()),
|
||||
key=lambda p: len(p.parts),
|
||||
reverse=True,
|
||||
):
|
||||
try:
|
||||
folder.rmdir()
|
||||
except OSError:
|
||||
pass # not empty — the user's own files live here
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _read_manifest(destination: Path) -> dict:
|
||||
from . import paths
|
||||
|
||||
data = paths.read_json(manifest_path(destination), {})
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def _write_manifest(destination: Path, *, library: str, files: list[str], name: str) -> None:
|
||||
from . import paths
|
||||
|
||||
paths.write_json(
|
||||
manifest_path(destination),
|
||||
{
|
||||
"note": "Written by Konduktor. It lists what this export put here, "
|
||||
"so re-exporting can replace exactly those files.",
|
||||
"export": name,
|
||||
"written": time.time(),
|
||||
"library": library,
|
||||
"files": files,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
# ---- planning ----------------------------------------------------------------
|
||||
|
||||
|
||||
def plan(adapter, export_set) -> ExportPlan:
|
||||
"""Resolve the set and work out where every file lands. Reads only."""
|
||||
destination = Path(export_set.destination).expanduser()
|
||||
built = ExportPlan(destination=destination)
|
||||
|
||||
if for_platform(export_set.target) is None:
|
||||
built.blocked = BLOCKED_NO_TARGET
|
||||
return built
|
||||
|
||||
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]
|
||||
|
||||
# The source is the adapter's `audio_path`, never `Track.filepath`: that is
|
||||
# a DISPLAY path, which on Traktor omits the volume and ignores the active
|
||||
# path mapping — so every track off the boot volume (or on a remapped
|
||||
# Windows drive) read as missing and the export was "empty".
|
||||
sources = {t.id: adapter.audio_path(t.id) for t in tracks}
|
||||
|
||||
# Mirror relative to the deepest shared folder, so the export carries the
|
||||
# user's structure without carrying their home directory.
|
||||
present = [str(p) for p in sources.values() if p]
|
||||
root = common_dir_prefix(present) if present else ""
|
||||
|
||||
for track in tracks:
|
||||
source = sources[track.id]
|
||||
exists = False
|
||||
size = 0
|
||||
try:
|
||||
exists = bool(source and source.is_file())
|
||||
size = source.stat().st_size if exists else 0
|
||||
except OSError:
|
||||
exists = False
|
||||
built.tracks.append(
|
||||
PlannedTrack(
|
||||
track_id=track.id,
|
||||
title=track.title or (source.name if source else track.id),
|
||||
source_path=source,
|
||||
destination=(destination / _relative(source, root)) if exists else None,
|
||||
size=size,
|
||||
missing=not exists,
|
||||
)
|
||||
)
|
||||
|
||||
names = {p.id: p for p in resolved.playlists}
|
||||
folders = _folder_paths(adapter)
|
||||
for playlist in resolved.playlists:
|
||||
if playlist.missing or not playlist.track_ids:
|
||||
continue
|
||||
built.playlists.append(
|
||||
ExportPlaylist(
|
||||
name=names[playlist.id].name,
|
||||
track_ids=list(playlist.track_ids),
|
||||
folders=folders.get(playlist.id, []),
|
||||
)
|
||||
)
|
||||
|
||||
if not built.exportable:
|
||||
built.blocked = BLOCKED_EMPTY
|
||||
else:
|
||||
built.blocked = destination_blocked(destination)
|
||||
built.replacing = is_ours(destination)
|
||||
return built
|
||||
|
||||
|
||||
def _relative(source: Path, root: str) -> Path:
|
||||
"""Where `source` sits under the export root, mirroring its own folders."""
|
||||
text = str(source).replace("\\", "/")
|
||||
if root and text.startswith(root + "/"):
|
||||
return Path(text[len(root) + 1:])
|
||||
# No shared root (tracks on different volumes): keep the full path minus its
|
||||
# leading separator, which is ugly but never collides.
|
||||
return Path(text.lstrip("/"))
|
||||
|
||||
|
||||
def _folder_paths(adapter) -> dict[str, list[str]]:
|
||||
"""Each playlist's folder chain, outermost first."""
|
||||
out: dict[str, list[str]] = {}
|
||||
|
||||
def walk(nodes, path: list[str]) -> None:
|
||||
for node in nodes or []:
|
||||
if node.kind == "folder":
|
||||
walk(getattr(node, "children", None), path + [node.name])
|
||||
else:
|
||||
out[node.id] = path
|
||||
walk(getattr(node, "children", None), path)
|
||||
|
||||
walk(adapter.playlist_tree(), [])
|
||||
return out
|
||||
|
||||
|
||||
# ---- running -----------------------------------------------------------------
|
||||
|
||||
|
||||
def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict:
|
||||
"""Copy the audio, then write the library. Rolls back everything on cancel."""
|
||||
exporter = for_platform(export_set.target)
|
||||
if exporter is None:
|
||||
raise ValueError(f"Konduktor cannot export to {export_set.target}")
|
||||
if built.blocked:
|
||||
raise ValueError(f"This export cannot run: {built.blocked}")
|
||||
|
||||
destination = Path(built.destination)
|
||||
items = built.exportable
|
||||
total = sum(t.size for t in items)
|
||||
handle.progress(done=0, total=total, message="Preparing…")
|
||||
|
||||
# Registered BEFORE each write, so a cancel mid-file removes the partial one
|
||||
# too. Cleaning up only completed copies leaves debris the retry then
|
||||
# suffixes around — a bug the import feature had.
|
||||
created: list[Path] = []
|
||||
done = 0
|
||||
try:
|
||||
destination.mkdir(parents=True, exist_ok=True)
|
||||
if is_ours(destination):
|
||||
handle.progress(message="Replacing the previous export…")
|
||||
_clear(destination)
|
||||
|
||||
payload_tracks: list[ExportTrack] = []
|
||||
for planned in items:
|
||||
handle.raise_if_cancelled()
|
||||
handle.progress(message=f"Copying {planned.title}")
|
||||
target = Path(planned.destination)
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
created.append(target)
|
||||
|
||||
def advance(n: int) -> None:
|
||||
nonlocal done
|
||||
done += n
|
||||
handle.progress(done=done)
|
||||
|
||||
copy_file(planned.source_path, target, handle, advance)
|
||||
payload_tracks.append(
|
||||
ExportTrack(
|
||||
track=adapter.track(planned.track_id),
|
||||
destination=target,
|
||||
cues=adapter.track_cues(planned.track_id),
|
||||
)
|
||||
)
|
||||
|
||||
handle.raise_if_cancelled()
|
||||
handle.progress(message=f"Writing the {export_set.target} library…")
|
||||
written = exporter.write(
|
||||
ExportPayload(
|
||||
name=export_set.name,
|
||||
tracks=payload_tracks,
|
||||
playlists=built.playlists,
|
||||
),
|
||||
destination,
|
||||
)
|
||||
# Everything the exporter reported, not just the library: a target can
|
||||
# write a database PLUS a per-track analysis file, and anything left out
|
||||
# here is an orphan the next re-export cannot clear.
|
||||
created.extend(written.all_paths)
|
||||
|
||||
library = written.library
|
||||
_write_manifest(
|
||||
destination,
|
||||
library=str(library.relative_to(destination)),
|
||||
files=sorted(
|
||||
{str(p.relative_to(destination)) for p in created if p != library}
|
||||
),
|
||||
name=export_set.name,
|
||||
)
|
||||
return {
|
||||
"tracks": len(payload_tracks),
|
||||
"playlists": len(built.playlists),
|
||||
"skipped": len(built.tracks) - len(items),
|
||||
"destination": str(destination),
|
||||
"library": str(library),
|
||||
}
|
||||
except BaseException:
|
||||
# Cancelled or failed: leave no library file and no half-written copies.
|
||||
# Matches import, deliberately — two features whose cancel means
|
||||
# different things is worse than either behaviour on its own.
|
||||
for path in created:
|
||||
try:
|
||||
path.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
manifest_path(destination).unlink()
|
||||
except OSError:
|
||||
pass
|
||||
_prune_empty(destination)
|
||||
raise
|
||||
|
||||
|
||||
def space_for(built: ExportPlan) -> int | None:
|
||||
return free_bytes(Path(built.destination)) if built.destination else None
|
||||
|
||||
|
||||
__all__ = [
|
||||
"BLOCKED_EMPTY", "BLOCKED_NO_TARGET", "BLOCKED_OCCUPIED", "ExportPlan",
|
||||
"MANIFEST_NAME", "PlannedTrack", "destination_blocked", "is_ours", "plan",
|
||||
"run", "space_for",
|
||||
]
|
||||
@@ -0,0 +1,335 @@
|
||||
"""Export sets: a named, persisted slice of the library, bound to a destination.
|
||||
|
||||
An export set is what the user curates before exporting — a name, a target
|
||||
platform, a destination folder, and the tracks and playlists to include. It is
|
||||
**Konduktor's own data**, never written into the user's library: a Traktor
|
||||
collection has nowhere to put this, and putting it there would mean a concept
|
||||
only Konduktor understands living in a file Traktor rewrites.
|
||||
|
||||
Three things shape the design:
|
||||
|
||||
**References are LIVE.** A set stores playlist *ids*, not the tracks that were in
|
||||
them when you dragged one in. They are resolved at export time, so adding a track
|
||||
to a playlist next week means the next export picks it up. The consequence is
|
||||
that the contents of a set can never be cached — `resolve()` asks the adapter
|
||||
every time, and the UI's count changes underneath the user by design.
|
||||
|
||||
**A playlist is removable only as a whole.** A live reference and per-track
|
||||
removal are in tension: honouring both needs an exclusion list, i.e. hidden state
|
||||
that silently decides what a future export contains. Loose tracks are removable
|
||||
individually; for a subset of a playlist, add the tracks instead of the playlist.
|
||||
|
||||
**Keyed by library id, not path.** These are curated work. Keying them on the
|
||||
library's OS path — as everything else in the app still does — would orphan every
|
||||
set the moment the user moves their collection. See `library_id.py`.
|
||||
|
||||
Storage is one JSON file per library under the app-data dir, written atomically
|
||||
via `paths.write_json`. Deliberately NOT `prefs.py`, whose best-effort "any I/O
|
||||
error degrades to no prefs" is right for a window size and wrong for this.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from . import paths
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExportSet:
|
||||
"""One curated export. `destination` is bound at creation, not at run time.
|
||||
|
||||
Bound early because it is not merely convenient: a Traktor `<LOCATION>` is a
|
||||
volume name plus a volume-relative path, both derived from where the export
|
||||
lands, so the library file cannot be written until the destination is known.
|
||||
"""
|
||||
|
||||
id: str
|
||||
name: str
|
||||
target: str # platform id of the export TARGET, e.g. "traktor"
|
||||
destination: str # OS path of the folder the export is written into
|
||||
playlist_ids: list[str] = field(default_factory=list)
|
||||
track_ids: list[str] = field(default_factory=list) # loose tracks only
|
||||
created: float = 0.0
|
||||
modified: float = 0.0
|
||||
|
||||
def as_dict(self) -> dict:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ResolvedPlaylist:
|
||||
"""A referenced playlist, as it stands right now."""
|
||||
|
||||
id: str
|
||||
name: str
|
||||
missing: bool # the playlist has since been deleted
|
||||
track_ids: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ResolvedSet:
|
||||
"""What an export set contains at this instant.
|
||||
|
||||
Never stored. The references are live, so a cached answer would be a lie the
|
||||
moment the user edits a playlist.
|
||||
"""
|
||||
|
||||
playlists: list[ResolvedPlaylist] = field(default_factory=list)
|
||||
loose_track_ids: list[str] = field(default_factory=list)
|
||||
# Ids in the set that the library no longer has. Surfaced rather than
|
||||
# silently dropped: a gig stick quietly missing four tracks is the worst
|
||||
# failure this feature has.
|
||||
dangling_track_ids: list[str] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def track_ids(self) -> list[str]:
|
||||
"""Every track this export would carry, DEDUPED, in a stable order.
|
||||
|
||||
A track referenced both loosely and through a playlist is one track and
|
||||
one file copy. Playlists come first so the order follows the tree the
|
||||
user sees.
|
||||
"""
|
||||
seen: set[str] = set()
|
||||
out: list[str] = []
|
||||
for playlist in self.playlists:
|
||||
for track_id in playlist.track_ids:
|
||||
if track_id not in seen:
|
||||
seen.add(track_id)
|
||||
out.append(track_id)
|
||||
for track_id in self.loose_track_ids:
|
||||
if track_id not in seen:
|
||||
seen.add(track_id)
|
||||
out.append(track_id)
|
||||
return out
|
||||
|
||||
|
||||
# ---- storage -----------------------------------------------------------------
|
||||
|
||||
|
||||
def _store_path(library_id: str) -> Path:
|
||||
return paths.app_data_dir() / "exports" / f"{library_id}.json"
|
||||
|
||||
|
||||
def _load(library_id: str) -> dict[str, ExportSet]:
|
||||
data = paths.read_json(_store_path(library_id), {})
|
||||
raw = data.get("sets") if isinstance(data, dict) else None
|
||||
out: dict[str, ExportSet] = {}
|
||||
if isinstance(raw, dict):
|
||||
for set_id, values in raw.items():
|
||||
if not isinstance(values, dict):
|
||||
continue
|
||||
try:
|
||||
out[set_id] = ExportSet(
|
||||
id=set_id,
|
||||
name=values.get("name") or "Untitled",
|
||||
target=values.get("target") or "traktor",
|
||||
destination=values.get("destination") or "",
|
||||
playlist_ids=list(values.get("playlist_ids") or []),
|
||||
track_ids=list(values.get("track_ids") or []),
|
||||
created=float(values.get("created") or 0.0),
|
||||
modified=float(values.get("modified") or 0.0),
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
log.warning("skipping unreadable export set %s", set_id)
|
||||
return out
|
||||
|
||||
|
||||
def _save(library_id: str, sets: dict[str, ExportSet]) -> None:
|
||||
paths.write_json(
|
||||
_store_path(library_id),
|
||||
{"library_id": library_id, "sets": {k: v.as_dict() for k, v in sets.items()}},
|
||||
)
|
||||
|
||||
|
||||
# ---- reading -----------------------------------------------------------------
|
||||
|
||||
|
||||
def all_sets(library_id: str) -> list[ExportSet]:
|
||||
"""Every export set for one library, oldest first so the list is stable."""
|
||||
return sorted(_load(library_id).values(), key=lambda s: (s.created, s.name.lower()))
|
||||
|
||||
|
||||
def get(library_id: str, set_id: str) -> ExportSet | None:
|
||||
return _load(library_id).get(set_id)
|
||||
|
||||
|
||||
def destination_conflict(library_id: str, destination: str, *, ignore: str | None = None) -> str | None:
|
||||
"""The name of another set already pointing at `destination`, if any.
|
||||
|
||||
An export CLEARS its destination before writing, so two sets sharing one
|
||||
folder means the second silently wipes the first's output. Caught when the
|
||||
destination is chosen rather than at run time, where it would already be too
|
||||
late to be a warning.
|
||||
"""
|
||||
target = _normalise(destination)
|
||||
if not target:
|
||||
return None
|
||||
for existing in _load(library_id).values():
|
||||
if existing.id != ignore and _normalise(existing.destination) == target:
|
||||
return existing.name
|
||||
return None
|
||||
|
||||
|
||||
def _normalise(destination: str) -> str:
|
||||
try:
|
||||
return str(Path(destination).expanduser().resolve())
|
||||
except (OSError, ValueError):
|
||||
return destination.strip()
|
||||
|
||||
|
||||
# ---- writing -----------------------------------------------------------------
|
||||
|
||||
|
||||
def create(library_id: str, *, name: str, target: str, destination: str) -> ExportSet:
|
||||
sets = _load(library_id)
|
||||
now = time.time()
|
||||
created = ExportSet(
|
||||
id=uuid.uuid4().hex,
|
||||
name=name.strip() or "Untitled",
|
||||
target=target,
|
||||
destination=destination,
|
||||
created=now,
|
||||
modified=now,
|
||||
)
|
||||
sets[created.id] = created
|
||||
_save(library_id, sets)
|
||||
return created
|
||||
|
||||
|
||||
def update(library_id: str, set_id: str, **fields) -> ExportSet | None:
|
||||
"""Rename, retarget or relocate a set. Unknown fields are ignored."""
|
||||
sets = _load(library_id)
|
||||
found = sets.get(set_id)
|
||||
if found is None:
|
||||
return None
|
||||
for key in ("name", "target", "destination"):
|
||||
if key in fields and fields[key] is not None:
|
||||
setattr(found, key, fields[key])
|
||||
found.modified = time.time()
|
||||
_save(library_id, sets)
|
||||
return found
|
||||
|
||||
|
||||
def delete(library_id: str, set_id: str) -> bool:
|
||||
"""Forget a set. Deliberately does NOT touch its destination folder."""
|
||||
sets = _load(library_id)
|
||||
if sets.pop(set_id, None) is None:
|
||||
return False
|
||||
_save(library_id, sets)
|
||||
return True
|
||||
|
||||
|
||||
def add(library_id: str, set_id: str, *, track_ids=None, playlist_ids=None) -> ExportSet | None:
|
||||
"""Add tracks and/or playlists, preserving order and ignoring duplicates."""
|
||||
sets = _load(library_id)
|
||||
found = sets.get(set_id)
|
||||
if found is None:
|
||||
return None
|
||||
for incoming, existing in (
|
||||
(track_ids or [], found.track_ids),
|
||||
(playlist_ids or [], found.playlist_ids),
|
||||
):
|
||||
have = set(existing)
|
||||
for item in incoming:
|
||||
if item not in have:
|
||||
have.add(item)
|
||||
existing.append(item)
|
||||
found.modified = time.time()
|
||||
_save(library_id, sets)
|
||||
return found
|
||||
|
||||
|
||||
def remove(library_id: str, set_id: str, *, track_ids=None, playlist_ids=None) -> ExportSet | None:
|
||||
"""Remove loose tracks and/or whole playlists.
|
||||
|
||||
There is no "remove a track from a referenced playlist": see the module
|
||||
docstring. A track id passed here is dropped from the LOOSE list only, so
|
||||
removing one that a referenced playlist also supplies is a no-op — which is
|
||||
honest, because the playlist still puts it in the export.
|
||||
"""
|
||||
sets = _load(library_id)
|
||||
found = sets.get(set_id)
|
||||
if found is None:
|
||||
return None
|
||||
if track_ids:
|
||||
drop = set(track_ids)
|
||||
found.track_ids = [t for t in found.track_ids if t not in drop]
|
||||
if playlist_ids:
|
||||
drop = set(playlist_ids)
|
||||
found.playlist_ids = [p for p in found.playlist_ids if p not in drop]
|
||||
found.modified = time.time()
|
||||
_save(library_id, sets)
|
||||
return found
|
||||
|
||||
|
||||
def retarget(library_id: str, mapping: dict[str, str]) -> None:
|
||||
"""Follow track ids that changed, e.g. after an OS-path remap.
|
||||
|
||||
A Traktor track id IS its path, so a remap renames every id in the library.
|
||||
Without this a set's references would dangle silently — and silently is the
|
||||
problem, since the set would still look fine and export fewer tracks.
|
||||
"""
|
||||
if not mapping:
|
||||
return
|
||||
sets = _load(library_id)
|
||||
touched = False
|
||||
for found in sets.values():
|
||||
renamed = [mapping.get(t, t) for t in found.track_ids]
|
||||
if renamed != found.track_ids:
|
||||
found.track_ids = renamed
|
||||
found.modified = time.time()
|
||||
touched = True
|
||||
if touched:
|
||||
_save(library_id, sets)
|
||||
|
||||
|
||||
# ---- resolution --------------------------------------------------------------
|
||||
|
||||
|
||||
def resolve(adapter, export_set: ExportSet) -> ResolvedSet:
|
||||
"""What this set contains RIGHT NOW, against the loaded library.
|
||||
|
||||
Computed on every call and never stored, because the references are live —
|
||||
the whole point is that a playlist edited after curation is picked up.
|
||||
"""
|
||||
resolved = ResolvedSet()
|
||||
names = _playlist_names(adapter)
|
||||
|
||||
for playlist_id in export_set.playlist_ids:
|
||||
entries = adapter.playlist_entries(playlist_id)
|
||||
resolved.playlists.append(
|
||||
ResolvedPlaylist(
|
||||
id=playlist_id,
|
||||
name=names.get(playlist_id, playlist_id),
|
||||
# A playlist deleted since curation. Shown, not dropped: the set
|
||||
# is the user's record of intent and losing it silently is worse
|
||||
# than showing something broken.
|
||||
missing=entries is None,
|
||||
track_ids=list(entries or []),
|
||||
)
|
||||
)
|
||||
|
||||
for track_id in export_set.track_ids:
|
||||
if adapter.track(track_id) is None:
|
||||
resolved.dangling_track_ids.append(track_id)
|
||||
else:
|
||||
resolved.loose_track_ids.append(track_id)
|
||||
return resolved
|
||||
|
||||
|
||||
def _playlist_names(adapter) -> dict[str, str]:
|
||||
out: dict[str, str] = {}
|
||||
|
||||
def walk(nodes) -> None:
|
||||
for node in nodes or []:
|
||||
out[node.id] = node.name
|
||||
walk(getattr(node, "children", None))
|
||||
|
||||
walk(adapter.playlist_tree())
|
||||
return out
|
||||
@@ -0,0 +1,205 @@
|
||||
"""Per-collection version history backed by a purely-local git repo (dulwich).
|
||||
|
||||
Replaces the old ``.bak`` copy-on-save. Every Konduktor write to a collection is
|
||||
committed to a small git repo — one per collection — living in the app-data dir
|
||||
(NOT next to the user's collection). Git's delta packing makes near-identical
|
||||
NMLs almost free, so we keep full history forever; a manual "delete all history"
|
||||
is the only pruning.
|
||||
|
||||
Design rules:
|
||||
* ALL git interaction is confined to this module.
|
||||
* EVERY public function is best-effort: it swallows its own errors (returning a
|
||||
safe empty/None value) so a history failure can never break a save or an open.
|
||||
* The tracked file is named after the library itself; the
|
||||
repo is keyed by a hash of the collection's absolute OS path (mirrors prefs'
|
||||
path-based keying). Collection identity is therefore the OS path — moving the
|
||||
collection starts a fresh history (same fragility prefs already accepts).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import shutil
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from dulwich import porcelain
|
||||
from dulwich.repo import Repo
|
||||
|
||||
from . import paths
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
_LEGACY_TRACKED_NAME = "collection.nml"
|
||||
|
||||
|
||||
def _tracked_name(library_path: Path) -> str:
|
||||
"""The file name used inside the repo.
|
||||
|
||||
Was hard-coded to ``collection.nml``. Using the library's own name lets a
|
||||
non-Traktor library be versioned the same way; reads fall back to the legacy
|
||||
name so histories recorded before this change stay readable.
|
||||
"""
|
||||
return Path(library_path).name
|
||||
_AUTHOR = b"Konduktor <konduktor@localhost>"
|
||||
|
||||
|
||||
@dataclass
|
||||
class HistoryEntry:
|
||||
id: str # full commit sha (hex)
|
||||
timestamp: str # ISO 8601, UTC
|
||||
summary: str # first line of the commit message
|
||||
|
||||
|
||||
# ---- repo location -----------------------------------------------------------
|
||||
|
||||
def _key(nml_path: Path) -> str:
|
||||
return hashlib.sha256(str(Path(nml_path).resolve()).encode()).hexdigest()[:16]
|
||||
|
||||
|
||||
def _repo_dir(nml_path: Path) -> Path:
|
||||
return paths.app_data_dir() / "history" / _key(nml_path)
|
||||
|
||||
|
||||
def _tracked_file(repo_dir: Path, nml_path: Path) -> Path:
|
||||
return repo_dir / _tracked_name(nml_path)
|
||||
|
||||
|
||||
def _write_meta(repo_dir: Path, nml_path: Path) -> None:
|
||||
"""A tiny sidecar recording which collection this repo belongs to (for
|
||||
debugging / a friendly display name). Best-effort."""
|
||||
try:
|
||||
meta = {"path": str(Path(nml_path).resolve()), "name": Path(nml_path).parent.name}
|
||||
(repo_dir / ".meta.json").write_text(json.dumps(meta, indent=2))
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _open_or_init(nml_path: Path) -> Path:
|
||||
"""Ensure the collection's repo exists; return its directory."""
|
||||
repo_dir = _repo_dir(nml_path)
|
||||
if not (repo_dir / ".git").exists():
|
||||
repo_dir.mkdir(parents=True, exist_ok=True)
|
||||
porcelain.init(str(repo_dir))
|
||||
_write_meta(repo_dir, nml_path)
|
||||
return repo_dir
|
||||
|
||||
|
||||
def _tree_blob(tree, nml_path: Path):
|
||||
"""Find the tracked blob in a commit's tree.
|
||||
|
||||
Tries the library's own name first, then the legacy fixed name, then — if the
|
||||
repo holds exactly one file — that one, so a history written under any past
|
||||
naming rule stays readable.
|
||||
"""
|
||||
for name in (_tracked_name(nml_path), _LEGACY_TRACKED_NAME):
|
||||
try:
|
||||
return tree[name.encode()]
|
||||
except KeyError:
|
||||
continue
|
||||
items = list(tree.items())
|
||||
if len(items) == 1:
|
||||
return items[0].mode, items[0].sha
|
||||
raise KeyError(f"no tracked file in history for {nml_path}")
|
||||
|
||||
|
||||
def _head_blob(repo: Repo, nml_path: Path) -> bytes | None:
|
||||
"""The tracked file's bytes at HEAD, or None if the repo has no commits."""
|
||||
try:
|
||||
head = repo.head()
|
||||
except KeyError:
|
||||
return None
|
||||
commit = repo[head]
|
||||
tree = repo[commit.tree]
|
||||
try:
|
||||
_mode, blob_sha = _tree_blob(tree, nml_path)
|
||||
except KeyError:
|
||||
return None
|
||||
return repo[blob_sha].data
|
||||
|
||||
|
||||
# ---- public API --------------------------------------------------------------
|
||||
|
||||
def commit(nml_path: Path, data: bytes, message: str, app_version: str) -> str | None:
|
||||
"""Commit ``data`` as the collection's newest version. Deduped: if ``data``
|
||||
is byte-identical to HEAD, no commit is made and None is returned. Returns
|
||||
the new commit sha (hex) on success, None on dedup or any failure."""
|
||||
try:
|
||||
repo_dir = _open_or_init(nml_path)
|
||||
with Repo(str(repo_dir)) as repo:
|
||||
if _head_blob(repo, nml_path) == data:
|
||||
return None # nothing changed since last version
|
||||
path = _tracked_file(repo_dir, nml_path)
|
||||
path.write_bytes(data)
|
||||
porcelain.add(str(repo_dir), paths=[str(path)])
|
||||
msg = f"{message}\n\nApp-Version: {app_version}".encode()
|
||||
sha = porcelain.commit(str(repo_dir), message=msg, author=_AUTHOR, committer=_AUTHOR)
|
||||
return sha.decode() if isinstance(sha, bytes) else str(sha)
|
||||
except Exception: # best-effort — history must never break a save
|
||||
log.exception("history.commit failed for %s", nml_path)
|
||||
return None
|
||||
|
||||
|
||||
def ensure_baseline(nml_path: Path) -> None:
|
||||
"""Commit the current on-disk collection as an "as I found it" baseline.
|
||||
Deduped, so re-opening an unchanged collection is a no-op. Best-effort."""
|
||||
try:
|
||||
data = Path(nml_path).read_bytes()
|
||||
except OSError:
|
||||
return
|
||||
commit(nml_path, data, "Baseline — opened collection", _app_version())
|
||||
|
||||
|
||||
def list_history(nml_path: Path) -> list[HistoryEntry]:
|
||||
"""All versions, newest first. Empty list if no history / on any failure."""
|
||||
repo_dir = _repo_dir(nml_path)
|
||||
if not (repo_dir / ".git").exists():
|
||||
return []
|
||||
try:
|
||||
entries: list[HistoryEntry] = []
|
||||
with Repo(str(repo_dir)) as repo:
|
||||
try:
|
||||
repo.head()
|
||||
except KeyError:
|
||||
return []
|
||||
for e in repo.get_walker():
|
||||
c = e.commit
|
||||
ts = datetime.fromtimestamp(c.commit_time, tz=timezone.utc).isoformat()
|
||||
summary = c.message.decode("utf-8", "replace").splitlines()[0] if c.message else ""
|
||||
entries.append(HistoryEntry(id=c.id.decode(), timestamp=ts, summary=summary))
|
||||
return entries
|
||||
except Exception:
|
||||
log.exception("history.list_history failed for %s", nml_path)
|
||||
return []
|
||||
|
||||
|
||||
def read_version(nml_path: Path, commit_id: str) -> bytes | None:
|
||||
"""The tracked collection bytes at a specific commit, or None on failure."""
|
||||
repo_dir = _repo_dir(nml_path)
|
||||
if not (repo_dir / ".git").exists():
|
||||
return None
|
||||
try:
|
||||
with Repo(str(repo_dir)) as repo:
|
||||
c = repo[commit_id.encode()]
|
||||
tree = repo[c.tree]
|
||||
_mode, blob_sha = _tree_blob(tree, nml_path)
|
||||
return repo[blob_sha].data
|
||||
except Exception:
|
||||
log.exception("history.read_version failed for %s @ %s", nml_path, commit_id)
|
||||
return None
|
||||
|
||||
|
||||
def clear_history(nml_path: Path) -> None:
|
||||
"""Delete ALL version history for a collection (removes its repo). Best-effort."""
|
||||
try:
|
||||
shutil.rmtree(_repo_dir(nml_path), ignore_errors=True)
|
||||
except Exception:
|
||||
log.exception("history.clear_history failed for %s", nml_path)
|
||||
|
||||
|
||||
def _app_version() -> str:
|
||||
from . import __version__
|
||||
|
||||
return __version__
|
||||
@@ -0,0 +1,424 @@
|
||||
"""Importing tracks from a source library into the loaded one.
|
||||
|
||||
App-level, not adapter-level, and deliberately so: this coordinates TWO
|
||||
libraries, and neither adapter should know the other exists. The source is asked
|
||||
for generic tracks and cues; the destination is handed generic `NewTrack`s. The
|
||||
only thing this module adds is everything in between — the audio copy, the
|
||||
pre-scan, and the playlist reconstruction.
|
||||
|
||||
**The copy is this module's job, not the adapter's.** `NewTrack.audio_path` must
|
||||
already exist when it reaches the destination, because a file copy that failed
|
||||
halfway is not something a library write should be discovering.
|
||||
|
||||
Scope, chosen deliberately: **everything is added as a new entry**. Nothing is
|
||||
matched against tracks the destination already holds by metadata, so there is no
|
||||
merge policy and no cross-platform identity problem. Re-importing the same stick
|
||||
duplicates, and a preview warns about that rather than preventing it.
|
||||
|
||||
The one match that IS made is by **file**: a source file the destination already
|
||||
points at is never added again. Copying never hits that (it writes a fresh
|
||||
path), but **referencing in place** does — the folder browser can add
|
||||
`~/Music/x.mp3` to a collection that already holds it — and on Traktor two
|
||||
entries for one path share a primary key, which is a corrupt collection rather
|
||||
than a duplicate track. Such a file maps to the EXISTING track instead, so a
|
||||
playlist or export it was headed for still gets it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from .core.adapter import NewTrack
|
||||
from .jobs import JobHandle
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
# Copy in chunks so a cancel lands within a few milliseconds rather than at the
|
||||
# end of a 50 MB file, and so progress can move within one big track.
|
||||
COPY_CHUNK = 1024 * 1024
|
||||
|
||||
# Leave the destination some room rather than filling it exactly. A disk with
|
||||
# zero bytes free is a broken machine, not a successful import.
|
||||
SPACE_HEADROOM = 64 * 1024 * 1024
|
||||
|
||||
|
||||
@dataclass
|
||||
class PlannedTrack:
|
||||
track_id: str # the id in the SOURCE library
|
||||
title: str
|
||||
source_path: Path | None
|
||||
size: int = 0
|
||||
missing: bool = False
|
||||
# True when the destination already holds a track with this filename. Only a
|
||||
# warning: the user chose "add everything as new entries".
|
||||
duplicate: bool = False
|
||||
# The destination's own id for this exact file, when it already holds it.
|
||||
# Not added again; it stands in for the new id wherever one is needed.
|
||||
existing_id: str | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class ImportPlan:
|
||||
tracks: list[PlannedTrack] = field(default_factory=list)
|
||||
playlists: list[tuple[str, str]] = field(default_factory=list) # (id, name)
|
||||
destination: Path | None = None
|
||||
|
||||
@property
|
||||
def importable(self) -> list[PlannedTrack]:
|
||||
return [t for t in self.tracks if not t.missing and t.existing_id is None]
|
||||
|
||||
@property
|
||||
def existing(self) -> list[PlannedTrack]:
|
||||
return [t for t in self.tracks if t.existing_id is not None]
|
||||
|
||||
@property
|
||||
def total_bytes(self) -> int:
|
||||
return sum(t.size for t in self.importable)
|
||||
|
||||
def as_dict(self, free_bytes: int | None = None) -> dict:
|
||||
return {
|
||||
"tracks": len(self.tracks),
|
||||
"importable": len(self.importable),
|
||||
"missing": [t.title for t in self.tracks if t.missing],
|
||||
"duplicates": [t.title for t in self.tracks if t.duplicate],
|
||||
"existing": [t.title for t in self.existing],
|
||||
"playlists": [name for _, name in self.playlists],
|
||||
"total_bytes": self.total_bytes,
|
||||
"destination": str(self.destination) if self.destination else None,
|
||||
"free_bytes": free_bytes,
|
||||
"enough_space": (
|
||||
None if free_bytes is None
|
||||
else free_bytes >= self.total_bytes + SPACE_HEADROOM
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _existing_filenames(dest) -> set[str]:
|
||||
out: set[str] = set()
|
||||
for track in dest.tracks:
|
||||
path = getattr(track, "filepath", None)
|
||||
if path:
|
||||
out.add(Path(path).name.lower())
|
||||
return out
|
||||
|
||||
|
||||
def _key(path: Path) -> str:
|
||||
return os.path.normcase(os.path.normpath(str(path)))
|
||||
|
||||
|
||||
def _existing_files(dest) -> dict[str, str]:
|
||||
"""Every audio file the destination points at → its track id.
|
||||
|
||||
Resolved through the adapter's own `audio_path`, which is the only answer
|
||||
that includes the volume and the active path mapping; the projected
|
||||
`filepath` is a display string and is not good enough to match on.
|
||||
"""
|
||||
out: dict[str, str] = {}
|
||||
for track in dest.tracks:
|
||||
try:
|
||||
path = dest.audio_path(track.id)
|
||||
except Exception: # noqa: BLE001
|
||||
path = None
|
||||
if path is not None:
|
||||
out.setdefault(_key(path), track.id)
|
||||
return out
|
||||
|
||||
|
||||
def plan(source, dest, destination: Path | None, *, track_ids=None, playlist_ids=None) -> ImportPlan:
|
||||
"""Work out what an import would do, WITHOUT doing any of it.
|
||||
|
||||
Computed fresh every time and never stored. Playlist membership on the source
|
||||
can change between planning and importing (a stick can be re-exported), and a
|
||||
stale preview is worse than no preview.
|
||||
|
||||
Playlist selection AUTO-INCLUDES the tracks in those playlists, and the whole
|
||||
set is deduplicated, so a track in three chosen playlists is copied once.
|
||||
"""
|
||||
plan = ImportPlan(destination=destination)
|
||||
wanted: list[str] = []
|
||||
seen: set[str] = set()
|
||||
|
||||
def want(track_id: str) -> None:
|
||||
if track_id not in seen:
|
||||
seen.add(track_id)
|
||||
wanted.append(track_id)
|
||||
|
||||
for node_id in playlist_ids or []:
|
||||
node_tracks = source.playlist_tracks(node_id) or []
|
||||
for t in node_tracks:
|
||||
want(t.id)
|
||||
name = _playlist_name(source, node_id)
|
||||
if name:
|
||||
plan.playlists.append((node_id, name))
|
||||
|
||||
for track_id in track_ids or []:
|
||||
want(track_id)
|
||||
|
||||
# Neither given: the whole drive.
|
||||
if not (track_ids or playlist_ids):
|
||||
for t in source.tracks:
|
||||
want(t.id)
|
||||
for node_id, name in _all_playlists(source):
|
||||
plan.playlists.append((node_id, name))
|
||||
|
||||
existing = _existing_filenames(dest)
|
||||
held = _existing_files(dest)
|
||||
for track_id in wanted:
|
||||
track = source.track(track_id)
|
||||
if track is None:
|
||||
continue
|
||||
raw = getattr(track, "filepath", None)
|
||||
path = Path(raw) if raw else None
|
||||
planned = PlannedTrack(
|
||||
track_id=track_id,
|
||||
title=track.title or (path.name if path else track_id),
|
||||
source_path=path,
|
||||
)
|
||||
try:
|
||||
if path is not None and path.is_file():
|
||||
planned.size = path.stat().st_size
|
||||
planned.existing_id = held.get(_key(path))
|
||||
planned.duplicate = planned.existing_id is None and path.name.lower() in existing
|
||||
else:
|
||||
planned.missing = True
|
||||
except OSError:
|
||||
planned.missing = True
|
||||
plan.tracks.append(planned)
|
||||
return plan
|
||||
|
||||
|
||||
def _playlist_name(source, node_id: str) -> str | None:
|
||||
for nid, name in _all_playlists(source):
|
||||
if nid == node_id:
|
||||
return name
|
||||
return None
|
||||
|
||||
|
||||
def _all_playlists(source) -> list[tuple[str, str]]:
|
||||
"""Every selectable playlist on the source, flattened.
|
||||
|
||||
Folders are dropped rather than recreated. The destination gets ONE folder,
|
||||
named after the drive, and nesting a stick's folder tree inside it would bury
|
||||
the playlists a user is trying to find.
|
||||
"""
|
||||
out: list[tuple[str, str]] = []
|
||||
|
||||
def walk(nodes):
|
||||
for n in nodes:
|
||||
if n.kind == "playlist":
|
||||
out.append((n.id, n.name))
|
||||
walk(n.children or [])
|
||||
|
||||
walk(source.playlist_tree())
|
||||
return out
|
||||
|
||||
|
||||
def free_bytes(path: Path) -> int | None:
|
||||
try:
|
||||
target = path if path.exists() else path.parent
|
||||
return shutil.disk_usage(target).free
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def _unique_target(folder: Path, name: str, taken: set[str]) -> Path:
|
||||
"""A free filename in `folder`, suffixing on collision.
|
||||
|
||||
`taken` covers names claimed earlier in THIS run, which the filesystem cannot
|
||||
answer for — two sticks can both hold `Track.mp3`, and the first copy has not
|
||||
necessarily been written yet when the second is planned.
|
||||
|
||||
Known consequence of suffixing by processing order (accepted in the export
|
||||
design): re-importing may assign a different suffix to the same track.
|
||||
"""
|
||||
stem, dot, ext = name.rpartition(".")
|
||||
if not dot:
|
||||
stem, ext = name, ""
|
||||
candidate = name
|
||||
n = 1
|
||||
while candidate.lower() in taken or (folder / candidate).exists():
|
||||
n += 1
|
||||
candidate = f"{stem}-{n}{'.' + ext if ext else ''}"
|
||||
taken.add(candidate.lower())
|
||||
return folder / candidate
|
||||
|
||||
|
||||
def copy_file(src: Path, dst: Path, handle: JobHandle, on_bytes) -> None:
|
||||
"""Copy a file, checking for cancellation between chunks.
|
||||
|
||||
Public because export copies audio the same way and for the same reason: a
|
||||
second chunked-copy loop would be a second place for the cancel check to be
|
||||
forgotten, and a forgotten cancel check is invisible until someone tries to
|
||||
stop a multi-gigabyte copy.
|
||||
"""
|
||||
with src.open("rb") as fin, dst.open("wb") as fout:
|
||||
while True:
|
||||
handle.raise_if_cancelled()
|
||||
chunk = fin.read(COPY_CHUNK)
|
||||
if not chunk:
|
||||
break
|
||||
fout.write(chunk)
|
||||
on_bytes(len(chunk))
|
||||
shutil.copystat(src, dst, follow_symlinks=True)
|
||||
|
||||
|
||||
def run(
|
||||
source,
|
||||
dest,
|
||||
plan: ImportPlan,
|
||||
handle: JobHandle,
|
||||
*,
|
||||
folder_name: str | None = None,
|
||||
reference: bool = False,
|
||||
into_playlist: str | None = None,
|
||||
) -> dict:
|
||||
"""Perform the import. Returns a summary dict for the job result.
|
||||
|
||||
Ordering is the safety property. Audio is copied FIRST and the library is
|
||||
written LAST, so a cancel or a failure during the long part leaves the
|
||||
collection untouched and the copied files are removed on the way out. Once
|
||||
copying is done the library write is fast and is allowed to finish.
|
||||
|
||||
This is a COMMITTED action — it saves at the end — rather than an in-memory
|
||||
edit the Save button flushes. A multi-gigabyte copy is not a pending tweak,
|
||||
and audio on disk with unsaved entries pointing at it is the worst of both.
|
||||
|
||||
`reference` adds each file WHERE IT IS instead of copying it, so there is no
|
||||
destination and nothing to roll back. `into_playlist` appends every planned
|
||||
track — the new ones and those the destination already held — to one of the
|
||||
destination's playlists before the save, so both land in one commit.
|
||||
"""
|
||||
destination = plan.destination
|
||||
if not reference:
|
||||
assert destination is not None
|
||||
destination.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
importable = plan.importable
|
||||
total = plan.total_bytes or len(importable)
|
||||
handle.progress(done=0, total=total, message="Copying audio…")
|
||||
|
||||
copied: list[tuple[PlannedTrack, Path]] = []
|
||||
# Every path this run has opened for writing, including the one being written
|
||||
# when a cancel lands. `copied` holds only COMPLETED copies, so cleaning up
|
||||
# from it leaves the half-written file behind — which then makes the next
|
||||
# attempt suffix around a file that is not really there.
|
||||
created: list[Path] = []
|
||||
taken: set[str] = set()
|
||||
moved = 0
|
||||
|
||||
def bump(n: int) -> None:
|
||||
nonlocal moved
|
||||
moved += n
|
||||
handle.progress(done=moved)
|
||||
|
||||
try:
|
||||
for planned in importable:
|
||||
handle.raise_if_cancelled()
|
||||
assert planned.source_path is not None
|
||||
if reference:
|
||||
copied.append((planned, planned.source_path))
|
||||
continue
|
||||
handle.progress(message=f"Copying {planned.title}")
|
||||
target = _unique_target(destination, planned.source_path.name, taken)
|
||||
created.append(target) # registered BEFORE the write, so a cancel
|
||||
copy_file(planned.source_path, target, handle, bump) # mid-file is cleaned
|
||||
copied.append((planned, target))
|
||||
|
||||
handle.raise_if_cancelled()
|
||||
handle.progress(message="Adding tracks to the library…")
|
||||
|
||||
items: list[NewTrack] = []
|
||||
for planned, target in copied:
|
||||
track = source.track(planned.track_id)
|
||||
if track is None:
|
||||
continue
|
||||
cues = None
|
||||
try:
|
||||
cues = source.track_cues(planned.track_id)
|
||||
except Exception: # noqa: BLE001 — prep is a bonus, not a blocker
|
||||
log.debug("could not read cues for %s", planned.track_id, exc_info=True)
|
||||
items.append(NewTrack(track=track, audio_path=target, cues=cues))
|
||||
|
||||
new_ids = dest.add_tracks(items)
|
||||
by_source = {
|
||||
planned.track_id: new_id
|
||||
for (planned, _), new_id in zip(copied, new_ids)
|
||||
}
|
||||
by_source.update({t.track_id: t.existing_id for t in plan.existing})
|
||||
# Every planned track's id in the destination, in plan order.
|
||||
all_ids = [by_source[t.track_id] for t in plan.tracks if t.track_id in by_source]
|
||||
|
||||
if into_playlist is not None:
|
||||
handle.progress(message="Adding to the playlist…")
|
||||
current = dest.playlist_entries(into_playlist) or []
|
||||
have = set(current)
|
||||
dest.set_playlist_entries(
|
||||
into_playlist, current + [i for i in all_ids if i not in have]
|
||||
)
|
||||
|
||||
playlists_made = _rebuild_playlists(
|
||||
source, dest, plan, by_source, folder_name, handle
|
||||
)
|
||||
|
||||
handle.progress(message="Saving…")
|
||||
outcome, _commit = _save(dest)
|
||||
return {
|
||||
"tracks": len(new_ids),
|
||||
"track_ids": all_ids,
|
||||
"already_held": len(plan.existing),
|
||||
"playlists": playlists_made,
|
||||
"skipped_missing": len([t for t in plan.tracks if t.missing]),
|
||||
"destination": str(destination) if destination else None,
|
||||
"summary": getattr(outcome, "summary", ""),
|
||||
}
|
||||
except BaseException:
|
||||
# A cancelled or failed import must not leave orphaned audio behind: the
|
||||
# library was never written, so those files reference nothing.
|
||||
for target in created:
|
||||
try:
|
||||
target.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
log.debug("could not clean up %s", target, exc_info=True)
|
||||
raise
|
||||
|
||||
|
||||
def _save(dest):
|
||||
"""Save through AppState so the version-history commit is not skipped."""
|
||||
from .app_state import STATE
|
||||
|
||||
if STATE.adapter is dest:
|
||||
return STATE.save()
|
||||
return dest.save(), None
|
||||
|
||||
|
||||
def _rebuild_playlists(source, dest, plan, by_source, folder_name, handle) -> int:
|
||||
"""Recreate the source's playlists in the destination.
|
||||
|
||||
They go into ONE folder named after the drive, so a re-import is easy to find
|
||||
and easy to delete, and the collection's root does not accumulate. A platform
|
||||
that cannot make folders puts them at the root instead — the capability says
|
||||
which, rather than this guessing.
|
||||
"""
|
||||
if not plan.playlists:
|
||||
return 0
|
||||
parent = None
|
||||
if folder_name and dest.capabilities().playlists.folders:
|
||||
try:
|
||||
parent = dest.create_folder(folder_name)
|
||||
except Exception: # noqa: BLE001 — a missing folder is not worth failing over
|
||||
log.debug("could not create folder %r", folder_name, exc_info=True)
|
||||
|
||||
made = 0
|
||||
for node_id, name in plan.playlists:
|
||||
handle.progress(message=f"Recreating playlist {name}")
|
||||
source_tracks = source.playlist_tracks(node_id) or []
|
||||
ids = [by_source[t.id] for t in source_tracks if t.id in by_source]
|
||||
if not ids:
|
||||
continue
|
||||
new_id = dest.create_playlist(name, parent)
|
||||
dest.set_playlist_entries(new_id, ids)
|
||||
made += 1
|
||||
return made
|
||||
@@ -0,0 +1,176 @@
|
||||
"""Long-running operations, with progress and a working cancel.
|
||||
|
||||
Every route in this app is a synchronous `def` that finishes in milliseconds,
|
||||
which has been fine while every operation was "edit an object in memory". Import
|
||||
is not: it copies audio off a USB stick, and a DJ's stick is tens of gigabytes.
|
||||
A synchronous copy would hold an HTTP request open for minutes and give the user
|
||||
no way to stop it or see how far it had got.
|
||||
|
||||
So this is the smallest thing that fixes that, and deliberately no more:
|
||||
|
||||
* a **thread per job** — the work is IO-bound (file copying), so threads are
|
||||
the right shape and asyncio would mean rewriting the routes;
|
||||
* **polling**, not SSE or websockets — a progress bar wants a number a few
|
||||
times a second, and adding a streaming transport to an app that has none is
|
||||
a lot of new failure modes for a smoother number;
|
||||
* **cooperative cancel** — the job checks a flag between units of work. There
|
||||
is no way to kill a thread in Python, and there should not be: a copy
|
||||
interrupted mid-file needs to clean up after itself, which it can only do if
|
||||
it is the one deciding to stop.
|
||||
|
||||
Jobs are kept in memory and die with the process. That is correct rather than
|
||||
lazy: a job describes work happening right now, and a "running" job whose thread
|
||||
no longer exists would be a lie that survived a restart.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Callable, Literal
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
JobState = Literal["running", "done", "failed", "cancelled"]
|
||||
|
||||
# Finished jobs are kept so a client that polls a moment late still sees the
|
||||
# result. Bounded, so a long session cannot grow this without limit.
|
||||
MAX_FINISHED = 20
|
||||
|
||||
|
||||
@dataclass
|
||||
class Job:
|
||||
id: str
|
||||
kind: str
|
||||
state: JobState = "running"
|
||||
# `total` is 0 until the job knows its size — a copy has to scan first — and
|
||||
# the UI is expected to show an indeterminate bar until it is positive.
|
||||
total: int = 0
|
||||
done: int = 0
|
||||
message: str = ""
|
||||
result: Any = None
|
||||
error: str | None = None
|
||||
started_at: float = field(default_factory=time.time)
|
||||
finished_at: float | None = None
|
||||
_cancel: threading.Event = field(default_factory=threading.Event, repr=False)
|
||||
|
||||
@property
|
||||
def finished(self) -> bool:
|
||||
return self.state in ("done", "failed", "cancelled")
|
||||
|
||||
def as_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"kind": self.kind,
|
||||
"state": self.state,
|
||||
"total": self.total,
|
||||
"done": self.done,
|
||||
"message": self.message,
|
||||
"result": self.result,
|
||||
"error": self.error,
|
||||
"started_at": self.started_at,
|
||||
"finished_at": self.finished_at,
|
||||
}
|
||||
|
||||
|
||||
class JobHandle:
|
||||
"""What the running work is given: report progress, ask whether to stop.
|
||||
|
||||
Deliberately the only thing a job function touches, so the work cannot reach
|
||||
into the registry and, say, mark itself done — that is the registry's call,
|
||||
and it is what makes "the state always reflects the thread" true.
|
||||
"""
|
||||
|
||||
def __init__(self, job: Job) -> None:
|
||||
self._job = job
|
||||
|
||||
def progress(self, done: int | None = None, total: int | None = None,
|
||||
message: str | None = None) -> None:
|
||||
if done is not None:
|
||||
self._job.done = done
|
||||
if total is not None:
|
||||
self._job.total = total
|
||||
if message is not None:
|
||||
self._job.message = message
|
||||
|
||||
@property
|
||||
def cancelled(self) -> bool:
|
||||
return self._job._cancel.is_set()
|
||||
|
||||
def raise_if_cancelled(self) -> None:
|
||||
if self.cancelled:
|
||||
raise JobCancelled()
|
||||
|
||||
|
||||
class JobCancelled(Exception):
|
||||
"""Raised inside a job when the user asked it to stop.
|
||||
|
||||
An exception rather than a return value so a job can unwind through whatever
|
||||
it was doing — and so its cleanup can be an ordinary `finally`.
|
||||
"""
|
||||
|
||||
|
||||
class JobRegistry:
|
||||
def __init__(self) -> None:
|
||||
self._jobs: dict[str, Job] = {}
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def submit(self, kind: str, fn: Callable[[JobHandle], Any]) -> Job:
|
||||
job = Job(id=uuid.uuid4().hex, kind=kind)
|
||||
with self._lock:
|
||||
self._jobs[job.id] = job
|
||||
self._prune()
|
||||
|
||||
def run() -> None:
|
||||
handle = JobHandle(job)
|
||||
try:
|
||||
job.result = fn(handle)
|
||||
job.state = "cancelled" if handle.cancelled else "done"
|
||||
except JobCancelled:
|
||||
job.state = "cancelled"
|
||||
except Exception as ex: # noqa: BLE001 — surfaced to the client
|
||||
log.exception("job %s (%s) failed", job.id, kind)
|
||||
job.state = "failed"
|
||||
job.error = str(ex) or ex.__class__.__name__
|
||||
finally:
|
||||
job.finished_at = time.time()
|
||||
|
||||
threading.Thread(target=run, name=f"job-{kind}-{job.id[:8]}", daemon=True).start()
|
||||
return job
|
||||
|
||||
def get(self, job_id: str) -> Job | None:
|
||||
with self._lock:
|
||||
return self._jobs.get(job_id)
|
||||
|
||||
def cancel(self, job_id: str) -> bool:
|
||||
"""Ask a job to stop. Returns False for an unknown or finished job.
|
||||
|
||||
Only a REQUEST: the job stops at its next checkpoint and cleans up after
|
||||
itself, so the state does not become "cancelled" here.
|
||||
"""
|
||||
job = self.get(job_id)
|
||||
if job is None or job.finished:
|
||||
return False
|
||||
job._cancel.set()
|
||||
return True
|
||||
|
||||
def active(self, kind: str | None = None) -> list[Job]:
|
||||
with self._lock:
|
||||
return [
|
||||
j for j in self._jobs.values()
|
||||
if not j.finished and (kind is None or j.kind == kind)
|
||||
]
|
||||
|
||||
def _prune(self) -> None:
|
||||
"""Drop the oldest finished jobs. Caller holds the lock."""
|
||||
finished = sorted(
|
||||
(j for j in self._jobs.values() if j.finished),
|
||||
key=lambda j: j.finished_at or 0.0,
|
||||
)
|
||||
for job in finished[: max(0, len(finished) - MAX_FINISHED)]:
|
||||
self._jobs.pop(job.id, None)
|
||||
|
||||
|
||||
JOBS = JobRegistry()
|
||||
@@ -0,0 +1,208 @@
|
||||
"""A stable identity for a library, surviving a move or a rename.
|
||||
|
||||
Everything Konduktor persists ABOUT a library currently keys off its OS path:
|
||||
`history` hashes the resolved path to pick a repo directory, `prefs` stores
|
||||
`path_mappings` and `last_collection` as path strings. That is fine for things
|
||||
the user can shrug at losing. It is not fine for **export sets**, which are
|
||||
curated work holding references into one specific library — moving a collection
|
||||
would silently orphan every one of them.
|
||||
|
||||
## How identity survives a move
|
||||
|
||||
Two halves, and only the first is authoritative:
|
||||
|
||||
1. **A sidecar beside the library** — `.konduktor-library.json`, holding a random
|
||||
id. It lives in the library's own folder, so it MOVES WITH IT. Rename the
|
||||
folder, drag it to another disk, restore it from a backup: same id.
|
||||
2. **A registry in app-data** — `libraries.json`, mapping id → last known path,
|
||||
platform and label. Derived and disposable; it exists so Konduktor can answer
|
||||
"which libraries do I know about" without touching every disk, and it is
|
||||
rebuilt from the sidecar whenever a library is opened.
|
||||
|
||||
The id is **random**, not derived. Deriving it from the path defeats the whole
|
||||
purpose, and deriving it from the contents would change on every save.
|
||||
|
||||
## When a sidecar cannot be written
|
||||
|
||||
A removable or read-only library gets no sidecar — writing to a user's USB stick
|
||||
to satisfy Konduktor's bookkeeping is not a trade worth making. Those fall back
|
||||
to a **path-derived** id, which is stable for as long as the drive mounts at the
|
||||
same place and is marked as such so nothing mistakes it for the durable kind.
|
||||
|
||||
Writing beside the user's library is not a new intrusion: saves already create a
|
||||
`backups/` folder there. The sidecar is a hidden dotfile, so it does not show up
|
||||
in the app's own file browser, which skips dotfiles.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from . import paths
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
SIDECAR_NAME = ".konduktor-library.json"
|
||||
_REGISTRY_NAME = "libraries.json"
|
||||
|
||||
# Path-derived ids carry this prefix so "durable" and "only as stable as this
|
||||
# mount point" can never be confused — they behave differently on a move, and a
|
||||
# caller that cares can ask.
|
||||
VOLATILE_PREFIX = "path-"
|
||||
|
||||
|
||||
def _registry_path() -> Path:
|
||||
return paths.app_data_dir() / _REGISTRY_NAME
|
||||
|
||||
|
||||
def _sidecar_path(library_path: Path) -> Path:
|
||||
"""Where the sidecar lives for a library.
|
||||
|
||||
A library is a FILE on some platforms and a DIRECTORY on others, so the
|
||||
sidecar goes inside a directory library and beside a file one — either way,
|
||||
in the folder that travels with it.
|
||||
"""
|
||||
library_path = Path(library_path)
|
||||
try:
|
||||
folder = library_path if library_path.is_dir() else library_path.parent
|
||||
except OSError:
|
||||
folder = library_path.parent
|
||||
return folder / SIDECAR_NAME
|
||||
|
||||
|
||||
def _sidecar_key(library_path: Path) -> str:
|
||||
"""Which entry in the sidecar belongs to this library.
|
||||
|
||||
One sidecar per FOLDER, keyed by filename, because a folder can legitimately
|
||||
hold more than one library — a `collection.nml` beside an older one someone
|
||||
kept. A single id per folder would hand both the same identity and, once
|
||||
export sets exist, show one library's curated sets against another.
|
||||
|
||||
A directory library is the folder itself, so it keys on ".".
|
||||
"""
|
||||
library_path = Path(library_path)
|
||||
try:
|
||||
return "." if library_path.is_dir() else library_path.name
|
||||
except OSError:
|
||||
return library_path.name
|
||||
|
||||
|
||||
def _volatile_id(library_path: Path) -> str:
|
||||
digest = hashlib.sha256(str(Path(library_path).resolve()).encode()).hexdigest()
|
||||
return f"{VOLATILE_PREFIX}{digest[:16]}"
|
||||
|
||||
|
||||
def is_durable(library_id: str) -> bool:
|
||||
"""Whether this id survives the library being moved."""
|
||||
return not library_id.startswith(VOLATILE_PREFIX)
|
||||
|
||||
|
||||
# ---- the registry ------------------------------------------------------------
|
||||
|
||||
|
||||
def known() -> dict[str, dict]:
|
||||
"""Every library Konduktor has seen, by id. Derived data — safe to lose."""
|
||||
data = paths.read_json(_registry_path(), {})
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def describe(library_id: str) -> dict | None:
|
||||
return known().get(library_id)
|
||||
|
||||
|
||||
def _remember(library_id: str, library_path: Path, platform: str | None, label: str | None) -> None:
|
||||
registry = known()
|
||||
entry = registry.get(library_id) or {}
|
||||
entry.update(
|
||||
{
|
||||
"path": str(library_path),
|
||||
"platform": platform or entry.get("platform"),
|
||||
"label": label or entry.get("label") or Path(library_path).name,
|
||||
"last_seen": time.time(),
|
||||
}
|
||||
)
|
||||
entry.setdefault("first_seen", entry["last_seen"])
|
||||
registry[library_id] = entry
|
||||
try:
|
||||
paths.write_json(_registry_path(), registry)
|
||||
except OSError:
|
||||
# The registry is a convenience index; the sidecar is the source of
|
||||
# truth, so failing to write it must not fail opening a library.
|
||||
log.warning("could not update the library registry", exc_info=True)
|
||||
|
||||
|
||||
def forget(library_id: str) -> None:
|
||||
"""Drop a library from the registry. Does NOT touch its sidecar."""
|
||||
registry = known()
|
||||
if registry.pop(library_id, None) is not None:
|
||||
try:
|
||||
paths.write_json(_registry_path(), registry)
|
||||
except OSError:
|
||||
log.warning("could not update the library registry", exc_info=True)
|
||||
|
||||
|
||||
# ---- identity ----------------------------------------------------------------
|
||||
|
||||
|
||||
def for_path(
|
||||
library_path: Path,
|
||||
*,
|
||||
platform: str | None = None,
|
||||
label: str | None = None,
|
||||
sidecar: bool = True,
|
||||
) -> str:
|
||||
"""This library's id, creating and recording one on first sight.
|
||||
|
||||
`sidecar=False` for a library Konduktor should not write next to — a
|
||||
removable drive, or one opened read-only. Those get a path-derived id.
|
||||
"""
|
||||
library_path = Path(library_path)
|
||||
found = read_sidecar(library_path) if sidecar else None
|
||||
|
||||
if found is None and sidecar:
|
||||
found = uuid.uuid4().hex
|
||||
if not _write_sidecar(library_path, found):
|
||||
found = None # unwritable, e.g. a locked or read-only folder
|
||||
|
||||
library_id = found or _volatile_id(library_path)
|
||||
_remember(library_id, library_path, platform, label)
|
||||
return library_id
|
||||
|
||||
|
||||
def read_sidecar(library_path: Path) -> str | None:
|
||||
"""The id recorded beside this library, or None."""
|
||||
entry = _sidecar_entries(library_path).get(_sidecar_key(library_path))
|
||||
if isinstance(entry, dict):
|
||||
value = entry.get("id")
|
||||
if isinstance(value, str) and value:
|
||||
return value
|
||||
return None
|
||||
|
||||
|
||||
def _sidecar_entries(library_path: Path) -> dict:
|
||||
data = paths.read_json(_sidecar_path(library_path), {})
|
||||
entries = data.get("libraries") if isinstance(data, dict) else None
|
||||
return entries if isinstance(entries, dict) else {}
|
||||
|
||||
|
||||
def _write_sidecar(library_path: Path, library_id: str) -> bool:
|
||||
"""Record an id beside the library. False when the location refuses it."""
|
||||
entries = _sidecar_entries(library_path)
|
||||
entries[_sidecar_key(library_path)] = {"id": library_id, "created": time.time()}
|
||||
try:
|
||||
paths.write_json(
|
||||
_sidecar_path(library_path),
|
||||
{
|
||||
# Only so a human finding this file knows what it is for. Never
|
||||
# read back: the path is exactly what must not be trusted here.
|
||||
"note": "Konduktor library ids. Keep this beside the library.",
|
||||
"libraries": entries,
|
||||
},
|
||||
)
|
||||
return True
|
||||
except OSError:
|
||||
log.info("no sidecar for %s — falling back to a path-derived id", library_path)
|
||||
return False
|
||||
+1316
-304
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,68 @@
|
||||
"""Resolves the app's per-OS, user-writable data directory.
|
||||
|
||||
Everything Konduktor persists that is NOT part of the user's collection lives
|
||||
here: `userprefs.json` and the per-collection version-history git repos. It must
|
||||
be a real writable location — the package-relative path prefs.py used to use is
|
||||
read-only/ephemeral in a frozen PyInstaller build (`sys._MEIPASS`).
|
||||
|
||||
Resolution order:
|
||||
1. ``KONDUKTOR_DATA_DIR`` env var (tests point this at a temp dir to stay
|
||||
isolated from the real user data).
|
||||
2. platformdirs' per-OS user-data dir
|
||||
(~/Library/Application Support/Konduktor, %LOCALAPPDATA%\\Konduktor, …).
|
||||
|
||||
Best-effort: any failure to create the dir degrades to returning the path
|
||||
anyway; callers already treat all data I/O as best-effort.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import platformdirs
|
||||
|
||||
_APP_NAME = "Konduktor"
|
||||
_APP_AUTHOR = "Liquid Ice Studios"
|
||||
|
||||
|
||||
def write_json(path: Path, data) -> None:
|
||||
"""Write JSON so a crash mid-write cannot leave a truncated file.
|
||||
|
||||
Deliberately NOT best-effort, unlike `prefs.save_prefs`: this is for data the
|
||||
user CURATED — export sets, library identity — where losing it is real work
|
||||
lost, not a forgotten window size. Failures raise so a caller can say so.
|
||||
|
||||
Written to a temp file in the SAME directory and then `os.replace`d, which is
|
||||
atomic on POSIX and on Windows: a reader sees either the whole old file or
|
||||
the whole new one, never half of either.
|
||||
"""
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = path.with_name(f".{path.name}.tmp{os.getpid()}")
|
||||
try:
|
||||
tmp.write_text(json.dumps(data, indent=2))
|
||||
os.replace(tmp, path)
|
||||
finally:
|
||||
try:
|
||||
tmp.unlink()
|
||||
except OSError:
|
||||
pass # already replaced, which is the success path
|
||||
|
||||
|
||||
def read_json(path: Path, default=None):
|
||||
"""Read JSON, or `default` if it is missing or unreadable."""
|
||||
try:
|
||||
return json.loads(path.read_text())
|
||||
except (OSError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def app_data_dir() -> Path:
|
||||
"""The user-writable directory for Konduktor's persisted app data."""
|
||||
override = os.environ.get("KONDUKTOR_DATA_DIR")
|
||||
base = Path(override) if override else Path(platformdirs.user_data_dir(_APP_NAME, _APP_AUTHOR))
|
||||
try:
|
||||
base.mkdir(parents=True, exist_ok=True)
|
||||
except OSError:
|
||||
pass # non-fatal — callers handle missing/unwritable data dirs
|
||||
return base
|
||||
@@ -1,674 +0,0 @@
|
||||
"""Editable playlist store backed by the traktor-nml-utils dataclass model.
|
||||
|
||||
Design goals:
|
||||
* minimal diff — unedited playlists must serialize byte-for-byte as Traktor
|
||||
wrote them (the xsdata serializer used by the library reproduces Traktor's
|
||||
exact formatting; lxml does not),
|
||||
* surgical — the ~14 MB COLLECTION stays byte-identical (we splice only the
|
||||
<PLAYLISTS> span back into the original file bytes),
|
||||
* safe — a timestamped .bak is written before every save.
|
||||
|
||||
We edit the parsed dataclass model in memory (create/rename/delete/set-entries),
|
||||
then on save render the full model, extract just the freshly-rendered
|
||||
<PLAYLISTS>…</PLAYLISTS> span, and splice it into the untouched original bytes.
|
||||
|
||||
Playlists are identified by their stable UUID; folders by a synthetic path id
|
||||
(``fld:<name>/<name>``). Smart playlists are read-only.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
import threading
|
||||
import time
|
||||
import uuid as uuidlib
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from traktor_nml_utils import (
|
||||
TraktorCollection,
|
||||
format_traktor_layout,
|
||||
restore_traktor_float_format,
|
||||
)
|
||||
from traktor_nml_utils.models.collection import (
|
||||
Albumtype,
|
||||
CueV2Type,
|
||||
Entrytype,
|
||||
GridType,
|
||||
Infotype,
|
||||
Nodetype,
|
||||
Playlisttype,
|
||||
Primarykeytype,
|
||||
Subnodestype,
|
||||
Tempotype,
|
||||
)
|
||||
from xsdata.formats.dataclass.serializers import XmlSerializer
|
||||
|
||||
from .path_mapping import PathMapping
|
||||
from .schemas import PlaylistNode
|
||||
|
||||
|
||||
class PlaylistError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class FileTagResult:
|
||||
track_id: str
|
||||
file: str
|
||||
ok: bool
|
||||
status: str # "written" | "file-not-found" | "unsupported-format" | "error"
|
||||
detail: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class SaveOutcome:
|
||||
backup: Path
|
||||
tag_results: list[FileTagResult]
|
||||
|
||||
|
||||
class PlaylistStore:
|
||||
def __init__(self, nml_path: Path):
|
||||
self.nml_path = Path(nml_path)
|
||||
self._lock = threading.RLock()
|
||||
self.dirty = False
|
||||
# Active OS-path prefix remapping (empty = identity). Survives _load().
|
||||
self._path_mapping = PathMapping()
|
||||
self._load()
|
||||
|
||||
# ---- load ----------------------------------------------------------
|
||||
def _load(self) -> None:
|
||||
self._collection = TraktorCollection(path=self.nml_path)
|
||||
self._nml = self._collection.nml
|
||||
# Index collection entries by their Traktor primary key (volume+dir+file)
|
||||
# so track-metadata edits can find their ENTRY in O(1).
|
||||
self._entry_by_key: dict[str, Entrytype] = {}
|
||||
for e in self._nml.collection.entry:
|
||||
loc = e.location
|
||||
if loc:
|
||||
key = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}"
|
||||
self._entry_by_key[key] = e
|
||||
# track_id -> set of field names edited this session (drives file-tag sync)
|
||||
self._track_edits: dict[str, set[str]] = {}
|
||||
# track_id -> (image_bytes, mime) of staged replacement cover art
|
||||
self._track_art: dict[str, tuple[bytes, str]] = {}
|
||||
self.dirty = False
|
||||
|
||||
def _root(self) -> Nodetype:
|
||||
node = self._nml.playlists.node if self._nml.playlists else None
|
||||
if node is None:
|
||||
raise PlaylistError("PLAYLISTS has no root NODE")
|
||||
return node
|
||||
|
||||
@staticmethod
|
||||
def _children(node: Nodetype) -> list[Nodetype]:
|
||||
return list(node.subnodes.node) if node.subnodes else []
|
||||
|
||||
# ---- tree walking --------------------------------------------------
|
||||
def tree(self) -> list[PlaylistNode]:
|
||||
with self._lock:
|
||||
return [self._to_model(c, []) for c in self._children(self._root())]
|
||||
|
||||
def _to_model(self, node: Nodetype, parent_path: list[str]) -> PlaylistNode:
|
||||
ntype = node.type or "FOLDER"
|
||||
name = node.name or "(unnamed)"
|
||||
if ntype == "PLAYLIST" or node.playlist is not None:
|
||||
pl = node.playlist
|
||||
keys = self._entry_keys_of(pl) if pl is not None else []
|
||||
return PlaylistNode(
|
||||
id=pl.uuid if pl and pl.uuid else name,
|
||||
name=name,
|
||||
type="PLAYLIST",
|
||||
uuid=pl.uuid if pl else None,
|
||||
count=len(keys),
|
||||
)
|
||||
if ntype == "SMARTLIST" or node.smartplaylist is not None:
|
||||
return PlaylistNode(
|
||||
id="sl:" + "/".join(parent_path + [name]), name=name, type="SMARTLIST"
|
||||
)
|
||||
path = parent_path + [name]
|
||||
return PlaylistNode(
|
||||
id="fld:" + "/".join(path),
|
||||
name=name,
|
||||
type="FOLDER",
|
||||
children=[self._to_model(c, path) for c in self._children(node)],
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _entry_keys_of(pl: Playlisttype) -> list[str]:
|
||||
return [
|
||||
e.primarykey.key
|
||||
for e in (pl.entry or [])
|
||||
if e.primarykey and e.primarykey.key
|
||||
]
|
||||
|
||||
# ---- lookups -------------------------------------------------------
|
||||
def _iter_nodes(self, node: Nodetype):
|
||||
yield node
|
||||
for c in self._children(node):
|
||||
yield from self._iter_nodes(c)
|
||||
|
||||
def _find_playlist_node(self, playlist_uuid: str) -> Nodetype | None:
|
||||
for n in self._iter_nodes(self._root()):
|
||||
if n.playlist is not None and n.playlist.uuid == playlist_uuid:
|
||||
return n
|
||||
return None
|
||||
|
||||
def _find_parent_of(self, target: Nodetype) -> Nodetype | None:
|
||||
for n in self._iter_nodes(self._root()):
|
||||
if n.subnodes and target in n.subnodes.node:
|
||||
return n
|
||||
return None
|
||||
|
||||
def _find_folder(self, folder_id: str | None) -> Nodetype:
|
||||
root = self._root()
|
||||
if folder_id in (None, "", "fld:"):
|
||||
return root
|
||||
if not folder_id.startswith("fld:"):
|
||||
raise PlaylistError(f"Not a folder id: {folder_id}")
|
||||
cur = root
|
||||
for name in folder_id[len("fld:") :].split("/"):
|
||||
match = next(
|
||||
(
|
||||
c
|
||||
for c in self._children(cur)
|
||||
if (c.type or "FOLDER") == "FOLDER" and c.name == name
|
||||
),
|
||||
None,
|
||||
)
|
||||
if match is None:
|
||||
raise PlaylistError(f"Folder not found: {folder_id}")
|
||||
cur = match
|
||||
return cur
|
||||
|
||||
def entry_keys(self, playlist_uuid: str) -> list[str] | None:
|
||||
with self._lock:
|
||||
node = self._find_playlist_node(playlist_uuid)
|
||||
return None if node is None else self._entry_keys_of(node.playlist)
|
||||
|
||||
# ---- edits ---------------------------------------------------------
|
||||
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
|
||||
with self._lock:
|
||||
folder = self._find_folder(parent_id)
|
||||
if folder.subnodes is None:
|
||||
folder.subnodes = Subnodestype(node=[], count=0)
|
||||
new_uuid = uuidlib.uuid4().hex
|
||||
node = Nodetype(
|
||||
type="PLAYLIST",
|
||||
name=name,
|
||||
playlist=Playlisttype(entry=[], entries=0, type="LIST", uuid=new_uuid),
|
||||
)
|
||||
folder.subnodes.node.append(node)
|
||||
folder.subnodes.count = len(folder.subnodes.node)
|
||||
self.dirty = True
|
||||
return new_uuid
|
||||
|
||||
def rename_playlist(self, playlist_uuid: str, name: str) -> None:
|
||||
with self._lock:
|
||||
node = self._find_playlist_node(playlist_uuid)
|
||||
if node is None:
|
||||
raise PlaylistError(f"Playlist not found: {playlist_uuid}")
|
||||
node.name = name
|
||||
self.dirty = True
|
||||
|
||||
def delete_playlist(self, playlist_uuid: str) -> None:
|
||||
with self._lock:
|
||||
node = self._find_playlist_node(playlist_uuid)
|
||||
if node is None:
|
||||
raise PlaylistError(f"Playlist not found: {playlist_uuid}")
|
||||
parent = self._find_parent_of(node)
|
||||
if parent is None:
|
||||
raise PlaylistError("Cannot delete a top-level node")
|
||||
parent.subnodes.node.remove(node)
|
||||
parent.subnodes.count = len(parent.subnodes.node)
|
||||
self.dirty = True
|
||||
|
||||
def set_entries(self, playlist_uuid: str, entries: list[tuple[str, str]]) -> None:
|
||||
with self._lock:
|
||||
node = self._find_playlist_node(playlist_uuid)
|
||||
if node is None:
|
||||
raise PlaylistError(f"Playlist not found: {playlist_uuid}")
|
||||
pl = node.playlist
|
||||
pl.entry = [
|
||||
Entrytype(primarykey=Primarykeytype(type=ptype or "TRACK", key=key))
|
||||
for key, ptype in entries
|
||||
]
|
||||
pl.entries = len(pl.entry)
|
||||
self.dirty = True
|
||||
|
||||
# ---- track metadata editing ---------------------------------------
|
||||
# Safe, free-text-ish fields only. Deliberately NOT editable here: file path
|
||||
# (it's the primary key), bpm/key (audio/grid territory), and read-only info
|
||||
# like bitrate/playcount.
|
||||
_INFO_FIELDS = {"genre", "label", "remixer", "producer", "comment", "mix", "release_date"}
|
||||
EDITABLE_FIELDS = {"title", "artist", "album", "rating"} | _INFO_FIELDS
|
||||
|
||||
def set_track_metadata(self, track_id: str, fields: dict) -> None:
|
||||
with self._lock:
|
||||
entry = self._entry_by_key.get(track_id)
|
||||
if entry is None:
|
||||
raise PlaylistError(f"Track not found: {track_id}")
|
||||
if entry.info is None:
|
||||
entry.info = Infotype()
|
||||
for k, v in fields.items():
|
||||
if k in ("title", "artist"):
|
||||
setattr(entry, k, v or None)
|
||||
elif k == "album":
|
||||
if entry.album is None:
|
||||
entry.album = Albumtype()
|
||||
entry.album.title = v or None
|
||||
elif k in self._INFO_FIELDS:
|
||||
setattr(entry.info, k, v or None)
|
||||
elif k == "rating":
|
||||
stars = max(0, min(5, int(v))) if v is not None else 0
|
||||
# Traktor RANKING = stars * 51; unrated has no RANKING attr.
|
||||
entry.info.ranking = stars * 51 or None
|
||||
else:
|
||||
continue # unknown / read-only fields are ignored
|
||||
self._track_edits.setdefault(track_id, set()).add(k)
|
||||
self.dirty = True
|
||||
|
||||
def model_entry(self, track_id: str) -> Entrytype | None:
|
||||
with self._lock:
|
||||
return self._entry_by_key.get(track_id)
|
||||
|
||||
# ---- hotcues ------------------------------------------------------
|
||||
# Creatable/editable types: 0 cue, 1 fade-in, 2 fade-out, 3 load, 5 loop.
|
||||
# A loop (type 5) carries a length; the point types don't. Grid markers
|
||||
# (type 4, redefine the beatgrid) are excluded. Cues are NML-only.
|
||||
POINT_CUE_TYPES = {0, 1, 2, 3} # types the dropdown can switch between
|
||||
CREATABLE_TYPES = {0, 1, 2, 3, 5}
|
||||
|
||||
def _entry_or_raise(self, track_id: str) -> Entrytype:
|
||||
entry = self._entry_by_key.get(track_id)
|
||||
if entry is None:
|
||||
raise PlaylistError(f"Track not found: {track_id}")
|
||||
return entry
|
||||
|
||||
def set_hotcue(
|
||||
self,
|
||||
track_id: str,
|
||||
slot: int,
|
||||
start_sec: float,
|
||||
cue_type: int,
|
||||
length_sec: float = 0.0,
|
||||
name: str | None = None,
|
||||
) -> None:
|
||||
"""Create (or reposition + retype) the hotcue in `slot` at `start_sec`.
|
||||
|
||||
`length_sec` > 0 makes it a loop (used with cue_type 5). `name` sets the
|
||||
cue label on create; when unset it falls back to Traktor's "n.n."."""
|
||||
if not 0 <= slot <= 7:
|
||||
raise PlaylistError(f"Invalid hotcue slot: {slot}")
|
||||
if cue_type not in self.CREATABLE_TYPES:
|
||||
raise PlaylistError(f"Unsupported cue type: {cue_type}")
|
||||
with self._lock:
|
||||
entry = self._entry_or_raise(track_id)
|
||||
start_ms = max(0.0, start_sec * 1000.0) # Traktor stores START/LEN in ms
|
||||
len_ms = max(0.0, length_sec * 1000.0)
|
||||
existing = next(
|
||||
(c for c in (entry.cue_v2 or []) if c.hotcue == slot), None
|
||||
)
|
||||
if existing is not None:
|
||||
existing.start = start_ms
|
||||
existing.type = cue_type
|
||||
existing.len = len_ms
|
||||
else:
|
||||
if entry.cue_v2 is None:
|
||||
entry.cue_v2 = []
|
||||
entry.cue_v2.append(
|
||||
CueV2Type(
|
||||
name=name or "n.n.", # Traktor's default name for a manual cue
|
||||
displ_order=0,
|
||||
type=cue_type,
|
||||
start=start_ms,
|
||||
len=len_ms,
|
||||
repeats=-1,
|
||||
hotcue=slot,
|
||||
color=None,
|
||||
grid=None,
|
||||
)
|
||||
)
|
||||
self.dirty = True
|
||||
|
||||
def place_hotcues(
|
||||
self, track_id: str, specs: list, *, overwrite: bool = False
|
||||
) -> None:
|
||||
"""Batch-create hotcues from `specs` (each has .slot/.start/.name and
|
||||
optional .type/.length). With `overwrite` False (the default), slots that
|
||||
already hold a hotcue are skipped so hand-placed cues are never clobbered.
|
||||
Used by Auto Hotcues."""
|
||||
with self._lock:
|
||||
entry = self._entry_or_raise(track_id)
|
||||
occupied = {
|
||||
c.hotcue for c in (entry.cue_v2 or []) if c.hotcue is not None and c.hotcue >= 0
|
||||
}
|
||||
for spec in specs:
|
||||
if not overwrite and spec.slot in occupied:
|
||||
continue
|
||||
self.set_hotcue(
|
||||
track_id,
|
||||
spec.slot,
|
||||
spec.start,
|
||||
getattr(spec, "type", 0),
|
||||
getattr(spec, "length", 0.0),
|
||||
name=getattr(spec, "name", None),
|
||||
)
|
||||
|
||||
def set_hotcue_type(self, track_id: str, slot: int, cue_type: int) -> None:
|
||||
"""Change the type of the existing hotcue in `slot` (keeps its position)."""
|
||||
if cue_type not in self.POINT_CUE_TYPES:
|
||||
raise PlaylistError(f"Unsupported cue type: {cue_type}")
|
||||
with self._lock:
|
||||
entry = self._entry_or_raise(track_id)
|
||||
cue = next((c for c in (entry.cue_v2 or []) if c.hotcue == slot), None)
|
||||
if cue is None:
|
||||
raise PlaylistError(f"Hotcue {slot} is not set")
|
||||
cue.type = cue_type
|
||||
self.dirty = True
|
||||
|
||||
def delete_hotcue(self, track_id: str, slot: int) -> None:
|
||||
with self._lock:
|
||||
entry = self._entry_or_raise(track_id)
|
||||
entry.cue_v2 = [c for c in (entry.cue_v2 or []) if c.hotcue != slot]
|
||||
self.dirty = True
|
||||
|
||||
# ---- beatgrid -----------------------------------------------------
|
||||
@staticmethod
|
||||
def _grid_marker(entry: Entrytype) -> CueV2Type | None:
|
||||
return next(
|
||||
(c for c in (entry.cue_v2 or []) if getattr(c, "grid", None) is not None), None
|
||||
)
|
||||
|
||||
def set_grid(
|
||||
self, track_id: str, bpm: float | None = None, anchor_sec: float | None = None
|
||||
) -> None:
|
||||
"""Set the beatgrid tempo (TEMPO + grid marker BPM) and/or move the grid
|
||||
marker (beat 1). Creates a grid marker if the track has none."""
|
||||
with self._lock:
|
||||
entry = self._entry_or_raise(track_id)
|
||||
marker = self._grid_marker(entry)
|
||||
if bpm is not None:
|
||||
if bpm <= 0:
|
||||
raise PlaylistError(f"BPM must be positive: {bpm}")
|
||||
if entry.tempo is None:
|
||||
entry.tempo = Tempotype(bpm=bpm, bpm_quality=100.0)
|
||||
else:
|
||||
entry.tempo.bpm = bpm
|
||||
if marker is not None and marker.grid is not None:
|
||||
marker.grid.bpm = bpm
|
||||
if anchor_sec is not None:
|
||||
start_ms = max(0.0, anchor_sec * 1000.0)
|
||||
if marker is not None:
|
||||
marker.start = start_ms
|
||||
else:
|
||||
grid_bpm = bpm if bpm is not None else (entry.tempo.bpm if entry.tempo else None)
|
||||
if grid_bpm is None:
|
||||
raise PlaylistError("No BPM available to create a beatgrid")
|
||||
if entry.cue_v2 is None:
|
||||
entry.cue_v2 = []
|
||||
entry.cue_v2.append(
|
||||
CueV2Type(
|
||||
name="AutoGrid",
|
||||
displ_order=0,
|
||||
type=4,
|
||||
start=start_ms,
|
||||
len=0.0,
|
||||
repeats=-1,
|
||||
hotcue=-1,
|
||||
color=None,
|
||||
grid=GridType(bpm=grid_bpm),
|
||||
)
|
||||
)
|
||||
self.dirty = True
|
||||
|
||||
def delete_grid(self, track_id: str) -> None:
|
||||
with self._lock:
|
||||
entry = self._entry_or_raise(track_id)
|
||||
entry.cue_v2 = [
|
||||
c for c in (entry.cue_v2 or []) if getattr(c, "grid", None) is None
|
||||
]
|
||||
self.dirty = True
|
||||
|
||||
def set_lock(self, track_id: str, locked: bool) -> None:
|
||||
with self._lock:
|
||||
entry = self._entry_or_raise(track_id)
|
||||
entry.lock = 1 if locked else None
|
||||
self.dirty = True
|
||||
|
||||
# ---- cover art -----------------------------------------------------
|
||||
def set_track_art(self, track_id: str, data: bytes, mime: str) -> None:
|
||||
with self._lock:
|
||||
if track_id not in self._entry_by_key:
|
||||
raise PlaylistError(f"Track not found: {track_id}")
|
||||
self._track_art[track_id] = (data, mime)
|
||||
self.dirty = True
|
||||
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None:
|
||||
"""Set the active OS-path prefix remapping (applied at resolve time)."""
|
||||
with self._lock:
|
||||
self._path_mapping = mapping
|
||||
|
||||
def _resolve(self, loc) -> "Path | None":
|
||||
"""Resolve a LOCATION to an OS path, applying the active path mapping.
|
||||
|
||||
The single FS chokepoint: LOCATION -> `resolve_path` -> prefix remap.
|
||||
Falls back to the un-remapped path when the remapped target doesn't
|
||||
exist, so a misconfigured mapping never makes a present file unreachable.
|
||||
"""
|
||||
from . import file_tags
|
||||
|
||||
if loc is None:
|
||||
return None
|
||||
base = file_tags.resolve_path(loc.volume, loc.dir, loc.file)
|
||||
if self._path_mapping.empty:
|
||||
return base
|
||||
remapped = self._path_mapping.apply(base)
|
||||
if remapped == base:
|
||||
return base
|
||||
return remapped if remapped.exists() else base
|
||||
|
||||
def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
|
||||
"""Staged replacement if present, else the file's current embedded art."""
|
||||
from . import file_tags
|
||||
|
||||
with self._lock:
|
||||
if track_id in self._track_art:
|
||||
return self._track_art[track_id]
|
||||
entry = self._entry_by_key.get(track_id)
|
||||
if entry is None or entry.location is None:
|
||||
return None
|
||||
path = self._resolve(entry.location)
|
||||
return file_tags.read_cover(path) if path else None
|
||||
|
||||
def audio_path(self, track_id: str) -> "Path | None":
|
||||
"""Resolve a track's audio file to an OS path (for playback streaming)."""
|
||||
with self._lock:
|
||||
entry = self._entry_by_key.get(track_id)
|
||||
if entry is None or entry.location is None:
|
||||
return None
|
||||
return self._resolve(entry.location)
|
||||
|
||||
def path_prefix_suggestions(self) -> dict:
|
||||
"""Auto-suggest ``from`` prefixes by resolving every track's LOCATION and
|
||||
finding the common directory prefix per volume. Returns a ``primary``
|
||||
(the largest group's prefix) plus per-group prefixes ranked by track
|
||||
count, so the editor can prefill and offer alternatives."""
|
||||
from collections import defaultdict
|
||||
|
||||
from . import file_tags
|
||||
from .path_mapping import common_dir_prefix
|
||||
|
||||
with self._lock:
|
||||
groups: dict[str, list[str]] = defaultdict(list)
|
||||
for e in self._nml.collection.entry:
|
||||
loc = e.location
|
||||
if not loc:
|
||||
continue
|
||||
groups[loc.volume or ""].append(
|
||||
str(file_tags.resolve_path(loc.volume, loc.dir, loc.file))
|
||||
)
|
||||
ranked = sorted(
|
||||
(
|
||||
{"prefix": common_dir_prefix(paths), "count": len(paths)}
|
||||
for paths in groups.values()
|
||||
),
|
||||
key=lambda g: g["count"],
|
||||
reverse=True,
|
||||
)
|
||||
ranked = [g for g in ranked if g["prefix"]]
|
||||
return {"primary": ranked[0]["prefix"] if ranked else "", "groups": ranked[:5]}
|
||||
|
||||
def remap_preview(self, mapping: PathMapping) -> dict:
|
||||
"""How a mapping would affect the collection, without changing anything:
|
||||
total tracks, how many match ``from``, and how many exist at ``to``
|
||||
(plus a few samples). Powers the mapping editor's validation line."""
|
||||
from . import file_tags
|
||||
|
||||
with self._lock:
|
||||
total = matched = existing = 0
|
||||
samples: list[dict] = []
|
||||
for e in self._nml.collection.entry:
|
||||
loc = e.location
|
||||
if not loc:
|
||||
continue
|
||||
total += 1
|
||||
base = file_tags.resolve_path(loc.volume, loc.dir, loc.file)
|
||||
if mapping.matches(base):
|
||||
matched += 1
|
||||
target = mapping.apply(base)
|
||||
ok = target.exists()
|
||||
if ok:
|
||||
existing += 1
|
||||
if len(samples) < 5:
|
||||
samples.append({"from": str(base), "to": str(target), "exists": ok})
|
||||
return {"total": total, "matched": matched, "existing": existing, "samples": samples}
|
||||
|
||||
def remap_locations(self, mapping: PathMapping) -> int:
|
||||
"""Permanently rewrite matching track LOCATIONs to the mapping's ``to``
|
||||
prefix — a deliberate library move (write-back).
|
||||
|
||||
Because ``track_id`` IS the LOCATION key (``volume+dir+file``), every
|
||||
playlist ``PRIMARYKEY`` that referenced a moved track is rewritten too,
|
||||
so playlists keep pointing at their tracks. Non-matching entries are
|
||||
untouched. Returns the number of tracks rewritten; the caller saves.
|
||||
"""
|
||||
from . import file_tags
|
||||
from .path_mapping import os_path_to_location
|
||||
|
||||
if mapping.empty:
|
||||
return 0
|
||||
with self._lock:
|
||||
key_remap: dict[str, str] = {}
|
||||
for e in self._nml.collection.entry:
|
||||
loc = e.location
|
||||
if not loc:
|
||||
continue
|
||||
base = file_tags.resolve_path(loc.volume, loc.dir, loc.file)
|
||||
if not mapping.matches(base):
|
||||
continue
|
||||
target = mapping.apply(base)
|
||||
volume, dir_, file = os_path_to_location(target)
|
||||
old_key = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}"
|
||||
new_key = f"{volume or ''}{dir_ or ''}{file or ''}"
|
||||
if old_key == new_key:
|
||||
continue # no-op (e.g. from == to); leave byte-identical
|
||||
loc.volume, loc.dir, loc.file = volume, dir_, file
|
||||
key_remap[old_key] = new_key
|
||||
if not key_remap:
|
||||
return 0
|
||||
# Rewrite playlist entry primary keys that referenced moved tracks.
|
||||
for node in self._iter_nodes(self._root()):
|
||||
pl = node.playlist
|
||||
if pl is None or not pl.entry:
|
||||
continue
|
||||
for entry in pl.entry:
|
||||
pk = entry.primarykey
|
||||
if pk and pk.key in key_remap:
|
||||
pk.key = key_remap[pk.key]
|
||||
self.dirty = True
|
||||
return len(key_remap)
|
||||
|
||||
def _entry_field_value(self, entry: Entrytype, field: str):
|
||||
"""Read a single editable field's current value from the model, in the
|
||||
shape file_tags expects (rating as 0–5 stars)."""
|
||||
if field == "title":
|
||||
return entry.title
|
||||
if field == "artist":
|
||||
return entry.artist
|
||||
if field == "album":
|
||||
return entry.album.title if entry.album else None
|
||||
if field == "rating":
|
||||
r = entry.info.ranking if entry.info else None
|
||||
return round(r / 51) if r else 0
|
||||
return getattr(entry.info, field, None) if entry.info else None
|
||||
|
||||
def count_playlists(self) -> int:
|
||||
with self._lock:
|
||||
return sum(1 for n in self._iter_nodes(self._root()) if n.playlist is not None)
|
||||
|
||||
# ---- persistence ---------------------------------------------------
|
||||
def save(self) -> "SaveOutcome":
|
||||
with self._lock:
|
||||
backup = self._backup()
|
||||
new_data = self._render()
|
||||
tmp = self.nml_path.with_suffix(self.nml_path.suffix + ".tmp")
|
||||
tmp.write_bytes(new_data)
|
||||
tmp.replace(self.nml_path)
|
||||
# Best-effort: sync the edited fields into each edited track's file.
|
||||
tag_results = self._sync_file_tags()
|
||||
self._load() # clears dirty + _track_edits
|
||||
return SaveOutcome(backup=backup, tag_results=tag_results)
|
||||
|
||||
def _sync_file_tags(self) -> list["FileTagResult"]:
|
||||
from . import file_tags
|
||||
|
||||
results: list[FileTagResult] = []
|
||||
# Union of tracks with edited fields and/or replaced art.
|
||||
for track_id in self._track_edits.keys() | self._track_art.keys():
|
||||
entry = self._entry_by_key.get(track_id)
|
||||
if entry is None or entry.location is None:
|
||||
continue
|
||||
path = self._resolve(entry.location)
|
||||
if path is None:
|
||||
continue
|
||||
r = None
|
||||
if track_id in self._track_edits:
|
||||
meta = {f: self._entry_field_value(entry, f) for f in self._track_edits[track_id]}
|
||||
r = file_tags.write_tags(path, meta)
|
||||
if track_id in self._track_art:
|
||||
data, mime = self._track_art[track_id]
|
||||
r = file_tags.write_cover(path, data, mime)
|
||||
if r is not None:
|
||||
results.append(
|
||||
FileTagResult(
|
||||
track_id=track_id, file=str(path), ok=r.ok, status=r.status, detail=r.detail
|
||||
)
|
||||
)
|
||||
return results
|
||||
|
||||
def _render(self) -> bytes:
|
||||
"""Render the whole model exactly as the library's save() does.
|
||||
|
||||
The two post-processing steps restore Traktor's precise layout (expanded
|
||||
empty tags, 6-decimal floats, newlines), so a no-op render reproduces the
|
||||
file byte-for-byte and only the objects we actually edited (playlists
|
||||
AND/OR track entries) diff. Verified by backend/test_save_fidelity.py.
|
||||
"""
|
||||
s = XmlSerializer().render(self._nml)
|
||||
s = restore_traktor_float_format(s, self._nml)
|
||||
s = format_traktor_layout(s)
|
||||
return s.encode("utf-8")
|
||||
|
||||
def _backup(self) -> Path:
|
||||
# Backups live in a `backups/` folder next to the collection, not beside
|
||||
# the file itself (keeps the collection's directory clean).
|
||||
stamp = time.strftime("%Y%m%d-%H%M%S", time.localtime())
|
||||
backup_dir = self.nml_path.parent / "backups"
|
||||
backup_dir.mkdir(exist_ok=True)
|
||||
backup = backup_dir / f"{self.nml_path.name}.{stamp}.bak"
|
||||
n = 1
|
||||
while backup.exists():
|
||||
backup = backup_dir / f"{self.nml_path.name}.{stamp}-{n}.bak"
|
||||
n += 1
|
||||
shutil.copy2(self.nml_path, backup)
|
||||
return backup
|
||||
@@ -1,20 +1,35 @@
|
||||
"""Tiny persisted user-preferences store.
|
||||
|
||||
Kept as a self-contained JSON file that travels with the app (resolved relative
|
||||
to this package, not a per-OS config dir) so it works the same on every platform
|
||||
and when the app is moved. Best-effort: any I/O error degrades to "no prefs".
|
||||
A self-contained JSON file in the app's per-OS user-writable data dir (see
|
||||
``paths.app_data_dir``) so it survives a frozen/packaged build and works the same
|
||||
on every platform. Best-effort: any I/O error degrades to "no prefs".
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
# backend/userprefs.json — one level up from the package (konduktor/).
|
||||
_PREFS_PATH = Path(__file__).resolve().parent.parent / "userprefs.json"
|
||||
from . import paths
|
||||
|
||||
# userprefs.json in the app-data dir. Older versions kept it package-relative
|
||||
# (backend/userprefs.json); _migrate_legacy() copies that in once on first use.
|
||||
_PREFS_PATH = paths.app_data_dir() / "userprefs.json"
|
||||
_LEGACY_PREFS_PATH = Path(__file__).resolve().parent.parent / "userprefs.json"
|
||||
|
||||
|
||||
def _migrate_legacy() -> None:
|
||||
"""One-time: if the new file is absent but a legacy package-relative one
|
||||
exists, copy it into the app-data dir. Best-effort."""
|
||||
try:
|
||||
if not _PREFS_PATH.exists() and _LEGACY_PREFS_PATH.exists():
|
||||
_PREFS_PATH.write_bytes(_LEGACY_PREFS_PATH.read_bytes())
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def load_prefs() -> dict:
|
||||
try:
|
||||
_migrate_legacy()
|
||||
data = json.loads(_PREFS_PATH.read_text())
|
||||
return data if isinstance(data, dict) else {}
|
||||
except (OSError, ValueError):
|
||||
@@ -66,12 +81,36 @@ def set_path_mapping(
|
||||
save_prefs(prefs)
|
||||
|
||||
|
||||
def get_last_collection() -> str | None:
|
||||
val = load_prefs().get("last_collection")
|
||||
def get_last_collection(platform: str | None = None) -> str | None:
|
||||
"""The last library opened — overall, or on one platform.
|
||||
|
||||
Per-platform because the picker asks which platform FIRST: offering a
|
||||
Rekordbox ``master.db`` under "Open last" to someone who just chose Traktor
|
||||
is an offer that cannot be taken. A platform with no record returns None
|
||||
rather than falling back to the global one, for the same reason.
|
||||
|
||||
The flat ``last_collection`` stays: it is the global answer, and it is what
|
||||
libraries opened before this existed are recorded in.
|
||||
"""
|
||||
prefs = load_prefs()
|
||||
if platform:
|
||||
by_platform = prefs.get("last_collection_by_platform")
|
||||
if isinstance(by_platform, dict):
|
||||
val = by_platform.get(platform)
|
||||
return val if isinstance(val, str) else None
|
||||
return None
|
||||
val = prefs.get("last_collection")
|
||||
return val if isinstance(val, str) else None
|
||||
|
||||
|
||||
def set_last_collection(path: str) -> None:
|
||||
def set_last_collection(path: str, platform: str | None = None) -> None:
|
||||
"""Record a library as the last opened, globally and for its platform."""
|
||||
prefs = load_prefs()
|
||||
prefs["last_collection"] = path
|
||||
if platform:
|
||||
by_platform = prefs.get("last_collection_by_platform")
|
||||
if not isinstance(by_platform, dict):
|
||||
by_platform = {}
|
||||
by_platform[platform] = path
|
||||
prefs["last_collection_by_platform"] = by_platform
|
||||
save_prefs(prefs)
|
||||
+308
-137
@@ -1,89 +1,11 @@
|
||||
"""API response models (Pydantic)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class Track(BaseModel):
|
||||
"""A single track, flattened from a Traktor collection ENTRY."""
|
||||
|
||||
id: str # primary key: "<VOLUME><DIR><FILE>", used to join playlist entries
|
||||
artist: str | None = None
|
||||
title: str | None = None
|
||||
album: str | None = None
|
||||
genre: str | None = None
|
||||
label: str | None = None
|
||||
remixer: str | None = None
|
||||
producer: str | None = None
|
||||
mix: str | None = None
|
||||
comment: str | None = None
|
||||
bpm: float | None = None
|
||||
key: str | None = None # Traktor display key, e.g. "10m"
|
||||
rating: int = 0 # 0-5 stars (derived from RANKING/51)
|
||||
playcount: int | None = None
|
||||
length: int | None = None # seconds
|
||||
bitrate: int | None = None
|
||||
import_date: str | None = None
|
||||
last_played: str | None = None
|
||||
release_date: str | None = None
|
||||
filepath: str | None = None # human-readable OS path
|
||||
cue_count: int = 0
|
||||
hotcue_count: int = 0
|
||||
has_grid: bool = False
|
||||
is_stem: bool = False # a Stem file (<STEMS> child) vs a normal audio track
|
||||
|
||||
|
||||
class TrackPage(BaseModel):
|
||||
total: int # total matching the filter (before pagination)
|
||||
offset: int
|
||||
limit: int
|
||||
items: list[Track]
|
||||
|
||||
|
||||
class GenreCount(BaseModel):
|
||||
name: str
|
||||
count: int
|
||||
|
||||
|
||||
class Facets(BaseModel):
|
||||
"""Distinct values available for building filter UI."""
|
||||
|
||||
genres: list[GenreCount]
|
||||
keys: list[GenreCount]
|
||||
bpm_min: float | None
|
||||
bpm_max: float | None
|
||||
total_tracks: int
|
||||
|
||||
|
||||
class Stats(BaseModel):
|
||||
total_tracks: int
|
||||
total_playlists: int
|
||||
rated: int
|
||||
unrated: int
|
||||
missing_key: int
|
||||
missing_genre: int
|
||||
missing_bpm: int
|
||||
no_cues: int
|
||||
rating_breakdown: dict[int, int] # stars -> count
|
||||
bpm_histogram: list[dict] # [{bucket: "120-130", count: n}]
|
||||
top_genres: list[GenreCount]
|
||||
|
||||
|
||||
class PlaylistNode(BaseModel):
|
||||
"""A node in the playlist tree — either a FOLDER or a PLAYLIST/SMARTLIST."""
|
||||
|
||||
id: str # stable synthetic id ("pl-<n>" / "fld-<n>")
|
||||
name: str
|
||||
type: str # "FOLDER" | "PLAYLIST" | "SMARTLIST"
|
||||
uuid: str | None = None
|
||||
count: int = 0 # track count (for playlists)
|
||||
children: list["PlaylistNode"] = []
|
||||
|
||||
|
||||
PlaylistNode.model_rebuild()
|
||||
|
||||
|
||||
# ---- write request bodies ----
|
||||
from .core.capabilities import CueRole, CueType
|
||||
|
||||
|
||||
class CreatePlaylist(BaseModel):
|
||||
@@ -114,73 +36,119 @@ class FileTagOutcome(BaseModel):
|
||||
|
||||
class SaveResult(BaseModel):
|
||||
saved: bool
|
||||
backup: str | None = None
|
||||
commit: str | None = None # sha of the version-history commit (None if deduped)
|
||||
playlists: int
|
||||
file_tags: list[FileTagOutcome] = []
|
||||
|
||||
|
||||
class CuePoint(BaseModel):
|
||||
name: str | None = None
|
||||
type: int # Traktor: 0 cue, 1 fade-in, 2 fade-out, 3 load, 4 grid, 5 loop
|
||||
start: float # seconds
|
||||
length: float # seconds (>0 for loops)
|
||||
hotcue: int # -1 if not assigned to a hotcue slot
|
||||
color: str | None = None # "#RRGGBB" if set
|
||||
class HistoryEntry(BaseModel):
|
||||
id: str # commit sha
|
||||
timestamp: str # ISO 8601, UTC
|
||||
summary: str # human-readable edit summary
|
||||
|
||||
|
||||
class TrackCues(BaseModel):
|
||||
bpm: float | None = None # beatgrid BPM (from the grid marker; falls back to tempo)
|
||||
grid_anchor: float | None = None # seconds — first grid marker (beat 1 of the grid)
|
||||
locked: bool = False # Traktor LOCK flag
|
||||
cues: list[CuePoint] = [] # cue/loop markers (grid markers excluded)
|
||||
|
||||
|
||||
class GridEdit(BaseModel):
|
||||
class AddGridMarker(BaseModel):
|
||||
track_id: str
|
||||
bpm: float | None = None # set the beatgrid tempo
|
||||
anchor: float | None = None # set the grid marker (beat 1) position, in seconds
|
||||
start: float # seconds
|
||||
bpm: float | None = None # unset = inherit the tempo governing that position
|
||||
|
||||
|
||||
class SetLock(BaseModel):
|
||||
class GridMarkerEdit(BaseModel):
|
||||
track_id: str
|
||||
index: int # into the start-ordered marker list
|
||||
start: float | None = None # move it (clamped between its neighbours)
|
||||
bpm: float | None = None # retempo the section it opens
|
||||
|
||||
|
||||
class ReplaceGrid(BaseModel):
|
||||
track_id: str
|
||||
markers: list[GridMarker] = [] # [] is equivalent to deleting the grid
|
||||
|
||||
|
||||
class SetGridLock(BaseModel):
|
||||
track_id: str
|
||||
locked: bool
|
||||
|
||||
|
||||
class SetHotcue(BaseModel):
|
||||
class SetCue(BaseModel):
|
||||
track_id: str
|
||||
slot: int # 0–7
|
||||
slot: int # bank slot; capabilities.cues.hotcue_slots bounds it
|
||||
start: float # seconds
|
||||
type: int # 0 cue, 1 fade-in, 2 fade-out, 3 load, 5 loop
|
||||
length: float = 0.0 # seconds (>0 for a loop hotcue)
|
||||
name: str | None = None # cue label; defaults to Traktor's "n.n." when unset
|
||||
type: CueType = "cue"
|
||||
role: CueRole = "hotcue"
|
||||
length: float = 0.0 # seconds (>0 for a loop cue)
|
||||
name: str | None = None
|
||||
color: str | None = None
|
||||
|
||||
|
||||
class AutoHotcue(BaseModel):
|
||||
slot: int # 0–7
|
||||
start: float # seconds
|
||||
name: str | None = None # positional label (e.g. "Drop")
|
||||
type: int = 0 # plain cue
|
||||
length: float = 0.0 # seconds (>0 for a loop hotcue)
|
||||
AutoCueEvent = Literal[
|
||||
"first_beat", "intro_end",
|
||||
"build_1", "drop_1", "breakdown_1",
|
||||
"build_2", "drop_2", "breakdown_2",
|
||||
"build_3", "drop_3", "breakdown_3",
|
||||
"outro", "last_beat",
|
||||
]
|
||||
AutoCueStatus = Literal["placed", "not_found", "out_of_range", "occupied", "protected", "duplicate"]
|
||||
|
||||
|
||||
class AutoCueSlot(BaseModel):
|
||||
"""One row of the Auto Hotcues template: bind a slot to a structural event."""
|
||||
|
||||
slot: int
|
||||
event: AutoCueEvent
|
||||
offset_beats: int = 0
|
||||
overwrite: bool = False # replace a cue already in this slot
|
||||
|
||||
|
||||
class AutoHotcuesRequest(BaseModel):
|
||||
track_id: str
|
||||
max_cues: int | None = None # defaults to MAX_HOTCUES (8) server-side
|
||||
slots: list[AutoCueSlot]
|
||||
|
||||
|
||||
class TrackIds(BaseModel):
|
||||
"""A body naming a set of tracks — the bulk Remove commands."""
|
||||
|
||||
track_ids: list[str]
|
||||
|
||||
|
||||
class AutoHotcuesBatchRequest(BaseModel):
|
||||
"""The same template applied to every track. `overwrite` on a slot means
|
||||
"replace this slot's cue on every track that has one"."""
|
||||
|
||||
track_ids: list[str]
|
||||
slots: list[AutoCueSlot]
|
||||
|
||||
|
||||
class AutoCueOutcome(BaseModel):
|
||||
slot: int
|
||||
event: AutoCueEvent
|
||||
status: AutoCueStatus
|
||||
start: float | None = None # seconds, when placed
|
||||
name: str | None = None
|
||||
duplicate_of: int | None = None # for "duplicate": the slot whose cue (kept or new) has this beat
|
||||
|
||||
|
||||
|
||||
class AutoGridRequest(BaseModel):
|
||||
track_id: str
|
||||
|
||||
|
||||
class SetHotcueType(BaseModel):
|
||||
class AutoGridBatchRequest(BaseModel):
|
||||
track_ids: list[str]
|
||||
# False skips tracks that already have a grid. Locked grids are skipped
|
||||
# either way: a lock is the user saying "never re-analyse this".
|
||||
replace_existing: bool = False
|
||||
|
||||
|
||||
class SetCueType(BaseModel):
|
||||
track_id: str
|
||||
slot: int
|
||||
type: int
|
||||
type: CueType
|
||||
|
||||
|
||||
class EditState(BaseModel):
|
||||
dirty: bool # unsaved in-memory playlist changes exist
|
||||
nml_path: str
|
||||
dirty: bool # unsaved in-memory changes exist
|
||||
library: LibraryInfo
|
||||
|
||||
|
||||
# ---- collection selection ----
|
||||
@@ -191,6 +159,9 @@ class CollectionStatus(BaseModel):
|
||||
path: str | None = None
|
||||
tracks: int | None = None
|
||||
playlists: int | None = None
|
||||
# Identity of the loaded library, so the UI can name it without parsing the
|
||||
# path (a Serato library is a directory, not a file).
|
||||
library: LibraryInfo | None = None
|
||||
|
||||
|
||||
class OpenCollection(BaseModel):
|
||||
@@ -207,9 +178,101 @@ class CollectionCandidate(BaseModel):
|
||||
|
||||
class CollectionOptions(BaseModel):
|
||||
auto: CollectionCandidate | None = None # best auto-detected (latest version)
|
||||
# EVERY library detected, best first. `auto` is simply the first of these.
|
||||
# Carried in full because one platform can genuinely have several at once —
|
||||
# two Traktor versions installed, or two sticks plugged in — and silently
|
||||
# anointing one of them is how the old single-candidate route could open a
|
||||
# USB drive as the user's collection.
|
||||
detected: list[CollectionCandidate] = []
|
||||
recent: CollectionCandidate | None = None # last opened (from userprefs)
|
||||
|
||||
|
||||
# ---- export sets -------------------------------------------------------------
|
||||
#
|
||||
# Konduktor's own data, never written into the user's library, and keyed by the
|
||||
# library's stable ID rather than its path. See `exports.py`.
|
||||
|
||||
|
||||
class ExportSetOut(BaseModel):
|
||||
id: str
|
||||
name: str
|
||||
target: str # platform id of the export TARGET
|
||||
destination: str
|
||||
playlist_ids: list[str] = []
|
||||
track_ids: list[str] = [] # loose tracks only
|
||||
created: float = 0.0
|
||||
modified: float = 0.0
|
||||
|
||||
|
||||
class CreateExportSet(BaseModel):
|
||||
name: str
|
||||
target: str = "traktor"
|
||||
destination: str
|
||||
|
||||
|
||||
class UpdateExportSet(BaseModel):
|
||||
name: str | None = None
|
||||
target: str | None = None
|
||||
destination: str | None = None
|
||||
|
||||
|
||||
class ExportSetMembers(BaseModel):
|
||||
track_ids: list[str] = []
|
||||
playlist_ids: list[str] = []
|
||||
|
||||
|
||||
class ExportPlaylistOut(BaseModel):
|
||||
id: str
|
||||
name: str
|
||||
#: The playlist has been deleted since it was added to the set.
|
||||
missing: bool = False
|
||||
count: int = 0
|
||||
|
||||
|
||||
class ExportContents(BaseModel):
|
||||
"""What a set holds RIGHT NOW. Never cached — the references are live."""
|
||||
|
||||
playlists: list[ExportPlaylistOut] = []
|
||||
loose: int = 0
|
||||
#: Deduped across playlists and loose tracks: one track, one file copy.
|
||||
tracks: int = 0
|
||||
#: Track ids the library no longer has, surfaced rather than dropped.
|
||||
dangling: list[str] = []
|
||||
#: Another set already writes to this destination, and an export CLEARS it.
|
||||
destination_conflict: str | None = None
|
||||
|
||||
|
||||
class ExportPreview(BaseModel):
|
||||
"""What an export would do if run now. Computed fresh; never stored."""
|
||||
|
||||
tracks: int = 0
|
||||
exportable: int = 0
|
||||
missing: list[str] = []
|
||||
playlists: list[str] = []
|
||||
total_bytes: int = 0
|
||||
destination: str | None = None
|
||||
free_bytes: int | None = None
|
||||
enough_space: bool | None = None
|
||||
#: A FACT, not a sentence — the UI words it. One of `destination_not_empty`,
|
||||
#: `nothing_to_export`, `unsupported_target`, or null when it can run.
|
||||
blocked: str | None = None
|
||||
#: The destination already holds a Konduktor export, which will be replaced.
|
||||
replacing: bool = False
|
||||
|
||||
|
||||
class FsPlace(BaseModel):
|
||||
"""A shortcut in the file browser's sidebar.
|
||||
|
||||
`kind` groups it and picks its icon; it is never a finished sentence, and
|
||||
the browser decides what "volume" looks like. A place is always a DIRECTORY
|
||||
that exists right now — one that does not is omitted rather than disabled.
|
||||
"""
|
||||
|
||||
kind: str # home | music | desktop | documents | downloads | volume | library
|
||||
name: str
|
||||
path: str
|
||||
|
||||
|
||||
class FsEntry(BaseModel):
|
||||
name: str
|
||||
path: str
|
||||
@@ -236,30 +299,138 @@ class PathMappingInfo(BaseModel):
|
||||
to: str = ""
|
||||
|
||||
|
||||
class RemapSample(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
from_: str = Field(alias="from")
|
||||
to: str
|
||||
exists: bool
|
||||
|
||||
|
||||
class RemapPreview(BaseModel):
|
||||
total: int # tracks with a resolvable location
|
||||
matched: int # how many match the `from` prefix
|
||||
existing: int # of matched, how many exist at the `to` target
|
||||
samples: list[RemapSample] = []
|
||||
|
||||
|
||||
class RemapResult(BaseModel):
|
||||
rewritten: int # tracks whose LOCATION was rewritten
|
||||
backup: str | None = None # path of the .bak written before the rewrite
|
||||
commit: str | None = None # sha of the version-history commit for the rewrite
|
||||
|
||||
|
||||
class PrefixGroup(BaseModel):
|
||||
prefix: str # common directory prefix of a group of tracks
|
||||
count: int # tracks sharing it
|
||||
# The generic model lives in core.model; re-exported here so the HTTP layer has
|
||||
# one import site. The dependency runs schemas -> core, never the reverse.
|
||||
from .core.model import ( # noqa: E402,F401
|
||||
AutoHotcue,
|
||||
LibraryInfo,
|
||||
PlatformOption,
|
||||
CuePoint,
|
||||
Facets,
|
||||
GenreCount,
|
||||
GridMarker,
|
||||
HotcueChip,
|
||||
PlaylistNode,
|
||||
PrefixGroup,
|
||||
PrefixSuggestions,
|
||||
RemapPreview,
|
||||
RemapSample,
|
||||
Stats,
|
||||
Track,
|
||||
TrackCues,
|
||||
TrackPage,
|
||||
)
|
||||
|
||||
|
||||
class PrefixSuggestions(BaseModel):
|
||||
primary: str # best guess for the `from` prefix (largest group)
|
||||
groups: list[PrefixGroup] = [] # alternatives, ranked by count
|
||||
class AutoHotcuesResult(BaseModel):
|
||||
"""The refreshed cues, plus what happened to every requested slot."""
|
||||
|
||||
cues: TrackCues
|
||||
outcomes: list[AutoCueOutcome]
|
||||
|
||||
|
||||
# ---- import sources ---------------------------------------------------
|
||||
#
|
||||
# A SOURCE is a library being read FROM — a plugged-in OneLibrary stick whose
|
||||
# tracks are about to be imported. It is deliberately not a `CollectionStatus`:
|
||||
# a source is never saved, never edited and never the fallback when nothing is
|
||||
# loaded, so reusing the loaded-library shape would invite routes to treat the
|
||||
# two as interchangeable.
|
||||
|
||||
|
||||
class SourceCandidate(BaseModel):
|
||||
"""A removable library Konduktor can currently see."""
|
||||
|
||||
path: str
|
||||
label: str # what a person recognises, e.g. "OneLibrary — Hardy"
|
||||
platform: str
|
||||
tracks: int | None = None # None until it is opened; a probe would be slow
|
||||
modified: float | None = None
|
||||
|
||||
|
||||
class SourceStatus(BaseModel):
|
||||
loaded: bool
|
||||
path: str | None = None
|
||||
label: str | None = None
|
||||
platform: str | None = None
|
||||
tracks: int | None = None
|
||||
playlists: int | None = None
|
||||
|
||||
|
||||
class OpenSource(BaseModel):
|
||||
path: str
|
||||
|
||||
|
||||
class ImportRequest(BaseModel):
|
||||
"""What to import, and where its audio should land.
|
||||
|
||||
Empty `track_ids` AND empty `playlist_ids` means the whole drive — an
|
||||
explicit "import everything" rather than a mistake, matching the settled
|
||||
export design's separate "export entire library" action.
|
||||
"""
|
||||
|
||||
destination: str # folder the audio is copied into
|
||||
track_ids: list[str] = []
|
||||
playlist_ids: list[str] = []
|
||||
# Playlists land in a folder named after the drive. Null keeps them at the
|
||||
# root; the default is filled in from the source's label.
|
||||
folder_name: str | None = None
|
||||
|
||||
|
||||
class Drive(BaseModel):
|
||||
"""A drive in the sidebar, under Devices (`external`) or Local Storage.
|
||||
|
||||
`library` is the OneLibrary database on it, when there is one — the same
|
||||
candidate `/api/sources` reports, attached to the drive it lives on so the
|
||||
sidebar can show one row per drive rather than a device list and a drive
|
||||
list that disagree about what is plugged in.
|
||||
"""
|
||||
|
||||
name: str
|
||||
path: str
|
||||
kind: Literal["local", "external"]
|
||||
library: SourceCandidate | None = None
|
||||
|
||||
|
||||
class FolderTracks(BaseModel):
|
||||
"""The audio files directly inside one folder, projected as tracks."""
|
||||
|
||||
path: str
|
||||
tracks: list[Track]
|
||||
# Ids (= absolute paths) of the files the collection already points at.
|
||||
in_collection: list[str]
|
||||
# On an external drive: a track referenced in place goes missing when the
|
||||
# drive is unplugged, which the add dialog has to say.
|
||||
removable: bool
|
||||
|
||||
|
||||
class FolderAddRequest(BaseModel):
|
||||
"""Add browsed files to the collection, and optionally to a playlist/export.
|
||||
|
||||
`mode` is asked every time rather than defaulted, because the right answer
|
||||
depends on the drive and on how the DJ keeps their music.
|
||||
"""
|
||||
|
||||
track_ids: list[str]
|
||||
mode: Literal["copy", "reference"]
|
||||
destination: str | None = None # required for `copy`
|
||||
playlist_id: str | None = None
|
||||
export_id: str | None = None
|
||||
|
||||
|
||||
class JobStatus(BaseModel):
|
||||
id: str
|
||||
kind: str
|
||||
state: str # running | done | failed | cancelled
|
||||
total: int
|
||||
done: int
|
||||
message: str
|
||||
result: dict | None = None
|
||||
error: str | None = None
|
||||
started_at: float
|
||||
finished_at: float | None = None
|
||||
@@ -5,6 +5,11 @@ uvicorn[standard]>=0.34
|
||||
pydantic>=2.11
|
||||
mutagen>=1.47 # embedded audio-file tag read/write (ID3/MP4/FLAC/AIFF)
|
||||
python-multipart>=0.0.9 # multipart form parsing for cover-art upload
|
||||
# Version-history backups: a self-contained git impl (no system git needed;
|
||||
# ships prebuilt py3.14 wheels, no from-source build) + a per-OS user-writable
|
||||
# app-data dir. Both bundle cleanly into the frozen sidecar.
|
||||
dulwich>=0.22
|
||||
platformdirs>=4.0
|
||||
# Auto Hotcues: structural segmentation (McFee/Ellis Laplacian). Pure-Python,
|
||||
# ~150MB; numba/llvmlite ship Python 3.14 wheels (verified). No torch/native build.
|
||||
librosa>=0.11
|
||||
@@ -12,3 +17,15 @@ scikit-learn>=1.5
|
||||
# Traktor Pro 4 (NML v20) support requires the GitHub master (v4.0.0),
|
||||
# NOT the stale PyPI release (3.1.0), which cannot parse v4 files.
|
||||
traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git
|
||||
# Rekordbox (master.db is SQLCipher-encrypted SQLite + per-track ANLZ analysis
|
||||
# files). Both ship prebuilt Python 3.14 wheels — no Rust/OpenSSL source build.
|
||||
#
|
||||
# FROM GITHUB, NOT PyPI — the same situation as traktor-nml-utils above, and for
|
||||
# the same kind of reason. PyPI's latest (0.4.4) has no `devicelib_plus`, which
|
||||
# is the OneLibrary (`exportLibrary.db`) reader the OneLibrary adapter is built
|
||||
# on; it exists only on master. Do not "simplify" this back to a version pin.
|
||||
#
|
||||
# The upgrade also renames `db6` to `masterdb`. `db6` still works as a
|
||||
# deprecated alias and is removed in 0.6.0, so the Rekordbox adapter keeps
|
||||
# running as-is — but that rename is the thing to fix before taking 0.6.
|
||||
pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git
|
||||
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
|
||||
source .venv/bin/activate
|
||||
|
||||
fail=0
|
||||
for t in test_save_fidelity.py test_phase3.py; do
|
||||
for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_phase3.py test_history.py; do
|
||||
echo "──────────────────────────────────────────"
|
||||
echo "▶ $t"
|
||||
echo "──────────────────────────────────────────"
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
"""Tests for Auto Hotcues: structure analysis, slot resolution and the route.
|
||||
|
||||
Three layers, because each failed silently before:
|
||||
- `structure.analyse` on SYNTHETIC audio whose sections are known by
|
||||
construction (intro / breakdown / drop / …), so a wrong bar is a wrong answer
|
||||
rather than a disagreement with another analyser;
|
||||
- `auto_hotcues.plan`, the pure part: offsets in beats (across a tempo change),
|
||||
and every outcome a slot can report;
|
||||
- the ROUTE, end to end against a temp copy of the real collection. The previous
|
||||
implementation's route raised a 500 on every call for a week after a model
|
||||
change, and nothing noticed, because only its placement helper was tested.
|
||||
|
||||
Accuracy on real music is measured against Rekordbox's phrase analysis, which
|
||||
needs local audio; see the Auto Hotcues section of CLAUDE.md.
|
||||
"""
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-autocue-appdata-")
|
||||
|
||||
from konduktor.core import auto_hotcues as ah # noqa: E402
|
||||
from konduktor.core import structure # noqa: E402
|
||||
|
||||
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
|
||||
SR = 22050
|
||||
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
|
||||
|
||||
|
||||
# ---- synthetic track ----------------------------------------------------------
|
||||
rng = np.random.default_rng(0)
|
||||
BPM, FIRST = 128.0, 0.25
|
||||
BEAT = 60.0 / BPM
|
||||
BAR = 4 * BEAT
|
||||
|
||||
|
||||
def _fade(x):
|
||||
n = min(len(x), int(0.02 * SR))
|
||||
x = x.copy()
|
||||
x[-n:] *= np.linspace(1, 0, n)
|
||||
return x
|
||||
|
||||
|
||||
def _kick():
|
||||
t = np.arange(int(0.25 * SR)) / SR
|
||||
return _fade(np.sin(2 * np.pi * 52 * t) * np.exp(-t / 0.1) + np.r_[rng.standard_normal(40) * 0.4, np.zeros(len(t) - 40)])
|
||||
|
||||
|
||||
def _hat():
|
||||
n = int(0.04 * SR)
|
||||
return _fade(np.diff(rng.standard_normal(n + 1)) * np.exp(-np.arange(n) / SR / 0.01) * 0.3)
|
||||
|
||||
|
||||
# (name, bars, kick, bass, pad, hats)
|
||||
LAYOUT = [
|
||||
("intro", 16, True, False, False, True),
|
||||
("breakdown", 16, False, False, True, False),
|
||||
("drop", 32, True, True, True, True),
|
||||
("breakdown", 16, False, False, True, False),
|
||||
("drop", 32, True, True, True, True),
|
||||
("outro", 16, True, False, False, True),
|
||||
]
|
||||
|
||||
|
||||
def synth():
|
||||
total = sum(b for _, b, *_ in LAYOUT) * BAR + FIRST + 1.0
|
||||
y = np.zeros(int(total * SR))
|
||||
t_all = np.arange(len(y)) / SR
|
||||
k, h = _kick(), _hat()
|
||||
bar = 0
|
||||
for _, bars, kick, bass, pad, hats in LAYOUT:
|
||||
t0 = FIRST + bar * BAR
|
||||
t1 = t0 + bars * BAR
|
||||
m = (t_all >= t0) & (t_all < t1)
|
||||
if bass: # a loud sustained 55 Hz bass with some harmonics
|
||||
y[m] += 0.5 * np.sign(np.sin(2 * np.pi * 55 * t_all[m])) * 0.6
|
||||
if pad: # a mid-range chord
|
||||
y[m] += 0.08 * sum(np.sin(2 * np.pi * f * t_all[m]) for f in (330, 415, 494))
|
||||
for b in range(bars * 4):
|
||||
tb = t0 + b * BEAT
|
||||
i = int(tb * SR)
|
||||
if kick:
|
||||
y[i : i + len(k)] += k[: len(y) - i]
|
||||
if hats:
|
||||
j = int((tb + BEAT / 2) * SR)
|
||||
y[j : j + len(h)] += h[: max(0, len(y) - j)]
|
||||
bar += bars
|
||||
return (0.3 * y).astype(np.float32)
|
||||
|
||||
|
||||
print("== structure on a track whose sections are known ==")
|
||||
y = synth()
|
||||
st = structure.analyse("", [(FIRST, BPM)], y=y)
|
||||
bar_of = {e: (b - st.bar0) // 4 for e, b in st.events.items()}
|
||||
check("first drop at bar 32", bar_of.get("drop_1") == 32, str(bar_of))
|
||||
check("first breakdown at bar 64 (where the first drop ends)", bar_of.get("breakdown_1") == 64, str(bar_of))
|
||||
check("second drop at bar 80", bar_of.get("drop_2") == 80, str(bar_of))
|
||||
check("the intro is NOT a drop, though it has a kick", bar_of.get("drop_1") != 0, str(bar_of))
|
||||
check("intro ends at bar 16", bar_of.get("intro_end") == 16, str(bar_of))
|
||||
check("no third drop is invented", "drop_3" not in bar_of, str(bar_of))
|
||||
check("no breakdown after the LAST drop (that is the outro)", "breakdown_2" not in bar_of, str(bar_of))
|
||||
check("outro starts at bar 112", bar_of.get("outro") == 112, str(bar_of))
|
||||
check("first beat is the first kick", abs(st.beat_time(st.events["first_beat"]) - FIRST) < 0.01,
|
||||
f"{st.beat_time(st.events['first_beat'])}")
|
||||
check("every section boundary is on a 4-bar line", all(s.start % 4 == 0 for s in st.sections),
|
||||
str([s.start for s in st.sections]))
|
||||
|
||||
print("== a flexible grid: beats follow each marker's tempo ==")
|
||||
beats, bar0 = structure.grid_beats([(1.0, 120.0), (9.0, 60.0)], duration=20.0)
|
||||
check("beats before the first marker are extrapolated back", bar0 == 2 and abs(beats[0] - 0.0) < 1e-9, f"{bar0} {beats[:3]}")
|
||||
check("0.5 s apart under the first marker", abs(beats[bar0 + 1] - beats[bar0] - 0.5) < 1e-9)
|
||||
check("1.0 s apart after the second", abs(beats[-1] - beats[-2] - 1.0) < 1e-9)
|
||||
|
||||
|
||||
# ---- plan: the pure part ----------------------------------------------------------
|
||||
def fake_structure(events, n_beats=400, bpm=120.0):
|
||||
s = structure.Structure(beats=np.arange(n_beats) * 60.0 / bpm, bar0=0, n_bars=n_beats // 4,
|
||||
duration=n_beats * 60.0 / bpm)
|
||||
s.events = dict(events)
|
||||
return s
|
||||
|
||||
|
||||
print("== plan: offsets and outcomes ==")
|
||||
fs = fake_structure({"drop_1": 128, "outro": 384, "first_beat": 0})
|
||||
R = ah.SlotRequest
|
||||
E = ah.ExistingCue
|
||||
out = {o.slot: o for o in ah.plan(fs, [
|
||||
R(0, "first_beat"),
|
||||
R(1, "drop_1", -16),
|
||||
R(2, "drop_3"),
|
||||
R(3, "first_beat", -4),
|
||||
R(4, "drop_1"),
|
||||
R(5, "drop_1", 0, overwrite=True),
|
||||
R(6, "drop_1", 0, overwrite=True),
|
||||
], existing={4: E(True, 190.0), 5: E(True, 190.5), 6: E(False, 191.0)})}
|
||||
check("placed on the event's beat", out[0].status == ah.PLACED and out[0].start == 0.0)
|
||||
check("an offset counts BEATS: drop -16 is 8 s earlier at 120 BPM",
|
||||
out[1].status == ah.PLACED and abs(out[1].start - (128 - 16) * 0.5) < 1e-9, str(out[1]))
|
||||
check("the offset is in the cue's name", out[1].name == "Drop 1 -16", str(out[1].name))
|
||||
check("a missing event is reported, not placed", out[2].status == ah.NOT_FOUND)
|
||||
check("an offset before the track start is out of range", out[3].status == ah.OUT_OF_RANGE)
|
||||
check("an occupied slot is left alone by default", out[4].status == ah.OCCUPIED)
|
||||
check("…and replaced when overwrite is asked for", out[5].status == ah.PLACED)
|
||||
check("a protected cue is never replaced, even with overwrite", out[6].status == ah.PROTECTED)
|
||||
|
||||
print("== plan: two slots on the same beat get ONE cue, in the lower slot ==")
|
||||
dup = fake_structure({"drop_1": 128, "breakdown_1": 112, "build_2": 112})
|
||||
out = {o.slot: o for o in ah.plan(dup, [
|
||||
R(3, "breakdown_1"),
|
||||
R(4, "build_2"), # the same beat as slot 3, by a different event
|
||||
R(5, "drop_1", -16), # …and again, by an offset (128 - 16 = 112)
|
||||
R(6, "drop_1", -15), # one beat later: a different beat, placed
|
||||
], existing={})}
|
||||
check("the lower slot keeps the beat", out[3].status == ah.PLACED)
|
||||
check("a higher slot on the same beat is skipped", out[4].status == ah.DUPLICATE and out[4].duplicate_of == 3, str(out[4]))
|
||||
check("…whichever event or offset got it there", out[5].status == ah.DUPLICATE and out[5].duplicate_of == 3, str(out[5]))
|
||||
check("one beat apart is not a duplicate", out[6].status == ah.PLACED)
|
||||
rev = {o.slot: o.status for o in ah.plan(dup, [R(4, "build_2"), R(3, "breakdown_1")], existing={})}
|
||||
check("lower slot wins whatever order the request lists them in",
|
||||
rev == {3: ah.PLACED, 4: ah.DUPLICATE}, str(rev))
|
||||
|
||||
print("== plan: cues already in the bank claim their beats too ==")
|
||||
# beat k is at k * 0.5 s in fake_structure; breakdown_1 / build_2 are beat 112 = 56 s.
|
||||
o = {x.slot: x for x in ah.plan(dup, [R(3, "breakdown_1")], existing={0: E(False, 56.0)})}
|
||||
check("a new cue on the GRID cue's beat is skipped as its duplicate",
|
||||
o[3].status == ah.DUPLICATE and o[3].duplicate_of == 0, str(o[3]))
|
||||
o = {x.slot: x for x in ah.plan(dup, [R(3, "breakdown_1")], existing={6: E(True, 56.03)})}
|
||||
check("…and on a hand-placed cue a few ms off the grid (higher slot, still kept)",
|
||||
o[3].status == ah.DUPLICATE and o[3].duplicate_of == 6, str(o[3]))
|
||||
o = {x.slot: x for x in ah.plan(dup, [R(3, "breakdown_1")], existing={6: E(True, 56.25)})}
|
||||
check("a cue on the half-beat is a different beat", o[3].status == ah.PLACED, str(o[3]))
|
||||
o = {x.slot: x.status for x in ah.plan(dup, [R(3, "breakdown_1"), R(4, "build_2")], existing={3: E(True, 10.0)})}
|
||||
check("a kept cue elsewhere claims only ITS beat", o == {3: ah.OCCUPIED, 4: ah.PLACED}, str(o))
|
||||
|
||||
print("== plan: a replaced cue frees its beat only if its replacement is placed ==")
|
||||
o = {x.slot: x.status for x in ah.plan(dup, [
|
||||
R(2, "drop_1", overwrite=True), R(5, "breakdown_1"),
|
||||
], existing={2: E(True, 56.0)})}
|
||||
check("replaced → its old beat is free for another slot", o == {2: ah.PLACED, 5: ah.PLACED}, str(o))
|
||||
o = {x.slot: x for x in ah.plan(dup, [
|
||||
R(1, "drop_1"), R(2, "drop_1", overwrite=True), R(5, "breakdown_1"),
|
||||
], existing={2: E(True, 56.0)})}
|
||||
check("a replacement that is itself a duplicate is skipped…",
|
||||
o[2].status == ah.DUPLICATE and o[2].duplicate_of == 1, str(o[2]))
|
||||
check("…so the old cue stays, and still claims its beat",
|
||||
o[5].status == ah.DUPLICATE and o[5].duplicate_of == 2, str(o[5]))
|
||||
|
||||
flex = structure.Structure(beats=np.r_[np.arange(0, 10, 0.5), np.arange(10, 30, 1.0)], bar0=0, n_bars=10, duration=30)
|
||||
flex.events = {"drop_1": 24} # beat 24 is at 14 s (20 beats at 0.5 s, then 4 at 1.0 s)
|
||||
o = ah.plan(flex, [R(0, "drop_1", -8)], {})[0]
|
||||
# 8 beats back is beat 16, at 8.0 s; 8 beats at the LOCAL tempo would be 6.0 s.
|
||||
check("an offset across a tempo change counts beats, not seconds", abs(o.start - 8.0) < 1e-9, str(o.start))
|
||||
|
||||
|
||||
# ---- the route --------------------------------------------------------------------
|
||||
print("== the route, end to end ==")
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
work = Path(d) / "collection.nml"
|
||||
shutil.copy2(REAL, work)
|
||||
os.environ["KONDUKTOR_NML"] = str(work)
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
import konduktor.main as main
|
||||
|
||||
# The real collection's audio is not on every machine, so the route gets a
|
||||
# stand-in structure and an existing file: this pins the WIRING — request
|
||||
# validation, the plan, the adapter write and the response model.
|
||||
# Its events are put on beats chosen per track (below), clear of the cues
|
||||
# already there — otherwise the one-cue-per-beat rule, not the wiring, would
|
||||
# decide the outcome.
|
||||
ROUTE_EVENTS: dict = {}
|
||||
main.structure.analyse = lambda path, markers: fake_structure(ROUTE_EVENTS, bpm=markers[0][1])
|
||||
with TestClient(main.app, raise_server_exceptions=False) as c:
|
||||
a = main.require_adapter()
|
||||
a.audio_path = lambda track_id: Path(__file__)
|
||||
def free_slots(cu):
|
||||
return [s for s in range(8) if not any(q.slot == s for q in cu.cues)]
|
||||
tid = next(t.id for t in a.tracks
|
||||
if (cu := a.track_cues(t.id)) and len(cu.grid_markers) == 1 and len(free_slots(cu)) >= 4
|
||||
and any(q.grid_marker is not None and q.slot is not None for q in cu.cues))
|
||||
cu = a.track_cues(tid)
|
||||
step = 60.0 / cu.grid_markers[0].bpm
|
||||
taken_t = [q.start for q in cu.cues if q.slot is not None]
|
||||
clear = [k for k in range(8, 390) if all(abs(k * step - t) > step for t in taken_t)]
|
||||
drop = next(k for k in clear if k - 16 in clear and k >= 80)
|
||||
outro = next(k for k in clear if k > drop + 40)
|
||||
grid_cue = next(q for q in cu.cues if q.grid_marker is not None and q.slot is not None)
|
||||
ROUTE_EVENTS.update(drop_1=drop, outro=outro, first_beat=round(grid_cue.start / step))
|
||||
f0, f1, f2, f3 = free_slots(cu)[:4]
|
||||
r = c.post("/api/tracks/cue/auto", json={"track_id": tid, "slots": [
|
||||
{"slot": f0, "event": "first_beat"},
|
||||
{"slot": f1, "event": "drop_1", "offset_beats": -16},
|
||||
{"slot": f2, "event": "drop_3"},
|
||||
{"slot": f3, "event": "outro"},
|
||||
]})
|
||||
check("the route answers 200", r.status_code == 200, r.text[:200])
|
||||
if r.status_code == 200:
|
||||
j = r.json()
|
||||
oc = {o["slot"]: o for o in j["outcomes"]}
|
||||
st_ = {k: o["status"] for k, o in oc.items()}
|
||||
check("outcomes per slot", st_ == {f0: "duplicate", f1: "placed", f2: "not_found", f3: "placed"}, str(st_))
|
||||
check("a new cue on the track's real GRID cue is skipped as its duplicate",
|
||||
oc[f0]["duplicate_of"] == grid_cue.slot, str(oc[f0]))
|
||||
names = {q["slot"]: q["name"] for q in j["cues"]["cues"] if q["slot"] is not None}
|
||||
check("the cues are in the returned projection", names.get(f1) == "Drop 1 -16", str(names))
|
||||
r2 = c.post("/api/tracks/cue/auto", json={"track_id": tid, "slots": [{"slot": f1, "event": "drop_1"}]})
|
||||
check("running again leaves the now-occupied slot alone",
|
||||
r2.status_code == 200 and r2.json()["outcomes"][0]["status"] == "occupied", r2.text[:200])
|
||||
f4 = free_slots(a.track_cues(tid))[0]
|
||||
r3 = c.post("/api/tracks/cue/auto", json={"track_id": tid, "slots": [{"slot": f4, "event": "outro"}]})
|
||||
o3 = r3.json()["outcomes"][0] if r3.status_code == 200 else {}
|
||||
check("…and a later run will not stack a cue on one it placed earlier",
|
||||
o3.get("status") == "duplicate" and o3.get("duplicate_of") == f3, r3.text[:300])
|
||||
r = c.post("/api/tracks/cue/auto", json={"track_id": tid, "slots": [{"slot": f0, "event": "drop_1"}, {"slot": f0, "event": "outro"}]})
|
||||
check("a slot requested twice is refused", r.status_code == 400)
|
||||
r = c.post("/api/tracks/cue/auto", json={"track_id": tid, "slots": [{"slot": f0, "event": "the_best_bit"}]})
|
||||
check("an unknown event is refused", r.status_code == 422)
|
||||
check("nothing was written to disk (edits stay in memory until Save)",
|
||||
work.read_bytes() == REAL.read_bytes())
|
||||
|
||||
print()
|
||||
print("FAILED" if failed else "RESULT: ALL PASSED")
|
||||
raise SystemExit(1 if failed else 0)
|
||||
@@ -0,0 +1,126 @@
|
||||
"""The context menu's Remove ▸ commands, through their routes, on a temp copy.
|
||||
|
||||
Removing from the COLLECTION is new — the protocol's only destroying verb for
|
||||
tracks — and its bytes are pinned by invariant L in `test_save_fidelity.py`.
|
||||
This pins what the routes decide: which tracks each command skips (locked
|
||||
grids, memory cues), that "clear hotcues" empties the whole bank but leaves the
|
||||
grid, that a removed track leaves the projection AND every playlist while its
|
||||
audio file is untouched, that the capability gates the route, and that a
|
||||
running batch analysis blocks all three.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
|
||||
|
||||
failed = False
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
global failed
|
||||
print(f" {'✓' if cond else '✗'} {label}" + ("" if cond else f" [{detail}]"))
|
||||
if not cond:
|
||||
failed = True
|
||||
|
||||
|
||||
print("== bulk remove ==")
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
work = Path(d) / "collection.nml"
|
||||
shutil.copy2(REAL, work)
|
||||
os.environ["KONDUKTOR_NML"] = str(work)
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
import konduktor.main as main
|
||||
|
||||
with TestClient(main.app, raise_server_exceptions=False) as c:
|
||||
a = main.require_adapter()
|
||||
gridded = [t.id for t in a.tracks if t.grid_marker_count > 0 and not t.grid_locked][:3]
|
||||
locked = gridded[2]
|
||||
a.set_grid_lock(locked, True)
|
||||
bare = next(t.id for t in a.tracks if t.grid_marker_count == 0)
|
||||
|
||||
# ---- grids ----------------------------------------------------------
|
||||
r = c.post("/api/tracks/grid/clear", json={"track_ids": [*gridded, bare]})
|
||||
check("grid clear answers 200", r.status_code == 200, r.text[:200])
|
||||
check("…counts cleared / locked / empty",
|
||||
r.json() == {"cleared": 2, "locked": 1, "empty": 1}, r.text)
|
||||
check("the grids are gone", all(not a.track_cues(t).grid_markers for t in gridded[:2]))
|
||||
check("a locked grid is kept", bool(a.track_cues(locked).grid_markers))
|
||||
|
||||
# ---- hotcues --------------------------------------------------------
|
||||
with_cues = [t.id for t in a.tracks
|
||||
if (cu := a.track_cues(t.id)) and len(cu.grid_markers) > 0
|
||||
and any(q.slot is not None and q.grid_marker is not None for q in cu.cues)
|
||||
and sum(q.slot is not None for q in cu.cues) >= 2][:2]
|
||||
before = {t: a.track_cues(t) for t in with_cues}
|
||||
n_cues = sum(sum(q.slot is not None for q in cu.cues) for cu in before.values())
|
||||
r = c.post("/api/tracks/cue/clear", json={"track_ids": with_cues})
|
||||
check("hotcue clear answers 200", r.status_code == 200, r.text[:200])
|
||||
check("…counts tracks and cues", r.json() == {"tracks": 2, "cues": n_cues}, f"{r.text} vs {n_cues}")
|
||||
check("the whole bank is empty, incl. the grid's beat-1 cue",
|
||||
all(not any(q.slot is not None for q in a.track_cues(t).cues) for t in with_cues))
|
||||
# Positions and tempos, not the whole marker: its `companion` slot is
|
||||
# SUPPOSED to become None, since the paired cue was just deleted.
|
||||
def grid(cu):
|
||||
return [(m.start, m.bpm) for m in cu.grid_markers]
|
||||
check("…and the grid itself is untouched (only its pairing ends)",
|
||||
all(grid(a.track_cues(t)) == grid(before[t]) for t in with_cues)
|
||||
and all(m.companion is None for t in with_cues for m in a.track_cues(t).grid_markers))
|
||||
|
||||
# ---- from collection ------------------------------------------------
|
||||
caps = c.get("/api/capabilities").json()
|
||||
check("Traktor advertises removable tracks", caps["tracks"]["removable"] is True)
|
||||
tree = c.get("/api/playlists").json()
|
||||
|
||||
def lists(nodes):
|
||||
for n in nodes:
|
||||
yield n
|
||||
yield from lists(n["children"])
|
||||
|
||||
pl = next(n for n in lists(tree) if n.get("count") and n.get("can_add_tracks"))
|
||||
in_pl = c.get(f"/api/playlists/{pl['id']}/tracks").json()
|
||||
in_pl = in_pl["tracks"] if isinstance(in_pl, dict) else in_pl
|
||||
victim = in_pl[0]["id"]
|
||||
audio = a.audio_path(victim)
|
||||
existed = audio is not None and audio.exists()
|
||||
n_before = len(a.tracks)
|
||||
|
||||
r = c.post("/api/tracks/remove", json={"track_ids": [victim, victim, "nope"]})
|
||||
check("remove answers 200", r.status_code == 200, r.text[:200])
|
||||
check("…and removes exactly one (duplicates / unknowns ignored)", r.json() == {"removed": 1}, r.text)
|
||||
check("the track leaves the projection", a.track(victim) is None and len(a.tracks) == n_before - 1)
|
||||
after = c.get(f"/api/playlists/{pl['id']}/tracks").json()
|
||||
after = after["tracks"] if isinstance(after, dict) else after
|
||||
check("…and the playlist", all(t["id"] != victim for t in after) and len(after) == len(in_pl) - 1)
|
||||
check("the audio file is untouched", not existed or audio.exists())
|
||||
check("the edit is unsaved (Save lights up)", c.get("/api/state").json().get("dirty") is True)
|
||||
|
||||
# ---- gating ----------------------------------------------------------
|
||||
orig_caps = a.capabilities
|
||||
a.capabilities = lambda: orig_caps().model_copy(update={
|
||||
"tracks": orig_caps().tracks.model_copy(update={"removable": False})})
|
||||
r = c.post("/api/tracks/remove", json={"track_ids": [gridded[0]]})
|
||||
check("remove is refused without the capability", r.status_code == 422, r.text[:200])
|
||||
a.capabilities = orig_caps
|
||||
|
||||
main.grid_detect.detect_grid = lambda p, *a_, **k: (time.sleep(0.05), SimpleNamespace(anchor=0.1, bpm=128.0))[1]
|
||||
a.audio_path = lambda tid: Path(__file__)
|
||||
jid = c.post("/api/tracks/grid/auto-batch",
|
||||
json={"track_ids": [t.id for t in a.tracks][:40], "replace_existing": True}).json()["id"]
|
||||
for route in ("/api/tracks/grid/clear", "/api/tracks/cue/clear", "/api/tracks/remove"):
|
||||
r = c.post(route, json={"track_ids": [gridded[0]]})
|
||||
check(f"{route} is refused while a batch runs", r.status_code == 409, r.text[:200])
|
||||
c.post(f"/api/jobs/{jid}/cancel")
|
||||
|
||||
check("nothing was written to disk (edits stay in memory until Save)",
|
||||
work.read_bytes() == REAL.read_bytes())
|
||||
|
||||
print()
|
||||
print("FAILED" if failed else "RESULT: ALL PASSED")
|
||||
raise SystemExit(1 if failed else 0)
|
||||
@@ -0,0 +1,370 @@
|
||||
"""Writing a brand-new Traktor collection from nothing.
|
||||
|
||||
Everywhere else in Konduktor the write target was parsed from a file Traktor
|
||||
wrote, and `test_save_fidelity.py` guards that nothing else in it moves. An
|
||||
export has no original, so the guarantee has to be different: **the result must
|
||||
be a collection Traktor would have written** — the right skeleton, a coherent
|
||||
playlist tree, and prep that survived the crossing intact.
|
||||
|
||||
The property with the most riding on it is the LOCATION: Traktor stores a volume
|
||||
NAME plus a volume-relative path, never a host path, which is the whole reason a
|
||||
USB export is portable. If an export ever wrote absolute host paths it would
|
||||
work perfectly on the machine that made it and resolve to nothing at the gig.
|
||||
|
||||
Runs against the 8,485-entry fixture collection, so the tracks have real prep —
|
||||
flexible grids, hot cues on specific pads — rather than anything invented here.
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp()
|
||||
|
||||
from konduktor.adapters.traktor.driver import TraktorDriver # noqa: E402
|
||||
from konduktor.adapters.traktor.export import SKELETON # noqa: E402
|
||||
from konduktor.core import export as core_export # noqa: E402
|
||||
from konduktor.core.export import ExportPayload, ExportPlaylist, ExportTrack # noqa: E402
|
||||
|
||||
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
|
||||
|
||||
|
||||
FIXTURE = Path(__file__).resolve().parents[1] / "collection.nml"
|
||||
src = TraktorDriver().open(FIXTURE)
|
||||
exporter = core_export.for_platform("traktor")
|
||||
|
||||
print("== the target declares itself without a library to read ==")
|
||||
check("traktor is a target", exporter is not None)
|
||||
# All three platforms Konduktor can OPEN can now also be written from nothing.
|
||||
# The two registries stay separate anyway: they answer different questions, and
|
||||
# a future read-only platform would be in one and not the other.
|
||||
check("so are rekordbox and onelibrary",
|
||||
core_export.for_platform("rekordbox") is not None
|
||||
and core_export.for_platform("onelibrary") is not None)
|
||||
check("a platform with no exporter is not a target",
|
||||
core_export.for_platform("serato") is None)
|
||||
caps = exporter.capabilities()
|
||||
check("static capabilities answer with no path", caps.platform == "traktor" and caps.writable)
|
||||
check("and describe the FORMAT, not an instance", caps.cues.hotcue_slots == 8)
|
||||
|
||||
# ---- build a payload out of real tracks --------------------------------------
|
||||
# One with a flexible (multi-marker) grid, one with several hot cues: the two
|
||||
# things most likely to be quietly lost.
|
||||
flexible = next(t for t in src.tracks if (t.grid_marker_count or 0) > 1)
|
||||
cued = next(t for t in src.tracks if (t.cue_count or 0) >= 3 and t.id != flexible.id)
|
||||
plain = next(t for t in src.tracks if t.id not in (flexible.id, cued.id))
|
||||
chosen = [flexible, cued, plain]
|
||||
|
||||
dest = Path(tempfile.mkdtemp()) / "GIG"
|
||||
dest.mkdir(parents=True)
|
||||
items = []
|
||||
for track in chosen:
|
||||
audio = dest / "Music" / "Library" / Path(track.filepath).name
|
||||
audio.parent.mkdir(parents=True, exist_ok=True)
|
||||
audio.write_bytes(b"\0" * 64)
|
||||
items.append(ExportTrack(track=track, destination=audio, cues=src.track_cues(track.id)))
|
||||
|
||||
payload = ExportPayload(
|
||||
name="GIG",
|
||||
tracks=items,
|
||||
playlists=[
|
||||
ExportPlaylist(name="Peak Time", track_ids=[flexible.id, cued.id], folders=["House"]),
|
||||
ExportPlaylist(name="Warmup", track_ids=[cued.id], folders=["House", "Slow"]),
|
||||
],
|
||||
)
|
||||
result = exporter.write(payload, dest)
|
||||
written = result.library
|
||||
check("the exporter reports what it wrote", result.all_paths == [written])
|
||||
text = written.read_text(encoding="utf-8")
|
||||
|
||||
print("== the skeleton is what Traktor writes ==")
|
||||
check("named collection.nml", written.name == "collection.nml")
|
||||
check("the XML declaration is there", text.startswith('<?xml version="1.0" encoding="UTF-8"'))
|
||||
check("NML VERSION 20", '<NML VERSION="20">' in text)
|
||||
check("a HEAD element", "<HEAD " in text)
|
||||
# Measured from a real Traktor file: it has no MUSICFOLDERS at all.
|
||||
check("no MUSICFOLDERS is required", "<MUSICFOLDERS" not in SKELETON)
|
||||
check("SETS is present and empty", '<SETS ENTRIES="0">' in text)
|
||||
# Playlists cannot sit at the top level; they hang off a $ROOT FOLDER node.
|
||||
check("PLAYLISTS wraps a $ROOT folder", '<NODE TYPE="FOLDER" NAME="$ROOT">' in text)
|
||||
check("INDEXING is present", '<SORTING_INFO PATH="$COLLECTION">' in text)
|
||||
check("the ENTRIES header matches the entry count",
|
||||
f'<COLLECTION ENTRIES="{len(chosen)}">' in text,
|
||||
re.search(r'<COLLECTION ENTRIES="\d+"', text).group(0))
|
||||
|
||||
print("== LOCATION is volume-relative — the reason a stick is portable ==")
|
||||
locations = re.findall(r'<LOCATION DIR="([^"]*)" FILE="([^"]*)" VOLUME="([^"]*)"', text)
|
||||
check("every track has a location", len(locations) == len(chosen))
|
||||
check("no host path leaks into DIR",
|
||||
all(not d.startswith("/:Users/:") or "/:Music/:Library/:" in d for d, _f, _v in locations),
|
||||
[d for d, _f, _v in locations])
|
||||
check("DIR is volume-relative, ending at the audio folder",
|
||||
all(d.endswith("/:Music/:Library/:") for d, _f, _v in locations),
|
||||
[d for d, _f, _v in locations])
|
||||
check("VOLUME is a name, not a path",
|
||||
all("/" not in v for _d, _f, v in locations), [v for _d, _f, v in locations])
|
||||
check("FILE is just the filename",
|
||||
all("/" not in f for _d, f, _v in locations))
|
||||
|
||||
print("== it re-opens as a library ==")
|
||||
back = TraktorDriver().open(written)
|
||||
check("every track came across", len(back.tracks) == len(chosen))
|
||||
by_title = {t.title: t for t in back.tracks}
|
||||
check("titles survived", all(t.title in by_title for t in chosen),
|
||||
sorted(set(t.title for t in chosen) - set(by_title)))
|
||||
check("artist survived", by_title[plain.title].artist == plain.artist)
|
||||
# Traktor→Traktor copies the key string verbatim: a user's notation is a
|
||||
# preference their exported library should not silently change.
|
||||
if plain.key:
|
||||
check("key notation is copied, not converted", by_title[plain.title].key == plain.key)
|
||||
|
||||
print("== the playlist tree ==")
|
||||
tree = {}
|
||||
|
||||
|
||||
def walk(nodes, path=()):
|
||||
for n in nodes:
|
||||
tree[path + (n.name,)] = n
|
||||
walk(n.children, path + (n.name,))
|
||||
|
||||
|
||||
walk(back.playlist_tree())
|
||||
check("one folder named after the export", ("GIG",) in tree and tree[("GIG",)].kind == "folder")
|
||||
check("nested folders are preserved", ("GIG", "House") in tree)
|
||||
check("and nest further", ("GIG", "House", "Slow") in tree)
|
||||
check("playlists land in their folder",
|
||||
("GIG", "House", "Peak Time") in tree and ("GIG", "House", "Slow", "Warmup") in tree)
|
||||
check("with the right counts",
|
||||
tree[("GIG", "House", "Peak Time")].count == 2
|
||||
and tree[("GIG", "House", "Slow", "Warmup")].count == 1)
|
||||
# A track added individually would otherwise be reachable only by search.
|
||||
check("loose tracks get an 'Other' playlist", ("GIG", "Other") in tree)
|
||||
check("holding exactly the ones no playlist claimed",
|
||||
tree[("GIG", "Other")].count == 1, tree[("GIG", "Other")].count)
|
||||
other_ids = back.playlist_entries(tree[("GIG", "Other")].id)
|
||||
check("and it is the right track",
|
||||
back.track(other_ids[0]).title == plain.title)
|
||||
|
||||
print("== the prep crossed intact ==")
|
||||
src_grid = src.track_cues(flexible.id)
|
||||
out_grid = back.track_cues(by_title[flexible.title].id)
|
||||
check("a flexible multi-marker grid survives",
|
||||
len(out_grid.grid_markers) == len(src_grid.grid_markers),
|
||||
f"{len(out_grid.grid_markers)} vs {len(src_grid.grid_markers)}")
|
||||
check("with its tempo changes",
|
||||
[round(m.bpm, 3) for m in out_grid.grid_markers]
|
||||
== [round(m.bpm, 3) for m in src_grid.grid_markers])
|
||||
check("and its marker positions",
|
||||
[round(m.start, 3) for m in out_grid.grid_markers]
|
||||
== [round(m.start, 3) for m in src_grid.grid_markers])
|
||||
# Ben's decision: exported grids are NOT locked, so they stay editable like any
|
||||
# other track. If Traktor turns out to re-analyse and flatten them, this is what
|
||||
# makes that visible rather than hidden behind a lock.
|
||||
check("grids are not locked", not by_title[flexible.title].grid_locked)
|
||||
|
||||
src_cues = src.track_cues(cued.id)
|
||||
out_cues = back.track_cues(by_title[cued.title].id)
|
||||
src_hot = {c.slot: round(c.start, 3) for c in src_cues.cues if c.role == "hotcue"}
|
||||
out_hot = {c.slot: round(c.start, 3) for c in out_cues.cues if c.role == "hotcue"}
|
||||
check("hot cues keep their PAD, not just their position", out_hot == src_hot,
|
||||
f"{out_hot} vs {src_hot}")
|
||||
|
||||
print("== writing twice into the same folder replaces, never appends ==")
|
||||
again = exporter.write(payload, dest).library
|
||||
check("the entry count did not double",
|
||||
f'<COLLECTION ENTRIES="{len(chosen)}">' in again.read_text(encoding="utf-8"))
|
||||
check("and the tree did not duplicate",
|
||||
len(TraktorDriver().open(again).playlist_tree()) == 1)
|
||||
|
||||
# ==============================================================================
|
||||
# Running an export: the copy, the safety rules, and the rollback.
|
||||
# ==============================================================================
|
||||
import tempfile as _tf # noqa: E402
|
||||
import time # noqa: E402
|
||||
|
||||
os.environ.setdefault("KONDUKTOR_DATA_DIR", _tf.mkdtemp())
|
||||
from konduktor import exporter, exports # noqa: E402
|
||||
from konduktor.app_state import STATE # noqa: E402
|
||||
from konduktor.core.export import ExportPayload as _Payload # noqa: E402
|
||||
from konduktor.jobs import JOBS, JobCancelled # noqa: E402
|
||||
|
||||
# A SOURCE library whose audio genuinely exists on disk — built with the very
|
||||
# exporter tested above, which is the cheapest way to get real LOCATIONs.
|
||||
lib_root = Path(tempfile.mkdtemp()) / "MyMusic"
|
||||
seed_items = []
|
||||
for i, track in enumerate(src.tracks[:4]):
|
||||
audio = lib_root / ("House" if i % 2 else "Techno") / Path(track.filepath).name
|
||||
audio.parent.mkdir(parents=True, exist_ok=True)
|
||||
audio.write_bytes(b"\0" * 300_000)
|
||||
seed_items.append(ExportTrack(track=track, destination=audio, cues=src.track_cues(track.id)))
|
||||
exporter_obj = core_export.for_platform("traktor")
|
||||
exporter_obj.write(
|
||||
_Payload(name="Source", tracks=seed_items,
|
||||
playlists=[ExportPlaylist(name="Peak Time",
|
||||
track_ids=[src.tracks[0].id, src.tracks[1].id])]),
|
||||
lib_root,
|
||||
)
|
||||
STATE.open(lib_root / "collection.nml")
|
||||
ad = STATE.adapter
|
||||
LIB = STATE.library_id
|
||||
|
||||
dest = Path(tempfile.mkdtemp()) / "GIG"
|
||||
eset = exports.create(LIB, name="GIG", target="traktor", destination=str(dest))
|
||||
source_pl = next(n for n in ad.playlist_tree()[0].children if n.kind == "playlist")
|
||||
exports.add(LIB, eset.id, playlist_ids=[source_pl.id], track_ids=[ad.tracks[3].id])
|
||||
eset = exports.get(LIB, eset.id)
|
||||
|
||||
|
||||
def run_now(plan):
|
||||
job = JOBS.submit("export", lambda h: exporter.run(ad, eset, plan, h))
|
||||
while not job.finished:
|
||||
time.sleep(0.02)
|
||||
return job
|
||||
|
||||
|
||||
print("== the plan mirrors the source tree, relative to its shared root ==")
|
||||
built = exporter.plan(ad, eset)
|
||||
check("nothing is blocking it", built.blocked is None, str(built.blocked))
|
||||
check("every track has somewhere to go", all(t.destination for t in built.exportable))
|
||||
rel = [str(t.destination.relative_to(dest)) for t in built.exportable]
|
||||
# Mirroring ABSOLUTE paths would put the user's home directory on the stick.
|
||||
check("the user's own folders are preserved",
|
||||
all(r.startswith(("House/", "Techno/")) for r in rel), rel)
|
||||
check("and nothing above the shared root comes with them",
|
||||
not any("Users" in r or r.startswith("/") for r in rel), rel)
|
||||
check("space is checked before starting", exporter.space_for(built) is not None)
|
||||
|
||||
print("== running it ==")
|
||||
job = run_now(built)
|
||||
check("it finishes", job.state == "done", f"{job.state}: {job.error}")
|
||||
check("every track was copied", job.result["tracks"] == len(built.exportable))
|
||||
check("the library was written", (dest / "collection.nml").is_file())
|
||||
check("and a manifest beside it", (dest / exporter.MANIFEST_NAME).is_file())
|
||||
check("the audio is really there",
|
||||
all((dest / r).stat().st_size == 300_000 for r in rel))
|
||||
check("the result re-opens as a library",
|
||||
len(TraktorDriver().open(dest / "collection.nml").tracks) == len(built.exportable))
|
||||
|
||||
print("== Konduktor only ever deletes what Konduktor wrote ==")
|
||||
mine = dest / "MY OWN NOTES.txt"
|
||||
mine.write_text("do not delete")
|
||||
again = exporter.plan(ad, exports.get(LIB, eset.id))
|
||||
# The folder is now non-empty AND has a manifest, so it is ours to replace.
|
||||
check("a folder we wrote is not blocked", again.blocked is None)
|
||||
check("and is reported as a replacement", again.replacing)
|
||||
job2 = run_now(again)
|
||||
check("the re-export succeeds", job2.state == "done", f"{job2.state}: {job2.error}")
|
||||
check("a file the USER put there survives", mine.is_file() and mine.read_text() == "do not delete")
|
||||
check("the audio did not double up",
|
||||
len([p for p in dest.rglob("*") if p.is_file()]) == len(rel) + 3, # + nml, manifest, notes
|
||||
sorted(str(p.relative_to(dest)) for p in dest.rglob("*") if p.is_file()))
|
||||
|
||||
print("== a folder we did NOT write is refused, not confirmed ==")
|
||||
foreign = Path(tempfile.mkdtemp()) / "Documents"
|
||||
foreign.mkdir()
|
||||
(foreign / "tax return.pdf").write_text("important")
|
||||
exports.update(LIB, eset.id, destination=str(foreign))
|
||||
blocked = exporter.plan(ad, exports.get(LIB, eset.id))
|
||||
check("it is blocked", blocked.blocked == exporter.BLOCKED_OCCUPIED, str(blocked.blocked))
|
||||
check("the user's file is untouched", (foreign / "tax return.pdf").read_text() == "important")
|
||||
# There is deliberately no "do it anyway": run() refuses a blocked plan even if
|
||||
# a caller ignored the preview.
|
||||
try:
|
||||
exporter.run(ad, exports.get(LIB, eset.id), blocked, None)
|
||||
check("run refuses a blocked plan", False, "it ran")
|
||||
except ValueError:
|
||||
check("run refuses a blocked plan even when asked directly", True)
|
||||
check("and still nothing was deleted", (foreign / "tax return.pdf").is_file())
|
||||
# An EMPTY folder is fine — there is nothing there to lose.
|
||||
empty = Path(tempfile.mkdtemp()) / "Empty"
|
||||
empty.mkdir()
|
||||
check("an empty folder is allowed", exporter.destination_blocked(empty) is None)
|
||||
check("a folder that does not exist yet is allowed",
|
||||
exporter.destination_blocked(empty / "nested" / "deeper") is None)
|
||||
# A stick's root after its first mount on a Mac: not empty to iterdir(), but
|
||||
# nothing in it is the user's.
|
||||
stick = Path(tempfile.mkdtemp()) / "STICK"
|
||||
for d in (".Spotlight-V100", ".fseventsd", ".Trashes", "System Volume Information"):
|
||||
(stick / d).mkdir(parents=True)
|
||||
for f in (".DS_Store", "._Track.mp3", "Thumbs.db"):
|
||||
(stick / f).write_bytes(b"")
|
||||
check("OS housekeeping does not make a folder occupied",
|
||||
exporter.destination_blocked(stick) is None)
|
||||
(stick / "My Set.mp3").write_bytes(b"")
|
||||
check("but one file of the user's still does",
|
||||
exporter.destination_blocked(stick) == exporter.BLOCKED_OCCUPIED)
|
||||
|
||||
print("== cancelling rolls back, leaving an empty folder ==")
|
||||
fresh = Path(tempfile.mkdtemp()) / "Cancelled"
|
||||
exports.update(LIB, eset.id, destination=str(fresh))
|
||||
cancel_plan = exporter.plan(ad, exports.get(LIB, eset.id))
|
||||
|
||||
|
||||
class _CancelAfter:
|
||||
"""Deterministic cancellation: stop partway through the second file."""
|
||||
|
||||
def __init__(self, after):
|
||||
self.n, self.after = 0, after
|
||||
|
||||
def progress(self, **kw):
|
||||
pass
|
||||
|
||||
@property
|
||||
def cancelled(self):
|
||||
return self.n >= self.after
|
||||
|
||||
def raise_if_cancelled(self):
|
||||
self.n += 1
|
||||
if self.cancelled:
|
||||
raise JobCancelled()
|
||||
|
||||
|
||||
try:
|
||||
exporter.run(ad, exports.get(LIB, eset.id), cancel_plan, _CancelAfter(3))
|
||||
check("it stops", False, "it did not raise")
|
||||
except JobCancelled:
|
||||
check("it stops", True)
|
||||
check("NO library file was written", not (fresh / "collection.nml").exists())
|
||||
check("no manifest either", not (fresh / exporter.MANIFEST_NAME).exists())
|
||||
# Including the file being written when the cancel landed. Cleaning up only
|
||||
# COMPLETED copies leaves the in-flight one behind — the bug import had.
|
||||
leftover = [p for p in fresh.rglob("*") if p.is_file()] if fresh.exists() else []
|
||||
check("and no audio was left behind", leftover == [], [str(p) for p in leftover])
|
||||
|
||||
print("== a missing file is skipped, not fatal ==")
|
||||
gone = Path(seed_items[0].destination)
|
||||
gone.unlink()
|
||||
partial = exporter.plan(ad, exports.get(LIB, eset.id))
|
||||
check("it is reported", len([t for t in partial.tracks if t.missing]) == 1)
|
||||
check("the rest still export", len(partial.exportable) == len(built.exportable) - 1)
|
||||
check("and it is not blocking", partial.blocked is None)
|
||||
|
||||
print("== the source is where the ADAPTER resolves it, not the display path ==")
|
||||
# The bug: a collection on a drive (or a Windows collection with an X: → /Volumes
|
||||
# mapping) exported "nothing", because the plan read `Track.filepath` — a display
|
||||
# path without the volume or the active mapping — and called every track missing.
|
||||
import shutil # noqa: E402
|
||||
from konduktor.core.pathmap import PathMapping # noqa: E402
|
||||
|
||||
moved_root = Path(tempfile.mkdtemp()) / "Elsewhere"
|
||||
for sub in ("House", "Techno"):
|
||||
shutil.copytree(lib_root / sub, moved_root / sub)
|
||||
shutil.rmtree(lib_root / sub)
|
||||
ad.set_path_mapping(PathMapping.make(str(lib_root), str(moved_root)))
|
||||
remapped = exporter.plan(ad, exports.get(LIB, eset.id))
|
||||
check("every surviving track is found through the mapping",
|
||||
len(remapped.exportable) == len(partial.exportable),
|
||||
f"{len(remapped.exportable)} of {len(partial.exportable)}")
|
||||
check("and it is copied from the mapped location",
|
||||
all(str(t.source_path).startswith(str(moved_root)) for t in remapped.exportable))
|
||||
ad.set_path_mapping(PathMapping())
|
||||
|
||||
print("\n" + ("❌ FAILED" if failed else "✅ PASSED"))
|
||||
raise SystemExit(1 if failed else 0)
|
||||
@@ -0,0 +1,185 @@
|
||||
"""The two Pioneer export targets, against the same contract as Traktor's.
|
||||
|
||||
`test_export.py` proves a Traktor collection can be written from nothing. These
|
||||
two are harder in a way that test cannot cover: each writes a **database plus
|
||||
per-track analysis files**, so what "the library" means is no longer one path,
|
||||
and the prep has to survive a genuine change of representation rather than a
|
||||
re-render of the same format.
|
||||
|
||||
Three crossings are worth pinning because each fails SILENTLY:
|
||||
|
||||
* **Key notation.** The generic `Track.key` is the SOURCE platform's display
|
||||
string — Traktor's "10m". Copying it verbatim puts "10m" where a Pioneer
|
||||
deck expects "Cm". The only correct crossing is via `key_wheel`/`key_mode`.
|
||||
* **Hot-cue slot numbering.** ANLZ uses a DENSE 1-based `hot_cue`; `master.db`
|
||||
uses a SPARSE `Kind` bank that skips 4. Reuse one for the other and every
|
||||
cue from pad D lands one pad too far along — a cue in the wrong place, not
|
||||
an error.
|
||||
* **The beatgrid changes shape.** Traktor's is a marker list; Pioneer's is
|
||||
every beat. It has to expand on the way out and collapse back identically.
|
||||
|
||||
Both exports are read back with Konduktor's OWN adapters, which is the strongest
|
||||
check available without the hardware: the reader is the code that has to accept
|
||||
what the writer produced, and it was written against real rekordbox output.
|
||||
"""
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp()
|
||||
|
||||
from konduktor.adapters.onelibrary.driver import OneLibraryDriver # noqa: E402
|
||||
from konduktor.adapters.rekordbox.driver import RekordboxDriver # noqa: E402
|
||||
from konduktor.adapters.rekordbox.projection import parse_key, render_key # noqa: E402
|
||||
from konduktor.adapters.traktor.driver import TraktorDriver # noqa: E402
|
||||
from konduktor.adapters.traktor.projection import parse_key as traktor_key_parse # noqa: E402
|
||||
from konduktor.core import export as core_export # noqa: E402
|
||||
from konduktor.core.export import ExportPayload, ExportPlaylist, ExportTrack # noqa: E402
|
||||
|
||||
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
|
||||
|
||||
|
||||
FIXTURE = Path(__file__).resolve().parents[1] / "collection.nml"
|
||||
src = TraktorDriver().open(FIXTURE)
|
||||
|
||||
# A flexible multi-tempo grid and a track with cues past pad C: the two things
|
||||
# most likely to be quietly wrong.
|
||||
flexible = next(t for t in src.tracks if (t.grid_marker_count or 0) > 1)
|
||||
cued = next(t for t in src.tracks
|
||||
if (t.cue_count or 0) >= 5 and t.id != flexible.id)
|
||||
chosen = [flexible, cued]
|
||||
|
||||
|
||||
def build(root: Path) -> ExportPayload:
|
||||
items = []
|
||||
for i, track in enumerate(chosen):
|
||||
audio = root / ("House" if i % 2 else "Techno") / Path(track.filepath).name
|
||||
audio.parent.mkdir(parents=True, exist_ok=True)
|
||||
audio.write_bytes(b"\0" * 4096)
|
||||
items.append(ExportTrack(track=track, destination=audio,
|
||||
cues=src.track_cues(track.id)))
|
||||
return ExportPayload(
|
||||
name="GIG", tracks=items,
|
||||
playlists=[ExportPlaylist(name="Peak Time",
|
||||
track_ids=[t.id for t in chosen],
|
||||
folders=["House"])],
|
||||
)
|
||||
|
||||
|
||||
def hotcues(cues):
|
||||
return sorted((c.slot, round(c.start, 2)) for c in cues.cues if c.role == "hotcue")
|
||||
|
||||
|
||||
def grid(cues):
|
||||
return [(round(m.start, 2), round(m.bpm, 2)) for m in cues.grid_markers]
|
||||
|
||||
|
||||
print("== the key crossing, as a unit ==")
|
||||
# Traktor Open Key -> Camelot wheel -> Pioneer's musical naming.
|
||||
for traktor_key, expected in (("10m", "Cm"), ("1m", "Am"), ("12d", "F")):
|
||||
wheel, mode = traktor_key_parse(traktor_key)
|
||||
check(f"{traktor_key} renders as {expected}", render_key(wheel, mode) == expected,
|
||||
render_key(wheel, mode))
|
||||
check("all 24 keys round-trip through the wheel",
|
||||
all(parse_key(render_key(*parse_key(n))) == parse_key(n)
|
||||
for n in ("Abm", "Am", "Bbm", "Bm", "Cm", "C#m", "Dm", "Ebm", "Em",
|
||||
"Fm", "F#m", "Gm", "C", "Db", "D", "Eb", "E", "F", "F#",
|
||||
"G", "Ab", "A", "Bb", "B")))
|
||||
check("an unknown key stays blank rather than invented",
|
||||
render_key(None, None) is None and render_key(99, "minor") is None)
|
||||
|
||||
|
||||
for platform, reopen in (
|
||||
("onelibrary", lambda r: OneLibraryDriver().open(r)),
|
||||
("rekordbox", lambda r: RekordboxDriver().open(r / "master.db")),
|
||||
):
|
||||
print(f"\n== {platform}: a library written from nothing ==")
|
||||
exporter = core_export.for_platform(platform)
|
||||
check("it is a registered target", exporter is not None)
|
||||
caps = exporter.capabilities()
|
||||
# The OneLibrary ADAPTER reports read-only — Konduktor cannot edit a drive
|
||||
# in place. An export target is a different question and the answer is yes.
|
||||
check("static capabilities say it is writable", caps.writable, str(caps.readonly_cause))
|
||||
|
||||
root = Path(tempfile.mkdtemp()) / "GIG"
|
||||
payload = build(root)
|
||||
written = exporter.write(payload, root)
|
||||
|
||||
check("the library exists", written.library.is_file(), str(written.library))
|
||||
check("and is inside the destination",
|
||||
written.library.is_relative_to(root))
|
||||
# Both write a database PLUS per-track analysis files. Under-reporting them
|
||||
# leaves orphans a re-export cannot clear, because the manifest is the list.
|
||||
check("analysis files are REPORTED, not just written",
|
||||
len(written.extra) >= len(chosen), f"{len(written.extra)} for {len(chosen)} tracks")
|
||||
check("every reported path exists", all(p.is_file() for p in written.extra))
|
||||
check("all_paths includes the library",
|
||||
written.library in written.all_paths
|
||||
and len(written.all_paths) == len(written.extra) + 1)
|
||||
|
||||
back = reopen(root)
|
||||
check("it re-opens with Konduktor's own adapter", len(back.tracks) == len(chosen),
|
||||
f"{len(back.tracks)} of {len(chosen)}")
|
||||
by_title = {t.title: t for t in back.tracks}
|
||||
check("titles survived", all(t.title in by_title for t in chosen))
|
||||
check("artists survived",
|
||||
all(by_title[t.title].artist == t.artist for t in chosen if t.artist))
|
||||
check("bpm survived",
|
||||
all(abs((by_title[t.title].bpm or 0) - (t.bpm or 0)) < 0.02
|
||||
for t in chosen if t.bpm))
|
||||
|
||||
print(f"-- {platform}: the key was CONVERTED, not copied")
|
||||
for track in chosen:
|
||||
if not track.key:
|
||||
continue
|
||||
out = by_title[track.title].key
|
||||
wheel, mode = traktor_key_parse(track.key)
|
||||
check(f"{track.key!r} -> {out!r}", out == render_key(wheel, mode),
|
||||
f"expected {render_key(wheel, mode)}")
|
||||
check("and is NOT the source's own notation", out != track.key)
|
||||
|
||||
print(f"-- {platform}: the prep crossed")
|
||||
for track in chosen:
|
||||
s, o = src.track_cues(track.id), back.track_cues(by_title[track.title].id)
|
||||
check(f"{track.title[:22]}: hot cues keep their PAD",
|
||||
hotcues(o) == hotcues(s), f"{hotcues(o)} vs {hotcues(s)}")
|
||||
check(f"{track.title[:22]}: the grid survives expansion + collapse",
|
||||
grid(o) == grid(s), f"{grid(o)} vs {grid(s)}")
|
||||
check("the flexible grid really is multi-tempo",
|
||||
len({b for _a, b in grid(src.track_cues(flexible.id))}) > 1)
|
||||
check("and a cue past pad C came across",
|
||||
max((c.slot or 0) for c in src.track_cues(cued.id).cues) >= 3)
|
||||
|
||||
print(f"-- {platform}: the playlist tree")
|
||||
tree = {}
|
||||
|
||||
def walk(nodes, path=()):
|
||||
for n in nodes:
|
||||
tree[path + (n.name,)] = n
|
||||
walk(n.children, path + (n.name,))
|
||||
|
||||
tree.clear()
|
||||
walk(back.playlist_tree())
|
||||
check("a folder named after the export", ("GIG",) in tree)
|
||||
check("nested folders are preserved", ("GIG", "House") in tree)
|
||||
check("with the playlist inside",
|
||||
("GIG", "House", "Peak Time") in tree
|
||||
and tree[("GIG", "House", "Peak Time")].count == len(chosen))
|
||||
|
||||
print(f"-- {platform}: re-exporting replaces rather than doubling")
|
||||
again = exporter.write(build(root), root)
|
||||
reopened = reopen(root)
|
||||
check("the track count did not double", len(reopened.tracks) == len(chosen),
|
||||
str(len(reopened.tracks)))
|
||||
check("nor did the tree", len(reopened.playlist_tree()) == 1)
|
||||
check("and it still reports its files", len(again.all_paths) == len(written.all_paths))
|
||||
|
||||
print("\n" + ("❌ FAILED" if failed else "✅ PASSED"))
|
||||
raise SystemExit(1 if failed else 0)
|
||||
@@ -0,0 +1,207 @@
|
||||
"""Export sets: curation that outlives the session, keyed to a library.
|
||||
|
||||
The properties worth pinning are the ones that fail SILENTLY:
|
||||
|
||||
* a **live** playlist reference picks up later edits — a set that quietly
|
||||
froze at curation time would still look right and ship the wrong tracks;
|
||||
* contents **dedupe** across playlists and loose tracks, so one track is one
|
||||
file copy;
|
||||
* a deleted playlist or track is **surfaced**, never dropped — a gig stick
|
||||
missing four tracks with no warning is this feature's worst failure;
|
||||
* sets are **per library**, so opening another collection shows another shelf;
|
||||
* two sets pointing at one destination are **caught**, because an export
|
||||
CLEARS its destination and would wipe the other's output.
|
||||
|
||||
Runs against a temp COPY of the real collection, and a temp app-data dir, so it
|
||||
touches neither the user's library nor their real export sets.
|
||||
"""
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
_TMP = tempfile.TemporaryDirectory()
|
||||
os.environ["KONDUKTOR_DATA_DIR"] = _TMP.name
|
||||
|
||||
from konduktor import exports # noqa: E402
|
||||
from konduktor.app_state import STATE # noqa: E402
|
||||
|
||||
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
|
||||
|
||||
|
||||
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
|
||||
work = Path(tempfile.mkdtemp())
|
||||
shutil.copy2(REAL, work / "collection.nml")
|
||||
STATE.open(work / "collection.nml")
|
||||
adapter = STATE.adapter
|
||||
LIB = STATE.library_id
|
||||
check("opening a library issues an id", bool(LIB))
|
||||
|
||||
# A real playlist with tracks in it, to reference.
|
||||
def _first_playlist(nodes):
|
||||
for node in nodes or []:
|
||||
if node.kind == "playlist" and (node.count or 0) >= 2:
|
||||
return node
|
||||
found = _first_playlist(getattr(node, "children", None))
|
||||
if found:
|
||||
return found
|
||||
return None
|
||||
|
||||
|
||||
playlist = _first_playlist(adapter.playlist_tree())
|
||||
assert playlist is not None, "the fixture collection has no playlist with 2+ tracks"
|
||||
playlist_tracks = adapter.playlist_entries(playlist.id) or []
|
||||
all_tracks = [t.id for t in adapter.tracks]
|
||||
|
||||
print("== creating, listing, updating, deleting ==")
|
||||
s1 = exports.create(LIB, name="GIG", target="traktor", destination=str(work / "out"))
|
||||
check("a set is created with an id", bool(s1.id))
|
||||
check("it lists", [s.id for s in exports.all_sets(LIB)] == [s1.id])
|
||||
check("it survives a reload from disk", exports.get(LIB, s1.id).name == "GIG")
|
||||
exports.update(LIB, s1.id, name="Ibiza")
|
||||
check("rename persists", exports.get(LIB, s1.id).name == "Ibiza")
|
||||
check("and bumps modified", exports.get(LIB, s1.id).modified >= s1.created)
|
||||
|
||||
print("== membership: ordered, deduped, and removable ==")
|
||||
exports.add(LIB, s1.id, track_ids=[all_tracks[0], all_tracks[1]])
|
||||
exports.add(LIB, s1.id, track_ids=[all_tracks[1], all_tracks[2]])
|
||||
check("duplicates are ignored, order kept",
|
||||
exports.get(LIB, s1.id).track_ids == all_tracks[:3],
|
||||
exports.get(LIB, s1.id).track_ids)
|
||||
exports.add(LIB, s1.id, playlist_ids=[playlist.id, playlist.id])
|
||||
check("a playlist is added once", exports.get(LIB, s1.id).playlist_ids == [playlist.id])
|
||||
exports.remove(LIB, s1.id, track_ids=[all_tracks[1]])
|
||||
check("a loose track is removable",
|
||||
exports.get(LIB, s1.id).track_ids == [all_tracks[0], all_tracks[2]])
|
||||
|
||||
print("== resolution is LIVE and deduped ==")
|
||||
resolved = exports.resolve(adapter, exports.get(LIB, s1.id))
|
||||
check("the referenced playlist resolves by name",
|
||||
resolved.playlists[0].name == playlist.name and not resolved.playlists[0].missing)
|
||||
check("with its CURRENT tracks", resolved.playlists[0].track_ids == playlist_tracks)
|
||||
# The whole point of a reference: what ships is what the playlist holds at
|
||||
# export time, not what it held when it was dragged in.
|
||||
spare = next(t for t in all_tracks if t not in playlist_tracks)
|
||||
adapter.set_playlist_entries(playlist.id, playlist_tracks + [spare])
|
||||
again = exports.resolve(adapter, exports.get(LIB, s1.id))
|
||||
check("a track added to the playlist LATER is picked up",
|
||||
spare in again.playlists[0].track_ids)
|
||||
check("without the set itself changing",
|
||||
exports.get(LIB, s1.id).playlist_ids == [playlist.id])
|
||||
adapter.set_playlist_entries(playlist.id, playlist_tracks) # put it back
|
||||
|
||||
# One track, one file copy — even when it is both loose and in a playlist.
|
||||
exports.add(LIB, s1.id, track_ids=[playlist_tracks[0]])
|
||||
deduped = exports.resolve(adapter, exports.get(LIB, s1.id)).track_ids
|
||||
check("a track in a playlist AND loose appears once",
|
||||
deduped.count(playlist_tracks[0]) == 1, deduped)
|
||||
check("the total is the union, not the sum",
|
||||
len(deduped) == len(set(deduped)) and len(deduped) >= len(playlist_tracks))
|
||||
exports.remove(LIB, s1.id, track_ids=[playlist_tracks[0]])
|
||||
|
||||
# The bug this replaced: the "Other" row selected the export ROOT, so clicking
|
||||
# it showed every track the export would ship instead of only the loose ones.
|
||||
# Three views, three genuinely different questions.
|
||||
loose_view = exports.resolve(adapter, exports.get(LIB, s1.id)).loose_track_ids
|
||||
root_view = exports.resolve(adapter, exports.get(LIB, s1.id)).track_ids
|
||||
check("Other holds only the individually-added tracks",
|
||||
loose_view == exports.get(LIB, s1.id).track_ids, loose_view)
|
||||
check("which is NOT the same as the root view",
|
||||
loose_view != root_view and set(loose_view) < set(root_view),
|
||||
f"{len(loose_view)} vs {len(root_view)}")
|
||||
check("and the playlist's tracks are absent from it",
|
||||
not (set(loose_view) & set(playlist_tracks)))
|
||||
|
||||
print("== what is gone is SURFACED, never silently dropped ==")
|
||||
exports.add(LIB, s1.id, track_ids=["Macintosh HD/:nowhere/:ghost.mp3"])
|
||||
gone = exports.resolve(adapter, exports.get(LIB, s1.id))
|
||||
check("a track the library no longer has is reported",
|
||||
gone.dangling_track_ids == ["Macintosh HD/:nowhere/:ghost.mp3"])
|
||||
check("and is NOT counted as exportable",
|
||||
"Macintosh HD/:nowhere/:ghost.mp3" not in gone.track_ids)
|
||||
exports.remove(LIB, s1.id, track_ids=["Macintosh HD/:nowhere/:ghost.mp3"])
|
||||
|
||||
s2 = exports.create(LIB, name="Deleted playlist test", target="traktor",
|
||||
destination=str(work / "out2"))
|
||||
exports.add(LIB, s2.id, playlist_ids=["no-such-playlist"])
|
||||
ghost = exports.resolve(adapter, exports.get(LIB, s2.id))
|
||||
check("a deleted playlist is shown as missing, not dropped",
|
||||
len(ghost.playlists) == 1 and ghost.playlists[0].missing)
|
||||
check("and contributes no tracks", ghost.track_ids == [])
|
||||
|
||||
print("== two sets, one destination ==")
|
||||
# An export CLEARS its destination, so the second would wipe the first's output.
|
||||
# Caught when the destination is chosen, not when it is too late to warn.
|
||||
check("no conflict for distinct destinations",
|
||||
exports.destination_conflict(LIB, str(work / "out"), ignore=s1.id) is None)
|
||||
s3 = exports.create(LIB, name="Clash", target="traktor", destination=str(work / "out"))
|
||||
check("a clash is reported by NAME",
|
||||
exports.destination_conflict(LIB, str(work / "out"), ignore=s3.id) == "Ibiza")
|
||||
check("a set never conflicts with itself",
|
||||
exports.destination_conflict(LIB, str(work / "out"), ignore=s1.id) == "Clash")
|
||||
check("paths are compared normalised, not as strings",
|
||||
exports.destination_conflict(LIB, str(work / "out") + "/./", ignore=s3.id) == "Ibiza")
|
||||
exports.delete(LIB, s3.id)
|
||||
|
||||
print("== following track ids that change under a path remap ==")
|
||||
exports.retarget(LIB, {all_tracks[0]: "Macintosh HD/:Moved/:one.mp3"})
|
||||
check("a renamed id is followed",
|
||||
"Macintosh HD/:Moved/:one.mp3" in exports.get(LIB, s1.id).track_ids)
|
||||
check("and the old one is gone", all_tracks[0] not in exports.get(LIB, s1.id).track_ids)
|
||||
exports.retarget(LIB, {"Macintosh HD/:Moved/:one.mp3": all_tracks[0]})
|
||||
check("an empty mapping is a no-op",
|
||||
(exports.retarget(LIB, {}), exports.get(LIB, s1.id).track_ids[0])[1] == all_tracks[0])
|
||||
|
||||
print("== sets belong to ONE library ==")
|
||||
other = Path(tempfile.mkdtemp()) / "Other"
|
||||
other.mkdir()
|
||||
shutil.copy2(REAL, other / "collection.nml")
|
||||
STATE.open(other / "collection.nml")
|
||||
check("a different library has a different id", STATE.library_id != LIB)
|
||||
check("and an empty shelf", exports.all_sets(STATE.library_id) == [])
|
||||
check("the first library's sets are untouched", len(exports.all_sets(LIB)) == 2)
|
||||
# Stored per library, so one shelf cannot be read through the other's id.
|
||||
check("stores are separate files",
|
||||
exports._store_path(LIB) != exports._store_path(STATE.library_id))
|
||||
|
||||
print("== deleting a set leaves the destination alone ==")
|
||||
dest = work / "out"
|
||||
dest.mkdir(parents=True, exist_ok=True)
|
||||
(dest / "already-there.txt").write_text("x")
|
||||
exports.delete(LIB, s1.id)
|
||||
check("the set is gone", exports.get(LIB, s1.id) is None)
|
||||
check("the destination folder is NOT touched", (dest / "already-there.txt").is_file())
|
||||
|
||||
print("== a path rewrite carries every set's track ids with it ==")
|
||||
# Through the ROUTE, not exports.retarget: the route is what joins the adapter's
|
||||
# renames to the sets, and it once 500'd on every call with no test to notice.
|
||||
from fastapi.testclient import TestClient # noqa: E402
|
||||
|
||||
import konduktor.main as main # noqa: E402
|
||||
|
||||
ad, lib = STATE.adapter, STATE.library_id
|
||||
prefix = ad.path_prefix_suggestions()["primary"]
|
||||
loose = next(t.id for t in ad.tracks if str(ad.audio_path(t.id) or "").startswith(prefix))
|
||||
s3 = exports.create(lib, name="Remapped", target="traktor", destination=str(work / "remapped"))
|
||||
exports.add(lib, s3.id, track_ids=[loose])
|
||||
r = TestClient(main.app, raise_server_exceptions=False).post(
|
||||
"/api/library/remap-paths", json={"from": prefix, "to": "/Volumes/KonduktorTest"}
|
||||
)
|
||||
check("the route answers 200", r.status_code == 200, r.text[:300])
|
||||
check("and rewrote tracks", r.status_code == 200 and r.json()["rewritten"] > 0, r.text[:300])
|
||||
followed = exports.get(lib, s3.id).track_ids
|
||||
check("the set no longer holds the old id", loose not in followed, str(followed))
|
||||
check("it holds the track's NEW id",
|
||||
len(followed) == 1 and ad.track(followed[0]) is not None
|
||||
and str(ad.audio_path(followed[0])).startswith("/Volumes/KonduktorTest"), str(followed))
|
||||
|
||||
print("\n" + ("❌ FAILED" if failed else "✅ PASSED"))
|
||||
_TMP.cleanup()
|
||||
raise SystemExit(1 if failed else 0)
|
||||
@@ -0,0 +1,203 @@
|
||||
"""Browsing drives and folders, and adding loose files, through the routes.
|
||||
|
||||
Runs on a temp copy of the real collection, a temp app-data dir, and FLAC files
|
||||
generated here — so the tags are known rather than borrowed from a real file.
|
||||
|
||||
Pins the things that would fail SILENTLY or dangerously:
|
||||
|
||||
* a folder lists only the audio DIRECTLY in it, and never hidden or
|
||||
OS-housekeeping files (macOS writes a `._` twin beside every file on FAT);
|
||||
* the audio route streams only files a scan found — it is not a way to read
|
||||
any path on the disk;
|
||||
* a file the collection already points at is never added twice. On Traktor two
|
||||
entries for one path share a primary key, which is a corrupt collection —
|
||||
and that is exactly what "add in place" would do on a second click;
|
||||
* such a file still reaches the playlist or export it was headed for;
|
||||
* "copy" leaves the collection pointing at the COPY, and "reference" at the
|
||||
original, with nothing copied.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
|
||||
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
|
||||
_DATA = tempfile.TemporaryDirectory()
|
||||
os.environ["KONDUKTOR_DATA_DIR"] = _DATA.name
|
||||
|
||||
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 flac(path: Path, **tags) -> Path:
|
||||
from mutagen.flac import FLAC
|
||||
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
sf.write(path, np.zeros((44100, 2), dtype="float32"), 44100, format="FLAC")
|
||||
audio = FLAC(path)
|
||||
for k, v in tags.items():
|
||||
audio[k] = str(v)
|
||||
audio.save()
|
||||
return path
|
||||
|
||||
|
||||
# ---- the folder on disk ------------------------------------------------------
|
||||
music = Path(tempfile.mkdtemp()) / "Loose"
|
||||
one = flac(music / "one.flac", title="First Light", artist="Someone", genre="House", bpm=124)
|
||||
two = flac(music / "two.flac") # untagged: titled by its filename
|
||||
flac(music / "Deeper" / "three.flac", title="Not Listed")
|
||||
(music / "notes.txt").write_text("not audio")
|
||||
shutil.copy2(one, music / "._one.flac") # a macOS AppleDouble twin
|
||||
flac(music / ".hidden.flac")
|
||||
(music / ".secret-folder").mkdir()
|
||||
(music / ".Trashes").mkdir()
|
||||
|
||||
work = Path(tempfile.mkdtemp()) / "collection.nml"
|
||||
shutil.copy2(REAL, work)
|
||||
os.environ["KONDUKTOR_NML"] = str(work)
|
||||
|
||||
from fastapi.testclient import TestClient # noqa: E402
|
||||
|
||||
import konduktor.main as main # noqa: E402
|
||||
from konduktor import exports # noqa: E402
|
||||
from konduktor.app_state import STATE # noqa: E402
|
||||
from konduktor.core import places # noqa: E402
|
||||
|
||||
|
||||
def wait(c, job):
|
||||
while job["state"] == "running":
|
||||
time.sleep(0.05)
|
||||
job = c.get(f"/api/jobs/{job['id']}").json()
|
||||
return job
|
||||
|
||||
|
||||
with TestClient(main.app, raise_server_exceptions=False) as c:
|
||||
a = main.require_adapter()
|
||||
before = len(a.tracks)
|
||||
|
||||
print("== drives ==")
|
||||
r = c.get("/api/fs/drives")
|
||||
check("answers 200", r.status_code == 200, r.text[:200])
|
||||
drives = r.json()
|
||||
check("the boot disk is local, at the filesystem root",
|
||||
any(d["kind"] == "local" and d["path"] == "/" for d in drives), str(drives))
|
||||
check("each drive is listed once", len({d["path"] for d in drives}) == len(drives))
|
||||
|
||||
print("== folder tree: visible folders only ==")
|
||||
r = c.get("/api/fs/folders", params={"path": str(music)})
|
||||
names = [e["name"] for e in r.json()]
|
||||
check("lists the subfolder", names == ["Deeper"], str(names))
|
||||
if sys.platform == "darwin":
|
||||
flagged = music / "Flagged"
|
||||
flagged.mkdir()
|
||||
os.chflags(flagged, 0x8000) # UF_HIDDEN, as macOS sets on /usr and /bin
|
||||
names = [e["name"] for e in c.get("/api/fs/folders", params={"path": str(music)}).json()]
|
||||
check("a folder hidden by FLAG is left out, as Finder does", "Flagged" not in names, str(names))
|
||||
check("a missing folder is a 404",
|
||||
c.get("/api/fs/folders", params={"path": str(music / "nope")}).status_code == 404)
|
||||
|
||||
print("== a folder's tracks: this folder only, audio only ==")
|
||||
r = c.get("/api/folder/tracks", params={"path": str(music)})
|
||||
check("answers 200", r.status_code == 200, r.text[:300])
|
||||
body = r.json()
|
||||
ids = [t["id"] for t in body["tracks"]]
|
||||
check("exactly the two visible audio files", ids == [str(one), str(two)], str(ids))
|
||||
first = body["tracks"][0]
|
||||
check("tags are read", (first["title"], first["artist"], first["genre"], first["bpm"])
|
||||
== ("First Light", "Someone", "House", 124.0), str(first))
|
||||
check("an untagged file is titled by its name", body["tracks"][1]["title"] == "two")
|
||||
check("the length comes from the audio", first["length"] == 1, str(first["length"]))
|
||||
check("nothing is in the collection yet", body["in_collection"] == [])
|
||||
caps = c.get("/api/folder/capabilities", params={"path": str(music)}).json()
|
||||
check("the view is read-only, and says why",
|
||||
caps["writable"] is False and caps["readonly_cause"] == "not_in_library")
|
||||
|
||||
print("== the audio route streams only what a scan found ==")
|
||||
r = c.get("/api/folder/tracks/audio", params={"track_id": str(one)})
|
||||
check("a scanned file streams", r.status_code == 200 and len(r.content) > 0)
|
||||
check("an arbitrary file does not",
|
||||
c.get("/api/folder/tracks/audio", params={"track_id": "/etc/passwd"}).status_code == 404)
|
||||
check("nor does real audio in a folder nobody browsed",
|
||||
c.get("/api/folder/tracks/audio",
|
||||
params={"track_id": str(music / "Deeper" / "three.flac")}).status_code == 404)
|
||||
check("nor a hidden file beside a scanned one",
|
||||
c.get("/api/folder/tracks/audio",
|
||||
params={"track_id": str(music / ".hidden.flac")}).status_code == 404)
|
||||
check("cues are empty, not an error",
|
||||
c.get("/api/folder/tracks/cues", params={"track_id": str(one)}).json()["cues"] == [])
|
||||
|
||||
print("== reference in place, into a playlist ==")
|
||||
playlist = a.create_playlist("Folder Test")
|
||||
req = {"track_ids": [str(one)], "mode": "reference", "playlist_id": playlist}
|
||||
p = c.post("/api/folder/add/preview", json=req).json()
|
||||
check("the preview counts one to add", p["importable"] == 1 and p["existing"] == [], str(p))
|
||||
check("and nothing to copy", p["total_bytes"] == 0)
|
||||
job = wait(c, c.post("/api/folder/add", json=req).json())
|
||||
check("the job finishes", job["state"] == "done", str(job))
|
||||
check("one entry was added", len(a.tracks) == before + 1)
|
||||
added = job["result"]["track_ids"][0]
|
||||
check("it points at the ORIGINAL file", a.audio_path(added) == one, str(a.audio_path(added)))
|
||||
check("its tags came with it", a.track(added).title == "First Light")
|
||||
check("it is in the playlist", a.playlist_entries(playlist) == [added])
|
||||
check("it was saved, not left pending", not a.dirty)
|
||||
body = c.get("/api/folder/tracks", params={"path": str(music)}).json()
|
||||
check("the folder now marks it as held", body["in_collection"] == [str(one)], str(body["in_collection"]))
|
||||
|
||||
print("== a held file is never added twice, but still reaches its target ==")
|
||||
library = STATE.library_id
|
||||
eset = exports.create(library, name="Folder Export", target="traktor",
|
||||
destination=str(Path(tempfile.mkdtemp()) / "out"))
|
||||
req = {"track_ids": [str(one), str(two)], "mode": "reference",
|
||||
"playlist_id": playlist, "export_id": eset.id}
|
||||
p = c.post("/api/folder/add/preview", json=req).json()
|
||||
check("the preview reports it as already held", p["existing"] == ["First Light"], str(p))
|
||||
job = wait(c, c.post("/api/folder/add", json=req).json())
|
||||
check("the job finishes", job["state"] == "done", str(job))
|
||||
check("only the NEW file was added", len(a.tracks) == before + 2, f"{len(a.tracks) - before}")
|
||||
check("the held one kept its id", job["result"]["track_ids"][0] == added)
|
||||
new = job["result"]["track_ids"][1]
|
||||
check("the playlist holds both, once each", a.playlist_entries(playlist) == [added, new],
|
||||
str(a.playlist_entries(playlist)))
|
||||
check("and so does the export", exports.get(library, eset.id).track_ids == [added, new])
|
||||
|
||||
print("== copy: the collection points at the copy ==")
|
||||
three_dir = music / "Deeper"
|
||||
c.get("/api/folder/tracks", params={"path": str(three_dir)})
|
||||
dest = Path(tempfile.mkdtemp()) / "Imported"
|
||||
req = {"track_ids": [str(three_dir / "three.flac")], "mode": "copy", "destination": str(dest)}
|
||||
p = c.post("/api/folder/add/preview", json=req).json()
|
||||
check("the preview sizes the copy", p["total_bytes"] > 0, str(p))
|
||||
job = wait(c, c.post("/api/folder/add", json=req).json())
|
||||
check("the job finishes", job["state"] == "done", str(job))
|
||||
copied_id = job["result"]["track_ids"][0]
|
||||
check("the audio was copied", (dest / "three.flac").is_file())
|
||||
check("the entry points at the copy", a.audio_path(copied_id) == dest / "three.flac",
|
||||
str(a.audio_path(copied_id)))
|
||||
check("the original is untouched", (three_dir / "three.flac").is_file())
|
||||
check("copy without a destination is refused",
|
||||
c.post("/api/folder/add", json={"track_ids": [str(one)], "mode": "copy"}).status_code == 400)
|
||||
check("an unscanned file cannot be added",
|
||||
c.post("/api/folder/add/preview",
|
||||
json={"track_ids": ["/etc/passwd"], "mode": "reference"}).status_code == 404)
|
||||
|
||||
print("== hidden entries ==")
|
||||
check("AppleDouble twins are hidden", places.is_hidden(music / "._one.flac"))
|
||||
check("OS housekeeping is hidden", places.is_hidden(music / ".Trashes"))
|
||||
check("an ordinary file is not", not places.is_hidden(one))
|
||||
|
||||
print("\n" + ("❌ FAILED" if failed else "✅ PASSED"))
|
||||
_DATA.cleanup()
|
||||
raise SystemExit(1 if failed else 0)
|
||||
@@ -0,0 +1,203 @@
|
||||
"""Batch analysis — grid and Auto Hotcues jobs, on a temp copy of the collection.
|
||||
|
||||
Detection itself is `test_grid_detect.py`'s job; this pins the WIRING, and the
|
||||
decisions only the batch makes: locked grids are skipped always, existing grids
|
||||
only when asked, a failing track is reported and skipped rather than fatal, a
|
||||
cancel keeps what is done, and nothing reaches disk before Save. Batch Auto
|
||||
Hotcues adds: one template on every track, a grid analysed first where there is
|
||||
none (and an existing one left alone), Replace applying to every track, and one
|
||||
batch job at a time ACROSS both kinds.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
|
||||
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
|
||||
|
||||
failed = False
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
global failed
|
||||
print(f" {'✓' if cond else '✗'} {label}" + ("" if cond else f" [{detail}]"))
|
||||
if not cond:
|
||||
failed = True
|
||||
|
||||
|
||||
def wait(c, job_id, timeout=30.0):
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
j = c.get(f"/api/jobs/{job_id}").json()
|
||||
if j["state"] != "running":
|
||||
return j
|
||||
time.sleep(0.02)
|
||||
raise AssertionError("job did not finish")
|
||||
|
||||
|
||||
print("== batch grid analysis ==")
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
work = Path(d) / "collection.nml"
|
||||
shutil.copy2(REAL, work)
|
||||
os.environ["KONDUKTOR_NML"] = str(work)
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
import konduktor.main as main
|
||||
|
||||
detected: list[str] = []
|
||||
|
||||
def fake_detect(path, *a, **k):
|
||||
detected.append(path)
|
||||
return SimpleNamespace(anchor=0.123, bpm=127.5)
|
||||
|
||||
main.grid_detect.detect_grid = fake_detect
|
||||
|
||||
with TestClient(main.app, raise_server_exceptions=False) as c:
|
||||
a = main.require_adapter()
|
||||
missing = next(t.id for t in a.tracks if t.grid_marker_count == 0)
|
||||
a.audio_path = lambda tid: None if tid == missing else Path(__file__)
|
||||
|
||||
gridded = [t.id for t in a.tracks if t.grid_marker_count > 0 and not t.grid_locked][:2]
|
||||
bare = [t.id for t in a.tracks if t.grid_marker_count == 0 and t.id != missing][:2]
|
||||
locked = gridded[1]
|
||||
a.set_grid_lock(locked, True)
|
||||
ids = [gridded[0], locked, *bare, missing]
|
||||
|
||||
# The deck's single-track Analyze shares the batch's helper.
|
||||
r = c.post("/api/tracks/grid/auto", json={"track_id": bare[1]})
|
||||
check("single-track Analyze still answers 200", r.status_code == 200, r.text[:200])
|
||||
r = c.post("/api/tracks/grid/auto", json={"track_id": missing})
|
||||
check("…and 400 on a missing file", r.status_code == 400, r.text[:200])
|
||||
a.delete_grid(bare[1])
|
||||
|
||||
r = c.post("/api/tracks/grid/auto-batch", json={"track_ids": ids})
|
||||
check("the route starts a job", r.status_code == 200, r.text[:200])
|
||||
j = wait(c, r.json()["id"])
|
||||
res = j["result"]
|
||||
check("the job finishes", j["state"] == "done", str(j))
|
||||
check("progress reaches the total", j["done"] == j["total"] == len(ids), str(j))
|
||||
check("tracks without a grid are analysed", res["analysed"] == bare, str(res))
|
||||
check("an existing grid is skipped by default", res["existing"] == 1, str(res))
|
||||
check("a locked grid is skipped", res["locked"] == 1, str(res))
|
||||
check("a missing file is reported, not fatal",
|
||||
len(res["failed"]) == 1 and "not found" in res["failed"][0]["reason"], str(res))
|
||||
g = a.track_cues(bare[0]).grid_markers
|
||||
check("the analysed grid is written", len(g) == 1 and abs(g[0].bpm - 127.5) < 1e-6, str(g))
|
||||
|
||||
r = c.post("/api/tracks/grid/auto-batch",
|
||||
json={"track_ids": [gridded[0], locked], "replace_existing": True})
|
||||
res = wait(c, r.json()["id"])["result"]
|
||||
check("replace_existing re-analyses an existing grid", res["analysed"] == [gridded[0]], str(res))
|
||||
check("…but never a locked one", res["locked"] == 1, str(res))
|
||||
|
||||
# Cancel: a slow detector gives the cancel time to land mid-run.
|
||||
main.grid_detect.detect_grid = lambda p, *a, **k: (time.sleep(0.05), fake_detect(p))[1]
|
||||
many = [t.id for t in a.tracks if not t.grid_locked][:40]
|
||||
r = c.post("/api/tracks/grid/auto-batch",
|
||||
json={"track_ids": many, "replace_existing": True})
|
||||
jid = r.json()["id"]
|
||||
r2 = c.post("/api/tracks/grid/auto-batch", json={"track_ids": many})
|
||||
check("a second run while one is going is refused", r2.status_code == 409, r2.text[:200])
|
||||
time.sleep(0.2)
|
||||
c.post(f"/api/jobs/{jid}/cancel")
|
||||
j = wait(c, jid)
|
||||
check("a cancelled run says so", j["state"] == "cancelled", str(j))
|
||||
n = len(j["result"]["analysed"]) if j["result"] else -1
|
||||
check("…and still returns what it finished", 0 < n < len(many), str(n))
|
||||
|
||||
# ---- batch Auto Hotcues --------------------------------------------
|
||||
print("== batch auto hotcues ==")
|
||||
main.grid_detect.detect_grid = fake_detect
|
||||
from konduktor.core import structure
|
||||
|
||||
def fake_analyse(path, markers):
|
||||
bpm = markers[0][1]
|
||||
st = structure.Structure(beats=np.arange(400) * 60.0 / bpm, bar0=0,
|
||||
n_bars=100, duration=400 * 60.0 / bpm)
|
||||
st.events = {"drop_1": 129, "outro": 353} # clear of any beat-0 grid cue
|
||||
return st
|
||||
|
||||
main.structure.analyse = fake_analyse
|
||||
|
||||
def free(tid, n):
|
||||
cu = a.track_cues(tid)
|
||||
used = {q.slot for q in cu.cues if q.slot is not None}
|
||||
return [k for k in range(8) if k not in used][:n]
|
||||
|
||||
gridded = next(t.id for t in a.tracks if t.grid_marker_count > 0 and not t.grid_locked
|
||||
and len(free(t.id, 2)) == 2 and t.id not in many)
|
||||
nogrid = next(t.id for t in a.tracks if t.grid_marker_count == 0
|
||||
and t.id not in (missing, *bare, *many))
|
||||
before_grid = a.track_cues(gridded).grid_markers
|
||||
s0, s1 = free(gridded, 2)
|
||||
tmpl = [{"slot": s0, "event": "drop_1"}, {"slot": s1, "event": "outro"}]
|
||||
|
||||
r = c.post("/api/tracks/cue/auto-batch",
|
||||
json={"track_ids": [gridded, nogrid, missing], "slots": tmpl})
|
||||
check("the batch route starts a job", r.status_code == 200, r.text[:200])
|
||||
j = wait(c, r.json()["id"])
|
||||
res = j["result"]
|
||||
check("the job finishes", j["state"] == "done", str(j))
|
||||
check("both tracks got cues", res["tracks"] == [gridded, nogrid], str(res))
|
||||
check("a grid is created only where there was none", res["grids_created"] == 1, str(res))
|
||||
check("an existing grid is left untouched",
|
||||
a.track_cues(gridded).grid_markers == before_grid)
|
||||
check("the track without a grid now has one", len(a.track_cues(nogrid).grid_markers) == 1)
|
||||
names = {q.slot: q.name for q in a.track_cues(gridded).cues if q.slot is not None}
|
||||
check("the template's cues are placed", names.get(s0) == "Drop 1" and names.get(s1) == "Outro", str(names))
|
||||
check("placed cues are counted", res["cues_placed"] == 4, str(res))
|
||||
check("a missing file is reported, not fatal",
|
||||
len(res["failed"]) == 1 and "not found" in res["failed"][0]["reason"], str(res))
|
||||
|
||||
# Occupied slots: kept, unless ticked — and then replaced on every track.
|
||||
# A fresh beat (16 before the drop), so the one-cue-per-beat rule cannot
|
||||
# be what decides it.
|
||||
tmpl2 = [{"slot": s0, "event": "drop_1", "offset_beats": -16}]
|
||||
res = wait(c, c.post("/api/tracks/cue/auto-batch",
|
||||
json={"track_ids": [gridded], "slots": tmpl2}).json()["id"])["result"]
|
||||
check("an occupied slot is kept without Replace", res["cues_placed"] == 0, str(res))
|
||||
tmpl2[0]["overwrite"] = True
|
||||
res = wait(c, c.post("/api/tracks/cue/auto-batch",
|
||||
json={"track_ids": [gridded], "slots": tmpl2}).json()["id"])["result"]
|
||||
names = {q.slot: q.name for q in a.track_cues(gridded).cues if q.slot is not None}
|
||||
check("…and replaced with it", names.get(s0) == "Drop 1 -16" and res["cues_placed"] == 1,
|
||||
f"{names} {res}")
|
||||
|
||||
r = c.post("/api/tracks/cue/auto-batch",
|
||||
json={"track_ids": [gridded], "slots": [{"slot": 99, "event": "outro"}]})
|
||||
check("a template the bank cannot hold is refused up front", r.status_code == 400, r.text[:200])
|
||||
r = c.post("/api/tracks/cue/auto-batch", json={"track_ids": [gridded], "slots": []})
|
||||
check("an empty template is refused", r.status_code == 400, r.text[:200])
|
||||
|
||||
# One batch at a time ACROSS kinds.
|
||||
main.grid_detect.detect_grid = lambda p, *a, **k: (time.sleep(0.05), fake_detect(p))[1]
|
||||
jid = c.post("/api/tracks/grid/auto-batch",
|
||||
json={"track_ids": many, "replace_existing": True}).json()["id"]
|
||||
r = c.post("/api/tracks/cue/auto-batch", json={"track_ids": [gridded], "slots": tmpl})
|
||||
check("hotcues are refused while a grid run is going", r.status_code == 409, r.text[:200])
|
||||
c.post(f"/api/jobs/{jid}/cancel")
|
||||
wait(c, jid)
|
||||
|
||||
# Opening another library cancels a running batch.
|
||||
main.structure.analyse = lambda p, m: (time.sleep(0.05), fake_analyse(p, m))[1]
|
||||
gridded_many = [t.id for t in a.tracks if t.grid_marker_count > 0][:40]
|
||||
jid = c.post("/api/tracks/cue/auto-batch",
|
||||
json={"track_ids": gridded_many, "slots": tmpl}).json()["id"]
|
||||
time.sleep(0.1)
|
||||
other = Path(d) / "other.nml"
|
||||
shutil.copy2(REAL, other)
|
||||
c.post("/api/library/open", json={"path": str(other)})
|
||||
check("opening another library cancels the run", wait(c, jid)["state"] == "cancelled")
|
||||
|
||||
check("nothing was written to disk (edits stay in memory until Save)",
|
||||
work.read_bytes() == REAL.read_bytes())
|
||||
|
||||
print()
|
||||
print("FAILED" if failed else "RESULT: ALL PASSED")
|
||||
raise SystemExit(1 if failed else 0)
|
||||
@@ -0,0 +1,149 @@
|
||||
"""Tests for beatgrid detection (`core/grid_detect.py`) on synthetic audio.
|
||||
|
||||
Needs no audio files and no library: every track here is generated, so its
|
||||
tempo and first beat are KNOWN rather than taken from another analyser. That
|
||||
is what these can pin that `bench_grid_detect.py` (real music, scored against
|
||||
Rekordbox) cannot: exactness, and each trap that fooled a band in isolation —
|
||||
the loud off-beat hat, the syncopated bassline, and the frame-quantised tempo
|
||||
the previous detector could not escape.
|
||||
"""
|
||||
import warnings
|
||||
|
||||
import numpy as np
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
from konduktor.core.grid_detect import detect_grid # noqa: E402
|
||||
|
||||
SR = 22050
|
||||
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
|
||||
|
||||
|
||||
rng = np.random.default_rng(0)
|
||||
|
||||
|
||||
def _faded(x: np.ndarray) -> np.ndarray:
|
||||
"""End a sound smoothly: a hard cut is itself a click, half a beat after the
|
||||
kick, which no real sample has and which would test the generator instead."""
|
||||
n = min(len(x), int(0.02 * SR))
|
||||
x = x.copy()
|
||||
x[-n:] *= np.linspace(1.0, 0.0, n)
|
||||
return x
|
||||
|
||||
|
||||
def _kick() -> np.ndarray:
|
||||
t = np.arange(int(0.25 * SR)) / SR
|
||||
body = np.sin(2 * np.pi * (50 * t + 60 * (1 - np.exp(-t / 0.02)) * 0.02)) * np.exp(-t / 0.12)
|
||||
click = np.zeros_like(t)
|
||||
click[: int(0.002 * SR)] = rng.standard_normal(int(0.002 * SR)) * 0.5
|
||||
return _faded(body + click)
|
||||
|
||||
|
||||
def _hat(amp: float) -> np.ndarray:
|
||||
n = int(0.04 * SR)
|
||||
noise = np.diff(rng.standard_normal(n + 1)) # tilt up: hat-like
|
||||
return _faded(amp * noise * np.exp(-np.arange(n) / SR / 0.012))
|
||||
|
||||
|
||||
def _bass(amp: float) -> np.ndarray:
|
||||
t = np.arange(int(0.2 * SR)) / SR
|
||||
ramp = np.minimum(1.0, t / 0.015) # a bass note swells; it has no click
|
||||
return _faded(amp * np.sin(2 * np.pi * 70 * t) * ramp * np.exp(-t / 0.15))
|
||||
|
||||
|
||||
def track(bpm, first=0.3, seconds=180.0, hat=0.0, bass=0.0, tempo_b=None):
|
||||
"""Kick on every beat from ``first``; optional off-beat hat and a bass note
|
||||
60% of the way to the next beat. ``tempo_b`` is the tempo at the END: the
|
||||
tempo glides linearly from ``bpm`` to it, as a live drummer's does."""
|
||||
y = np.zeros(int(seconds * SR))
|
||||
|
||||
def put(x, at):
|
||||
i = int(round(at * SR))
|
||||
if 0 <= i < len(y):
|
||||
j = min(len(y), i + len(x))
|
||||
y[i:j] += x[: j - i]
|
||||
|
||||
t, beat = first, 60.0 / bpm
|
||||
k, h, b = _kick(), _hat(hat), _bass(bass)
|
||||
while t < seconds:
|
||||
put(k, t)
|
||||
if hat:
|
||||
put(h, t + beat / 2)
|
||||
if bass:
|
||||
put(b, t + 0.6 * beat)
|
||||
if tempo_b:
|
||||
beat = 60.0 / (bpm + (tempo_b - bpm) * t / seconds)
|
||||
t += beat
|
||||
return (0.3 * y).astype(np.float32)
|
||||
|
||||
|
||||
def detect(y, **kw):
|
||||
return detect_grid("", y=y, sr=SR, **kw)
|
||||
|
||||
|
||||
def beat_error_ms(res, bpm, first, at):
|
||||
"""Distance from the true beat nearest ``at`` to the detected grid's."""
|
||||
p = 60.0 / bpm
|
||||
true = first + round((at - first) / p) * p
|
||||
dp = 60.0 / res.bpm
|
||||
got = res.anchor + round((true - res.anchor) / dp) * dp
|
||||
return (got - true) * 1000.0
|
||||
|
||||
|
||||
print("== round tempo: exact BPM, anchor on the first kick ==")
|
||||
r = detect(track(124, first=0.3))
|
||||
check("124 BPM detected as exactly 124", r.bpm == 124.0, f"got {r.bpm}")
|
||||
check("anchor on the first kick (±3 ms)", abs(r.anchor - 0.3) <= 0.003, f"got {r.anchor}")
|
||||
check("still on the beat at the end (±3 ms)", abs(beat_error_ms(r, 124, 0.3, 175)) <= 3)
|
||||
check("a constant track reports little drift", r.drift_ms is not None and r.drift_ms <= 5, f"{r.drift_ms}")
|
||||
|
||||
print("== the old detector's blind spot: 125 BPM ==")
|
||||
# librosa's frame-quantised tempo could only return 123.05 or 129.20 here.
|
||||
r = detect(track(125, first=0.05))
|
||||
check("125 BPM is 125, not 123.05", r.bpm == 125.0, f"got {r.bpm}")
|
||||
|
||||
print("== non-round tempo is fitted, not snapped ==")
|
||||
r = detect(track(123.37, first=0.2))
|
||||
check("123.37 within 0.005", abs(r.bpm - 123.37) <= 0.005, f"got {r.bpm}")
|
||||
check("…and on the beat at the end (±5 ms)", abs(beat_error_ms(r, 123.37, 0.2, 175)) <= 5)
|
||||
|
||||
print("== octave: a four-on-the-floor kick is not half or double tempo ==")
|
||||
r = detect(track(128))
|
||||
check("128 BPM, not 64 or 256", r.bpm == 128.0, f"got {r.bpm}")
|
||||
r = detect(track(90), bpm_range=(100.0, 200.0))
|
||||
check("bpm_range folds 90 up to 180", r.bpm == 180.0, f"got {r.bpm}")
|
||||
|
||||
print("== phase traps: each fooled one band on real music ==")
|
||||
r = detect(track(126, first=0.4, hat=1.5))
|
||||
check("an off-beat hat louder than the kick does not take the beat",
|
||||
abs(beat_error_ms(r, 126, 0.4, 60)) <= 3, f"{beat_error_ms(r, 126, 0.4, 60):+.1f} ms")
|
||||
r = detect(track(124, first=0.25, bass=1.5))
|
||||
check("a syncopated bassline does not take the beat",
|
||||
abs(beat_error_ms(r, 124, 0.25, 60)) <= 3, f"{beat_error_ms(r, 124, 0.25, 60):+.1f} ms")
|
||||
r = detect(track(124, first=0.25, hat=1.2, bass=1.2))
|
||||
check("…nor both together", abs(beat_error_ms(r, 124, 0.25, 60)) <= 3,
|
||||
f"{beat_error_ms(r, 124, 0.25, 60):+.1f} ms")
|
||||
|
||||
print("== a wandering tempo is reported, not hidden ==")
|
||||
# 124 → 124.15 over three minutes: any one constant grid is ~25 ms off somewhere.
|
||||
r = detect(track(124, tempo_b=124.15))
|
||||
check("drift is reported when one grid cannot fit", r.drift_ms is not None and r.drift_ms >= 12, f"{r.drift_ms}")
|
||||
|
||||
print("== nothing to fit ==")
|
||||
for label, y in (("silence", np.zeros(SR * 20, dtype=np.float32)), ("too short", np.zeros(SR, dtype=np.float32))):
|
||||
try:
|
||||
detect(y)
|
||||
check(f"{label} raises ValueError", False, "returned a grid")
|
||||
except ValueError:
|
||||
check(f"{label} raises ValueError", True)
|
||||
|
||||
print()
|
||||
print("FAILED" if failed else "OK")
|
||||
raise SystemExit(1 if failed else 0)
|
||||
@@ -0,0 +1,113 @@
|
||||
"""Version-history tests (git-backed backups replacing the old .bak scheme).
|
||||
|
||||
Runs against a COPY of the collection (never the original), with an isolated
|
||||
throwaway app-data dir. Verifies:
|
||||
* opening a collection records a baseline commit
|
||||
* a save adds a commit with a non-empty edit summary
|
||||
* a byte-identical save is deduped (no new commit)
|
||||
* list_history is newest-first
|
||||
* restoring an earlier version round-trips the .nml bytes AND adds a
|
||||
"Restored …" commit (a forward save, not a rewind)
|
||||
* clear_history removes the repo
|
||||
* no .bak files are left next to the collection
|
||||
|
||||
Run: `python test_history.py` in the backend venv (see run_tests.sh).
|
||||
"""
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
|
||||
work_dir = Path(tempfile.mkdtemp(prefix="konduktor-history-"))
|
||||
WORK = work_dir / "collection.nml"
|
||||
shutil.copy2(REAL, WORK)
|
||||
|
||||
os.environ["KONDUKTOR_NML"] = str(WORK)
|
||||
os.environ["KONDUKTOR_DATA_DIR"] = str(work_dir / "appdata")
|
||||
|
||||
from fastapi.testclient import TestClient # noqa: E402
|
||||
|
||||
from konduktor import history, main # noqa: E402
|
||||
|
||||
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
|
||||
|
||||
|
||||
client = TestClient(main.app)
|
||||
|
||||
|
||||
def first_playlist(nodes):
|
||||
for n in nodes:
|
||||
if n["kind"] == "playlist":
|
||||
return n
|
||||
if n.get("children"):
|
||||
found = first_playlist(n["children"])
|
||||
if found:
|
||||
return found
|
||||
return None
|
||||
|
||||
|
||||
print("== baseline on open ==")
|
||||
hist = client.get("/api/history").json()
|
||||
check("baseline commit exists", len(hist) == 1)
|
||||
check("baseline summary set", hist and "Baseline" in hist[0]["summary"])
|
||||
|
||||
original_bytes = WORK.read_bytes()
|
||||
|
||||
print("== save records a commit ==")
|
||||
pl = first_playlist(client.get("/api/playlists").json())
|
||||
new_name = pl["name"] + " ✎"
|
||||
r = client.patch(f"/api/playlists/{pl['id']}", json={"name": new_name})
|
||||
check("rename ok", r.status_code == 200)
|
||||
res = client.post("/api/save").json()
|
||||
check("save reports a commit", bool(res["commit"]))
|
||||
hist = client.get("/api/history").json()
|
||||
check("history grew to 2", len(hist) == 2)
|
||||
check("newest is the rename", hist and new_name in hist[0]["summary"])
|
||||
check("newest-first ordering", "Baseline" in hist[-1]["summary"])
|
||||
|
||||
print("== dedup: byte-identical save makes no commit ==")
|
||||
# Force a save with no real change: rename back and forth nets a re-render of the
|
||||
# same content is not guaranteed; instead call history.commit directly with HEAD.
|
||||
head_bytes = WORK.read_bytes()
|
||||
before = len(client.get("/api/history").json())
|
||||
dup = history.commit(WORK, head_bytes, "should be deduped", "test")
|
||||
after = len(client.get("/api/history").json())
|
||||
check("dedup returns None", dup is None)
|
||||
check("dedup adds no commit", after == before)
|
||||
|
||||
print("== restore round-trips bytes + adds a forward commit ==")
|
||||
hist = client.get("/api/history").json()
|
||||
baseline_id = hist[-1]["id"]
|
||||
count_before = len(hist)
|
||||
rr = client.post(f"/api/history/{baseline_id}/restore")
|
||||
check("restore ok", rr.status_code == 200)
|
||||
check("restored bytes == original", WORK.read_bytes() == original_bytes)
|
||||
hist = client.get("/api/history").json()
|
||||
check("restore added a commit", len(hist) == count_before + 1)
|
||||
check("restore commit labelled", hist and "Restored" in hist[0]["summary"])
|
||||
|
||||
print("== read_version returns the right blob ==")
|
||||
check("baseline blob == original", history.read_version(WORK, baseline_id) == original_bytes)
|
||||
|
||||
print("== no .bak litter ==")
|
||||
check("no .bak files next to collection", not list(work_dir.glob("*.bak")))
|
||||
check("no backups/ dir next to collection", not (work_dir / "backups").exists())
|
||||
|
||||
print("== clear_history removes the repo ==")
|
||||
cr = client.delete("/api/history")
|
||||
check("clear ok", cr.status_code == 200)
|
||||
check("history empty after clear", client.get("/api/history").json() == [])
|
||||
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -0,0 +1,451 @@
|
||||
"""Importing a OneLibrary drive into a Traktor collection.
|
||||
|
||||
The first operation that puts tracks into a library that never had them, and
|
||||
therefore the first that writes an ENTRY Traktor did not write. Two things need
|
||||
guarding, and they pull in opposite directions:
|
||||
|
||||
* **The new entries must carry the prep.** Cues on the pads they were on, the
|
||||
beatgrid including its tempo changes, and nothing silently dropped.
|
||||
* **The old entries must not move.** The whole save-fidelity guarantee rests on
|
||||
every unedited object rendering the bytes it was parsed from, and appending
|
||||
to COLLECTION is the first thing that could disturb that. So this asserts on
|
||||
rendered bytes as well as on the projection.
|
||||
|
||||
Runs against a temp copy of the real Traktor collection (gotcha 2: it is real,
|
||||
irreplaceable data) and the checked-in OneLibrary fixture drive.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import warnings
|
||||
from difflib import unified_diff
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-import-appdata-")
|
||||
|
||||
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
|
||||
FIXTURE = Path(__file__).resolve().parent / "fixtures" / "onelibrary"
|
||||
|
||||
from konduktor.adapters.onelibrary.adapter import OneLibraryAdapter # noqa: E402
|
||||
from konduktor.adapters.rekordbox.adapter import RekordboxAdapter # noqa: E402
|
||||
from konduktor.adapters.traktor.adapter import TraktorAdapter # noqa: E402
|
||||
from konduktor.core.adapter import InvalidCommand, NewTrack, Unsupported # noqa: E402
|
||||
from konduktor.core.model import CuePoint, GridMarker, Track, TrackCues # noqa: E402
|
||||
|
||||
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 _raises(fn, exc) -> bool:
|
||||
try:
|
||||
fn()
|
||||
except exc:
|
||||
return True
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
return False
|
||||
|
||||
|
||||
if not REAL.is_file() or not (FIXTURE / "PIONEER" / "rekordbox" / "exportLibrary.db").is_file():
|
||||
print(f"SKIP: need {REAL} and the OneLibrary fixture")
|
||||
sys.exit(0)
|
||||
|
||||
|
||||
def fresh_collection() -> tuple[Path, Path, bytes]:
|
||||
"""A throwaway copy of the real collection, plus a folder for copied audio."""
|
||||
work = Path(tempfile.mkdtemp(prefix="konduktor-import-"))
|
||||
nml = work / "collection.nml"
|
||||
shutil.copy(REAL, nml)
|
||||
music = work / "Imported"
|
||||
music.mkdir()
|
||||
return nml, music, nml.read_bytes()
|
||||
|
||||
|
||||
def stage(src: OneLibraryAdapter, music: Path) -> list[NewTrack]:
|
||||
"""Copy the drive's audio and describe each track as a NewTrack.
|
||||
|
||||
This is what the import feature will do around the adapter: the copy is the
|
||||
caller's job, so a half-finished file copy is never something a library
|
||||
write discovers.
|
||||
"""
|
||||
items = []
|
||||
for t in src.tracks:
|
||||
target = music / Path(t.filepath).name
|
||||
shutil.copy(t.filepath, target)
|
||||
items.append(NewTrack(track=t, audio_path=target, cues=src.track_cues(t.id)))
|
||||
return items
|
||||
|
||||
|
||||
print("== a drive's tracks land in the collection ==")
|
||||
nml, music, original = fresh_collection()
|
||||
source = OneLibraryAdapter(FIXTURE)
|
||||
dest = TraktorAdapter(nml)
|
||||
before = len(dest.tracks)
|
||||
items = stage(source, music)
|
||||
ids = dest.add_tracks(items)
|
||||
|
||||
check("every staged track was added", len(ids) == len(items) == 2, str(len(ids)))
|
||||
check("the collection grew by exactly that many", len(dest.tracks) == before + 2)
|
||||
check("the new ids are unique", len(set(ids)) == len(ids))
|
||||
# A track that is not in the projection is invisible to search, playlists and
|
||||
# the deck — added but unusable.
|
||||
check("each added track is in the projection", all(dest.track(i) is not None for i in ids))
|
||||
check("and is findable by its id", all(dest.by_key.get(i) is not None for i in ids))
|
||||
|
||||
added = dest.track(ids[0])
|
||||
origin = source.tracks[0]
|
||||
check("title survives", added.title == origin.title, f"{added.title!r}")
|
||||
check("artist survives", added.artist == origin.artist)
|
||||
check("bpm survives", added.bpm == origin.bpm)
|
||||
check("label survives", added.label == origin.label)
|
||||
check("comment survives", added.comment == origin.comment)
|
||||
check("the id is the Traktor primary key, not the drive's",
|
||||
added.id != origin.id and added.id.startswith("Macintosh HD"), added.id)
|
||||
check("filepath points at the COPY, not the drive",
|
||||
str(music) in (added.filepath or ""), str(added.filepath))
|
||||
|
||||
print("== prep survives the crossing ==")
|
||||
src_cues = source.track_cues(origin.id)
|
||||
got = dest.track_cues(ids[0])
|
||||
|
||||
check("the flexible grid crosses intact",
|
||||
[(round(m.start, 3), m.bpm) for m in got.grid_markers]
|
||||
== [(round(m.start, 3), m.bpm) for m in src_cues.grid_markers],
|
||||
str([(m.start, m.bpm) for m in got.grid_markers]))
|
||||
check("both tempo segments are there", len(got.grid_markers) == 2)
|
||||
|
||||
# Hot cues must keep their PAD. Muscle memory is most of what a hotcue layout
|
||||
# is, so a cue that moves is nearly as bad as one that vanishes.
|
||||
src_hot = {c.slot: c for c in src_cues.cues if c.role == "hotcue"}
|
||||
got_by_slot = {c.slot: c for c in got.cues}
|
||||
same_pad = [
|
||||
s for s, c in src_hot.items()
|
||||
if s in got_by_slot and abs(got_by_slot[s].start - c.start) < 0.001
|
||||
]
|
||||
check("every hot cue keeps the pad it was on",
|
||||
sorted(same_pad) == sorted(src_hot), f"kept {sorted(same_pad)} of {sorted(src_hot)}")
|
||||
check("a loop stays a loop, with its length",
|
||||
got_by_slot[0].type == "loop" and abs(got_by_slot[0].length - 1.875) < 0.001)
|
||||
|
||||
# Traktor has no memory cues, so they degrade into spare pads rather than being
|
||||
# dropped — the settled lossiness rule.
|
||||
n_memory = sum(1 for c in src_cues.cues if c.role != "hotcue")
|
||||
check("memory cues are preserved in spare slots, not dropped",
|
||||
len(got.cues) == len(src_hot) + n_memory, f"{len(got.cues)} cues")
|
||||
check("and they do not overwrite a hot cue",
|
||||
len({c.slot for c in got.cues}) == len(got.cues))
|
||||
check("every imported cue occupies a real pad",
|
||||
all(c.role == "hotcue" and c.slot is not None for c in got.cues))
|
||||
|
||||
# `set_analysed_grid` would place Traktor's beat-1 companion on pad A. That both
|
||||
# invents a cue the source never had and displaces the imported pad A cue — it
|
||||
# silently ate one during development, which is why this is asserted.
|
||||
check("no beatgrid companion cue is invented",
|
||||
all(c.grid_marker is None for c in got.cues),
|
||||
str([(c.slot, c.grid_marker) for c in got.cues]))
|
||||
|
||||
print("== the existing 8,485 entries do not move ==")
|
||||
outcome = dest.save()
|
||||
after = nml.read_bytes()
|
||||
diff = list(unified_diff(original.decode("utf-8", "replace").splitlines(),
|
||||
after.decode("utf-8", "replace").splitlines(), lineterm="", n=0))
|
||||
removed = [l for l in diff if l.startswith("-") and not l.startswith("---")]
|
||||
# Exactly one line is rewritten: the one carrying <COLLECTION ENTRIES="N">, whose
|
||||
# count changed. Everything else is pure addition.
|
||||
check("only the COLLECTION header line is rewritten",
|
||||
len(removed) == 1 and "<COLLECTION ENTRIES=" in removed[0],
|
||||
f"{len(removed)} removed: {removed[:1]}")
|
||||
check("nothing else is removed or reformatted",
|
||||
all("<COLLECTION ENTRIES=" in l for l in removed))
|
||||
|
||||
# ENTRIES is a real count Traktor reads, not decoration. Nothing else in the app
|
||||
# changes how many entries exist, so nothing had ever needed to maintain it.
|
||||
import re # noqa: E402
|
||||
|
||||
declared = int(re.search(rb'<COLLECTION ENTRIES="(\d+)"', after).group(1))
|
||||
check("the ENTRIES count is updated to match",
|
||||
declared == after.count(b"<ENTRY ") == before + 2,
|
||||
f"declared {declared}, actual {after.count(b'<ENTRY ')}")
|
||||
# The version-history message is what a user reads when deciding which version
|
||||
# to roll back to, so an import must not read as an edit. Asserted on the
|
||||
# SaveOutcome because save() clears the journal.
|
||||
check("the version-history message says the tracks were ADDED",
|
||||
"Added 2 tracks" in outcome.summary, outcome.summary)
|
||||
check("and does not also call them edited",
|
||||
"edited 2 tracks" not in outcome.summary.lower(), outcome.summary)
|
||||
|
||||
print("== reopening proves it is really there ==")
|
||||
reopened = TraktorAdapter(nml)
|
||||
check("the added tracks survive a round trip", len(reopened.tracks) == before + 2)
|
||||
round_tripped = reopened.track(ids[0])
|
||||
check("with their metadata", round_tripped is not None and round_tripped.title == origin.title)
|
||||
rt_cues = reopened.track_cues(ids[0])
|
||||
check("with their grid", len(rt_cues.grid_markers) == 2)
|
||||
check("and with their cues", len(rt_cues.cues) == len(got.cues))
|
||||
|
||||
print("== refusals ==")
|
||||
check("a second import of the same file is refused, not silently duplicated",
|
||||
_raises(lambda: dest.add_tracks(items), InvalidCommand))
|
||||
missing = NewTrack(track=items[0].track, audio_path=music / "nope.mp3", cues=None)
|
||||
check("a missing audio file is refused before anything is written",
|
||||
_raises(lambda: dest.add_tracks([missing]), InvalidCommand))
|
||||
check("read-only OneLibrary refuses to receive tracks",
|
||||
_raises(lambda: source.add_tracks(items), Unsupported))
|
||||
|
||||
print("== a track with no prep at all ==")
|
||||
nml2, music2, _ = fresh_collection()
|
||||
dest2 = TraktorAdapter(nml2)
|
||||
bare_audio = music2 / "bare.mp3"
|
||||
shutil.copy(items[0].audio_path, bare_audio)
|
||||
bare = NewTrack(
|
||||
track=Track(id="ignored", title="Bare", artist="Nobody"),
|
||||
audio_path=bare_audio,
|
||||
cues=None,
|
||||
)
|
||||
bare_ids = dest2.add_tracks([bare])
|
||||
check("a track with no cues and no grid still imports", len(bare_ids) == 1)
|
||||
bare_cues = dest2.track_cues(bare_ids[0])
|
||||
check("and has no grid", bare_cues.grid_markers == [])
|
||||
check("and no cues", bare_cues.cues == [])
|
||||
check("and no BPM was invented", dest2.track(bare_ids[0]).bpm is None)
|
||||
|
||||
print("== a full hotcue bank ==")
|
||||
# Traktor has 8 pads. Nine cues cannot all fit, so the rule has to be explicit
|
||||
# about WHICH survive rather than leaving it to iteration order.
|
||||
crowded_audio = music2 / "crowded.mp3"
|
||||
shutil.copy(items[0].audio_path, crowded_audio)
|
||||
many = TrackCues(
|
||||
grid_markers=[GridMarker(start=0.0, bpm=120.0)],
|
||||
cues=[CuePoint(type="cue", role="hotcue", start=float(i), length=0.0, slot=i)
|
||||
for i in range(8)]
|
||||
+ [CuePoint(type="cue", role="memory", start=99.0, length=0.0, slot=None)],
|
||||
)
|
||||
crowded_id = dest2.add_tracks([NewTrack(
|
||||
track=Track(id="ignored", title="Crowded", bpm=120.0),
|
||||
audio_path=crowded_audio,
|
||||
cues=many,
|
||||
)])[0]
|
||||
crowded = dest2.track_cues(crowded_id)
|
||||
check("the bank is filled but not overflowed", len(crowded.cues) == 8, str(len(crowded.cues)))
|
||||
check("the hot cues are the ones that survived",
|
||||
sorted(c.slot for c in crowded.cues) == list(range(8)))
|
||||
check("the memory cue that would not fit is dropped, not misplaced",
|
||||
all(c.start < 99.0 for c in crowded.cues))
|
||||
|
||||
print("== the source slot ==")
|
||||
# A source is a library read FROM, open alongside the loaded one. The whole slot
|
||||
# rests on it being read-only, so that is asserted where the source is opened
|
||||
# rather than assumed by everything downstream.
|
||||
from konduktor.app_state import AppState # noqa: E402
|
||||
|
||||
state = AppState()
|
||||
nml3, _, _ = fresh_collection()
|
||||
state.open(nml3)
|
||||
check("a collection loads as the destination", state.loaded)
|
||||
check("and no source is open yet", not state.source_loaded)
|
||||
|
||||
state.open_source(FIXTURE)
|
||||
check("a read-only drive opens as a source", state.source_loaded)
|
||||
check("the destination is untouched by opening a source",
|
||||
state.loaded and state.path == nml3)
|
||||
check("the source projects its own tracks", len(state.source.tracks) == 2)
|
||||
check("the two libraries are genuinely different objects",
|
||||
state.source is not state.adapter)
|
||||
|
||||
# Opening your own collection as a source of itself is the mistake this guards.
|
||||
before_source = state.source
|
||||
check("a WRITABLE library is refused as a source",
|
||||
_raises(lambda: state.open_source(nml3), ValueError))
|
||||
check("and the refusal leaves the existing source in place",
|
||||
state.source is before_source)
|
||||
|
||||
state.close_source()
|
||||
check("closing releases the source", not state.source_loaded)
|
||||
check("but not the destination", state.loaded)
|
||||
check("closing twice is safe", state.close_source() is None)
|
||||
|
||||
print("== folders ==")
|
||||
# Imported playlists land in a folder named after the drive, and the protocol had
|
||||
# no folder verb until this feature needed one.
|
||||
nml4, _, _ = fresh_collection()
|
||||
dest4 = TraktorAdapter(nml4)
|
||||
fid = dest4.create_folder("Hardy")
|
||||
check("a folder can be created", fid.startswith("fld:"), fid)
|
||||
# Re-importing the same stick must land BESIDE the first import, not next to an
|
||||
# identically-named twin.
|
||||
check("creating it again returns the same folder", dest4.create_folder("Hardy") == fid)
|
||||
pid = dest4.create_playlist("demos", fid)
|
||||
node = next((n for n in dest4.playlist_tree() if n.id == fid), None)
|
||||
check("the folder is in the tree", node is not None and node.kind == "folder")
|
||||
check("and the playlist is inside it",
|
||||
node is not None and [c.name for c in node.children] == ["demos"])
|
||||
check("read-only sources refuse to make folders",
|
||||
_raises(lambda: source.create_folder("x"), Unsupported))
|
||||
|
||||
print("== the job registry ==")
|
||||
from konduktor.jobs import JobCancelled, JobRegistry # noqa: E402
|
||||
|
||||
reg = JobRegistry()
|
||||
job = reg.submit("test", lambda h: 41 + 1)
|
||||
for _ in range(200):
|
||||
if job.finished:
|
||||
break
|
||||
time.sleep(0.01)
|
||||
check("a job runs and reports its result", job.state == "done" and job.result == 42)
|
||||
|
||||
def boom(h):
|
||||
raise RuntimeError("nope")
|
||||
|
||||
|
||||
# The registry logs a traceback for a failed job, which is right in production
|
||||
# and alarming in test output — a deliberate failure should not look like a
|
||||
# real one to someone scanning the suite.
|
||||
logging.getLogger("konduktor.jobs").setLevel(logging.CRITICAL)
|
||||
failing = reg.submit("test", boom)
|
||||
for _ in range(200):
|
||||
if failing.finished:
|
||||
break
|
||||
time.sleep(0.01)
|
||||
check("a failing job is reported, not swallowed",
|
||||
failing.state == "failed" and "nope" in (failing.error or ""))
|
||||
logging.getLogger("konduktor.jobs").setLevel(logging.NOTSET)
|
||||
|
||||
# Cancel is a REQUEST: the job stops at its next checkpoint, so the state must
|
||||
# not flip until the work has actually unwound and cleaned up.
|
||||
started = threading.Event()
|
||||
|
||||
def slow(h):
|
||||
started.set()
|
||||
while True:
|
||||
h.raise_if_cancelled()
|
||||
time.sleep(0.01)
|
||||
|
||||
running = reg.submit("test", slow)
|
||||
started.wait(2)
|
||||
check("cancel is accepted while running", reg.cancel(running.id))
|
||||
for _ in range(400):
|
||||
if running.finished:
|
||||
break
|
||||
time.sleep(0.01)
|
||||
check("and the job ends up cancelled", running.state == "cancelled")
|
||||
check("cancelling a finished job does nothing", not reg.cancel(running.id))
|
||||
check("cancelling an unknown job does nothing", not reg.cancel("nope"))
|
||||
|
||||
print("== import: plan and run ==")
|
||||
from konduktor import importer # noqa: E402
|
||||
|
||||
nml5, music5, _ = fresh_collection()
|
||||
dest5 = TraktorAdapter(nml5)
|
||||
plan5 = importer.plan(source, dest5, music5)
|
||||
check("the plan covers the whole drive when nothing is selected", len(plan5.tracks) == 2)
|
||||
check("it finds the playlist", [n for _, n in plan5.playlists] == ["demos"])
|
||||
check("it sizes the copy", plan5.total_bytes > 0)
|
||||
check("nothing is missing", plan5.importable == plan5.tracks)
|
||||
|
||||
# Selecting a playlist AUTO-INCLUDES its tracks, deduplicated.
|
||||
pl_id = importer._all_playlists(source)[0][0]
|
||||
plan_pl = importer.plan(source, dest5, music5, playlist_ids=[pl_id])
|
||||
check("selecting a playlist pulls in its tracks", len(plan_pl.tracks) == 2)
|
||||
plan_both = importer.plan(
|
||||
source, dest5, music5, playlist_ids=[pl_id],
|
||||
track_ids=[t.id for t in source.tracks],
|
||||
)
|
||||
check("a track in both a selection and a playlist is copied once",
|
||||
len(plan_both.tracks) == 2, str(len(plan_both.tracks)))
|
||||
|
||||
|
||||
class _Handle:
|
||||
"""A JobHandle stand-in, so the import can be driven without a thread."""
|
||||
|
||||
def __init__(self, cancel_after=None):
|
||||
self.messages = []
|
||||
self.done = 0
|
||||
self.total = 0
|
||||
self._cancel_after = cancel_after
|
||||
self.cancelled = False
|
||||
|
||||
def progress(self, done=None, total=None, message=None):
|
||||
if done is not None:
|
||||
self.done = done
|
||||
if total is not None:
|
||||
self.total = total
|
||||
if message is not None:
|
||||
self.messages.append(message)
|
||||
if self._cancel_after is not None and self.done >= self._cancel_after:
|
||||
self.cancelled = True
|
||||
|
||||
def raise_if_cancelled(self):
|
||||
if self.cancelled:
|
||||
raise JobCancelled()
|
||||
|
||||
|
||||
handle = _Handle()
|
||||
result = importer.run(source, dest5, plan5, handle, folder_name="Hardy")
|
||||
check("the import reports what it did", result["tracks"] == 2 and result["playlists"] == 1)
|
||||
check("progress reached the total", handle.total > 0 and handle.done == handle.total,
|
||||
f"{handle.done}/{handle.total}")
|
||||
check("it said what it was doing", any("Copying" in m for m in handle.messages))
|
||||
check("the audio really was copied",
|
||||
sorted(p.name for p in music5.iterdir()) == ["Demo Track 1.mp3", "Demo Track 2.mp3"])
|
||||
check("the tracks are in the collection", len(dest5.tracks) == 8485 + 2)
|
||||
tree5 = dest5.playlist_tree()
|
||||
folder = next((n for n in tree5 if n.name == "Hardy"), None)
|
||||
check("the playlist landed in a folder named after the drive",
|
||||
folder is not None and [c.name for c in folder.children] == ["demos"])
|
||||
check("and the playlist has its tracks",
|
||||
folder is not None and folder.children[0].count == 2)
|
||||
|
||||
print("== import: cancelling rolls back ==")
|
||||
nml6, music6, original6 = fresh_collection()
|
||||
dest6 = TraktorAdapter(nml6)
|
||||
plan6 = importer.plan(source, dest6, music6)
|
||||
# Cancel mid-copy — which is the case that used to leave a half-written file
|
||||
# behind, because cleanup only covered COMPLETED copies.
|
||||
cancelling = _Handle(cancel_after=1)
|
||||
cancelled_ok = _raises(
|
||||
lambda: importer.run(source, dest6, plan6, cancelling, folder_name="Hardy"),
|
||||
JobCancelled,
|
||||
)
|
||||
check("a cancelled import raises rather than half-finishing", cancelled_ok)
|
||||
left = sorted(p.name for p in music6.iterdir()) if music6.exists() else []
|
||||
check("no audio is left orphaned, including the file being written", left == [], str(left))
|
||||
check("the collection on disk is untouched", nml6.read_bytes() == original6)
|
||||
check("and nothing was added in memory either", len(dest6.tracks) == 8485)
|
||||
# The retry must not have to suffix around debris from the cancelled run.
|
||||
retry = _Handle()
|
||||
importer.run(source, dest6, plan6, retry, folder_name="Hardy")
|
||||
check("a retry after a cancel copies under the original names",
|
||||
sorted(p.name for p in music6.iterdir()) == ["Demo Track 1.mp3", "Demo Track 2.mp3"],
|
||||
str(sorted(p.name for p in music6.iterdir())))
|
||||
|
||||
print("== import: missing audio ==")
|
||||
nml7, music7, _ = fresh_collection()
|
||||
dest7 = TraktorAdapter(nml7)
|
||||
plan7 = importer.plan(source, dest7, music7)
|
||||
plan7.tracks[0].missing = True
|
||||
check("a missing file is excluded from the copy", len(plan7.importable) == 1)
|
||||
check("but still reported", len(plan7.as_dict()["missing"]) == 1)
|
||||
r7 = importer.run(source, dest7, plan7, _Handle(), folder_name="Hardy")
|
||||
check("the import proceeds without it", r7["tracks"] == 1 and r7["skipped_missing"] == 1)
|
||||
|
||||
print("== import: duplicate detection ==")
|
||||
plan8 = importer.plan(source, dest5, music5)
|
||||
check("re-importing flags the tracks as already present",
|
||||
all(t.duplicate for t in plan8.tracks), str([t.duplicate for t in plan8.tracks]))
|
||||
check("but does not refuse them — the user chose to add everything",
|
||||
len(plan8.importable) == 2)
|
||||
|
||||
print()
|
||||
print("RESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Layering guard: `core` must not know any platform exists.
|
||||
|
||||
The whole value of the adapter split is that `konduktor.core` can be read as the
|
||||
contract a future Rekordbox or Serato adapter is written against. One stray
|
||||
import of a native type would quietly make it Traktor-shaped again, and nothing
|
||||
else in the suite would notice.
|
||||
"""
|
||||
import ast
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
CORE = Path(__file__).resolve().parent / "konduktor" / "core"
|
||||
FORBIDDEN = ("traktor_nml_utils", "konduktor.adapters", "xsdata")
|
||||
|
||||
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
|
||||
|
||||
|
||||
print("== core/ imports nothing platform-specific ==")
|
||||
offences: list[str] = []
|
||||
for src in sorted(CORE.rglob("*.py")):
|
||||
tree = ast.parse(src.read_text())
|
||||
for node in ast.walk(tree):
|
||||
names: list[str] = []
|
||||
if isinstance(node, ast.Import):
|
||||
names = [a.name for a in node.names]
|
||||
elif isinstance(node, ast.ImportFrom):
|
||||
# level > 0 is a relative import; ".." from core/ reaches konduktor,
|
||||
# which is allowed (paths, prefs), but "...adapters" is not.
|
||||
names = [node.module or ""]
|
||||
if node.level and "adapters" in (node.module or ""):
|
||||
offences.append(f"{src.name}: relative import of {node.module}")
|
||||
for n in names:
|
||||
if any(n == f or n.startswith(f + ".") for f in FORBIDDEN):
|
||||
offences.append(f"{src.name}: {n}")
|
||||
|
||||
check("no core module imports a native library type", not offences, "; ".join(offences))
|
||||
|
||||
print("== adapters own their native model ==")
|
||||
store = (CORE.parent / "adapters" / "traktor" / "store.py").read_text()
|
||||
check("the Traktor store is where traktor_nml_utils lives", "traktor_nml_utils" in store)
|
||||
|
||||
# No adapter may import another platform's library. That is the rule that keeps
|
||||
# the packages independently removable, and it is checked on real imports (AST)
|
||||
# rather than on text, so merely NAMING another platform in a comment is fine.
|
||||
# OneLibrary shares Rekordbox's native library: both are AlphaTheta formats
|
||||
# read through pyrekordbox. That makes the map non-injective, which is fine —
|
||||
# the rule being enforced is "no adapter reaches for a RIVAL vendor's library",
|
||||
# and a shared dependency is not a layering breach. (The OneLibrary adapter
|
||||
# also imports the Rekordbox adapter's ANLZ beatgrid helper on purpose: one
|
||||
# definition of "when does a tempo change start a new marker" is worth more
|
||||
# than two packages that can be deleted independently.)
|
||||
NATIVE = {
|
||||
"traktor": "traktor_nml_utils",
|
||||
"rekordbox": "pyrekordbox",
|
||||
"onelibrary": "pyrekordbox",
|
||||
}
|
||||
|
||||
|
||||
def imported_modules(path):
|
||||
names = set()
|
||||
for node in ast.walk(ast.parse(path.read_text())):
|
||||
if isinstance(node, ast.Import):
|
||||
names.update(a.name for a in node.names)
|
||||
elif isinstance(node, ast.ImportFrom) and not node.level:
|
||||
names.add(node.module or "")
|
||||
return names
|
||||
|
||||
|
||||
for platform, module in NATIVE.items():
|
||||
pkg = CORE.parent / "adapters" / platform
|
||||
if not pkg.is_dir():
|
||||
continue
|
||||
# Subtract the adapter's OWN module: two adapters may legitimately share a
|
||||
# native library (Rekordbox and OneLibrary both use pyrekordbox), and
|
||||
# without this every shared dependency reads as a foreign one.
|
||||
foreign = {m for p_, m in NATIVE.items() if p_ != platform} - {module}
|
||||
strays = []
|
||||
for src in sorted(pkg.rglob("*.py")):
|
||||
for name in imported_modules(src):
|
||||
if any(name == f or name.startswith(f + ".") for f in foreign):
|
||||
strays.append(f"{src.name}: {name}")
|
||||
check(f"the {platform} adapter imports no other platform's library",
|
||||
not strays, "; ".join(strays))
|
||||
own = [
|
||||
src.name
|
||||
for src in sorted(pkg.rglob("*.py"))
|
||||
if any(n == module or n.startswith(module + ".") for n in imported_modules(src))
|
||||
]
|
||||
check(f"the {platform} adapter does import {module} somewhere", bool(own), "nowhere")
|
||||
|
||||
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Stable library identity: the thing export sets are keyed by.
|
||||
|
||||
The property under test is one no other suite covers: **a library that moves
|
||||
keeps its identity**. Everything Konduktor persists about a library keys off its
|
||||
OS path today, so moving a collection silently orphans its history repo and its
|
||||
path mapping. That is tolerable for those; it is not tolerable for export sets,
|
||||
which are curated user work.
|
||||
|
||||
Runs entirely on temp directories and a temp app-data dir — it never touches a
|
||||
real library, and `KONDUKTOR_DATA_DIR` keeps the registry out of the user's own.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
# Isolate the app-data dir BEFORE anything reads it.
|
||||
_TMP = tempfile.TemporaryDirectory()
|
||||
os.environ["KONDUKTOR_DATA_DIR"] = _TMP.name
|
||||
|
||||
from konduktor import library_id, paths # noqa: E402
|
||||
|
||||
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 a_library(folder: Path, name: str = "collection.nml") -> Path:
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
lib = folder / name
|
||||
lib.write_text("<NML/>")
|
||||
return lib
|
||||
|
||||
|
||||
root = Path(tempfile.mkdtemp())
|
||||
|
||||
print("== an id is stable, and written beside the library ==")
|
||||
lib = a_library(root / "Traktor 4.5.0")
|
||||
first = library_id.for_path(lib, platform="traktor", label="collection.nml")
|
||||
check("an id is issued", bool(first))
|
||||
check("asking again gives the same id", library_id.for_path(lib) == first)
|
||||
check("a sidecar is written", (lib.parent / library_id.SIDECAR_NAME).is_file())
|
||||
# The app's own file browser skips dotfiles, so the sidecar must be one or it
|
||||
# shows up in the picker as a mystery file next to the user's collection.
|
||||
check("the sidecar is hidden", library_id.SIDECAR_NAME.startswith("."))
|
||||
check("the id is durable", library_id.is_durable(first))
|
||||
# Used as a filename by the export-set store, so it must not need escaping.
|
||||
check("the id is filesystem-safe", first.replace("-", "").isalnum(), first)
|
||||
|
||||
print("== the whole point: it survives a move ==")
|
||||
moved = root / "Somewhere Else"
|
||||
lib.parent.rename(moved)
|
||||
after_move = library_id.for_path(moved / "collection.nml")
|
||||
check("a moved library keeps its id", after_move == first, f"{after_move} vs {first}")
|
||||
check("the registry follows it to the new path",
|
||||
library_id.describe(first)["path"] == str(moved / "collection.nml"))
|
||||
check("and it is still one library, not two", len(library_id.known()) == 1,
|
||||
list(library_id.known()))
|
||||
|
||||
print("== two libraries in ONE folder are two libraries ==")
|
||||
# The flaw this found: one sidecar per folder holding a single id would hand a
|
||||
# `collection.nml` and an older one kept beside it the SAME identity — and then
|
||||
# show one library's export sets against the other.
|
||||
second = a_library(moved, "collection-2023.nml")
|
||||
other = library_id.for_path(second, platform="traktor")
|
||||
check("a sibling library gets its own id", other != first, f"{other} vs {first}")
|
||||
check("one sidecar holds both", len(json.loads(
|
||||
(moved / library_id.SIDECAR_NAME).read_text())["libraries"]) == 2)
|
||||
check("each keeps its own on a re-read",
|
||||
library_id.for_path(moved / "collection.nml") == first
|
||||
and library_id.for_path(second) == other)
|
||||
|
||||
print("== separate folders are separate libraries ==")
|
||||
elsewhere = a_library(root / "Traktor 3.11.0")
|
||||
third = library_id.for_path(elsewhere, platform="traktor")
|
||||
check("a different folder gets a different id", len({first, other, third}) == 3)
|
||||
|
||||
print("== a library Konduktor must not write beside ==")
|
||||
# A removable drive: writing to a user's USB stick for Konduktor's own
|
||||
# bookkeeping is not a trade worth making, so those get a path-derived id.
|
||||
stick = root / "GIG"
|
||||
stick_lib = a_library(stick)
|
||||
volatile = library_id.for_path(stick_lib, platform="onelibrary", sidecar=False)
|
||||
check("no sidecar is written", not (stick / library_id.SIDECAR_NAME).exists())
|
||||
check("the id is reported as NOT durable", not library_id.is_durable(volatile))
|
||||
check("it is still stable for a given path", library_id.for_path(stick_lib, sidecar=False) == volatile)
|
||||
check("it is still registered", library_id.describe(volatile) is not None)
|
||||
|
||||
print("== a directory library keys on the folder itself ==")
|
||||
drive = root / "DriveLibrary"
|
||||
drive.mkdir()
|
||||
drive_id = library_id.for_path(drive, platform="onelibrary")
|
||||
check("a directory library gets an id", bool(drive_id))
|
||||
check("keyed as '.', not by a filename",
|
||||
"." in json.loads((drive / library_id.SIDECAR_NAME).read_text())["libraries"])
|
||||
check("and is stable", library_id.for_path(drive) == drive_id)
|
||||
|
||||
print("== an unwritable location falls back rather than failing ==")
|
||||
locked = root / "ReadOnly"
|
||||
locked_lib = a_library(locked)
|
||||
os.chmod(locked, 0o500) # r-x: cannot create the sidecar
|
||||
try:
|
||||
fallback = library_id.for_path(locked_lib, platform="traktor")
|
||||
check("an id is still issued", bool(fallback))
|
||||
check("and it says it is not durable", not library_id.is_durable(fallback))
|
||||
finally:
|
||||
os.chmod(locked, 0o700)
|
||||
|
||||
print("== the registry is an index, and disposable ==")
|
||||
before = len(library_id.known())
|
||||
library_id.forget(third)
|
||||
check("forget removes it", library_id.describe(third) is None)
|
||||
check("and only it", len(library_id.known()) == before - 1)
|
||||
# The sidecar is the source of truth, so re-opening reissues the SAME id rather
|
||||
# than a new one. A registry that could be lost and silently renumber libraries
|
||||
# would be worse than no registry.
|
||||
check("re-opening restores it from the sidecar",
|
||||
library_id.for_path(elsewhere) == third)
|
||||
|
||||
print("== atomic writes: a reader never sees half a file ==")
|
||||
target = Path(_TMP.name) / "atomic.json"
|
||||
paths.write_json(target, {"a": 1})
|
||||
paths.write_json(target, {"a": 2, "b": 3})
|
||||
check("the second write replaced the first whole", paths.read_json(target) == {"a": 2, "b": 3})
|
||||
check("no temp files left behind",
|
||||
not [p for p in target.parent.iterdir() if p.name.startswith(".atomic.json.tmp")],
|
||||
[p.name for p in target.parent.iterdir()])
|
||||
check("a missing file reads as the default", paths.read_json(target.with_name("nope.json"), "x") == "x")
|
||||
check("so does a corrupt one",
|
||||
(target.write_text("{not json"), paths.read_json(target, "x"))[1] == "x")
|
||||
|
||||
print("\n" + ("❌ FAILED" if failed else "✅ PASSED"))
|
||||
_TMP.cleanup()
|
||||
raise SystemExit(1 if failed else 0)
|
||||
@@ -0,0 +1,359 @@
|
||||
"""Tests for the OneLibrary adapter (read-only).
|
||||
|
||||
The third platform against the same contract, and the first whose library is a
|
||||
REMOVABLE DRIVE rather than a file — so the layout resolution gets as much
|
||||
attention here as the projection does.
|
||||
|
||||
Unlike `test_rekordbox_adapter.py`, this needs nothing installed and nothing
|
||||
plugged in: it runs against `fixtures/onelibrary/`, a real rekordbox 7 export
|
||||
trimmed to fixture size (see its README). That makes it deterministic on any
|
||||
machine, and it also means the expected values below are checked against bytes
|
||||
rekordbox wrote rather than against bytes Konduktor wrote — which is the only
|
||||
way a "we read the format correctly" claim means anything.
|
||||
|
||||
Where a value was cross-checked against the SAME cues in the desktop
|
||||
`master.db`, the test says so, because that cross-check is what pins the slot
|
||||
numbering (the one thing most likely to be silently wrong).
|
||||
"""
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-ol-appdata-")
|
||||
|
||||
from konduktor.adapters.onelibrary import discovery # noqa: E402
|
||||
from konduktor.adapters.onelibrary.adapter import OneLibraryAdapter # noqa: E402
|
||||
from konduktor.adapters.onelibrary.beatgrid import markers_from_beats # noqa: E402
|
||||
from konduktor.adapters.onelibrary.cues import ( # noqa: E402
|
||||
MEMORY_SLOT,
|
||||
NO_LOOP,
|
||||
cues_from_anlz,
|
||||
)
|
||||
from konduktor.adapters.onelibrary.driver import OneLibraryDriver # noqa: E402
|
||||
from konduktor.adapters.onelibrary.layout import DriveLayout # noqa: E402
|
||||
from konduktor.core import registry # noqa: E402
|
||||
from konduktor.core.adapter import LibraryAdapter, NotFound, Unsupported # noqa: E402
|
||||
|
||||
FIXTURE = Path(__file__).resolve().parent / "fixtures" / "onelibrary"
|
||||
|
||||
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 _raises(fn, exc) -> bool:
|
||||
try:
|
||||
fn()
|
||||
except exc:
|
||||
return True
|
||||
except Exception: # noqa: BLE001 — the wrong error is still a failure
|
||||
return False
|
||||
return False
|
||||
|
||||
|
||||
# ---- pure units: no drive required --------------------------------------
|
||||
print("== drive layout ==")
|
||||
tmp = Path(tempfile.mkdtemp(prefix="konduktor-ol-layout-"))
|
||||
(tmp / "PIONEER" / "rekordbox").mkdir(parents=True)
|
||||
db = tmp / "PIONEER" / "rekordbox" / "exportLibrary.db"
|
||||
db.write_bytes(b"not really a database")
|
||||
|
||||
layout = DriveLayout.locate(tmp)
|
||||
check("a drive root is recognised", layout is not None and layout.database == db)
|
||||
check("and so is the database file itself",
|
||||
(l2 := DriveLayout.locate(db)) is not None and l2.root == tmp)
|
||||
check("a directory with no PIONEER folder is not a drive",
|
||||
DriveLayout.locate(Path(tempfile.mkdtemp())) is None)
|
||||
check("a stray file called exportLibrary.db is not a drive",
|
||||
DriveLayout.locate(Path(tempfile.mkdtemp()) / "exportLibrary.db") is None)
|
||||
|
||||
# The stored path leads with a slash but is NOT absolute. Joining it naively
|
||||
# discards the mount point entirely and silently yields /Contents/... — a bug
|
||||
# that would look like "the drive is empty" rather than like a path error.
|
||||
resolved = layout.resolve("/Contents/Music/a.mp3")
|
||||
check("a drive-relative path resolves under the mount point",
|
||||
resolved == tmp / "Contents" / "Music" / "a.mp3", str(resolved))
|
||||
check("the leading slash is not treated as a host root",
|
||||
not str(resolved).startswith("/Contents"))
|
||||
check("backslashes resolve too", layout.resolve("\\Contents\\a.mp3") == tmp / "Contents" / "a.mp3")
|
||||
check("an empty path resolves to nothing", layout.resolve("") is None and layout.resolve(None) is None)
|
||||
check("the .EXT sits beside the .DAT",
|
||||
layout.extended_anlz(Path("/x/ANLZ0000.DAT")) == Path("/x/ANLZ0000.EXT"))
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
|
||||
print("== beatgrid collapse ==")
|
||||
# Shared with the Rekordbox adapter on purpose — two copies of this rule would be
|
||||
# free to drift apart by a rounding tolerance, and a drifting grid is silent.
|
||||
check("a constant tempo is one marker",
|
||||
len(markers_from_beats([0.0, 0.5, 1.0], [120.0, 120.0, 120.0])) == 1)
|
||||
check("a tempo change adds a marker",
|
||||
[m.bpm for m in markers_from_beats([0.0, 0.5, 1.0], [120.0, 120.0, 90.0])] == [120.0, 90.0])
|
||||
check("no beats is no grid", markers_from_beats([], []) == [])
|
||||
|
||||
|
||||
class _Entry(dict):
|
||||
"""A stand-in for a parsed ANLZ cue entry (construct Containers are dicts)."""
|
||||
|
||||
def __getattr__(self, name):
|
||||
try:
|
||||
return self[name]
|
||||
except KeyError as ex:
|
||||
raise AttributeError(name) from ex
|
||||
|
||||
|
||||
class _Tag:
|
||||
def __init__(self, tag_type, entries):
|
||||
self.type = tag_type
|
||||
self.struct = type("S", (), {"content": type("C", (), {"entries": entries})()})()
|
||||
|
||||
|
||||
class _Anlz:
|
||||
def __init__(self, tags):
|
||||
self.tags = tags
|
||||
|
||||
|
||||
def _entry(**kw):
|
||||
base = dict(hot_cue=1, time=1000, loop_time=NO_LOOP, type=1,
|
||||
color_red=0, color_green=0, color_blue=0, comment="")
|
||||
base.update(kw)
|
||||
return _Entry(base)
|
||||
|
||||
|
||||
print("== cue decoding ==")
|
||||
# The generic slot is 0-based (slot 0 is the pad labelled A). ANLZ's hot_cue is
|
||||
# a DENSE 1-based index, unlike master.db's Kind which skips 4 — so the two
|
||||
# platforms need different arithmetic even though they are the same vendor.
|
||||
one = cues_from_anlz(_Anlz([_Tag("PCO2", [_entry(hot_cue=1, time=5000)])]), None)
|
||||
check("ANLZ hot_cue 1 is generic slot 0 — the pad labelled A",
|
||||
len(one) == 1 and one[0].slot == 0 and one[0].role == "hotcue")
|
||||
four = cues_from_anlz(_Anlz([_Tag("PCO2", [_entry(hot_cue=4)])]), None)
|
||||
check("hot_cue 4 is slot 3 (pad D) — NOT shifted past a reserved value",
|
||||
four[0].slot == 3)
|
||||
mem = cues_from_anlz(_Anlz([_Tag("PCO2", [_entry(hot_cue=MEMORY_SLOT)])]), None)
|
||||
check("hot_cue 0 is a memory cue with no slot",
|
||||
mem[0].role == "memory" and mem[0].slot is None)
|
||||
|
||||
# loop_time is an unsigned -1 when there is no loop, so a falsiness test would
|
||||
# read 0xFFFFFFFF as a loop ending at zero.
|
||||
point = cues_from_anlz(_Anlz([_Tag("PCO2", [_entry(type=1, loop_time=NO_LOOP)])]), None)
|
||||
check("a point cue has no length", point[0].length == 0.0 and point[0].type == "cue")
|
||||
loop = cues_from_anlz(_Anlz([_Tag("PCO2", [_entry(type=2, time=40000, loop_time=41875)])]), None)
|
||||
check("a loop's length is its out minus its in",
|
||||
loop[0].type == "loop" and abs(loop[0].length - 1.875) < 1e-9)
|
||||
|
||||
check("a colour comes through as #RRGGBB",
|
||||
cues_from_anlz(_Anlz([_Tag("PCO2", [_entry(color_red=255, color_green=140, color_blue=0)])]),
|
||||
None)[0].color == "#FF8C00")
|
||||
check("all-zero RGB means 'unset', not black",
|
||||
cues_from_anlz(_Anlz([_Tag("PCO2", [_entry()])]), None)[0].color is None)
|
||||
|
||||
# PCOB is split across the two files — .DAT holds pads 1-3, .EXT holds 4 and up —
|
||||
# so a reader that looks at one file has an incomplete bank.
|
||||
dat = _Anlz([_Tag("PCOB", [_entry(hot_cue=1), _entry(hot_cue=2, time=2000)])])
|
||||
ext = _Anlz([_Tag("PCOB", [_entry(hot_cue=4, time=4000)])])
|
||||
merged = cues_from_anlz(dat, ext)
|
||||
check("PCOB is merged across the .DAT and the .EXT",
|
||||
sorted(c.slot for c in merged) == [0, 1, 3], str([c.slot for c in merged]))
|
||||
check("PCO2 wins over PCOB when both are present",
|
||||
cues_from_anlz(dat, _Anlz([_Tag("PCO2", [_entry(hot_cue=8, time=9000)])]))[0].slot == 7)
|
||||
check("the same cue in two tags is reported once",
|
||||
len(cues_from_anlz(_Anlz([_Tag("PCO2", [_entry()]), _Tag("PCO2", [_entry()])]), None)) == 1)
|
||||
check("no cue tags is no cues", cues_from_anlz(_Anlz([]), None) == [])
|
||||
check("no analysis file at all is no cues", cues_from_anlz(None, None) == [])
|
||||
check("nothing read from a drive claims to be editable",
|
||||
all(not c.editable for c in merged))
|
||||
|
||||
|
||||
# ---- the real drive ------------------------------------------------------
|
||||
if not (FIXTURE / "PIONEER" / "rekordbox" / "exportLibrary.db").is_file():
|
||||
print(f"\nSKIP: no fixture drive at {FIXTURE}")
|
||||
sys.exit(1 if failed else 0)
|
||||
|
||||
print("\n== the driver recognises a drive by layout AND schema ==")
|
||||
driver = OneLibraryDriver()
|
||||
check("can_open accepts the drive root", driver.can_open(FIXTURE))
|
||||
check("can_open accepts the database directly",
|
||||
driver.can_open(FIXTURE / "PIONEER" / "rekordbox" / "exportLibrary.db"))
|
||||
check("can_open rejects an unrelated directory", not driver.can_open(Path(tempfile.mkdtemp())))
|
||||
check("the registry picks OneLibrary for it", registry.driver_for(FIXTURE).platform == "onelibrary")
|
||||
|
||||
# The two encrypted databases must not be confused for one another. They are both
|
||||
# SQLCipher with no readable header, and only the KEY tells them apart.
|
||||
fake = Path(tempfile.mkdtemp()) / "PIONEER" / "rekordbox" / "exportLibrary.db"
|
||||
fake.parent.mkdir(parents=True)
|
||||
shutil.copy(Path(__file__), fake) # a plain text file wearing the right name
|
||||
check("can_open rejects a non-database in the right place", not driver.can_open(fake.parent.parent.parent))
|
||||
|
||||
adapter = OneLibraryAdapter(FIXTURE)
|
||||
check("implements the LibraryAdapter protocol", isinstance(adapter, LibraryAdapter))
|
||||
|
||||
print("== the projection ==")
|
||||
tracks = adapter.tracks
|
||||
check("both tracks project", len(tracks) == 2, str(len(tracks)))
|
||||
by_title = {t.title: t for t in tracks}
|
||||
one = next(t for t in tracks if t.title and t.title.startswith("Demo Track 1"))
|
||||
check("title comes through", one.title.startswith("Demo Track 1"))
|
||||
check("artist comes through the lookup table", one.artist == "Loopmasters")
|
||||
check("label comes through the lookup table", one.label == "Loopmasters")
|
||||
check("bpmx100 becomes a real BPM", one.bpm == 128.0, str(one.bpm))
|
||||
check("length is whole seconds", one.length == 172, str(one.length))
|
||||
check("rating is 0-5, not Traktor's /51", 0 <= one.rating <= 5)
|
||||
check("comment comes through", (one.comment or "").startswith("Tracks by"))
|
||||
|
||||
# The id is the drive-relative path, NOT content_id: rekordbox renumbers rows
|
||||
# from 1 on every re-export, so a row number would break every remembered
|
||||
# reference the moment the user re-wrote the stick.
|
||||
check("the track id is its drive-relative path",
|
||||
one.id == "/Contents/Loopmasters/UnknownAlbum/Demo Track 1.mp3", one.id)
|
||||
check("filepath resolves under the mount point",
|
||||
one.filepath == str(FIXTURE / "Contents/Loopmasters/UnknownAlbum/Demo Track 1.mp3"))
|
||||
check("and the resolved file is really there", Path(one.filepath).is_file())
|
||||
check("audio_path agrees with the projection", str(adapter.audio_path(one.id)) == one.filepath)
|
||||
|
||||
print("== counts are approximate until the cues are read ==")
|
||||
check("no cues are claimed before the analysis file is parsed", one.cue_count == 0)
|
||||
check("a tempo plus an analysis file is guessed as one marker", one.grid_marker_count == 1)
|
||||
cues = adapter.track_cues(one.id)
|
||||
check("reading cues corrects cue_count", one.cue_count == len(cues.cues) == 5, str(one.cue_count))
|
||||
check("reading cues corrects hotcue_count", one.hotcue_count == 4, str(one.hotcue_count))
|
||||
check("reading cues corrects grid_marker_count", one.grid_marker_count == 2, str(one.grid_marker_count))
|
||||
check("track_cues on an unknown track is None", adapter.track_cues("no-such-track") is None)
|
||||
|
||||
print("== the beatgrid survives an export ==")
|
||||
# This grid was written into master.db by Konduktor, exported by rekordbox, and
|
||||
# confirmed on screen in Rekordbox 7 before it ever reached this fixture.
|
||||
markers = cues.grid_markers
|
||||
check("a flexible grid stays flexible", len(markers) == 2, str(len(markers)))
|
||||
check("the first segment is 128 BPM", markers[0].bpm == 128.0)
|
||||
check("the second segment is 90 BPM", markers[1].bpm == 90.0)
|
||||
check("and it starts at 60 s", abs(markers[1].start - 60.0) < 0.001, str(markers[1].start))
|
||||
check("markers are ordered by position", [m.start for m in markers] == sorted(m.start for m in markers))
|
||||
|
||||
print("== cues, cross-checked against the same cues in master.db ==")
|
||||
# master.db held djmdCue Kind 1/2/3/5 at 40.000 s / 18.773 s / 90.667 s /
|
||||
# 120.000 s plus a reserved-Kind memory loop at 40.000 s. Those same five cues
|
||||
# must come back here as slots 0/1/2/3 and one memory cue — which is what pins
|
||||
# ANLZ's dense numbering against master.db's sparse bank.
|
||||
hot = {c.slot: c for c in cues.cues if c.role == "hotcue"}
|
||||
check("four hot cues, on pads A-D", sorted(hot) == [0, 1, 2, 3], str(sorted(hot)))
|
||||
check("pad A is the loop at 40.000 s",
|
||||
hot[0].type == "loop" and abs(hot[0].start - 40.0) < 0.001)
|
||||
check("pad A's loop is 4 beats at 128 BPM = 1.875 s", abs(hot[0].length - 1.875) < 0.001)
|
||||
check("pad B is at 18.775 s", abs(hot[1].start - 18.775) < 0.001, str(hot[1].start))
|
||||
check("pad C is at 90.667 s", abs(hot[2].start - 90.667) < 0.001, str(hot[2].start))
|
||||
# Pad D exists ONLY in the .EXT. A reader that stopped at the .DAT would lose it,
|
||||
# and would do so silently.
|
||||
check("pad D is at 120.000 s — the cue that lives only in the .EXT",
|
||||
abs(hot[3].start - 120.0) < 0.001, str(hot[3].start))
|
||||
check("hot cues carry their RGB colour", all(c.color and c.color.startswith("#") for c in hot.values()))
|
||||
|
||||
memory = [c for c in cues.cues if c.role == "memory"]
|
||||
check("the memory cue is preserved", len(memory) == 1)
|
||||
check("it has no slot", memory[0].slot is None)
|
||||
check("it is the same loop, at the same place", abs(memory[0].start - 40.0) < 0.001)
|
||||
check("no cue on a read-only drive is editable", all(not c.editable for c in cues.cues))
|
||||
|
||||
print("== playlists ==")
|
||||
tree = adapter.playlist_tree()
|
||||
check("the playlist is at the root", len(tree) == 1 and tree[0].name == "demos", str(tree))
|
||||
node = tree[0]
|
||||
check("it is a playlist, not a folder", node.kind == "playlist" and node.selectable)
|
||||
check("its count is right", node.count == 2, str(node.count))
|
||||
check("playlist_count agrees", adapter.playlist_count() == 1)
|
||||
entries = adapter.playlist_entries(node.id)
|
||||
check("its entries are track ids, in order",
|
||||
entries == [t.id for t in (adapter.playlist_tracks(node.id) or [])])
|
||||
check("and they resolve to the two tracks", len(adapter.playlist_tracks(node.id)) == 2)
|
||||
check("a root playlist's parent 0 is not treated as a real node id", len(tree) == 1)
|
||||
check("nothing on the drive claims to be editable",
|
||||
not any(n.can_rename or n.can_delete or n.can_add_tracks or n.can_reorder for n in tree))
|
||||
check("entries for an unknown node are None", adapter.playlist_entries("999999") is None)
|
||||
|
||||
print("== capabilities gate the UI ==")
|
||||
caps = adapter.capabilities()
|
||||
check("platform is onelibrary", caps.platform == "onelibrary")
|
||||
# The distinction the whole capability system exists for: this is a roadmap gap,
|
||||
# not a protective refusal, and the UI must word the two differently.
|
||||
check("the library is read-only", caps.writable is False)
|
||||
check("because the platform is incomplete, not because of a sync state",
|
||||
caps.readonly_cause == "platform_incomplete")
|
||||
check("the version is the drive's dbVersion", caps.version == "1000", str(caps.version))
|
||||
# The per-feature flags still describe the FORMAT. Blanking them to false would
|
||||
# claim OneLibrary has no hot cues, which is not what read-only means.
|
||||
check("the format is still reported as having hot cues", caps.cues.hotcue_slots == 8)
|
||||
check("cue colour is free RGB here, unlike master.db's palette", caps.cues.color == "free")
|
||||
check("loops are a cue type, not a separate bank", caps.cues.loops == "cue_type")
|
||||
check("memory cues are acknowledged", caps.cues.memory_cues is True)
|
||||
check("the grid is flexible even though we do not write it", caps.grid.flexible is True)
|
||||
check("nothing is editable", not caps.cues.editable and not caps.grid.editable)
|
||||
check("no metadata field is editable", caps.tracks.editable_fields == [])
|
||||
check("ratings are 0-5", caps.tracks.rating_max == 5)
|
||||
check("folders are supported by the format", caps.playlists.folders is True)
|
||||
check("a drive carries no smart playlists", caps.playlists.smart == "none")
|
||||
check("drives are not versioned", caps.save.history is False)
|
||||
check("nothing else can overwrite it, because we never write", caps.save.overwrite_risk == "none")
|
||||
check("the label is the drive's name", caps.save.library_label == FIXTURE.name)
|
||||
|
||||
print("== every command is refused ==")
|
||||
COMMANDS = [
|
||||
("set_track_metadata", lambda: adapter.set_track_metadata(one.id, {"title": "x"})),
|
||||
("set_cover_art", lambda: adapter.set_cover_art(one.id, b"", "image/png")),
|
||||
("remove_tracks", lambda: adapter.remove_tracks([one.id])),
|
||||
("create_playlist", lambda: adapter.create_playlist("x")),
|
||||
("rename_playlist", lambda: adapter.rename_playlist(node.id, "x")),
|
||||
("delete_playlist", lambda: adapter.delete_playlist(node.id)),
|
||||
("set_playlist_entries", lambda: adapter.set_playlist_entries(node.id, [])),
|
||||
("set_cue", lambda: adapter.set_cue(one.id, slot=0, start_sec=1.0, cue_type="cue")),
|
||||
("set_cue_type", lambda: adapter.set_cue_type(one.id, 0, "loop")),
|
||||
("delete_cue", lambda: adapter.delete_cue(one.id, 0)),
|
||||
("place_cues", lambda: adapter.place_cues(one.id, [])),
|
||||
("add_grid_marker", lambda: adapter.add_grid_marker(one.id, 1.0)),
|
||||
("move_grid_marker", lambda: adapter.move_grid_marker(one.id, 0, 1.0)),
|
||||
("set_grid_marker_bpm", lambda: adapter.set_grid_marker_bpm(one.id, 0, 120.0)),
|
||||
("delete_grid_marker", lambda: adapter.delete_grid_marker(one.id, 0)),
|
||||
("replace_grid", lambda: adapter.replace_grid(one.id, [])),
|
||||
("set_analysed_grid", lambda: adapter.set_analysed_grid(one.id, [])),
|
||||
("delete_grid", lambda: adapter.delete_grid(one.id)),
|
||||
("set_grid_lock", lambda: adapter.set_grid_lock(one.id, True)),
|
||||
("remap_locations", lambda: adapter.remap_locations(None)),
|
||||
("save", lambda: adapter.save()),
|
||||
("snapshot", lambda: adapter.snapshot()),
|
||||
]
|
||||
refused = [name for name, fn in COMMANDS if not _raises(fn, Unsupported)]
|
||||
check(f"all {len(COMMANDS)} commands raise Unsupported", not refused, "; ".join(refused))
|
||||
check("nothing is ever dirty", adapter.dirty is False)
|
||||
check("an unknown track is a NotFound, not an Unsupported",
|
||||
_raises(lambda: adapter.audio_path("no-such-track"), NotFound))
|
||||
|
||||
print("== reads that answer rather than refuse ==")
|
||||
check("cover art is absent, not an error", adapter.cover_art(one.id) is None)
|
||||
# A drive stores everything relative to its own root, so it cannot have stale
|
||||
# absolute paths and there is nothing for a remap to fix.
|
||||
check("a path mapping is accepted and ignored", adapter.set_path_mapping(None) is None)
|
||||
check("remap_preview matches nothing", adapter.remap_preview(None)["matched"] == 0)
|
||||
check("path suggestions still describe the drive",
|
||||
adapter.path_prefix_suggestions()["primary"] is not None)
|
||||
|
||||
print("== discovery ==")
|
||||
described = discovery.describe(FIXTURE)
|
||||
check("a drive describes itself by name", FIXTURE.name in described["label"], described["label"])
|
||||
check("and points at the database", described["path"].endswith("exportLibrary.db"))
|
||||
check("and reports that it exists", described["exists"] is True)
|
||||
check("detection of unplugged drives is empty, not an error",
|
||||
isinstance(discovery.detect_libraries(), list))
|
||||
|
||||
adapter.close()
|
||||
check("closing twice is safe", adapter.close() is None)
|
||||
|
||||
print()
|
||||
print("RESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
Loaded 100 of 170 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user