diff --git a/.claude/discussions/discuss-multi-platform-library-2026-09-17.md b/.claude/discussions/discuss-multi-platform-library-2026-09-17.md new file mode 100644 index 0000000..c719780 --- /dev/null +++ b/.claude/discussions/discuss-multi-platform-library-2026-09-17.md @@ -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 `` +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 `` +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 ``. +`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. diff --git a/.claude/handoffs/export.md b/.claude/handoffs/export.md new file mode 100644 index 0000000..fe5d706 --- /dev/null +++ b/.claude/handoffs/export.md @@ -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. diff --git a/.claude/handoffs/rekordbox-adapter.md b/.claude/handoffs/rekordbox-adapter.md new file mode 100644 index 0000000..cabb0c1 --- /dev/null +++ b/.claude/handoffs/rekordbox-adapter.md @@ -0,0 +1,1047 @@ +# Handoff: the Rekordbox adapter + +**For**: an agent picking up Konduktor with no prior context. +**Task**: add Rekordbox as the second platform — step 4 of the multi-platform plan. +**Status of the plan**: steps 1–3 are done and committed (`08c9b81`, `c9e85bb`, `6e24f5e`). + +All *design* decisions for this work were settled in +[`.claude/discussions/discuss-multi-platform-library-2026-09-17.md`](../discussions/discuss-multi-platform-library-2026-09-17.md). +Read its **"If Moving to Planning/Implementation"** section before designing +anything. This handoff is the *current-state* companion to it: what exists now, +what to do next, and what will bite you. Where the two disagree, the discussion +doc wins on intent and this one wins on facts about the code. + +--- + +## 1. Where the project is + +Konduktor is a library-management and track-prep tool for DJ software. Until +recently it was Traktor-only. It now has a **generic model + per-platform adapter** +architecture with Traktor as the only adapter, and the generic shape reaches all +the way to the UI — nothing above `adapters/traktor/` knows Traktor exists. + +**The architecture is projection + command replay.** The generic model is a *read +projection*. Edits are strictly-generic commands that 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 the only model that works for a format you cannot regenerate — which is +exactly Rekordbox's situation. + +``` +backend/konduktor/ + core/ generic. MUST NOT import a native library type. + model.py Track, CuePoint, GridMarker, TrackCues, PlaylistNode… + adapter.py LibraryAdapter / LibraryDriver protocols + error tree + capabilities.py Capabilities — what a loaded library can persist + query.py TrackIndex: query/filter/sort/facets/stats + edit_journal.py EditJournal: every edit at field resolution + registry.py adapter selection by can_open() probe + audio_tags.py pathmap.py auto_hotcues.py + adapters/traktor/ the reference implementation — read this first + store.py retained native model (TraktorStore) + adapter.py TraktorAdapter: owns store + TrackIndex + projection.py native -> generic + driver.py capabilities.py beatgrid.py locations.py cue_types.py + app_state.py the one loaded library + version-history commits + main.py thin routes; talks only to the adapter +``` + +Frontend (`frontend/src/`) is already generic: `api.ts` carries string cue types, +`lib/capabilities.tsx` exposes `useCaps()`, `lib/platformCopy.ts` composes +per-platform wording from adapter-supplied *facts*. No component branches on the +platform name. + +**Tests**: `cd backend && ./run_tests.sh` → 146 assertions across +`test_layering.py`, `test_save_fidelity.py`, `test_traktor_adapter.py`, +`test_phase3.py`, `test_history.py`. Frontend: `npm run build && npm run test` +(25 vitest assertions on `lib/beatgrid.ts`). + +--- + +## 2. Start here: research before code + +The discussion doc lists one genuinely open question, and it gates the whole +write path: + +> **Rekordbox `rb_local_usn` / update-sequence + cloud-sync columns**: writing rows +> without maintaining these may corrupt Rekordbox's own sync state. + +Settle this **first**, empirically, against a real `master.db` — do not design the +write path around an assumption. Specifically find out: + +- What `rb_local_usn` is per row, what the per-table/global sequence is, and what + Rekordbox does on next launch when it sees a row it did not write. +- Whether `pyrekordbox` maintains these for you on write, or whether that is the + caller's job. (Assume nothing; read its source.) +- What `USN`/`rb_data_status`/`rb_local_deleted` and the other `rb_*` columns mean. +- What happens on a cloud-synced library specifically, since that is the failure + mode that could lose data on *other* machines — which is worse than a local + corruption the version history can undo. + +Write the findings up as a **Findings** section in this file (the discussion doc +is Concluded; don't edit it). If the answer turns out to be "Konduktor cannot +safely write a cloud-synced library", that is a legitimate result and should be +surfaced to Ben as a scope decision, not worked around silently. + +**Standing lesson from the discussion, which has already been proved right twice**: +establish format capabilities empirically against real files rather than assuming +them. Both previous assumptions that got checked (Traktor cue colours, flexible +grid marker naming) turned out to be wrong. + +--- + +## 3. What to build + +### 3.1 The adapter + +Create `backend/konduktor/adapters/rekordbox/` mirroring the Traktor package, and +register it in `adapters/__init__.py` (one line; the registry does the rest). + +Implement the two protocols in `core/adapter.py`. `LibraryDriver` is small: +`can_open` / `open` / `detect` / `describe` / `restore`. `LibraryAdapter` is the +real surface — 38 methods, all already defined in generic terms: + +``` +capabilities reload +tracks track query_tracks facets stats +playlist_tree playlist_entries playlist_tracks track_cues +create_playlist rename_playlist delete_playlist set_playlist_entries +set_track_metadata set_cover_art cover_art +set_cue set_cue_type delete_cue place_cues +add_grid_marker move_grid_marker set_grid_marker_bpm delete_grid_marker +replace_grid set_analysed_grid delete_grid set_grid_lock +audio_path set_path_mapping path_prefix_suggestions remap_preview remap_locations +dirty save snapshot +``` + +Two rules the Traktor adapter follows and yours must too: + +1. **Every mutating command returns its refreshed projection.** This makes the + refresh an adapter-internal invariant rather than something a route has to + remember. A forgotten refresh is a silently stale UI that no test would catch. +2. **`core/` stays clean.** `test_layering.py` fails the build if anything in + `core/` imports a native type. If you find yourself wanting to widen a `core/` + model for a Rekordbox-only reason, that is the two-platform promotion rule + telling you not to — see §4. + +`can_open` must not be extension-based: Rekordbox's library is `master.db` and +Serato's is a *directory*. Probe cheaply (Traktor's reads 4 KB and looks for the +NML header; yours will need to recognise a SQLCipher file without decrypting it +twice). + +### 3.2 Capabilities + +`core/capabilities.py` already has the fields. Rekordbox's answers, from the +discussion doc's platform notes — **verify each against a real library**: + +| Field | Expected for Rekordbox | Note | +|---|---|---| +| `cues.hotcue_slots` | 8 | | +| `cues.slot_labels` | `'letter'` | **First real customer.** The field exists but no UI has exercised it — expect to find bugs. | +| `cues.memory_cues` | `true` | See §4: still *not editable*. | +| `cues.types` | `['cue','loop']` | No fade_in/fade_out/load — those are Traktor-only. | +| `cues.color` | `'free'` or `'palette'` | Determine empirically; if palette, populate it. | +| `grid.flexible` | likely `true` | Verify. | +| `grid.lockable` | ? | Rekordbox's analysis lock is a *different concept* from Traktor's LOCK — check before mapping it. | +| `save.overwrite_risk` | `'while_running'` | Rekordbox holds the DB open and cloud-syncs. The copy already exists in `lib/platformCopy.ts`. | +| `save.library_label` | `'master.db'` | | + +### 3.3 Verification — non-negotiable + +The project's core safety property is: **an edit changes only what it was supposed +to change.** For Traktor that is a byte diff. A byte diff is meaningless against +SQLite, so build the agreed analogue: + +- **`test_rekordbox_fidelity.py`** — full table dump before/after, row-level diff. + A no-op save must produce zero row changes. A single metadata edit must change + exactly one row (plus whatever the USN research says *must* also change). +- **`test_rekordbox_adapter.py`** — the generic-layer test, modelled on + `test_traktor_adapter.py`: one parse per open, the projection refreshing after + each command family, cue-type translation, capabilities, `Unsupported` where the + platform cannot represent an edit. +- Add both to `run_tests.sh`. +- **Back up `master.db` *and* its `-wal`/`-shm`** before any write. A `.db` copied + without its WAL is not a consistent snapshot. + +**Never test against Ben's real library.** Every existing test copies to a temp +dir first. Do the same. + +--- + +## 4. Landmines (earned, not speculative) + +**`history.py` assumes a single tracked file.** It commits one blob named after the +library file into a git repo keyed by a hash of the library's OS path. Neither +assumption survives `master.db` + WAL/SHM. There is a read-side fallback chain for +the blob name, but the *multi-artefact* case is genuinely unimplemented. Decide +early whether Rekordbox history commits a snapshot set or is disabled for this +platform — and if disabled, `capabilities.save.history` must say so, because the +UI reads it. + +**Four spots in the adapter protocol are over-fitted to Traktor.** These were +recorded during the refactor precisely so you would not rediscover them. Expect to +revise the protocol; v1 was never frozen: + +- `GridMarker.companion` — a Traktor convention (a white cue paired with a grid + marker, occupying a real hotcue slot). Should be `null` on Rekordbox. +- **Hotcue `slot` as a plain `int`** — memory cues have no slot. `CuePoint.slot` is + already nullable, but every *command* is slot-addressed. This is the most likely + thing to need changing, and the frontend design considered (and deferred) opaque + cue IDs as the fix. Revisit that decision with real evidence. +- **Grid marker `index` as identity** — fine for a list-shaped grid, untested + against rows with their own primary keys. +- `set_analysed_grid` — invented for one caller (Auto Grid), to let Traktor write + the companion cue without leaking the concept upward. Check it still earns its + keep with two platforms. + +**Memory cues stay preserved-but-uneditable even after this lands.** The +two-platform promotion rule promotes a concept once **two or more** platforms have +it. Rekordbox is the *only* platform with memory cues (Traktor has none, Serato has +a saved-loop bank instead). So: project them, show them read-only, do **not** build +a memory-cue editing UI. This will feel wrong — build it anyway, the rule exists to +stop one-platform concepts becoming fake abstractions. + +**Per-cue colour, by contrast, *is* now promotable.** Traktor and Rekordbox both +have it, which is two platforms. `cueColor()` in `frontend/src/lib/cues.ts` already +prefers a stored colour over the type palette, and `capabilities.cues.color` is +already plumbed — but there is **no colour-editing control yet**. Adding one is +legitimately in scope for this step. + +**`slot_labels: 'letter'` has never run.** Rekordbox labels hotcues A–H. The field +is threaded through `HotcueBar`, `drawCues` and the keyboard map, but nothing has +ever set it to `'letter'`. Assume it is subtly broken. + +--- + +## 5. Working agreements + +- **`./run_tests.sh` must be green at the end of every step.** The Traktor refactor + was done in 18 steps with the suite green at each one; that discipline is why a + 1,500-line change to the save path landed without a fidelity regression. +- **`schemas.py` and `api.ts` land in the same commit, always.** They are one + contract in two languages. +- **The collection is real, irreplaceable data.** Point `KONDUKTOR_NML` (or the + Rekordbox equivalent) at a **copy** when testing writes. See CLAUDE.md gotcha 2. +- Read `CLAUDE.md` in full before starting — its Architecture and "Write path" + sections describe the current state accurately and its "Critical gotchas" are + all still live. + +## 6. Do not relitigate + +Settled in the discussion doc; reopening these wastes a session: + +- Projection + command replay as the save model (and why generic-model-as-source-of-truth + and diff-based writeback were both rejected). +- Strictly-generic command vocabulary, **no adapter escape hatches**. +- Rich core model + mandatory capability system. +- Rekordbox before Serato (`pyrekordbox` is the more mature library, despite the + riskier write target). +- **Warn but proceed** if Rekordbox is running — do not hard-refuse. +- Export is step 6, after Serato. Export Sets, fresh-target-only, copied audio. +- **CDJ/USB export (`export.pdb` + ANLZ) is rejected as impractical.** It has been + re-proposed once already. Do not raise it again. +- Deferred, do not reopen without Ben raising them: the export loss report, Tauri + packaging, two-way sync. + +**Bulk metadata editing** was deferred *to* this point specifically so it would +only have to be written once, against the adapter architecture. It is now +unblocked, and is a much smaller piece of work than the Rekordbox adapter. If Ben +wants something shippable sooner, that is the alternative — confirm with him rather +than assuming. + +--- + +## 7. One outstanding verification from step 3 + +**The React UI has never been rendered in a browser.** The generic wire format was +verified end-to-end through the Vite proxy (every endpoint, full write round trip, +byte-fidelity diff), but no browser driver was available on the dev machine — +no `chromium-cli`, no Playwright, and `npx` refused to install one. + +Before building on top of the frontend, open `http://localhost:5173` (`./dev.sh`) +and click through the prep deck, the library table and the playlist tree. If you +can get a browser driver working, capturing the launch recipe via +`/run-skill-generator` would be worth it — the app needs `KONDUKTOR_NML` and +`KONDUKTOR_DATA_DIR` pointed at a temp copy to be driven safely, which is exactly +the kind of thing a project skill should hold. + +--- + +## 8. Findings — Rekordbox research spike (2026-09-17) + +Answers to §2, established empirically against a real Rekordbox 7 library +(`~/Library/Pioneer/rekordbox/master.db`, 52 tracks, 23 cues, 1 playlist) with +`pyrekordbox` 0.4.4. **Every experiment ran against a copy in a scratch dir; the +real library was only ever read.** Rekordbox was not running. + +Each finding is marked **VERIFIED** (observed directly), **INFERRED** (strongly +implied but not directly exercised) or **UNTESTED**. + +### 8.1 The USN question is answered — and it is not a blocker + +**VERIFIED — the sequence model.** There is one global counter and one per-row +stamp: + +- `agentRegistry` row `registry_id='localUpdateCount'`, column `int_1` — the + global local USN. Observed at **1489**, with the highest `rb_local_usn` found + anywhere in the library at 1487. The global counter is the high-water mark. +- Every syncable table carries `rb_local_usn`. One edit = increment the global + counter by one, stamp the changed row with the new value. + +**VERIFIED — `pyrekordbox` maintains this for you.** It is not the caller's job. +`RekordboxAgentRegistry` hooks SQLAlchemy's update/create/delete events into an +update buffer, and `db.commit()` (default `autoinc=True`) calls +`autoincrement_local_update_count(set_row_usn=True)`, which walks the buffer, +increments the counter once per change and stamps each affected row +(`db6/registry.py:311-347`). Konduktor should **use `commit()` and not touch USNs +by hand.** + +**VERIFIED — a single metadata edit is exactly as localized as the Traktor +invariant demands.** Full 47-table row-level dump before/after a one-field Title +edit produced exactly two changed rows: + +``` +agentRegistry localUpdateCount UPDATE int_1: 1489->1490 +djmdContent 231764591 UPDATE Title: 'NOISE'->'...', rb_local_usn: 210->1490 +``` + +A no-op open+close, and an open + `commit()` with no edits, both produce **zero +row changes**. Invariants A and C from `test_save_fidelity.py` therefore have +direct, achievable Rekordbox analogues. + +**VERIFIED — the cloud columns are inert on a local library.** `usn` (the +*server* sequence number, distinct from `rb_local_usn`) is **NULL on every row of +every table**, and `rb_data_status`, `rb_local_data_status`, `rb_local_deleted` +and `rb_local_synced` are **0 on every row**. This library has a signed-in +account (`agentRegistry.agentCredentials` is populated) but Cloud Library Sync is +not enabled for the collection. + +**UNTESTED — the cloud-synced case.** Because nothing in this library is synced, +the spike could not observe what the server does with a locally-bumped USN it did +not issue. The risk in the handoff stands unrefuted for that configuration. Two +mitigations are available and cheap, and both should be built: + +1. Detect sync state on open — `usn` non-NULL anywhere, or a populated + `djmdCloudProperty`/`cloudAgentRegistry` — and surface it. +2. Gate writes on a cloud-synced library behind an explicit confirmation, or + report `save.overwrite_risk` accordingly. **Recommend raising this with Ben as + a scope decision before the write path is built**, per the handoff. + +**VERIFIED — detecting a running Rekordbox is already solved**: +`pyrekordbox.utils.get_rekordbox_pid()`. That is all "warn but proceed" needs. + +### 8.2 The real surprise: the write surface is three artefacts, not one + +This is the finding that should change the plan. Konduktor's prep features do not +all live in `master.db`. + +**VERIFIED — the beatgrid is NOT in the database.** There is no beatgrid, beat, +grid or tempo table anywhere in the 47-table schema. `djmdContent.BPM` is a +scalar display value stored ×100 (`12500` = 125.00 BPM) and is **`0` for 22 of +the 52 tracks** despite all 52 being analysed. The grid lives in the ANLZ +analysis files that `djmdContent.AnalysisDataPath` points at. + +**VERIFIED — and it is a per-beat list, not a marker list.** The `PQTZ` tag in +`ANLZ0000.DAT` stores **every beat explicitly** — beat-number-in-bar, BPM and +time per beat (one track: 496 entries). This is a materially different shape from +Traktor's marker list. The adapter must *derive* `GridMarker`s from runs of +constant BPM on read, and *expand* markers back into a full beat list on write. + +This directly revises the handoff's §4 landmine "grid marker `index` as identity +— untested against rows with their own primary keys": Rekordbox has no marker +rows at all. Index-as-identity is actually fine here, because the adapter mints +the marker list itself. The real work is the projection both ways. + +**VERIFIED — cues live only in the database, in two places at once.** +`djmdCue` holds normalized cue rows, and `contentCue` holds a **JSON mirror** of +the same cues per track (`contentCue.Cues` is a JSON array of the full cue +objects, with `rb_cue_count` alongside). Both are maintained by Rekordbox and +must be kept consistent by any writer — this is Rekordbox's structural analogue +of Traktor's companion-cue convention, and the same class of trap. + +**VERIFIED — the ANLZ cue lists are empty and can be ignored.** Across the whole +library, every `PCOB` (hotcue and memory) and `PCO2` tag in every `.DAT` and +`.EXT` has a cue count of **0**, while the database holds 23 cues. Rekordbox 7 +populates the ANLZ cue tags only on device/USB export — which is out of scope. +**Konduktor should write cues to the DB only.** + +**VERIFIED — Rekordbox does not stamp `rb_local_usn` on `djmdCue`.** All 23 +`djmdCue` rows have a NULL `rb_local_usn`, while `contentCue` rows are stamped +(956–1482). The sync unit for cues is `contentCue`, not the individual rows. +Note that `pyrekordbox`'s `set_row_usn=True` stamps *every* buffered instance +that has the attribute, so committing a new `DjmdCue` through it **would stamp a +row Rekordbox itself leaves NULL**. Whether that matters is UNTESTED, but it is a +deviation from observed native behaviour and worth matching deliberately. + +### 8.3 ANLZ write fidelity — a clean, defensible boundary + +Parse → `build()` → byte-compare, over every analysis file in the library: + +| File | Byte-identical | Differs | Holds | +|---|---|---|---| +| `.DAT` | **52 / 52** | 0 | `PQTZ` beatgrid, waveform, cue tags | +| `.EXT` | **52 / 52** | 0 | `PQT2`, colour waveform, `PSSI`, cue tags | +| `.2EX` | 32 / 52 | **20** | RB7 colour-waveform tags only | + +`.DAT` and `.EXT` — the only files Konduktor needs to write — round-trip +**byte-exactly**, so the gotcha-3 guarantee generalizes. `.2EX` loses ~4 KB on +rebuild because `pyrekordbox` 0.4.4 drops tags it does not know (`PVDI`), and +`.3EX` it cannot parse at all (`File type '.3EX' not supported!`). Neither holds +anything Konduktor edits. + +**Rule for the adapter: only ever rebuild `.DAT` and `.EXT`; never touch `.2EX` +or `.3EX`.** A `test_rekordbox_fidelity.py` assertion should pin this. + +### 8.4 `pyrekordbox` has no cue or beatgrid write API + +Its write surface is playlists, folders, smart playlists, albums, artists, +genres, labels, `add_content`, and attribute assignment on ORM objects. There is +no `add_cue`/`set_cue`/`delete_cue` — only `get_cue` / `get_content_cue`. + +So Konduktor must implement itself, against the ORM: +- creating/updating/deleting `DjmdCue` rows (including Rekordbox's own ID/UUID + minting convention), +- regenerating the `contentCue.Cues` JSON mirror and `rb_cue_count`, +- the whole beatgrid path via the `anlz` module (`set_beats`/`set_bpms`/ + `set_times` exist on `PQTZAnlzTag`, plus `AnlzFile.build()`/`save()`). + +**This is the single biggest correction to the effort estimate in this handoff.** +§3.1 frames the adapter as implementing 38 already-defined methods against a +mature library. That is true for metadata and playlists; it is not true for cues +and grids, which are the prep deck — Konduktor's most valuable feature — and +which need a hand-written native store per artefact type. + +### 8.5 Two hazards found by hitting them + +**A stale WAL beside a restored `.db` silently corrupts it.** `pyrekordbox` leaves +`master.db-wal`/`-shm` behind on `close()` — the write is in the WAL, not the +main file. The handoff's "back up the WAL too" is right, and there is a sharper +corollary for restore: **deleting any existing `-wal`/`-shm` before putting a +snapshot back is mandatory**, or SQLite replays the old WAL onto the new file. +Version-history restore for Rekordbox must be a *set* operation, never a +single-file copy. This cost real time in the spike: an early experiment reported +a clean diff that was an artefact of a stale WAL. + +**A clean Rekordbox quit leaves no WAL.** `master.db-wal`/`-shm` exist only while +Rekordbox (or another writer) holds the DB open; on a clean quit it checkpoints +and removes them. So §3.3's "back up `master.db` *and* its `-wal`/`-shm`" is +conditional: copy them **if present**, and treat their presence on open as a +signal that something else has the library open. Konduktor's own writer must +checkpoint (`PRAGMA wal_checkpoint(TRUNCATE)`) before anything copies or +snapshots the file, or the snapshot is stale. + +**`AnlzFile.keys()` / `len()` infinitely recurse** in 0.4.4 (`__len__` → +`keys()` → `__len__`). Use `file.tags`, `get_tag()` and `getall_tags()`; never +treat an `AnlzFile` as a Mapping. + +### 8.6 Dependency posture + +`pyrekordbox` 0.4.4 and `sqlcipher3` both install cleanly on Python 3.14 from +prebuilt wheels — no Rust or OpenSSL source build — so they satisfy the +constraint in CLAUDE.md's Conventions. The SQLCipher key is embedded obfuscated +in `pyrekordbox` (`db6/database.py`, `deobfuscate(BLOB)`); no key download or +extraction step is needed. + +### 8.7 Capability table, revised against the real library + +Replaces the "expected" column in §3.2. Still to be confirmed per item where +marked. + +| Field | Value | Evidence | +|---|---|---| +| `cues.hotcue_slots` | 8 | INFERRED (RB convention; not exercised — this library has no full bank) | +| `cues.slot_labels` | `'letter'` | INFERRED | +| `cues.memory_cues` | `true` | VERIFIED (`djmdCue.Kind` distinguishes them) | +| `cues.types` | `['cue','loop']` | VERIFIED (a loop row carries `OutMsec` + `BeatLoopSize`) | +| `cues.color` | `'palette'` (probable) | UNRESOLVED: `djmdCue` has `Color` + `ColorTableIndex`, but the `djmdColor` table (8 rows: Pink/Red/Orange/Yellow/Green/Aqua/Blue/Purple) is the **track**-colour palette, not necessarily the cue one. Settle by colouring a cue in Rekordbox and diffing. | +| `cues.named` | `true` | VERIFIED (`djmdCue.Comment`, e.g. `"1.1Bars"`) | +| `grid.flexible` | `true` | VERIFIED (per-beat BPM in `PQTZ` can vary) | +| `grid.lockable` | ? | UNRESOLVED — no obvious lock column found; check `djmdContent` flags | +| `save.overwrite_risk` | `'while_running'` | as planned | +| `save.library_label` | `'master.db'` | | +| `save.history` | **`false` initially** | The artefact set is `master.db` + N ANLZ files + `masterPlaylists6.xml`; `history.py` is single-blob. See §4. | + +**UNRESOLVED — the `djmdCue.Kind` encoding.** Observed: `Kind=1` ×20 (one per +analysed track, near t=0, comment `"1.1Bars"` — Rekordbox's auto-placed cue), +plus `Kind=2`, `Kind=3` and `Kind=5` (the loop) on the one hand-prepped track. +The ANLZ tags could not disambiguate because they are empty. Resolve by setting a +known hot cue A–H and a known memory cue in Rekordbox and re-reading the table — +a five-minute experiment that needs the app. + +### 8.8 Recommended next steps + +1. ~~Ask Ben the scope question: cloud-synced libraries.~~ **DECIDED 2026-09-17: + detect and refuse.** If the library is cloud-synced, Konduktor opens it + read-only and does not write. Detection: `usn` non-NULL on any row, or a + populated `djmdCloudProperty` / `cloudAgentRegistry`. This needs a capability + answer the UI can gate on — the existing `save` capabilities have no + "readable but not writable" state, so either add one or report every + `editable_fields`/grid/cue capability as empty. Prefer an explicit flag: a + silently uneditable library looks like a bug. +2. **The one experiment this spike could not run**: make a Konduktor-shaped write + to a *copy* of `master.db`, put it in place, launch Rekordbox, and observe + whether it accepts the rows, rewrites them, or complains. This needs Ben's + go-ahead because it means pointing the real app at a modified library. It also + resolves the `Kind` encoding above in the same session. +3. **Re-scope step 4 before building.** The adapter is metadata + playlists + (straightforward, `pyrekordbox` does the work) *plus* a hand-written cue store + (two tables kept consistent) *plus* an ANLZ beatgrid store (per-beat ⇄ marker + projection). Consider landing them as three separately-green milestones rather + than one adapter. + +### 8.9 Rekordbox mutates the library just by starting up + +**VERIFIED.** Launching Rekordbox 7 and doing nothing advanced the global USN by +five (1489 → 1494) and changed, with no user edit at all: + +- `agentRegistry.agentCredentials` — the auth token, `str_1`/`str_2`/`text_1` and + its date, **rotated on launch**; +- `agentRegistry.notificationNextFetch` / `notificationFetchedUID` / + `LangPath` / `SyncSettingsRootPath` / `unrecoverableAuth` — timers and timestamps; +- three `djmdSampler` rows restamped (`rb_local_usn` 104→1490, 105→1492, 106→1494). + +Two consequences: + +1. **The "no-op changes nothing" invariant is only assertable across Konduktor's + own open/save cycle against a static file** — which is how §8.1 verified it. + `test_rekordbox_fidelity.py` must work on a temp copy and must not try to + assert quiescence across a Rekordbox app session. Worth stating in the test's + docstring, because the natural reading of "a no-op save changes nothing" will + otherwise look false the moment anyone launches the app. +2. **A whole-file restore of `master.db` rolls back more than library data.** It + would revert the auth token, notification state and sampler rows to whatever + they were at snapshot time. Traktor's `collection.nml` has no equivalent — + restoring it is harmless. This is an independent argument for + `capabilities.save.history = false` on Rekordbox at first, and for any later + history support being a *selective* restore rather than a file swap. + +### 8.10 Acceptance test: Rekordbox accepts Konduktor's writes — VERIFIED + +The §8.8 experiment has now been run, on the real library (full backup taken +first). A `master.db` carrying exactly one Konduktor-shaped edit — `djmdContent` +Title + `rb_local_usn` 843→1490, and `agentRegistry.localUpdateCount` 1489→1490, +committed through `pyrekordbox` — was installed and Rekordbox 7 was launched +against it. + +**Result: accepted, cleanly.** + +- Rekordbox **displayed the edited title** (`Demo Track 1 [KONDUKTOR WROTE + THIS]`). No warning, no error, no database-repair prompt, no re-analysis. +- It **left the edited row untouched**: `rb_local_usn` was still exactly 1490 + afterwards. Rekordbox did not restamp, revert or re-derive it. +- Crucially, it **continued the sequence from Konduktor's value instead of + resetting it**: startup housekeeping took `localUpdateCount` 1490 → 1495, + handing 1491/1493/1495 to the `djmdSampler` rows it always touches (§8.9). +- The only other differences were that same launch housekeeping — auth-token + rotation, notification timers, sampler restamps. Nothing related to the edit. + +So the USN protocol `pyrekordbox` implements is the one Rekordbox actually +expects, and a third-party write that maintains it is indistinguishable to +Rekordbox from its own. **This removes the last blocker on the local write path.** + +Scope of the claim: one library, one field, one table, local-only (not cloud +synced), Rekordbox 7 on macOS. It does not license writing *any* row — the cue +and beatgrid paths (§8.2, §8.4) are still unexercised and carry their own risks. +But the premise the whole step was gated on — "writing rows without maintaining +the sync columns may corrupt Rekordbox's sync state" — is answered: maintain them +via `commit()` and Rekordbox is content. + +**Still unresolved: the `djmdCue.Kind` encoding** (§8.7). The cue half of the +experiment was not performed; `Demo Track 2` still has zero cues. It needs +someone to set a hot cue in slot A, a hot cue in slot C (skipping B, to separate +slot-letter from sequence), a memory cue, and a distinctive colour on one of +them, in Rekordbox — then diff `djmdCue`. + +### 8.11 The cue encoding, resolved + +Settled by setting known cues in Rekordbox on a previously cue-free track +(`Demo Track 2`, 120.00 BPM) and reading back `djmdCue`. **VERIFIED** unless noted. + +**`Kind` is the cue's bank slot, and `0` means "memory cue".** + +| Observed | `Kind` | `OutMsec` | `ColorTableIndex` | +|---|---|---|---| +| hot cue **A** @ 25 ms | `1` | `-1` | 22 | +| hot cue **C** @ 62.5 s | `3` | `-1` | 62 | +| memory cue @ 78.0 s | `0` | `-1` | — | +| memory cue @ 25 ms | `0` | `-1` | — | +| hot cue **F**, 4-beat loop @ 120.0 s | `7` | `122026` | 0 | + +So `Kind = 0` → memory cue (unslotted, unlimited), `Kind = N ≥ 1` → hot cue in +slot N. A→1 and C→3 confirm a 1-based letter index directly. + +**CAVEAT — the slot→letter mapping is NOT a plain letter index.** The 4-beat loop +sits on pad **F**, the 6th of the eight pads (confirmed from a screenshot of the +deck: A/C/F lit, F sixth), yet it stored `Kind = 7`. So the observed mapping is +A→1, C→3, **F→7**, which no linear rule fits. The other track in the library +(`Motorola`) has `Kind` 2, 3 and 5, but which pads those were set on was never +observed, so it cannot arbitrate. + +Both loops in the library sit at a `Kind` one above the next-lowest used slot, +which hints the anomaly may be loop-related — but that is one sample and a guess. + +**Do not infer the mapping; measure it.** Set a cue on *all eight* pads A–H of a +fresh track and read the eight `Kind` values in one go. Two minutes, and it +yields the complete table with no inference. Until then the adapter should treat +`Kind` as an **opaque slot id** — store it, round-trip it, address cues by it — +and only the presentation layer needs the letter, which is precisely what +`cues.slot_labels = 'letter'` is for. Nothing else in this section depends on +the answer. + +**A loop is an ordinary cue row with an out-point.** There is no separate loop +bank: `OutMsec` becomes the loop end and `BeatLoopSize` carries the musical +length. So `capabilities.cues.loops = 'cue_type'` (as Traktor), **not** +`'separate_bank'`. A loop can occupy a hot cue slot (`Kind=7` above) or be a +memory cue. + +**`BeatLoopSize = (beats << 16) | 1`** — VERIFIED against two loops at different +tempos, each agreeing with the measured millisecond span: + +| Track | BPM | `OutMsec - InMsec` | `BeatLoopSize` | hex | beats | +|---|---|---|---|---|---| +| Motorola | 125.00 | 480 ms | 65537 | `0x10001` | 1 | +| Demo Track 2 | 120.00 | 2000 ms | 262145 | `0x40001` | 4 | + +The adapter must write both `OutMsec` and a consistent `BeatLoopSize`; deriving +one without the other will produce a loop Rekordbox renders inconsistently. + +**Cue colour is a PALETTE index, and not `djmdColor`.** This closes the §8.7 +question. The user-set colours came back as `ColorTableIndex` 22 and 62, with +`Color = -1`; Rekordbox's own auto-placed cues use `Color = 255, +ColorTableIndex = 0`. Index 62 is far beyond `djmdColor`'s 8 rows, so the cue +palette is a larger built-in table — `djmdColor` is the *track* colour palette +and is unrelated. Set `capabilities.cues.color = 'palette'` and populate +`palette` from the built-in table once its values are known (reading them out of +the Rekordbox app resources, or by sampling each swatch as above). `Color = -1` +appears to mean "no explicit colour". + +**Field-level notes for the writer.** `InFrame` is set alongside `InMsec` +(frames at 150 fps: 62526 ms → 9378) and `OutFrame` alongside `OutMsec`; both are +populated by Rekordbox and should be written consistently. `ID` is a random +32-bit integer as a string, `UUID` a fresh uuid4, and `ContentUUID` copies the +track's `contentCue.UUID`. `ActiveLoop`, `CueMicrosec` and `Comment` are `0`/`""` +on user cues; `Comment` carries Rekordbox's own label on auto cues (`"1.1Bars"`). + +**The `contentCue` mirror is maintained in lockstep** (§8.2): after the edits it +read `rb_cue_count = 5` with a 1964-byte JSON array holding all five records, +including their `created_at`/`updated_at`. Its `rb_local_usn` was stamped (1527) +while **every `djmdCue` row's stayed NULL** — confirming §8.2's finding that +`contentCue` is the sync unit and the individual cue rows are not. + +--- + +## 9. Milestone 1 landed: the read-only Rekordbox adapter + +`backend/konduktor/adapters/rekordbox/` now opens, projects and serves a real +Rekordbox library through the generic layer. `./run_tests.sh` is green at **217 +assertions** (was 146). Nothing about the Traktor path changed. + +**What works**: `can_open` probe (decrypts one page, looks for `djmdContent`; +rejects a plain SQLite `.db`), default-location discovery via `pyrekordbox`'s own +config, the full read projection (tracks, cues, beatgrid, playlist tree, query / +facets / stats), `audio_path` with path remapping, and capabilities. Verified end +to end through the HTTP API: `/api/capabilities`, `/api/tracks`, +`/api/tracks/cues`, `/api/playlists`, `/api/stats` all serve Rekordbox data, and +`PATCH /api/tracks` returns a clean 422. + +**What it deliberately does not do**: every one of the 21 mutating commands +raises `Unsupported`. The capability system is the mechanism (nothing is +advertised as editable); the raise is the backstop. + +### Decisions made while building it, which the write path inherits + +- **`Kind` stays an opaque slot id** all the way through. §8.11's anomaly (pad 6 + → `Kind` 7) therefore blocks nothing; only a UI label needs the mapping. +- **`grid_marker_count` is an approximation, corrected on read.** Reading every + ANLZ at open costs ~12 s on a full-size library, so the projection reports 1 + for any track with a BPM and `track_cues()` writes the true count back. BPM — + not the presence of an analysis file — is the signal: Rekordbox analyses + one-shot samples too and gives them an ANLZ with no grid. On the reference + library the two sets agree exactly (22 tracks, both). +- **Internal Rekordbox playlists are hidden** (`SPECIAL_PLAYLIST_IDS`: "CUE + Analysis Playlist", "Cloud Library Sync"). They are not the user's. +- **Cue colour is projected as `None`, not guessed.** `ColorTableIndex` is an + index into a built-in palette whose values are not yet known, and inventing an + RGB value would be worse than admitting the gap. `capabilities.cues.color` is + already `"palette"` so the UI knows not to offer a free picker. +- **`snapshot()` and `restore()` raise.** A Rekordbox library is + `master.db` + N ANLZ files + `masterPlaylists6.xml`, and restoring the database + alone would also roll back Rekordbox's auth token and sampler state (§8.9). + `capabilities.save.history` is `False` to match. + +### Two fixes that were not strictly in scope + +- **`main.py` no longer imports Traktor's `describe`.** The picker's "last + opened" shortcut ran every path through `adapters.traktor.discovery.describe` + regardless of platform — a layering leak `test_layering.py` could not see, + because it only guards `core/`. There is now a generic `registry.describe()` + that delegates to whichever driver recognises the path and falls back to a + plain `exists: false` record for a library that has since moved. +- **`test_layering.py` now guards every adapter**, not just `core/`: no adapter + may import another platform's library. It checks real imports via AST rather + than text, because the first (text-matching) version failed on docstrings that + merely *mention* the other platform. + +### Next, in order + +1. **Milestone 2 — metadata + playlist writes.** This is the part `pyrekordbox` + actually implements and §8.1/§8.10 verified: commit through it, USNs are + maintained, Rekordbox accepts the result. Needs `test_rekordbox_fidelity.py` + (the row-level dump/diff harness — a working prototype exists in the session + scratch dir and is described in §8.1), plus the cloud-sync refusal wired to a + real capability rather than only to `Unsupported`. +2. **The capability system needs a "readable but not writable" state.** Right now + read-only is expressed by reporting every individual capability as false, + which is indistinguishable from "this platform has no such feature" and will + read as a bug to a user. Add an explicit flag before milestone 2, not after. +3. **Milestone 3 — the cue store and the ANLZ grid store.** Both hand-written; + see §8.2 and §8.4. `beatgrid.beats_from_markers()` is already written and + unit-tested as the inverse of the read projection, so the grid write has a + starting point. + +--- + +## 10. The read-only capability landed + +`Capabilities` now carries **`writable: bool`** and **`readonly_cause`** +(`platform_incomplete` | `cloud_synced`), backend and frontend in the same +change. `./run_tests.sh` is green at **225 assertions**; `npm run build` and +`npm run test` (25) pass. + +This was §9's prerequisite, and building it surfaced that the gap was bigger than +"the UI lacks a label": + +**Almost nothing gated on editability.** `capabilities.tracks.editable_fields` +and `grid.editable` were modelled but consulted by **no component at all** — only +`hotcue_slots`, `cues.types` and `rating_max` were ever read. So on a Rekordbox +library the UI would have cheerfully offered Edit Tags, inline editing, +click-to-rate, playlist create/rename/delete and every prep-deck control, each +one 422-ing at the adapter. The adapter's `Unsupported` was doing all the work, +as a backstop for a UI that never gated. + +Now gated on `writable`: `SaveBar` (replaces the save button with the reason), +`App`'s `onEditField` (inline edit + rating go inert), the "Edit Tags…" context +item, `Sidebar`'s new-playlist button, and all 12 `PrepStrip` edit handlers — +which report the reason instead of firing the request. The deck stays fully +usable for listening, with a "Read-only" badge, because that is most of its value +on a library you cannot write. + +**Two latent bugs fixed in passing**, both only reachable once a second platform +existed: +- The sidebar's **delete** button was gated on `can_rename`, not `can_delete`, so + a platform allowing one but not the other would offer both. +- The playlist **track-count badge** was inside that same block, so a read-only + library would have shown no counts at all — information hidden as though it + were an action. + +**Verified end to end**, not just in tests: opening a Rekordbox library reports +`writable: false, readonly_cause: platform_incomplete` over HTTP, and switching +to the Traktor collection at runtime flips it to `writable: true, cause: null` +with 11 editable fields. + +**The cloud-synced branch is tested for real**, not asserted: the test forges a +server-issued `usn` on a throwaway copy, confirms detection flips to +`cloud_synced`, and confirms the refusal names Rekordbox Cloud rather than the +milestone. That is the one failure mode version history cannot undo, so it is +worth the setup. + +Also corrected: CLAUDE.md documented the runtime open route as +`POST /api/collection/open`; it is `POST /api/library/open`. + +### Note for whoever does milestone 2 + +When Rekordbox writes land, `writable` flips to true for a *local* library while +staying false for a cloud-synced one — the two causes already distinguish that, +and `RekordboxAdapter._readonly_reason()` already words both. The per-feature +flags (`editable_fields`, `grid.editable`, …) then become the finer gate, and +they will need components to actually read them: **this change did not retrofit +per-feature gating**, it added the library-level gate that was missing. A +platform that is writable but cannot, say, edit a beatgrid would still offer the +control today. + +--- + +## 11. Milestone 2: metadata + playlist writes + +**Scope decision (Ben, 2026-09-18): shipping Rekordbox writes with NO undo is +accepted.** `capabilities.save.history` stays `False` — a Rekordbox library is +`master.db` + ~200 ANLZ files + `masterPlaylists6.xml`, and restoring the +database alone would roll back Rekordbox's auth token and sampler state (§8.9). +Rekordbox's own `master.backup.db` is the only safety net. Revisit only if Ben +asks; do not silently add a half-backup. + +What turns on here: **track metadata and playlists**. Cues and the beatgrid stay +read-only until milestone 3 (§8.2, §8.4 — both are hand-written write paths). + +### Milestone 2 landed + +`./run_tests.sh` green at **258 assertions**; `npm run build` + 25 vitest pass. +Rekordbox now accepts **track metadata and playlist** edits. Cues and the +beatgrid still refuse, and now say so through `cues.editable` / `grid.editable` +rather than through the library-level flag. + +**Per-feature gating came first, deliberately.** §10 warned that flipping +`writable` would re-expose every prep control, because `caps.writable` was the +only gate in the app. So `cues.editable` was added to `CueCapabilities` +(symmetric with `grid.editable`), the 12 PrepStrip handlers were split onto +`refuseCueEdit` / `refuseGridEdit`, and the tables now gate **per field** via a +`editableFields` set in the table meta — `InlineEdit` takes a `readOnly` prop and +`RatingStars` simply loses its `onChange`. Without that, milestone 2 would have +shipped a regression. + +**Three real bugs found by building it:** + +1. **Foreign-key edits projected as no-ops.** `artist`/`album`/`genre`/`label`/ + `remixer` are FKs into lookup tables. Setting the id does not move + SQLAlchemy's cached relationship, so re-projecting immediately read the OLD + name back — the API returned `genre: null` for an edit that had in fact + worked. Fixed with a flush + expire; pinned by a test that sets both a brand + new lookup value and an existing one. +2. **`close()` did not release the file.** `pyrekordbox`'s `close()` only closes + the session; the pooled connection keeps the OS handle, so `master.db` could + not be replaced. Now disposes the engine. This surfaced as a `disk I/O error` + in the fidelity test and would have surfaced in production as a failed + restore or a locked library. +3. **Nothing ever closed the previous library.** `AppState.open()` replaced the + adapter without closing it, leaking a handle per library switch. It now closes + the old one *after* the new one parses, so a failed open leaves the current + library intact. + +**`SaveOutcome` was promoted to `core/adapter.py`** under the two-platform rule, +with `snapshot` now optional — Rekordbox has no single blob that IS the library. +`AppState.save()` gates version history on `capabilities.save.history` instead of +assuming every platform is versioned. + +Also corrected in CLAUDE.md: the cue routes are `/api/tracks/cue`, not +`/api/tracks/hotcue`. + +### What milestone 3 inherits + +- `cues.editable` / `grid.editable` are the flags to flip, and the UI already + gates on them — no frontend work should be needed beyond flipping them. +- `beatgrid.beats_from_markers()` is written and unit-tested as the inverse of + the read projection. +- The cue write must maintain **both** `djmdCue` rows and the `contentCue` JSON + mirror + `rb_cue_count` (§8.2), and should decide deliberately whether to stamp + `rb_local_usn` on `djmdCue` rows — Rekordbox itself leaves them NULL. +- `test_rekordbox_fidelity.py` is the harness to extend: add a cue edit and a + grid edit as phases F and G, asserting the same "exactly these rows" property. + +### Milestone 3a landed: hot cue writes + +`./run_tests.sh` green at **288 assertions**. `cues.editable` is now true; +`grid.editable` is still false. + +Every native field convention was read off the real library before writing any +of it, and all of them are asserted in `test_rekordbox_fidelity.py` phase F: + +| Field | Value Konduktor writes | Evidence | +|---|---|---| +| `InFrame` / `OutFrame` | `floor(msec × 150 / 1000)` | matches every row in the library | +| `ContentUUID` | the **track's** UUID | verified == `djmdContent.UUID` | +| `contentCue.ID` | the **track's** UUID too | same | +| uncoloured cue | `Color=-1, ColorTableIndex=NULL` | how Rekordbox wrote Ben's uncoloured hot cues | +| loop | `Color=255, ColorTableIndex=0, ActiveLoop=0, CueMicrosec=0` | how Rekordbox wrote both loops | +| `BeatLoopSize` | `(beats << 16) \| 1`, beats from the track's own tempo | §8.11, verified at two tempos | + +Fidelity phases F and G assert that a cue write touches **only** `djmdCue`, +`contentCue` and `agentRegistry` — never `djmdContent` — that the mirror holds +one record per live cue row with `rb_cue_count` agreeing, and that a delete +clears both. + +**Memory cues are refused**, not because they are hard but because of the +two-platform promotion rule: Rekordbox is the only platform that has them, so +they are projected and displayed and never written. `role="memory"` raises +`Unsupported` with that explanation. + +### Milestone 3b: the beatgrid — read this before starting + +`pyrekordbox`'s ANLZ tags **cannot change the number of beats**. `PQTZAnlzTag`'s +`set()`, `set_beats()`, `set_bpms()` and `set_times()` all raise unless the new +sequence is exactly as long as the existing one ("For now only values of existing +beats can be set"). Since a tempo change alters how many beats fit in a track, +every real grid edit changes that count. + +So a grid write means manipulating `tag.content.entries` (a `construct` +ListContainer) directly, setting `content.entry_count`, and calling the tag's +`update_len()` — which exists for exactly this and recomputes +`len_tag = len_header + 8 × entries`. `check_parse()` asserts the count and the +list agree, so it is worth calling after. + +Two further things that make this the riskiest piece so far: +- the grid lives in **two files** — `PQTZ` in `.DAT` and `PQT2` in `.EXT` — which + presumably must stay consistent; and `djmdContent.BPM` (tempo ×100) is a third + copy that Rekordbox shows in the library list. +- `.DAT`/`.EXT` round-trip byte-identically today (§8.3), which is the property + that makes a grid write verifiable at all. **Re-check it after any write**: if + a rebuilt file stops being byte-identical in the regions we did not touch, the + write is corrupting something. + +`beatgrid.beats_from_markers()` is already written and unit-tested as the exact +inverse of the read projection, so the marker→beat maths is not the hard part. + +### Milestone 3a verification: point cues confirmed, LOOP WRITES DISABLED + +The staged acceptance test was run in Rekordbox 7. Two results, one good and one +that changed the plan. + +**Good: Rekordbox accepted the cue rows verbatim.** A re-read after the session +showed both rows byte-for-byte as Konduktor wrote them — same `Kind`, same +`BeatLoopSize`, same USN stamps. No repair, no renumbering. The write mechanism +and the `contentCue` mirror are sound, and a point cue written with `Kind=2` +landed on **pad B** exactly as predicted. + +**Bad: a cue row carrying `OutMsec` does not land in the slot its `Kind` names.** +Written with `Kind=4` plus an out-point, it appeared as a **memory cue** with pad +D left empty (confirmed from a screenshot of the deck — only B lit). The loop's +*length* was right (4 beats), so `BeatLoopSize` is correct; only its placement is +wrong. Rekordbox's own 4-beat loop on pad F — the 6th pad — stores `Kind=7`, so +loops evidently use a slot encoding that has not been measured. + +**So loop writing is now refused** (`WRITABLE_CUE_TYPES = ["cue"]`, and +`capabilities.cues.types` reports only `cue`). Loops are still READ and projected +with their length — losing them from the projection would be worse than being +unable to edit them. Writing one anyway would have silently created a memory cue, +which Konduktor deliberately cannot edit or delete, on a platform with no version +history. + +**To finish loops, measure the encoding**: in Rekordbox, put a 4-beat loop on pad +**D** and another on pad **E** of any track, quit, and read the `Kind` values — +two points on known pads, plus Rekordbox-authored loop rows to diff field by +field against Konduktor's. Until then this is the one gap in cue support. + +### Found while verifying: pyrekordbox refuses to commit while Rekordbox runs + +`pyrekordbox.commit()` raises `RuntimeError` outright when it detects a Rekordbox +process. That contradicts the settled decision to **warn but proceed** (§6), and +the check is **process-wide rather than per-file** — so it refuses to write a +temp copy while the user has an entirely different library open, which made the +whole test suite fail purely because Rekordbox happened to be running. + +`RekordboxStore._commit()` now suppresses that veto for the duration of the call +and logs a warning instead, so everything else `commit()` does — the USN +auto-increment and keeping `masterPlaylists6.xml`'s timestamps in step — still +runs as the library intends. `store.app_running` exposes the detection for +warning the user rather than blocking them. A test pins the behaviour by faking +a running process. + +### Milestone 3b progress: the grid can be written, but only half of it + +**The mechanical problem is solved.** `beatgrid.write_pqtz()` rebuilds a `.DAT`'s +`PQTZ` entry list from scratch — including changing the number of beats, which +`pyrekordbox`'s own setters refuse — by replacing `content.entries`, setting +`entry_count`, and calling the tag's `update_len()`. Verified on a real file: +resizing 374 → 367 beats produced exactly the expected byte-size delta, re-parsed +correctly, and left **every other tag byte-identical**. + +**The blocker is `.EXT`.** The grid exists twice: `PQTZ` in `.DAT` and the +"extended" `PQT2` in `.EXT`. `PQT2` carries a 2-byte-per-beat array whose second +byte `pyrekordbox` literally names `unkown`, plus an undecoded `u3` field. +Inspection did not crack it: the value drifts ~2.75 per beat with a jump at each +bar boundary and must wrap within 8 bits, so it is neither a time nor a simple +index. Writing guesses into it would corrupt real user data on a platform with no +version history, so **`PQT2` is left untouched**. + +That leaves one empirical question, and it decides the whole feature: + +> **Does Rekordbox read the grid from `PQTZ` (`.DAT`) or from `PQT2` (`.EXT`)?** + +A test is staged: Demo Track 1's `PQTZ` rewritten to **half-time (64 BPM, 184 +beats)**, `.EXT` and `master.db` untouched, installed as a single-file copy. +Half-time is chosen because it is unmistakable — beat markers at half density and +a 64 BPM readout — rather than a subtle shift someone has to judge. + +- **If Rekordbox shows the half-time grid**: `PQTZ` is authoritative, and grid + editing is feasible. `PQT2` may still need attention for CDJ export, which is + out of scope anyway. +- **If it shows the original 128 BPM grid**: `PQT2` wins, and grid editing stays + out of reach until someone decodes it. That is a legitimate result — Rekordbox + support would ship as library management + cues, with grid editing remaining a + Traktor feature. + +Note `djmdContent.BPM` is deliberately left at 128 in this test, so the library +list and the deck disagreeing is itself a signal about which copy is read where. + +### Milestone 3b landed: the beatgrid writes + +**`PQTZ` is authoritative — verified in Rekordbox 7.** The staged half-time test +showed the deck at 64 BPM with the grid correctly half-timed. Afterwards the +`.DAT` was byte-identical to what Konduktor wrote, `.EXT` and `.2EX` were +untouched, and Rekordbox did **not** reconcile `djmdContent.BPM`, which sat at +128 while the deck showed 64. + +Three things follow, all now implemented: + +1. **Only `.DAT`'s `PQTZ` is written.** The stale extended grid in `.EXT` does + not trouble Rekordbox's own display; it would matter only for CDJ export, + which is out of scope. +2. **`djmdContent.BPM` is Konduktor's to maintain**, mirroring the first marker — + the same relationship Traktor's `` has to its first grid marker. + Without it the library list and the deck disagree. +3. **Grid edits are buffered until `save()`.** ANLZ edits are file writes, so + applying them at command time would put an unsaved edit on disk and break the + save contract every other platform obeys. `save()` writes the files first and + commits the database second, so a failed file write leaves nothing committed. + +The full marker vocabulary works — add / move (clamped between neighbours) / +retempo / delete / replace / delete-grid — including genuinely **flexible +multi-tempo grids**, end to end through the HTTP API. + +Fidelity phase H is the safety net: an unsaved grid edit does not touch the file; +`.EXT`/`.2EX` stay byte-identical; **every tag in the rewritten `.DAT` except +`PQTZ` is byte-identical**; and in the database only `BPM` + the row USN + the +counter move. Suite: **316 assertions**. + +### Remaining Rekordbox gaps + +- **Saved loops** — read but not written (§ above). Needs the slot encoding + measured: a 4-beat loop on pads D and E, then read the `Kind` values. +- ~~A Konduktor-written FLEXIBLE grid has not been seen in Rekordbox.~~ + **VERIFIED 2026-09-19**: Demo Track 1 written as 128 BPM dropping to 90 at + 1:00 displayed exactly that in Rekordbox 7 — the deck's BPM readout followed + the tempo change at the marker. Multi-marker grids are confirmed end to end, + which is the last thing milestone 3 was waiting on. +- **Cover art** — never investigated; `tracks.artwork` is false. +- **`PQT2` is undecoded**, so the extended grid drifts out of step with `PQTZ` + after any Konduktor grid edit. Harmless for Rekordbox itself; would need + solving before any CDJ/USB export (currently rejected as out of scope). + +### The hot cue slot encoding, measured — and it was never about loops + +`djmdCue.Kind` is 1-based **and skips 4**. Established by writing a 4-beat loop +at every `Kind` from 1 to 8, ten seconds apart, and reading the pads off a real +deck: + +| `Kind` | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | +|---|---|---|---|---|---|---|---|---|---| +| pad | A | B | C | **—** | D | E | F | G | H | + +A cue at `Kind=4` occupies no pad at all; Rekordbox displays it as a memory cue. + +That single gap explains everything that had been confusing: + +- Ben's Rekordbox-authored loop on pad **F** stored `Kind=7` — correct, not an + anomaly; +- a Konduktor cue written at `Kind=4` "turned into a memory cue" — it *was* one; +- pad H stayed empty in the probe because H is `Kind=9`, and the probe stopped + at 8. + +**Loops were never the problem.** They had been disabled on the theory that an +out-point changed the slot encoding; in fact the adapter's `slot -> Kind` map was +simply wrong from pad D upward, for *every* cue type. Loops write fine now, and +`cue_types.WRITABLE_CUE_TYPES` is back to `["cue", "loop"]`. **Confirmed in +Rekordbox**: looped hot cues set in Konduktor save and display correctly. + +The lesson is the project's own standing one, and it cost two rounds of wrong +theory: the mapping was *inferred* from three incidental data points before +anyone thought to *measure* it across the whole range. One probe settled it. + +Tests now pin the exact `Kind` sequence and assert that all eight pads are +individually addressable, so a regression fails loudly instead of quietly moving +someone's cues. + +### Remaining Rekordbox gap + +Only **cover art**, which has never been investigated (`tracks.artwork` is +false; `djmdContent.ImagePath` plus separate artwork files). `PQT2` also stays +undecoded, which only matters for CDJ export — out of scope. diff --git a/CLAUDE.md b/CLAUDE.md index 743f934..9d69ffe 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -16,53 +16,408 @@ given a mobile version. Two independent apps that talk over HTTP: -- **`backend/`** — Python + FastAPI. Parses `collection.nml` via - `traktor-nml-utils` and serves a query + edit API. Entry point: +- **`backend/`** — Python + FastAPI. Entry point: [backend/konduktor/main.py](backend/konduktor/main.py). - - `collection_service.py` — the **read** model: loads the NML, flattens ENTRYs - into `Track` objects, indexes them by primary key. All query logic - (filter/sort/facets/stats) lives here. `replace_track()` refreshes one - projection after an edit (bridges the read model and the edit store). - - `playlist_store.py` (`PlaylistStore`) — the **edit** model: owns the parsed - dataclass NML and applies all edits (playlists, track metadata, cover art, - AND track-prep edits: hotcues/cues, beatgrid/BPM, lock), then renders + - saves. See "Write path" below. - - `file_tags.py` — reads/writes embedded audio-file tags & cover art (mutagen) - and resolves Traktor `LOCATION`s to OS paths. Best-effort. - - `discovery.py` — finds Traktor collections in their default install location - (`~/Documents/Native Instruments/Traktor /collection.nml`) for the - picker's "Automatic" option; sorts newest Traktor version first. - - `prefs.py` — tiny persisted user-prefs store in `userprefs.json` (resolved - relative to the package so it travels with the app; gitignored). Holds the - last-opened collection path, the library column layout, and the prep deck's - main-waveform zoom (`mainZoomSec`). Best-effort I/O. - - `schemas.py` — Pydantic response/request models. - - `main.py` — FastAPI routes (all under `/api`). Holds an `AppState` with the - currently-loaded collection; it starts **unloaded** and the collection is - chosen at runtime via `POST /api/collection/open` (data routes 409 until - then). `GET /api/fs/list` powers the in-app file browser; - `GET /api/collection/options` feeds the picker's auto-detect + last-opened - shortcuts; `GET`/`PATCH /api/prefs` persist UI prefs. Setting `KONDUKTOR_NML` - auto-loads on startup (dev/tests). + + **Architecture: projection + command replay.** The generic model is a *read + projection*; edits are strictly-generic commands that a per-platform **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 the only model that works for formats you cannot + regenerate (a Rekordbox SQLite row, a Serato tag inside an audio file). Traktor + is currently the only adapter; see `.claude/discussions/` for the decision log. + + - `core/` — **platform-independent. Must not import `traktor_nml_utils` or + `konduktor.adapters`** (`test_layering.py` enforces this). This is the + contract a Rekordbox or Serato adapter will be written against. + - `model.py` — the generic model (`Track`, `CuePoint`, `GridMarker`, + `TrackCues`, `PlaylistNode`, `Facets`, `Stats`, …). Served straight to HTTP. + - `adapter.py` — the `LibraryAdapter` / `LibraryDriver` protocols and the + error tree (`NotFound` → 404, `InvalidCommand` → 400, `Unsupported` → 422), + mapped to status codes once in `main.py` rather than per route. + - `capabilities.py` — `Capabilities`: what the loaded library can persist, so + the UI can gate controls instead of branching on the platform. + - `query.py` (`TrackIndex`) — all query/filter/sort/facet/stats logic, over + generic `Track`s. Shared so "sort by artist" cannot mean different things + on different platforms behind one UI. + - `edit_journal.py` (`EditJournal`) — every edit this session at **field + resolution** (`track/set/genre`, `cue/add/slot:1`, `grid/marker-bpm/marker:0`). + Drives the file-tag sync, the version-history message, and `retarget()` + when a path remap changes track ids. Recording `before` keeps undo cheap later. + - `registry.py` — adapter selection by **`can_open()` probe**, not extension + (Rekordbox is a `.db`, Serato is a directory). + - `audio_tags.py`, `pathmap.py` — format-agnostic helpers. + - `structure.py` + `auto_hotcues.py` — **Auto Hotcues** (the deck's ✨ Auto + button → `AutoCueDialog` → `POST /api/tracks/cue/auto`). The user binds each + slot to an EVENT (`first_beat`, `intro_end`, `build_n`, `drop_n`, + `breakdown_n` for n ≤ 3, `outro`, `last_beat`) plus an offset in BEATS; + `structure.analyse` finds the events, `auto_hotcues.plan` resolves the + template and reports an outcome per slot (`placed` / `not_found` / + `out_of_range` / `occupied` / `protected` / `duplicate`) — "this track has + no third drop" is an answer, not a silent gap. **One cue per beat**: a slot + landing on a beat that already has a cue — one KEPT in the bank (the grid + cue, a hand-placed cue, within a quarter beat) or a new one in a lower + slot — is a `duplicate` of that slot. A replaced cue frees its beat only + if its replacement is placed, which is circular, so `plan` iterates to a + fixpoint. How it finds them: + - **Everything is per bar ON THE TRACK'S GRID**, bar 1 = the first marker + (Traktor's convention). Bar-1 detection from audio was tried: it never + beat that rule, because DJ tracks start on a downbeat. + - Per-bar kick / bass / loudness / brightness + MFCC, then an **exact DP + segmentation whose boundary price depends on bar position** (cheap on + ×8, dearer on ×4, very dear elsewhere) — the phrase bias lives in the + objective, not in a snap afterwards. + - **A drop is a high section entered from a low one**, not a loud one: a + house intro is often as loud as its drop. A breakdown is where a drop + ends when another drop follows; the end of the last one is the outro's. + - Kick is the grid detector's sharp low-band onset, NOT on- vs off-beat + energy (a house bassline lives on the off-beat), and "high" does not + require a kick (drum & bass has none on every beat). + Measured against the phrase analysis Rekordbox stores for 12 local + "High"-mood tracks (PSSI; the previous detector's cues scored below a cue + every 16 bars): drops 81% on the exact bar (22/27), breakdowns 80% + (12/15), outro 42% within 4 bars — `backend/bench_structure.py` reruns + it. Rekordbox's own "Up" spans the whole pre-drop groove where a DJ's + build is the last 8–16 bars, so build scores against it are not + meaningful. Halftime tracks inherit the grid's octave: at 174 a "bar" is + half a musical bar. + - `grid_detect.py` — **beatgrid detection** (the deck's Analyze button, + `POST /api/tracks/grid/auto`). Fits ONE constant tempo + anchor to the whole + track rather than tracking beats: `librosa.beat.beat_track`, which it + replaced, quantises tempo to 23 ms frames and can only return 117.45 / + 123.05 / 129.20 / 136.00 between 115 and 140 BPM. Timing comes from a + 1–8 kHz attack band, and which attack is the beat from whether a kick's + low end follows it — each band alone lost a real track to an off-beat hat + or a syncopated bassline. Positions are in the **decoded audio's** time + base (libsndfile = CoreAudio to the sample on MP3). **Rekordbox's grids sit + a constant ~25 ms later on lossy files** and at 0 on WAV — a platform + time-base difference, deliberately NOT corrected here; Traktor's is + unmeasured. `backend/bench_grid_detect.py` scores it against any library's + single-marker grids and reports that constant separately from detection + error (29 Rekordbox references: old 1/29 BPMs, new 27/29). + - `places.py` — where a person keeps things on THIS computer: the user's own + folders (via `platformdirs` — hardcoding is wrong on every OS differently: + `~/Videos` is `Movies` on macOS, Linux's are user-configurable localised + XDG dirs, and Windows Known Folders are routinely relocated by OneDrive) + and mounted volumes. The mount scanner lives here rather than in the + OneLibrary adapter, where it grew: "where does this OS mount things" is + not adapter knowledge, the file browser needs the same answer, and two + scanners would drift. `is_boot_volume()` compares **st_dev against `/`**, + not the name, because macOS lists the startup disk in `/Volumes` next to + real removable media and `Macintosh HD` is only its default name. + `is_os_housekeeping()` names what an OS writes into a folder by itself + (`.Spotlight-V100`, `.Trashes`, `._*`, `System Volume Information`, …), so + the export's "is this folder empty?" check does not refuse a stick's root + just because a Mac has mounted it once. `drives()` splits drives into + `local` (the boot disk at `/`, never its `/Volumes` alias, plus internal + drives per `diskutil`, cached per mount) and `external` — **anything + uncertain is external**, so a stick is never presented as a safe place to + reference tracks from; mounted `.dmg`s are dropped. `is_hidden()` reads + macOS's hidden FLAG (as Finder does), not a list of names. + - `folder.py` — **a folder of loose audio files read as a read-only + source** (`FolderSource`), for the sidebar's Files trees. NOT a + registered driver: `can_open("any directory")` would make every folder a + library to the picker. **This folder only** (the tree reaches + subfolders), **track id = absolute path**, tags read once per folder + mtime by `FolderScanner` — which is also the audio route's gatekeeper: + only a file a scan found is streamed, so `/api/folder/tracks/audio` cannot + read an arbitrary path. Tagged keys are deliberately dropped (every + notation there is). The listed suffixes are the collection's + `tracks.audio_formats` capability. + - `adapters/traktor/` — everything that knows NML exists. + - `store.py` (`TraktorStore`) — the retained native model: owns the parsed + dataclass NML, applies every edit, renders + saves. See "Write path". + - `adapter.py` (`TraktorAdapter`) — owns the store **and** the `TrackIndex` + built from it, so projection and native model cannot drift. Translates the + generic cue vocabulary to Traktor's integers (the only place that mapping + exists). **Every mutating command returns its refreshed projection** — a + forgotten refresh would be a silently stale UI no byte test would catch. + - `projection.py` — native → generic (`to_track`, `to_track_cues`). + - `driver.py`/`discovery.py` — `can_open`, default-location detection, restore. + - `beatgrid.py`, `locations.py`, `capabilities.py` — Traktor's grid/companion + rules, LOCATION ↔ OS path conversion, and its capability set. + - `adapters/rekordbox/` — **track metadata, playlists and hot cues writable; + the beatgrid still read-only** (milestones 2 and 3a). Also home to + `anlz_writer.py`, which BUILDS analysis files from nothing — Pioneer's format, + not one product's, so the OneLibrary exporter borrows it the same way it + already borrows `beatgrid`. + `master.db` is SQLCipher-encrypted SQLite, read via `pyrekordbox`. Every + mutating command raises `Unsupported` and `capabilities()` advertises nothing + as editable, so the UI never offers an edit. Three things differ from Traktor + and are the reason this adapter is not a copy of it: + - **The beatgrid is NOT in the database, and is written to ONE tag of ONE + file.** There is no grid table at all; it + lives in per-track ANLZ analysis files as a `PQTZ` tag listing EVERY BEAT. + `beatgrid.py` collapses those into the generic marker list on read and + expands them back on write. `write_pqtz()` rebuilds the entry list + directly — `pyrekordbox`'s own setters refuse to change the NUMBER of + beats, which every real edit does — then calls the tag's `update_len()`. + **Only `.DAT`'s `PQTZ` is written.** `.EXT` holds a second "extended" grid + (`PQT2`) whose per-beat byte `pyrekordbox` itself calls `unkown`, so + writing it would mean guessing at bytes in data with no version history. + Verified in Rekordbox 7: it reads the grid AND the deck's BPM from `PQTZ`, + leaves a Konduktor-written `.DAT` untouched, and is unbothered by the stale + `.EXT` (which would matter only for CDJ export — out of scope). It does + **not** reconcile `djmdContent.BPM`, so the adapter maintains that column + itself, mirroring the first marker exactly as Traktor's `` does. + Grid edits are **buffered until `save()`** so ANLZ file writes obey the same + "edit in memory, Save writes to disk" contract as everything else; `save()` + writes the files BEFORE committing the database, so a failed file write + leaves nothing committed. `store.anlz_grid()` parses them **lazily** — + ~1.4 ms each, i.e. ~12 s for a library of 8,500 if done at open — so + `Track.grid_marker_count` carries a documented approximation (1 when the + track has a BPM) that `track_cues()` corrects. + - **Cues live in two places** that must agree: `djmdCue` rows and a JSON + mirror in `contentCue.Cues` (+ `rb_cue_count`). Rekordbox stamps + `rb_local_usn` on `contentCue`, never on the cue rows. Every cue write ends + in `_sync_content_cue()`, which rebuilds the mirror from the rows — leaving + it stale is this platform's version of Traktor's companion-cue desync. + Field conventions are read off a real library, not guessed: + `InFrame`/`OutFrame` are the position in frames at **150 fps**, a cue's + `ContentUUID` and its mirror row's `ID` are both the **track's UUID**, an + uncoloured cue is `Color=-1, ColorTableIndex=NULL`, and a loop is + `Color=255, ColorTableIndex=0` with `BeatLoopSize = (beats << 16) | 1`. + **`Kind` is 1-based AND skips 4** — the bank is `1,2,3,5,6,7,8,9` for pads + A–H. Measured by writing a cue at every `Kind` 1–8 and reading the deck: a + cue at `Kind=4` lands on no pad and Rekordbox shows it as a memory cue. + Get this wrong and cues silently move to the wrong pad or vanish from the + bank. Point cues AND loops both write; `cue_types` owns the translation. + **Memory cues stay preserved-but-uneditable** (Rekordbox is the only + platform with them — the two-platform promotion rule). + - **Saving warns but does not block when Rekordbox is running.** + `pyrekordbox.commit()` refuses outright, and its check is process-wide + rather than per-file, so `RekordboxStore._commit()` suppresses that veto + and logs instead — otherwise a temp copy could not be written while the + user had a different library open. + - **`djmdCue.Kind` is an OPAQUE slot id**: 0 = memory cue, N = hot cue slot N. + Pads A and C store 1 and 3, but the 6th pad stored 7 — so the slot→letter + mapping is NOT a plain index and is deliberately left to the UI. + Writes are refused outright on a **cloud-synced** library (detected by a + server-issued `usn` on any row): a bad sync state would propagate to the + user's other machines, and there is no version history here to undo it. + Every command passes through `_require_writable()` so a command added later + cannot forget that check. + Edits accumulate in the SQLAlchemy session and `save()` commits — which maps + onto Konduktor's "edit in memory, Save writes to disk" model exactly, since + `pyrekordbox`'s `commit()` is what assigns Rekordbox's USNs. A real Rekordbox + 7 was verified to accept a library written this way, display the edit, leave + the row alone, and continue from the counter it was left at. + `artist`/`album`/`genre`/`label`/`remixer` are **foreign keys into lookup + tables**, so a write is find-or-create (pyrekordbox's `add_*` RAISES on an + existing name) followed by a **flush + expire** — without which the ORM + re-reads the stale relationship and a successful edit projects as a no-op. + `producer`/`mix` are absent from `editable_fields`: Rekordbox has no column + for them and its Composer is a different field. + `close()` disposes the SQLAlchemy engine, not just the session — otherwise + the OS file handle stays open and `master.db` cannot be replaced. `AppState` + closes the previous adapter when opening a new library. + - `adapters/onelibrary/` — **read-only.** The cross-vendor USB export format + (AlphaTheta + Algoriddim + Native Instruments), read by CDJ-class hardware. + Built as the source half of a future "import a stick into Traktor" feature. + Full research, incl. the schema, is in + [.claude/handoffs/onelibrary-adapter.md](.claude/handoffs/onelibrary-adapter.md); + the four things that make it unlike the Rekordbox adapter: + - **The library is a REMOVABLE DRIVE, not a file in a known place.** So + `discovery.py` scans mount points rather than probing fixed paths, and + `layout.py` owns the on-drive layout (`PIONEER/rekordbox/exportLibrary.db`, + analysis under `PIONEER/USBANLZ/P0/<8 hex>/`). Every stored path is + **drive-relative with a leading slash** — `/Contents/…/x.mp3` — which is + NOT an absolute host path: joining it naively discards the mount point and + silently yields `/Contents/…`, which looks like an empty drive rather than + a path bug. `DriveLayout.resolve()` is the only place that join happens. + A track's id is that drive-relative path, not `content_id`, which rekordbox + renumbers from 1 on every re-export. + - **Cues are NOT in the `cue` table**, which rekordbox exports empty; they are + in the ANLZ files. `PCOB` is **split by pad** (`.DAT` holds 1–3, `.EXT` holds + 4 and up — reading only the `.DAT` silently loses pads D–H), and `PCO2` in + the `.EXT` holds the complete set plus RGB colour and comments. `PCO2` wins, + `PCOB` is the fallback, both merge across files first. + - **The slot numbering differs from `master.db`.** `djmdCue.Kind` is a sparse + bank that skips 4; ANLZ `hot_cue` is a **dense 1-based index** (pad D is + `Kind` 5 but `hot_cue` 4), and 0 means memory cue. Measured by aligning the + same five cues in both representations. Reuse the Rekordbox mapping here and + every cue from pad D on lands one pad too far along. Times are **ms**, not + 150 fps frames; `loop_time` is `0xFFFFFFFF` (not 0) when there is no loop. + - **Analysis files are parsed lazily** — `.DAT` ~2 ms but `.EXT` ~23 ms, so + eager parsing would cost ~23 s on a 1,000-track drive. Cue and marker counts + are therefore approximate in the library table and corrected by + `track_cues()`. The `PQTZ` beatgrid is the same tag as Rekordbox's, and the + collapse rule is **shared by import** rather than copied — two definitions of + "when does a tempo change start a marker" would drift silently. + - `importer.py` also serves the folder add: `reference=True` adds each file + where it is (nothing to copy or roll back), and every planned file the + destination already points at (matched on `audio_path`, never the display + `filepath`) maps to its EXISTING id instead of being added again. + **`PrepStrip` takes `origin`** (`collection`/`device`/`folder`), recorded + with the deck's track in `App` — the deck follows its TRACK's library, not + the view's, so browsing elsewhere cannot point it at endpoints that do not + know the track. `trackAudioUrl`/`trackCuesFor` in `api.ts` are the one place + that choice is made. + - `app_state.py` — the one loaded library, and the **version-history commit**. + History is app-level: the adapter returns the bytes it wrote plus a summary, + and `AppState.save()` versions them. Every write path must go through it. + - `library_id.py` — a **stable identity for a library that survives it being + moved**. Everything else keys off the OS path (`history` hashes it, `prefs` + stores it), which is fine for things a user shrugs at losing and NOT fine for + export sets, which are curated work holding references into one library. Two + halves, only the first authoritative: a hidden `.konduktor-library.json` + **sidecar beside the library**, which moves with it, plus a disposable + `libraries.json` index in app-data. The id is **random** — deriving it from + the path defeats the point and from the contents would change on every save. + The sidecar is keyed **by filename**, because one folder can hold two + libraries and a single id per folder would hand both the same identity. + A **removable** library gets no sidecar (writing to a user's USB stick for + Konduktor's bookkeeping is not a trade worth making) and falls back to a + path-derived id that `is_durable()` reports honestly. Writing beside the + library is not a new intrusion — saves already create `backups/` there. + - `exports.py` — **export sets**: a named, persisted slice of the library bound + to a destination. Konduktor's OWN data, never written into the user's library + (a Traktor collection has nowhere to put it, and it would live in a file + Traktor rewrites). Three rules shape it: references are **LIVE** (a set + stores playlist *ids*, resolved at export time, so `resolve()` is computed on + every call and NEVER cached); a playlist is **removable only as a whole** + (a live reference plus per-track removal needs an exclusion list, i.e. hidden + state silently deciding what a future export contains); and it is **keyed by + `library_id`**, not path. `resolve()` dedupes across playlists and loose + tracks — one track, one file copy — and SURFACES what is gone rather than + dropping it, because a gig stick quietly missing four tracks is this + feature's worst failure. `retarget()` follows ids through a path remap, which + `/api/library/remap-paths` calls with a before/after snapshot. + - `prefs.py` — persisted user prefs (`userprefs.json` in the per-OS app-data + dir). Last-opened collection (global AND per-platform), library column + layout, prep-deck zoom, import destination. Best-effort. + - `schemas.py` — HTTP request bodies + envelopes; re-exports `core.model`. + - `main.py` — thin FastAPI routes (all under `/api`), talking only to the + adapter. Starts **unloaded**; the library is chosen at runtime via + `POST /api/library/open` (data routes 409 until then). + `GET /api/capabilities` feeds the UI's gating; `GET /api/fs/list` powers the + file browser; `GET`/`PATCH /api/prefs` persist UI prefs. Setting + `KONDUKTOR_NML` auto-loads on startup (dev/tests). + The picker's three routes are all **scoped by `?platform=`**, because it + asks which platform first: `/api/platforms` (the pre-load equivalent of + capabilities — reports `selects`, `removable` and `found`, sorted so a menu + does not reshuffle between launches), `/api/library/options` (that + platform's detections + its own last-opened) and `/api/fs/list` (that + platform's suffixes; a directory-selecting platform contributes none, so its + browse shows folders only) and `/api/fs/places` (the browser's sidebar — + the user's folders, then drives, plus that platform's own location when it + keeps one at a fixed path; a place that does not exist is **omitted, never + disabled**, since a greyed-out Music folder reads as breakage where its + absence reads as an accurate description of the machine). + `/api/library/open` checks `exists()`, **not + `is_file()`** — which shapes are valid is `can_open()`'s business, and a + OneLibrary library is a drive. `prefs` keeps last-opened **per platform**: + offering a Rekordbox `master.db` to someone who just chose Traktor is an + offer that cannot be taken. - **`frontend/`** — React + TypeScript + Vite. A dark, virtualized track explorer. Entry: [frontend/src/App.tsx](frontend/src/App.tsx). - - `api.ts` — typed client + all API types (keep in sync with backend - `schemas.py`). - - `components/` — `CollectionPicker` (startup chooser: Automatic / Open last / - Find manually — the last reveals a file browser), `Sidebar` (playlist tree + - create/rename/delete), `SaveBar`, `Toolbar` (search/filters + `ColumnsMenu`), - `TrackTable` (All Tracks — TanStack Table + **virtualized** grid; per-row play - button, configurable columns, inline double-click editing) and `PlaylistTable` - (playlists — same columns/cells/play/inline-edit via shared `HeaderRow`/ - `RowCells`/`PlayButton`, so the two views look identical, PLUS dnd-kit - drag-to-reorder + a remove button, header sorting disabled so the manual order - stands; `canReorder` is false while a filter/search is active so a partial order - can't overwrite the full entry list). `PlaylistTable` is non-virtualized - (playlists are small) and feeds `useReactTable` a **stable** empty `sorting` - array (`NO_SORTING`): a controlled `state.sorting` that's a fresh `[]` each - render with no `onSortingChange` makes TanStack Table re-sync its internal - state every commit → infinite re-render loop. Keep that reference stable. - `SelectionBar` (bulk add-to-playlist), `ContextMenu` + `EditTagsDialog` + - `api.ts` — typed client + all API types. **Generic, not Traktor-shaped**: + cue types are the strings `cue`/`fade_in`/`fade_out`/`load`/`loop`, a cue has + a `role` (`hotcue`/`memory`) and a nullable `slot`, and `editable` + + `readonly_reason` say whether the adapter will accept a command on it — gate + on `editable`, never on a platform-specific reason like `grid_marker`. Keep + in lockstep with `core/model.py`; land both in the same commit. + - `lib/capabilities.tsx` — `useCaps()` over `GET /api/capabilities`. The app + does not render until capabilities resolve, so no first frame can offer an + edit the adapter would reject. Containers call `useCaps()`; presentational + leaves take plain values as props. **No component branches on the platform.** + - `lib/platformCopy.ts` — composes user-facing wording from the *facts* the + adapter supplies (`app_name`, `library_label`, `overwrite_risk`), so + "Close Traktor before saving — it overwrites collection.nml on exit" stays + specific without being hard-coded. Never put finished sentences in the API. + - `components/` — `FileBrowser` (**the one file browser**: places rail + path + bar + listing, `mode: 'file' | 'directory'`. Deliberately NOT the chrome or + the confirm footer — its two callers frame it very differently, one as a step + inside a full-screen card and one as a modal over the import dialog, and a + shared wrapper would put a modal inside a modal. `path` is controlled, + because the caller needs to know where you are standing to label its footer; + `useFsListing()` is exported so the caller reads the RESOLVED path through + the same query key rather than being told it by an effect. The rail + **navigates, never selects** — one click there must not be able to open a + library or commit an import destination. It polls, because drives come and + go while a dialog is open, and the volatile Drives group is LAST so an + appearing drive cannot shift the rows above a moving cursor), + `ExportsSection` + `ExportDialog` (**exports in the sidebar** — each a + named, persisted slice of the library bound to a destination. An export + expands to show its referenced playlists, whose counts come from `contents` + recomputed on every read, because the references are LIVE. Two deliberate + omissions: a referenced playlist has **no per-track remove** — that would + need an exclusion list, i.e. hidden state deciding future exports — and an + export's views pass `TrackTable` **no `onRemove` / `reorder`** — in a + playlist those act on the user's REAL playlist: same pixels, opposite + meaning. Removal from an export is on the context menu, and only on its root + view. Adding is not gated + on the library being writable, since an export set is Konduktor's own data. + `ExportDialog` shows unsupported targets **disabled with a reason** rather + than hiding them), `DevicesSection` (**every drive**, polled from + `/api/fs/drives`: external ones under Devices, the computer's own under an + expandable Local Storage. A drive carrying a OneLibrary library opens as a + device as before, and EVERY drive has a lazily-fetched **Files** tree; + clicking a folder is the `folder` source kind — its audio in the ordinary + table, read-only via `readonly_cause: 'not_in_library'`, with files the + collection already holds checked off in the # column (`TrackTable`'s + `marked`). Capped at 40% of the sidebar and self-scrolling so a deep tree + gives way before the playlists do) + `AddFilesDialog` (copy vs. leave in + place is **asked every time with nothing preselected** — the answer depends + on the drive — and warns that a referenced file on an external drive goes + missing on unplug. A playlist/export target adds to the collection first + and says so; it runs through `importer.run(reference=…, into_playlist=…)`), + `CollectionPicker` (**two steps: which PLATFORM, then which + library** — Automatic / Open last / Find manually, the last revealing a file + browser. The platform comes first because every later answer depends on it: + asked the other way round, "Automatic" had to guess ACROSS platforms and did + it by adapter registration order, so a plugged-in stick could be opened as + the user's collection. Scoping removes that by construction rather than by + ranking candidates better. Nothing is remembered between launches — the + platform list is where every session starts. `selects` decides whether the + browser offers files or a folder to confirm, because a library is a file on + some platforms and a DIRECTORY on others), `Sidebar` (a header naming the + open library, which is also the only way to switch to another one — the + picker used to be a one-way door with `forcePicker` never set, so changing + library meant restarting; switching confirms first when there are unsaved + edits, since the adapter holds them in a native model that opening another + library replaces — plus the playlist tree. **Creating is right-click + only**: a folder's menu offers New Playlist / New Folder inside it, empty + space below the rows creates at the top level, and the new node is named + in place (Esc or an empty name creates nothing). Rename/Delete are on the + same menu and the row's hover buttons, which share one set of actions. + A Traktor folder's id is its PATH of names, so the `PATCH`/`DELETE` + playlist routes take a `:path` param, a folder name may not contain `/`, + and renaming onto a sibling folder's name is refused), `SaveBar` (+ the settings gear beside it, whose menu opens `ShortcutsDialog` — the shortcut list is written out BY HAND, so a new or changed shortcut in `PrepStrip` / `TrackTable` must be added there too), `Toolbar` (search/filters; columns are chosen by right-clicking the table header), + `TrackTable` (**the one track list** — All Tracks, playlists, exports and + devices. TanStack Table + **virtualized** grid; per-row play button, + configurable columns, header sorting, inline double-click editing, and + **Finder-style row selection** — click / Cmd-Ctrl+click / Shift+click over + the SORTED rows, ↑/↓ (Shift extends), Cmd/Ctrl+A, Esc, Enter (load + play + the highlighted row, winning over a focused button); shortcuts stand down + while an `aria-modal` dialog or `role="menu"` is open, so new dialogs need + `aria-modal="true"`. Right-click acts on the whole selection; single-track + items are hidden for a multi-selection. A view with a manual order passes + `reorder` (drag rows — the whole selection moves as a block — with an + insertion line and edge auto-scroll); `enabled` is false while a sort or + filter is active, so a partial or re-sorted order can never overwrite the + real entry list. `onRemove` wires Delete/Backspace; `positions` makes the # + column show playlist positions. Playlists gate both on the node's own + `can_reorder`, so smart playlists get neither. **Row reorder is hand-rolled, + not dnd-kit sortable**: a SortableContext around the virtualizer loops on its + flushSync-driven measurement — which is why playlists were once a separate, + non-virtualized `PlaylistTable`. Fixed 44 px rows make the drop index just + pointer-y / ROW_HEIGHT. dnd-kit still reorders the header's columns.) + `AutoCueDialog` (the Auto Hotcues slot template: event + beat offset per + slot, a per-slot Replace tick for occupied slots — never remembered, since + overwriting is a decision about THIS track — and the template itself + persisted as `autoCueTemplate` in userprefs. Also has a **batch mode** for + the context menu: same template, but it starts a job via `onRun`, and each + tick reads "Replace" and applies to every track in the batch. A Replace + RENAMES the slot's cue — `set_hotcue` keeps the old name only when called + without one, which is what a hand move does), + `ContextMenu` (supports `▸` submenus, section headings, separators and + checkbox items that toggle without closing — the header row's right-click + column chooser uses those; "Add to" lists + playlists + exports and acts on the whole selection; "Remove ▸" holds + From this playlist / From this export / Grids / Hotcues / From collection, + each behind a `ConfirmDialog` — as is the playlist Delete key. Enter + confirms unless a button has focus, so Tab-to-Cancel + Enter cancels) + `EditTagsDialog` (right-click → multi-field metadata + album-art edit), `StatusBar`, `RatingStars` (read-only, or click-to-set when given `onChange`), `Toast`, `UpdateDialog` (`UpdateCheck`, mounted in `main.tsx` beside `App` so it shows @@ -73,23 +428,73 @@ Two independent apps that talk over HTTP: browser via `@tauri-apps/plugin-shell` `open` — falls back to `window.open` outside Tauri; "Skip this version" persists `skippedUpdateVersion` to userprefs via `/api/prefs`; all failures are silent). - - **Prep strip** (DJ deck across the top of the window): `PrepStrip` owns it — - transport (play/pause, CUE), two waveforms (`MainWaveform` scrolling+zoomable - — its zoom is owned by `PrepStrip` so it survives track switches and persists, - `OverviewWaveform` whole-track), `LoopControls`, `HotcueBar`, `GridControls` - (BPM readout/editor, fine ±0.01 / coarse ±0.25 BPM nudge, /2·×2, tap tempo, - grid-phase nudge, set beat 1, lock, delete grid). + - **Prep strip** (DJ deck across the top of the window): `PrepStrip` owns it, + in three rows. **Header**: cover, title/artist · album · genre, a Read-only + badge, the readout well (ELAPSED / REMAIN to tenths, KEY, and `BpmReadout` — + click to type an exact BPM; with no grid, a typed or tapped BPM CREATES one at the playhead, and + Set grid on a track with no BPM opens the readout to ask rather than failing), SNAP, Analyze, Auto hotcues. **Waveforms**: + `MainWaveform` (scrolling; zoom +/− in its corner and Cmd/Ctrl+scroll, owned + by `PrepStrip` so it survives track switches and persists) over + `OverviewWaveform`, which frames the main view's visible range around the + playhead (it takes `secPerView` for exactly that). **Controls**: play, CUE, `LoopControls`, then EITHER + `HotcueBar` OR — in **Grid mode** — `GridEditStrip`, then `TempoControls` + (±0.01 / ±0.25, ÷2 ×2, tap, lock) and the Grid toggle. Every grid control acts + on the marker **governing the playhead**, since a beatgrid is a marker list + and there is no separate marker selection; see "Beatgrid" below. + - **One size for loops AND beat jump** (`beatSize`, 1/32–32, persisted as + `beatSize`; the old `beatJumpBeats` pref is read once on upgrade). + `LoopControls` has a BEAT / MAN switch: BEAT shows `− size +` (the size + key sets or clears a loop of that length; −/+ halve/double, resizing an + engaged beat loop from its locked start), MAN shows IN / OUT / toggle. + The armed IN point is React STATE (`loopInPoint`), not a ref, because the + IN button (lit "armed") and the waveform (`drawLoopIn`: a green IN line + plus a dashed band to the playhead — the loop OUT would make now) both + show it. OUT closes an armed IN, or with a manual loop already set moves + its end to the playhead. A loop that is switched off stays drawn as a dim + outline (`drawLoop(…, idle)`), so the toggle shows what it would restore. + **‹ › (and ←/→) MOVE an engaged loop by its own length**, Traktor-style, + and only jump the playhead when no loop is engaged. The move sets the new + loop BEFORE seeking: `PlaybackEngine.seek` honours the loop in force, so + seeking first wraps the playhead back into the old loop. + - **Hotcue edits live on the pad's right-click menu** (type as one-click + choices, Rename…, Delete); there is no standalone type dropdown or delete + button. Rename re-sets the slot with its own start/type/length plus the + new name, since `set_cue` replaces a slot. A non-editable cue gets the + same menu disabled, not no menu. Prep libs live in `src/lib/`: `playbackEngine.ts` (Web Audio, seamless loops), `scratchEngine.ts` (drag-to-scratch), `waveform.ts` (frequency-colored - analysis + paint), `cues.ts` (draw cues/loop/beatgrid/cue-point). See "Prep - engine" below. - - `lib/trackColumns.tsx` — single source of truth for the library table's + analysis + paint), `beatgrid.ts` (the marker-list beat math — every + beat/bar/snap/jump calculation goes through it), `cues.ts` (draw + cues/loop/beatgrid/cue-point). See "Prep engine" below. + - **`capabilities.writable`** is the library-level gate, and it is deliberately + NOT the same as every per-feature flag being false: "the platform has no such + feature" and "this library cannot be written at all" look identical to a UI + that only sees per-feature flags, and silently inert controls read as a bug. + `readonly_cause` says which kind (`platform_incomplete` / `cloud_synced`) and + `platformCopy.readOnlyNotice()` words it — the two need very different + sentences, since one is a roadmap gap and the other a permanent refusal that + protects the user's other machines. Gated on it: `SaveBar` (replaces the save + button with the reason), `App`'s `onEditField` (inline edit + click-to-rate + go inert), the "Edit Tags…" context item, `Sidebar`'s new-playlist button, + and all 12 `PrepStrip` edit handlers (which report the reason rather than + firing a request the adapter would refuse — the deck stays fully usable for + listening, and shows a "Read-only" badge). + - Capability-gated today: hotcue bank size (`HotcueBar`, the auto-cue guard and + the digit shortcuts all read `cues.hotcue_slots`), the cue-type dropdown + (`cues.types`), the rating scale (`tracks.rating_max`), the grid Lock button + (`grid.lockable`). Per-node playlist flags (`can_rename`, `can_delete`, + `can_add_tracks`) gate the sidebar and the context menu's "Add to" — each on its OWN flag, + since a platform may allow renaming but not deleting. Carried but deliberately unused until a second adapter + exists: `slot_labels: 'letter'`, `palette`, `loops: 'separate_bank'`, and + memory-cue *editing* (one-platform features stay preserved-but-uneditable). +- `lib/trackColumns.tsx` — single source of truth for the library table's columns (defs, default widths/visibility/order, the Columns-menu list, the inline `InlineEdit` cell, and the `TableMeta.onEditField` augmentation). - Data flow: the whole library is fetched once (`/api/tracks?limit=20000`); filtering and sorting happen **client-side** for instant interaction. Edits apply in-memory (server holds them) and the sidebar **Save to Traktor** - button flushes to disk. Styling is Tailwind v4 with tokens in `src/index.css`. + button flushes to disk. Styling is Tailwind v4 with tokens in `src/index.css` + — see "Theme" below. Library column layout (visibility/order/width) persists to `userprefs.json` via `GET`/`PATCH /api/prefs` (debounced; hydrated on launch, merged against defaults so newly-added columns still appear). The prep deck's main-waveform @@ -110,6 +515,7 @@ uvicorn konduktor.main:app --reload --port 8000 cd frontend npm run dev # dev server (proxies /api -> :8000) npm run build # tsc -b && vite build — run this to typecheck +npm run test # vitest — unit tests for src/lib/beatgrid.ts ``` **Tests:** `cd backend && ./run_tests.sh` (runs against a temp copy of the real @@ -118,10 +524,138 @@ serialization path.** It enforces: - `test_save_fidelity.py` — a no-op save is byte-identical (A); a playlist edit changes only that playlist's block (B); a **track-metadata edit changes only that ``** (C); a **hotcue create is localized + round-trips** with - START stored in ms (D); a **beatgrid/BPM edit is localized + round-trips** (E). + START stored in ms (D); a **grid-marker edit is localized + round-trips** (E); + **flexible (multi-marker) grids** add/move/delete reversibly, `delete_grid` + leaves no companion debris (I); **companion cues are ordinary editable + hotcues** — move/retype/delete work and never touch the grid marker (J); and + real flexible grids in the collection project correctly (K); and + **removing a track from the collection** drops its `` and its + PRIMARYKEYs from exactly the playlists that held it — the only ADDED lines are + the `ENTRIES=` recounts, every other playlist byte-identical (L). The guard that catches serialization regressions like the lxml reformatting bug. - `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays Traktor-valid, backup-first, COLLECTION byte-identical, original untouched. +- `test_traktor_adapter.py` — the **generic layer**: one parse per open, the + projection refreshing after every command family, cue-type translation, + capabilities, and `set_analysed_grid` vs `replace_grid`. `test_save_fidelity` + covers the store and its bytes; without this the adapter layer would be untested. +- `test_rekordbox_adapter.py` — the second adapter against the same contract: + cue/grid/key translation as pure units (they need no library), then the + projection, playlist tree, capabilities and the refusal of all 21 commands + against a **temp copy** of the local Rekordbox library. Skips cleanly when no + Rekordbox is installed, so it is safe on any machine. +- `test_rekordbox_fidelity.py` — the **row-level analogue of the byte diff**: a + full table dump before/after, compared row by row (a byte diff is meaningless + against SQLite). Asserts a no-op save changes zero rows; a one-field edit + changes exactly two — the track and `agentRegistry.localUpdateCount` — with the + counter up by one and the edited row stamped with it; edits are invisible on + disk until save; and playlist create/fill/rename/delete round-trip. +- `test_onelibrary_adapter.py` — the third adapter against the same contract. + Unlike the Rekordbox tests it needs **nothing installed and nothing plugged + in**: it runs against `fixtures/onelibrary/`, a real rekordbox 7 export trimmed + to fixture size (its README says what was removed; the database is untouched). + So the expected values are checked against bytes *rekordbox* wrote, not bytes + Konduktor wrote. Pins the drive-relative path resolution, the `PCOB`/`PCO2` + merge, and — cross-checked against the same cues in `master.db` — the dense + ANLZ slot numbering, which is the thing most likely to be silently wrong. +- `test_import.py` — the import feature end to end: a drive's tracks into a temp + copy of the real collection. Asserts the prep survives (hot cues keep their + PAD, memory cues fill spare ones, the flexible grid crosses intact, no + companion cue is invented), that the existing 8,485 entries render + byte-identically, that the job registry runs/fails/cancels, and that a + cancelled import leaves **no orphaned audio and an untouched collection**. +- `test_grid_detect.py` — beatgrid detection on **synthetic** audio, so the + tempo and first beat are known rather than borrowed from another analyser: + exact integer and non-integer BPMs, the 125 BPM the old detector could not + return, octave choice, and the loud off-beat hat and syncopated bassline that + each fooled one band on real music. Accuracy on REAL music is + `bench_grid_detect.py`'s job (not in `run_tests.sh`: it needs audio). +- `test_auto_hotcues.py` — Auto Hotcues in three layers: `structure.analyse` + on SYNTHETIC audio with known sections (the intro with a kick is not a drop; + no breakdown after the last drop), `plan`'s outcomes and beat-counted offsets + (across a tempo change), and the ROUTE end to end on a temp copy of the real + collection — the previous implementation's route returned 500 on every call + for a week while its helper's tests passed. +- `test_grid_batch.py` — **batch analysis** from the context menu, both + `jobs.py` jobs shown in the status bar: Analyze Grid & BPM + (`POST /api/tracks/grid/auto-batch`) and Auto Hotcues… + (`POST /api/tracks/cue/auto-batch`, one template for every track). Pins the + batch-only decisions: locked grids are skipped always, existing grids unless + `replace_existing`; a hotcue batch analyses a grid FIRST where there is none + and never touches an existing one, and a ticked Replace applies to every + track; a failing track is reported not fatal; **one batch at a time ACROSS + both kinds** (a grid run would move the beats a hotcue run is placing cues + on); a cancel KEEPS finished tracks (unsaved edits like any other) and still + returns its result; opening another library cancels the run. Each shares its + helper (`_analyse_grid`, `_place_auto_cues`) with the deck's single-track + button. +- `test_bulk_remove.py` — the context menu's **Remove ▸** routes + (`/api/tracks/grid/clear`, `/api/tracks/cue/clear`, `/api/tracks/remove`): + locked grids are kept, clearing hotcues empties the whole bank (loops and the + grid's beat-1 cue too) but never the grid, a removed track leaves the + projection AND its playlists while its audio file is untouched, removal is + gated on `tracks.removable`, and all three are refused while a batch + analysis runs. `remove_tracks` is the protocol's only DESTROYING verb for + tracks; Traktor implements it, Rekordbox and OneLibrary refuse (a Rekordbox + track spans rows in several tables plus ANLZ files, and which Rekordbox + expects deleted together is unmeasured). The journal records it as + `track/remove`, NOT an edit — otherwise history would read "edited 40 tracks". +- `test_folders.py` — the Files trees and adding loose files, through the + routes, on generated FLACs and a temp copy of the collection: a folder lists + only the visible audio DIRECTLY in it; the audio route refuses anything a + scan did not find; **a file the collection already points at is never added + twice** (on Traktor that would be two ENTRYs sharing a primary key — a corrupt + collection) but still reaches the playlist/export it was headed for; "copy" + points the entry at the copy and "reference" at the original. +- `test_picker.py` — the picker's routes. Pins the scoping, because the bug it + replaced was invisible: `/api/library/options` flattened every driver's + detections and returned `[0]`, so a plugged-in USB stick could be offered as + the user's collection and nothing failed — it just opened the wrong library. + Also pins that a drive is named the same whichever of its two valid paths was + opened, that every offered place exists, that the boot volume is not offered + as a drive, and that the adapter and the browser share ONE mount scanner. Needs nothing installed: every assertion is about the SHAPE of the + answer, and prefs are redirected to a temp file so a test can never rewrite + the user's last-opened library. +- `test_exports.py` — export sets against a temp copy of the real collection. + Pins the things that would fail SILENTLY: a live reference picks up a playlist + edited AFTER curation; contents dedupe across playlists and loose tracks; a + deleted playlist or track is surfaced, not dropped; sets are per-library; two + sets sharing a destination are caught (an export clears its destination, so the + second would wipe the first); and deleting a set never touches its folder. +- `test_export.py` — writing a Traktor collection from NOTHING. There is no + original here, so the guarantee differs from `test_save_fidelity.py`'s: the + result must be a collection Traktor would have written. Pins the skeleton, and + above all that **`` is volume-relative** — an export writing host + paths would work perfectly on the machine that made it and resolve to nothing + at the gig. Also that a flexible multi-marker grid and hot-cue PADS survive, + grids are not locked, loose tracks get their "Other" playlist, and re-exporting + into the same folder replaces rather than appends. + It then runs a real export end to end (the source library is built with the + exporter itself, so its LOCATIONs point at audio that exists) and pins the + safety rules with teeth: a folder Konduktor did NOT write is refused, and + `run()` refuses a blocked plan even when called directly; a re-export replaces + its own files and leaves the user's alone; a cancel leaves no library file and + **no audio at all**, including the file being written; a missing source file is + skipped rather than fatal. +- `test_export_pioneer.py` — the two Pioneer targets against the same contract. + Harder than Traktor's in a way that test cannot cover: each writes a database + PLUS per-track analysis files, so "the library" is no longer one path, and the + prep survives a real change of representation rather than a re-render. Pins the + three crossings that fail SILENTLY — the key is CONVERTED not copied, hot cues + keep their PAD across the dense-vs-sparse slot difference, and a flexible + multi-tempo grid survives expansion to per-beat and collapse back. Both are read + back with Konduktor's own adapters, which is the strongest check short of the + hardware: the reader was written against real rekordbox output. +- `test_library_id.py` — the property no other suite covers: **a library that + moves keeps its identity**. Also that two libraries in one folder stay two, a + removable library is never written beside, an unwritable location falls back + rather than failing, and `paths.write_json` is atomic (curated user work, so + `prefs.py`'s best-effort "any I/O error degrades to no prefs" is NOT adequate). +- `test_layering.py` — `core/` imports nothing platform-specific, and no adapter + imports another platform's library (checked on real imports via AST, so merely + naming a platform in a comment is fine). Rekordbox and OneLibrary deliberately + **share** `pyrekordbox`: the rule is "no adapter reaches for a rival vendor's + library", and a shared dependency is not a breach. Also validate the backend interactively at `http://localhost:8000/docs` and the frontend at `http://localhost:5173`. @@ -132,6 +666,12 @@ frontend at `http://localhost:5173`. stale and **cannot parse Traktor Pro 4 (NML v20)** files — its strict parser dies on the v4 `` element inside `CUE_V2`. `requirements.txt` pins the GitHub `master` (v4.0.0). Do not "simplify" this to a plain PyPI pin. + **`pyrekordbox` is now the same situation**: PyPI's latest (0.4.4) has no + `devicelib_plus`, which is the OneLibrary (`exportLibrary.db`) reader, so + `requirements.txt` pins the GitHub master. That upgrade renamed `db6` → + `masterdb` and `tables` → `models` and moved `BLOB` out of `db6.database`; + the Rekordbox adapter uses the new names. `db6` still works as a deprecated + alias and is **removed in 0.6.0**. 2. **The collection is real, irreplaceable data — protect it.** Every save writes a timestamped `.bak` first (into a `backups/` folder next to the collection). When testing writes, point `KONDUKTOR_NML` at a COPY. Warn the @@ -149,6 +689,27 @@ frontend at `http://localhost:5173`. (`PRIMARYKEY.KEY`) join to collection tracks. `Track.id` uses this. - **Rating** = `RANKING / 51`, giving 0–5 stars (`_rating_stars`). - **Key** is Traktor's display key string, e.g. `"10m"` (Open Key notation). +- **Beatgrid = an ORDERED LIST of markers**, never a single BPM + anchor. + Traktor stores each as a `CUE_V2 TYPE="4"` with its own `` child + (flexible beatgrids, 3.4+); `` mirrors the **first marker by + START**. A constant-tempo track is simply a list of length one, so this is the + model for every track. Two rules verified against the real 8485-entry + collection — get these wrong and you corrupt grids: + - **Marker NAME is not a discriminator** (`AutoGrid` ×7888, `n.n.` ×64, + `Beat Marker` ×14, `Unnamed` ×4). Identify by the `` child, order by + `START` — never by name or document order. + - **Companion cues are conventional, not structural.** Traktor usually pairs a + marker with a white (`COLOR="#FFFFFF"`) `TYPE="0"` cue at the same position, + which occupies a **real hotcue slot** — but 60 of 7970 markers have none. + Konduktor follows them, keeps them in sync, and **never invents one** (except + `place_grid_companion`, used only by Auto Grid). They are **not locked**: + Traktor 4 keeps a beatgrid without one, so a companion is an ordinary hotcue + the user may move, retype or delete — doing so simply ends the pairing + (it is no longer a white cue on a marker), and the grid is untouched. Grid + edits still drag or delete a companion that is still paired. The `#FFFFFF` test is + load-bearing: 49 uncoloured cues and 18 *loops* also sit within 1 ms of a + marker and must not be dragged or deleted. `backend/konduktor/beatgrid.py` + is the single shared definition of all of this. - **Playlist tree**: recurse `nml.playlists.node.subnodes.node`. A node's `.type` is `FOLDER`, `PLAYLIST`, or `SMARTLIST`. Smart playlists are rule-based and have no static entry list. `PlaylistNode.id` is the playlist's stable `UUID`; @@ -161,8 +722,80 @@ frontend at `http://localhost:5173`. - Backend: type hints, Pydantic models for all responses, keep query logic in `collection_service.py` (routes stay thin). - Frontend: functional components, TanStack Query for fetching, Tailwind - utility classes with the `ink-*`/`accent`/`gold`/`mint`/`pink` tokens from - `index.css`. Keep `api.ts` types aligned with `schemas.py`. + utility classes with the `ink-*`/`well`/`accent`/`gold`/`mint`/`pink` tokens + and the material classes from `index.css` (see "Theme"). Icons come from + `lib/icons.tsx`, never emoji; a platform's own mark comes from + `lib/platformIcons.tsx` (`` — single-colour marks + redrawn from each platform's app icon, masks keyed by `useId` since one page + can show a mark twice). That file is a lookup of display ASSETS by platform + id, not platform branching; an unknown id falls back to a generic mark, so a + new adapter needs no change there to appear. Keep `api.ts` types aligned with `schemas.py`. +- **Never `window.confirm` / `alert` / `prompt`.** They cannot be themed, they + block the event loop (a playing deck stutters), and under Tauri they read as a + web page. Use `await askConfirm({ title, body, confirmLabel, tone? })` from + `lib/confirm.tsx` — same one-line shape as `confirm()`, rendered as the themed + `ConfirmDialog` by the `ConfirmHost` mounted once in `main.tsx`. `tone` is + `danger` (default, pink) or `primary`. Components that already hold dialog + state may still render `ConfirmDialog` directly. + +## Theme — "dark liquid glass" + +Floating frosted panels (12 px gutters) over a drifting wash of colour sampled +from the loaded track's cover art. Colour is reserved for MEANING — cue types, +key, playhead, the one primary action; chrome stays neutral. The rules that are +easy to break: + +- **`ink-900`…`ink-600` are translucent WHITE overlays, not greys**, so they + read on any panel. Only `ink-950` is opaque: it is the dark text on light + buttons and the page base. Recessed things (inputs, waveforms, readouts, + progress tracks) use `well` / the `.well` class — never `bg-ink-950`. +- **Materials are classes in `index.css`**: `.glass` (panel), `.glass-overlay` + (menus, dialogs, toasts — denser), `.well`, `.btn-glass`, `.btn-primary` + (white→accent pill, one per view), `.is-selected`. The rim light is a + `::before`, so these set `position: relative`; Tailwind's `fixed`/`absolute` + utilities win because utilities outrank the components layer. +- **Never put `backdrop-filter` (or `filter`/`transform`) on an element that can + contain a popup.** It makes that element the containing block for every + `position: fixed` descendant, so a context menu or dialog opened inside it is + placed relative to the panel, not the window — the sidebar's playlist menu + opened far from the cursor. `.glass`'s blur and tint therefore live on its + `::after` (z-index -1 under `isolation: isolate`), not on the panel. +- **Every overlay renders through `createPortal(…, document.body)`** — all + dialogs, `ContextMenu` and `Toast`. Each `.glass` panel is a stacking context + (`isolation`), so an overlay rendered INSIDE one can never rise above a + neighbouring panel, whatever its z-index: New Export (from the sidebar) sat + behind the library, and the deck's Auto Hotcues dialog behind both. One + z scale, set on the overlay's root: dialogs `z-50`, a dialog opened from a + dialog (`FolderPicker`) `z-[60]`, menus `z-[70]`, toasts `z-[80]`. A new + overlay that skips the portal will look fine when opened from `App` and break + the first time a panel opens it. Small popovers anchored to a control inside a + scrolling list should open the shared `ContextMenu` instead (as the playlist + row's "Add to export" does) — a popover inside the list is clipped by it. +- **A `.glass` / `.glass-overlay` box must never be the element that scrolls.** + Its tint, blur and rim are pseudo-elements sized to the box, so they scroll + away with the first screenful and leave later content on bare background (the + column chooser's last items did). Give the glass frame `overflow-hidden` and + scroll an inner element — as every dialog and `ContextMenu` do. +- **Keep backdrop blurs on SHORT elements small** (the table's sticky header uses + 8 px). Chrome silently skips a large backdrop blur on a thin strip — 12 px and + up left the rows under the ~33 px header perfectly sharp, with the computed + style still reporting the blur, so nothing looks wrong in DevTools. +- **The accent is `oklch(0.8 0.11 var(--accent-hue))`** — the cover's hue at a + FIXED lightness and chroma, so dark text on it keeps its contrast whatever is + loaded. `lib/ambient.ts` sets `--accent-hue` and `--amb-1..4` on ``; + they are `@property`-registered so a track change glides, and nothing in React + state depends on them (no re-render on a track change). The art is fetched as + a blob → `createImageBitmap`, because a cross-origin `` (the API under + Tauri) taints the canvas. A device track, or greyscale art, gets the default. +- `AmbientBackdrop` is mounted in `main.tsx`, behind the picker too; so no root + container may set an opaque background, or the glass has nothing behind it. +- **Canvas drawing glows instead of outlining** (`cues.ts`): a black outline on + glass reads as a gap in the waveform. The playhead is `drawPlayhead`, shared + by both waveforms. +- The table's Cues column draws one dot per occupied slot from + `Track.hotcues` (`HotcueChip`: slot, type, colour), which every adapter + projects with the SAME slot test its `track_cues()` uses, so the dots cannot + disagree with the pads. OneLibrary fills it lazily, like `hotcue_count`. - Python 3.14 note: pin dependencies loosely enough to get prebuilt wheels (older `pydantic-core` pins force a from-source Rust build that fails). @@ -202,8 +835,167 @@ that number and nothing else — everything derives from it: collection picker (Automatic / last-opened / manual), persisted to `userprefs.json` - ✅ Track prep — audio playback, frequency-colored scrolling waveform, scratch, beatgrid display + editing, cue/hotcue create/jump/delete, loops; keyboard - shortcuts (Space = play/pause, 1–8 = hotcues, Shift+1–8 = delete). See "Prep engine". + shortcuts (Space = play/pause, 1–8 = hotcues, Shift+1–8 = delete, Cmd/Ctrl+↑/↓ = + loop/jump size). See "Prep engine". - ✅ Track prep Tier 2 — cue-point fine editing / audio export polish +- ✅ Flexible beatgrids — the grid is a marker list end to end (marker-level + commands, piecewise beat math, playhead-derived marker editing). Step 1 of the + multi-platform plan in `.claude/discussions/`. +- ✅ Generic model + adapter interface (Traktor as the only adapter) — step 2 of + the multi-platform plan. Backend, wire format and UI are all generic; nothing + above `adapters/traktor/` knows what Traktor is. +- 🟡 Rekordbox adapter — **read + metadata/playlist/hot-cue/beatgrid writes + done** (milestones 1–3). A Rekordbox library opens, projects, browses and + accepts track metadata, playlist, hot cue and beatgrid edits — including + flexible multi-tempo grids, confirmed rendering correctly in Rekordbox 7 — + verified row-by-row by + `test_rekordbox_fidelity.py`, end to end through the API, and in Rekordbox 7 + itself. Research is captured in `.claude/handoffs/rekordbox-adapter.md` §8, + incl. the verified result that Rekordbox accepts Konduktor-written rows when + USNs are maintained. Remaining gap: **writing cover art** (reading works: the file's embedded art, + else Rekordbox's own `ImagePath` copy under `share/`). **No version history on Rekordbox** — accepted scope decision, + see handoff §11. +- ✅ **Import a OneLibrary stick into Traktor** — done end to end. A plugged-in + drive appears under **Devices** in the sidebar, browses in the ordinary table + and deck (audio streams off the stick so a track can be auditioned before + importing), and imports into the loaded collection: audio copied, cues and + flexible beatgrids translated, playlists recreated in a folder named after the + drive. Verified in Traktor 4.5 itself. Three pieces worth knowing: + - **`add_tracks` is the protocol's only CREATING verb** (`core/adapter.py`, + `NewTrack`). Everywhere else the write target was parsed from a real file, + which is what makes the byte-fidelity guarantee hold; here the rule becomes + "an added entry must not perturb any existing one", which `test_import.py` + checks on rendered bytes — exactly one line changes, the one carrying + ``, whose count the store now maintains. The store + creates a bare `ENTRY` and the cues/grid are written by **replaying the + ordinary commands**, so an import inherits `replace_grid`'s companion + handling and tests instead of growing a second implementation. + `AUDIO_ID` and `LOUDNESS` are left empty — they are Traktor's own analysis + outputs and cannot be computed; **verified that Traktor loads and plays such + entries** and re-analyses them. + - **`jobs.py` + `importer.py`** — the app's first long-running operation. + Thread per job, polling, cooperative cancel; deliberately not asyncio or SSE. + **Ordering is the safety property**: audio copies first and the library is + written last, so a cancel leaves the collection untouched and removes what it + copied (including the file being written — cleaning up only COMPLETED copies + left debris the retry then suffixed around). Export will reuse this. + - **The UI gates itself through capabilities, not conditions.** Browsing a + device swaps the `CapabilitiesContext` for the device's own read-only set, so + inline editing, Edit Tags, rating stars and all 12 deck handlers go inert + with **no component learning what a device is**. The Sidebar sits outside + that swap so `SaveBar` still saves collection edits. While a device's + capabilities load the fallback is read-only, never the collection's — + guessing "writable" for one frame would offer an edit bound for the wrong + library. Lossiness follows the settled rule: memory cues become hot cues in + spare pads (earliest first), cue colour is dropped (Traktor derives it from + type). +- 🟡 OneLibrary adapter — **read-only, done**. A OneLibrary USB drive opens, + projects, browses and searches: tracks, playlists, hot cues, memory cues, loops + and flexible beatgrids. Built as the readable SOURCE half of a future + **"import a OneLibrary stick into a Traktor library"** feature, which is the + motivating use case. Everything unknown about the format is on the write side + (the `cue` table's MPEG seek columns, the waveform tags a CDJ draws from, the + update counters), so read-only is a deliberate boundary rather than an + unfinished one. All research — including the schema, which has no public spec — + is in [.claude/handoffs/onelibrary-adapter.md](.claude/handoffs/onelibrary-adapter.md). +- 🟡 **Export/conversion** — **in progress.** Both the design AND the user flow + are settled; see + [the export discussion doc](.claude/discussions/discuss-export-implementation-2026-09-22.md), + whose 2026-09-23 section is the current one, plus + [.claude/handoffs/export.md](.claude/handoffs/export.md) for the landmines. + An **export** is a named, persisted object in the sidebar carrying its name, + target platform and destination; tracks and playlists are added to it; an + Export button copies the audio and writes the library. Settled: **Traktor-only + target** for v1, source is whatever library is loaded, **mirror the source + folder structure** (so filename collisions cannot happen), playlists are **live + links removable only as a whole**, re-export **clears the destination first**, + cancel **rolls back**, key notation **mirrors the source**, grids are **not + locked**, no whole-library export. + Verified against the real collection: Traktor stores `VOLUME="Hardy"` plus a + **volume-relative** `DIR`, never a host path — so a USB export is portable by + construction, and the `.nml` cannot be written until the destination is known. + Also settled: loose tracks land in an **"Other" playlist**, playlist folders + are preserved, and the export is a **standalone `collection.nml`** the user + swaps into a Traktor install — so it needs the full skeleton, verified from the + real file: ``, ``, ``, + ``, `` wrapping a `$ROOT` FOLDER node with a + `SUBNODES COUNT`, and ``. There is + **no `` element**, so it is not required. + **Safety**: "clear the destination first" plus "the user picks the destination" + is a folder-deletion hazard, so an export writes a `.konduktor-export.json` + manifest and **refuses to clear any folder that lacks one** — Konduktor only + ever deletes what Konduktor wrote. + **All three targets are now writable from nothing** (2026-09-23). The UI needed + **no change at all** — `/api/export-targets` reads the exporter registry, so + registering one is what makes a platform selectable. Three things were measured + rather than assumed, each contradicting the handoff's expectation: + - **ANLZ analysis files CAN be created from scratch.** The handoff called this + unexplored and a likely blocker. `adapters/rekordbox/anlz_writer.py` builds + them; both Pioneer targets need one per track. Two traps: `AnlzTag.content` + is a construct **Switch** (pass the structure, not bytes), and the cue-entry + structs `AnlzCuePoint`/`AnlzCuePoint2` **cannot be built at all** — each + declares `"type"` twice, once as a magic `Const` and once as the cue kind, so + parsing works (the second overwrites) and building cannot. Cue entries are + therefore packed by hand, and the whole FILE is assembled here too, because + `AnlzFile.build()` re-builds every tag through those same structs. + - **`Base.metadata.create_all()` does NOT reproduce Rekordbox's schema.** The + ORM models 37 tables where a real `master.db` has 47, and marks columns NOT + NULL that Rekordbox leaves nullable (`agentRegistry.id_1` caught it). So + `fixtures/rekordbox/schema.sql` is the real DDL, plus `seed.sql` for the + scaffolding rows `add_content` requires — `djmdDevice`/`djmdProperty` are + deliberately NOT in the fixture, since they carry the machine's name and + UUIDs; those are generated fresh per export. + - **The two Pioneer key blobs are different.** `masterdb`'s key and + `devicelib_plus`'s are not the same string; mixing them up yields a database + Rekordbox cannot open. + `adapters/onelibrary/export.py` writes a whole drive (`PIONEER/rekordbox/ + exportLibrary.db` from the checked-in DDL, plus ANLZ under `PIONEER/USBANLZ/`, + paths drive-relative). `adapters/rekordbox/export.py` writes a `master.db` and + **replays cues through the ordinary `RekordboxAdapter.set_cue`**, so it inherits + `_sync_content_cue`, the sparse `Kind` bank and their tests rather than + redefining them; its ANLZ files go under a **`share/` directory beside + `master.db`**, which is what `AnalysisDataPath` is rooted at — write them at the + library root and the grid silently reads back empty. + **Key notation crosses via the wheel**, never by copying the string: + `projection.render_key()` is the inverse of `parse_key`, shared by both Pioneer + targets, so Traktor's `"10m"` becomes `"Cm"` rather than a literal `"10m"` in a + Pioneer library. **Caveat**: `djmdContent.FolderPath` is an ABSOLUTE host path, + so unlike Traktor and OneLibrary a Rekordbox export is not portable by copying + the folder. Still unwritten and documented as unknown: OneLibrary's waveform + tags and the `cue` table's MPEG seek columns. + **Step 5 done**: `exporter.py` — plan, mirrored copy, manifest, rollback — on + `jobs.py`, plus `POST /api/exports/{id}/preview` and `/run`, and the + `ExportRunDialog`. Three properties it is built around: audio is copied FIRST + and the library written LAST, so a cancel leaves **no** library file and its + absence is what marks an export unfinished; rollback registers each file + BEFORE writing it, so the in-flight copy is cleaned up too; and the **manifest** + (`.konduktor-export.json`) means clearing removes exactly what the last export + wrote, so a file the user put in the folder survives a re-export. Audio mirrors + the source tree **relative to `common_dir_prefix`** — mirroring absolute paths + would put the user's home directory on the stick, and relative paths make + filename collisions impossible. A destination Konduktor did not write is + **refused, not confirmed**: there is no "do it anyway". + **Step 4 done**: `core/export.py` (the `LibraryExporter` protocol, its own + registry, and the strictly-generic `ExportPayload` — so a Rekordbox collection + exports to Traktor with no exporter knowing Rekordbox exists) and + `adapters/traktor/export.py`. The writer **creates then replays**: it writes a + minimal valid NML skeleton, opens a `TraktorAdapter` on it and populates it + with the ordinary commands. That amends the original design note, which + rejected create-then-replay on the grounds that the write target must always be + a native model parsed from a real file — here it literally is, a skeleton + Konduktor just wrote, and the alternative was a second definition of "Track + + cues + grid → ENTRY" that would drift from `add_entry` and inherit none of its + tests. Exporters declare **static** capabilities: no instance, no path, because + the library being described does not exist yet. + **Steps 1–3 done**: `library_id.py`; `exports.py` + 10 routes + `api.ts`; and + the UI (`ExportsSection`, `ExportDialog`, export views in `App`, "Add to" on + the track context menu and each sidebar playlist row). + Next: `core/exporter.py` + the Traktor writer, and the export run itself on top + of `jobs.py` and `importer.py`'s copy machinery — **there is no Export button + yet**, since nothing can be written. Note the OneLibrary work already demonstrated + creating an `exportLibrary.db` from nothing, and `fixtures/onelibrary/schema.sql` + is the DDL to do it with. +- ⬜ Serato adapter - ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging ## Write path (playlists + track metadata + prep) @@ -232,10 +1024,18 @@ diff — no COLLECTION splicing needed. `set_hotcue(track_id, slot, start_sec, type, length_sec)` creates/replaces a `CUE_V2` (types 0 cue, 1 fade-in, 2 fade-out, 3 load, 5 loop; START/LEN stored in **ms**; a loop hotcue carries LEN); `set_hotcue_type` changes just the type; - `delete_hotcue` removes a slot. `set_grid(track_id, bpm?, anchor_sec?)` edits - the TEMPO + the grid marker (`CUE_V2` type 4 with a `` child); - `delete_grid` drops it; `set_lock(track_id, locked)` toggles the `LOCK` attr. - Invariants D/E prove hotcue + grid edits are localized and round-trip. + `delete_hotcue` removes a slot. (The adapter exposes these generically as + `set_cue`/`set_cue_type`/`delete_cue`, taking a `cue_type` STRING — `cue`, + `fade_in`, `fade_out`, `load`, `loop` — which the Traktor adapter maps to the + integers below.) A grid marker's companion cue is an ordinary hotcue to these + commands (see "Beatgrid"). Beatgrid commands are marker-level: + `add_grid_marker` (inherits the governing tempo when no BPM is given), + `move_grid_marker` (clamped between its neighbours, drags the companion), + `set_grid_marker_bpm` (also serves ×2 / ÷2, which retempo the governing marker + like every other tempo control), `delete_grid_marker`, `replace_grid` (Auto + Grid and the deck's Reset), `delete_grid` (markers **and** companions; keeps + `TEMPO`), `place_grid_companion`. `set_lock(track_id, locked)` toggles `LOCK`. + Invariants D/E/I/J prove hotcue + grid edits are localized and round-trip. - **Embedded file tags + cover art**: on save, for each edited track, `_sync_file_tags()` writes the changed fields (and staged cover art) into the audio file via `file_tags` (mutagen; ID3/MP4/FLAC/AIFF, WAV skipped) — @@ -251,8 +1051,10 @@ diff — no COLLECTION splicing needed. `POST/PATCH/DELETE /api/playlists[...]`, `PUT .../entries` (replace), `POST .../add` (append); `PATCH /api/tracks` (metadata); `GET/PUT /api/tracks/art` (cover art); `GET /api/tracks/audio` (Range-aware stream for playback/analysis); - `GET /api/tracks/cues`, `POST/PATCH/DELETE /api/tracks/hotcue`, - `PATCH/DELETE /api/tracks/grid`, `PATCH /api/tracks/lock` (prep); `POST /api/save`. + `GET /api/tracks/cues`, `POST/PATCH/DELETE /api/tracks/cue`, + `POST/PATCH/DELETE /api/tracks/grid/marker`, + `PUT /api/tracks/grid` (replace), `DELETE /api/tracks/grid`, + `PATCH /api/tracks/lock` (prep); `POST /api/save`. - Tests: `backend/run_tests.sh` → `test_save_fidelity.py` + `test_phase3.py` (both run against a temp copy). Run before touching the save/serialization path. @@ -274,12 +1076,23 @@ The prep strip plays every track through the **Web Audio API** (a plain playback buffer's views). Playback and scratch also run on **separate `AudioContext`s** — sharing one goes silent after a source has played. - `waveform.ts` — decodes once (buffer reused by both engines, no re-decode), - splits into 3 bands via `OfflineAudioContext` biquads, and colors each column - by blending three palette targets (bass→orange, mids→violet, highs→cyan — no - green, matching Traktor's Spectrum). Height = amplitude. + splits into 3 bands via `OfflineAudioContext` biquads, and paints them as + **three layers**, not one blended colour per column: bass (orange) first and + tallest, then mids (violet) and highs (cyan) with a `screen` blend — no green, + matching Traktor's Spectrum. Each band is normalised to its own 99.5th + percentile and then EXPANDED (bass steepest): dance music holds its bass near + full scale for whole sections, so a linear map draws a solid orange wall + instead of the kick pulse. The main view draws 2 px bars with a 1 px gap, + **binned in track space** so bars scroll rather than flicker. - `cues.ts` — canvas drawers for cue markers (type-colored), the active loop - band, the beatgrid (white beats/brighter downbeats), and the floating CUE - point (gold). The main waveform's playhead is red; both waveforms share these. + band, the beatgrid (per-segment white beats/brighter downbeats, plus marker + lines — gold for the one governing the playhead, accent otherwise, with the + active segment tinted), and the floating CUE point (gold). The main waveform's + playhead is red; both waveforms share these. +- `beatgrid.ts` — the `BeatGrid` model (`buildBeatGrid` → `BeatGrid | null`). + Unit-tested (`npm run test`, vitest); `beatgrid.test.ts` pins the property that + a **single-marker grid is algebraically identical to the old single-BPM math**, + which is what protects the 99.98% of tracks with a constant tempo. - Prep edits go straight to the prep endpoints above; after each edit the endpoint refreshes the read model (`service.replace_track()`) so cue/grid counts update live, and the frontend invalidates the relevant queries. diff --git a/backend/bench_grid_detect.py b/backend/bench_grid_detect.py new file mode 100644 index 0000000..aa8f4a6 --- /dev/null +++ b/backend/bench_grid_detect.py @@ -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()) diff --git a/backend/bench_structure.py b/backend/bench_structure.py new file mode 100644 index 0000000..88e2d41 --- /dev/null +++ b/backend/bench_structure.py @@ -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()) diff --git a/backend/fixtures/onelibrary/Contents/Loopmasters/UnknownAlbum/Demo Track 1.mp3 b/backend/fixtures/onelibrary/Contents/Loopmasters/UnknownAlbum/Demo Track 1.mp3 new file mode 100644 index 0000000..48cdce8 --- /dev/null +++ b/backend/fixtures/onelibrary/Contents/Loopmasters/UnknownAlbum/Demo Track 1.mp3 @@ -0,0 +1 @@ +placeholder diff --git a/backend/fixtures/onelibrary/Contents/Loopmasters/UnknownAlbum/Demo Track 2.mp3 b/backend/fixtures/onelibrary/Contents/Loopmasters/UnknownAlbum/Demo Track 2.mp3 new file mode 100644 index 0000000..48cdce8 --- /dev/null +++ b/backend/fixtures/onelibrary/Contents/Loopmasters/UnknownAlbum/Demo Track 2.mp3 @@ -0,0 +1 @@ +placeholder diff --git a/backend/fixtures/onelibrary/PIONEER/USBANLZ/P016/0000875E/ANLZ0000.DAT b/backend/fixtures/onelibrary/PIONEER/USBANLZ/P016/0000875E/ANLZ0000.DAT new file mode 100644 index 0000000..707cf5b Binary files /dev/null and b/backend/fixtures/onelibrary/PIONEER/USBANLZ/P016/0000875E/ANLZ0000.DAT differ diff --git a/backend/fixtures/onelibrary/PIONEER/USBANLZ/P016/0000875E/ANLZ0000.EXT b/backend/fixtures/onelibrary/PIONEER/USBANLZ/P016/0000875E/ANLZ0000.EXT new file mode 100644 index 0000000..acaa8a3 Binary files /dev/null and b/backend/fixtures/onelibrary/PIONEER/USBANLZ/P016/0000875E/ANLZ0000.EXT differ diff --git a/backend/fixtures/onelibrary/PIONEER/USBANLZ/P053/0001D21F/ANLZ0000.DAT b/backend/fixtures/onelibrary/PIONEER/USBANLZ/P053/0001D21F/ANLZ0000.DAT new file mode 100644 index 0000000..ca74814 Binary files /dev/null and b/backend/fixtures/onelibrary/PIONEER/USBANLZ/P053/0001D21F/ANLZ0000.DAT differ diff --git a/backend/fixtures/onelibrary/PIONEER/USBANLZ/P053/0001D21F/ANLZ0000.EXT b/backend/fixtures/onelibrary/PIONEER/USBANLZ/P053/0001D21F/ANLZ0000.EXT new file mode 100644 index 0000000..f1383d1 Binary files /dev/null and b/backend/fixtures/onelibrary/PIONEER/USBANLZ/P053/0001D21F/ANLZ0000.EXT differ diff --git a/backend/fixtures/onelibrary/PIONEER/rekordbox/exportLibrary.db b/backend/fixtures/onelibrary/PIONEER/rekordbox/exportLibrary.db new file mode 100755 index 0000000..319a86e Binary files /dev/null and b/backend/fixtures/onelibrary/PIONEER/rekordbox/exportLibrary.db differ diff --git a/backend/fixtures/onelibrary/README.md b/backend/fixtures/onelibrary/README.md new file mode 100644 index 0000000..edfec7b --- /dev/null +++ b/backend/fixtures/onelibrary/README.md @@ -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. diff --git a/backend/fixtures/onelibrary/schema.sql b/backend/fixtures/onelibrary/schema.sql new file mode 100644 index 0000000..9d035fc --- /dev/null +++ b/backend/fixtures/onelibrary/schema.sql @@ -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 +); + diff --git a/backend/fixtures/rekordbox/README.md b/backend/fixtures/rekordbox/README.md new file mode 100644 index 0000000..804a2b5 --- /dev/null +++ b/backend/fixtures/rekordbox/README.md @@ -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. diff --git a/backend/fixtures/rekordbox/schema.sql b/backend/fixtures/rekordbox/schema.sql new file mode 100644 index 0000000..f0e05ee --- /dev/null +++ b/backend/fixtures/rekordbox/schema.sql @@ -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`); diff --git a/backend/fixtures/rekordbox/seed.sql b/backend/fixtures/rekordbox/seed.sql new file mode 100644 index 0000000..01137c7 --- /dev/null +++ b/backend/fixtures/rekordbox/seed.sql @@ -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'); diff --git a/backend/konduktor/adapters/__init__.py b/backend/konduktor/adapters/__init__.py new file mode 100644 index 0000000..75d1a81 --- /dev/null +++ b/backend/konduktor/adapters/__init__.py @@ -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 diff --git a/backend/konduktor/adapters/onelibrary/__init__.py b/backend/konduktor/adapters/onelibrary/__init__.py new file mode 100644 index 0000000..5acdd31 --- /dev/null +++ b/backend/konduktor/adapters/onelibrary/__init__.py @@ -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) diff --git a/backend/konduktor/adapters/onelibrary/adapter.py b/backend/konduktor/adapters/onelibrary/adapter.py new file mode 100644 index 0000000..f7c682f --- /dev/null +++ b/backend/konduktor/adapters/onelibrary/adapter.py @@ -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") diff --git a/backend/konduktor/adapters/onelibrary/beatgrid.py b/backend/konduktor/adapters/onelibrary/beatgrid.py new file mode 100644 index 0000000..f739932 --- /dev/null +++ b/backend/konduktor/adapters/onelibrary/beatgrid.py @@ -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) diff --git a/backend/konduktor/adapters/onelibrary/capabilities.py b/backend/konduktor/adapters/onelibrary/capabilities.py new file mode 100644 index 0000000..fba47d9 --- /dev/null +++ b/backend/konduktor/adapters/onelibrary/capabilities.py @@ -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, + ), + ) diff --git a/backend/konduktor/adapters/onelibrary/cues.py b/backend/konduktor/adapters/onelibrary/cues.py new file mode 100644 index 0000000..e1ee0a4 --- /dev/null +++ b/backend/konduktor/adapters/onelibrary/cues.py @@ -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 diff --git a/backend/konduktor/adapters/onelibrary/discovery.py b/backend/konduktor/adapters/onelibrary/discovery.py new file mode 100644 index 0000000..b5a3b62 --- /dev/null +++ b/backend/konduktor/adapters/onelibrary/discovery.py @@ -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 diff --git a/backend/konduktor/adapters/onelibrary/driver.py b/backend/konduktor/adapters/onelibrary/driver.py new file mode 100644 index 0000000..df216b6 --- /dev/null +++ b/backend/konduktor/adapters/onelibrary/driver.py @@ -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." + ) diff --git a/backend/konduktor/adapters/onelibrary/export.py b/backend/konduktor/adapters/onelibrary/export.py new file mode 100644 index 0000000..619d4f4 --- /dev/null +++ b/backend/konduktor/adapters/onelibrary/export.py @@ -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: + + /PIONEER/rekordbox/exportLibrary.db the library (SQLCipher) + /PIONEER/USBANLZ/P0xx/xxxxxxxx/ANLZ0000.{DAT,EXT} per-track analysis + /… 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 diff --git a/backend/konduktor/adapters/onelibrary/layout.py b/backend/konduktor/adapters/onelibrary/layout.py new file mode 100644 index 0000000..de99fe9 --- /dev/null +++ b/backend/konduktor/adapters/onelibrary/layout.py @@ -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/<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) diff --git a/backend/konduktor/adapters/onelibrary/projection.py b/backend/konduktor/adapters/onelibrary/projection.py new file mode 100644 index 0000000..639363b --- /dev/null +++ b/backend/konduktor/adapters/onelibrary/projection.py @@ -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)) diff --git a/backend/konduktor/adapters/onelibrary/store.py b/backend/konduktor/adapters/onelibrary/store.py new file mode 100644 index 0000000..295d3ed --- /dev/null +++ b/backend/konduktor/adapters/onelibrary/store.py @@ -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 diff --git a/backend/konduktor/adapters/rekordbox/__init__.py b/backend/konduktor/adapters/rekordbox/__init__.py new file mode 100644 index 0000000..6076a5b --- /dev/null +++ b/backend/konduktor/adapters/rekordbox/__init__.py @@ -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) diff --git a/backend/konduktor/adapters/rekordbox/adapter.py b/backend/konduktor/adapters/rekordbox/adapter.py new file mode 100644 index 0000000..53c385d --- /dev/null +++ b/backend/konduktor/adapters/rekordbox/adapter.py @@ -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") diff --git a/backend/konduktor/adapters/rekordbox/anlz_writer.py b/backend/konduktor/adapters/rekordbox/anlz_writer.py new file mode 100644 index 0000000..5429a71 --- /dev/null +++ b/backend/konduktor/adapters/rekordbox/anlz_writer.py @@ -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 diff --git a/backend/konduktor/adapters/rekordbox/beatgrid.py b/backend/konduktor/adapters/rekordbox/beatgrid.py new file mode 100644 index 0000000..e9c9081 --- /dev/null +++ b/backend/konduktor/adapters/rekordbox/beatgrid.py @@ -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 diff --git a/backend/konduktor/adapters/rekordbox/capabilities.py b/backend/konduktor/adapters/rekordbox/capabilities.py new file mode 100644 index 0000000..e3cc73d --- /dev/null +++ b/backend/konduktor/adapters/rekordbox/capabilities.py @@ -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, + ), + ) diff --git a/backend/konduktor/adapters/rekordbox/cue_types.py b/backend/konduktor/adapters/rekordbox/cue_types.py new file mode 100644 index 0000000..62c8387 --- /dev/null +++ b/backend/konduktor/adapters/rekordbox/cue_types.py @@ -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 diff --git a/backend/konduktor/adapters/rekordbox/discovery.py b/backend/konduktor/adapters/rekordbox/discovery.py new file mode 100644 index 0000000..294ec01 --- /dev/null +++ b/backend/konduktor/adapters/rekordbox/discovery.py @@ -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 diff --git a/backend/konduktor/adapters/rekordbox/driver.py b/backend/konduktor/adapters/rekordbox/driver.py new file mode 100644 index 0000000..f6040b0 --- /dev/null +++ b/backend/konduktor/adapters/rekordbox/driver.py @@ -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." + ) diff --git a/backend/konduktor/adapters/rekordbox/export.py b/backend/konduktor/adapters/rekordbox/export.py new file mode 100644 index 0000000..c695108 --- /dev/null +++ b/backend/konduktor/adapters/rekordbox/export.py @@ -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///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 diff --git a/backend/konduktor/adapters/rekordbox/projection.py b/backend/konduktor/adapters/rekordbox/projection.py new file mode 100644 index 0000000..27cd735 --- /dev/null +++ b/backend/konduktor/adapters/rekordbox/projection.py @@ -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 diff --git a/backend/konduktor/adapters/rekordbox/store.py b/backend/konduktor/adapters/rekordbox/store.py new file mode 100644 index 0000000..ebfc700 --- /dev/null +++ b/backend/konduktor/adapters/rekordbox/store.py @@ -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 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() diff --git a/backend/konduktor/adapters/traktor/__init__.py b/backend/konduktor/adapters/traktor/__init__.py new file mode 100644 index 0000000..a2bc648 --- /dev/null +++ b/backend/konduktor/adapters/traktor/__init__.py @@ -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) diff --git a/backend/konduktor/adapters/traktor/adapter.py b/backend/konduktor/adapters/traktor/adapter.py new file mode 100644 index 0000000..63318d9 --- /dev/null +++ b/backend/konduktor/adapters/traktor/adapter.py @@ -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 diff --git a/backend/konduktor/adapters/traktor/beatgrid.py b/backend/konduktor/adapters/traktor/beatgrid.py new file mode 100644 index 0000000..070a2df --- /dev/null +++ b/backend/konduktor/adapters/traktor/beatgrid.py @@ -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 `` 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. + +`` 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 `` 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 `` + 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 `` 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 `` and falls back to `` 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()) diff --git a/backend/konduktor/adapters/traktor/capabilities.py b/backend/konduktor/adapters/traktor/capabilities.py new file mode 100644 index 0000000..e6eac5a --- /dev/null +++ b/backend/konduktor/adapters/traktor/capabilities.py @@ -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' 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, + ), + ) diff --git a/backend/konduktor/adapters/traktor/cue_types.py b/backend/konduktor/adapters/traktor/cue_types.py new file mode 100644 index 0000000..07b8405 --- /dev/null +++ b/backend/konduktor/adapters/traktor/cue_types.py @@ -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()} diff --git a/backend/konduktor/discovery.py b/backend/konduktor/adapters/traktor/discovery.py similarity index 100% rename from backend/konduktor/discovery.py rename to backend/konduktor/adapters/traktor/discovery.py diff --git a/backend/konduktor/adapters/traktor/driver.py b/backend/konduktor/adapters/traktor/driver.py new file mode 100644 index 0000000..413a6c8 --- /dev/null +++ b/backend/konduktor/adapters/traktor/driver.py @@ -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"` element at all**, so it is not required, and `` 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 = ( + '\n' + '\n' + '\n' + '\n' + '' + "\n\n\n" + '\n' + "\n\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 + ] diff --git a/backend/konduktor/adapters/traktor/locations.py b/backend/konduktor/adapters/traktor/locations.py new file mode 100644 index 0000000..e250f46 --- /dev/null +++ b/backend/konduktor/adapters/traktor/locations.py @@ -0,0 +1,71 @@ +"""Traktor LOCATION <-> OS path conversion. + +A Traktor ```` 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/. + """ + 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 diff --git a/backend/konduktor/adapters/traktor/projection.py b/backend/konduktor/adapters/traktor/projection.py new file mode 100644 index 0000000..df9124e --- /dev/null +++ b/backend/konduktor/adapters/traktor/projection.py @@ -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 + ) diff --git a/backend/konduktor/adapters/traktor/store.py b/backend/konduktor/adapters/traktor/store.py new file mode 100644 index 0000000..fdc0510 --- /dev/null +++ b/backend/konduktor/adapters/traktor/store.py @@ -0,0 +1,1187 @@ +"""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 — only the objects actually edited differ in the output; the rest + of the ~14 MB file renders byte-identically, + * safe — every save is committed to the collection's version history (see + ``history.py``); the commit is additive and never alters the saved bytes. + +We edit the parsed dataclass model in memory and, on save, render the WHOLE +model through the library's own pipeline — proven byte-identical for unedited +content, so no splicing is needed. + +Playlists are identified by their stable UUID; folders by a synthetic path id +(``fld:/``). Smart playlists are read-only. +""" +from __future__ import annotations + +import threading +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, + Locationtype, + Nodetype, + Playlisttype, + Primarykeytype, + Subnodestype, + Tempotype, +) +from xsdata.formats.dataclass.serializers import XmlSerializer + +from ...core.adapter import InvalidCommand, SaveOutcome +from ...core.edit_journal import EditJournal +from ...core.pathmap import common_dir_prefix +from ...core.pathmap import PathMapping +from ...schemas import PlaylistNode +from . import beatgrid +from .locations import os_path_to_location, resolve_path + +# Traktor's POPM frame owner: an ID3 rating is per-owner, so writing under +# this email is what makes the stars show up in Traktor itself. +TRAKTOR_POPM_EMAIL = "traktor@native-instruments.de" + + +class PlaylistError(InvalidCommand): + """A command this library cannot accept. + + Subclasses the generic `InvalidCommand` so the HTTP layer maps it without + knowing Traktor exists; the name is kept because it is what every call site + and the fidelity tests already catch. + """ + + +@dataclass +class FileTagResult: + track_id: str + file: str + ok: bool + status: str # "written" | "file-not-found" | "unsupported-format" | "error" + detail: str = "" + + +class TraktorStore: + 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 + # Every edit this session, at field resolution: drives the file-tag sync, + # the version-history message, and (later) undo. + self._journal = EditJournal() + # track_id -> (image_bytes, mime) of staged replacement cover art + self._track_art: dict[str, tuple[bytes, str]] = {} + self.dirty = False + + def _note( + self, + category: str, + detail: str | None = None, + track_id: str | None = None, + target: str | None = None, + ) -> None: + """Record one command in the edit journal. + + `category` names the scope and `detail` the operation; playlists carry + their name as the target instead of a track id, and a remap carries its + count. `target` optionally names the field/slot/marker touched. + """ + if category.startswith("playlist-"): + self._journal.record("playlist", category.split("-", 1)[1], detail) + elif category == "remap": + self._journal.record("library", "remap", after=detail) + elif category == "hotcue": + self._journal.record("cue", detail or "modify", track_id, target) + else: + self._journal.record(category, detail or "edit", track_id, target) + + 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, + kind="playlist", + count=len(keys), + selectable=True, + can_add_tracks=True, + can_reorder=True, + can_rename=True, + can_delete=True, + ) + if ntype == "SMARTLIST" or node.smartplaylist is not None: + # Rule-based, so it has no static entry list to show or edit. + return PlaylistNode( + id="sl:" + "/".join(parent_path + [name]), name=name, kind="smart" + ) + path = parent_path + [name] + return PlaylistNode( + id="fld:" + "/".join(path), + name=name, + kind="folder", + children=[self._to_model(c, path) for c in self._children(node)], + can_contain_children=True, + can_rename=True, + can_delete=True, + ) + + @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._note("playlist-create", name) + self.dirty = True + return new_uuid + + def create_folder(self, name: str, parent_id: str | None = None) -> str: + """Create a playlist FOLDER and return its synthetic id. + + A folder has no UUID of its own in the NML — it is identified by its path + of names — so the id is built the same way `_to_model` builds it, and the + two must agree or the folder will be invisible to the very next call. + + An existing folder of the same name in the same parent is RETURNED rather + than duplicated. Import creates a folder named after the drive, and a + second import from the same stick should land beside the first rather + than next to an identically-named twin. + """ + self._check_folder_name(name) + with self._lock: + parent = self._find_folder(parent_id) + existing = next( + ( + c + for c in self._children(parent) + if (c.type or "FOLDER") == "FOLDER" and c.name == name + ), + None, + ) + prefix = parent_id[len("fld:"):] if parent_id and parent_id.startswith("fld:") else "" + folder_id = "fld:" + "/".join([p for p in (prefix, name) if p]) + if existing is not None: + return folder_id + if parent.subnodes is None: + parent.subnodes = Subnodestype(node=[], count=0) + parent.subnodes.node.append( + Nodetype(type="FOLDER", name=name, subnodes=Subnodestype(node=[], count=0)) + ) + parent.subnodes.count = len(parent.subnodes.node) + self._note("playlist-create-folder", name) + self.dirty = True + return folder_id + + @staticmethod + def _check_folder_name(name: str) -> None: + # A folder is addressed by its path of names, so a "/" in one would + # split it into two path segments and the folder could never be found. + if not name: + raise PlaylistError("A folder needs a name") + if "/" in name: + raise PlaylistError('A folder name cannot contain "/"') + + def _rename_folder(self, folder_id: str, name: str) -> None: + """Rename a folder. Its id is its path, so the id changes with it — + and a sibling folder of the same name would make both unaddressable, + so that is refused rather than silently merged.""" + self._check_folder_name(name) + node = self._find_folder(folder_id) + if node is self._root(): + raise PlaylistError("Cannot rename the root folder") + parent = self._find_parent_of(node) + if any( + c is not node and (c.type or "FOLDER") == "FOLDER" and c.name == name + for c in self._children(parent) + ): + raise PlaylistError(f'There is already a folder called "{name}" here') + node.name = name + self._note("playlist-rename", name) + self.dirty = True + + def rename_playlist(self, playlist_uuid: str, name: str) -> None: + with self._lock: + if playlist_uuid.startswith("fld:"): + self._rename_folder(playlist_uuid, name) + return + node = self._find_playlist_node(playlist_uuid) + if node is None: + raise PlaylistError(f"Playlist not found: {playlist_uuid}") + node.name = name + self._note("playlist-rename", name) + self.dirty = True + + def delete_playlist(self, playlist_uuid: str) -> None: + """Delete a playlist, or a FOLDER and everything nested in it. + + A folder is addressed by its synthetic `fld:` path id. Removing its node + removes its subtree with it — the NML nests children inside the parent's + SUBNODES, so there is nothing elsewhere to clean up; the tracks stay in + the collection. + """ + with self._lock: + if playlist_uuid.startswith("fld:"): + if playlist_uuid == "fld:": + raise PlaylistError("Cannot delete the root folder") + node = self._find_folder(playlist_uuid) + else: + 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._note("playlist-delete", node.name) + 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._note("playlist-entries", node.name) + 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._journal.record("track", "set", track_id, k) + self.dirty = True + + # ---- adding tracks -------------------------------------------------- + def add_entry(self, track, audio_path: Path) -> str: + """Append a brand-new ENTRY for `audio_path` and return its track id. + + The one place Konduktor builds a collection entry instead of editing one + Traktor wrote. Two rules make that safe: + + * **Append only.** The new ENTRY goes on the end of COLLECTION and + nothing else is touched, so every existing entry still renders the + bytes it was parsed from. `test_save_fidelity.py` checks exactly + that rather than trusting it. + * **The primary key must be free.** Traktor keys playlist entries on + ``volume+dir+file``, so two ENTRYs sharing one is a corrupt + collection, not a duplicate track. Importing copies audio to a fresh + filename, which is what keeps repeat imports honest. + + Deliberately left empty: ``audio_id`` (Traktor's analysis fingerprint) + and ``loudness``. Both are outputs of Traktor's own analysis and cannot + be computed here; Traktor re-analyses a track that has none. Writing a + plausible-looking fingerprint would be inventing data. + """ + with self._lock: + volume, dir_, file = os_path_to_location(Path(audio_path)) + key = f"{volume}{dir_}{file}" + if key in self._entry_by_key: + raise PlaylistError( + f"The collection already has an entry for {audio_path}" + ) + + info = Infotype( + genre=getattr(track, "genre", None) or None, + label=getattr(track, "label", None) or None, + comment=getattr(track, "comment", None) or None, + remixer=getattr(track, "remixer", None) or None, + producer=getattr(track, "producer", None) or None, + mix=getattr(track, "mix", None) or None, + key=getattr(track, "key", None) or None, + bitrate=getattr(track, "bitrate", None) or None, + playcount=getattr(track, "playcount", None) or None, + release_date=getattr(track, "release_date", None) or None, + import_date=getattr(track, "import_date", None) or None, + # Traktor's RANKING is stars x 51; an unrated track has no + # attribute at all rather than a zero. + ranking=(max(0, min(5, int(getattr(track, "rating", 0) or 0))) * 51) or None, + playtime=getattr(track, "length", None) or None, + ) + album = None + if getattr(track, "album", None): + album = Albumtype(title=track.album) + + bpm = getattr(track, "bpm", None) + entry = Entrytype( + location=Locationtype(volume=volume, dir=dir_, file=file), + title=getattr(track, "title", None) or None, + artist=getattr(track, "artist", None) or None, + album=album, + info=info, + # TEMPO mirrors the first grid marker. It is set here from the + # projected BPM so a track with no grid still shows a tempo; + # `replace_grid` overwrites it from the markers when they land. + tempo=Tempotype(bpm=float(bpm)) if bpm else None, + cue_v2=[], + ) + self._nml.collection.entry.append(entry) + self._entry_by_key[key] = entry + # `` is a real count Traktor writes and + # reads, not decoration. No existing command changes how many + # entries there are, so nothing has ever had to maintain it — + # leaving it stale is a corrupt file that still looks well-formed. + self._nml.collection.entries = len(self._nml.collection.entry) + self._note("track", "add", key) + self.dirty = True + return key + + def remove_entries(self, track_ids: list[str]) -> int: + """Remove tracks from the collection AND from every playlist; return + how many ENTRYs went. + + The mirror of `add_entry`, with the same care about bytes: only the + removed ENTRYs, the `` count and the playlists that + actually referenced a removed track change — any other playlist is left + alone rather than rebuilt, so it still renders what it was parsed from. + + Playlists must be purged too: a PRIMARYKEY naming a track that is no + longer in COLLECTION is a dangling reference, not an empty slot. The + audio file is never touched — this is the library's record of the track, + like Traktor's own "Delete from Collection". + + Matches by primary key in DOCUMENT order, so two ENTRYs sharing a key + (which `iter_entries` warns can happen) both go, where the key→entry + dict would have found only one. + """ + gone = set(track_ids) + with self._lock: + before = self._nml.collection.entry + kept = [e for e in before if self._key_of(e) not in gone] + removed = len(before) - len(kept) + if removed == 0: + return 0 + self._nml.collection.entry = kept + self._nml.collection.entries = len(kept) + for key in gone: + if self._entry_by_key.pop(key, None) is not None: + self._track_art.pop(key, None) + self._note("track", "remove", key) + for n in self._iter_nodes(self._root()): + pl = n.playlist + if pl is None or not pl.entry: + continue + entries = [ + e for e in pl.entry + if not (e.primarykey is not None and e.primarykey.key in gone) + ] + if len(entries) != len(pl.entry): + pl.entry = entries + pl.entries = len(entries) + self.dirty = True + return removed + + @staticmethod + def _key_of(entry) -> str | None: + loc = entry.location + return f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}" if loc else None + + def iter_entries(self): + """Every collection ENTRY in document order. + + Document order, not ``_entry_by_key.values()``: two entries can share a + primary key, and the dict would silently drop one of them. + """ + with self._lock: + return list(self._nml.collection.entry) + + def stem_keys(self) -> set[str]: + """Track ids whose ENTRY has a child. + + Playlist entries for these use ``PRIMARYKEY TYPE="STEM"`` (verified + 945/945 against the real collection); everything else uses ``TRACK``. + """ + with self._lock: + return { + f"{e.location.volume or ''}{e.location.dir or ''}{e.location.file or ''}" + for e in self._nml.collection.entry + if e.location and getattr(e, "stems", None) is not None + } + + def entries_for(self, track_ids: list[str]) -> list[tuple[str, str]]: + """Pair each known track id with its PRIMARYKEY TYPE, dropping unknowns.""" + stems = self.stem_keys() + with self._lock: + known = self._entry_by_key + return [ + (tid, "STEM" if tid in stems else "TRACK") + for tid in track_ids + if tid in known + ] + + 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 + label: on create it falls back to Traktor's "n.n."; on a replace, None + keeps the old label (a hand move is still the same cue) while a name + renames it (Auto Hotcues' Replace puts a DIFFERENT cue in the slot, and + keeping "Drop 1" on a cue now at "Drop 1 -16" would mislabel it).""" + 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 + if name is not None: + existing.name = name + 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, + ) + ) + # "add" only when it's a genuinely new hotcue; repositioning/retyping + # an existing slot is a "modify" (keeps the net add/remove count honest). + self._note( + "hotcue", "modify" if existing is not None else "add", track_id, f"slot:{slot}" + ) + 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._note("hotcue", "modify", track_id, f"slot:{slot}") + self.dirty = True + + def delete_hotcue(self, track_id: str, slot: int) -> None: + with self._lock: + entry = self._entry_or_raise(track_id) + before = entry.cue_v2 or [] + entry.cue_v2 = [c for c in before if c.hotcue != slot] + if len(entry.cue_v2) != len(before): # only count an actual removal + self._note("hotcue", "delete", track_id, f"slot:{slot}") + self.dirty = True + + # ---- beatgrid ----------------------------------------------------- + # A beatgrid is an ORDERED LIST of markers (see beatgrid.py); a constant + # grid is a list of length one. Markers are addressed by their index in that + # start-ordered list. CUE_V2 has no id attribute and save() reparses the + # whole file, so any synthetic id would have to be rebuilt by position + # anyway — the index IS the identity. + _MARKER_MIN_GAP_MS = 1.0 + + @staticmethod + def _grid_marker(entry: Entrytype) -> CueV2Type | None: + """The first grid marker BY START — the one mirrors.""" + return beatgrid.first_marker(entry) + + @staticmethod + def _sync_tempo(entry: Entrytype) -> None: + """Mirror from the first marker (7968/7968 in the reference + collection). Called last by every grid mutator, so a move that changes + which marker is first re-mirrors for free. + + With no markers left, TEMPO is LEFT ALONE: Traktor keeps the analysed + BPM on gridless tracks (53 such entries exist in the reference file). + """ + marker = beatgrid.first_marker(entry) + if marker is None or marker.grid is None or not marker.grid.bpm: + return + if entry.tempo is None: + entry.tempo = Tempotype(bpm=marker.grid.bpm, bpm_quality=100.0) + else: + entry.tempo.bpm = marker.grid.bpm + + @staticmethod + def _sort_cues(entry: Entrytype) -> None: + """Keep CUE_V2 ascending by START — true for 8485/8485 reference + entries, so an inserted marker must not become the one exception. + Stable, so a marker stays ahead of a companion at an identical START. + """ + if entry.cue_v2: + entry.cue_v2.sort(key=lambda c: c.start or 0.0) + + def _markers_or_raise( + self, entry: Entrytype, index: int + ) -> tuple[list[CueV2Type], CueV2Type]: + markers = beatgrid.grid_markers(entry) + if not markers: + raise PlaylistError("Track has no beatgrid") + if not 0 <= index < len(markers): + raise PlaylistError( + f"Grid marker {index} out of range (track has {len(markers)})" + ) + return markers, markers[index] + + def _drop_grid(self, entry: Entrytype) -> None: + """Remove every marker AND every companion. No _note — callers do that.""" + doomed = {id(m) for m in beatgrid.grid_markers(entry)} + doomed |= {id(c) for c in beatgrid.companions(entry).values()} + entry.cue_v2 = [c for c in (entry.cue_v2 or []) if id(c) not in doomed] + + def add_grid_marker( + self, + track_id: str, + start_sec: float, + bpm: float | None = None, + name: str | None = None, + ) -> int: + """Add a beatgrid marker at `start_sec`; returns its index. + + With `bpm` unset the marker INHERITS the tempo of the section it lands + in, so splitting a section is musically a no-op until it's retempoed. + Creates no companion cue — Traktor tolerates markers without one, and + inventing them would silently consume the user's hotcue slots. + """ + if bpm is not None and bpm <= 0: + raise PlaylistError(f"BPM must be positive: {bpm}") + with self._lock: + entry = self._entry_or_raise(track_id) + start_ms = max(0.0, start_sec * 1000.0) + markers = beatgrid.grid_markers(entry) + for m in markers: + if abs((m.start or 0.0) - start_ms) < self._MARKER_MIN_GAP_MS: + raise PlaylistError("A grid marker already exists at that position") + if bpm is None: + bpm = self._bpm_governing(entry, start_ms) + if 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=name or ("AutoGrid" if not markers else "n.n."), + displ_order=0, + type=4, + start=start_ms, + len=0.0, + repeats=-1, + hotcue=-1, + color=None, + grid=GridType(bpm=bpm), + ) + ) + self._sort_cues(entry) + self._sync_tempo(entry) + self._note("grid", "marker-add", track_id) + self.dirty = True + return next( + i + for i, m in enumerate(beatgrid.grid_markers(entry)) + if abs((m.start or 0.0) - start_ms) < 1e-9 + ) + + @staticmethod + def _bpm_governing(entry: Entrytype, start_ms: float) -> float | None: + """The tempo in force at `start_ms`: the last marker at or before it, + else the first marker (extrapolated backwards), else .""" + markers = beatgrid.grid_markers(entry) + if not markers: + return entry.tempo.bpm if entry.tempo else None + governing = markers[0] + for m in markers: + if (m.start or 0.0) <= start_ms: + governing = m + else: + break + return governing.grid.bpm if governing.grid else None + + def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> None: + """Move marker `index`, DRAGGING ITS COMPANION with it. + + The new position is CLAMPED between the neighbouring markers rather than + allowed to reorder them, so an index can never go stale mid-edit. Phase + nudges are +/-1 and +/-10 ms, so this is no practical constraint; + restructuring a grid is add-then-delete. + """ + with self._lock: + entry = self._entry_or_raise(track_id) + markers, marker = self._markers_or_raise(entry, index) + start_ms = max(0.0, start_sec * 1000.0) + if index > 0: + lo = (markers[index - 1].start or 0.0) + self._MARKER_MIN_GAP_MS + start_ms = max(start_ms, lo) + if index < len(markers) - 1: + hi = (markers[index + 1].start or 0.0) - self._MARKER_MIN_GAP_MS + start_ms = min(start_ms, hi) + companion = beatgrid.companions(entry).get(index) + marker.start = start_ms + if companion is not None: + # Copy the float — never recompute from seconds. A 1-ULP drift + # here would change the rendered bytes and break byte-reverts. + companion.start = marker.start + self._sync_tempo(entry) + self._note("grid", "marker-move", track_id, f"marker:{index}") + self.dirty = True + + def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> None: + """Set marker `index`'s tempo (governs until the next marker).""" + if bpm <= 0: + raise PlaylistError(f"BPM must be positive: {bpm}") + with self._lock: + entry = self._entry_or_raise(track_id) + _, marker = self._markers_or_raise(entry, index) + if marker.grid is None: + marker.grid = GridType(bpm=bpm) + else: + marker.grid.bpm = bpm + self._sync_tempo(entry) + self._note("grid", "marker-bpm", track_id, f"marker:{index}") + self.dirty = True + + def delete_grid_marker(self, track_id: str, index: int) -> None: + """Remove marker `index` and its companion (freeing that hotcue slot).""" + with self._lock: + entry = self._entry_or_raise(track_id) + markers, marker = self._markers_or_raise(entry, index) + companion = beatgrid.companions(entry).get(index) + doomed = {id(marker)} | ({id(companion)} if companion is not None else set()) + entry.cue_v2 = [c for c in (entry.cue_v2 or []) if id(c) not in doomed] + self._sync_tempo(entry) + # Removing the last marker IS deleting the grid — report it as one. + self._note( + "grid", + "delete" if len(markers) == 1 else "marker-delete", + track_id, + f"marker:{index}", + ) + self.dirty = True + + def replace_grid( + self, track_id: str, markers: list[tuple[float, float]] + ) -> None: + """Throw the grid away and rebuild it from `markers` [(start_sec, bpm)]. + + Serves both Auto Grid (a single marker) and the deck's Reset (restore + the list as loaded) as one atomic, single-event command. Companions of + the old grid go with it; none are created. + """ + for start_sec, bpm in markers: + if bpm <= 0: + raise PlaylistError(f"BPM must be positive: {bpm}") + with self._lock: + entry = self._entry_or_raise(track_id) + self._drop_grid(entry) + if entry.cue_v2 is None: + entry.cue_v2 = [] + for i, (start_sec, bpm) in enumerate( + sorted(markers, key=lambda m: m[0]) + ): + entry.cue_v2.append( + CueV2Type( + name="AutoGrid" if i == 0 else "n.n.", + displ_order=0, + type=4, + start=max(0.0, start_sec * 1000.0), + len=0.0, + repeats=-1, + hotcue=-1, + color=None, + grid=GridType(bpm=bpm), + ) + ) + self._sort_cues(entry) + self._sync_tempo(entry) + self._note("grid", "replace", track_id) + self.dirty = True + + def place_grid_companion( + self, track_id: str, index: int, *, prefer_slot: int = 0 + ) -> int | None: + """Give marker `index` the white beat-1 hotcue Traktor writes beside its + own markers: `prefer_slot` when free, else the lowest free slot. + + Returns the slot used, or None when the bank is full or the marker + already has a companion. NEVER overwrites. This is the ONLY place + Konduktor creates a companion — grid edits never do — because it is a + deliberate, user-invoked feature (Auto Grid), not a side effect. + """ + with self._lock: + entry = self._entry_or_raise(track_id) + _, marker = self._markers_or_raise(entry, index) + if index in beatgrid.companions(entry): + return None + used = { + c.hotcue + for c in (entry.cue_v2 or []) + if c.hotcue is not None and c.hotcue >= 0 + } + slot = next( + (s for s in [prefer_slot, *range(8)] if 0 <= s <= 7 and s not in used), + None, + ) + if slot is None: + return None + entry.cue_v2.append( + CueV2Type( + name=marker.name or "AutoGrid", + displ_order=0, + type=0, + start=marker.start, # copy the float, not start_sec * 1000 + len=0.0, + repeats=-1, + hotcue=slot, + color=beatgrid.COMPANION_COLOR, + grid=None, + ) + ) + self._sort_cues(entry) + self._note("grid", "marker-add", track_id) + self.dirty = True + return slot + + def delete_grid(self, track_id: str) -> None: + """Remove EVERY grid marker AND EVERY companion; is kept. + + Dropping companions is the debris fix: the old code stripped markers + only, leaving orphan white cues squatting in hotcue slots. + """ + with self._lock: + entry = self._entry_or_raise(track_id) + self._drop_grid(entry) + self._note("grid", "delete", track_id) + 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._note("lock", "on" if locked else "off", track_id) + 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. + """ + + if loc is None: + return None + base = 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 ...core import audio_tags as 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 + + + 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(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.""" + + 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 = 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) -> dict[str, str]: + """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 ``{old track id: new track id}`` for every track + rewritten — callers holding ids (export sets) follow them with it, and + must not rebuild it from paths; the caller saves. + """ + + if mapping.empty: + return {} + with self._lock: + key_remap: dict[str, str] = {} + for e in self._nml.collection.entry: + loc = e.location + if not loc: + continue + base = 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 {} + # 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] + # Track ids derive from the LOCATION, so a remap renames them. Carry + # this session's journal entries across or their file-tag sync is lost. + for old_key, new_key in key_remap.items(): + self._journal.retarget(old_key, new_key) + self._note("remap", str(len(key_remap))) + self.dirty = True + return 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: + 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() + # Computed before _load() clears the journal. Versioning the bytes is + # the app's job, not the adapter's — see app_state.AppState.save. + summary = self._edit_summary() + self._load() # clears dirty + the edit journal + staged art + return SaveOutcome(summary=summary, snapshot=new_data, tag_results=tag_results) + + def _edit_summary(self) -> str: + """Delegates to the journal; kept as a method because save() and the + tests reach for it by this name.""" + return self._journal.summary(extra_tracks=set(self._track_art)) + + def _sync_file_tags(self) -> list["FileTagResult"]: + from ...core import audio_tags as file_tags + + results: list[FileTagResult] = [] + # Union of tracks with edited fields and/or replaced art. + for track_id in self._journal.edited_tracks() | 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 + # Report BOTH writes: a failed tag write must not be masked by a + # successful art write on the same track. + written = [] + if fields := self._journal.fields_for(track_id): + meta = {f: self._entry_field_value(entry, f) for f in fields} + written.append(file_tags.write_tags(path, meta, popm_email=TRAKTOR_POPM_EMAIL)) + if track_id in self._track_art: + data, mime = self._track_art[track_id] + written.append(file_tags.write_cover(path, data, mime)) + for r in written: + 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") diff --git a/backend/konduktor/app_state.py b/backend/konduktor/app_state.py new file mode 100644 index 0000000..96916b6 --- /dev/null +++ b/backend/konduktor/app_state.py @@ -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 diff --git a/backend/konduktor/auto_hotcues.py b/backend/konduktor/auto_hotcues.py deleted file mode 100644 index 55b5e45..0000000 --- a/backend/konduktor/auto_hotcues.py +++ /dev/null @@ -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 diff --git a/backend/konduktor/collection_service.py b/backend/konduktor/collection_service.py deleted file mode 100644 index fbd545a..0000000 --- a/backend/konduktor/collection_service.py +++ /dev/null @@ -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 diff --git a/backend/konduktor/core/__init__.py b/backend/konduktor/core/__init__.py new file mode 100644 index 0000000..2dad5af --- /dev/null +++ b/backend/konduktor/core/__init__.py @@ -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. +""" diff --git a/backend/konduktor/core/adapter.py b/backend/konduktor/core/adapter.py new file mode 100644 index 0000000..7f981a4 --- /dev/null +++ b/backend/konduktor/core/adapter.py @@ -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: ... diff --git a/backend/konduktor/file_tags.py b/backend/konduktor/core/audio_tags.py similarity index 88% rename from backend/konduktor/file_tags.py rename to backend/konduktor/core/audio_tags.py index c82d52e..bee8dc5 100644 --- a/backend/konduktor/file_tags.py +++ b/backend/konduktor/core/audio_tags.py @@ -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/. - """ - 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() diff --git a/backend/konduktor/core/auto_hotcues.py b/backend/konduktor/core/auto_hotcues.py new file mode 100644 index 0000000..46dc46a --- /dev/null +++ b/backend/konduktor/core/auto_hotcues.py @@ -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 diff --git a/backend/konduktor/core/capabilities.py b/backend/konduktor/core/capabilities.py new file mode 100644 index 0000000..a29e223 --- /dev/null +++ b/backend/konduktor/core/capabilities.py @@ -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 diff --git a/backend/konduktor/core/edit_journal.py b/backend/konduktor/core/edit_journal.py new file mode 100644 index 0000000..eedc00a --- /dev/null +++ b/backend/konduktor/core/edit_journal.py @@ -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:] diff --git a/backend/konduktor/core/export.py b/backend/konduktor/core/export.py new file mode 100644 index 0000000..1913929 --- /dev/null +++ b/backend/konduktor/core/export.py @@ -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 `` 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} diff --git a/backend/konduktor/core/folder.py b/backend/konduktor/core/folder.py new file mode 100644 index 0000000..2208d2d --- /dev/null +++ b/backend/konduktor/core/folder.py @@ -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() diff --git a/backend/konduktor/core/grid_detect.py b/backend/konduktor/core/grid_detect.py new file mode 100644 index 0000000..040e973 --- /dev/null +++ b/backend/konduktor/core/grid_detect.py @@ -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) diff --git a/backend/konduktor/core/model.py b/backend/konduktor/core/model.py new file mode 100644 index 0000000..b000713 --- /dev/null +++ b/backend/konduktor/core/model.py @@ -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 diff --git a/backend/konduktor/path_mapping.py b/backend/konduktor/core/pathmap.py similarity index 63% rename from backend/konduktor/path_mapping.py rename to backend/konduktor/core/pathmap.py index e7efd10..e440b1b 100644 --- a/backend/konduktor/path_mapping.py +++ b/backend/konduktor/core/pathmap.py @@ -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 diff --git a/backend/konduktor/core/places.py b/backend/konduktor/core/places.py new file mode 100644 index 0000000..b0ba148 --- /dev/null +++ b/backend/konduktor/core/places.py @@ -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()) diff --git a/backend/konduktor/core/query.py b/backend/konduktor/core/query.py new file mode 100644 index 0000000..406f95b --- /dev/null +++ b/backend/konduktor/core/query.py @@ -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], + ) diff --git a/backend/konduktor/core/registry.py b/backend/konduktor/core/registry.py new file mode 100644 index 0000000..4105d8b --- /dev/null +++ b/backend/konduktor/core/registry.py @@ -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) diff --git a/backend/konduktor/core/structure.py b/backend/konduktor/core/structure.py new file mode 100644 index 0000000..70222af --- /dev/null +++ b/backend/konduktor/core/structure.py @@ -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 diff --git a/backend/konduktor/exporter.py b/backend/konduktor/exporter.py new file mode 100644 index 0000000..50056f2 --- /dev/null +++ b/backend/konduktor/exporter.py @@ -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 `` 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", +] diff --git a/backend/konduktor/exports.py b/backend/konduktor/exports.py new file mode 100644 index 0000000..0db0924 --- /dev/null +++ b/backend/konduktor/exports.py @@ -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 `` 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 diff --git a/backend/konduktor/history.py b/backend/konduktor/history.py index 451c1b0..22e73ce 100644 --- a/backend/konduktor/history.py +++ b/backend/konduktor/history.py @@ -10,7 +10,7 @@ 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 a fixed name inside each repo (``collection.nml``); the + * 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). @@ -32,7 +32,17 @@ from . import paths log = logging.getLogger(__name__) -_TRACKED_NAME = "collection.nml" +_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 " @@ -53,8 +63,8 @@ def _repo_dir(nml_path: Path) -> Path: return paths.app_data_dir() / "history" / _key(nml_path) -def _tracked_file(repo_dir: Path) -> Path: - return repo_dir / _TRACKED_NAME +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: @@ -77,7 +87,25 @@ def _open_or_init(nml_path: Path) -> Path: return repo_dir -def _head_blob(repo: Repo) -> bytes | None: +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() @@ -85,7 +113,10 @@ def _head_blob(repo: Repo) -> bytes | None: return None commit = repo[head] tree = repo[commit.tree] - _mode, blob_sha = tree[_TRACKED_NAME.encode()] + try: + _mode, blob_sha = _tree_blob(tree, nml_path) + except KeyError: + return None return repo[blob_sha].data @@ -98,9 +129,9 @@ def commit(nml_path: Path, data: bytes, message: str, app_version: str) -> str | try: repo_dir = _open_or_init(nml_path) with Repo(str(repo_dir)) as repo: - if _head_blob(repo) == data: + if _head_blob(repo, nml_path) == data: return None # nothing changed since last version - path = _tracked_file(repo_dir) + 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() @@ -153,7 +184,7 @@ def read_version(nml_path: Path, commit_id: str) -> bytes | None: with Repo(str(repo_dir)) as repo: c = repo[commit_id.encode()] tree = repo[c.tree] - _mode, blob_sha = tree[_TRACKED_NAME.encode()] + _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) diff --git a/backend/konduktor/importer.py b/backend/konduktor/importer.py new file mode 100644 index 0000000..ccf5d5d --- /dev/null +++ b/backend/konduktor/importer.py @@ -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 diff --git a/backend/konduktor/jobs.py b/backend/konduktor/jobs.py new file mode 100644 index 0000000..f38e79b --- /dev/null +++ b/backend/konduktor/jobs.py @@ -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() diff --git a/backend/konduktor/library_id.py b/backend/konduktor/library_id.py new file mode 100644 index 0000000..9166281 --- /dev/null +++ b/backend/konduktor/library_id.py @@ -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 diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index fbd3063..93839d1 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -11,33 +11,67 @@ from pathlib import Path from fastapi import FastAPI, File, Form, HTTPException, Query, Response, UploadFile from fastapi.middleware.cors import CORSMiddleware -from fastapi.responses import FileResponse +from fastapi.responses import FileResponse, JSONResponse -from . import __version__ -from . import auto_hotcues as ah -from . import history, prefs -from .collection_service import CollectionService -from .discovery import describe, detect_collections -from .path_mapping import PathMapping -from .playlist_store import PlaylistError, PlaylistStore +from . import __version__, exporter, exports, history, prefs +from .app_state import STATE +from .core import auto_hotcues as ah +from .core import grid_detect, structure +from . import importer +from .core import export as core_export +from .core import places, registry +from .core.folder import FolderScanner, FolderSource +from .core.adapter import ( + AdapterError, + InvalidCommand, + LibraryAdapter, + LibraryNotSupported, + NotFound, + Unsupported, +) +from .core.capabilities import Capabilities +from .jobs import JOBS +from .core.pathmap import PathMapping from .schemas import ( + AutoGridBatchRequest, AutoGridRequest, + AutoCueOutcome, AutoHotcue, + AutoHotcuesBatchRequest, + TrackIds, AutoHotcuesRequest, + AutoHotcuesResult, CollectionCandidate, CollectionOptions, CollectionStatus, CreatePlaylist, - CuePoint, EditState, + LibraryInfo, + PlatformOption, EditTrack, Facets, FileTagOutcome, + CreateExportSet, + ExportContents, + ExportPlaylistOut, + ExportSetMembers, + ExportSetOut, + ExportPreview, + Drive, + FolderAddRequest, + FolderTracks, FsEntry, FsListing, - GridEdit, + FsPlace, + UpdateExportSet, + AddGridMarker, + GridMarkerEdit, + ReplaceGrid, HistoryEntry, + ImportRequest, + JobStatus, OpenCollection, + OpenSource, PathMappingInfo, PlaylistNode, PrefixSuggestions, @@ -46,9 +80,11 @@ from .schemas import ( RenamePlaylist, SaveResult, SetEntries, - SetHotcue, - SetHotcueType, - SetLock, + SourceCandidate, + SourceStatus, + SetCue, + SetCueType, + SetGridLock, Stats, Track, TrackCues, @@ -72,161 +108,161 @@ app.add_middleware( ) -class AppState: - """Holds the currently-loaded collection (selectable at runtime).""" - - def __init__(self) -> None: - self.path: Path | None = None - self.service: CollectionService | None = None - self.store: PlaylistStore | None = None - - @property - def loaded(self) -> bool: - return self.service is not None - - def open(self, path: Path) -> None: - # Both raise on an invalid/parse-incompatible or playlist-less file; - # only commit to the new collection if BOTH succeed. - service = CollectionService(path) - store = PlaylistStore(path) - # Apply this collection's saved OS-path remapping (per-machine, keyed by - # the collection's local path) so runtime translation is live on open. - saved = prefs.get_path_mapping(str(path)) - if saved: - store.set_path_mapping(PathMapping.make(saved["from"], saved["to"])) - self.path, self.service, self.store = path, service, store - # Version history: record an "as I found it" baseline (deduped, so - # re-opening an unchanged collection is a no-op). Best-effort. - history.ensure_baseline(path) - - -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 - - -def require_service() -> CollectionService: +def require_adapter() -> LibraryAdapter: + """The loaded library, or a 409. Routes talk to this and nothing else.""" if not STATE.loaded: raise HTTPException(409, "No collection loaded") - assert STATE.service is not None - return STATE.service + assert STATE.adapter is not None + return STATE.adapter -def require_store() -> PlaylistStore: - if not STATE.loaded: - raise HTTPException(409, "No collection loaded") - assert STATE.store is not None - return STATE.store +@app.exception_handler(AdapterError) +def _adapter_error(_request, exc: AdapterError): + """Map the adapter's error vocabulary onto status codes in one place, so no + route has to guess whether a given failure is a 400 or a 404.""" + status = { + NotFound: 404, + InvalidCommand: 400, + Unsupported: 422, + LibraryNotSupported: 400, + }.get(type(exc), 400) + return JSONResponse(status_code=status, content={"detail": str(exc)}) # ---- collection selection --------------------------------------------- -@app.get("/api/collection", response_model=CollectionStatus) +@app.get("/api/library", response_model=CollectionStatus) def collection_status() -> CollectionStatus: if not STATE.loaded: return CollectionStatus(loaded=False) return CollectionStatus( loaded=True, path=str(STATE.path), - tracks=len(require_service().tracks), - playlists=require_store().count_playlists(), + tracks=len(require_adapter().tracks), + playlists=require_adapter().playlist_count(), + library=_library_info(), ) -@app.post("/api/collection/open", response_model=CollectionStatus) +@app.post("/api/library/open", response_model=CollectionStatus) def open_collection(body: OpenCollection) -> CollectionStatus: path = Path(body.path).expanduser() - if not path.exists() or not path.is_file(): - raise HTTPException(400, f"File not found: {path}") + # Deliberately NOT `is_file()`. A library is a file on some platforms and a + # DIRECTORY on others — OneLibrary's is the drive, Serato's will be a + # `_Serato_` folder — and which shapes are valid is the driver's business. + # This checks only that the path is there at all; `can_open()` decides. + if not path.exists(): + raise HTTPException(400, f"Not found: {path}") + # A running analysis writes into the library being replaced; stop it. + for kind in BATCH_JOBS: + for job in JOBS.active(kind): + JOBS.cancel(job.id) try: STATE.open(path) - except PlaylistError as ex: - raise HTTPException(400, f"Not a valid Traktor collection: {ex}") + except AdapterError as ex: + raise HTTPException(400, f"Not a valid collection: {ex}") except Exception as ex: # noqa: BLE001 - raise HTTPException(400, f"Could not parse as a Traktor collection: {ex}") - prefs.set_last_collection(str(path)) + raise HTTPException(400, f"Could not open that collection: {ex}") + prefs.set_last_collection(str(path), require_adapter().capabilities().platform) return collection_status() -@app.get("/api/collection/options", response_model=CollectionOptions) -def collection_options() -> CollectionOptions: - """Startup shortcuts for the picker: the best auto-detected Traktor - collection and the last one opened (may no longer exist → exists=False).""" - detected = detect_collections() - auto = CollectionCandidate(**detected[0]) if detected else None +@app.get("/api/library/options", response_model=CollectionOptions) +def collection_options(platform: str | None = None) -> CollectionOptions: + """Startup shortcuts for the picker, scoped to one platform. + + Scoped because the picker asks which platform first, and both shortcuts are + only meaningful inside that answer: unscoped, "auto" meant "whatever the + first-registered driver happened to find" — so a plugged-in USB stick could + be offered as the user's collection — and "last opened" could name a library + of the platform they had just declined. + + `recent` may no longer exist (→ `exists=False`), which the picker shows + rather than hides: a library that has moved is worth saying so about. + """ + detected = registry.detect_for(platform) if platform else registry.detect_all() + candidates = [CollectionCandidate(**d) for d in detected] recent = None - last = prefs.get_last_collection() + last = prefs.get_last_collection(platform) if last: - recent = CollectionCandidate(**describe(Path(last))) - return CollectionOptions(auto=auto, recent=recent) + recent = CollectionCandidate(**registry.describe(Path(last))) + return CollectionOptions( + auto=candidates[0] if candidates else None, + detected=candidates, + recent=recent, + ) -@app.get("/api/collection/path-mapping", response_model=PathMappingInfo) +@app.get("/api/library/path-mapping", response_model=PathMappingInfo) def get_path_mapping() -> PathMappingInfo: """The current collection's saved OS-path remapping (blank if none).""" - require_store() + require_adapter() saved = prefs.get_path_mapping(str(STATE.path)) if saved: return PathMappingInfo.model_validate({"from": saved["from"], "to": saved["to"]}) return PathMappingInfo() -@app.put("/api/collection/path-mapping", response_model=PathMappingInfo) +@app.put("/api/library/path-mapping", response_model=PathMappingInfo) def put_path_mapping(body: PathMappingInfo) -> PathMappingInfo: """Set (or, with blank prefixes, clear) the current collection's remapping. Persists to userprefs AND updates the live store so playback/analysis re-resolve immediately — no reopen needed. Never touches the .nml.""" - store = require_store() + a = require_adapter() mapping = PathMapping.make(body.from_, body.to) prefs.set_path_mapping( str(STATE.path), mapping.from_prefix or None, mapping.to_prefix or None ) - store.set_path_mapping(mapping) + a.set_path_mapping(mapping) return PathMappingInfo.model_validate( {"from": mapping.from_prefix, "to": mapping.to_prefix} ) -@app.get("/api/collection/path-mapping/suggest", response_model=PrefixSuggestions) +@app.get("/api/library/path-mapping/suggest", response_model=PrefixSuggestions) def suggest_path_prefix() -> PrefixSuggestions: """Auto-detected `from` prefix candidates (common directory per volume), so the editor can prefill the stored prefix.""" - store = require_store() - return PrefixSuggestions.model_validate(store.path_prefix_suggestions()) + return PrefixSuggestions.model_validate(require_adapter().path_prefix_suggestions()) -@app.get("/api/collection/path-mapping/preview", response_model=RemapPreview) +@app.get("/api/library/path-mapping/preview", response_model=RemapPreview) def preview_path_mapping( from_: str = Query("", alias="from"), to: str = Query("") ) -> RemapPreview: """Validate a candidate mapping before saving/committing: how many tracks match `from` and how many exist at `to`.""" - store = require_store() - return RemapPreview.model_validate(store.remap_preview(PathMapping.make(from_, to))) + return RemapPreview.model_validate( + require_adapter().remap_preview(PathMapping.make(from_, to)) + ) -@app.post("/api/collection/remap-paths", response_model=RemapResult) +@app.post("/api/library/remap-paths", response_model=RemapResult) def remap_paths(body: PathMappingInfo) -> RemapResult: """Write-back: permanently rewrite matching track LOCATIONs (and the playlist references that join to them) to the `to` prefix, then save (a version-history commit is written). Destructive and OS-specific — the UI warns accordingly.""" - store = require_store() mapping = PathMapping.make(body.from_, body.to) if mapping.empty: raise HTTPException(400, "Both a `from` and `to` prefix are required") - count = store.remap_locations(mapping) - if count == 0: + adapter = require_adapter() + # A Traktor track id IS its location, so a remap renames every matching id. + # Follow them, or every export set referencing a remapped track would + # dangle — and dangle SILENTLY, still looking curated while quietly + # exporting fewer tracks than it says. The adapter returns the renames + # itself: rebuilding them here from display paths (which omit the volume) + # could pair up two tracks with the same folder on different drives. + moved = adapter.remap_locations(mapping) + if not moved: return RemapResult(rewritten=0, commit=None) - outcome = store.save() - return RemapResult(rewritten=count, commit=outcome.commit) + if moved and STATE.library_id: + exports.retarget(STATE.library_id, moved) + # Through AppState, not the adapter: this is the one route besides /api/save + # that writes, and skipping it would leave a gap in the version history. + _outcome, commit = STATE.save() + return RemapResult(rewritten=len(moved), commit=commit) @app.get("/api/prefs") @@ -241,13 +277,60 @@ def patch_prefs(patch: dict) -> dict: return prefs.update_prefs(patch) +@app.get("/api/fs/places", response_model=list[FsPlace]) +def fs_places(platform: str | None = None) -> list[FsPlace]: + """Sidebar shortcuts for the file browser: the user's folders, then drives. + + Answered by the server because only it can stat a filesystem, and re-asked + by the client rather than cached: drives come and go while a dialog is open, + and a browser that exists to find a stick you just plugged in has to show it. + + `platform` adds that platform's own default location, which is the likeliest + destination when browsing for one of its libraries. Only for platforms whose + library sits at a fixed path — a removable one's libraries ARE the drives, + which are already listed. + """ + out = [FsPlace(**p) for p in places.user_places()] + out += [FsPlace(**p) for p in places.volume_places()] + if platform: + try: + driver = registry.driver_by_platform(platform) + except LibraryNotSupported: + driver = None + if driver is not None and not getattr(driver, "removable", False): + seen = {p.path for p in out} + try: + found = driver.detect() + except OSError: + found = [] + for candidate in found: + # The place is the folder CONTAINING the library, because a + # place is somewhere you navigate to, not something you pick. + folder = Path(candidate["path"]).parent + if str(folder) in seen or not folder.is_dir(): + continue + seen.add(str(folder)) + out.append( + FsPlace(kind="library", name=candidate.get("label") or folder.name, + path=str(folder)) + ) + return out + + @app.get("/api/fs/list", response_model=FsListing) -def fs_list(path: str | None = None) -> FsListing: - """List directories and .nml files for the in-app file browser.""" +def fs_list(path: str | None = None, platform: str | None = None) -> FsListing: + """List directories and openable library files for the in-app file browser. + + `platform` narrows the files to that platform's own: a Traktor browse that + also listed `master.db` would be offering a file the chosen adapter cannot + open. A platform whose library is a directory contributes no suffixes at + all, so its browse shows folders only. + """ base = Path(path).expanduser() if path else Path.home() if not base.exists() or not base.is_dir(): base = Path.home() base = base.resolve() + suffixes = registry.browsable_suffixes(platform) dirs: list[FsEntry] = [] files: list[FsEntry] = [] try: @@ -257,7 +340,7 @@ def fs_list(path: str | None = None) -> FsListing: try: if entry.is_dir(): dirs.append(FsEntry(name=entry.name, path=str(entry))) - elif entry.suffix.lower() == ".nml": + elif entry.suffix.lower() in suffixes: files.append(FsEntry(name=entry.name, path=str(entry))) except OSError: continue @@ -269,6 +352,221 @@ def fs_list(path: str | None = None) -> FsListing: ) +# ---- export sets ------------------------------------------------------------- +# +# Curation, not library data: a set is Konduktor's own record of what to export, +# where to, and for which platform. Every route is scoped to the LOADED library +# by its stable id, so opening a different collection shows a different shelf and +# moving a collection does not orphan the sets built against it. + + +def _require_library_id() -> str: + require_adapter() + if STATE.library_id is None: # pragma: no cover — loaded implies an id + raise HTTPException(409, "No library is loaded") + return STATE.library_id + + +def _require_set(set_id: str): + found = exports.get(_require_library_id(), set_id) + if found is None: + raise HTTPException(404, f"No export called {set_id}") + return found + + +@app.get("/api/exports", response_model=list[ExportSetOut]) +def list_exports() -> list[ExportSetOut]: + return [ExportSetOut(**s.as_dict()) for s in exports.all_sets(_require_library_id())] + + +@app.post("/api/exports", response_model=ExportSetOut) +def create_export(body: CreateExportSet) -> ExportSetOut: + if not body.destination.strip(): + raise HTTPException(400, "An export needs a destination folder") + # Only platforms that can actually be WRITTEN may be targets. Gating here as + # well as in the UI, because a set persists: one created against a target + # that later stops being supported would otherwise fail at export time. + if body.target not in _export_targets(): + raise HTTPException(422, f"Konduktor cannot export to {body.target} yet") + created = exports.create( + _require_library_id(), + name=body.name, + target=body.target, + destination=body.destination, + ) + return ExportSetOut(**created.as_dict()) + + +@app.patch("/api/exports/{set_id}", response_model=ExportSetOut) +def update_export(set_id: str, body: UpdateExportSet) -> ExportSetOut: + _require_set(set_id) + if body.target is not None and body.target not in _export_targets(): + raise HTTPException(422, f"Konduktor cannot export to {body.target} yet") + updated = exports.update( + _require_library_id(), + set_id, + name=body.name, + target=body.target, + destination=body.destination, + ) + return ExportSetOut(**updated.as_dict()) + + +@app.delete("/api/exports/{set_id}") +def delete_export(set_id: str) -> dict: + """Forget a set. Deliberately does NOT touch anything at its destination.""" + _require_set(set_id) + return {"deleted": exports.delete(_require_library_id(), set_id)} + + +@app.post("/api/exports/{set_id}/add", response_model=ExportSetOut) +def add_to_export(set_id: str, body: ExportSetMembers) -> ExportSetOut: + _require_set(set_id) + updated = exports.add( + _require_library_id(), set_id, + track_ids=body.track_ids, playlist_ids=body.playlist_ids, + ) + return ExportSetOut(**updated.as_dict()) + + +@app.post("/api/exports/{set_id}/remove", response_model=ExportSetOut) +def remove_from_export(set_id: str, body: ExportSetMembers) -> ExportSetOut: + """Remove loose tracks and/or WHOLE playlists. + + There is no per-track removal inside a referenced playlist: the reference is + live, so honouring both would need an exclusion list — hidden state silently + deciding what a future export contains. For a subset, add the tracks instead. + """ + _require_set(set_id) + updated = exports.remove( + _require_library_id(), set_id, + track_ids=body.track_ids, playlist_ids=body.playlist_ids, + ) + return ExportSetOut(**updated.as_dict()) + + +@app.get("/api/exports/{set_id}/contents", response_model=ExportContents) +def export_contents(set_id: str) -> ExportContents: + """What the set holds right now. Computed every call, never cached.""" + found = _require_set(set_id) + resolved = exports.resolve(require_adapter(), found) + return ExportContents( + playlists=[ + ExportPlaylistOut(id=p.id, name=p.name, missing=p.missing, count=len(p.track_ids)) + for p in resolved.playlists + ], + loose=len(resolved.loose_track_ids), + tracks=len(resolved.track_ids), + dangling=resolved.dangling_track_ids, + destination_conflict=exports.destination_conflict( + _require_library_id(), found.destination, ignore=set_id + ), + ) + + +@app.get("/api/exports/{set_id}/tracks", response_model=list[Track]) +def export_tracks(set_id: str) -> list[Track]: + """Every track the export would carry, deduped — the set's root view.""" + found = _require_set(set_id) + adapter = require_adapter() + resolved = exports.resolve(adapter, found) + return [t for t in (adapter.track(tid) for tid in resolved.track_ids) if t is not None] + + +@app.get("/api/exports/{set_id}/loose", response_model=list[Track]) +def export_loose_tracks(set_id: str) -> list[Track]: + """Only the LOOSE tracks — the ones added individually. + + A separate route rather than a filter on the root view, because the two are + genuinely different questions: the root is everything this export would ship + (playlists included, deduped), and this is the "Other" bucket that becomes + its own playlist in the exported library. A track added loosely AND supplied + by a referenced playlist appears in both, which is honest — it is in the + loose list, and that is what the count beside "Other" reports. + """ + found = _require_set(set_id) + adapter = require_adapter() + resolved = exports.resolve(adapter, found) + return [ + t for t in (adapter.track(tid) for tid in resolved.loose_track_ids) if t is not None + ] + + +@app.get("/api/exports/{set_id}/playlists/{playlist_id}/tracks", response_model=list[Track]) +def export_playlist_tracks(set_id: str, playlist_id: str) -> list[Track]: + """One included playlist, as it stands now. + + Read straight from the library rather than from the set, which is the live + reference doing its job: what ships is whatever the playlist holds today. + """ + found = _require_set(set_id) + if playlist_id not in found.playlist_ids: + raise HTTPException(404, "That playlist is not in this export") + tracks = require_adapter().playlist_tracks(playlist_id) + if tracks is None: + raise HTTPException(404, "That playlist no longer exists") + return tracks + + +@app.post("/api/exports/{set_id}/preview", response_model=ExportPreview) +def preview_export(set_id: str) -> ExportPreview: + """What this export would do, right now. Never cached — the set is live.""" + found = _require_set(set_id) + built = exporter.plan(require_adapter(), found) + return ExportPreview(**built.as_dict(exporter.space_for(built))) + + +@app.post("/api/exports/{set_id}/run", response_model=JobStatus) +def run_export(set_id: str) -> JobStatus: + """Start the export on a background thread; poll `/api/jobs/{id}`. + + Planned again HERE rather than trusting whatever the preview showed: a + playlist can be edited, a file deleted or a drive unplugged between looking + and clicking, and the plan carries the destination-safety check. + """ + found = _require_set(set_id) + adapter = require_adapter() + built = exporter.plan(adapter, found) + if built.blocked: + raise HTTPException(409, built.blocked) + job = JOBS.submit("export", lambda handle: exporter.run(adapter, found, built, handle)) + return JobStatus(**job.as_dict()) + + +def _export_targets() -> set[str]: + """Platforms Konduktor can write a NEW library for. + + Asked of the exporter registry rather than hard-coded: reading a library and + creating one from nothing are different capabilities, and a platform can + have the first without the second. Registering an exporter is what makes a + platform a target, so this cannot drift from what actually exists. + """ + return core_export.targets() + + +@app.get("/api/export-targets", response_model=list[PlatformOption]) +def export_targets() -> list[PlatformOption]: + """Every platform, flagged by whether it can be an export TARGET. + + Returns the unsupported ones too, with `installed=False` standing for "not a + target yet", so the UI can show them disabled with a reason. A silently + absent option reads as a missing feature; a disabled one reads as a roadmap. + """ + supported = _export_targets() + return [ + PlatformOption( + platform=d.platform, + name=d.display_name, + library_label=getattr(d, "library_label", ""), + selects="directory", # an export destination is always a folder + installed=d.platform in supported, + found=0, + removable=bool(getattr(d, "removable", False)), + ) + for d in registry.drivers() + ] + + # ---- health / state --------------------------------------------------- @@ -277,10 +575,68 @@ def health() -> dict: return {"status": "ok", "loaded": STATE.loaded, "path": str(STATE.path) if STATE.path else None} +def _library_info() -> LibraryInfo: + """Identity of the loaded library, for display and for composing warnings.""" + caps = require_adapter().capabilities() + path = Path(str(STATE.path)) + # A library's on-screen name is the driver's to give when it cares: a drive + # has one library reachable by two valid paths, and the filename would name + # it differently depending on which one the user happened to pick. + driver = next((d for d in registry.drivers() if d.platform == caps.platform), None) + namer = getattr(driver, "display_name_for", None) + try: + display_name = namer(path) if namer else path.name + except OSError: + display_name = path.name + return LibraryInfo( + platform=caps.platform, + name=caps.save.app_name, + library_label=caps.save.library_label, + path=str(STATE.path), + display_name=display_name, + version=caps.version, + ) + + +@app.get("/api/platforms", response_model=list[PlatformOption]) +def platforms() -> list[PlatformOption]: + """Every DJ platform Konduktor can open — used by the picker BEFORE a + library is loaded, where capabilities are not yet available.""" + out = [] + for d in registry.drivers(): + found = [] + try: + found = d.detect() + except OSError: + pass + out.append( + PlatformOption( + platform=d.platform, + name=d.display_name, + library_label=getattr(d, "library_label", ""), + selects=getattr(d, "selects", "file"), + installed=bool(found), + found=len(found), + removable=bool(getattr(d, "removable", False)), + ) + ) + # Registration order is an import-order accident, and this list is a MENU — + # it must not reshuffle itself between two launches. Sorted so the platforms + # that keep a library in a known place come before the ones that are a + # plugged-in drive, which is the real distinction a chooser is making. + out.sort(key=lambda o: (o.removable, o.name.lower())) + return out + + +@app.get("/api/capabilities", response_model=Capabilities) +def capabilities() -> Capabilities: + """What the loaded library can persist, so the UI can gate its controls.""" + return require_adapter().capabilities() + + @app.get("/api/state", response_model=EditState) def state() -> EditState: - store = require_store() - return EditState(dirty=store.dirty, nml_path=str(STATE.path)) + return EditState(dirty=require_adapter().dirty, library=_library_info()) @app.post("/api/reload") @@ -288,7 +644,7 @@ def reload_collection() -> dict: if not STATE.loaded: raise HTTPException(409, "No collection loaded") STATE.open(STATE.path) # re-parse current file from disk - return {"status": "reloaded", "tracks": len(require_service().tracks)} + return {"status": "reloaded", "tracks": len(require_adapter().tracks)} # ---- read: stats / facets / tracks ------------------------------------ @@ -296,12 +652,13 @@ def reload_collection() -> dict: @app.get("/api/stats", response_model=Stats) def stats() -> Stats: - return require_service().stats(playlist_count=require_store().count_playlists()) + a = require_adapter() + return a.stats(playlist_count=a.playlist_count()) @app.get("/api/facets", response_model=Facets) def facets() -> Facets: - return require_service().facets() + return require_adapter().facets() @app.get("/api/tracks", response_model=TrackPage) @@ -318,7 +675,7 @@ def tracks( limit: int = Query(100, ge=1, le=20000), offset: int = Query(0, ge=0), ) -> TrackPage: - return require_service().query_tracks( + return require_adapter().query_tracks( q=q, genre=genre, key=key, bpm_min=bpm_min, bpm_max=bpm_max, rating_min=rating_min, has_cues=has_cues, sort=sort, order=order, limit=limit, offset=offset, @@ -330,16 +687,15 @@ def tracks( @app.get("/api/playlists", response_model=list[PlaylistNode]) def playlists() -> list[PlaylistNode]: - return require_store().tree() + return require_adapter().playlist_tree() @app.get("/api/playlists/{playlist_id}/tracks", response_model=list[Track]) def playlist_tracks(playlist_id: str) -> list[Track]: - keys = require_store().entry_keys(playlist_id) - if keys is None: + tracks = require_adapter().playlist_tracks(playlist_id) + if tracks is None: raise HTTPException(404, f"Playlist not found: {playlist_id}") - svc = require_service() - return [svc.by_key[k] for k in keys if k in svc.by_key] + return tracks # ---- write: playlist editing ------------------------------------------ @@ -347,76 +703,81 @@ def playlist_tracks(playlist_id: str) -> list[Track]: @app.post("/api/playlists", response_model=PlaylistNode) def create_playlist(body: CreatePlaylist) -> PlaylistNode: - store = require_store() - try: - new_uuid = store.create_playlist(body.name.strip() or "New Playlist", body.parent_id) - except PlaylistError as ex: - raise HTTPException(400, str(ex)) - return PlaylistNode(id=new_uuid, name=body.name, type="PLAYLIST", uuid=new_uuid, count=0) + new_id = require_adapter().create_playlist( + body.name.strip() or "New Playlist", body.parent_id + ) + return PlaylistNode( + id=new_id, + name=body.name, + kind="playlist", + count=0, + selectable=True, + can_add_tracks=True, + can_reorder=True, + can_rename=True, + can_delete=True, + ) -@app.patch("/api/playlists/{playlist_uuid}") +@app.post("/api/playlists/folders", response_model=PlaylistNode) +def create_folder(body: CreatePlaylist) -> PlaylistNode: + name = body.name.strip() or "New Folder" + new_id = require_adapter().create_folder(name, body.parent_id) + return PlaylistNode( + id=new_id, + name=name, + kind="folder", + can_contain_children=True, + can_rename=True, + can_delete=True, + ) + + +# `:path` for the same reason as delete: a folder id is a path of names. +@app.patch("/api/playlists/{playlist_uuid:path}") def rename_playlist(playlist_uuid: str, body: RenamePlaylist) -> dict: - try: - require_store().rename_playlist(playlist_uuid, body.name.strip()) - except PlaylistError as ex: - raise HTTPException(404, str(ex)) + require_adapter().rename_playlist(playlist_uuid, body.name.strip()) return {"status": "renamed", "id": playlist_uuid, "name": body.name} -@app.delete("/api/playlists/{playlist_uuid}") +# `:path` because a folder id is a path of names (`fld:a/b`), and the slash +# would otherwise end the segment. +@app.delete("/api/playlists/{playlist_uuid:path}") def delete_playlist(playlist_uuid: str) -> dict: - try: - require_store().delete_playlist(playlist_uuid) - except PlaylistError as ex: - raise HTTPException(404, str(ex)) + require_adapter().delete_playlist(playlist_uuid) return {"status": "deleted", "id": playlist_uuid} @app.put("/api/playlists/{playlist_uuid}/entries") def set_entries(playlist_uuid: str, body: SetEntries) -> dict: - store = require_store() - entries = require_service().entries_for(body.track_ids) - try: - store.set_entries(playlist_uuid, entries) - except PlaylistError as ex: - raise HTTPException(404, str(ex)) - return {"status": "updated", "id": playlist_uuid, "count": len(entries)} + n = require_adapter().set_playlist_entries(playlist_uuid, body.track_ids) + return {"status": "updated", "id": playlist_uuid, "count": n} @app.post("/api/playlists/{playlist_uuid}/add") def add_entries(playlist_uuid: str, body: SetEntries) -> dict: """Append tracks to a playlist (skips ids already present).""" - store = require_store() - current = store.entry_keys(playlist_uuid) + a = require_adapter() + current = a.playlist_entries(playlist_uuid) if current is None: raise HTTPException(404, f"Playlist not found: {playlist_uuid}") have = set(current) added = [tid for tid in body.track_ids if tid not in have] - entries = require_service().entries_for(current + added) - store.set_entries(playlist_uuid, entries) - return {"status": "added", "id": playlist_uuid, "added": len(added), "count": len(entries)} + n = a.set_playlist_entries(playlist_uuid, current + added) + return {"status": "added", "id": playlist_uuid, "added": len(added), "count": n} @app.patch("/api/tracks") def edit_track(body: EditTrack) -> dict: """Edit a single track's safe metadata fields (in-memory; persisted on save).""" - store = require_store() - try: - store.set_track_metadata(body.track_id, body.fields) - except PlaylistError as ex: - raise HTTPException(404, str(ex)) - # Keep the read projection in sync so the edit shows immediately. - entry = store.model_entry(body.track_id) - if entry is not None: - require_service().replace_track(body.track_id, entry) + require_adapter().set_track_metadata(body.track_id, body.fields) return {"status": "updated", "id": body.track_id} @app.get("/api/tracks/art") def track_art(track_id: str) -> Response: """Stream a track's embedded cover art (staged replacement if unsaved).""" - art = require_store().cover_art(track_id) + art = require_adapter().cover_art(track_id) if art is None: raise HTTPException(404, "No cover art") data, mime = art @@ -439,7 +800,7 @@ _AUDIO_MIME = { @app.get("/api/tracks/audio") def track_audio(track_id: str) -> FileResponse: """Stream a track's audio file for playback (supports HTTP Range/seeking).""" - path = require_store().audio_path(track_id) + path = require_adapter().audio_path(track_id) if path is None: raise HTTPException(404, "Track not found") if not path.exists(): @@ -451,39 +812,11 @@ def track_audio(track_id: str) -> FileResponse: return FileResponse(path, media_type=mime) -def _build_track_cues(entry) -> TrackCues: - grid_anchor: float | None = None - grid_bpm: float | None = None - cues: list[CuePoint] = [] - for c in entry.cue_v2 or []: - grid = getattr(c, "grid", None) - start_sec = (c.start or 0.0) / 1000.0 # Traktor stores cue START in ms - if grid is not None: - if grid_anchor is None: - grid_anchor = start_sec - grid_bpm = grid.bpm - continue # grid markers are represented by the beatgrid, not as cues - cues.append( - CuePoint( - name=c.name, - type=c.type if c.type is not None else 0, - start=start_sec, - length=(c.len or 0.0) / 1000.0, - hotcue=c.hotcue if c.hotcue is not None else -1, - color=c.color, - ) - ) - bpm = grid_bpm if grid_bpm is not None else (entry.tempo.bpm if entry.tempo else None) - return TrackCues( - bpm=bpm, grid_anchor=grid_anchor, locked=bool(entry.lock), cues=cues - ) - - def _cues_for(track_id: str) -> TrackCues: - entry = require_store().model_entry(track_id) - if entry is None: + cues = require_adapter().track_cues(track_id) + if cues is None: raise HTTPException(404, "Track not found") - return _build_track_cues(entry) + return cues @app.get("/api/tracks/cues", response_model=TrackCues) @@ -492,169 +825,384 @@ def track_cues(track_id: str) -> TrackCues: return _cues_for(track_id) -def _sync_cue_edit(track_id: str) -> TrackCues: - """After a hotcue edit, refresh the read projection and return fresh cues.""" - store = require_store() - entry = store.model_entry(track_id) - if entry is not None: - require_service().replace_track(track_id, entry) - return _build_track_cues(entry) if entry is not None else TrackCues() - - -@app.post("/api/tracks/hotcue", response_model=TrackCues) -def create_hotcue(body: SetHotcue) -> TrackCues: - """Create (or reposition + retype) the hotcue in a slot at a position.""" - try: - require_store().set_hotcue( - body.track_id, body.slot, body.start, body.type, body.length, name=body.name - ) - except PlaylistError as ex: - raise HTTPException(400, str(ex)) - return _sync_cue_edit(body.track_id) - - -@app.post("/api/tracks/auto-hotcues", response_model=TrackCues) -def auto_hotcues(body: AutoHotcuesRequest) -> TrackCues: - """Analyze the track's audio and place structural hotcues into empty slots. - - Detects section boundaries (librosa Laplacian segmentation), snaps them to - the track's beatgrid phrases, names them positionally, and places up to - MAX_HOTCUES into empty slots only (never overwrites). Requires a beatgrid.""" - store = require_store() - entry = store.model_entry(body.track_id) - if entry is None: - raise HTTPException(404, "Track not found") - cues = _build_track_cues(entry) - if not cues.bpm or cues.bpm <= 0 or cues.grid_anchor is None: - raise HTTPException(400, "Set a beatgrid before using Auto Hotcues") - path = store.audio_path(body.track_id) - if path is None or not path.exists(): - raise HTTPException(400, "Audio file not found (is the drive mounted?)") - - try: - boundaries, duration = ah.detect_boundaries(str(path)) - except Exception as ex: # analysis is best-effort; never 500 the UI - raise HTTPException(400, f"Analysis failed: {ex}") - - occupied = {c.hotcue for c in cues.cues if c.hotcue is not None and c.hotcue >= 0} - free = [s for s in range(ah.MAX_HOTCUES) if s not in occupied] - existing_times = [c.start for c in cues.cues if c.hotcue is not None and c.hotcue >= 0] - specs = ah.select_hotcues( - boundaries, - bpm=cues.bpm, - anchor=cues.grid_anchor, - duration=duration, - free_slots=free, - existing_times=existing_times, - max_cues=body.max_cues or ah.MAX_HOTCUES, +@app.post("/api/tracks/cue", response_model=TrackCues) +def create_cue(body: SetCue) -> TrackCues: + """Create (or reposition + retype) the cue in a slot at a position.""" + return require_adapter().set_cue( + body.track_id, + slot=body.slot, + start_sec=body.start, + cue_type=body.type, + role=body.role, + length_sec=body.length, + name=body.name, ) - if not specs: - return cues # no confident structure / no free slots — leave untouched - try: - store.place_hotcues(body.track_id, [AutoHotcue(**s) for s in specs]) - except PlaylistError as ex: - raise HTTPException(400, str(ex)) - return _sync_cue_edit(body.track_id) -@app.post("/api/tracks/auto-grid", response_model=TrackCues) -def auto_grid(body: AutoGridRequest) -> TrackCues: - """Detect tempo + first beat and build a beatgrid: sets BPM, sets hotcue 1 - (slot 0) to the first beat, and anchors the grid to that position. Octave - (half/double) errors are left for the user to fix with the ×2/÷2 controls.""" - store = require_store() - if store.model_entry(body.track_id) is None: +@app.post("/api/tracks/cue/auto", response_model=AutoHotcuesResult) +def auto_hotcues(body: AutoHotcuesRequest) -> AutoHotcuesResult: + """Analyse the track's structure on its beatgrid and place the template. + + Each requested slot is bound to an event (``drop_1``, ``outro``, …) plus an + offset in beats. Every slot reports an outcome — placed, not found, out of + range, occupied (a cue is there and overwrite was not asked for), protected + (a cue the adapter will not replace) or duplicate (that beat already has a + cue — a kept one, or a new one in a lower slot) — so the UI can say which events this track does not have. + Requires a beatgrid. + """ + a = require_adapter() + cues = a.track_cues(body.track_id) + if cues is None: raise HTTPException(404, "Track not found") - path = store.audio_path(body.track_id) + if not cues.grid_markers: + raise HTTPException(400, "Set a beatgrid before using Auto Hotcues") + _check_cue_slots(a, body.slots) + try: + return _place_auto_cues(a, body.track_id, cues, body.slots) + except _AnalysisError as ex: + raise HTTPException(400, str(ex)) + + +def _check_cue_slots(a, slots: list) -> None: + """Refuse a template the bank cannot hold — once, before any track is touched.""" + n = a.capabilities().cues.hotcue_slots + seen: set[int] = set() + for r in slots: + if not 0 <= r.slot < n: + raise HTTPException(400, f"Slot {r.slot} is outside this library's {n} hotcues") + if r.slot in seen: + raise HTTPException(400, f"Slot {r.slot} is requested twice") + seen.add(r.slot) + + +def _place_auto_cues(a, track_id: str, cues: TrackCues, slots: list) -> AutoHotcuesResult: + """Analyse one gridded track's structure and place the template — shared by + the deck's Auto button and the batch job, so the two cannot drift.""" + path = a.audio_path(track_id) if path is None or not path.exists(): - raise HTTPException(400, "Audio file not found (is the drive mounted?)") + raise _AnalysisError("Audio file not found (is the drive mounted?)") try: - bpm, first_beat = ah.detect_grid(str(path)) + found = structure.analyse(str(path), [(m.start, m.bpm) for m in cues.grid_markers]) except Exception as ex: # analysis is best-effort; never 500 the UI - raise HTTPException(400, f"Analysis failed: {ex}") + raise _AnalysisError(f"Analysis failed: {ex}") from ex + + existing = { + c.slot: ah.ExistingCue(c.editable, c.start) + for c in cues.cues + if c.role == "hotcue" and c.slot is not None + } + outcomes = ah.plan( + found, + [ah.SlotRequest(r.slot, r.event, r.offset_beats, r.overwrite) for r in slots], + existing, + ) + placed = [o for o in outcomes if o.status == ah.PLACED] + if placed: + # overwrite=True is safe: `plan` only passes an occupied slot when the + # user ticked it, and the adapter still refuses a protected one. + cues = a.place_cues( + track_id, + [AutoHotcue(slot=o.slot, start=o.start, name=o.name) for o in placed], + overwrite=True, + ) + return AutoHotcuesResult( + cues=cues, + outcomes=[AutoCueOutcome(**vars(o)) for o in outcomes], + ) + + +@app.post("/api/tracks/grid/auto", response_model=TrackCues) +def auto_grid(body: AutoGridRequest) -> TrackCues: + """Detect tempo + first beat and build a beatgrid (see `core/grid_detect`). + + One constant-tempo marker, written the way the platform's own analyser would + (on Traktor that also sets hotcue 1 to the first beat). Octave (half/double) + ambiguity in halftime genres is left for the ×2 / ÷2 controls.""" + a = require_adapter() + if a.track(body.track_id) is None: + raise HTTPException(404, "Track not found") try: - store.set_grid(body.track_id, bpm=bpm, anchor_sec=first_beat) - store.set_hotcue(body.track_id, 0, first_beat, 0) # hotcue 1 = slot 0 - except PlaylistError as ex: + return _analyse_grid(a, body.track_id) + except _AnalysisError as ex: raise HTTPException(400, str(ex)) - return _sync_cue_edit(body.track_id) -@app.patch("/api/tracks/hotcue", response_model=TrackCues) -def edit_hotcue_type(body: SetHotcueType) -> TrackCues: - """Change the type of an existing hotcue (keeps its position).""" +class _AnalysisError(Exception): + """A track that could not be analysed; the message is user-facing.""" + + +# Batch analysis jobs. ONE at a time across both kinds: a grid run replacing a +# track's grid while a hotcue run places cues on the old one would put cues on +# beats that no longer exist. +GRID_JOB = "grid-analysis" +CUE_JOB = "auto-hotcues" +BATCH_JOBS = (GRID_JOB, CUE_JOB) + + +def _require_no_batch() -> None: + if any(JOBS.active(k) for k in BATCH_JOBS): + raise HTTPException(409, "A batch analysis is already running") + + +def _analyse_grid(a, track_id: str) -> TrackCues: + """Detect and write one track's grid — shared by the deck's Analyze and the + batch job, so the two cannot come to mean different things.""" + path = a.audio_path(track_id) + if path is None or not path.exists(): + raise _AnalysisError("Audio file not found (is the drive mounted?)") try: - require_store().set_hotcue_type(body.track_id, body.slot, body.type) - except PlaylistError as ex: - raise HTTPException(400, str(ex)) - return _sync_cue_edit(body.track_id) + found = grid_detect.detect_grid(str(path)) + except Exception as ex: # analysis is best-effort; never 500 the UI + raise _AnalysisError(f"Analysis failed: {ex}") from ex + # "Analysed", not "replace": each platform writes an analysis result in its + # own shape (Traktor pairs the first marker with a beat-1 cue). + return a.set_analysed_grid(track_id, [(found.anchor, found.bpm)]) -@app.delete("/api/tracks/hotcue", response_model=TrackCues) -def delete_hotcue(track_id: str, slot: int) -> TrackCues: + +@app.post("/api/tracks/grid/auto-batch", response_model=JobStatus) +def auto_grid_batch(body: AutoGridBatchRequest) -> JobStatus: + """Analyse many tracks' grids as a JOB; poll `/api/jobs/{id}`. + + Each track is written as it finishes, into the in-memory model like any + other edit — so a cancel keeps what is done (it is all unsaved until Save), + and the result is returned even from a cancelled run. A track that fails is + reported and skipped, never fatal: one unmounted drive must not stop 400 + other tracks.""" + a = require_adapter() + if not a.capabilities().grid.editable: + raise HTTPException(422, "This library's beatgrids cannot be edited") + _require_no_batch() + ids = list(dict.fromkeys(body.track_ids)) + + def run(handle) -> dict: + result = {"analysed": [], "locked": 0, "existing": 0, "failed": []} + handle.progress(done=0, total=len(ids)) + for i, track_id in enumerate(ids): + if handle.cancelled: + break # keep what is done; return it rather than raise + track = a.track(track_id) + title = (track.title or track_id) if track else track_id + handle.progress(message=title) + if track is None: + result["failed"].append({"title": title, "reason": "Track not found"}) + elif track.grid_locked: + result["locked"] += 1 + elif track.grid_marker_count > 0 and not body.replace_existing: + result["existing"] += 1 + else: + try: + _analyse_grid(a, track_id) + result["analysed"].append(track_id) + except (_AnalysisError, AdapterError) as ex: + result["failed"].append({"title": title, "reason": str(ex)}) + handle.progress(done=i + 1) + return result + + job = JOBS.submit(GRID_JOB, run) + return JobStatus(**job.as_dict()) + + +@app.post("/api/tracks/cue/auto-batch", response_model=JobStatus) +def auto_hotcues_batch(body: AutoHotcuesBatchRequest) -> JobStatus: + """Place one Auto Hotcues template on many tracks, as a JOB. + + A track with no beatgrid gets one analysed first (as "Analyze Grid & BPM" + would), since the events are found on the grid; a track that has one keeps + it untouched. Same contract as the grid batch: written as each track + finishes, a cancel keeps what is done, a failing track is reported and + skipped.""" + a = require_adapter() + caps = a.capabilities() + if not caps.writable or caps.cues.hotcue_slots == 0: + raise HTTPException(422, "This library's hotcues cannot be edited") + _check_cue_slots(a, body.slots) + if not body.slots: + raise HTTPException(400, "The template places no cues") + _require_no_batch() + ids = list(dict.fromkeys(body.track_ids)) + + def run(handle) -> dict: + result = {"tracks": [], "cues_placed": 0, "grids_created": 0, "failed": []} + handle.progress(done=0, total=len(ids)) + for i, track_id in enumerate(ids): + if handle.cancelled: + break # keep what is done; return it rather than raise + track = a.track(track_id) + title = (track.title or track_id) if track else track_id + handle.progress(message=title) + try: + cues = a.track_cues(track_id) if track else None + if cues is None: + raise _AnalysisError("Track not found") + if not cues.grid_markers: + if track.grid_locked: + raise _AnalysisError("No beatgrid, and the grid is locked") + if not caps.grid.editable: + raise _AnalysisError("No beatgrid") + cues = _analyse_grid(a, track_id) + result["grids_created"] += 1 + placed = _place_auto_cues(a, track_id, cues, body.slots) + result["tracks"].append(track_id) + result["cues_placed"] += sum(o.status == ah.PLACED for o in placed.outcomes) + except (_AnalysisError, AdapterError) as ex: + result["failed"].append({"title": title, "reason": str(ex)}) + handle.progress(done=i + 1) + return result + + job = JOBS.submit(CUE_JOB, run) + return JobStatus(**job.as_dict()) + + +@app.patch("/api/tracks/cue", response_model=TrackCues) +def edit_cue_type(body: SetCueType) -> TrackCues: + """Change the type of an existing cue (keeps its position).""" + return require_adapter().set_cue_type(body.track_id, body.slot, body.type) + + +@app.delete("/api/tracks/cue", response_model=TrackCues) +def delete_cue(track_id: str, slot: int) -> TrackCues: """Remove the hotcue in a slot.""" - try: - require_store().delete_hotcue(track_id, slot) - except PlaylistError as ex: - raise HTTPException(400, str(ex)) - return _sync_cue_edit(track_id) + return require_adapter().delete_cue(track_id, slot) -@app.patch("/api/tracks/grid", response_model=TrackCues) -def edit_grid(body: GridEdit) -> TrackCues: - """Set the beatgrid BPM and/or move the grid marker (beat 1).""" - try: - require_store().set_grid(body.track_id, body.bpm, body.anchor) - except PlaylistError as ex: - raise HTTPException(400, str(ex)) - return _sync_cue_edit(body.track_id) +@app.post("/api/tracks/grid/marker", response_model=TrackCues) +def add_grid_marker(body: AddGridMarker) -> TrackCues: + """Add a beatgrid marker. Omitting `bpm` inherits the governing tempo.""" + return require_adapter().add_grid_marker(body.track_id, body.start, body.bpm) + + +@app.patch("/api/tracks/grid/marker", response_model=TrackCues) +def edit_grid_marker(body: GridMarkerEdit) -> TrackCues: + """Retempo and/or move one grid marker. + + BPM is applied before the move: a tempo change can never reorder markers, so + `index` is still valid for the move afterwards. + """ + a = require_adapter() + cues = a.track_cues(body.track_id) + if body.bpm is not None: + cues = a.set_grid_marker_bpm(body.track_id, body.index, body.bpm) + if body.start is not None: + cues = a.move_grid_marker(body.track_id, body.index, body.start) + if cues is None: + raise HTTPException(404, "Track not found") + return cues + + +@app.delete("/api/tracks/grid/marker", response_model=TrackCues) +def remove_grid_marker(track_id: str, index: int) -> TrackCues: + """Delete one grid marker (and its companion cue).""" + return require_adapter().delete_grid_marker(track_id, index) + + +@app.put("/api/tracks/grid", response_model=TrackCues) +def replace_grid(body: ReplaceGrid) -> TrackCues: + """Replace the whole beatgrid (the deck's Reset). `markers: []` clears it.""" + return require_adapter().replace_grid( + body.track_id, [(m.start, m.bpm) for m in body.markers] + ) @app.delete("/api/tracks/grid", response_model=TrackCues) def remove_grid(track_id: str) -> TrackCues: - """Delete the track's grid marker(s).""" - try: - require_store().delete_grid(track_id) - except PlaylistError as ex: - raise HTTPException(400, str(ex)) - return _sync_cue_edit(track_id) + """Delete every grid marker and its companion cue. is kept.""" + return require_adapter().delete_grid(track_id) -@app.patch("/api/tracks/lock", response_model=TrackCues) -def edit_lock(body: SetLock) -> TrackCues: +# ---- bulk Remove (the context menu's Remove ▸ submenu) -------------------- +# +# Quick in-memory edits, so requests rather than jobs — but refused while a +# batch analysis runs: it would write cues/grids onto a track removed under it. + + +@app.post("/api/tracks/grid/clear") +def clear_grids(body: TrackIds) -> dict: + """Delete the beatgrid of every given track. Locked grids are skipped — + a lock is the user saying "leave this grid alone" — and reported.""" + a = require_adapter() + if not a.capabilities().grid.editable: + raise HTTPException(422, "This library's beatgrids cannot be edited") + _require_no_batch() + out = {"cleared": 0, "locked": 0, "empty": 0} + for tid in dict.fromkeys(body.track_ids): + track = a.track(tid) + if track is None: + continue + if track.grid_locked: + out["locked"] += 1 + elif not (a.track_cues(tid) or TrackCues()).grid_markers: + out["empty"] += 1 # counted from the cues: the projection's count can be approximate + else: + a.delete_grid(tid) + out["cleared"] += 1 + return out + + +@app.post("/api/tracks/cue/clear") +def clear_hotcues(body: TrackIds) -> dict: + """Empty the whole hotcue bank of every given track — point cues, loops + and the grid's paired beat-1 cue alike (the grid itself is untouched). + Cues the adapter will not edit — Rekordbox memory cues — are kept.""" + a = require_adapter() + caps = a.capabilities() + if not caps.writable or caps.cues.hotcue_slots == 0: + raise HTTPException(422, "This library's hotcues cannot be edited") + _require_no_batch() + out = {"tracks": 0, "cues": 0} + for tid in dict.fromkeys(body.track_ids): + cues = a.track_cues(tid) + slots = sorted({ + c.slot for c in (cues.cues if cues else []) + if c.role == "hotcue" and c.slot is not None and c.editable + }) + for slot in slots: + a.delete_cue(tid, slot) + if slots: + out["tracks"] += 1 + out["cues"] += len(slots) + return out + + +@app.post("/api/tracks/remove") +def remove_tracks(body: TrackIds) -> dict: + """Remove tracks from the library and every playlist. Audio files are + never touched. An export set referencing one will report it as missing, + which is what export sets do with any track that has gone.""" + a = require_adapter() + if not a.capabilities().tracks.removable: + raise HTTPException(422, "Tracks cannot be removed from this library") + _require_no_batch() + return {"removed": a.remove_tracks(list(dict.fromkeys(body.track_ids)))} + + +@app.patch("/api/tracks/grid/lock", response_model=TrackCues) +def edit_grid_lock(body: SetGridLock) -> TrackCues: """Toggle Traktor's LOCK flag on a track.""" - try: - require_store().set_lock(body.track_id, body.locked) - except PlaylistError as ex: - raise HTTPException(400, str(ex)) - return _sync_cue_edit(body.track_id) + return require_adapter().set_grid_lock(body.track_id, body.locked) @app.put("/api/tracks/art") async def set_track_art(track_id: str = Form(...), file: UploadFile = File(...)) -> dict: """Stage replacement cover art for a track (written to the file on save).""" - store = require_store() + a = require_adapter() data = await file.read() if not data: raise HTTPException(400, "Empty image") - mime = file.content_type or "image/jpeg" - try: - store.set_track_art(track_id, data, mime) - except PlaylistError as ex: - raise HTTPException(404, str(ex)) + a.set_cover_art(track_id, data, file.content_type or "image/jpeg") return {"status": "staged", "id": track_id, "bytes": len(data)} @app.post("/api/save", response_model=SaveResult) def save() -> SaveResult: - store = require_store() - if not store.dirty: - return SaveResult(saved=False, commit=None, playlists=store.count_playlists()) - outcome = store.save() + a = require_adapter() + if not a.dirty: + return SaveResult(saved=False, commit=None, playlists=a.playlist_count()) + outcome, commit = STATE.save() return SaveResult( saved=True, - commit=outcome.commit, - playlists=store.count_playlists(), + commit=commit, + playlists=a.playlist_count(), file_tags=[FileTagOutcome(**r.__dict__) for r in outcome.tag_results], ) @@ -665,7 +1213,7 @@ def save() -> SaveResult: @app.get("/api/history", response_model=list[HistoryEntry]) def get_history() -> list[HistoryEntry]: """All saved versions of the current collection, newest first.""" - require_store() + require_adapter() return [HistoryEntry(**e.__dict__) for e in history.list_history(STATE.path)] @@ -674,14 +1222,13 @@ def restore_version(commit_id: str) -> CollectionStatus: """Restore the collection to a past version. Writes that version back as a NEW forward save (a fresh commit on top of history — never a rewind), then reloads. The user should close Traktor first (it overwrites on exit).""" - require_store() + require_adapter() data = history.read_version(STATE.path, commit_id) if data is None: raise HTTPException(404, f"Version not found: {commit_id}") path = STATE.path - tmp = path.with_suffix(path.suffix + ".tmp") - tmp.write_bytes(data) - tmp.replace(path) + # The adapter's driver owns writing its own format back, even for a restore. + registry.driver_for(path).restore(path, data) history.commit(path, data, f"Restored version {commit_id[:8]}", __version__) STATE.open(path) # rebuild read + edit models from the restored file return collection_status() @@ -690,6 +1237,430 @@ def restore_version(commit_id: str) -> CollectionStatus: @app.delete("/api/history") def clear_history() -> dict: """Permanently delete ALL version history for the current collection.""" - require_store() + require_adapter() history.clear_history(STATE.path) return {"status": "cleared"} + + +# ---- import sources --------------------------------------------------- +# +# A SOURCE is a library being read FROM, open alongside the loaded one. Its +# routes are read-only by construction: there is no source equivalent of any +# command, so no route here can be confused about which library it targets. + + +def require_source() -> LibraryAdapter: + """The open source, or a 409.""" + if not STATE.source_loaded: + raise HTTPException(409, "No source library open") + assert STATE.source is not None + return STATE.source + + +def _source_status() -> SourceStatus: + if not STATE.source_loaded: + return SourceStatus(loaded=False) + source = STATE.source + caps = source.capabilities() + return SourceStatus( + loaded=True, + path=str(STATE.source_path), + label=caps.save.library_label, + platform=caps.platform, + tracks=len(source.tracks), + playlists=source.playlist_count(), + ) + + +@app.get("/api/sources", response_model=list[SourceCandidate]) +def sources() -> list[SourceCandidate]: + """Every removable library plugged in right now. + + Unlike `/api/library/options`, this genuinely changes between two calls a + second apart — a stick is whatever is mounted — so the UI is expected to + poll it rather than read it once at startup. + + Only read-only platforms are offered. A source is a thing to import FROM, + and a writable library appearing here would invite someone to open their own + collection as a source of itself. + """ + out: list[SourceCandidate] = [] + for driver in registry.drivers(): + try: + found = driver.detect() + except OSError: + continue + for candidate in found: + path = Path(candidate["path"]) + # Removable libraries are the ones discovery finds by scanning mount + # points. Ask the driver rather than hard-coding which platform that + # is, so a future Serato-on-a-stick needs no change here. + if not getattr(driver, "removable", False): + continue + out.append( + SourceCandidate( + path=str(path), + label=candidate.get("label") or path.name, + platform=driver.platform, + modified=candidate.get("modified"), + ) + ) + return out + + +@app.get("/api/source", response_model=SourceStatus) +def source_status() -> SourceStatus: + return _source_status() + + +@app.post("/api/source/open", response_model=SourceStatus) +def open_source(body: OpenSource) -> SourceStatus: + path = Path(body.path).expanduser() + # NOT `is_file()`, unlike opening a collection: a OneLibrary source is a + # DRIVE, so the thing the user picks is a directory. + if not path.exists(): + raise HTTPException(400, f"Not found: {path}") + try: + STATE.open_source(path) + except ValueError as ex: + raise HTTPException(400, str(ex)) + except AdapterError as ex: + raise HTTPException(400, f"Not a library Konduktor can read: {ex}") + except Exception as ex: # noqa: BLE001 + raise HTTPException(400, f"Could not open that source: {ex}") + return _source_status() + + +@app.delete("/api/source", response_model=SourceStatus) +def close_source() -> SourceStatus: + """Close the source and release its file handle. + + Worth calling rather than leaving to chance: the source is on a removable + drive, and a held handle is what stops a stick ejecting. + """ + STATE.close_source() + return _source_status() + + +@app.get("/api/source/capabilities", response_model=Capabilities) +def source_capabilities() -> Capabilities: + return require_source().capabilities() + + +@app.get("/api/source/tracks", response_model=TrackPage) +def source_tracks( + 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 = Query(None, ge=0, le=5), + has_cues: bool | None = None, + sort: str = "artist", + order: str = Query("asc", pattern="^(asc|desc)$"), + limit: int = Query(100, ge=1, le=20000), + offset: int = Query(0, ge=0), +) -> TrackPage: + return require_source().query_tracks( + q=q, genre=genre, key=key, bpm_min=bpm_min, bpm_max=bpm_max, + rating_min=rating_min, has_cues=has_cues, sort=sort, order=order, + limit=limit, offset=offset, + ) + + +@app.get("/api/source/playlists", response_model=list[PlaylistNode]) +def source_playlists() -> list[PlaylistNode]: + return require_source().playlist_tree() + + +@app.get("/api/source/playlists/{playlist_id}/tracks", response_model=list[Track]) +def source_playlist_tracks(playlist_id: str) -> list[Track]: + tracks = require_source().playlist_tracks(playlist_id) + if tracks is None: + raise HTTPException(404, f"Playlist not found: {playlist_id}") + return tracks + + +@app.get("/api/source/tracks/cues", response_model=TrackCues) +def source_track_cues(track_id: str) -> TrackCues: + cues = require_source().track_cues(track_id) + if cues is None: + raise HTTPException(404, "Track not found") + return cues + + +@app.get("/api/source/tracks/audio") +def source_track_audio(track_id: str) -> FileResponse: + """Stream a track's audio straight off the source drive. + + So the deck can audition a track BEFORE importing it, which is most of the + reason the stick is browsable in the ordinary table rather than in a picker + dialog. + """ + path = require_source().audio_path(track_id) + if path is None: + raise HTTPException(404, "Track not found") + if not path.exists(): + raise HTTPException(404, f"Audio file not found: {path}") + mime = _AUDIO_MIME.get(path.suffix.lower(), "application/octet-stream") + return FileResponse(path, media_type=mime) + + +# ---- drives and folders ----------------------------------------------- +# +# The sidebar's Devices and Local Storage trees. Browsing a folder is READ-ONLY +# and needs no library of its own: the files are projected as tracks for the +# table and deck, and adding them goes through the ordinary importer. + +FOLDERS = FolderScanner() + + +def _drive_of(path: Path, drives: list[dict]) -> dict | None: + """The drive `path` lives on: the longest drive root that contains it.""" + best = None + for d in drives: + root = Path(d["path"]) + try: + path.relative_to(root) + except ValueError: + continue + if best is None or len(root.parts) > len(Path(best["path"]).parts): + best = d + return best + + +@app.get("/api/fs/drives", response_model=list[Drive]) +def fs_drives() -> list[Drive]: + """Every drive, with the OneLibrary library on it where there is one. + + Polled, like `/api/sources`, because drives come and go while the app is + open. Cheap after the first call: which drives are internal is cached per + mount, since asking the OS is a subprocess on macOS. + """ + found = places.drives() + libraries = sources() + out = [Drive(**d) for d in found] + externals = [d for d in found if d["path"] != "/"] + for lib in libraries: + home = _drive_of(Path(lib.path), externals) + if home is None: + continue + for drive in out: + if drive.path == home["path"]: + drive.library = lib + return out + + +@app.get("/api/fs/folders", response_model=list[FsEntry]) +def fs_folders(path: str) -> list[FsEntry]: + """The visible folders directly inside `path` — one level of a Files tree.""" + base = Path(path).expanduser() + if not base.is_dir(): + raise HTTPException(404, f"Not a folder: {base}") + return [FsEntry(name=p.name, path=str(p)) for p in places.subfolders(base)] + + +def _formats() -> list[str]: + return require_adapter().capabilities().tracks.audio_formats + + +@app.get("/api/folder/tracks", response_model=FolderTracks) +def folder_tracks(path: str) -> FolderTracks: + """The audio files directly inside a folder, and which are already held.""" + base = Path(path).expanduser() + if not base.is_dir(): + raise HTTPException(404, f"Not a folder: {base}") + source = FOLDERS.scan(base, _formats()) + held = importer._existing_files(require_adapter()) + drive = _drive_of(base, places.drives()) + return FolderTracks( + path=str(base), + tracks=source.tracks, + in_collection=[t.id for t in source.tracks if importer._key(Path(t.id)) in held], + removable=drive is None or drive["kind"] == "external", + ) + + +def _folder_track(track_id: str) -> FolderSource: + # Only a file a scan found. This is what keeps the audio route from being a + # way to read any path on the disk. + source = FOLDERS.source_for_file(track_id) + if source is None: + raise HTTPException(404, "Track not found — browse to its folder first") + return source + + +@app.get("/api/folder/capabilities", response_model=Capabilities) +def folder_capabilities(path: str) -> Capabilities: + from .core.folder import capabilities_for + + return capabilities_for(Path(path)) + + +@app.get("/api/folder/tracks/cues", response_model=TrackCues) +def folder_track_cues(track_id: str) -> TrackCues: + cues = _folder_track(track_id).track_cues(track_id) + assert cues is not None + return cues + + +@app.get("/api/folder/tracks/audio") +def folder_track_audio(track_id: str) -> FileResponse: + path = _folder_track(track_id).audio_path(track_id) + if path is None or not path.is_file(): + raise HTTPException(404, "Audio file not found") + mime = _AUDIO_MIME.get(path.suffix.lower(), "application/octet-stream") + return FileResponse(path, media_type=mime) + + +def _folder_add_plan(body: FolderAddRequest): + dest = require_adapter() + tracks = [] + for track_id in body.track_ids: + track = _folder_track(track_id).track(track_id) + if track is not None: + tracks.append(track) + if not tracks: + raise HTTPException(400, "No tracks to add") + # One source across however many folders the ids came from. + source = FolderSource(Path(tracks[0].id).parent, tracks) + destination = None + if body.mode == "copy": + if not body.destination: + raise HTTPException(400, "Copying needs a destination folder") + destination = Path(body.destination).expanduser() + if body.playlist_id is not None and dest.playlist_entries(body.playlist_id) is None: + raise HTTPException(404, f"Playlist not found: {body.playlist_id}") + if body.export_id is not None: + if STATE.library_id is None or exports.get(STATE.library_id, body.export_id) is None: + raise HTTPException(404, f"Export not found: {body.export_id}") + return source, dest, destination, importer.plan( + source, dest, destination, track_ids=[t.id for t in tracks] + ) + + +@app.post("/api/folder/add/preview") +def folder_add_preview(body: FolderAddRequest) -> dict: + _source, _dest, destination, plan = _folder_add_plan(body) + out = plan.as_dict(free_bytes=importer.free_bytes(destination) if destination else None) + if body.mode == "reference": + # Nothing is copied, so there is no size to fit anywhere. + out.update(total_bytes=0, free_bytes=None, enough_space=None) + drive = _drive_of(Path(body.track_ids[0]), places.drives()) if body.track_ids else None + out["removable"] = drive is None or drive["kind"] == "external" + return out + + +@app.post("/api/folder/add", response_model=JobStatus) +def folder_add(body: FolderAddRequest) -> JobStatus: + """Add browsed files to the collection. A job, like import: copying can be long.""" + source, dest, destination, plan = _folder_add_plan(body) + if not plan.importable and not plan.existing: + raise HTTPException(400, "Nothing to add (none of those files exist)") + if body.mode == "copy": + free = importer.free_bytes(destination) + if free is not None and free < plan.total_bytes + importer.SPACE_HEADROOM: + raise HTTPException( + 400, + f"Not enough space: {plan.total_bytes / 1e9:.1f} GB needed, " + f"{free / 1e9:.1f} GB free at {destination}", + ) + if JOBS.active("import"): + raise HTTPException(409, "An import is already running") + library = STATE.library_id + + def work(handle): + result = importer.run( + source, dest, plan, handle, + reference=body.mode == "reference", + into_playlist=body.playlist_id, + ) + # Export sets are Konduktor's own data, not the library's, so they are + # updated after the library has been saved rather than inside it. + if body.export_id is not None and library is not None: + exports.add(library, body.export_id, track_ids=result["track_ids"]) + return result + + job = JOBS.submit("import", work) + return JobStatus(**job.as_dict()) + + +# ---- import ----------------------------------------------------------- +# +# The only operation in the app that can run for minutes, so it is the only one +# that is a JOB rather than a request. See `jobs.py` for why that is polling and +# threads rather than something fancier. + + +def _import_plan(body: ImportRequest): + source, dest = require_source(), require_adapter() + destination = Path(body.destination).expanduser() + return source, dest, destination, importer.plan( + source, + dest, + destination, + track_ids=body.track_ids, + playlist_ids=body.playlist_ids, + ) + + +@app.post("/api/import/preview") +def import_preview(body: ImportRequest) -> dict: + """What an import would do: counts, size, missing files, duplicates, space. + + Computed fresh on every call and never stored — a stick can be re-exported + between the preview and the import, and a stale preview is worse than none. + """ + _source, _dest, destination, plan = _import_plan(body) + return plan.as_dict(free_bytes=importer.free_bytes(destination)) + + +@app.post("/api/import", response_model=JobStatus) +def start_import(body: ImportRequest) -> JobStatus: + """Start an import. Returns immediately; poll the job for progress.""" + source, dest, destination, plan = _import_plan(body) + if not plan.importable: + raise HTTPException(400, "Nothing to import (no tracks, or none of their files exist)") + free = importer.free_bytes(destination) + if free is not None and free < plan.total_bytes + importer.SPACE_HEADROOM: + raise HTTPException( + 400, + f"Not enough space: {plan.total_bytes / 1e9:.1f} GB needed, " + f"{free / 1e9:.1f} GB free at {destination}", + ) + # One at a time: two concurrent imports would race on filename collisions and + # on the destination library's save. + if JOBS.active("import"): + raise HTTPException(409, "An import is already running") + + folder_name = body.folder_name + if folder_name is None and STATE.source is not None: + folder_name = STATE.source.capabilities().save.library_label + + job = JOBS.submit( + "import", + lambda handle: importer.run(source, dest, plan, handle, folder_name=folder_name), + ) + return JobStatus(**job.as_dict()) + + +@app.get("/api/jobs/{job_id}", response_model=JobStatus) +def job_status(job_id: str) -> JobStatus: + job = JOBS.get(job_id) + if job is None: + raise HTTPException(404, f"No such job: {job_id}") + return JobStatus(**job.as_dict()) + + +@app.post("/api/jobs/{job_id}/cancel", response_model=JobStatus) +def cancel_job(job_id: str) -> JobStatus: + """Ask a job to stop. + + A REQUEST, not a kill: the job stops at its next checkpoint and cleans up + after itself, so the status stays "running" until it has actually done so. + """ + job = JOBS.get(job_id) + if job is None: + raise HTTPException(404, f"No such job: {job_id}") + JOBS.cancel(job_id) + return JobStatus(**job.as_dict()) diff --git a/backend/konduktor/paths.py b/backend/konduktor/paths.py index c9c7ca0..841eea8 100644 --- a/backend/konduktor/paths.py +++ b/backend/konduktor/paths.py @@ -16,6 +16,7 @@ anyway; callers already treat all data I/O as best-effort. """ from __future__ import annotations +import json import os from pathlib import Path @@ -25,6 +26,37 @@ _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") diff --git a/backend/konduktor/playlist_store.py b/backend/konduktor/playlist_store.py deleted file mode 100644 index 761607b..0000000 --- a/backend/konduktor/playlist_store.py +++ /dev/null @@ -1,773 +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 - span back into the original file bytes), - * safe — every save is committed to the collection's version history (see - ``history.py``); the commit is additive and never alters the saved bytes. - -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 -… span, and splice it into the untouched original bytes. - -Playlists are identified by their stable UUID; folders by a synthetic path id -(``fld:/``). Smart playlists are read-only. -""" -from __future__ import annotations - -import threading -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 . import __version__, history -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: - commit: str | None # sha of the version-history commit (None if deduped/failed) - 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]] = {} - # (category, detail, track_id) events this session -> commit summary. - # track_id lets prep edits report how many distinct tracks were affected. - self._edit_events: list[tuple[str, str | None, str | None]] = [] - self.dirty = False - - def _note(self, category: str, detail: str | None = None, track_id: str | None = None) -> None: - """Record a human-meaningful edit for the next commit's summary.""" - self._edit_events.append((category, detail, track_id)) - - 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._note("playlist-create", name) - 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._note("playlist-rename", 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._note("playlist-delete", node.name) - 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._note("playlist-entries", node.name) - 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, - ) - ) - # "add" only when it's a genuinely new hotcue; repositioning/retyping - # an existing slot is a "modify" (keeps the net add/remove count honest). - self._note("hotcue", "modify" if existing is not None else "add", track_id) - 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._note("hotcue", "modify", track_id) - self.dirty = True - - def delete_hotcue(self, track_id: str, slot: int) -> None: - with self._lock: - entry = self._entry_or_raise(track_id) - before = entry.cue_v2 or [] - entry.cue_v2 = [c for c in before if c.hotcue != slot] - if len(entry.cue_v2) != len(before): # only count an actual removal - self._note("hotcue", "delete", track_id) - 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._note("grid", "edit", track_id) - 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._note("grid", "delete", track_id) - 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._note("lock", "on" if locked else "off", track_id) - 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._note("remap", str(len(key_remap))) - 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: - 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() - # Version history: commit the saved bytes (additive — never touches the - # file we just wrote). Summary is computed before _load() clears state. - commit = history.commit(self.nml_path, new_data, self._edit_summary(), __version__) - self._load() # clears dirty + _track_edits + _edit_events - return SaveOutcome(commit=commit, tag_results=tag_results) - - def _edit_summary(self) -> 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'}" - - # --- track metadata + cover art (already counted per-track) --- - n_meta = len(self._track_edits.keys() | self._track_art.keys()) - if n_meta: - parts.append(f"edited {tracks(n_meta)}") - - # --- playlists (name-bearing) --- - pl_names: dict[str, list[str]] = {} - for cat, detail, _tid in self._edit_events: - if cat.startswith("playlist-") and detail: - pl_names.setdefault(cat, []).append(detail) - for cat, verb in ( - ("playlist-create", "created"), - ("playlist-rename", "renamed"), - ("playlist-delete", "deleted"), - ("playlist-entries", "reordered"), - ): - names = pl_names.get(cat, []) - if not names: - continue - if len(names) <= 2: - joined = ", ".join(f"'{n}'" for n in names) - parts.append(f"{verb} playlist{'' if len(names) == 1 else 's'} {joined}") - else: - parts.append(f"{verb} {len(names)} playlists") - - # --- 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 cat, detail, tid in self._edit_events: - if cat == "hotcue": - if tid: - hc_tracks.add(tid) - if detail == "add": - hc_add += 1 - elif detail == "delete": - hc_del += 1 - elif cat == "grid": - (grid_edit if detail == "edit" else grid_del).add(tid or "") - elif cat == "lock": - (lock_on if detail == "on" else lock_off).add(tid 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 cat, detail, _tid in self._edit_events: - if cat == "remap" and detail: - parts.append(f"remapped {detail} file paths") - - if not parts: - return "Saved changes" - summary = "; ".join(parts) - return summary[0].upper() + summary[1:] - - 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") diff --git a/backend/konduktor/prefs.py b/backend/konduktor/prefs.py index 5981ec0..f7d70aa 100644 --- a/backend/konduktor/prefs.py +++ b/backend/konduktor/prefs.py @@ -81,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) diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index 067115f..6a72bb5 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -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: "", 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 ( 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-" / "fld-") - 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): @@ -125,68 +47,108 @@ class HistoryEntry(BaseModel): summary: str # human-readable edit summary -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 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 ---- @@ -197,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): @@ -213,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 @@ -242,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 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 diff --git a/backend/requirements.txt b/backend/requirements.txt index 5d63084..449c9b0 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -17,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 diff --git a/backend/run_tests.sh b/backend/run_tests.sh index b0b6d48..15a1171 100755 --- a/backend/run_tests.sh +++ b/backend/run_tests.sh @@ -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 test_history.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 "──────────────────────────────────────────" diff --git a/backend/test_auto_hotcues.py b/backend/test_auto_hotcues.py new file mode 100644 index 0000000..1b2b26c --- /dev/null +++ b/backend/test_auto_hotcues.py @@ -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) diff --git a/backend/test_bulk_remove.py b/backend/test_bulk_remove.py new file mode 100644 index 0000000..2358c7d --- /dev/null +++ b/backend/test_bulk_remove.py @@ -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) diff --git a/backend/test_export.py b/backend/test_export.py new file mode 100644 index 0000000..63bc289 --- /dev/null +++ b/backend/test_export.py @@ -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('' in text) +check("a HEAD element", "' in text) +# Playlists cannot sit at the top level; they hang off a $ROOT FOLDER node. +check("PLAYLISTS wraps a $ROOT folder", '' in text) +check("INDEXING is present", '' in text) +check("the ENTRIES header matches the entry count", + f'' in text, + re.search(r'