Implemented OneLibrary adapter base

This commit is contained in:
patben8 committed 2026-09-22 16:43:12 +02:00
1 parent 7b0d7e3a07
commit 0b38d4826f
30 files changed
+2068 -22

No files matched your search

@@ -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)
@@ -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")
@@ -0,0 +1,62 @@
"""A OneLibrary beatgrid -> the generic marker list.
**The beatgrid is not in the database.** `exportLibrary.db` has no grid table at
all — `content.bpmx100` is a single display tempo — and the real grid is the
`PQTZ` tag of the track's ANLZ `.DAT`, holding EVERY BEAT explicitly. That is the
same arrangement, and the same tag, as a desktop Rekordbox library: a drive is
exported from one, and rekordbox regenerates the analysis files rather than
inventing a new format for them.
Verified end to end on a track whose flexible grid Konduktor itself had written
into `master.db`: exporting it to a OneLibrary drive preserved both tempo
segments exactly (128.00 BPM to 60 s, then 90.00 BPM), so multi-tempo grids
survive the whole chain and the marker list is the right generic shape.
The collapse rule is shared with the Rekordbox adapter deliberately rather than
copied. Two implementations of "when is this a new marker?" would be free to
drift apart by a rounding tolerance, and a drifting grid is a silent corruption
rather than a visible bug. If a third AlphaTheta-format adapter ever appears,
this and `rekordbox.beatgrid` should be promoted to one shared ANLZ module; the
import direction here is the cheapest way to stay honest until then.
"""
from __future__ import annotations
from ...core.model import GridMarker
from ..rekordbox.beatgrid import BPM_EPSILON, markers_from_beats # noqa: F401
__all__ = ["BPM_EPSILON", "markers_from_beats", "beats_from_pqtz", "markers_from_anlz"]
def beats_from_pqtz(anlz) -> tuple[list[float], list[float]] | None:
"""Per-beat ``(times_sec, bpms)`` from a parsed ANLZ file's `PQTZ` tag.
Returns None when the file has no `PQTZ` — which is a real state, not an
error: rekordbox analyses one-shot samples too, and gives them an analysis
file with no beatgrid in it.
`PQTZ` stores time in milliseconds and tempo in hundredths of a BPM.
"""
for tag in getattr(anlz, "tags", []):
if tag.type != "PQTZ":
continue
entries = getattr(getattr(tag.struct, "content", None), "entries", None)
if not entries:
return None
times: list[float] = []
bpms: list[float] = []
for e in entries:
try:
times.append(int(e.time) / 1000.0)
bpms.append(int(e.tempo) / 100.0)
except (AttributeError, TypeError, ValueError):
continue
return (times, bpms) if times else None
return None
def markers_from_anlz(anlz) -> list[GridMarker]:
"""The generic marker list for a parsed ANLZ file."""
grid = beats_from_pqtz(anlz)
if grid is None:
return []
return markers_from_beats(*grid)
@@ -0,0 +1,95 @@
"""What a OneLibrary drive can persist: nothing, for now.
`writable` is False with cause `platform_incomplete`. That is the distinction the
capability system exists to draw — this is a ROADMAP GAP, not a refusal. A
cloud-synced Rekordbox library is refused permanently to protect the user's other
machines; a OneLibrary drive simply has no write path yet, and the UI must word
those two very differently.
The per-feature flags below still report what the FORMAT supports rather than
being blanked to false, because that is what `writable=False` is for: the UI can
show a drive's cues and grid honestly, and say once, in one place, that the whole
library is read-only. Blanking them would claim OneLibrary has no hot cues.
Two answers are worth recording now, while the evidence is in front of us, since
getting them wrong later would be a silent data bug rather than a missing
feature:
* cue colour is **free RGB**, not a palette index. The `PCO2` tag stores three
bytes per cue, and the reference drive held #4D00FF, #33FF00, #00C4FF and
#FF8C00. This differs from the desktop Rekordbox adapter, which reports
"palette" because `djmdCue` stores an index into a built-in table — the same
vendor, two genuinely different representations.
* a loop is a cue with an out-point, so ``loops="cue_type"`` — the same answer
as Traktor and Rekordbox, and NOT the `separate_bank` the original
multi-platform plan assumed.
"""
from __future__ import annotations
from ...core.capabilities import (
Capabilities,
CueCapabilities,
GridCapabilities,
PlaylistCapabilities,
SaveCapabilities,
TrackCapabilities,
)
# Pads A-H. Unlike `djmdCue.Kind`, the ANLZ slot number is a dense 1-based index,
# so the bank really is 1..8 (see `cues.py`).
HOTCUE_SLOTS = 8
def capabilities_for(device_name: str | None = None, version: str | None = None) -> Capabilities:
return Capabilities(
platform="onelibrary",
version=version,
# A roadmap gap, not a protective refusal — the UI words the two
# differently, which is the whole reason `readonly_cause` exists.
writable=False,
readonly_cause="platform_incomplete",
cues=CueCapabilities(
editable=False,
hotcue_slots=HOTCUE_SLOTS,
slot_labels="letter",
# OneLibrary carries memory cues, as Rekordbox does. They are
# projected and preserved; nothing here is editable anyway.
memory_cues=True,
max_memory_cues=None,
types=["cue", "loop"],
color="free", # PCO2 stores RGB per cue, not a palette index
palette=[],
named=True, # PCO2 carries a per-cue comment
loops="cue_type",
),
# The grid is the ANLZ `PQTZ` tag, per beat, and multi-tempo grids do
# survive an export — so the format is flexible even though Konduktor
# does not write it here.
grid=GridCapabilities(editable=False, flexible=True, lockable=False),
tracks=TrackCapabilities(
rating_max=5, # stored 0-5 directly, as in master.db
editable_fields=[],
media_kinds=["audio"],
# The drive has an `image` table and an Artwork folder, but nothing
# is wired up to read them yet.
artwork=False,
artwork_note=None,
),
playlists=PlaylistCapabilities(
folders=True, # `playlist.attribute` 1, nested via playlist_id_parent
# A drive carries no smart playlists: rekordbox resolves them to
# static lists on export, because a CDJ cannot evaluate rules.
smart="none",
reorder=False,
),
save=SaveCapabilities(
app_name="OneLibrary",
library_label=device_name or "exportLibrary.db",
# Nothing is written, so nothing can be overwritten by another app.
overwrite_risk="none",
# A drive is a database plus N analysis files plus the audio itself,
# so there is no single blob that IS the library — the same reason
# Rekordbox libraries are not versioned.
history=False,
),
)
@@ -0,0 +1,188 @@
"""OneLibrary cues: read from the ANLZ analysis files, not the database.
**The `cue` table is not where a drive's cues are.** It exists in the schema —
and has columns for everything a cue needs — but rekordbox exports an empty one
and puts the cues in the track's ANLZ file instead. Measured on a real rekordbox
7 export of a track carrying four hot cues and a looped memory cue: the `cue`
table held zero rows and every cue was present in the analysis files. The table
appears to be for hardware writing edits BACK to the drive, which is a different
direction than this adapter reads.
Two tags carry cues, and they are not equivalent:
* **`PCOB`** is the original list, and it is SPLIT BY PAD. The `.DAT` holds
only hot cues 1-3 — the three pads the earliest CDJs had — and the `.EXT`
holds 4 and up. Reading only the `.DAT` silently loses pads D-H.
* **`PCO2`** is the extended list in the `.EXT`, and it holds the COMPLETE set
in one tag plus three things `PCOB` has nowhere to put: an RGB colour, a
comment, and the loop length expressed in BEATS.
So `PCO2` is preferred and `PCOB` is the fallback for a drive old enough not to
have one. Both are merged across files before that choice is made, because "the
complete list" must not depend on which file happened to be read.
**Slot numbering differs from `master.db` and this is the trap.** In the desktop
database a hot cue's `djmdCue.Kind` is a sparse bank that SKIPS 4 (`1,2,3,5,…`
for pads A-H). In ANLZ, `hot_cue` is a plain dense 1-based index (1=A, 2=B, …),
and `0` means the cue is a memory cue rather than a pad. The two were aligned
against each other on one track: `Kind` 1/2/3/5 at 40.000 s, 18.773 s, 90.667 s
and 120.000 s came out as `hot_cue` 1/2/3/4 at exactly the same times. Carry the
Rekordbox adapter's mapping over here unchanged and every cue from pad D onward
lands one pad too far along.
Times are MILLISECONDS here, where the desktop database counts frames at 150 fps.
"""
from __future__ import annotations
import logging
from ...core.model import CuePoint
log = logging.getLogger(__name__)
# `loop_time` when a cue is not a loop. Stored as an unsigned 32-bit -1 rather
# than 0, so a plain falsiness test would read it as "a loop ending at zero".
NO_LOOP = 0xFFFFFFFF
# `hot_cue` for a cue that sits in no pad bank, i.e. a memory cue.
MEMORY_SLOT = 0
# PCO2/PCOB entry kinds. The value is the same in both tags; PCOB exposes it as
# a construct enum and PCO2 as a plain int, so both are normalised to an int.
ENTRY_CUE = 1
ENTRY_LOOP = 2
def _entry_kind(value) -> int:
"""PCOB gives an enum, PCO2 an int — one number out of either."""
try:
return int(value)
except (TypeError, ValueError):
return ENTRY_CUE
def _color(entry) -> str | None:
"""A cue's colour as ``#RRGGBB``, when the tag carries one.
Only `PCO2` stores RGB. A cue with no colour set stores 0,0,0 — which is a
real black in principle, but rekordbox uses it as "unset" and shows such a
cue in the default colour, so it is reported as no colour rather than as
black. Memory cues in the reference export are exactly this case.
"""
try:
r, g, b = int(entry.color_red), int(entry.color_green), int(entry.color_blue)
except (AttributeError, TypeError, ValueError):
return None
if (r, g, b) == (0, 0, 0):
return None
return f"#{r:02X}{g:02X}{b:02X}"
def _to_cue(entry, *, with_color: bool) -> CuePoint | None:
"""One ANLZ cue entry as a generic `CuePoint`, or None if unreadable."""
try:
hot_cue = int(entry.hot_cue)
start_ms = int(entry.time)
except (AttributeError, TypeError, ValueError):
return None
loop_ms = getattr(entry, "loop_time", NO_LOOP)
try:
loop_ms = int(loop_ms)
except (TypeError, ValueError):
loop_ms = NO_LOOP
is_loop = _entry_kind(getattr(entry, "type", ENTRY_CUE)) == ENTRY_LOOP
length = 0.0
if is_loop and loop_ms != NO_LOOP and loop_ms > start_ms:
length = (loop_ms - start_ms) / 1000.0
# hot_cue 0 is the memory list; 1..N are the pads, dense and 1-based, so the
# generic 0-based slot is simply one less.
role = "memory" if hot_cue == MEMORY_SLOT else "hotcue"
slot = None if role == "memory" else hot_cue - 1
comment = getattr(entry, "comment", None)
return CuePoint(
name=(str(comment) or None) if comment else None,
type="loop" if length > 0 else "cue",
role=role,
start=start_ms / 1000.0,
length=length,
slot=slot,
color=_color(entry) if with_color else None,
# A OneLibrary drive is read-only in Konduktor, so no cue accepts a
# command. `capabilities.writable` is what the UI actually gates on;
# this keeps the per-cue answer consistent with it.
editable=False,
readonly_reason="platform_managed",
grid_marker=None,
)
def _entries(anlz, tag_type: str) -> list:
"""Every entry of every `tag_type` tag in one parsed ANLZ file.
A file carries the tag twice — once for hot cues and once for memory cues —
so both are collected and the entry's own `hot_cue` decides which it is.
That is more robust than trusting the container's type field, which is
absent on some tags in real files.
"""
out: list = []
for tag in getattr(anlz, "tags", []):
if tag.type != tag_type:
continue
content = getattr(tag.struct, "content", None)
out.extend(getattr(content, "entries", None) or [])
return out
def cues_from_anlz(dat, ext) -> list[CuePoint]:
"""The track's complete cue list, from its parsed `.DAT` and `.EXT`.
Either may be None — a drive can carry a `.DAT` with no `.EXT` — and a track
with no cues at all yields an empty list rather than an error.
"""
files = [f for f in (dat, ext) if f is not None]
if not files:
return []
# PCO2 first: it is the complete list and the only one with colour, comment
# and beat-denominated loops. It lives only in the .EXT.
pco2: list = []
for f in files:
pco2.extend(_entries(f, "PCO2"))
if pco2:
cues = [c for e in pco2 if (c := _to_cue(e, with_color=True)) is not None]
else:
# Fallback: merge PCOB across BOTH files. The .DAT holds pads 1-3 and the
# .EXT the rest, so either alone is an incomplete bank.
pcob: list = []
for f in files:
pcob.extend(_entries(f, "PCOB"))
cues = [c for e in pcob if (c := _to_cue(e, with_color=False)) is not None]
return _dedupe(cues)
def _dedupe(cues: list[CuePoint]) -> list[CuePoint]:
"""Collapse the same cue appearing in more than one tag or file.
Identity is (role, slot, start) rather than the whole cue: the same pad can
be described by both `PCOB` and `PCO2`, and by both files, and those copies
agree on position while differing in how much detail they carry. The first
one wins, which — given PCO2 is read first — is the richest.
Ordered by position, then by slot, so the projection is stable across reads
regardless of the order the tags happened to store.
"""
seen: set[tuple[str, int | None, int]] = set()
out: list[CuePoint] = []
for c in cues:
key = (c.role, c.slot, round(c.start * 1000))
if key in seen:
continue
seen.add(key)
out.append(c)
out.sort(key=lambda c: (c.start, c.slot if c.slot is not None else -1))
return out
@@ -0,0 +1,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
@@ -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."
)
@@ -0,0 +1,103 @@
"""Where things live on a OneLibrary drive.
A OneLibrary library is a **removable drive**, not a file, and that is the one
structural fact that separates this adapter from every other one. Everything the
library refers to — the audio, the analysis files, the artwork — is stored
DRIVE-RELATIVE (``/Contents/Loopmasters/Demo Track 1.mp3``), because the same
stick must resolve on a CDJ, on macOS and on Windows, where it is mounted at
three different places. Nothing inside the database is an absolute host path.
So resolving a stored path means joining it to the mount point, and that is what
this module exists to do. It is kept separate from the store because it is also
the knowledge a future *export* would need to lay a drive out from nothing.
Two layout details are measured from a real rekordbox 7 export rather than
assumed:
* the database is at ``PIONEER/rekordbox/exportLibrary.db``, alongside — not
instead of — the legacy ``export.pdb``. Both formats coexist on one drive,
and newer players prefer OneLibrary when they find it.
* analysis files sit under ``PIONEER/USBANLZ/P0<xx>/<8 hex>/ANLZ0000.*``,
where the two directory levels are a hash of the track's path. Konduktor
never has to compute that hash to READ, because ``content.analysisDataFilePath``
stores the resulting path outright — it would only matter for writing.
``.PIONEER`` is accepted as well as ``PIONEER``. Traktor's own OneLibrary writer
looks for both, so a drive written by it may use the dot-prefixed (hidden) form.
"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
# In preference order: a drive may legitimately carry either spelling, and the
# visible one is what rekordbox itself writes.
PIONEER_DIRS = ("PIONEER", ".PIONEER")
DB_SUBPATH = Path("rekordbox") / "exportLibrary.db"
# The analysis file the database points at is the `.DAT`; its siblings differ
# only by extension. `.EXT` carries the complete cue list and the colour
# waveforms, `.2EX` the newer high-resolution ones.
ANLZ_EXTENDED = ".EXT"
@dataclass(frozen=True)
class DriveLayout:
"""A located OneLibrary drive: its mount point and its database."""
root: Path
database: Path
@classmethod
def locate(cls, path: Path) -> "DriveLayout | None":
"""Find the layout for `path`, or None if it is not a OneLibrary drive.
Accepts either end of the drive deliberately: the MOUNT POINT, which is
what discovery finds and what a user picks in a file browser, or the
``exportLibrary.db`` ITSELF, which is what someone reaches by drilling
into the folder or by re-opening a remembered path. Both name the same
library, and refusing one of them would make the picker and the
last-opened shortcut disagree about what a valid library is.
"""
path = Path(path)
try:
if path.is_file():
# .../PIONEER/rekordbox/exportLibrary.db -> the drive is 3 up.
if path.name.lower() != "exportLibrary.db".lower():
return None
root = path.parent.parent.parent
if path.parent.parent.name not in PIONEER_DIRS:
return None
return cls(root=root, database=path)
if path.is_dir():
for pioneer in PIONEER_DIRS:
db = path / pioneer / DB_SUBPATH
if db.is_file():
return cls(root=path, database=db)
except OSError:
return None
return None
def resolve(self, drive_relative: str | None) -> Path | None:
"""A stored drive-relative path as a real path on this host.
Stored paths are POSIX-style and lead with a slash. That leading slash is
NOT a host root — treating it as one is the mistake this method exists to
prevent, since ``Path('/Volumes/X') / '/Contents/a.mp3'`` silently
discards the mount point and yields ``/Contents/a.mp3``.
"""
if not drive_relative:
return None
relative = str(drive_relative).replace("\\", "/").lstrip("/")
if not relative:
return None
return self.root / relative
def extended_anlz(self, dat_path: Path) -> Path:
"""The `.EXT` beside a given `.DAT`.
Cues are read from the `.EXT`, not the `.DAT` the database points at:
see `cues.py` for why that distinction is load-bearing rather than a
preference.
"""
return dat_path.with_suffix(ANLZ_EXTENDED)
@@ -0,0 +1,118 @@
"""OneLibrary rows -> the generic projection.
The only place a ``devicelib_plus`` ORM object becomes a generic `Track` /
`TrackCues`. Everything above this file sees generic types exclusively.
Field conventions are read off a real rekordbox 7 export rather than guessed:
* ``bpmx100`` is the tempo in hundredths, and it is a DISPLAY value — the real
grid is per-beat in the ANLZ file, and a variable-tempo track stores only its
first tempo here.
* ``rating`` is 0-5 directly, like `master.db` and unlike Traktor's /51.
* ``length`` is whole seconds.
* ``path`` is drive-relative with a leading slash; the store resolves it.
* dates arrive as `datetime` from the ORM, not as strings.
"""
from __future__ import annotations
from ...core.model import GridMarker, Track, TrackCues
from ..rekordbox.projection import parse_key
def _name_of(related) -> str | None:
"""A joined lookup row's display name, or None when unset."""
if related is None:
return None
value = getattr(related, "name", None)
return str(value) if value else None
def _iso_date(value) -> str | None:
"""`YYYY-MM-DD` from whatever the column holds.
The ORM converts the stored strings to `datetime`, so this takes the date
part of one — but a drive written by another vendor's software may well
store a plain string, and passing that through unchanged is better than
losing it.
"""
if not value:
return None
date = getattr(value, "date", None)
if callable(date):
try:
return date().isoformat()
except Exception: # noqa: BLE001
pass
text = str(value).strip()
return text.split(" ")[0] if text else None
def _bpm(row) -> float | None:
raw = getattr(row, "bpmx100", None)
if not raw:
return None
return round(int(raw) / 100.0, 2)
def to_track(row, drive_path: str | None = None) -> Track:
"""Project one ``Content`` row.
**The three count fields are approximations here**, and deliberately so. Cues
and the beatgrid both live in the track's ANLZ files, and parsing a track's
`.EXT` costs ~23 ms — ~23 s for a 1,000-track drive if done at open. So a
track that has an analysis file and a tempo is reported as having one grid
marker (constant tempo, true for all but a fraction of a percent of tracks)
and no cues, and all three are corrected the moment the track's cues are
actually read. `adapter.track_cues` is where that happens.
Reporting zero cues rather than a guess is the honest direction to be wrong
in: a count that appears from nowhere on selection reads as the detail
arriving, whereas one that shrinks reads as data being lost.
"""
key_name = _name_of(getattr(row, "key", None))
wheel, mode = parse_key(key_name)
has_analysis = bool(getattr(row, "analysisDataFilePath", None))
bpm = _bpm(row)
return Track(
id=str(getattr(row, "path", "") or ""),
artist=_name_of(getattr(row, "artist", None)),
title=getattr(row, "title", None),
album=_name_of(getattr(row, "album", None)),
genre=_name_of(getattr(row, "genre", None)),
label=_name_of(getattr(row, "label", None)),
remixer=_name_of(getattr(row, "remixer", None)),
# OneLibrary has `composer` and `lyricist`, neither of which is Traktor's
# "producer" or "mix", so nothing is mapped onto them approximately.
producer=None,
mix=None,
comment=getattr(row, "djComment", None),
bpm=bpm,
key=key_name,
key_wheel=wheel,
key_mode=mode,
rating=max(0, min(5, int(getattr(row, "rating", 0) or 0))),
playcount=getattr(row, "djPlayCount", None),
length=getattr(row, "length", None),
bitrate=getattr(row, "bitrate", None),
import_date=_iso_date(getattr(row, "dateAdded", None)),
last_played=None, # the drive records history as playlists, not per track
release_date=_iso_date(getattr(row, "releaseDate", None))
or (str(getattr(row, "releaseYear", "") or "") or None),
filepath=drive_path,
cue_count=0,
hotcue_count=0,
grid_marker_count=1 if (bpm and has_analysis) else 0,
grid_locked=False, # OneLibrary has no grid lock
media_kind="audio",
)
def to_track_cues(cues: list, grid_markers: list[GridMarker]) -> TrackCues:
"""Project a track's cues and beatgrid.
`cues` are already generic — see `store.cues` for why that boundary sits
where it does — so this is the assembly point rather than a translation.
Nothing here is editable: a OneLibrary drive is read-only in Konduktor, and
`capabilities.writable` says so at the library level.
"""
return TrackCues(grid_markers=grid_markers, grid_locked=False, cues=list(cues))
@@ -0,0 +1,248 @@
"""The retained native model for a OneLibrary drive.
Owns the open ``exportLibrary.db`` and the drive layout around it, and is the
only place a ``pyrekordbox.devicelib_plus`` row or an ANLZ tag is touched.
The database is SQLCipher-encrypted SQLite, like Rekordbox's ``master.db``, but
with a **different and universal key**: every OneLibrary drive from every vendor
is encrypted with the same one, which is what makes the format readable across
brands at all. `pyrekordbox` carries it, so nothing here needs to know it.
**Analysis files are parsed lazily, and that is a measurement, not a
preference.** The beatgrid and the cues both live in the per-track ANLZ files,
and parsing one costs ~2 ms for the `.DAT` but ~23 ms for the `.EXT`, which
carries the colour waveforms as well. Reading every track's `.EXT` at open would
cost ~23 s on a 1,000-track drive — so it happens on demand and is cached, the
same bargain the Rekordbox adapter strikes for its grids. The visible
consequence is that cue and marker counts are approximate in the library table
until a track's cues are actually read; see `projection.to_track`.
"""
from __future__ import annotations
import logging
from pathlib import Path
from ...core.adapter import LibraryNotSupported, NotFound
from ...core.model import CuePoint
from . import beatgrid, cues as cue_reader
from .layout import DriveLayout
log = logging.getLogger(__name__)
class OneLibraryStore:
def __init__(self, path: Path):
layout = DriveLayout.locate(Path(path))
if layout is None:
raise LibraryNotSupported(f"No OneLibrary database found at {path}")
self.layout = layout
self.path = layout.database
self._db = None
# Parsed ANLZ, keyed by track id. Two caches because the two files cost
# an order of magnitude apart: a grid read must not drag in the .EXT.
self._dat_cache: dict[str, object | None] = {}
self._ext_cache: dict[str, object | None] = {}
self._content_cache: list | None = None
self._by_id: dict[str, object] | None = None
self._load()
# ---- open / close ----------------------------------------------------
def _load(self) -> None:
try:
from pyrekordbox.devicelib_plus import DeviceLibraryPlus
except ImportError as ex: # pragma: no cover — dependency missing
raise LibraryNotSupported(
"Reading OneLibrary drives needs pyrekordbox with devicelib_plus"
) from ex
try:
self._db = DeviceLibraryPlus(str(self.path))
except Exception as ex: # noqa: BLE001 — surfaced as a clean 4xx
raise LibraryNotSupported(f"Could not open OneLibrary database: {ex}") from ex
self._dat_cache.clear()
self._ext_cache.clear()
self._content_cache = None
self._by_id = None
def close(self) -> None:
"""Release the database AND the underlying file handle.
Disposing the engine matters more here than anywhere else: the library
is on a REMOVABLE drive, and a lingering handle is what makes a stick
refuse to eject. `DeviceLibraryPlus.close()` only ends the session, so
the engine is disposed explicitly — the same gap the Rekordbox store
had to close for `master.db`.
"""
db, self._db = self._db, None
if db is None:
return
try:
db.close()
except Exception: # noqa: BLE001 — closing must not raise
log.debug("OneLibrary session close failed", exc_info=True)
engine = getattr(db, "engine", None)
if engine is not None:
try:
engine.dispose()
except Exception: # noqa: BLE001
log.debug("OneLibrary engine dispose failed", exc_info=True)
def _require_db(self):
if self._db is None:
raise LibraryNotSupported("The OneLibrary database is closed")
return self._db
# ---- identity --------------------------------------------------------
@property
def device_name(self) -> str | None:
"""The drive's own name, which is NOT the volume label.
Stored in `property.deviceName` and often blank — rekordbox leaves it
empty unless the user names the device — so the mount point's name is
the fallback a person will actually recognise.
"""
try:
row = self._require_db().get_property().first()
except Exception: # noqa: BLE001
return None
name = (getattr(row, "deviceName", "") or "").strip() if row is not None else ""
return name or self.layout.root.name or None
@property
def db_version(self) -> str | None:
try:
row = self._require_db().get_property().first()
except Exception: # noqa: BLE001
return None
value = getattr(row, "dbVersion", None) if row is not None else None
return str(value) if value else None
# ---- tracks ----------------------------------------------------------
def iter_content(self) -> list:
"""Every track row, cached for the life of the open library."""
if self._content_cache is None:
rows = list(self._require_db().get_content())
self._content_cache = rows
self._by_id = {self.track_id(r): r for r in rows}
return self._content_cache
@staticmethod
def track_id(row) -> str:
"""A track's stable id: its DRIVE-RELATIVE path.
Not `content_id`, which is a row number rekordbox reassigns from 1 every
time it rewrites the drive — so it would change under a user who merely
re-exported, breaking every playlist reference Konduktor had remembered.
The path is stable, unique on the drive, and is also the key a future
import would match against a Traktor collection, so it is the honest
identity here.
"""
return str(getattr(row, "path", "") or f"content:{getattr(row, 'content_id', '')}")
def content(self, track_id: str):
self.iter_content()
row = (self._by_id or {}).get(str(track_id))
if row is None:
raise NotFound(f"No track {track_id!r} on this OneLibrary drive")
return row
def audio_path(self, track_id: str) -> Path | None:
return self.layout.resolve(getattr(self.content(track_id), "path", None))
def all_audio_paths(self) -> list[str]:
out: list[str] = []
for row in self.iter_content():
resolved = self.layout.resolve(getattr(row, "path", None))
if resolved is not None:
out.append(str(resolved))
return out
# ---- analysis files --------------------------------------------------
def _anlz(self, track_id: str, *, extended: bool):
"""The parsed `.DAT` or `.EXT` for a track, or None if unreadable.
A missing or corrupt analysis file is a normal state on a real drive —
an unanalysed track has none — so it is cached as None and never raised.
"""
cache = self._ext_cache if extended else self._dat_cache
key = str(track_id)
if key in cache:
return cache[key]
cache[key] = None
row = self.content(track_id)
dat = self.layout.resolve(getattr(row, "analysisDataFilePath", None))
if dat is None:
return None
target = self.layout.extended_anlz(dat) if extended else dat
try:
if not target.is_file():
return None
from pyrekordbox.anlz import AnlzFile
cache[key] = AnlzFile.parse_file(str(target))
except Exception: # noqa: BLE001 — a bad file must not break browsing
log.debug("Could not parse ANLZ %s", target, exc_info=True)
return None
return cache[key]
def anlz_grid(self, track_id: str) -> tuple[list[float], list[float]] | None:
"""The per-beat ``(times, bpms)`` from the track's `PQTZ` tag.
`PQTZ` is in the `.DAT`, which is the cheap file — a grid read does not
pay for the `.EXT`'s waveforms.
"""
anlz = self._anlz(track_id, extended=False)
if anlz is None:
return None
return beatgrid.beats_from_pqtz(anlz)
def cues(self, track_id: str) -> list[CuePoint]:
"""The track's cues, already generic.
Unusually for a store, this returns generic types rather than native
rows: the native shape is a pair of parsed tag containers whose entries
only mean anything once merged across two files, and handing that to the
projection would put ANLZ knowledge on both sides of the boundary.
"""
return cue_reader.cues_from_anlz(
self._anlz(track_id, extended=False),
self._anlz(track_id, extended=True),
)
# ---- playlists -------------------------------------------------------
def playlists(self) -> list:
return list(self._require_db().get_playlist())
def count_playlists(self) -> int:
try:
return self._require_db().get_playlist().count()
except Exception: # noqa: BLE001
return 0
def playlist_song_ids(self, node_id: str) -> list[str]:
"""Track ids in a playlist, in the order the drive stores them.
`playlist_content` joins on `content_id`, but Konduktor's track id is the
path (see `track_id`), so the row numbers are translated here rather than
leaking a second notion of identity upward.
"""
try:
pid = int(node_id)
except (TypeError, ValueError):
return []
self.iter_content()
by_content_id = {
int(getattr(r, "content_id", -1)): self.track_id(r) for r in self.iter_content()
}
rows = [
r
for r in self._require_db().get_playlist_content()
if int(getattr(r, "playlist_id", -1)) == pid
]
rows.sort(key=lambda r: int(getattr(r, "sequenceNo", 0) or 0))
out: list[str] = []
for r in rows:
track_id = by_content_id.get(int(getattr(r, "content_id", -1)))
if track_id is not None:
out.append(track_id)
return out