From c9e85bbdb50deab7fa5fdf34e51ca76117c8ced6 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Thu, 17 Sep 2026 17:30:36 +0200 Subject: [PATCH] Updated backend --- CLAUDE.md | 95 +++-- backend/konduktor/adapters/__init__.py | 3 + .../konduktor/adapters/traktor/__init__.py | 11 +- backend/konduktor/adapters/traktor/adapter.py | 14 +- backend/konduktor/adapters/traktor/driver.py | 40 ++ backend/konduktor/adapters/traktor/store.py | 24 +- backend/konduktor/app_state.py | 75 ++++ backend/konduktor/auto_hotcues.py | 11 - backend/konduktor/beatgrid.py | 11 - backend/konduktor/core/registry.py | 61 +++ backend/konduktor/discovery.py | 11 - backend/konduktor/file_tags.py | 17 - backend/konduktor/history.py | 49 ++- backend/konduktor/main.py | 373 +++++++----------- backend/konduktor/path_mapping.py | 10 - backend/konduktor/playlist_store.py | 11 - backend/test_save_fidelity.py | 59 +-- 17 files changed, 497 insertions(+), 378 deletions(-) create mode 100644 backend/konduktor/adapters/traktor/driver.py create mode 100644 backend/konduktor/app_state.py delete mode 100644 backend/konduktor/auto_hotcues.py delete mode 100644 backend/konduktor/beatgrid.py create mode 100644 backend/konduktor/core/registry.py delete mode 100644 backend/konduktor/discovery.py delete mode 100644 backend/konduktor/file_tags.py delete mode 100644 backend/konduktor/path_mapping.py delete mode 100644 backend/konduktor/playlist_store.py diff --git a/CLAUDE.md b/CLAUDE.md index d3931c6..19e0044 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -16,34 +16,61 @@ 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`, `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 explorer. Entry: [frontend/src/App.tsx](frontend/src/App.tsx). - `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. - `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_layering.py` — `core/` imports nothing platform-specific. Also validate the backend interactively at `http://localhost:8000/docs` and the 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 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 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 ## 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 `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. 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: `add_grid_marker` (inherits the governing tempo when no BPM is given), `move_grid_marker` (clamped between its neighbours, drags the companion), diff --git a/backend/konduktor/adapters/__init__.py b/backend/konduktor/adapters/__init__.py index 8c7d8a9..28daab3 100644 --- a/backend/konduktor/adapters/__init__.py +++ b/backend/konduktor/adapters/__init__.py @@ -1,3 +1,6 @@ """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. """ +from . import traktor # noqa: F401 — registers the Traktor driver diff --git a/backend/konduktor/adapters/traktor/__init__.py b/backend/konduktor/adapters/traktor/__init__.py index 1fb1975..7d3a1d8 100644 --- a/backend/konduktor/adapters/traktor/__init__.py +++ b/backend/konduktor/adapters/traktor/__init__.py @@ -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) diff --git a/backend/konduktor/adapters/traktor/adapter.py b/backend/konduktor/adapters/traktor/adapter.py index 004751e..0c6267c 100644 --- a/backend/konduktor/adapters/traktor/adapter.py +++ b/backend/konduktor/adapters/traktor/adapter.py @@ -2,7 +2,7 @@ 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. * 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 . import capabilities as caps 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 # 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. 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: @@ -34,7 +35,7 @@ class TraktorAdapter: def __init__(self, path: Path): self.path = Path(path) - self._store = PlaylistStore(self.path) + self._store = TraktorStore(self.path) self._index = TrackIndex() self._rebuild() @@ -81,7 +82,7 @@ class TraktorAdapter: # 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) -> PlaylistStore: + def store(self) -> TraktorStore: return self._store def entries_for(self, track_ids: list[str]) -> list[tuple[str, str]]: @@ -94,8 +95,11 @@ class TraktorAdapter: 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(PlaylistStore.EDITABLE_FIELDS)) + return caps.capabilities_for(self.path, sorted(TraktorStore.EDITABLE_FIELDS)) # ---- playlists ------------------------------------------------------- def playlist_tree(self) -> list[PlaylistNode]: diff --git a/backend/konduktor/adapters/traktor/driver.py b/backend/konduktor/adapters/traktor/driver.py new file mode 100644 index 0000000..27bbd78 --- /dev/null +++ b/backend/konduktor/adapters/traktor/driver.py @@ -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" str: """Delegates to the journal; kept as a method because save() and the diff --git a/backend/konduktor/app_state.py b/backend/konduktor/app_state.py new file mode 100644 index 0000000..455979c --- /dev/null +++ b/backend/konduktor/app_state.py @@ -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 diff --git a/backend/konduktor/auto_hotcues.py b/backend/konduktor/auto_hotcues.py deleted file mode 100644 index cf23e33..0000000 --- a/backend/konduktor/auto_hotcues.py +++ /dev/null @@ -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 diff --git a/backend/konduktor/beatgrid.py b/backend/konduktor/beatgrid.py deleted file mode 100644 index 3d53c56..0000000 --- a/backend/konduktor/beatgrid.py +++ /dev/null @@ -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 diff --git a/backend/konduktor/core/registry.py b/backend/konduktor/core/registry.py new file mode 100644 index 0000000..7bd42ed --- /dev/null +++ b/backend/konduktor/core/registry.py @@ -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) diff --git a/backend/konduktor/discovery.py b/backend/konduktor/discovery.py deleted file mode 100644 index eba5dfe..0000000 --- a/backend/konduktor/discovery.py +++ /dev/null @@ -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 diff --git a/backend/konduktor/file_tags.py b/backend/konduktor/file_tags.py deleted file mode 100644 index 11e34ea..0000000 --- a/backend/konduktor/file_tags.py +++ /dev/null @@ -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, -) 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/main.py b/backend/konduktor/main.py index dd44eae..d3b9300 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -11,16 +11,24 @@ 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 .adapters.traktor import projection +from . import __version__, history, prefs +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 . import history, prefs -from .adapters.traktor.adapter import TraktorAdapter -from .adapters.traktor.discovery import describe, detect_collections +from .core import registry +from .core.adapter import ( + AdapterError, + InvalidCommand, + LibraryAdapter, + LibraryNotSupported, + NotFound, + Unsupported, +) +from .core.capabilities import Capabilities from .core.pathmap import PathMapping -from .adapters.traktor.store import PlaylistError, PlaylistStore from .schemas import ( AutoGridRequest, AutoHotcue, @@ -29,7 +37,6 @@ from .schemas import ( CollectionOptions, CollectionStatus, CreatePlaylist, - CuePoint, EditState, EditTrack, Facets, @@ -37,7 +44,6 @@ from .schemas import ( FsEntry, FsListing, AddGridMarker, - GridMarker, GridMarkerEdit, ReplaceGrid, HistoryEntry, @@ -76,56 +82,37 @@ app.add_middleware( ) -class AppState: - """Holds the currently-loaded collection (selectable at runtime).""" +def _cue_type_name(native: int) -> str: + """Map the wire's Traktor cue integer onto the generic vocabulary. - def __init__(self) -> None: - self.path: Path | None = None - self.adapter: TraktorAdapter | None = None - - @property - def loaded(self) -> bool: - return self.adapter is not None - - 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) + Transitional: the HTTP contract still carries Traktor's encoding, so the + translation happens here at the boundary rather than in the adapter. + """ + name = NATIVE_TO_CUE_TYPE.get(native) + if name is None: + raise HTTPException(400, f"Unsupported cue type: {native}") + return name -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() -> TraktorAdapter: +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.adapter is not None return STATE.adapter -def require_store() -> PlaylistStore: - if not STATE.loaded: - raise HTTPException(409, "No collection loaded") - assert STATE.adapter is not None - return STATE.adapter.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 --------------------------------------------- @@ -138,8 +125,8 @@ def collection_status() -> CollectionStatus: 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(), ) @@ -150,10 +137,10 @@ def open_collection(body: OpenCollection) -> CollectionStatus: raise HTTPException(400, f"File not found: {path}") 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}") + raise HTTPException(400, f"Could not open that collection: {ex}") prefs.set_last_collection(str(path)) return collection_status() @@ -162,7 +149,7 @@ def open_collection(body: OpenCollection) -> CollectionStatus: 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() + detected = registry.detect_all() auto = CollectionCandidate(**detected[0]) if detected else None recent = None last = prefs.get_last_collection() @@ -174,7 +161,7 @@ def collection_options() -> CollectionOptions: @app.get("/api/collection/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"]}) @@ -186,12 +173,12 @@ 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} ) @@ -201,8 +188,7 @@ def put_path_mapping(body: PathMappingInfo) -> PathMappingInfo: 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) @@ -211,8 +197,9 @@ def preview_path_mapping( ) -> 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) @@ -221,15 +208,16 @@ def remap_paths(body: PathMappingInfo) -> RemapResult: 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) + count = require_adapter().remap_locations(mapping) if count == 0: return RemapResult(rewritten=0, commit=None) - outcome = store.save() - return RemapResult(rewritten=count, commit=outcome.commit) + # 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=count, commit=commit) @app.get("/api/prefs") @@ -260,7 +248,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 registry.browsable_suffixes(): files.append(FsEntry(name=entry.name, path=str(entry))) except OSError: continue @@ -280,10 +268,15 @@ def health() -> dict: 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) def state() -> EditState: - store = require_store() - return EditState(dirty=store.dirty, nml_path=str(STATE.path)) + return EditState(dirty=require_adapter().dirty, nml_path=str(STATE.path)) @app.post("/api/reload") @@ -291,7 +284,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 ------------------------------------ @@ -299,12 +292,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) @@ -321,7 +315,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, @@ -333,16 +327,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 ------------------------------------------ @@ -350,76 +343,54 @@ 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, type="PLAYLIST", uuid=new_id, count=0) @app.patch("/api/playlists/{playlist_uuid}") 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}") 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 @@ -442,7 +413,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(): @@ -454,17 +425,11 @@ def track_audio(track_id: str) -> FileResponse: 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: - 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 projection.to_track_cues(entry) + return cues @app.get("/api/tracks/cues", response_model=TrackCues) @@ -473,25 +438,17 @@ 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 projection.to_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) + return require_adapter().set_cue( + body.track_id, + slot=body.slot, + start_sec=body.start, + cue_type=_cue_type_name(body.type), + length_sec=body.length, + name=body.name, + ) @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 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: + a = require_adapter() + cues = a.track_cues(body.track_id) + if cues is None: raise HTTPException(404, "Track not found") - cues = projection.to_track_cues(entry) if not cues.grid_markers: 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(): 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 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} - 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] specs = ah.select_hotcues( boundaries, @@ -526,15 +483,11 @@ def auto_hotcues(body: AutoHotcuesRequest) -> TrackCues: duration=duration, free_slots=free, existing_times=existing_times, - max_cues=body.max_cues or ah.MAX_HOTCUES, + max_cues=body.max_cues or slots, ) 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) + return a.place_cues(body.track_id, [AutoHotcue(**s) for s in specs]) @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 (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: + a = require_adapter() + if a.track(body.track_id) is None: 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(): raise HTTPException(400, "Audio file not found (is the drive mounted?)") try: bpm, first_beat = ah.detect_grid(str(path)) except Exception as ex: # analysis is best-effort; never 500 the UI raise HTTPException(400, f"Analysis failed: {ex}") - try: - store.replace_grid(body.track_id, [(first_beat, bpm)]) - # Traktor pairs its own grid markers with a white beat-1 cue; mirror - # 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) + # "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(body.track_id, [(first_beat, bpm)]) @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).""" - 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) + return require_adapter().set_cue_type( + body.track_id, body.slot, _cue_type_name(body.type) + ) @app.delete("/api/tracks/hotcue", response_model=TrackCues) def delete_hotcue(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.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.""" - try: - 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) + return require_adapter().add_grid_marker(body.track_id, body.start, body.bpm) @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 `index` is still valid for the move afterwards. """ - store = require_store() - try: - if body.bpm is not None: - store.set_grid_marker_bpm(body.track_id, body.index, body.bpm) - if body.start is not None: - store.move_grid_marker(body.track_id, body.index, body.start) - except PlaylistError as ex: - raise HTTPException(400, str(ex)) - return _sync_cue_edit(body.track_id) + 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).""" - try: - require_store().delete_grid_marker(track_id, index) - except PlaylistError as ex: - raise HTTPException(400, str(ex)) - return _sync_cue_edit(track_id) + 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.""" - try: - require_store().replace_grid( - 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) + 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 every grid marker and its companion cue. is kept.""" - try: - require_store().delete_grid(track_id) - except PlaylistError as ex: - raise HTTPException(400, str(ex)) - return _sync_cue_edit(track_id) + return require_adapter().delete_grid(track_id) @app.patch("/api/tracks/lock", response_model=TrackCues) def edit_lock(body: SetLock) -> 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], ) @@ -687,7 +605,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)] @@ -696,14 +614,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() @@ -712,6 +629,6 @@ 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"} diff --git a/backend/konduktor/path_mapping.py b/backend/konduktor/path_mapping.py deleted file mode 100644 index 78b4c25..0000000 --- a/backend/konduktor/path_mapping.py +++ /dev/null @@ -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 diff --git a/backend/konduktor/playlist_store.py b/backend/konduktor/playlist_store.py deleted file mode 100644 index f60c91c..0000000 --- a/backend/konduktor/playlist_store.py +++ /dev/null @@ -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 diff --git a/backend/test_save_fidelity.py b/backend/test_save_fidelity.py index 5a4de1c..40940ab 100644 --- a/backend/test_save_fidelity.py +++ b/backend/test_save_fidelity.py @@ -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 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" -from konduktor.playlist_store import PlaylistError, PlaylistStore # noqa: E402 +from konduktor.adapters.traktor.store import PlaylistError, TraktorStore # noqa: E402 failed = False @@ -71,7 +75,7 @@ with tempfile.TemporaryDirectory() as d: work = Path(d) / "collection.nml" shutil.copy2(REAL, work) before = work.read_bytes() - store = PlaylistStore(work) + store = TraktorStore(work) store.save() # no edits after = work.read_bytes() check("whole file identical after no-op save", before == after) @@ -91,7 +95,7 @@ with tempfile.TemporaryDirectory() as d: shutil.copy2(REAL, work) original = work.read_bytes() - store = PlaylistStore(work) + store = TraktorStore(work) def walk(n): yield n @@ -139,7 +143,7 @@ with tempfile.TemporaryDirectory() as d: shutil.copy2(REAL, work) original = work.read_bytes() - store = PlaylistStore(work) + store = TraktorStore(work) # pick the first track that has a resolvable primary key entry = store._nml.collection.entry[0] loc = entry.location @@ -185,7 +189,7 @@ with tempfile.TemporaryDirectory() as d: shutil.copy2(REAL, work) original = work.read_bytes() - store = PlaylistStore(work) + store = TraktorStore(work) entry = store._nml.collection.entry[0] loc = entry.location 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) # 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.save() check("create+delete round-trips to the original bytes", work.read_bytes() == original) # ---- Invariant E: a beatgrid edit is fully localized ------------------- 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: work = Path(d) / "collection.nml" shutil.copy2(REAL, work) original = work.read_bytes() - store = PlaylistStore(work) + store = TraktorStore(work) def _key(e): 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) # 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.move_grid_marker(track_id, 0, orig_anchor_ms / 1000.0) store2.save() @@ -314,13 +318,13 @@ with tempfile.TemporaryDirectory() as d: # ---- Invariant F: batch place_hotcues (Auto Hotcues) ------------------- print("== F. place_hotcues fills empty slots only, names round-trip, localized ==") with tempfile.TemporaryDirectory() as d: - from konduktor.schemas import AutoHotcue + from konduktor.core.model import AutoHotcue from traktor_nml_utils import TraktorCollection work = Path(d) / "collection.nml" shutil.copy2(REAL, work) - store = PlaylistStore(work) + store = TraktorStore(work) entry = store._nml.collection.entry[0] loc = entry.location 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() # 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] 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] @@ -377,7 +381,7 @@ with tempfile.TemporaryDirectory() as d: # ---- Invariant G: select_hotcues placement logic (pure, no audio) ------ 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. 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 ==") from collections import Counter # noqa: E402 -from konduktor.file_tags import resolve_path # noqa: E402 -from konduktor.path_mapping import PathMapping, os_path_to_location # noqa: E402 +from konduktor.adapters.traktor.locations import resolve_path # 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 @@ -447,7 +452,7 @@ with tempfile.TemporaryDirectory() as d: shutil.copy2(REAL, work) original = work.read_bytes() - store = PlaylistStore(work) + store = TraktorStore(work) pl_keys = { k 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") # 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.save() 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" shutil.copy2(REAL, work) - store = PlaylistStore(work) + store = TraktorStore(work) # A collection entry whose key appears in at least one playlist. pl_keys = { k @@ -535,7 +540,7 @@ with tempfile.TemporaryDirectory() as d: ) check("H2: collection ENTRY location rewritten", moved is not None) - store3 = PlaylistStore(work) + store3 = TraktorStore(work) all_pl_keys = { k 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 # ones: those are the user's own data and could change at any time. - store = PlaylistStore(work) + store = TraktorStore(work) entry = next( e for e in store._nml.collection.entry 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:]) # 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.save() check("I: deleting the added marker round-trips to original bytes", work.read_bytes() == original) # 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.move_grid_marker(track_id, 0, (m0_start + 120_000.0) / 1000.0) e3 = store3.model_entry(track_id) @@ -631,7 +636,7 @@ with tempfile.TemporaryDirectory() as d: shutil.copy2(REAL, work) original = work.read_bytes() - store = PlaylistStore(work) + store = TraktorStore(work) entry = next( 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) # 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})() store2.place_hotcues(track_id, [spec], overwrite=True) 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: print(" [SKIP] no flexible-grid entries in the reference collection") else: - import konduktor.main as _m + from konduktor.adapters.traktor import projection as _proj ok_order = ok_tempo = ok_proj = ok_comp = True 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)) if e.tempo and e.tempo.bpm: 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( 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)