Updated backend

This commit is contained in:
patben8 committed 2026-09-17 17:30:36 +02:00
1 parent 08c9b8121d
commit c9e85bbdb5
17 files changed
+492 -373

No files matched your search

+67 -28
View File
@@ -16,34 +16,61 @@ given a mobile version.
Two independent apps that talk over HTTP: Two independent apps that talk over HTTP:
- **`backend/`** — Python + FastAPI. Parses `collection.nml` via - **`backend/`** — Python + FastAPI. Entry point:
`traktor-nml-utils` and serves a query + edit API. Entry point:
[backend/konduktor/main.py](backend/konduktor/main.py). [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 **Architecture: projection + command replay.** The generic model is a *read
(filter/sort/facets/stats) lives here. `replace_track()` refreshes one projection*; edits are strictly-generic commands that a per-platform **adapter**
projection after an edit (bridges the read model and the edit store). replays onto its **retained native model**, which stays the write target. The
- `playlist_store.py` (`PlaylistStore`) — the **edit** model: owns the parsed generic model is NEVER serialized back over a library — that is what preserves
dataclass NML and applies all edits (playlists, track metadata, cover art, byte-exact saves, and it is the only model that works for formats you cannot
AND track-prep edits: hotcues/cues, beatgrid/BPM, lock), then renders + regenerate (a Rekordbox SQLite row, a Serato tag inside an audio file). Traktor
saves. See "Write path" below. is currently the only adapter; see `.claude/discussions/` for the decision log.
- `file_tags.py` — reads/writes embedded audio-file tags & cover art (mutagen)
and resolves Traktor `LOCATION`s to OS paths. Best-effort. - `core/` — **platform-independent. Must not import `traktor_nml_utils` or
- `discovery.py` — finds Traktor collections in their default install location `konduktor.adapters`** (`test_layering.py` enforces this). This is the
(`~/Documents/Native Instruments/Traktor <version>/collection.nml`) for the contract a Rekordbox or Serato adapter will be written against.
picker's "Automatic" option; sorts newest Traktor version first. - `model.py` — the generic model (`Track`, `CuePoint`, `GridMarker`,
- `prefs.py` — tiny persisted user-prefs store in `userprefs.json` (resolved `TrackCues`, `PlaylistNode`, `Facets`, `Stats`, …). Served straight to HTTP.
relative to the package so it travels with the app; gitignored). Holds the - `adapter.py` — the `LibraryAdapter` / `LibraryDriver` protocols and the
last-opened collection path, the library column layout, and the prep deck's error tree (`NotFound` → 404, `InvalidCommand` → 400, `Unsupported` → 422),
main-waveform zoom (`mainZoomSec`). Best-effort I/O. mapped to status codes once in `main.py` rather than per route.
- `schemas.py` — Pydantic response/request models. - `capabilities.py` — `Capabilities`: what the loaded library can persist, so
- `main.py` — FastAPI routes (all under `/api`). Holds an `AppState` with the the UI can gate controls instead of branching on the platform.
currently-loaded collection; it starts **unloaded** and the collection is - `query.py` (`TrackIndex`) — all query/filter/sort/facet/stats logic, over
chosen at runtime via `POST /api/collection/open` (data routes 409 until generic `Track`s. Shared so "sort by artist" cannot mean different things
then). `GET /api/fs/list` powers the in-app file browser; on different platforms behind one UI.
`GET /api/collection/options` feeds the picker's auto-detect + last-opened - `edit_journal.py` (`EditJournal`) — every edit this session at **field
shortcuts; `GET`/`PATCH /api/prefs` persist UI prefs. Setting `KONDUKTOR_NML` resolution** (`track/set/genre`, `cue/add/slot:1`, `grid/marker-bpm/marker:0`).
auto-loads on startup (dev/tests). 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`, `auto_hotcues.py` — format-agnostic helpers.
- `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.
- `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.
- `prefs.py` — persisted user prefs (`userprefs.json` in the per-OS app-data
dir). Last-opened collection, library column layout, prep-deck zoom. 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/collection/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).
- **`frontend/`** — React + TypeScript + Vite. A dark, virtualized track - **`frontend/`** — React + TypeScript + Vite. A dark, virtualized track
explorer. Entry: [frontend/src/App.tsx](frontend/src/App.tsx). explorer. Entry: [frontend/src/App.tsx](frontend/src/App.tsx).
- `api.ts` — typed client + all API types (keep in sync with backend - `api.ts` — typed client + all API types (keep in sync with backend
@@ -129,6 +156,11 @@ serialization path.** It enforces:
The guard that catches serialization regressions like the lxml reformatting bug. The guard that catches serialization regressions like the lxml reformatting bug.
- `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays - `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays
Traktor-valid, backup-first, COLLECTION byte-identical, original untouched. Traktor-valid, backup-first, COLLECTION byte-identical, original untouched.
- `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_layering.py` — `core/` imports nothing platform-specific.
Also validate the backend interactively at `http://localhost:8000/docs` and the Also validate the backend interactively at `http://localhost:8000/docs` and the
frontend at `http://localhost:5173`. frontend at `http://localhost:5173`.
@@ -231,6 +263,10 @@ that number and nothing else — everything derives from it:
- ✅ Flexible beatgrids — the grid is a marker list end to end (marker-level - ✅ 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 commands, piecewise beat math, playhead-derived marker editing). Step 1 of the
multi-platform plan in `.claude/discussions/`. multi-platform plan in `.claude/discussions/`.
- ✅ Generic model + adapter interface (Traktor as the only adapter) — step 2 of
the multi-platform plan. Backend done; the wire format and UI are still
Traktor-shaped (cue type integers, 8 hard-coded hotcue slots) and are next.
- ⬜ Rekordbox adapter; ⬜ Serato adapter; ⬜ export/conversion
- ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging - ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging
## Write path (playlists + track metadata + prep) ## Write path (playlists + track metadata + prep)
@@ -259,7 +295,10 @@ diff — no COLLECTION splicing needed.
`set_hotcue(track_id, slot, start_sec, type, length_sec)` creates/replaces a `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 `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; in **ms**; a loop hotcue carries LEN); `set_hotcue_type` changes just the type;
`delete_hotcue` removes a slot. Hotcue commands **refuse a slot held by a grid `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.) Hotcue commands **refuse a slot held by a grid
marker's companion cue** (see "Beatgrid"). Beatgrid commands are marker-level: marker's companion cue** (see "Beatgrid"). Beatgrid commands are marker-level:
`add_grid_marker` (inherits the governing tempo when no BPM is given), `add_grid_marker` (inherits the governing tempo when no BPM is given),
`move_grid_marker` (clamped between its neighbours, drags the companion), `move_grid_marker` (clamped between its neighbours, drags the companion),
+3
View File
@@ -1,3 +1,6 @@
"""Per-platform adapters. Each owns a native library model and translates the """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. generic commands onto it; nothing outside an adapter package sees a native type.
Importing this package registers every adapter.
""" """
from . import traktor # noqa: F401 — registers the Traktor driver
+10 -1
View File
@@ -1 +1,10 @@
"""The Traktor adapter: NML v20 (Traktor Pro 4) via ``traktor-nml-utils``.""" """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.
"""
from ...core import registry
from .driver import TraktorDriver
TRAKTOR = TraktorDriver()
registry.register(TRAKTOR)
@@ -2,7 +2,7 @@
This is the object the app talks to. It holds: This is the object the app talks to. It holds:
* a ``PlaylistStore`` — the retained NATIVE model, which is the write target. * a ``TraktorStore`` — the retained NATIVE model, which is the write target.
Commands are replayed onto it; it is never regenerated from the projection. Commands are replayed onto it; it is never regenerated from the projection.
* a ``TrackIndex`` — the generic READ projection, rebuilt from the store. * a ``TrackIndex`` — the generic READ projection, rebuilt from the store.
@@ -21,12 +21,13 @@ from ...core.pathmap import PathMapping
from ...core.query import TrackIndex from ...core.query import TrackIndex
from . import capabilities as caps from . import capabilities as caps
from . import projection from . import projection
from .store import PlaylistError, PlaylistStore from .store import PlaylistError, TraktorStore
# Generic cue vocabulary -> Traktor's CUE_V2 TYPE encoding. This table is the # Generic cue vocabulary -> Traktor's CUE_V2 TYPE encoding. This table is the
# only place the integers exist outside the store; type 4 is a grid marker and # only place the integers exist outside the store; type 4 is a grid marker and
# is never a cue, so it has no generic name. # is never a cue, so it has no generic name.
CUE_TYPE_TO_NATIVE = {"cue": 0, "fade_in": 1, "fade_out": 2, "load": 3, "loop": 5} 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()}
class TraktorAdapter: class TraktorAdapter:
@@ -34,7 +35,7 @@ class TraktorAdapter:
def __init__(self, path: Path): def __init__(self, path: Path):
self.path = Path(path) self.path = Path(path)
self._store = PlaylistStore(self.path) self._store = TraktorStore(self.path)
self._index = TrackIndex() self._index = TrackIndex()
self._rebuild() self._rebuild()
@@ -81,7 +82,7 @@ class TraktorAdapter:
# main.py still drives the store directly and calls replace_track after each # 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). # command; both go away when the routes move onto the protocol (step 7).
@property @property
def store(self) -> PlaylistStore: def store(self) -> TraktorStore:
return self._store return self._store
def entries_for(self, track_ids: list[str]) -> list[tuple[str, str]]: def entries_for(self, track_ids: list[str]) -> list[tuple[str, str]]:
@@ -94,8 +95,11 @@ class TraktorAdapter:
self._store._load() self._store._load()
self._rebuild() self._rebuild()
def playlist_count(self) -> int:
return self._store.count_playlists()
def capabilities(self) -> Capabilities: def capabilities(self) -> Capabilities:
return caps.capabilities_for(self.path, sorted(PlaylistStore.EDITABLE_FIELDS)) return caps.capabilities_for(self.path, sorted(TraktorStore.EDITABLE_FIELDS))
# ---- playlists ------------------------------------------------------- # ---- playlists -------------------------------------------------------
def playlist_tree(self) -> list[PlaylistNode]: def playlist_tree(self) -> list[PlaylistNode]:
@@ -0,0 +1,40 @@
"""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"
def can_open(self, path: Path) -> bool:
"""Recognise an NML without parsing 14 MB of it."""
if not path.is_file() or path.suffix.lower() != ".nml":
return False
try:
with path.open("rb") as fh:
head = fh.read(4096)
except OSError:
return False
return b"<NML" in head and b"VERSION=" in head
def open(self, path: Path) -> TraktorAdapter:
return TraktorAdapter(path)
def detect(self) -> list[dict]:
return discovery.detect_collections()
def describe(self, path: Path) -> dict:
return discovery.describe(path)
def restore(self, path: Path, data: bytes) -> None:
"""Write a history snapshot back over the library, atomically."""
tmp = path.with_suffix(path.suffix + ".tmp")
tmp.write_bytes(data)
tmp.replace(path)
+15 -9
View File
@@ -42,7 +42,7 @@ from traktor_nml_utils.models.collection import (
) )
from xsdata.formats.dataclass.serializers import XmlSerializer from xsdata.formats.dataclass.serializers import XmlSerializer
from ... import __version__, history from ...core.adapter import InvalidCommand
from ...core.edit_journal import EditJournal from ...core.edit_journal import EditJournal
from ...core.pathmap import common_dir_prefix from ...core.pathmap import common_dir_prefix
from ...core.pathmap import PathMapping from ...core.pathmap import PathMapping
@@ -55,8 +55,13 @@ from .locations import os_path_to_location, resolve_path
TRAKTOR_POPM_EMAIL = "traktor@native-instruments.de" TRAKTOR_POPM_EMAIL = "traktor@native-instruments.de"
class PlaylistError(Exception): class PlaylistError(InvalidCommand):
pass """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 @dataclass
@@ -70,11 +75,12 @@ class FileTagResult:
@dataclass @dataclass
class SaveOutcome: class SaveOutcome:
commit: str | None # sha of the version-history commit (None if deduped/failed) summary: str # human-readable edit summary, for the version-history message
snapshot: bytes # exactly the bytes written, for the version-history commit
tag_results: list[FileTagResult] tag_results: list[FileTagResult]
class PlaylistStore: class TraktorStore:
def __init__(self, nml_path: Path): def __init__(self, nml_path: Path):
self.nml_path = Path(nml_path) self.nml_path = Path(nml_path)
self._lock = threading.RLock() self._lock = threading.RLock()
@@ -938,11 +944,11 @@ class PlaylistStore:
tmp.replace(self.nml_path) tmp.replace(self.nml_path)
# Best-effort: sync the edited fields into each edited track's file. # Best-effort: sync the edited fields into each edited track's file.
tag_results = self._sync_file_tags() tag_results = self._sync_file_tags()
# Version history: commit the saved bytes (additive — never touches the # Computed before _load() clears the journal. Versioning the bytes is
# file we just wrote). Summary is computed before _load() clears state. # the app's job, not the adapter's — see app_state.AppState.save.
commit = history.commit(self.nml_path, new_data, self._edit_summary(), __version__) summary = self._edit_summary()
self._load() # clears dirty + the edit journal + staged art self._load() # clears dirty + the edit journal + staged art
return SaveOutcome(commit=commit, tag_results=tag_results) return SaveOutcome(summary=summary, snapshot=new_data, tag_results=tag_results)
def _edit_summary(self) -> str: def _edit_summary(self) -> str:
"""Delegates to the journal; kept as a method because save() and the """Delegates to the journal; kept as a method because save() and the
+75
View File
@@ -0,0 +1,75 @@
"""The one loaded library, and the version-history bookkeeping around saving it.
Exactly one library is open 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.
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, 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
@property
def loaded(self) -> bool:
return self.adapter is not None
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)
# 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
# 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()
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
-11
View File
@@ -1,11 +0,0 @@
"""Compatibility shim — this module moved to ``konduktor.core.auto_hotcues``.
Kept so the existing test suite keeps importing the old path unchanged while the
adapter refactor lands; removed in the final cleanup step. Replacing the entry in
``sys.modules`` makes this module *be* the new one, so private names resolve too.
"""
import sys
from .core import auto_hotcues as _moved
sys.modules[__name__] = _moved
-11
View File
@@ -1,11 +0,0 @@
"""Compatibility shim — this module moved to ``konduktor.adapters.traktor.beatgrid``.
Kept so the existing test suite keeps importing the old path unchanged while the
adapter refactor lands; removed in the final cleanup step. Replacing the entry in
``sys.modules`` makes this module *be* the new one, so private names resolve too.
"""
import sys
from .adapters.traktor import beatgrid as _moved
sys.modules[__name__] = _moved
+61
View File
@@ -0,0 +1,61 @@
"""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_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 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() -> tuple[str, ...]:
"""File extensions the in-app browser should show, across all platforms."""
seen: list[str] = []
for d in _DRIVERS:
for suffix in d.suffixes:
if suffix not in seen:
seen.append(suffix)
return tuple(seen)
-11
View File
@@ -1,11 +0,0 @@
"""Compatibility shim — this module moved to ``konduktor.adapters.traktor.discovery``.
Kept so the existing test suite keeps importing the old path unchanged while the
adapter refactor lands; removed in the final cleanup step. Replacing the entry in
``sys.modules`` makes this module *be* the new one, so private names resolve too.
"""
import sys
from .adapters.traktor import discovery as _moved
sys.modules[__name__] = _moved
-17
View File
@@ -1,17 +0,0 @@
"""Compatibility shim — this module was split.
The mutagen read/write half is format-agnostic and moved to
``konduktor.core.audio_tags``; ``resolve_path`` encodes Traktor's LOCATION
convention and moved to ``konduktor.adapters.traktor.locations``. Kept so the
existing test suite keeps importing the old path unchanged; removed in the final
cleanup step.
"""
from .adapters.traktor.locations import resolve_path # noqa: F401
from .core.audio_tags import ( # noqa: F401
DEFAULT_POPM_EMAIL,
TagMeta,
TagResult,
read_cover,
write_cover,
write_tags,
)
+40 -9
View File
@@ -10,7 +10,7 @@ Design rules:
* ALL git interaction is confined to this module. * ALL git interaction is confined to this module.
* EVERY public function is best-effort: it swallows its own errors (returning a * 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. 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' 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 path-based keying). Collection identity is therefore the OS path — moving the
collection starts a fresh history (same fragility prefs already accepts). collection starts a fresh history (same fragility prefs already accepts).
@@ -32,7 +32,17 @@ from . import paths
log = logging.getLogger(__name__) 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 <konduktor@localhost>" _AUTHOR = b"Konduktor <konduktor@localhost>"
@@ -53,8 +63,8 @@ def _repo_dir(nml_path: Path) -> Path:
return paths.app_data_dir() / "history" / _key(nml_path) return paths.app_data_dir() / "history" / _key(nml_path)
def _tracked_file(repo_dir: Path) -> Path: def _tracked_file(repo_dir: Path, nml_path: Path) -> Path:
return repo_dir / _TRACKED_NAME return repo_dir / _tracked_name(nml_path)
def _write_meta(repo_dir: Path, nml_path: Path) -> None: 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 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.""" """The tracked file's bytes at HEAD, or None if the repo has no commits."""
try: try:
head = repo.head() head = repo.head()
@@ -85,7 +113,10 @@ def _head_blob(repo: Repo) -> bytes | None:
return None return None
commit = repo[head] commit = repo[head]
tree = repo[commit.tree] 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 return repo[blob_sha].data
@@ -98,9 +129,9 @@ def commit(nml_path: Path, data: bytes, message: str, app_version: str) -> str |
try: try:
repo_dir = _open_or_init(nml_path) repo_dir = _open_or_init(nml_path)
with Repo(str(repo_dir)) as repo: 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 return None # nothing changed since last version
path = _tracked_file(repo_dir) path = _tracked_file(repo_dir, nml_path)
path.write_bytes(data) path.write_bytes(data)
porcelain.add(str(repo_dir), paths=[str(path)]) porcelain.add(str(repo_dir), paths=[str(path)])
msg = f"{message}\n\nApp-Version: {app_version}".encode() 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: with Repo(str(repo_dir)) as repo:
c = repo[commit_id.encode()] c = repo[commit_id.encode()]
tree = repo[c.tree] tree = repo[c.tree]
_mode, blob_sha = tree[_TRACKED_NAME.encode()] _mode, blob_sha = _tree_blob(tree, nml_path)
return repo[blob_sha].data return repo[blob_sha].data
except Exception: except Exception:
log.exception("history.read_version failed for %s @ %s", nml_path, commit_id) log.exception("history.read_version failed for %s @ %s", nml_path, commit_id)
+140 -223
View File
@@ -11,16 +11,24 @@ from pathlib import Path
from fastapi import FastAPI, File, Form, HTTPException, Query, Response, UploadFile from fastapi import FastAPI, File, Form, HTTPException, Query, Response, UploadFile
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse from fastapi.responses import FileResponse, JSONResponse
from . import __version__ from . import __version__, history, prefs
from .adapters.traktor import projection from .adapters.traktor.adapter import NATIVE_TO_CUE_TYPE
from .adapters.traktor.discovery import describe
from .app_state import STATE
from .core import auto_hotcues as ah from .core import auto_hotcues as ah
from . import history, prefs from .core import registry
from .adapters.traktor.adapter import TraktorAdapter from .core.adapter import (
from .adapters.traktor.discovery import describe, detect_collections AdapterError,
InvalidCommand,
LibraryAdapter,
LibraryNotSupported,
NotFound,
Unsupported,
)
from .core.capabilities import Capabilities
from .core.pathmap import PathMapping from .core.pathmap import PathMapping
from .adapters.traktor.store import PlaylistError, PlaylistStore
from .schemas import ( from .schemas import (
AutoGridRequest, AutoGridRequest,
AutoHotcue, AutoHotcue,
@@ -29,7 +37,6 @@ from .schemas import (
CollectionOptions, CollectionOptions,
CollectionStatus, CollectionStatus,
CreatePlaylist, CreatePlaylist,
CuePoint,
EditState, EditState,
EditTrack, EditTrack,
Facets, Facets,
@@ -37,7 +44,6 @@ from .schemas import (
FsEntry, FsEntry,
FsListing, FsListing,
AddGridMarker, AddGridMarker,
GridMarker,
GridMarkerEdit, GridMarkerEdit,
ReplaceGrid, ReplaceGrid,
HistoryEntry, HistoryEntry,
@@ -76,56 +82,37 @@ app.add_middleware(
) )
class AppState: def _cue_type_name(native: int) -> str:
"""Holds the currently-loaded collection (selectable at runtime).""" """Map the wire's Traktor cue integer onto the generic vocabulary.
def __init__(self) -> None: Transitional: the HTTP contract still carries Traktor's encoding, so the
self.path: Path | None = None translation happens here at the boundary rather than in the adapter.
self.adapter: TraktorAdapter | None = None """
name = NATIVE_TO_CUE_TYPE.get(native)
@property if name is None:
def loaded(self) -> bool: raise HTTPException(400, f"Unsupported cue type: {native}")
return self.adapter is not None return name
def open(self, path: Path) -> None:
# Raises on an invalid/parse-incompatible file; only commit to the new
# collection once it has parsed. One parse — the adapter builds its read
# projection from the same object graph the commands mutate.
adapter = TraktorAdapter(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:
adapter.store.set_path_mapping(PathMapping.make(saved["from"], saved["to"]))
self.path, self.adapter = path, adapter
# 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() def require_adapter() -> LibraryAdapter:
"""The loaded library, or a 409. Routes talk to this and nothing else."""
# 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() -> TraktorAdapter:
if not STATE.loaded: if not STATE.loaded:
raise HTTPException(409, "No collection loaded") raise HTTPException(409, "No collection loaded")
assert STATE.adapter is not None assert STATE.adapter is not None
return STATE.adapter return STATE.adapter
def require_store() -> PlaylistStore: @app.exception_handler(AdapterError)
if not STATE.loaded: def _adapter_error(_request, exc: AdapterError):
raise HTTPException(409, "No collection loaded") """Map the adapter's error vocabulary onto status codes in one place, so no
assert STATE.adapter is not None route has to guess whether a given failure is a 400 or a 404."""
return STATE.adapter.store status = {
NotFound: 404,
InvalidCommand: 400,
Unsupported: 422,
LibraryNotSupported: 400,
}.get(type(exc), 400)
return JSONResponse(status_code=status, content={"detail": str(exc)})
# ---- collection selection --------------------------------------------- # ---- collection selection ---------------------------------------------
@@ -138,8 +125,8 @@ def collection_status() -> CollectionStatus:
return CollectionStatus( return CollectionStatus(
loaded=True, loaded=True,
path=str(STATE.path), path=str(STATE.path),
tracks=len(require_service().tracks), tracks=len(require_adapter().tracks),
playlists=require_store().count_playlists(), playlists=require_adapter().playlist_count(),
) )
@@ -150,10 +137,10 @@ def open_collection(body: OpenCollection) -> CollectionStatus:
raise HTTPException(400, f"File not found: {path}") raise HTTPException(400, f"File not found: {path}")
try: try:
STATE.open(path) STATE.open(path)
except PlaylistError as ex: except AdapterError as ex:
raise HTTPException(400, f"Not a valid Traktor collection: {ex}") raise HTTPException(400, f"Not a valid collection: {ex}")
except Exception as ex: # noqa: BLE001 except Exception as ex: # noqa: BLE001
raise HTTPException(400, f"Could not parse as a Traktor collection: {ex}") raise HTTPException(400, f"Could not open that collection: {ex}")
prefs.set_last_collection(str(path)) prefs.set_last_collection(str(path))
return collection_status() return collection_status()
@@ -162,7 +149,7 @@ def open_collection(body: OpenCollection) -> CollectionStatus:
def collection_options() -> CollectionOptions: def collection_options() -> CollectionOptions:
"""Startup shortcuts for the picker: the best auto-detected Traktor """Startup shortcuts for the picker: the best auto-detected Traktor
collection and the last one opened (may no longer exist → exists=False).""" collection and the last one opened (may no longer exist → exists=False)."""
detected = detect_collections() detected = registry.detect_all()
auto = CollectionCandidate(**detected[0]) if detected else None auto = CollectionCandidate(**detected[0]) if detected else None
recent = None recent = None
last = prefs.get_last_collection() last = prefs.get_last_collection()
@@ -174,7 +161,7 @@ def collection_options() -> CollectionOptions:
@app.get("/api/collection/path-mapping", response_model=PathMappingInfo) @app.get("/api/collection/path-mapping", response_model=PathMappingInfo)
def get_path_mapping() -> PathMappingInfo: def get_path_mapping() -> PathMappingInfo:
"""The current collection's saved OS-path remapping (blank if none).""" """The current collection's saved OS-path remapping (blank if none)."""
require_store() require_adapter()
saved = prefs.get_path_mapping(str(STATE.path)) saved = prefs.get_path_mapping(str(STATE.path))
if saved: if saved:
return PathMappingInfo.model_validate({"from": saved["from"], "to": saved["to"]}) return PathMappingInfo.model_validate({"from": saved["from"], "to": saved["to"]})
@@ -186,12 +173,12 @@ def put_path_mapping(body: PathMappingInfo) -> PathMappingInfo:
"""Set (or, with blank prefixes, clear) the current collection's remapping. """Set (or, with blank prefixes, clear) the current collection's remapping.
Persists to userprefs AND updates the live store so playback/analysis Persists to userprefs AND updates the live store so playback/analysis
re-resolve immediately — no reopen needed. Never touches the .nml.""" re-resolve immediately — no reopen needed. Never touches the .nml."""
store = require_store() a = require_adapter()
mapping = PathMapping.make(body.from_, body.to) mapping = PathMapping.make(body.from_, body.to)
prefs.set_path_mapping( prefs.set_path_mapping(
str(STATE.path), mapping.from_prefix or None, mapping.to_prefix or None 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( return PathMappingInfo.model_validate(
{"from": mapping.from_prefix, "to": mapping.to_prefix} {"from": mapping.from_prefix, "to": mapping.to_prefix}
) )
@@ -201,8 +188,7 @@ def put_path_mapping(body: PathMappingInfo) -> PathMappingInfo:
def suggest_path_prefix() -> PrefixSuggestions: def suggest_path_prefix() -> PrefixSuggestions:
"""Auto-detected `from` prefix candidates (common directory per volume), """Auto-detected `from` prefix candidates (common directory per volume),
so the editor can prefill the stored prefix.""" so the editor can prefill the stored prefix."""
store = require_store() return PrefixSuggestions.model_validate(require_adapter().path_prefix_suggestions())
return PrefixSuggestions.model_validate(store.path_prefix_suggestions())
@app.get("/api/collection/path-mapping/preview", response_model=RemapPreview) @app.get("/api/collection/path-mapping/preview", response_model=RemapPreview)
@@ -211,8 +197,9 @@ def preview_path_mapping(
) -> RemapPreview: ) -> RemapPreview:
"""Validate a candidate mapping before saving/committing: how many tracks """Validate a candidate mapping before saving/committing: how many tracks
match `from` and how many exist at `to`.""" match `from` and how many exist at `to`."""
store = require_store() return RemapPreview.model_validate(
return RemapPreview.model_validate(store.remap_preview(PathMapping.make(from_, to))) require_adapter().remap_preview(PathMapping.make(from_, to))
)
@app.post("/api/collection/remap-paths", response_model=RemapResult) @app.post("/api/collection/remap-paths", response_model=RemapResult)
@@ -221,15 +208,16 @@ def remap_paths(body: PathMappingInfo) -> RemapResult:
playlist references that join to them) to the `to` prefix, then save (a playlist references that join to them) to the `to` prefix, then save (a
version-history commit is written). Destructive and OS-specific — the UI version-history commit is written). Destructive and OS-specific — the UI
warns accordingly.""" warns accordingly."""
store = require_store()
mapping = PathMapping.make(body.from_, body.to) mapping = PathMapping.make(body.from_, body.to)
if mapping.empty: if mapping.empty:
raise HTTPException(400, "Both a `from` and `to` prefix are required") raise HTTPException(400, "Both a `from` and `to` prefix are required")
count = store.remap_locations(mapping) count = require_adapter().remap_locations(mapping)
if count == 0: if count == 0:
return RemapResult(rewritten=0, commit=None) return RemapResult(rewritten=0, commit=None)
outcome = store.save() # Through AppState, not the adapter: this is the one route besides /api/save
return RemapResult(rewritten=count, commit=outcome.commit) # that writes, and skipping it would leave a gap in the version history.
_outcome, commit = STATE.save()
return RemapResult(rewritten=count, commit=commit)
@app.get("/api/prefs") @app.get("/api/prefs")
@@ -260,7 +248,7 @@ def fs_list(path: str | None = None) -> FsListing:
try: try:
if entry.is_dir(): if entry.is_dir():
dirs.append(FsEntry(name=entry.name, path=str(entry))) dirs.append(FsEntry(name=entry.name, path=str(entry)))
elif entry.suffix.lower() == ".nml": elif entry.suffix.lower() in registry.browsable_suffixes():
files.append(FsEntry(name=entry.name, path=str(entry))) files.append(FsEntry(name=entry.name, path=str(entry)))
except OSError: except OSError:
continue continue
@@ -280,10 +268,15 @@ def health() -> dict:
return {"status": "ok", "loaded": STATE.loaded, "path": str(STATE.path) if STATE.path else None} return {"status": "ok", "loaded": STATE.loaded, "path": str(STATE.path) if STATE.path else None}
@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) @app.get("/api/state", response_model=EditState)
def state() -> EditState: def state() -> EditState:
store = require_store() return EditState(dirty=require_adapter().dirty, nml_path=str(STATE.path))
return EditState(dirty=store.dirty, nml_path=str(STATE.path))
@app.post("/api/reload") @app.post("/api/reload")
@@ -291,7 +284,7 @@ def reload_collection() -> dict:
if not STATE.loaded: if not STATE.loaded:
raise HTTPException(409, "No collection loaded") raise HTTPException(409, "No collection loaded")
STATE.open(STATE.path) # re-parse current file from disk 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 ------------------------------------ # ---- read: stats / facets / tracks ------------------------------------
@@ -299,12 +292,13 @@ def reload_collection() -> dict:
@app.get("/api/stats", response_model=Stats) @app.get("/api/stats", response_model=Stats)
def stats() -> 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) @app.get("/api/facets", response_model=Facets)
def facets() -> Facets: def facets() -> Facets:
return require_service().facets() return require_adapter().facets()
@app.get("/api/tracks", response_model=TrackPage) @app.get("/api/tracks", response_model=TrackPage)
@@ -321,7 +315,7 @@ def tracks(
limit: int = Query(100, ge=1, le=20000), limit: int = Query(100, ge=1, le=20000),
offset: int = Query(0, ge=0), offset: int = Query(0, ge=0),
) -> TrackPage: ) -> 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, 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, rating_min=rating_min, has_cues=has_cues, sort=sort, order=order,
limit=limit, offset=offset, limit=limit, offset=offset,
@@ -333,16 +327,15 @@ def tracks(
@app.get("/api/playlists", response_model=list[PlaylistNode]) @app.get("/api/playlists", response_model=list[PlaylistNode])
def playlists() -> 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]) @app.get("/api/playlists/{playlist_id}/tracks", response_model=list[Track])
def playlist_tracks(playlist_id: str) -> list[Track]: def playlist_tracks(playlist_id: str) -> list[Track]:
keys = require_store().entry_keys(playlist_id) tracks = require_adapter().playlist_tracks(playlist_id)
if keys is None: if tracks is None:
raise HTTPException(404, f"Playlist not found: {playlist_id}") raise HTTPException(404, f"Playlist not found: {playlist_id}")
svc = require_service() return tracks
return [svc.by_key[k] for k in keys if k in svc.by_key]
# ---- write: playlist editing ------------------------------------------ # ---- write: playlist editing ------------------------------------------
@@ -350,76 +343,54 @@ def playlist_tracks(playlist_id: str) -> list[Track]:
@app.post("/api/playlists", response_model=PlaylistNode) @app.post("/api/playlists", response_model=PlaylistNode)
def create_playlist(body: CreatePlaylist) -> PlaylistNode: def create_playlist(body: CreatePlaylist) -> PlaylistNode:
store = require_store() new_id = require_adapter().create_playlist(
try: body.name.strip() or "New Playlist", body.parent_id
new_uuid = store.create_playlist(body.name.strip() or "New Playlist", body.parent_id) )
except PlaylistError as ex: return PlaylistNode(id=new_id, name=body.name, type="PLAYLIST", uuid=new_id, count=0)
raise HTTPException(400, str(ex))
return PlaylistNode(id=new_uuid, name=body.name, type="PLAYLIST", uuid=new_uuid, count=0)
@app.patch("/api/playlists/{playlist_uuid}") @app.patch("/api/playlists/{playlist_uuid}")
def rename_playlist(playlist_uuid: str, body: RenamePlaylist) -> dict: def rename_playlist(playlist_uuid: str, body: RenamePlaylist) -> dict:
try: require_adapter().rename_playlist(playlist_uuid, body.name.strip())
require_store().rename_playlist(playlist_uuid, body.name.strip())
except PlaylistError as ex:
raise HTTPException(404, str(ex))
return {"status": "renamed", "id": playlist_uuid, "name": body.name} return {"status": "renamed", "id": playlist_uuid, "name": body.name}
@app.delete("/api/playlists/{playlist_uuid}") @app.delete("/api/playlists/{playlist_uuid}")
def delete_playlist(playlist_uuid: str) -> dict: def delete_playlist(playlist_uuid: str) -> dict:
try: require_adapter().delete_playlist(playlist_uuid)
require_store().delete_playlist(playlist_uuid)
except PlaylistError as ex:
raise HTTPException(404, str(ex))
return {"status": "deleted", "id": playlist_uuid} return {"status": "deleted", "id": playlist_uuid}
@app.put("/api/playlists/{playlist_uuid}/entries") @app.put("/api/playlists/{playlist_uuid}/entries")
def set_entries(playlist_uuid: str, body: SetEntries) -> dict: def set_entries(playlist_uuid: str, body: SetEntries) -> dict:
store = require_store() n = require_adapter().set_playlist_entries(playlist_uuid, body.track_ids)
entries = require_service().entries_for(body.track_ids) return {"status": "updated", "id": playlist_uuid, "count": n}
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)}
@app.post("/api/playlists/{playlist_uuid}/add") @app.post("/api/playlists/{playlist_uuid}/add")
def add_entries(playlist_uuid: str, body: SetEntries) -> dict: def add_entries(playlist_uuid: str, body: SetEntries) -> dict:
"""Append tracks to a playlist (skips ids already present).""" """Append tracks to a playlist (skips ids already present)."""
store = require_store() a = require_adapter()
current = store.entry_keys(playlist_uuid) current = a.playlist_entries(playlist_uuid)
if current is None: if current is None:
raise HTTPException(404, f"Playlist not found: {playlist_uuid}") raise HTTPException(404, f"Playlist not found: {playlist_uuid}")
have = set(current) have = set(current)
added = [tid for tid in body.track_ids if tid not in have] added = [tid for tid in body.track_ids if tid not in have]
entries = require_service().entries_for(current + added) n = a.set_playlist_entries(playlist_uuid, current + added)
store.set_entries(playlist_uuid, entries) return {"status": "added", "id": playlist_uuid, "added": len(added), "count": n}
return {"status": "added", "id": playlist_uuid, "added": len(added), "count": len(entries)}
@app.patch("/api/tracks") @app.patch("/api/tracks")
def edit_track(body: EditTrack) -> dict: def edit_track(body: EditTrack) -> dict:
"""Edit a single track's safe metadata fields (in-memory; persisted on save).""" """Edit a single track's safe metadata fields (in-memory; persisted on save)."""
store = require_store() require_adapter().set_track_metadata(body.track_id, body.fields)
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)
return {"status": "updated", "id": body.track_id} return {"status": "updated", "id": body.track_id}
@app.get("/api/tracks/art") @app.get("/api/tracks/art")
def track_art(track_id: str) -> Response: def track_art(track_id: str) -> Response:
"""Stream a track's embedded cover art (staged replacement if unsaved).""" """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: if art is None:
raise HTTPException(404, "No cover art") raise HTTPException(404, "No cover art")
data, mime = art data, mime = art
@@ -442,7 +413,7 @@ _AUDIO_MIME = {
@app.get("/api/tracks/audio") @app.get("/api/tracks/audio")
def track_audio(track_id: str) -> FileResponse: def track_audio(track_id: str) -> FileResponse:
"""Stream a track's audio file for playback (supports HTTP Range/seeking).""" """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: if path is None:
raise HTTPException(404, "Track not found") raise HTTPException(404, "Track not found")
if not path.exists(): if not path.exists():
@@ -454,17 +425,11 @@ def track_audio(track_id: str) -> FileResponse:
return FileResponse(path, media_type=mime) return FileResponse(path, media_type=mime)
# Compatibility alias — the cue projection moved into the Traktor adapter.
# Kept so test_save_fidelity's invariant K imports the old name unchanged while
# the refactor lands; removed in the final cleanup step.
_build_track_cues = projection.to_track_cues
def _cues_for(track_id: str) -> TrackCues: def _cues_for(track_id: str) -> TrackCues:
entry = require_store().model_entry(track_id) cues = require_adapter().track_cues(track_id)
if entry is None: if cues is None:
raise HTTPException(404, "Track not found") raise HTTPException(404, "Track not found")
return projection.to_track_cues(entry) return cues
@app.get("/api/tracks/cues", response_model=TrackCues) @app.get("/api/tracks/cues", response_model=TrackCues)
@@ -473,25 +438,17 @@ def track_cues(track_id: str) -> TrackCues:
return _cues_for(track_id) 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 projection.to_track_cues(entry) if entry is not None else TrackCues()
@app.post("/api/tracks/hotcue", response_model=TrackCues) @app.post("/api/tracks/hotcue", response_model=TrackCues)
def create_hotcue(body: SetHotcue) -> TrackCues: def create_hotcue(body: SetHotcue) -> TrackCues:
"""Create (or reposition + retype) the hotcue in a slot at a position.""" """Create (or reposition + retype) the hotcue in a slot at a position."""
try: return require_adapter().set_cue(
require_store().set_hotcue( body.track_id,
body.track_id, body.slot, body.start, body.type, body.length, name=body.name slot=body.slot,
start_sec=body.start,
cue_type=_cue_type_name(body.type),
length_sec=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) @app.post("/api/tracks/auto-hotcues", response_model=TrackCues)
@@ -501,14 +458,13 @@ def auto_hotcues(body: AutoHotcuesRequest) -> TrackCues:
Detects section boundaries (librosa Laplacian segmentation), snaps them to Detects section boundaries (librosa Laplacian segmentation), snaps them to
the track's beatgrid phrases, names them positionally, and places up to the track's beatgrid phrases, names them positionally, and places up to
MAX_HOTCUES into empty slots only (never overwrites). Requires a beatgrid.""" MAX_HOTCUES into empty slots only (never overwrites). Requires a beatgrid."""
store = require_store() a = require_adapter()
entry = store.model_entry(body.track_id) cues = a.track_cues(body.track_id)
if entry is None: if cues is None:
raise HTTPException(404, "Track not found") raise HTTPException(404, "Track not found")
cues = projection.to_track_cues(entry)
if not cues.grid_markers: if not cues.grid_markers:
raise HTTPException(400, "Set a beatgrid before using Auto Hotcues") raise HTTPException(400, "Set a beatgrid before using Auto Hotcues")
path = store.audio_path(body.track_id) path = a.audio_path(body.track_id)
if path is None or not path.exists(): if path is None or not path.exists():
raise HTTPException(400, "Audio file not found (is the drive mounted?)") raise HTTPException(400, "Audio file not found (is the drive mounted?)")
@@ -517,8 +473,9 @@ def auto_hotcues(body: AutoHotcuesRequest) -> TrackCues:
except Exception as ex: # analysis is best-effort; never 500 the UI except Exception as ex: # analysis is best-effort; never 500 the UI
raise HTTPException(400, f"Analysis failed: {ex}") raise HTTPException(400, f"Analysis failed: {ex}")
slots = a.capabilities().cues.hotcue_slots
occupied = {c.hotcue for c in cues.cues if c.hotcue is not None and c.hotcue >= 0} 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] free = [s for s in range(slots) if s not in occupied]
existing_times = [c.start for c in cues.cues if c.hotcue is not None and c.hotcue >= 0] existing_times = [c.start for c in cues.cues if c.hotcue is not None and c.hotcue >= 0]
specs = ah.select_hotcues( specs = ah.select_hotcues(
boundaries, boundaries,
@@ -526,15 +483,11 @@ def auto_hotcues(body: AutoHotcuesRequest) -> TrackCues:
duration=duration, duration=duration,
free_slots=free, free_slots=free,
existing_times=existing_times, existing_times=existing_times,
max_cues=body.max_cues or ah.MAX_HOTCUES, max_cues=body.max_cues or slots,
) )
if not specs: if not specs:
return cues # no confident structure / no free slots — leave untouched return cues # no confident structure / no free slots — leave untouched
try: return a.place_cues(body.track_id, [AutoHotcue(**s) for s in specs])
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) @app.post("/api/tracks/auto-grid", response_model=TrackCues)
@@ -542,54 +495,39 @@ def auto_grid(body: AutoGridRequest) -> TrackCues:
"""Detect tempo + first beat and build a beatgrid: sets BPM, sets hotcue 1 """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 (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.""" (half/double) errors are left for the user to fix with the ×2/÷2 controls."""
store = require_store() a = require_adapter()
if store.model_entry(body.track_id) is None: if a.track(body.track_id) is None:
raise HTTPException(404, "Track not found") raise HTTPException(404, "Track not found")
path = store.audio_path(body.track_id) path = a.audio_path(body.track_id)
if path is None or not path.exists(): if path is None or not path.exists():
raise HTTPException(400, "Audio file not found (is the drive mounted?)") raise HTTPException(400, "Audio file not found (is the drive mounted?)")
try: try:
bpm, first_beat = ah.detect_grid(str(path)) bpm, first_beat = ah.detect_grid(str(path))
except Exception as ex: # analysis is best-effort; never 500 the UI except Exception as ex: # analysis is best-effort; never 500 the UI
raise HTTPException(400, f"Analysis failed: {ex}") raise HTTPException(400, f"Analysis failed: {ex}")
try: # "Analysed", not "replace": each platform writes an analysis result in its
store.replace_grid(body.track_id, [(first_beat, bpm)]) # own shape (Traktor pairs the first marker with a beat-1 cue).
# Traktor pairs its own grid markers with a white beat-1 cue; mirror return a.set_analysed_grid(body.track_id, [(first_beat, bpm)])
# that, but never over an existing hotcue (the old code clobbered slot 0).
store.place_grid_companion(body.track_id, 0, prefer_slot=0)
except PlaylistError as ex:
raise HTTPException(400, str(ex))
return _sync_cue_edit(body.track_id)
@app.patch("/api/tracks/hotcue", response_model=TrackCues) @app.patch("/api/tracks/hotcue", response_model=TrackCues)
def edit_hotcue_type(body: SetHotcueType) -> TrackCues: def edit_hotcue_type(body: SetHotcueType) -> TrackCues:
"""Change the type of an existing hotcue (keeps its position).""" """Change the type of an existing hotcue (keeps its position)."""
try: return require_adapter().set_cue_type(
require_store().set_hotcue_type(body.track_id, body.slot, body.type) body.track_id, body.slot, _cue_type_name(body.type)
except PlaylistError as ex: )
raise HTTPException(400, str(ex))
return _sync_cue_edit(body.track_id)
@app.delete("/api/tracks/hotcue", response_model=TrackCues) @app.delete("/api/tracks/hotcue", response_model=TrackCues)
def delete_hotcue(track_id: str, slot: int) -> TrackCues: def delete_hotcue(track_id: str, slot: int) -> TrackCues:
"""Remove the hotcue in a slot.""" """Remove the hotcue in a slot."""
try: return require_adapter().delete_cue(track_id, slot)
require_store().delete_hotcue(track_id, slot)
except PlaylistError as ex:
raise HTTPException(400, str(ex))
return _sync_cue_edit(track_id)
@app.post("/api/tracks/grid/marker", response_model=TrackCues) @app.post("/api/tracks/grid/marker", response_model=TrackCues)
def add_grid_marker(body: AddGridMarker) -> TrackCues: def add_grid_marker(body: AddGridMarker) -> TrackCues:
"""Add a beatgrid marker. Omitting `bpm` inherits the governing tempo.""" """Add a beatgrid marker. Omitting `bpm` inherits the governing tempo."""
try: return require_adapter().add_grid_marker(body.track_id, body.start, body.bpm)
require_store().add_grid_marker(body.track_id, body.start, body.bpm)
except PlaylistError as ex:
raise HTTPException(400, str(ex))
return _sync_cue_edit(body.track_id)
@app.patch("/api/tracks/grid/marker", response_model=TrackCues) @app.patch("/api/tracks/grid/marker", response_model=TrackCues)
@@ -599,84 +537,64 @@ def edit_grid_marker(body: GridMarkerEdit) -> TrackCues:
BPM is applied before the move: a tempo change can never reorder markers, so BPM is applied before the move: a tempo change can never reorder markers, so
`index` is still valid for the move afterwards. `index` is still valid for the move afterwards.
""" """
store = require_store() a = require_adapter()
try: cues = a.track_cues(body.track_id)
if body.bpm is not None: if body.bpm is not None:
store.set_grid_marker_bpm(body.track_id, body.index, body.bpm) cues = a.set_grid_marker_bpm(body.track_id, body.index, body.bpm)
if body.start is not None: if body.start is not None:
store.move_grid_marker(body.track_id, body.index, body.start) cues = a.move_grid_marker(body.track_id, body.index, body.start)
except PlaylistError as ex: if cues is None:
raise HTTPException(400, str(ex)) raise HTTPException(404, "Track not found")
return _sync_cue_edit(body.track_id) return cues
@app.delete("/api/tracks/grid/marker", response_model=TrackCues) @app.delete("/api/tracks/grid/marker", response_model=TrackCues)
def remove_grid_marker(track_id: str, index: int) -> TrackCues: def remove_grid_marker(track_id: str, index: int) -> TrackCues:
"""Delete one grid marker (and its companion cue).""" """Delete one grid marker (and its companion cue)."""
try: return require_adapter().delete_grid_marker(track_id, index)
require_store().delete_grid_marker(track_id, index)
except PlaylistError as ex:
raise HTTPException(400, str(ex))
return _sync_cue_edit(track_id)
@app.put("/api/tracks/grid", response_model=TrackCues) @app.put("/api/tracks/grid", response_model=TrackCues)
def replace_grid(body: ReplaceGrid) -> TrackCues: def replace_grid(body: ReplaceGrid) -> TrackCues:
"""Replace the whole beatgrid (the deck's Reset). `markers: []` clears it.""" """Replace the whole beatgrid (the deck's Reset). `markers: []` clears it."""
try: return require_adapter().replace_grid(
require_store().replace_grid(
body.track_id, [(m.start, m.bpm) for m in body.markers] body.track_id, [(m.start, m.bpm) for m in body.markers]
) )
except PlaylistError as ex:
raise HTTPException(400, str(ex))
return _sync_cue_edit(body.track_id)
@app.delete("/api/tracks/grid", response_model=TrackCues) @app.delete("/api/tracks/grid", response_model=TrackCues)
def remove_grid(track_id: str) -> TrackCues: def remove_grid(track_id: str) -> TrackCues:
"""Delete every grid marker and its companion cue. <TEMPO> is kept.""" """Delete every grid marker and its companion cue. <TEMPO> is kept."""
try: return require_adapter().delete_grid(track_id)
require_store().delete_grid(track_id)
except PlaylistError as ex:
raise HTTPException(400, str(ex))
return _sync_cue_edit(track_id)
@app.patch("/api/tracks/lock", response_model=TrackCues) @app.patch("/api/tracks/lock", response_model=TrackCues)
def edit_lock(body: SetLock) -> TrackCues: def edit_lock(body: SetLock) -> TrackCues:
"""Toggle Traktor's LOCK flag on a track.""" """Toggle Traktor's LOCK flag on a track."""
try: return require_adapter().set_grid_lock(body.track_id, body.locked)
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)
@app.put("/api/tracks/art") @app.put("/api/tracks/art")
async def set_track_art(track_id: str = Form(...), file: UploadFile = File(...)) -> dict: 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).""" """Stage replacement cover art for a track (written to the file on save)."""
store = require_store() a = require_adapter()
data = await file.read() data = await file.read()
if not data: if not data:
raise HTTPException(400, "Empty image") raise HTTPException(400, "Empty image")
mime = file.content_type or "image/jpeg" a.set_cover_art(track_id, data, file.content_type or "image/jpeg")
try:
store.set_track_art(track_id, data, mime)
except PlaylistError as ex:
raise HTTPException(404, str(ex))
return {"status": "staged", "id": track_id, "bytes": len(data)} return {"status": "staged", "id": track_id, "bytes": len(data)}
@app.post("/api/save", response_model=SaveResult) @app.post("/api/save", response_model=SaveResult)
def save() -> SaveResult: def save() -> SaveResult:
store = require_store() a = require_adapter()
if not store.dirty: if not a.dirty:
return SaveResult(saved=False, commit=None, playlists=store.count_playlists()) return SaveResult(saved=False, commit=None, playlists=a.playlist_count())
outcome = store.save() outcome, commit = STATE.save()
return SaveResult( return SaveResult(
saved=True, saved=True,
commit=outcome.commit, commit=commit,
playlists=store.count_playlists(), playlists=a.playlist_count(),
file_tags=[FileTagOutcome(**r.__dict__) for r in outcome.tag_results], file_tags=[FileTagOutcome(**r.__dict__) for r in outcome.tag_results],
) )
@@ -687,7 +605,7 @@ def save() -> SaveResult:
@app.get("/api/history", response_model=list[HistoryEntry]) @app.get("/api/history", response_model=list[HistoryEntry])
def get_history() -> list[HistoryEntry]: def get_history() -> list[HistoryEntry]:
"""All saved versions of the current collection, newest first.""" """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)] return [HistoryEntry(**e.__dict__) for e in history.list_history(STATE.path)]
@@ -696,14 +614,13 @@ def restore_version(commit_id: str) -> CollectionStatus:
"""Restore the collection to a past version. Writes that version back as a """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 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).""" reloads. The user should close Traktor first (it overwrites on exit)."""
require_store() require_adapter()
data = history.read_version(STATE.path, commit_id) data = history.read_version(STATE.path, commit_id)
if data is None: if data is None:
raise HTTPException(404, f"Version not found: {commit_id}") raise HTTPException(404, f"Version not found: {commit_id}")
path = STATE.path path = STATE.path
tmp = path.with_suffix(path.suffix + ".tmp") # The adapter's driver owns writing its own format back, even for a restore.
tmp.write_bytes(data) registry.driver_for(path).restore(path, data)
tmp.replace(path)
history.commit(path, data, f"Restored version {commit_id[:8]}", __version__) history.commit(path, data, f"Restored version {commit_id[:8]}", __version__)
STATE.open(path) # rebuild read + edit models from the restored file STATE.open(path) # rebuild read + edit models from the restored file
return collection_status() return collection_status()
@@ -712,6 +629,6 @@ def restore_version(commit_id: str) -> CollectionStatus:
@app.delete("/api/history") @app.delete("/api/history")
def clear_history() -> dict: def clear_history() -> dict:
"""Permanently delete ALL version history for the current collection.""" """Permanently delete ALL version history for the current collection."""
require_store() require_adapter()
history.clear_history(STATE.path) history.clear_history(STATE.path)
return {"status": "cleared"} return {"status": "cleared"}
-10
View File
@@ -1,10 +0,0 @@
"""Compatibility shim — this module was split.
``PathMapping``/``common_dir_prefix`` are format-agnostic and moved to
``konduktor.core.pathmap``; ``os_path_to_location`` is the inverse of Traktor's
``resolve_path`` and moved to ``konduktor.adapters.traktor.locations``. Kept so
the existing test suite keeps importing the old path unchanged; removed in the
final cleanup step.
"""
from .adapters.traktor.locations import os_path_to_location # noqa: F401
from .core.pathmap import PathMapping, common_dir_prefix # noqa: F401
-11
View File
@@ -1,11 +0,0 @@
"""Compatibility shim — this module moved to ``konduktor.adapters.traktor.store``.
Kept so the existing test suite keeps importing the old path unchanged while the
adapter refactor lands; removed in the final cleanup step. Replacing the entry in
``sys.modules`` makes this module *be* the new one, so private names resolve too.
"""
import sys
from .adapters.traktor import store as _moved
sys.modules[__name__] = _moved
+32 -27
View File
@@ -1,4 +1,8 @@
"""Regression guard for save fidelity — keeps playlist diffs minimal. """Regression guard for save fidelity — the Traktor adapter's byte contract.
This is deliberately a TRAKTOR test: it constructs the store directly and
asserts on rendered bytes, which is exactly the level the guarantee lives at.
The generic layer above it is covered by test_traktor_adapter.py.
This is the test that would have caught the lxml reformatting bug. It asserts This is the test that would have caught the lxml reformatting bug. It asserts
two invariants against a COPY of the real collection: two invariants against a COPY of the real collection:
@@ -30,7 +34,7 @@ os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-fidelity-a
REAL = Path(__file__).resolve().parents[1] / "collection.nml" REAL = Path(__file__).resolve().parents[1] / "collection.nml"
from konduktor.playlist_store import PlaylistError, PlaylistStore # noqa: E402 from konduktor.adapters.traktor.store import PlaylistError, TraktorStore # noqa: E402
failed = False failed = False
@@ -71,7 +75,7 @@ with tempfile.TemporaryDirectory() as d:
work = Path(d) / "collection.nml" work = Path(d) / "collection.nml"
shutil.copy2(REAL, work) shutil.copy2(REAL, work)
before = work.read_bytes() before = work.read_bytes()
store = PlaylistStore(work) store = TraktorStore(work)
store.save() # no edits store.save() # no edits
after = work.read_bytes() after = work.read_bytes()
check("whole file identical after no-op save", before == after) check("whole file identical after no-op save", before == after)
@@ -91,7 +95,7 @@ with tempfile.TemporaryDirectory() as d:
shutil.copy2(REAL, work) shutil.copy2(REAL, work)
original = work.read_bytes() original = work.read_bytes()
store = PlaylistStore(work) store = TraktorStore(work)
def walk(n): def walk(n):
yield n yield n
@@ -139,7 +143,7 @@ with tempfile.TemporaryDirectory() as d:
shutil.copy2(REAL, work) shutil.copy2(REAL, work)
original = work.read_bytes() original = work.read_bytes()
store = PlaylistStore(work) store = TraktorStore(work)
# pick the first track that has a resolvable primary key # pick the first track that has a resolvable primary key
entry = store._nml.collection.entry[0] entry = store._nml.collection.entry[0]
loc = entry.location loc = entry.location
@@ -185,7 +189,7 @@ with tempfile.TemporaryDirectory() as d:
shutil.copy2(REAL, work) shutil.copy2(REAL, work)
original = work.read_bytes() original = work.read_bytes()
store = PlaylistStore(work) store = TraktorStore(work)
entry = store._nml.collection.entry[0] entry = store._nml.collection.entry[0]
loc = entry.location loc = entry.location
track_id = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}" track_id = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}"
@@ -224,21 +228,21 @@ with tempfile.TemporaryDirectory() as d:
check("hotcue START stored in ms", new_cue is not None and abs(new_cue.start - 42500.0) < 1) check("hotcue START stored in ms", new_cue is not None and abs(new_cue.start - 42500.0) < 1)
# Create then delete must round-trip back to a byte-identical file. # Create then delete must round-trip back to a byte-identical file.
store2 = PlaylistStore(work) # reload the edited file store2 = TraktorStore(work) # reload the edited file
store2.delete_hotcue(track_id, slot) store2.delete_hotcue(track_id, slot)
store2.save() store2.save()
check("create+delete round-trips to the original bytes", work.read_bytes() == original) check("create+delete round-trips to the original bytes", work.read_bytes() == original)
# ---- Invariant E: a beatgrid edit is fully localized ------------------- # ---- Invariant E: a beatgrid edit is fully localized -------------------
print("== E. grid marker edit touches only that track's ENTRY ==") print("== E. grid marker edit touches only that track's ENTRY ==")
from konduktor import beatgrid as bg # noqa: E402 from konduktor.adapters.traktor import beatgrid as bg # noqa: E402
with tempfile.TemporaryDirectory() as d: with tempfile.TemporaryDirectory() as d:
work = Path(d) / "collection.nml" work = Path(d) / "collection.nml"
shutil.copy2(REAL, work) shutil.copy2(REAL, work)
original = work.read_bytes() original = work.read_bytes()
store = PlaylistStore(work) store = TraktorStore(work)
def _key(e): def _key(e):
loc = e.location loc = e.location
@@ -305,7 +309,7 @@ with tempfile.TemporaryDirectory() as d:
check("companion kept its hotcue slot", comp is not None and comp.hotcue == comp_slot) check("companion kept its hotcue slot", comp is not None and comp.hotcue == comp_slot)
# Reverting BPM + position round-trips to the original bytes. # Reverting BPM + position round-trips to the original bytes.
store2 = PlaylistStore(work) store2 = TraktorStore(work)
store2.set_grid_marker_bpm(track_id, 0, orig_bpm) store2.set_grid_marker_bpm(track_id, 0, orig_bpm)
store2.move_grid_marker(track_id, 0, orig_anchor_ms / 1000.0) store2.move_grid_marker(track_id, 0, orig_anchor_ms / 1000.0)
store2.save() store2.save()
@@ -314,13 +318,13 @@ with tempfile.TemporaryDirectory() as d:
# ---- Invariant F: batch place_hotcues (Auto Hotcues) ------------------- # ---- Invariant F: batch place_hotcues (Auto Hotcues) -------------------
print("== F. place_hotcues fills empty slots only, names round-trip, localized ==") print("== F. place_hotcues fills empty slots only, names round-trip, localized ==")
with tempfile.TemporaryDirectory() as d: with tempfile.TemporaryDirectory() as d:
from konduktor.schemas import AutoHotcue from konduktor.core.model import AutoHotcue
from traktor_nml_utils import TraktorCollection from traktor_nml_utils import TraktorCollection
work = Path(d) / "collection.nml" work = Path(d) / "collection.nml"
shutil.copy2(REAL, work) shutil.copy2(REAL, work)
store = PlaylistStore(work) store = TraktorStore(work)
entry = store._nml.collection.entry[0] entry = store._nml.collection.entry[0]
loc = entry.location loc = entry.location
track_id = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}" track_id = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}"
@@ -340,7 +344,7 @@ with tempfile.TemporaryDirectory() as d:
original = work.read_bytes() original = work.read_bytes()
# Batch: one spec targets the occupied slot (must be skipped), two fill free slots. # Batch: one spec targets the occupied slot (must be skipped), two fill free slots.
store2 = PlaylistStore(work) store2 = TraktorStore(work)
e2 = store2._nml.collection.entry[0] e2 = store2._nml.collection.entry[0]
now_used = {c.hotcue for c in (e2.cue_v2 or []) if c.hotcue is not None and c.hotcue >= 0} now_used = {c.hotcue for c in (e2.cue_v2 or []) if c.hotcue is not None and c.hotcue >= 0}
free = [s for s in range(8) if s not in now_used][:2] free = [s for s in range(8) if s not in now_used][:2]
@@ -377,7 +381,7 @@ with tempfile.TemporaryDirectory() as d:
# ---- Invariant G: select_hotcues placement logic (pure, no audio) ------ # ---- Invariant G: select_hotcues placement logic (pure, no audio) ------
print("== G. select_hotcues: phrase-snap, empty-slots, names, existing-cue avoidance ==") print("== G. select_hotcues: phrase-snap, empty-slots, names, existing-cue avoidance ==")
from konduktor import auto_hotcues as ah # noqa: E402 from konduktor.core import auto_hotcues as ah # noqa: E402
# 128 BPM => beat 0.46875s, 16-bar phrase = 30.0s exactly; marker at 0.0. # 128 BPM => beat 0.46875s, 16-bar phrase = 30.0s exactly; marker at 0.0.
BPM, ANCHOR, DUR = 128.0, 0.0, 300.0 BPM, ANCHOR, DUR = 128.0, 0.0, 300.0
@@ -424,8 +428,9 @@ check("flexible grid: post-seam points snap to that segment's 32s phrase",
print("== H. remap_locations rewrites LOCATIONs (+ playlist keys), localized, round-trips ==") print("== H. remap_locations rewrites LOCATIONs (+ playlist keys), localized, round-trips ==")
from collections import Counter # noqa: E402 from collections import Counter # noqa: E402
from konduktor.file_tags import resolve_path # noqa: E402 from konduktor.adapters.traktor.locations import resolve_path # noqa: E402
from konduktor.path_mapping import PathMapping, os_path_to_location # noqa: E402 from konduktor.core.pathmap import PathMapping # noqa: E402
from konduktor.adapters.traktor.locations import os_path_to_location # noqa: E402
from traktor_nml_utils import TraktorCollection # noqa: E402 from traktor_nml_utils import TraktorCollection # noqa: E402
@@ -447,7 +452,7 @@ with tempfile.TemporaryDirectory() as d:
shutil.copy2(REAL, work) shutil.copy2(REAL, work)
original = work.read_bytes() original = work.read_bytes()
store = PlaylistStore(work) store = TraktorStore(work)
pl_keys = { pl_keys = {
k k
for n in store._iter_nodes(store._root()) for n in store._iter_nodes(store._root())
@@ -492,7 +497,7 @@ with tempfile.TemporaryDirectory() as d:
check("H1: moved ENTRY has the new VOLUME", moved.location.volume == "KONDUKTOR_TEST_H1") check("H1: moved ENTRY has the new VOLUME", moved.location.volume == "KONDUKTOR_TEST_H1")
# Reverting (to -> from) round-trips to the original bytes exactly. # Reverting (to -> from) round-trips to the original bytes exactly.
store2 = PlaylistStore(work) store2 = TraktorStore(work)
store2.remap_locations(PathMapping.make(to_prefix, from_prefix)) store2.remap_locations(PathMapping.make(to_prefix, from_prefix))
store2.save() store2.save()
check("H1: revert round-trips to original bytes", work.read_bytes() == original) check("H1: revert round-trips to original bytes", work.read_bytes() == original)
@@ -502,7 +507,7 @@ with tempfile.TemporaryDirectory() as d:
work = Path(d) / "collection.nml" work = Path(d) / "collection.nml"
shutil.copy2(REAL, work) shutil.copy2(REAL, work)
store = PlaylistStore(work) store = TraktorStore(work)
# A collection entry whose key appears in at least one playlist. # A collection entry whose key appears in at least one playlist.
pl_keys = { pl_keys = {
k k
@@ -535,7 +540,7 @@ with tempfile.TemporaryDirectory() as d:
) )
check("H2: collection ENTRY location rewritten", moved is not None) check("H2: collection ENTRY location rewritten", moved is not None)
store3 = PlaylistStore(work) store3 = TraktorStore(work)
all_pl_keys = { all_pl_keys = {
k k
for node in store3._iter_nodes(store3._root()) for node in store3._iter_nodes(store3._root())
@@ -566,7 +571,7 @@ with tempfile.TemporaryDirectory() as d:
# Synthesize the flexible grid rather than relying on the handful of real # Synthesize the flexible grid rather than relying on the handful of real
# ones: those are the user's own data and could change at any time. # ones: those are the user's own data and could change at any time.
store = PlaylistStore(work) store = TraktorStore(work)
entry = next( entry = next(
e for e in store._nml.collection.entry e for e in store._nml.collection.entry
if e.tempo and len(bg.grid_markers(e)) == 1 if e.tempo and len(bg.grid_markers(e)) == 1
@@ -600,14 +605,14 @@ with tempfile.TemporaryDirectory() as d:
original[:os_] + b"@@" + original[oe:] == two[:es_] + b"@@" + two[ee:]) original[:os_] + b"@@" + original[oe:] == two[:es_] + b"@@" + two[ee:])
# Removing it must return the file to its original bytes exactly. # Removing it must return the file to its original bytes exactly.
store2 = PlaylistStore(work) store2 = TraktorStore(work)
store2.delete_grid_marker(track_id, 1) store2.delete_grid_marker(track_id, 1)
store2.save() store2.save()
check("I: deleting the added marker round-trips to original bytes", check("I: deleting the added marker round-trips to original bytes",
work.read_bytes() == original) work.read_bytes() == original)
# Moves clamp between neighbours rather than reordering the list. # Moves clamp between neighbours rather than reordering the list.
store3 = PlaylistStore(work) store3 = TraktorStore(work)
store3.add_grid_marker(track_id, (m0_start + 60_000.0) / 1000.0, bpm=m0_bpm * 0.99) store3.add_grid_marker(track_id, (m0_start + 60_000.0) / 1000.0, bpm=m0_bpm * 0.99)
store3.move_grid_marker(track_id, 0, (m0_start + 120_000.0) / 1000.0) store3.move_grid_marker(track_id, 0, (m0_start + 120_000.0) / 1000.0)
e3 = store3.model_entry(track_id) e3 = store3.model_entry(track_id)
@@ -631,7 +636,7 @@ with tempfile.TemporaryDirectory() as d:
shutil.copy2(REAL, work) shutil.copy2(REAL, work)
original = work.read_bytes() original = work.read_bytes()
store = PlaylistStore(work) store = TraktorStore(work)
entry = next( entry = next(
e for e in store._nml.collection.entry if bg.companions(e).get(0) is not None e for e in store._nml.collection.entry if bg.companions(e).get(0) is not None
) )
@@ -660,7 +665,7 @@ with tempfile.TemporaryDirectory() as d:
check("J: a non-companion slot is still editable", store.dirty is True) check("J: a non-companion slot is still editable", store.dirty is True)
# Auto Hotcues must skip companion slots even when told to overwrite. # Auto Hotcues must skip companion slots even when told to overwrite.
store2 = PlaylistStore(work) store2 = TraktorStore(work)
spec = type("S", (), {"slot": slot, "start": 42.0, "name": "X", "type": 0, "length": 0.0})() spec = type("S", (), {"slot": slot, "start": 42.0, "name": "X", "type": 0, "length": 0.0})()
store2.place_hotcues(track_id, [spec], overwrite=True) store2.place_hotcues(track_id, [spec], overwrite=True)
e2 = store2.model_entry(track_id) e2 = store2.model_entry(track_id)
@@ -682,7 +687,7 @@ _flex = [e for e in _real if len(bg.grid_markers(e)) > 1]
if not _flex: if not _flex:
print(" [SKIP] no flexible-grid entries in the reference collection") print(" [SKIP] no flexible-grid entries in the reference collection")
else: else:
import konduktor.main as _m from konduktor.adapters.traktor import projection as _proj
ok_order = ok_tempo = ok_proj = ok_comp = True ok_order = ok_tempo = ok_proj = ok_comp = True
for e in _flex: for e in _flex:
@@ -690,7 +695,7 @@ else:
ok_order &= all(ms[i].start < ms[i + 1].start for i in range(len(ms) - 1)) ok_order &= all(ms[i].start < ms[i + 1].start for i in range(len(ms) - 1))
if e.tempo and e.tempo.bpm: if e.tempo and e.tempo.bpm:
ok_tempo &= abs(e.tempo.bpm - ms[0].grid.bpm) < 1e-6 ok_tempo &= abs(e.tempo.bpm - ms[0].grid.bpm) < 1e-6
tc = _m._build_track_cues(e) tc = _proj.to_track_cues(e)
ok_proj &= len(tc.grid_markers) == len(ms) and all( ok_proj &= len(tc.grid_markers) == len(ms) and all(
abs(g.bpm - m.grid.bpm) < 1e-9 and abs(g.start - (m.start or 0) / 1000.0) < 1e-9 abs(g.bpm - m.grid.bpm) < 1e-9 and abs(g.start - (m.start or 0) / 1000.0) < 1e-9
for g, m in zip(tc.grid_markers, ms) for g, m in zip(tc.grid_markers, ms)