diff --git a/CLAUDE.md b/CLAUDE.md index 30b3c4d..3595446 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -131,6 +131,39 @@ Two independent apps that talk over HTTP: `close()` disposes the SQLAlchemy engine, not just the session — otherwise the OS file handle stays open and `master.db` cannot be replaced. `AppState` closes the previous adapter when opening a new library. + - `adapters/onelibrary/` — **read-only.** The cross-vendor USB export format + (AlphaTheta + Algoriddim + Native Instruments), read by CDJ-class hardware. + Built as the source half of a future "import a stick into Traktor" feature. + Full research, incl. the schema, is in + [.claude/handoffs/onelibrary-adapter.md](.claude/handoffs/onelibrary-adapter.md); + the four things that make it unlike the Rekordbox adapter: + - **The library is a REMOVABLE DRIVE, not a file in a known place.** So + `discovery.py` scans mount points rather than probing fixed paths, and + `layout.py` owns the on-drive layout (`PIONEER/rekordbox/exportLibrary.db`, + analysis under `PIONEER/USBANLZ/P0/<8 hex>/`). Every stored path is + **drive-relative with a leading slash** — `/Contents/…/x.mp3` — which is + NOT an absolute host path: joining it naively discards the mount point and + silently yields `/Contents/…`, which looks like an empty drive rather than + a path bug. `DriveLayout.resolve()` is the only place that join happens. + A track's id is that drive-relative path, not `content_id`, which rekordbox + renumbers from 1 on every re-export. + - **Cues are NOT in the `cue` table**, which rekordbox exports empty; they are + in the ANLZ files. `PCOB` is **split by pad** (`.DAT` holds 1–3, `.EXT` holds + 4 and up — reading only the `.DAT` silently loses pads D–H), and `PCO2` in + the `.EXT` holds the complete set plus RGB colour and comments. `PCO2` wins, + `PCOB` is the fallback, both merge across files first. + - **The slot numbering differs from `master.db`.** `djmdCue.Kind` is a sparse + bank that skips 4; ANLZ `hot_cue` is a **dense 1-based index** (pad D is + `Kind` 5 but `hot_cue` 4), and 0 means memory cue. Measured by aligning the + same five cues in both representations. Reuse the Rekordbox mapping here and + every cue from pad D on lands one pad too far along. Times are **ms**, not + 150 fps frames; `loop_time` is `0xFFFFFFFF` (not 0) when there is no loop. + - **Analysis files are parsed lazily** — `.DAT` ~2 ms but `.EXT` ~23 ms, so + eager parsing would cost ~23 s on a 1,000-track drive. Cue and marker counts + are therefore approximate in the library table and corrected by + `track_cues()`. The `PQTZ` beatgrid is the same tag as Rekordbox's, and the + collapse rule is **shared by import** rather than copied — two definitions of + "when does a tempo change start a marker" would drift silently. - `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. @@ -276,9 +309,19 @@ serialization path.** It enforces: changes exactly two — the track and `agentRegistry.localUpdateCount` — with the counter up by one and the edited row stamped with it; edits are invisible on disk until save; and playlist create/fill/rename/delete round-trip. +- `test_onelibrary_adapter.py` — the third adapter against the same contract. + Unlike the Rekordbox tests it needs **nothing installed and nothing plugged + in**: it runs against `fixtures/onelibrary/`, a real rekordbox 7 export trimmed + to fixture size (its README says what was removed; the database is untouched). + So the expected values are checked against bytes *rekordbox* wrote, not bytes + Konduktor wrote. Pins the drive-relative path resolution, the `PCOB`/`PCO2` + merge, and — cross-checked against the same cues in `master.db` — the dense + ANLZ slot numbering, which is the thing most likely to be silently wrong. - `test_layering.py` — `core/` imports nothing platform-specific, and no adapter imports another platform's library (checked on real imports via AST, so merely - naming a platform in a comment is fine). + naming a platform in a comment is fine). Rekordbox and OneLibrary deliberately + **share** `pyrekordbox`: the rule is "no adapter reaches for a rival vendor's + library", and a shared dependency is not a breach. Also validate the backend interactively at `http://localhost:8000/docs` and the frontend at `http://localhost:5173`. @@ -289,6 +332,12 @@ frontend at `http://localhost:5173`. stale and **cannot parse Traktor Pro 4 (NML v20)** files — its strict parser dies on the v4 `` element inside `CUE_V2`. `requirements.txt` pins the GitHub `master` (v4.0.0). Do not "simplify" this to a plain PyPI pin. + **`pyrekordbox` is now the same situation**: PyPI's latest (0.4.4) has no + `devicelib_plus`, which is the OneLibrary (`exportLibrary.db`) reader, so + `requirements.txt` pins the GitHub master. That upgrade renamed `db6` → + `masterdb` and `tables` → `models` and moved `BLOB` out of `db6.database`; + the Rekordbox adapter uses the new names. `db6` still works as a deprecated + alias and is **removed in 0.6.0**. 2. **The collection is real, irreplaceable data — protect it.** Every save writes a timestamped `.bak` first (into a `backups/` folder next to the collection). When testing writes, point `KONDUKTOR_NML` at a COPY. Warn the @@ -394,10 +443,21 @@ that number and nothing else — everything derives from it: incl. the verified result that Rekordbox accepts Konduktor-written rows when USNs are maintained. Remaining gap: **cover art**. **No version history on Rekordbox** — accepted scope decision, see handoff §11. +- 🟡 OneLibrary adapter — **read-only, done**. A OneLibrary USB drive opens, + projects, browses and searches: tracks, playlists, hot cues, memory cues, loops + and flexible beatgrids. Built as the readable SOURCE half of a future + **"import a OneLibrary stick into a Traktor library"** feature, which is the + motivating use case. Everything unknown about the format is on the write side + (the `cue` table's MPEG seek columns, the waveform tags a CDJ draws from, the + update counters), so read-only is a deliberate boundary rather than an + unfinished one. All research — including the schema, which has no public spec — + is in [.claude/handoffs/onelibrary-adapter.md](.claude/handoffs/onelibrary-adapter.md). - ⬜ **Export/conversion** — next up, brought forward ahead of Serato. Design is settled in the discussion doc; current state, the architectural gap (no adapter can create a library from nothing) and the landmines are written up in - [.claude/handoffs/export.md](.claude/handoffs/export.md). + [.claude/handoffs/export.md](.claude/handoffs/export.md). Note the OneLibrary + work already demonstrated creating an `exportLibrary.db` from nothing, and + `fixtures/onelibrary/schema.sql` is the DDL to do it with. - ⬜ Serato adapter - ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging diff --git a/backend/fixtures/onelibrary/Contents/Loopmasters/UnknownAlbum/Demo Track 1.mp3 b/backend/fixtures/onelibrary/Contents/Loopmasters/UnknownAlbum/Demo Track 1.mp3 new file mode 100644 index 0000000..48cdce8 --- /dev/null +++ b/backend/fixtures/onelibrary/Contents/Loopmasters/UnknownAlbum/Demo Track 1.mp3 @@ -0,0 +1 @@ +placeholder diff --git a/backend/fixtures/onelibrary/Contents/Loopmasters/UnknownAlbum/Demo Track 2.mp3 b/backend/fixtures/onelibrary/Contents/Loopmasters/UnknownAlbum/Demo Track 2.mp3 new file mode 100644 index 0000000..48cdce8 --- /dev/null +++ b/backend/fixtures/onelibrary/Contents/Loopmasters/UnknownAlbum/Demo Track 2.mp3 @@ -0,0 +1 @@ +placeholder diff --git a/backend/fixtures/onelibrary/PIONEER/USBANLZ/P016/0000875E/ANLZ0000.DAT b/backend/fixtures/onelibrary/PIONEER/USBANLZ/P016/0000875E/ANLZ0000.DAT new file mode 100644 index 0000000..707cf5b Binary files /dev/null and b/backend/fixtures/onelibrary/PIONEER/USBANLZ/P016/0000875E/ANLZ0000.DAT differ diff --git a/backend/fixtures/onelibrary/PIONEER/USBANLZ/P016/0000875E/ANLZ0000.EXT b/backend/fixtures/onelibrary/PIONEER/USBANLZ/P016/0000875E/ANLZ0000.EXT new file mode 100644 index 0000000..acaa8a3 Binary files /dev/null and b/backend/fixtures/onelibrary/PIONEER/USBANLZ/P016/0000875E/ANLZ0000.EXT differ diff --git a/backend/fixtures/onelibrary/PIONEER/USBANLZ/P053/0001D21F/ANLZ0000.DAT b/backend/fixtures/onelibrary/PIONEER/USBANLZ/P053/0001D21F/ANLZ0000.DAT new file mode 100644 index 0000000..ca74814 Binary files /dev/null and b/backend/fixtures/onelibrary/PIONEER/USBANLZ/P053/0001D21F/ANLZ0000.DAT differ diff --git a/backend/fixtures/onelibrary/PIONEER/USBANLZ/P053/0001D21F/ANLZ0000.EXT b/backend/fixtures/onelibrary/PIONEER/USBANLZ/P053/0001D21F/ANLZ0000.EXT new file mode 100644 index 0000000..f1383d1 Binary files /dev/null and b/backend/fixtures/onelibrary/PIONEER/USBANLZ/P053/0001D21F/ANLZ0000.EXT differ diff --git a/backend/fixtures/onelibrary/PIONEER/rekordbox/exportLibrary.db b/backend/fixtures/onelibrary/PIONEER/rekordbox/exportLibrary.db new file mode 100755 index 0000000..319a86e Binary files /dev/null and b/backend/fixtures/onelibrary/PIONEER/rekordbox/exportLibrary.db differ diff --git a/backend/fixtures/onelibrary/README.md b/backend/fixtures/onelibrary/README.md new file mode 100644 index 0000000..edfec7b --- /dev/null +++ b/backend/fixtures/onelibrary/README.md @@ -0,0 +1,58 @@ +# OneLibrary fixture drive + +A real OneLibrary USB export, trimmed to the size of a test fixture. This is the +drive `test_onelibrary_adapter.py` runs against, so the suite needs no USB stick +plugged in and gives the same answer on every machine. + +Produced by rekordbox 7.2.18 exporting a two-track playlist to an exFAT stick. +**Nothing in the database was written or edited by Konduktor** — it is the bytes +rekordbox itself wrote, which is the whole point of a fixture whose job is to +prove we read the real format correctly. + +## What was changed + +Only the analysis files, and only by deleting whole tags: + +| File | Original | Here | +|---|---|---| +| `ANLZ0000.DAT` | 4,972 B | 2,812 B | +| `ANLZ0000.EXT` | 85,602 B | 732 B | + +`PPTH`, `PQTZ`, `PCOB` and `PCO2` — the path, the beatgrid and the two cue lists, +i.e. everything the adapter reads — are kept **byte for byte**. The waveform tags +(`PWAV`, `PWV2`–`PWV5`) are dropped, which is where ~99% of the `.EXT` went, and +the `.2EX` files are omitted entirely. + +The trim is byte-level tag surgery, rewriting only the `PMAI` header's file +length: `pyrekordbox` cannot rebuild a file containing cue tags, so re-serialising +was not an option. + +The two `.mp3` files are **placeholders**, not audio. The adapter resolves paths +and never opens them; carrying 12 MB of demo tracks in the repo to prove that +would be silly. + +## What is in it + +- 2 tracks, one of which (`Demo Track 1`) carries a **flexible multi-tempo grid** + (128.00 BPM to 60 s, then 90.00 BPM) — the awkward case, deliberately. +- 4 hot cues plus a looped memory cue on that track, including one on pad **D**, + which is the cue that lives only in the `.EXT` and that a reader looking at the + `.DAT` alone would lose. +- 1 playlist, `demos`, holding both tracks in order. + +`Demo Track 1`'s title still reads `[KONDUKTOR WROTE THIS]` because the grid and +title were written into `master.db` by Konduktor before the export. That is +incidental to the fixture, but it does record that the whole chain — Konduktor → +`master.db` → rekordbox's OneLibrary export → this file — preserved them. + +## schema.sql + +The complete `CREATE TABLE` set for a OneLibrary database, all 22 tables, +extracted from Traktor Pro 4.5's binary, which embeds the DDL it uses to create +one. AlphaTheta publishes no specification, so this is the closest thing to one: +a second vendor's independent implementation of the same schema. It was verified +by building an empty database from it and having `pyrekordbox`'s ORM — a third +implementation — open and write to it. + +Not loaded by the tests; kept as documentation, and as the starting point if +Konduktor ever needs to create a drive from nothing. diff --git a/backend/fixtures/onelibrary/schema.sql b/backend/fixtures/onelibrary/schema.sql new file mode 100644 index 0000000..9d035fc --- /dev/null +++ b/backend/fixtures/onelibrary/schema.sql @@ -0,0 +1,208 @@ +CREATE TABLE IF NOT EXISTS "content" ( + "content_id" integer primary key not null, + "title" varchar, + "titleForSearch" varchar, + "subtitle" varchar, + "bpmx100" int, + "length" int, + "trackNo" int, + "discNo" int, + "artist_id_artist" int, + "artist_id_remixer" int, + "artist_id_originalArtist" int, + "artist_id_composer" int, + "artist_id_lyricist" int, + "album_id" int, + "genre_id" int, + "label_id" int, + "key_id" int, + "color_id" int, + "image_id" int, + "djComment" varchar, + "rating" int, + "releaseYear" int, + "releaseDate" varchar, + "dateAdded" varchar, + "dateCreated" varchar, + "path" varchar, + "fileName" varchar, + "fileSize" int, + "fileType" int, + "bitrate" int, + "bitDepth" int, + "samplingRate" int, + "isrc" varchar, + "djPlayCount" int, + "isHotCueAutoLoadOn" int, + "isKuvoDeliverStatusOn" int, + "kuvoDeliveryComment" varchar, + "masterDbId" int not null, + "masterContentId" int not null, + "analysisDataFilePath" varchar, + "analysedBits" int, + "contentLink" int, + "hasModified" int, + "cueUpdateCount" int, + "analysisDataUpdateCount" int, + "informationUpdateCount" int +); + +CREATE TABLE IF NOT EXISTS "genre" ( + "genre_id" integer primary key not null, + "name" varchar +); + +CREATE TABLE IF NOT EXISTS "artist" ( + "artist_id" integer primary key not null, + "name" varchar, + "nameForSearch" varchar +); + +CREATE TABLE IF NOT EXISTS "album" ( + "album_id" integer primary key not null, + "name" varchar not null, + "artist_id" int, + "image_id" int, + "isComplation" int, + "nameForSearch" varchar +); + +CREATE TABLE IF NOT EXISTS "label" ( + "label_id" integer primary key not null, + "name" varchar +); + +CREATE TABLE IF NOT EXISTS "key" ( + "key_id" integer primary key not null, + "name" varchar +); + +CREATE TABLE IF NOT EXISTS "color" ( + "color_id" integer primary key not null, + "name" varchar +); + +CREATE TABLE IF NOT EXISTS "playlist" ( + "playlist_id" integer primary key not null, + "sequenceNo" int, + "name" varchar, + "image_id" int, + "attribute" int, + "playlist_id_parent" int +); + +CREATE TABLE IF NOT EXISTS "playlist_content" ( + "playlist_id" int not null, + "content_id" int not null, + "sequenceNo" int not null +); + +CREATE TABLE IF NOT EXISTS "history" ( + "history_id" integer primary key not null, + "sequenceNo" int, + "name" varchar, + "attribute" int, + "history_id_parent" int +); + +CREATE TABLE IF NOT EXISTS "history_content" ( + "history_id" int, + "content_id" int, + "sequenceNo" int +); + +CREATE TABLE IF NOT EXISTS "image" ( + "image_id" integer primary key not null, + "path" varchar +); + +CREATE TABLE IF NOT EXISTS "menuItem" ( + "menuItem_id" integer primary key not null, + "kind" int, + "name" varchar +); + +CREATE TABLE IF NOT EXISTS "category" ( + "category_id" integer primary key not null, + "menuItem_id" int, + "sequenceNo" int, + "isVisible" int +); + +CREATE TABLE IF NOT EXISTS "sort" ( + "sort_id" integer primary key not null, + "menuItem_id" int, + "sequenceNo" int, + "isVisible" int, + "isSelectedAsSubColumn" int +); + +CREATE TABLE IF NOT EXISTS "property" ( + "deviceName" varchar, + "dbVersion" varchar, + "numberOfContents" int, + "createdDate" varchar, + "backGroundColorType" int, + "myTagMasterDBID" int +); + +CREATE TABLE IF NOT EXISTS "hotCueBankList" ( + "hotCueBankList_id" integer primary key not null, + "sequenceNo" int, + "name" varchar, + "image_id" int, + "attribute" int, + "hotCueBankList_id_parent" int +); + +CREATE TABLE IF NOT EXISTS "hotCueBankList_cue" ( + "hotCueBankList_id" int not null, + "cue_id" int not null, + "sequenceNo" int not null +); + +CREATE TABLE IF NOT EXISTS "cue" ( + "cue_id" integer primary key not null, + "content_id" int not null, + "kind" int not null, + "colorTableIndex" int, + "cueComment" varchar, + "isActiveLoop" int not null, + "beatLoopNumerator" int, + "beatLoopDenominator" int, + "inUsec" int not null, + "outUsec" int, + "in150FramePerSec" int not null, + "out150FramePerSec" int, + "inMpegFrameNumber" int, + "outMpegFrameNumber" int, + "inMpegAbs" int, + "outMpegAbs" int, + "inDecodingStartFramePosition" int, + "outDecodingStartFramePosition" int, + "inFileOffsetInBlock" int, + "outFileOffsetInBlock" int, + "inNumberOfSampleInBlock" int, + "outNumberOfSampleInBlock" int +); + +CREATE TABLE IF NOT EXISTS "recommendedLike" ( + "content_id_1" int not null, + "content_id_2" int not null, + "rating" int, + "createdDate" datetime +); + +CREATE TABLE IF NOT EXISTS "myTag" ( + "myTag_id" integer primary key not null, + "sequenceNo" int, + "name" varchar, + "attribute" int, + "myTag_id_parent" int +); + +CREATE TABLE IF NOT EXISTS "myTag_content" ( + "myTag_id" int not null, + "content_id" int not null +); + diff --git a/backend/konduktor/adapters/__init__.py b/backend/konduktor/adapters/__init__.py index b8686e1..75d1a81 100644 --- a/backend/konduktor/adapters/__init__.py +++ b/backend/konduktor/adapters/__init__.py @@ -3,7 +3,11 @@ generic commands onto it; nothing outside an adapter package sees a native type. Importing this package registers every adapter. Order matters only for the registry's ``can_open()`` probe, and the probes are mutually exclusive: Traktor -requires an NML header, Rekordbox an encrypted database with its own schema. +requires an NML header, Rekordbox an encrypted database with its own schema, and +OneLibrary a drive laid out around ``PIONEER/rekordbox/exportLibrary.db``. The +two encrypted databases cannot be confused for one another — they use different +SQLCipher keys, so each driver's decrypt fails outright on the other's file. """ +from . import onelibrary # noqa: F401 — registers the OneLibrary driver from . import rekordbox # noqa: F401 — registers the Rekordbox driver from . import traktor # noqa: F401 — registers the Traktor driver diff --git a/backend/konduktor/adapters/onelibrary/__init__.py b/backend/konduktor/adapters/onelibrary/__init__.py new file mode 100644 index 0000000..9ad852b --- /dev/null +++ b/backend/konduktor/adapters/onelibrary/__init__.py @@ -0,0 +1,18 @@ +"""The OneLibrary adapter: a USB drive's ``exportLibrary.db``, via ``pyrekordbox``. + +OneLibrary is the cross-vendor USB export format agreed between AlphaTheta, +Algoriddim and Native Instruments, and read by CDJ-class hardware as well as by +rekordbox, djay Pro and Traktor. Unlike every other adapter, its library is a +REMOVABLE DRIVE rather than a file in a known place — see `layout.py`. + +Importing this package registers the platform, so ``core.registry`` can find it +without knowing it exists. + +Read-only: a drive is projected, browsed and searched, and every command is +refused. See `adapter.py` for why that scope is deliberate. +""" +from ...core import registry +from .driver import OneLibraryDriver + +ONELIBRARY = OneLibraryDriver() +registry.register(ONELIBRARY) diff --git a/backend/konduktor/adapters/onelibrary/adapter.py b/backend/konduktor/adapters/onelibrary/adapter.py new file mode 100644 index 0000000..a6de9ed --- /dev/null +++ b/backend/konduktor/adapters/onelibrary/adapter.py @@ -0,0 +1,294 @@ +"""The OneLibrary adapter: owns the drive's database and the generic projection. + +Mirrors `adapters.rekordbox.adapter`. It holds: + + * a ``OneLibraryStore`` — the retained NATIVE model (the open drive), + * a ``TrackIndex`` — the generic READ projection built from it. + +**Read-only.** Every command is refused and `capabilities.writable` is False with +cause `platform_incomplete`, so the UI never offers an edit in the first place; +the raises here are the backstop, not the mechanism. + +That scope is deliberate rather than provisional. The purpose of this adapter is +to make a OneLibrary drive a readable SOURCE — the half an import into another +library needs — and every genuinely unknown part of the format sits on the write +side: the `cue` table's eight MPEG frame/offset columns, whose values a player +needs to seek accurately in a VBR file; the waveform tags a CDJ draws from; and +the update counters a drive uses to reconcile edits made on hardware. None of +those has to be guessed at to read a drive, and none of them should be guessed at +at all. +""" +from __future__ import annotations + +from pathlib import Path + +from ...core.adapter import Unsupported +from ...core.capabilities import Capabilities +from ...core.model import PlaylistNode, Track, TrackCues +from ...core.pathmap import PathMapping, common_dir_prefix +from ...core.query import TrackIndex +from . import capabilities as caps +from . import projection +from .store import OneLibraryStore + +# `playlist.attribute`, from pyrekordbox's own enum. A drive carries no smart +# playlists — rekordbox resolves them to static lists on export, because a CDJ +# cannot evaluate rules — but the value is handled rather than assumed absent. +ATTRIBUTE_PLAYLIST = 0 +ATTRIBUTE_FOLDER = 1 +ATTRIBUTE_SMART = 4 + + +class OneLibraryAdapter: + platform = "onelibrary" + + def __init__(self, path: Path): + self.path = Path(path) + self._store = OneLibraryStore(self.path) + self._index = TrackIndex() + self._rebuild() + + # ---- projection maintenance ----------------------------------------- + def _rebuild(self) -> None: + self._index.rebuild( + [ + projection.to_track(row, self._drive_path(row)) + for row in self._store.iter_content() + ] + ) + + def _drive_path(self, row) -> str | None: + resolved = self._store.layout.resolve(getattr(row, "path", None)) + return str(resolved) if resolved is not None else None + + def close(self) -> None: + """Release the database and its file handle. + + More than housekeeping here: the library is on a removable drive, and a + held handle is what stops it ejecting. + """ + self._store.close() + + def reload(self) -> None: + self._store._load() + self._rebuild() + + # ---- identity -------------------------------------------------------- + def capabilities(self) -> Capabilities: + return caps.capabilities_for( + device_name=self._store.device_name, + version=self._store.db_version, + ) + + # ---- read ------------------------------------------------------------ + @property + def tracks(self) -> list[Track]: + return self._index.tracks + + @property + def by_key(self) -> dict[str, Track]: + return self._index.by_key + + def track(self, track_id: str) -> Track | None: + return self._index.get(track_id) + + def query_tracks(self, **kw): + return self._index.query_tracks(**kw) + + def facets(self): + return self._index.facets() + + def stats(self, playlist_count: int): + return self._index.stats(playlist_count) + + def playlist_count(self) -> int: + return self._store.count_playlists() + + def track_cues(self, track_id: str) -> TrackCues | None: + """A track's cues and beatgrid — and where the approximate counts get fixed. + + `projection.to_track` cannot afford the track's analysis files at open + (~23 ms each for the `.EXT`), so it reports no cues and a guessed marker + count. This is the moment the real numbers exist, so the projected track + is corrected here rather than being left disagreeing with the deck. + """ + if self._index.get(track_id) is None: + return None + cues = self._store.cues(track_id) + grid = self._store.anlz_grid(track_id) + from . import beatgrid + + markers = beatgrid.markers_from_beats(*grid) if grid is not None else [] + result = projection.to_track_cues(cues, markers) + + track = self._index.get(track_id) + if track is not None: + track.grid_marker_count = len(result.grid_markers) + track.cue_count = len(result.cues) + track.hotcue_count = sum(1 for c in result.cues if c.role == "hotcue") + return result + + # ---- playlists ------------------------------------------------------- + def playlist_tree(self) -> list[PlaylistNode]: + """The drive's playlist tree: a flat table with `playlist_id_parent` links. + + A root node's parent is 0, not NULL — so "no parent" is a value here + rather than an absence, and treating 0 as a real id would orphan every + top-level playlist. + """ + rows = self._store.playlists() + nodes: dict[str, PlaylistNode] = {} + parents: dict[str, str] = {} + + for r in rows: + attribute = int(getattr(r, "attribute", 0) or 0) + if attribute == ATTRIBUTE_FOLDER: + kind = "folder" + elif attribute == ATTRIBUTE_SMART: + kind = "smart" + else: + kind = "playlist" + node_id = str(getattr(r, "playlist_id", "")) + nodes[node_id] = PlaylistNode( + id=node_id, + name=getattr(r, "name", "") or "", + kind=kind, + count=(0 if kind == "folder" else len(self._store.playlist_song_ids(node_id))), + children=[], + selectable=kind == "playlist", + # Read-only: every per-node flag is False, and + # `capabilities.writable` tells the UI why, once. + can_add_tracks=False, + can_reorder=False, + can_rename=False, + can_delete=False, + can_contain_children=kind == "folder", + ) + parent = str(getattr(r, "playlist_id_parent", 0) or 0) + parents[node_id] = "root" if parent in ("0", "", "None") else parent + + roots: list[PlaylistNode] = [] + for node_id, node in nodes.items(): + parent = nodes.get(parents.get(node_id, "root")) + if parent is None: + roots.append(node) + else: + parent.children.append(node) + return roots + + def playlist_entries(self, node_id: str) -> list[str] | None: + ids = self._store.playlist_song_ids(node_id) + return ids if ids or self._is_playlist(node_id) else None + + def playlist_tracks(self, node_id: str) -> list[Track] | None: + keys = self.playlist_entries(node_id) + if keys is None: + return None + return [t for k in keys if (t := self._index.get(k)) is not None] + + def _is_playlist(self, node_id: str) -> bool: + return any(str(getattr(r, "playlist_id", "")) == str(node_id) for r in self._store.playlists()) + + # ---- audio / paths ---------------------------------------------------- + def audio_path(self, track_id: str): + return self._store.audio_path(track_id) + + def set_path_mapping(self, mapping: PathMapping) -> None: + """Ignored: a drive's paths are relative to wherever it is mounted. + + Path remapping exists because a desktop library stores absolute paths + that go stale when music moves. A OneLibrary drive stores everything + relative to its own root, so it is self-contained by construction and + there is nothing for a mapping to fix. + """ + return None + + def path_prefix_suggestions(self) -> dict: + paths = self._store.all_audio_paths() + primary = common_dir_prefix(paths) + return { + "primary": primary, + "groups": [{"prefix": primary, "count": len(paths)}] if primary else [], + } + + def remap_preview(self, mapping: PathMapping) -> dict: + paths = [Path(p) for p in self._store.all_audio_paths()] + return {"total": len(paths), "matched": 0, "existing": 0, "samples": []} + + def remap_locations(self, mapping: PathMapping) -> int: + raise Unsupported(self._readonly_reason("Rewriting stored paths")) + + # ---- save ------------------------------------------------------------- + @property + def dirty(self) -> bool: + return False + + def save(self): + raise Unsupported(self._readonly_reason("Saving")) + + def snapshot(self) -> bytes: + raise Unsupported("OneLibrary drives are not versioned by Konduktor") + + # ---- commands: all refused ------------------------------------------- + def _readonly_reason(self, what: str) -> str: + return f"{what} is not supported yet for OneLibrary drives." + + def _refuse(self, what: str): + raise Unsupported(self._readonly_reason(what)) + + def set_track_metadata(self, track_id: str, fields: dict) -> Track | None: + self._refuse("Editing track metadata") + + def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None: + self._refuse("Editing cover art") + + def cover_art(self, track_id: str) -> tuple[bytes, str] | None: + return None + + def create_playlist(self, name: str, parent_id: str | None = None) -> str: + self._refuse("Creating playlists") + + def rename_playlist(self, node_id: str, name: str) -> None: + self._refuse("Renaming playlists") + + def delete_playlist(self, node_id: str) -> None: + self._refuse("Deleting playlists") + + def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: + self._refuse("Editing playlists") + + def set_cue(self, track_id: str, **kw) -> TrackCues: + self._refuse("Editing cues") + + def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> TrackCues: + self._refuse("Editing cues") + + def delete_cue(self, track_id: str, slot: int) -> TrackCues: + self._refuse("Deleting cues") + + def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues: + self._refuse("Placing cues") + + def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> TrackCues: + self._refuse("Editing the beatgrid") + + def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> TrackCues: + self._refuse("Editing the beatgrid") + + def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> TrackCues: + self._refuse("Editing the beatgrid") + + def delete_grid_marker(self, track_id: str, index: int) -> TrackCues: + self._refuse("Editing the beatgrid") + + def replace_grid(self, track_id: str, markers: list) -> TrackCues: + self._refuse("Editing the beatgrid") + + def set_analysed_grid(self, track_id: str, markers: list) -> TrackCues: + self._refuse("Editing the beatgrid") + + def delete_grid(self, track_id: str) -> TrackCues: + self._refuse("Deleting the beatgrid") + + def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues: + raise Unsupported("OneLibrary has no beatgrid lock") diff --git a/backend/konduktor/adapters/onelibrary/beatgrid.py b/backend/konduktor/adapters/onelibrary/beatgrid.py new file mode 100644 index 0000000..f739932 --- /dev/null +++ b/backend/konduktor/adapters/onelibrary/beatgrid.py @@ -0,0 +1,62 @@ +"""A OneLibrary beatgrid -> the generic marker list. + +**The beatgrid is not in the database.** `exportLibrary.db` has no grid table at +all — `content.bpmx100` is a single display tempo — and the real grid is the +`PQTZ` tag of the track's ANLZ `.DAT`, holding EVERY BEAT explicitly. That is the +same arrangement, and the same tag, as a desktop Rekordbox library: a drive is +exported from one, and rekordbox regenerates the analysis files rather than +inventing a new format for them. + +Verified end to end on a track whose flexible grid Konduktor itself had written +into `master.db`: exporting it to a OneLibrary drive preserved both tempo +segments exactly (128.00 BPM to 60 s, then 90.00 BPM), so multi-tempo grids +survive the whole chain and the marker list is the right generic shape. + +The collapse rule is shared with the Rekordbox adapter deliberately rather than +copied. Two implementations of "when is this a new marker?" would be free to +drift apart by a rounding tolerance, and a drifting grid is a silent corruption +rather than a visible bug. If a third AlphaTheta-format adapter ever appears, +this and `rekordbox.beatgrid` should be promoted to one shared ANLZ module; the +import direction here is the cheapest way to stay honest until then. +""" +from __future__ import annotations + +from ...core.model import GridMarker +from ..rekordbox.beatgrid import BPM_EPSILON, markers_from_beats # noqa: F401 + +__all__ = ["BPM_EPSILON", "markers_from_beats", "beats_from_pqtz", "markers_from_anlz"] + + +def beats_from_pqtz(anlz) -> tuple[list[float], list[float]] | None: + """Per-beat ``(times_sec, bpms)`` from a parsed ANLZ file's `PQTZ` tag. + + Returns None when the file has no `PQTZ` — which is a real state, not an + error: rekordbox analyses one-shot samples too, and gives them an analysis + file with no beatgrid in it. + + `PQTZ` stores time in milliseconds and tempo in hundredths of a BPM. + """ + for tag in getattr(anlz, "tags", []): + if tag.type != "PQTZ": + continue + entries = getattr(getattr(tag.struct, "content", None), "entries", None) + if not entries: + return None + times: list[float] = [] + bpms: list[float] = [] + for e in entries: + try: + times.append(int(e.time) / 1000.0) + bpms.append(int(e.tempo) / 100.0) + except (AttributeError, TypeError, ValueError): + continue + return (times, bpms) if times else None + return None + + +def markers_from_anlz(anlz) -> list[GridMarker]: + """The generic marker list for a parsed ANLZ file.""" + grid = beats_from_pqtz(anlz) + if grid is None: + return [] + return markers_from_beats(*grid) diff --git a/backend/konduktor/adapters/onelibrary/capabilities.py b/backend/konduktor/adapters/onelibrary/capabilities.py new file mode 100644 index 0000000..fba47d9 --- /dev/null +++ b/backend/konduktor/adapters/onelibrary/capabilities.py @@ -0,0 +1,95 @@ +"""What a OneLibrary drive can persist: nothing, for now. + +`writable` is False with cause `platform_incomplete`. That is the distinction the +capability system exists to draw — this is a ROADMAP GAP, not a refusal. A +cloud-synced Rekordbox library is refused permanently to protect the user's other +machines; a OneLibrary drive simply has no write path yet, and the UI must word +those two very differently. + +The per-feature flags below still report what the FORMAT supports rather than +being blanked to false, because that is what `writable=False` is for: the UI can +show a drive's cues and grid honestly, and say once, in one place, that the whole +library is read-only. Blanking them would claim OneLibrary has no hot cues. + +Two answers are worth recording now, while the evidence is in front of us, since +getting them wrong later would be a silent data bug rather than a missing +feature: + + * cue colour is **free RGB**, not a palette index. The `PCO2` tag stores three + bytes per cue, and the reference drive held #4D00FF, #33FF00, #00C4FF and + #FF8C00. This differs from the desktop Rekordbox adapter, which reports + "palette" because `djmdCue` stores an index into a built-in table — the same + vendor, two genuinely different representations. + * a loop is a cue with an out-point, so ``loops="cue_type"`` — the same answer + as Traktor and Rekordbox, and NOT the `separate_bank` the original + multi-platform plan assumed. +""" +from __future__ import annotations + +from ...core.capabilities import ( + Capabilities, + CueCapabilities, + GridCapabilities, + PlaylistCapabilities, + SaveCapabilities, + TrackCapabilities, +) + +# Pads A-H. Unlike `djmdCue.Kind`, the ANLZ slot number is a dense 1-based index, +# so the bank really is 1..8 (see `cues.py`). +HOTCUE_SLOTS = 8 + + +def capabilities_for(device_name: str | None = None, version: str | None = None) -> Capabilities: + return Capabilities( + platform="onelibrary", + version=version, + # A roadmap gap, not a protective refusal — the UI words the two + # differently, which is the whole reason `readonly_cause` exists. + writable=False, + readonly_cause="platform_incomplete", + cues=CueCapabilities( + editable=False, + hotcue_slots=HOTCUE_SLOTS, + slot_labels="letter", + # OneLibrary carries memory cues, as Rekordbox does. They are + # projected and preserved; nothing here is editable anyway. + memory_cues=True, + max_memory_cues=None, + types=["cue", "loop"], + color="free", # PCO2 stores RGB per cue, not a palette index + palette=[], + named=True, # PCO2 carries a per-cue comment + loops="cue_type", + ), + # The grid is the ANLZ `PQTZ` tag, per beat, and multi-tempo grids do + # survive an export — so the format is flexible even though Konduktor + # does not write it here. + grid=GridCapabilities(editable=False, flexible=True, lockable=False), + tracks=TrackCapabilities( + rating_max=5, # stored 0-5 directly, as in master.db + editable_fields=[], + media_kinds=["audio"], + # The drive has an `image` table and an Artwork folder, but nothing + # is wired up to read them yet. + artwork=False, + artwork_note=None, + ), + playlists=PlaylistCapabilities( + folders=True, # `playlist.attribute` 1, nested via playlist_id_parent + # A drive carries no smart playlists: rekordbox resolves them to + # static lists on export, because a CDJ cannot evaluate rules. + smart="none", + reorder=False, + ), + save=SaveCapabilities( + app_name="OneLibrary", + library_label=device_name or "exportLibrary.db", + # Nothing is written, so nothing can be overwritten by another app. + overwrite_risk="none", + # A drive is a database plus N analysis files plus the audio itself, + # so there is no single blob that IS the library — the same reason + # Rekordbox libraries are not versioned. + history=False, + ), + ) diff --git a/backend/konduktor/adapters/onelibrary/cues.py b/backend/konduktor/adapters/onelibrary/cues.py new file mode 100644 index 0000000..e1ee0a4 --- /dev/null +++ b/backend/konduktor/adapters/onelibrary/cues.py @@ -0,0 +1,188 @@ +"""OneLibrary cues: read from the ANLZ analysis files, not the database. + +**The `cue` table is not where a drive's cues are.** It exists in the schema — +and has columns for everything a cue needs — but rekordbox exports an empty one +and puts the cues in the track's ANLZ file instead. Measured on a real rekordbox +7 export of a track carrying four hot cues and a looped memory cue: the `cue` +table held zero rows and every cue was present in the analysis files. The table +appears to be for hardware writing edits BACK to the drive, which is a different +direction than this adapter reads. + +Two tags carry cues, and they are not equivalent: + + * **`PCOB`** is the original list, and it is SPLIT BY PAD. The `.DAT` holds + only hot cues 1-3 — the three pads the earliest CDJs had — and the `.EXT` + holds 4 and up. Reading only the `.DAT` silently loses pads D-H. + * **`PCO2`** is the extended list in the `.EXT`, and it holds the COMPLETE set + in one tag plus three things `PCOB` has nowhere to put: an RGB colour, a + comment, and the loop length expressed in BEATS. + +So `PCO2` is preferred and `PCOB` is the fallback for a drive old enough not to +have one. Both are merged across files before that choice is made, because "the +complete list" must not depend on which file happened to be read. + +**Slot numbering differs from `master.db` and this is the trap.** In the desktop +database a hot cue's `djmdCue.Kind` is a sparse bank that SKIPS 4 (`1,2,3,5,…` +for pads A-H). In ANLZ, `hot_cue` is a plain dense 1-based index (1=A, 2=B, …), +and `0` means the cue is a memory cue rather than a pad. The two were aligned +against each other on one track: `Kind` 1/2/3/5 at 40.000 s, 18.773 s, 90.667 s +and 120.000 s came out as `hot_cue` 1/2/3/4 at exactly the same times. Carry the +Rekordbox adapter's mapping over here unchanged and every cue from pad D onward +lands one pad too far along. + +Times are MILLISECONDS here, where the desktop database counts frames at 150 fps. +""" +from __future__ import annotations + +import logging + +from ...core.model import CuePoint + +log = logging.getLogger(__name__) + +# `loop_time` when a cue is not a loop. Stored as an unsigned 32-bit -1 rather +# than 0, so a plain falsiness test would read it as "a loop ending at zero". +NO_LOOP = 0xFFFFFFFF + +# `hot_cue` for a cue that sits in no pad bank, i.e. a memory cue. +MEMORY_SLOT = 0 + +# PCO2/PCOB entry kinds. The value is the same in both tags; PCOB exposes it as +# a construct enum and PCO2 as a plain int, so both are normalised to an int. +ENTRY_CUE = 1 +ENTRY_LOOP = 2 + + +def _entry_kind(value) -> int: + """PCOB gives an enum, PCO2 an int — one number out of either.""" + try: + return int(value) + except (TypeError, ValueError): + return ENTRY_CUE + + +def _color(entry) -> str | None: + """A cue's colour as ``#RRGGBB``, when the tag carries one. + + Only `PCO2` stores RGB. A cue with no colour set stores 0,0,0 — which is a + real black in principle, but rekordbox uses it as "unset" and shows such a + cue in the default colour, so it is reported as no colour rather than as + black. Memory cues in the reference export are exactly this case. + """ + try: + r, g, b = int(entry.color_red), int(entry.color_green), int(entry.color_blue) + except (AttributeError, TypeError, ValueError): + return None + if (r, g, b) == (0, 0, 0): + return None + return f"#{r:02X}{g:02X}{b:02X}" + + +def _to_cue(entry, *, with_color: bool) -> CuePoint | None: + """One ANLZ cue entry as a generic `CuePoint`, or None if unreadable.""" + try: + hot_cue = int(entry.hot_cue) + start_ms = int(entry.time) + except (AttributeError, TypeError, ValueError): + return None + + loop_ms = getattr(entry, "loop_time", NO_LOOP) + try: + loop_ms = int(loop_ms) + except (TypeError, ValueError): + loop_ms = NO_LOOP + + is_loop = _entry_kind(getattr(entry, "type", ENTRY_CUE)) == ENTRY_LOOP + length = 0.0 + if is_loop and loop_ms != NO_LOOP and loop_ms > start_ms: + length = (loop_ms - start_ms) / 1000.0 + + # hot_cue 0 is the memory list; 1..N are the pads, dense and 1-based, so the + # generic 0-based slot is simply one less. + role = "memory" if hot_cue == MEMORY_SLOT else "hotcue" + slot = None if role == "memory" else hot_cue - 1 + + comment = getattr(entry, "comment", None) + return CuePoint( + name=(str(comment) or None) if comment else None, + type="loop" if length > 0 else "cue", + role=role, + start=start_ms / 1000.0, + length=length, + slot=slot, + color=_color(entry) if with_color else None, + # A OneLibrary drive is read-only in Konduktor, so no cue accepts a + # command. `capabilities.writable` is what the UI actually gates on; + # this keeps the per-cue answer consistent with it. + editable=False, + readonly_reason="platform_managed", + grid_marker=None, + ) + + +def _entries(anlz, tag_type: str) -> list: + """Every entry of every `tag_type` tag in one parsed ANLZ file. + + A file carries the tag twice — once for hot cues and once for memory cues — + so both are collected and the entry's own `hot_cue` decides which it is. + That is more robust than trusting the container's type field, which is + absent on some tags in real files. + """ + out: list = [] + for tag in getattr(anlz, "tags", []): + if tag.type != tag_type: + continue + content = getattr(tag.struct, "content", None) + out.extend(getattr(content, "entries", None) or []) + return out + + +def cues_from_anlz(dat, ext) -> list[CuePoint]: + """The track's complete cue list, from its parsed `.DAT` and `.EXT`. + + Either may be None — a drive can carry a `.DAT` with no `.EXT` — and a track + with no cues at all yields an empty list rather than an error. + """ + files = [f for f in (dat, ext) if f is not None] + if not files: + return [] + + # PCO2 first: it is the complete list and the only one with colour, comment + # and beat-denominated loops. It lives only in the .EXT. + pco2: list = [] + for f in files: + pco2.extend(_entries(f, "PCO2")) + if pco2: + cues = [c for e in pco2 if (c := _to_cue(e, with_color=True)) is not None] + else: + # Fallback: merge PCOB across BOTH files. The .DAT holds pads 1-3 and the + # .EXT the rest, so either alone is an incomplete bank. + pcob: list = [] + for f in files: + pcob.extend(_entries(f, "PCOB")) + cues = [c for e in pcob if (c := _to_cue(e, with_color=False)) is not None] + + return _dedupe(cues) + + +def _dedupe(cues: list[CuePoint]) -> list[CuePoint]: + """Collapse the same cue appearing in more than one tag or file. + + Identity is (role, slot, start) rather than the whole cue: the same pad can + be described by both `PCOB` and `PCO2`, and by both files, and those copies + agree on position while differing in how much detail they carry. The first + one wins, which — given PCO2 is read first — is the richest. + + Ordered by position, then by slot, so the projection is stable across reads + regardless of the order the tags happened to store. + """ + seen: set[tuple[str, int | None, int]] = set() + out: list[CuePoint] = [] + for c in cues: + key = (c.role, c.slot, round(c.start * 1000)) + if key in seen: + continue + seen.add(key) + out.append(c) + out.sort(key=lambda c: (c.start, c.slot if c.slot is not None else -1)) + return out diff --git a/backend/konduktor/adapters/onelibrary/discovery.py b/backend/konduktor/adapters/onelibrary/discovery.py new file mode 100644 index 0000000..86ee0b2 --- /dev/null +++ b/backend/konduktor/adapters/onelibrary/discovery.py @@ -0,0 +1,99 @@ +"""Find OneLibrary drives that are plugged in right now. + +This is the one platform whose libraries have no fixed location: Traktor and +Rekordbox each keep theirs at a known per-OS path, but a OneLibrary library is +whatever USB stick happens to be mounted. So detection scans mount points rather +than probing a list of known paths, and what it finds legitimately changes +between two calls a second apart. + +Only the mount ROOTS are scanned, never their contents recursively. A drive can +hold tens of thousands of files, the database is at a fixed place within it, and +walking a slow USB stick at startup is exactly the kind of thing that makes an +app feel broken. +""" +from __future__ import annotations + +import logging +import os +import string +import sys +from pathlib import Path + +from .layout import DriveLayout + +log = logging.getLogger(__name__) + + +def _mount_points() -> list[Path]: + """Plausible removable-media mount points for this OS.""" + out: list[Path] = [] + if sys.platform == "darwin": + out.append(Path("/Volumes")) + elif sys.platform.startswith("linux"): + out.extend([Path("/media"), Path("/mnt"), Path("/run/media")]) + user = os.environ.get("USER") + if user: + out.append(Path("/media") / user) + out.append(Path("/run/media") / user) + + roots: list[Path] = [] + for base in out: + try: + if not base.is_dir(): + continue + roots.extend(p for p in base.iterdir() if p.is_dir()) + except OSError: + continue + + if sys.platform == "win32": + # No mount-point directory to list: check the drive letters directly. + for letter in string.ascii_uppercase: + drive = Path(f"{letter}:\\") + try: + if drive.is_dir(): + roots.append(drive) + except OSError: + continue + return roots + + +def describe(path: Path) -> dict: + """A candidate record for a drive or database path, shaped for the picker.""" + path = Path(path) + layout = DriveLayout.locate(path) + database = layout.database if layout is not None else path + exists = False + try: + exists = database.is_file() + except OSError: + pass + # The drive's name is what a person recognises — "Hardy", not + # "exportLibrary.db" — so the mount point supplies the label. + root_name = layout.root.name if layout is not None else path.name + return { + "path": str(database), + "label": f"OneLibrary — {root_name}" if root_name else "OneLibrary", + "version": None, + "modified": (database.stat().st_mtime if exists else None), + "exists": exists, + } + + +def detect_libraries() -> list[dict]: + """Every mounted drive that carries a OneLibrary database, newest first.""" + found: list[dict] = [] + seen: set[str] = set() + for root in _mount_points(): + layout = DriveLayout.locate(root) + if layout is None: + continue + try: + key = str(layout.database.resolve()) + except OSError: + continue + if key in seen: + continue + seen.add(key) + found.append(describe(layout.root)) + found.sort(key=lambda c: c["modified"] or 0.0, reverse=True) + return found diff --git a/backend/konduktor/adapters/onelibrary/driver.py b/backend/konduktor/adapters/onelibrary/driver.py new file mode 100644 index 0000000..9b5e081 --- /dev/null +++ b/backend/konduktor/adapters/onelibrary/driver.py @@ -0,0 +1,84 @@ +"""Opening OneLibrary drives: recognition and discovery.""" +from __future__ import annotations + +import logging +from pathlib import Path + +from . import discovery +from .adapter import OneLibraryAdapter +from .layout import DriveLayout + +log = logging.getLogger(__name__) + + +class OneLibraryDriver: + platform = "onelibrary" + display_name = "OneLibrary" + suffixes = (".db",) + library_label = "exportLibrary.db" + + def can_open(self, path: Path) -> bool: + """Recognise a OneLibrary drive, by layout and then by schema. + + Both halves are needed. The layout check alone would accept any file + called ``exportLibrary.db``; the schema check alone cannot run on a + directory, and a drive is what a user actually picks. + + It must also not collide with the Rekordbox driver, which probes for + `master.db`. It cannot: both files are SQLCipher databases with no + readable header, but they use DIFFERENT keys, so each driver's decrypt + simply fails on the other's file. The table probe then makes it explicit + rather than leaving the two relying on a key mismatch. + """ + layout = DriveLayout.locate(Path(path)) + if layout is None: + return False + return self._has_onelibrary_schema(layout.database) + + @staticmethod + def _has_onelibrary_schema(path: Path) -> bool: + try: + import sqlcipher3.dbapi2 as sqlcipher + from pyrekordbox.devicelib_plus.database import BLOB + from pyrekordbox.utils import deobfuscate + except ImportError: # pragma: no cover — dependency missing + return False + con = None + try: + con = sqlcipher.connect(str(path)) + con.execute(f"PRAGMA key='{deobfuscate(BLOB)}'") + # `content` is too generic a name to trust on its own, so the probe + # asks for a pair only this schema has together. + rows = con.execute( + "SELECT name FROM sqlite_master WHERE type='table' " + "AND name IN ('content','hotCueBankList')" + ).fetchall() + return len(rows) == 2 + except Exception: # noqa: BLE001 — wrong key or not a database + return False + finally: + if con is not None: + try: + con.close() + except Exception: # noqa: BLE001 + pass + + def open(self, path: Path) -> OneLibraryAdapter: + return OneLibraryAdapter(path) + + def detect(self) -> list[dict]: + return discovery.detect_libraries() + + def describe(self, path: Path) -> dict: + return discovery.describe(path) + + def restore(self, path: Path, data: bytes) -> None: + """Not supported: a drive is a database plus analysis files plus audio. + + `capabilities.save.history` is False for the same reason, so nothing + should reach this. + """ + raise NotImplementedError( + "Konduktor does not version OneLibrary drives: the library is a " + "database, N analysis files and the audio itself." + ) diff --git a/backend/konduktor/adapters/onelibrary/layout.py b/backend/konduktor/adapters/onelibrary/layout.py new file mode 100644 index 0000000..de99fe9 --- /dev/null +++ b/backend/konduktor/adapters/onelibrary/layout.py @@ -0,0 +1,103 @@ +"""Where things live on a OneLibrary drive. + +A OneLibrary library is a **removable drive**, not a file, and that is the one +structural fact that separates this adapter from every other one. Everything the +library refers to — the audio, the analysis files, the artwork — is stored +DRIVE-RELATIVE (``/Contents/Loopmasters/Demo Track 1.mp3``), because the same +stick must resolve on a CDJ, on macOS and on Windows, where it is mounted at +three different places. Nothing inside the database is an absolute host path. + +So resolving a stored path means joining it to the mount point, and that is what +this module exists to do. It is kept separate from the store because it is also +the knowledge a future *export* would need to lay a drive out from nothing. + +Two layout details are measured from a real rekordbox 7 export rather than +assumed: + + * the database is at ``PIONEER/rekordbox/exportLibrary.db``, alongside — not + instead of — the legacy ``export.pdb``. Both formats coexist on one drive, + and newer players prefer OneLibrary when they find it. + * analysis files sit under ``PIONEER/USBANLZ/P0/<8 hex>/ANLZ0000.*``, + where the two directory levels are a hash of the track's path. Konduktor + never has to compute that hash to READ, because ``content.analysisDataFilePath`` + stores the resulting path outright — it would only matter for writing. + +``.PIONEER`` is accepted as well as ``PIONEER``. Traktor's own OneLibrary writer +looks for both, so a drive written by it may use the dot-prefixed (hidden) form. +""" +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path + +# In preference order: a drive may legitimately carry either spelling, and the +# visible one is what rekordbox itself writes. +PIONEER_DIRS = ("PIONEER", ".PIONEER") +DB_SUBPATH = Path("rekordbox") / "exportLibrary.db" + +# The analysis file the database points at is the `.DAT`; its siblings differ +# only by extension. `.EXT` carries the complete cue list and the colour +# waveforms, `.2EX` the newer high-resolution ones. +ANLZ_EXTENDED = ".EXT" + + +@dataclass(frozen=True) +class DriveLayout: + """A located OneLibrary drive: its mount point and its database.""" + + root: Path + database: Path + + @classmethod + def locate(cls, path: Path) -> "DriveLayout | None": + """Find the layout for `path`, or None if it is not a OneLibrary drive. + + Accepts either end of the drive deliberately: the MOUNT POINT, which is + what discovery finds and what a user picks in a file browser, or the + ``exportLibrary.db`` ITSELF, which is what someone reaches by drilling + into the folder or by re-opening a remembered path. Both name the same + library, and refusing one of them would make the picker and the + last-opened shortcut disagree about what a valid library is. + """ + path = Path(path) + try: + if path.is_file(): + # .../PIONEER/rekordbox/exportLibrary.db -> the drive is 3 up. + if path.name.lower() != "exportLibrary.db".lower(): + return None + root = path.parent.parent.parent + if path.parent.parent.name not in PIONEER_DIRS: + return None + return cls(root=root, database=path) + if path.is_dir(): + for pioneer in PIONEER_DIRS: + db = path / pioneer / DB_SUBPATH + if db.is_file(): + return cls(root=path, database=db) + except OSError: + return None + return None + + def resolve(self, drive_relative: str | None) -> Path | None: + """A stored drive-relative path as a real path on this host. + + Stored paths are POSIX-style and lead with a slash. That leading slash is + NOT a host root — treating it as one is the mistake this method exists to + prevent, since ``Path('/Volumes/X') / '/Contents/a.mp3'`` silently + discards the mount point and yields ``/Contents/a.mp3``. + """ + if not drive_relative: + return None + relative = str(drive_relative).replace("\\", "/").lstrip("/") + if not relative: + return None + return self.root / relative + + def extended_anlz(self, dat_path: Path) -> Path: + """The `.EXT` beside a given `.DAT`. + + Cues are read from the `.EXT`, not the `.DAT` the database points at: + see `cues.py` for why that distinction is load-bearing rather than a + preference. + """ + return dat_path.with_suffix(ANLZ_EXTENDED) diff --git a/backend/konduktor/adapters/onelibrary/projection.py b/backend/konduktor/adapters/onelibrary/projection.py new file mode 100644 index 0000000..639363b --- /dev/null +++ b/backend/konduktor/adapters/onelibrary/projection.py @@ -0,0 +1,118 @@ +"""OneLibrary rows -> the generic projection. + +The only place a ``devicelib_plus`` ORM object becomes a generic `Track` / +`TrackCues`. Everything above this file sees generic types exclusively. + +Field conventions are read off a real rekordbox 7 export rather than guessed: + + * ``bpmx100`` is the tempo in hundredths, and it is a DISPLAY value — the real + grid is per-beat in the ANLZ file, and a variable-tempo track stores only its + first tempo here. + * ``rating`` is 0-5 directly, like `master.db` and unlike Traktor's /51. + * ``length`` is whole seconds. + * ``path`` is drive-relative with a leading slash; the store resolves it. + * dates arrive as `datetime` from the ORM, not as strings. +""" +from __future__ import annotations + +from ...core.model import GridMarker, Track, TrackCues +from ..rekordbox.projection import parse_key + + +def _name_of(related) -> str | None: + """A joined lookup row's display name, or None when unset.""" + if related is None: + return None + value = getattr(related, "name", None) + return str(value) if value else None + + +def _iso_date(value) -> str | None: + """`YYYY-MM-DD` from whatever the column holds. + + The ORM converts the stored strings to `datetime`, so this takes the date + part of one — but a drive written by another vendor's software may well + store a plain string, and passing that through unchanged is better than + losing it. + """ + if not value: + return None + date = getattr(value, "date", None) + if callable(date): + try: + return date().isoformat() + except Exception: # noqa: BLE001 + pass + text = str(value).strip() + return text.split(" ")[0] if text else None + + +def _bpm(row) -> float | None: + raw = getattr(row, "bpmx100", None) + if not raw: + return None + return round(int(raw) / 100.0, 2) + + +def to_track(row, drive_path: str | None = None) -> Track: + """Project one ``Content`` row. + + **The three count fields are approximations here**, and deliberately so. Cues + and the beatgrid both live in the track's ANLZ files, and parsing a track's + `.EXT` costs ~23 ms — ~23 s for a 1,000-track drive if done at open. So a + track that has an analysis file and a tempo is reported as having one grid + marker (constant tempo, true for all but a fraction of a percent of tracks) + and no cues, and all three are corrected the moment the track's cues are + actually read. `adapter.track_cues` is where that happens. + + Reporting zero cues rather than a guess is the honest direction to be wrong + in: a count that appears from nowhere on selection reads as the detail + arriving, whereas one that shrinks reads as data being lost. + """ + key_name = _name_of(getattr(row, "key", None)) + wheel, mode = parse_key(key_name) + has_analysis = bool(getattr(row, "analysisDataFilePath", None)) + bpm = _bpm(row) + return Track( + id=str(getattr(row, "path", "") or ""), + artist=_name_of(getattr(row, "artist", None)), + title=getattr(row, "title", None), + album=_name_of(getattr(row, "album", None)), + genre=_name_of(getattr(row, "genre", None)), + label=_name_of(getattr(row, "label", None)), + remixer=_name_of(getattr(row, "remixer", None)), + # OneLibrary has `composer` and `lyricist`, neither of which is Traktor's + # "producer" or "mix", so nothing is mapped onto them approximately. + producer=None, + mix=None, + comment=getattr(row, "djComment", None), + bpm=bpm, + key=key_name, + key_wheel=wheel, + key_mode=mode, + rating=max(0, min(5, int(getattr(row, "rating", 0) or 0))), + playcount=getattr(row, "djPlayCount", None), + length=getattr(row, "length", None), + bitrate=getattr(row, "bitrate", None), + import_date=_iso_date(getattr(row, "dateAdded", None)), + last_played=None, # the drive records history as playlists, not per track + release_date=_iso_date(getattr(row, "releaseDate", None)) + or (str(getattr(row, "releaseYear", "") or "") or None), + filepath=drive_path, + cue_count=0, + hotcue_count=0, + grid_marker_count=1 if (bpm and has_analysis) else 0, + grid_locked=False, # OneLibrary has no grid lock + media_kind="audio", + ) + + +def to_track_cues(cues: list, grid_markers: list[GridMarker]) -> TrackCues: + """Project a track's cues and beatgrid. + + `cues` are already generic — see `store.cues` for why that boundary sits + where it does — so this is the assembly point rather than a translation. + Nothing here is editable: a OneLibrary drive is read-only in Konduktor, and + `capabilities.writable` says so at the library level. + """ + return TrackCues(grid_markers=grid_markers, grid_locked=False, cues=list(cues)) diff --git a/backend/konduktor/adapters/onelibrary/store.py b/backend/konduktor/adapters/onelibrary/store.py new file mode 100644 index 0000000..295d3ed --- /dev/null +++ b/backend/konduktor/adapters/onelibrary/store.py @@ -0,0 +1,248 @@ +"""The retained native model for a OneLibrary drive. + +Owns the open ``exportLibrary.db`` and the drive layout around it, and is the +only place a ``pyrekordbox.devicelib_plus`` row or an ANLZ tag is touched. + +The database is SQLCipher-encrypted SQLite, like Rekordbox's ``master.db``, but +with a **different and universal key**: every OneLibrary drive from every vendor +is encrypted with the same one, which is what makes the format readable across +brands at all. `pyrekordbox` carries it, so nothing here needs to know it. + +**Analysis files are parsed lazily, and that is a measurement, not a +preference.** The beatgrid and the cues both live in the per-track ANLZ files, +and parsing one costs ~2 ms for the `.DAT` but ~23 ms for the `.EXT`, which +carries the colour waveforms as well. Reading every track's `.EXT` at open would +cost ~23 s on a 1,000-track drive — so it happens on demand and is cached, the +same bargain the Rekordbox adapter strikes for its grids. The visible +consequence is that cue and marker counts are approximate in the library table +until a track's cues are actually read; see `projection.to_track`. +""" +from __future__ import annotations + +import logging +from pathlib import Path + +from ...core.adapter import LibraryNotSupported, NotFound +from ...core.model import CuePoint +from . import beatgrid, cues as cue_reader +from .layout import DriveLayout + +log = logging.getLogger(__name__) + + +class OneLibraryStore: + def __init__(self, path: Path): + layout = DriveLayout.locate(Path(path)) + if layout is None: + raise LibraryNotSupported(f"No OneLibrary database found at {path}") + self.layout = layout + self.path = layout.database + self._db = None + # Parsed ANLZ, keyed by track id. Two caches because the two files cost + # an order of magnitude apart: a grid read must not drag in the .EXT. + self._dat_cache: dict[str, object | None] = {} + self._ext_cache: dict[str, object | None] = {} + self._content_cache: list | None = None + self._by_id: dict[str, object] | None = None + self._load() + + # ---- open / close ---------------------------------------------------- + def _load(self) -> None: + try: + from pyrekordbox.devicelib_plus import DeviceLibraryPlus + except ImportError as ex: # pragma: no cover — dependency missing + raise LibraryNotSupported( + "Reading OneLibrary drives needs pyrekordbox with devicelib_plus" + ) from ex + try: + self._db = DeviceLibraryPlus(str(self.path)) + except Exception as ex: # noqa: BLE001 — surfaced as a clean 4xx + raise LibraryNotSupported(f"Could not open OneLibrary database: {ex}") from ex + self._dat_cache.clear() + self._ext_cache.clear() + self._content_cache = None + self._by_id = None + + def close(self) -> None: + """Release the database AND the underlying file handle. + + Disposing the engine matters more here than anywhere else: the library + is on a REMOVABLE drive, and a lingering handle is what makes a stick + refuse to eject. `DeviceLibraryPlus.close()` only ends the session, so + the engine is disposed explicitly — the same gap the Rekordbox store + had to close for `master.db`. + """ + db, self._db = self._db, None + if db is None: + return + try: + db.close() + except Exception: # noqa: BLE001 — closing must not raise + log.debug("OneLibrary session close failed", exc_info=True) + engine = getattr(db, "engine", None) + if engine is not None: + try: + engine.dispose() + except Exception: # noqa: BLE001 + log.debug("OneLibrary engine dispose failed", exc_info=True) + + def _require_db(self): + if self._db is None: + raise LibraryNotSupported("The OneLibrary database is closed") + return self._db + + # ---- identity -------------------------------------------------------- + @property + def device_name(self) -> str | None: + """The drive's own name, which is NOT the volume label. + + Stored in `property.deviceName` and often blank — rekordbox leaves it + empty unless the user names the device — so the mount point's name is + the fallback a person will actually recognise. + """ + try: + row = self._require_db().get_property().first() + except Exception: # noqa: BLE001 + return None + name = (getattr(row, "deviceName", "") or "").strip() if row is not None else "" + return name or self.layout.root.name or None + + @property + def db_version(self) -> str | None: + try: + row = self._require_db().get_property().first() + except Exception: # noqa: BLE001 + return None + value = getattr(row, "dbVersion", None) if row is not None else None + return str(value) if value else None + + # ---- tracks ---------------------------------------------------------- + def iter_content(self) -> list: + """Every track row, cached for the life of the open library.""" + if self._content_cache is None: + rows = list(self._require_db().get_content()) + self._content_cache = rows + self._by_id = {self.track_id(r): r for r in rows} + return self._content_cache + + @staticmethod + def track_id(row) -> str: + """A track's stable id: its DRIVE-RELATIVE path. + + Not `content_id`, which is a row number rekordbox reassigns from 1 every + time it rewrites the drive — so it would change under a user who merely + re-exported, breaking every playlist reference Konduktor had remembered. + The path is stable, unique on the drive, and is also the key a future + import would match against a Traktor collection, so it is the honest + identity here. + """ + return str(getattr(row, "path", "") or f"content:{getattr(row, 'content_id', '')}") + + def content(self, track_id: str): + self.iter_content() + row = (self._by_id or {}).get(str(track_id)) + if row is None: + raise NotFound(f"No track {track_id!r} on this OneLibrary drive") + return row + + def audio_path(self, track_id: str) -> Path | None: + return self.layout.resolve(getattr(self.content(track_id), "path", None)) + + def all_audio_paths(self) -> list[str]: + out: list[str] = [] + for row in self.iter_content(): + resolved = self.layout.resolve(getattr(row, "path", None)) + if resolved is not None: + out.append(str(resolved)) + return out + + # ---- analysis files -------------------------------------------------- + def _anlz(self, track_id: str, *, extended: bool): + """The parsed `.DAT` or `.EXT` for a track, or None if unreadable. + + A missing or corrupt analysis file is a normal state on a real drive — + an unanalysed track has none — so it is cached as None and never raised. + """ + cache = self._ext_cache if extended else self._dat_cache + key = str(track_id) + if key in cache: + return cache[key] + + cache[key] = None + row = self.content(track_id) + dat = self.layout.resolve(getattr(row, "analysisDataFilePath", None)) + if dat is None: + return None + target = self.layout.extended_anlz(dat) if extended else dat + try: + if not target.is_file(): + return None + from pyrekordbox.anlz import AnlzFile + + cache[key] = AnlzFile.parse_file(str(target)) + except Exception: # noqa: BLE001 — a bad file must not break browsing + log.debug("Could not parse ANLZ %s", target, exc_info=True) + return None + return cache[key] + + def anlz_grid(self, track_id: str) -> tuple[list[float], list[float]] | None: + """The per-beat ``(times, bpms)`` from the track's `PQTZ` tag. + + `PQTZ` is in the `.DAT`, which is the cheap file — a grid read does not + pay for the `.EXT`'s waveforms. + """ + anlz = self._anlz(track_id, extended=False) + if anlz is None: + return None + return beatgrid.beats_from_pqtz(anlz) + + def cues(self, track_id: str) -> list[CuePoint]: + """The track's cues, already generic. + + Unusually for a store, this returns generic types rather than native + rows: the native shape is a pair of parsed tag containers whose entries + only mean anything once merged across two files, and handing that to the + projection would put ANLZ knowledge on both sides of the boundary. + """ + return cue_reader.cues_from_anlz( + self._anlz(track_id, extended=False), + self._anlz(track_id, extended=True), + ) + + # ---- playlists ------------------------------------------------------- + def playlists(self) -> list: + return list(self._require_db().get_playlist()) + + def count_playlists(self) -> int: + try: + return self._require_db().get_playlist().count() + except Exception: # noqa: BLE001 + return 0 + + def playlist_song_ids(self, node_id: str) -> list[str]: + """Track ids in a playlist, in the order the drive stores them. + + `playlist_content` joins on `content_id`, but Konduktor's track id is the + path (see `track_id`), so the row numbers are translated here rather than + leaking a second notion of identity upward. + """ + try: + pid = int(node_id) + except (TypeError, ValueError): + return [] + self.iter_content() + by_content_id = { + int(getattr(r, "content_id", -1)): self.track_id(r) for r in self.iter_content() + } + rows = [ + r + for r in self._require_db().get_playlist_content() + if int(getattr(r, "playlist_id", -1)) == pid + ] + rows.sort(key=lambda r: int(getattr(r, "sequenceNo", 0) or 0)) + out: list[str] = [] + for r in rows: + track_id = by_content_id.get(int(getattr(r, "content_id", -1))) + if track_id is not None: + out.append(track_id) + return out diff --git a/backend/konduktor/adapters/rekordbox/adapter.py b/backend/konduktor/adapters/rekordbox/adapter.py index 9b5fae5..4aa2154 100644 --- a/backend/konduktor/adapters/rekordbox/adapter.py +++ b/backend/konduktor/adapters/rekordbox/adapter.py @@ -137,7 +137,7 @@ class RekordboxAdapter: # ---- playlists ------------------------------------------------------- def playlist_tree(self) -> list[PlaylistNode]: """Rekordbox stores the tree as a flat table with ``ParentID`` links.""" - from pyrekordbox.db6 import tables + from pyrekordbox.masterdb import models as tables rows = self._store.playlists() folder = int(tables.PlaylistType.FOLDER) diff --git a/backend/konduktor/adapters/rekordbox/driver.py b/backend/konduktor/adapters/rekordbox/driver.py index 24e0192..f58ffa3 100644 --- a/backend/konduktor/adapters/rekordbox/driver.py +++ b/backend/konduktor/adapters/rekordbox/driver.py @@ -41,7 +41,7 @@ class RekordboxDriver: def _has_rekordbox_schema(path: Path) -> bool: try: import sqlcipher3.dbapi2 as sqlcipher - from pyrekordbox.db6.database import BLOB + from pyrekordbox.masterdb.database import BLOB from pyrekordbox.utils import deobfuscate except ImportError: # pragma: no cover — dependency missing return False diff --git a/backend/konduktor/adapters/rekordbox/store.py b/backend/konduktor/adapters/rekordbox/store.py index d14b48d..b661ddd 100644 --- a/backend/konduktor/adapters/rekordbox/store.py +++ b/backend/konduktor/adapters/rekordbox/store.py @@ -68,12 +68,12 @@ class RekordboxStore: # ---- open ------------------------------------------------------------ def _load(self) -> None: - from pyrekordbox import Rekordbox6Database - from pyrekordbox.db6 import tables + from pyrekordbox.masterdb import MasterDatabase + from pyrekordbox.masterdb import models as tables self._tables = tables try: - self._db = Rekordbox6Database(path=str(self.path), unlock=True) + self._db = MasterDatabase(path=str(self.path), unlock=True) except Exception as ex: # noqa: BLE001 — surfaced as a clean 4xx raise LibraryNotSupported(f"Could not open Rekordbox library: {ex}") from ex self._grid_cache.clear() @@ -208,7 +208,7 @@ class RekordboxStore: Sync") in the same table at reserved ids. They are not the user's and showing them in the sidebar would be noise. """ - from pyrekordbox.db6.database import SPECIAL_PLAYLIST_IDS + from pyrekordbox.masterdb.database import SPECIAL_PLAYLIST_IDS t = self._tables return [ @@ -480,7 +480,7 @@ class RekordboxStore: timestamps in step — still runs as the library intends. Duplicating that body here would silently drift from it on upgrade. """ - from pyrekordbox.db6 import database as rb_database + from pyrekordbox.masterdb import database as rb_database if rb_database.get_rekordbox_pid(): log.warning( @@ -508,7 +508,7 @@ class RekordboxStore: def app_running(self) -> bool: """Whether a Rekordbox process is up — for warning the user, not blocking.""" try: - from pyrekordbox.db6 import database as rb_database + from pyrekordbox.masterdb import database as rb_database return bool(rb_database.get_rekordbox_pid()) except Exception: # noqa: BLE001 — detection must never break a save diff --git a/backend/requirements.txt b/backend/requirements.txt index 54e7e4f..449c9b0 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -19,4 +19,13 @@ scikit-learn>=1.5 traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git # Rekordbox (master.db is SQLCipher-encrypted SQLite + per-track ANLZ analysis # files). Both ship prebuilt Python 3.14 wheels — no Rust/OpenSSL source build. -pyrekordbox>=0.4.4 +# +# FROM GITHUB, NOT PyPI — the same situation as traktor-nml-utils above, and for +# the same kind of reason. PyPI's latest (0.4.4) has no `devicelib_plus`, which +# is the OneLibrary (`exportLibrary.db`) reader the OneLibrary adapter is built +# on; it exists only on master. Do not "simplify" this back to a version pin. +# +# The upgrade also renames `db6` to `masterdb`. `db6` still works as a +# deprecated alias and is removed in 0.6.0, so the Rekordbox adapter keeps +# running as-is — but that rename is the thing to fix before taking 0.6. +pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git diff --git a/backend/run_tests.sh b/backend/run_tests.sh index 980559e..cc413cd 100755 --- a/backend/run_tests.sh +++ b/backend/run_tests.sh @@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")" source .venv/bin/activate fail=0 -for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_phase3.py test_history.py; do +for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_phase3.py test_history.py; do echo "──────────────────────────────────────────" echo "▶ $t" echo "──────────────────────────────────────────" diff --git a/backend/test_layering.py b/backend/test_layering.py index 5fd23cd..1835ffd 100644 --- a/backend/test_layering.py +++ b/backend/test_layering.py @@ -49,7 +49,18 @@ check("the Traktor store is where traktor_nml_utils lives", "traktor_nml_utils" # No adapter may import another platform's library. That is the rule that keeps # the packages independently removable, and it is checked on real imports (AST) # rather than on text, so merely NAMING another platform in a comment is fine. -NATIVE = {"traktor": "traktor_nml_utils", "rekordbox": "pyrekordbox"} +# OneLibrary shares Rekordbox's native library: both are AlphaTheta formats +# read through pyrekordbox. That makes the map non-injective, which is fine — +# the rule being enforced is "no adapter reaches for a RIVAL vendor's library", +# and a shared dependency is not a layering breach. (The OneLibrary adapter +# also imports the Rekordbox adapter's ANLZ beatgrid helper on purpose: one +# definition of "when does a tempo change start a new marker" is worth more +# than two packages that can be deleted independently.) +NATIVE = { + "traktor": "traktor_nml_utils", + "rekordbox": "pyrekordbox", + "onelibrary": "pyrekordbox", +} def imported_modules(path): @@ -66,7 +77,10 @@ for platform, module in NATIVE.items(): pkg = CORE.parent / "adapters" / platform if not pkg.is_dir(): continue - foreign = {m for p_, m in NATIVE.items() if p_ != platform} + # Subtract the adapter's OWN module: two adapters may legitimately share a + # native library (Rekordbox and OneLibrary both use pyrekordbox), and + # without this every shared dependency reads as a foreign one. + foreign = {m for p_, m in NATIVE.items() if p_ != platform} - {module} strays = [] for src in sorted(pkg.rglob("*.py")): for name in imported_modules(src): diff --git a/backend/test_onelibrary_adapter.py b/backend/test_onelibrary_adapter.py new file mode 100644 index 0000000..e314fce --- /dev/null +++ b/backend/test_onelibrary_adapter.py @@ -0,0 +1,358 @@ +"""Tests for the OneLibrary adapter (read-only). + +The third platform against the same contract, and the first whose library is a +REMOVABLE DRIVE rather than a file — so the layout resolution gets as much +attention here as the projection does. + +Unlike `test_rekordbox_adapter.py`, this needs nothing installed and nothing +plugged in: it runs against `fixtures/onelibrary/`, a real rekordbox 7 export +trimmed to fixture size (see its README). That makes it deterministic on any +machine, and it also means the expected values below are checked against bytes +rekordbox wrote rather than against bytes Konduktor wrote — which is the only +way a "we read the format correctly" claim means anything. + +Where a value was cross-checked against the SAME cues in the desktop +`master.db`, the test says so, because that cross-check is what pins the slot +numbering (the one thing most likely to be silently wrong). +""" +import os +import shutil +import sys +import tempfile +import warnings +from pathlib import Path + +warnings.filterwarnings("ignore") +os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-ol-appdata-") + +from konduktor.adapters.onelibrary import discovery # noqa: E402 +from konduktor.adapters.onelibrary.adapter import OneLibraryAdapter # noqa: E402 +from konduktor.adapters.onelibrary.beatgrid import markers_from_beats # noqa: E402 +from konduktor.adapters.onelibrary.cues import ( # noqa: E402 + MEMORY_SLOT, + NO_LOOP, + cues_from_anlz, +) +from konduktor.adapters.onelibrary.driver import OneLibraryDriver # noqa: E402 +from konduktor.adapters.onelibrary.layout import DriveLayout # noqa: E402 +from konduktor.core import registry # noqa: E402 +from konduktor.core.adapter import LibraryAdapter, NotFound, Unsupported # noqa: E402 + +FIXTURE = Path(__file__).resolve().parent / "fixtures" / "onelibrary" + +failed = False + + +def check(label, cond, detail=""): + global failed + print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else "")) + if not cond: + failed = True + + +def _raises(fn, exc) -> bool: + try: + fn() + except exc: + return True + except Exception: # noqa: BLE001 — the wrong error is still a failure + return False + return False + + +# ---- pure units: no drive required -------------------------------------- +print("== drive layout ==") +tmp = Path(tempfile.mkdtemp(prefix="konduktor-ol-layout-")) +(tmp / "PIONEER" / "rekordbox").mkdir(parents=True) +db = tmp / "PIONEER" / "rekordbox" / "exportLibrary.db" +db.write_bytes(b"not really a database") + +layout = DriveLayout.locate(tmp) +check("a drive root is recognised", layout is not None and layout.database == db) +check("and so is the database file itself", + (l2 := DriveLayout.locate(db)) is not None and l2.root == tmp) +check("a directory with no PIONEER folder is not a drive", + DriveLayout.locate(Path(tempfile.mkdtemp())) is None) +check("a stray file called exportLibrary.db is not a drive", + DriveLayout.locate(Path(tempfile.mkdtemp()) / "exportLibrary.db") is None) + +# The stored path leads with a slash but is NOT absolute. Joining it naively +# discards the mount point entirely and silently yields /Contents/... — a bug +# that would look like "the drive is empty" rather than like a path error. +resolved = layout.resolve("/Contents/Music/a.mp3") +check("a drive-relative path resolves under the mount point", + resolved == tmp / "Contents" / "Music" / "a.mp3", str(resolved)) +check("the leading slash is not treated as a host root", + not str(resolved).startswith("/Contents")) +check("backslashes resolve too", layout.resolve("\\Contents\\a.mp3") == tmp / "Contents" / "a.mp3") +check("an empty path resolves to nothing", layout.resolve("") is None and layout.resolve(None) is None) +check("the .EXT sits beside the .DAT", + layout.extended_anlz(Path("/x/ANLZ0000.DAT")) == Path("/x/ANLZ0000.EXT")) +shutil.rmtree(tmp, ignore_errors=True) + +print("== beatgrid collapse ==") +# Shared with the Rekordbox adapter on purpose — two copies of this rule would be +# free to drift apart by a rounding tolerance, and a drifting grid is silent. +check("a constant tempo is one marker", + len(markers_from_beats([0.0, 0.5, 1.0], [120.0, 120.0, 120.0])) == 1) +check("a tempo change adds a marker", + [m.bpm for m in markers_from_beats([0.0, 0.5, 1.0], [120.0, 120.0, 90.0])] == [120.0, 90.0]) +check("no beats is no grid", markers_from_beats([], []) == []) + + +class _Entry(dict): + """A stand-in for a parsed ANLZ cue entry (construct Containers are dicts).""" + + def __getattr__(self, name): + try: + return self[name] + except KeyError as ex: + raise AttributeError(name) from ex + + +class _Tag: + def __init__(self, tag_type, entries): + self.type = tag_type + self.struct = type("S", (), {"content": type("C", (), {"entries": entries})()})() + + +class _Anlz: + def __init__(self, tags): + self.tags = tags + + +def _entry(**kw): + base = dict(hot_cue=1, time=1000, loop_time=NO_LOOP, type=1, + color_red=0, color_green=0, color_blue=0, comment="") + base.update(kw) + return _Entry(base) + + +print("== cue decoding ==") +# The generic slot is 0-based (slot 0 is the pad labelled A). ANLZ's hot_cue is +# a DENSE 1-based index, unlike master.db's Kind which skips 4 — so the two +# platforms need different arithmetic even though they are the same vendor. +one = cues_from_anlz(_Anlz([_Tag("PCO2", [_entry(hot_cue=1, time=5000)])]), None) +check("ANLZ hot_cue 1 is generic slot 0 — the pad labelled A", + len(one) == 1 and one[0].slot == 0 and one[0].role == "hotcue") +four = cues_from_anlz(_Anlz([_Tag("PCO2", [_entry(hot_cue=4)])]), None) +check("hot_cue 4 is slot 3 (pad D) — NOT shifted past a reserved value", + four[0].slot == 3) +mem = cues_from_anlz(_Anlz([_Tag("PCO2", [_entry(hot_cue=MEMORY_SLOT)])]), None) +check("hot_cue 0 is a memory cue with no slot", + mem[0].role == "memory" and mem[0].slot is None) + +# loop_time is an unsigned -1 when there is no loop, so a falsiness test would +# read 0xFFFFFFFF as a loop ending at zero. +point = cues_from_anlz(_Anlz([_Tag("PCO2", [_entry(type=1, loop_time=NO_LOOP)])]), None) +check("a point cue has no length", point[0].length == 0.0 and point[0].type == "cue") +loop = cues_from_anlz(_Anlz([_Tag("PCO2", [_entry(type=2, time=40000, loop_time=41875)])]), None) +check("a loop's length is its out minus its in", + loop[0].type == "loop" and abs(loop[0].length - 1.875) < 1e-9) + +check("a colour comes through as #RRGGBB", + cues_from_anlz(_Anlz([_Tag("PCO2", [_entry(color_red=255, color_green=140, color_blue=0)])]), + None)[0].color == "#FF8C00") +check("all-zero RGB means 'unset', not black", + cues_from_anlz(_Anlz([_Tag("PCO2", [_entry()])]), None)[0].color is None) + +# PCOB is split across the two files — .DAT holds pads 1-3, .EXT holds 4 and up — +# so a reader that looks at one file has an incomplete bank. +dat = _Anlz([_Tag("PCOB", [_entry(hot_cue=1), _entry(hot_cue=2, time=2000)])]) +ext = _Anlz([_Tag("PCOB", [_entry(hot_cue=4, time=4000)])]) +merged = cues_from_anlz(dat, ext) +check("PCOB is merged across the .DAT and the .EXT", + sorted(c.slot for c in merged) == [0, 1, 3], str([c.slot for c in merged])) +check("PCO2 wins over PCOB when both are present", + cues_from_anlz(dat, _Anlz([_Tag("PCO2", [_entry(hot_cue=8, time=9000)])]))[0].slot == 7) +check("the same cue in two tags is reported once", + len(cues_from_anlz(_Anlz([_Tag("PCO2", [_entry()]), _Tag("PCO2", [_entry()])]), None)) == 1) +check("no cue tags is no cues", cues_from_anlz(_Anlz([]), None) == []) +check("no analysis file at all is no cues", cues_from_anlz(None, None) == []) +check("nothing read from a drive claims to be editable", + all(not c.editable for c in merged)) + + +# ---- the real drive ------------------------------------------------------ +if not (FIXTURE / "PIONEER" / "rekordbox" / "exportLibrary.db").is_file(): + print(f"\nSKIP: no fixture drive at {FIXTURE}") + sys.exit(1 if failed else 0) + +print("\n== the driver recognises a drive by layout AND schema ==") +driver = OneLibraryDriver() +check("can_open accepts the drive root", driver.can_open(FIXTURE)) +check("can_open accepts the database directly", + driver.can_open(FIXTURE / "PIONEER" / "rekordbox" / "exportLibrary.db")) +check("can_open rejects an unrelated directory", not driver.can_open(Path(tempfile.mkdtemp()))) +check("the registry picks OneLibrary for it", registry.driver_for(FIXTURE).platform == "onelibrary") + +# The two encrypted databases must not be confused for one another. They are both +# SQLCipher with no readable header, and only the KEY tells them apart. +fake = Path(tempfile.mkdtemp()) / "PIONEER" / "rekordbox" / "exportLibrary.db" +fake.parent.mkdir(parents=True) +shutil.copy(Path(__file__), fake) # a plain text file wearing the right name +check("can_open rejects a non-database in the right place", not driver.can_open(fake.parent.parent.parent)) + +adapter = OneLibraryAdapter(FIXTURE) +check("implements the LibraryAdapter protocol", isinstance(adapter, LibraryAdapter)) + +print("== the projection ==") +tracks = adapter.tracks +check("both tracks project", len(tracks) == 2, str(len(tracks))) +by_title = {t.title: t for t in tracks} +one = next(t for t in tracks if t.title and t.title.startswith("Demo Track 1")) +check("title comes through", one.title.startswith("Demo Track 1")) +check("artist comes through the lookup table", one.artist == "Loopmasters") +check("label comes through the lookup table", one.label == "Loopmasters") +check("bpmx100 becomes a real BPM", one.bpm == 128.0, str(one.bpm)) +check("length is whole seconds", one.length == 172, str(one.length)) +check("rating is 0-5, not Traktor's /51", 0 <= one.rating <= 5) +check("comment comes through", (one.comment or "").startswith("Tracks by")) + +# The id is the drive-relative path, NOT content_id: rekordbox renumbers rows +# from 1 on every re-export, so a row number would break every remembered +# reference the moment the user re-wrote the stick. +check("the track id is its drive-relative path", + one.id == "/Contents/Loopmasters/UnknownAlbum/Demo Track 1.mp3", one.id) +check("filepath resolves under the mount point", + one.filepath == str(FIXTURE / "Contents/Loopmasters/UnknownAlbum/Demo Track 1.mp3")) +check("and the resolved file is really there", Path(one.filepath).is_file()) +check("audio_path agrees with the projection", str(adapter.audio_path(one.id)) == one.filepath) + +print("== counts are approximate until the cues are read ==") +check("no cues are claimed before the analysis file is parsed", one.cue_count == 0) +check("a tempo plus an analysis file is guessed as one marker", one.grid_marker_count == 1) +cues = adapter.track_cues(one.id) +check("reading cues corrects cue_count", one.cue_count == len(cues.cues) == 5, str(one.cue_count)) +check("reading cues corrects hotcue_count", one.hotcue_count == 4, str(one.hotcue_count)) +check("reading cues corrects grid_marker_count", one.grid_marker_count == 2, str(one.grid_marker_count)) +check("track_cues on an unknown track is None", adapter.track_cues("no-such-track") is None) + +print("== the beatgrid survives an export ==") +# This grid was written into master.db by Konduktor, exported by rekordbox, and +# confirmed on screen in Rekordbox 7 before it ever reached this fixture. +markers = cues.grid_markers +check("a flexible grid stays flexible", len(markers) == 2, str(len(markers))) +check("the first segment is 128 BPM", markers[0].bpm == 128.0) +check("the second segment is 90 BPM", markers[1].bpm == 90.0) +check("and it starts at 60 s", abs(markers[1].start - 60.0) < 0.001, str(markers[1].start)) +check("markers are ordered by position", [m.start for m in markers] == sorted(m.start for m in markers)) + +print("== cues, cross-checked against the same cues in master.db ==") +# master.db held djmdCue Kind 1/2/3/5 at 40.000 s / 18.773 s / 90.667 s / +# 120.000 s plus a reserved-Kind memory loop at 40.000 s. Those same five cues +# must come back here as slots 0/1/2/3 and one memory cue — which is what pins +# ANLZ's dense numbering against master.db's sparse bank. +hot = {c.slot: c for c in cues.cues if c.role == "hotcue"} +check("four hot cues, on pads A-D", sorted(hot) == [0, 1, 2, 3], str(sorted(hot))) +check("pad A is the loop at 40.000 s", + hot[0].type == "loop" and abs(hot[0].start - 40.0) < 0.001) +check("pad A's loop is 4 beats at 128 BPM = 1.875 s", abs(hot[0].length - 1.875) < 0.001) +check("pad B is at 18.775 s", abs(hot[1].start - 18.775) < 0.001, str(hot[1].start)) +check("pad C is at 90.667 s", abs(hot[2].start - 90.667) < 0.001, str(hot[2].start)) +# Pad D exists ONLY in the .EXT. A reader that stopped at the .DAT would lose it, +# and would do so silently. +check("pad D is at 120.000 s — the cue that lives only in the .EXT", + abs(hot[3].start - 120.0) < 0.001, str(hot[3].start)) +check("hot cues carry their RGB colour", all(c.color and c.color.startswith("#") for c in hot.values())) + +memory = [c for c in cues.cues if c.role == "memory"] +check("the memory cue is preserved", len(memory) == 1) +check("it has no slot", memory[0].slot is None) +check("it is the same loop, at the same place", abs(memory[0].start - 40.0) < 0.001) +check("no cue on a read-only drive is editable", all(not c.editable for c in cues.cues)) + +print("== playlists ==") +tree = adapter.playlist_tree() +check("the playlist is at the root", len(tree) == 1 and tree[0].name == "demos", str(tree)) +node = tree[0] +check("it is a playlist, not a folder", node.kind == "playlist" and node.selectable) +check("its count is right", node.count == 2, str(node.count)) +check("playlist_count agrees", adapter.playlist_count() == 1) +entries = adapter.playlist_entries(node.id) +check("its entries are track ids, in order", + entries == [t.id for t in (adapter.playlist_tracks(node.id) or [])]) +check("and they resolve to the two tracks", len(adapter.playlist_tracks(node.id)) == 2) +check("a root playlist's parent 0 is not treated as a real node id", len(tree) == 1) +check("nothing on the drive claims to be editable", + not any(n.can_rename or n.can_delete or n.can_add_tracks or n.can_reorder for n in tree)) +check("entries for an unknown node are None", adapter.playlist_entries("999999") is None) + +print("== capabilities gate the UI ==") +caps = adapter.capabilities() +check("platform is onelibrary", caps.platform == "onelibrary") +# The distinction the whole capability system exists for: this is a roadmap gap, +# not a protective refusal, and the UI must word the two differently. +check("the library is read-only", caps.writable is False) +check("because the platform is incomplete, not because of a sync state", + caps.readonly_cause == "platform_incomplete") +check("the version is the drive's dbVersion", caps.version == "1000", str(caps.version)) +# The per-feature flags still describe the FORMAT. Blanking them to false would +# claim OneLibrary has no hot cues, which is not what read-only means. +check("the format is still reported as having hot cues", caps.cues.hotcue_slots == 8) +check("cue colour is free RGB here, unlike master.db's palette", caps.cues.color == "free") +check("loops are a cue type, not a separate bank", caps.cues.loops == "cue_type") +check("memory cues are acknowledged", caps.cues.memory_cues is True) +check("the grid is flexible even though we do not write it", caps.grid.flexible is True) +check("nothing is editable", not caps.cues.editable and not caps.grid.editable) +check("no metadata field is editable", caps.tracks.editable_fields == []) +check("ratings are 0-5", caps.tracks.rating_max == 5) +check("folders are supported by the format", caps.playlists.folders is True) +check("a drive carries no smart playlists", caps.playlists.smart == "none") +check("drives are not versioned", caps.save.history is False) +check("nothing else can overwrite it, because we never write", caps.save.overwrite_risk == "none") +check("the label is the drive's name", caps.save.library_label == FIXTURE.name) + +print("== every command is refused ==") +COMMANDS = [ + ("set_track_metadata", lambda: adapter.set_track_metadata(one.id, {"title": "x"})), + ("set_cover_art", lambda: adapter.set_cover_art(one.id, b"", "image/png")), + ("create_playlist", lambda: adapter.create_playlist("x")), + ("rename_playlist", lambda: adapter.rename_playlist(node.id, "x")), + ("delete_playlist", lambda: adapter.delete_playlist(node.id)), + ("set_playlist_entries", lambda: adapter.set_playlist_entries(node.id, [])), + ("set_cue", lambda: adapter.set_cue(one.id, slot=0, start_sec=1.0, cue_type="cue")), + ("set_cue_type", lambda: adapter.set_cue_type(one.id, 0, "loop")), + ("delete_cue", lambda: adapter.delete_cue(one.id, 0)), + ("place_cues", lambda: adapter.place_cues(one.id, [])), + ("add_grid_marker", lambda: adapter.add_grid_marker(one.id, 1.0)), + ("move_grid_marker", lambda: adapter.move_grid_marker(one.id, 0, 1.0)), + ("set_grid_marker_bpm", lambda: adapter.set_grid_marker_bpm(one.id, 0, 120.0)), + ("delete_grid_marker", lambda: adapter.delete_grid_marker(one.id, 0)), + ("replace_grid", lambda: adapter.replace_grid(one.id, [])), + ("set_analysed_grid", lambda: adapter.set_analysed_grid(one.id, [])), + ("delete_grid", lambda: adapter.delete_grid(one.id)), + ("set_grid_lock", lambda: adapter.set_grid_lock(one.id, True)), + ("remap_locations", lambda: adapter.remap_locations(None)), + ("save", lambda: adapter.save()), + ("snapshot", lambda: adapter.snapshot()), +] +refused = [name for name, fn in COMMANDS if not _raises(fn, Unsupported)] +check(f"all {len(COMMANDS)} commands raise Unsupported", not refused, "; ".join(refused)) +check("nothing is ever dirty", adapter.dirty is False) +check("an unknown track is a NotFound, not an Unsupported", + _raises(lambda: adapter.audio_path("no-such-track"), NotFound)) + +print("== reads that answer rather than refuse ==") +check("cover art is absent, not an error", adapter.cover_art(one.id) is None) +# A drive stores everything relative to its own root, so it cannot have stale +# absolute paths and there is nothing for a remap to fix. +check("a path mapping is accepted and ignored", adapter.set_path_mapping(None) is None) +check("remap_preview matches nothing", adapter.remap_preview(None)["matched"] == 0) +check("path suggestions still describe the drive", + adapter.path_prefix_suggestions()["primary"] is not None) + +print("== discovery ==") +described = discovery.describe(FIXTURE) +check("a drive describes itself by name", FIXTURE.name in described["label"], described["label"]) +check("and points at the database", described["path"].endswith("exportLibrary.db")) +check("and reports that it exists", described["exists"] is True) +check("detection of unplugged drives is empty, not an error", + isinstance(discovery.detect_libraries(), list)) + +adapter.close() +check("closing twice is safe", adapter.close() is None) + +print() +print("RESULT:", "FAILED" if failed else "ALL PASSED") +sys.exit(1 if failed else 0) diff --git a/backend/test_rekordbox_adapter.py b/backend/test_rekordbox_adapter.py index a909dd3..ac22482 100644 --- a/backend/test_rekordbox_adapter.py +++ b/backend/test_rekordbox_adapter.py @@ -230,10 +230,34 @@ with tempfile.TemporaryDirectory() as d: walk(tree) check("no internal Rekordbox playlist is exposed", all(i not in ("100000", "200000") for i in ids), str(ids)) - check("nothing claims to be editable", not any( - n.can_rename or n.can_delete or n.can_add_tracks or n.can_reorder - for n in tree - )) + # Per-node flags must follow the node's KIND, not the library's writability + # alone: a folder holds no tracks and a smart playlist has no static entry + # list, so offering "add tracks" on either would be a control that cannot + # work. (This assertion used to read "nothing claims to be editable", which + # was left over from the read-only milestone and had been passing only + # because the reference library happened to contain no user playlists.) + def flags_match_kind(n): + if n.kind == "playlist": + return n.can_add_tracks and n.can_reorder and n.selectable + return not n.can_add_tracks and not n.can_reorder and not n.selectable + + all_nodes: list = [] + + def collect(nodes): + for n in nodes: + all_nodes.append(n) + collect(n.children) + + collect(tree) + bad = [f"{n.name!r} ({n.kind})" for n in all_nodes if not flags_match_kind(n)] + check("per-node flags follow the node's kind", not bad, "; ".join(bad[:3])) + check("only folders may contain children", + all(n.can_contain_children == (n.kind == "folder") for n in all_nodes)) + # Playlists became writable in milestone 2, so on a non-cloud library the + # tree must NOT be inert — that is what the UI gates its controls on. + if all_nodes and not adapter.cloud_synced: + check("a writable library offers playlist editing", + any(n.can_rename and n.can_delete for n in all_nodes)) print("== capabilities gate the UI ==") caps = adapter.capabilities() @@ -450,7 +474,7 @@ with tempfile.TemporaryDirectory() as d: # Konduktor's settled behaviour is to warn, not block — matching Traktor — # and the library's check is process-wide, so it would otherwise refuse to # write a temp copy while the user had a different library open. - from pyrekordbox.db6 import database as _rb_database + from pyrekordbox.masterdb import database as _rb_database _real_pid = _rb_database.get_rekordbox_pid _rb_database.get_rekordbox_pid = lambda *a, **kw: 4242 # pretend it is running @@ -473,7 +497,7 @@ with tempfile.TemporaryDirectory() as d: synced = Path(d) / "synced.db" shutil.copy2(work, synced) import sqlcipher3.dbapi2 as sqlcipher - from pyrekordbox.db6.database import BLOB + from pyrekordbox.masterdb.database import BLOB from pyrekordbox.utils import deobfuscate con = sqlcipher.connect(str(synced)) diff --git a/backend/test_rekordbox_fidelity.py b/backend/test_rekordbox_fidelity.py index 69754e0..1a3315c 100644 --- a/backend/test_rekordbox_fidelity.py +++ b/backend/test_rekordbox_fidelity.py @@ -46,7 +46,7 @@ def check(label, cond, detail=""): def dump(db_path: Path) -> dict: """Every row of every table, keyed by primary key.""" import sqlcipher3.dbapi2 as sqlcipher - from pyrekordbox.db6.database import BLOB + from pyrekordbox.masterdb.database import BLOB from pyrekordbox.utils import deobfuscate con = sqlcipher.connect(str(db_path))