Files
konduktor/backend/konduktor/adapters/rekordbox/adapter.py
T

614 lines
26 KiB
Python

"""The Rekordbox adapter: owns the native database and the generic projection.
Mirrors `adapters.traktor.adapter`. It holds:
* a ``RekordboxStore`` — the retained NATIVE model (the open ``master.db``),
* a ``TrackIndex`` — the generic READ projection built from it.
**Track metadata and playlists are writable; cues and the beatgrid are not
yet.** Those two are separate native stores (two DB tables kept consistent, and
the per-track ANLZ analysis files), so they keep refusing until milestone 3 —
and `capabilities.cues.editable` / `grid.editable` say so, which is what the UI
actually gates on. The raise is the backstop, not the mechanism.
Writes are refused entirely, and permanently, on a **cloud-synced** library:
propagating a bad sync state to the user's other machines is not something
version history can undo — especially here, where there is no version history at
all. That check lives at the top of every command path so no future command can
forget it.
"""
from __future__ import annotations
from pathlib import Path
from ...core.adapter import InvalidCommand, Unsupported, local_audio_facts
from ...core.capabilities import Capabilities
from ...core.model import GridMarker, PlaylistNode, Track, TrackCues
from ...core.pathmap import PathMapping, common_dir_prefix
from ...core.query import TrackIndex
from . import capabilities as caps
from . import memory_palette, palette, projection, timebase
from ...core import add_analysis
from .store import RekordboxStore
class RekordboxAdapter:
platform = "rekordbox"
def __init__(self, path: Path):
self.path = Path(path)
self._store = RekordboxStore(self.path)
self._index = TrackIndex()
self._cloud_synced = self._store.cloud_synced
self._rebuild()
# ---- projection maintenance -----------------------------------------
def _rebuild(self) -> None:
kinds = self._store.cue_kinds()
self._index.rebuild(
[
projection.to_track(row, kinds.get(str(row.ID), ()),
stem=self._store.is_stem(str(row.ID)))
for row in self._store.iter_content()
]
)
def _refresh_cues(self, track_id: str) -> TrackCues:
"""Re-project a track AND return its fresh cues.
Every mutating cue/grid command ends here: the contract is that a command
returns the refreshed projection, so a route can never serve a stale one.
"""
self._refresh(track_id)
return self.track_cues(track_id) or TrackCues()
def _refresh(self, track_id: str) -> None:
"""Re-project one track after a command, so the UI cannot go stale.
Every mutating command must end in this — a forgotten refresh is a
silently stale projection that no byte- or row-level test would catch.
"""
kinds = self._store.cue_kinds()
row = self._store.content(track_id)
self._index.replace(projection.to_track(row, kinds.get(str(row.ID), ()),
stem=self._store.is_stem(str(row.ID))))
def close(self) -> None:
"""Release the database connection.
Rekordbox's library is a live SQLite file, not a document parsed into
memory: leaving the connection open keeps a file handle (and possibly a
`-wal`) around, so an adapter that is being replaced must be closed.
"""
self._store.close()
def reload(self) -> None:
"""Re-read the library from disk, DISCARDING unsaved edits (see
`RekordboxStore.discard` for why a plain re-open is not enough)."""
self._store.discard()
self._cloud_synced = self._store.cloud_synced
self._rebuild()
# ---- identity --------------------------------------------------------
def capabilities(self) -> Capabilities:
return caps.capabilities_for(
self.path,
cloud_synced=self._cloud_synced,
editable_fields=sorted(RekordboxStore.EDITABLE_FIELDS),
)
@property
def cloud_synced(self) -> bool:
return self._cloud_synced
# ---- read ------------------------------------------------------------
@property
def tracks(self) -> list[Track]:
return self._index.tracks
@property
def by_key(self) -> dict[str, Track]:
return self._index.by_key
def track(self, track_id: str) -> Track | None:
return self._index.get(track_id)
def query_tracks(self, **kw):
return self._index.query_tracks(**kw)
def facets(self):
return self._index.facets()
def stats(self, playlist_count: int):
return self._index.stats(playlist_count)
def playlist_count(self) -> int:
return self._store.count_playlists()
def track_cues(self, track_id: str) -> TrackCues | None:
if self._index.get(track_id) is None:
return None
cues = projection.to_track_cues(
self._store.cues(track_id), self._store.anlz_grid(track_id),
self._store.time_offset(track_id),
)
# The track projection carries an APPROXIMATE grid_marker_count until the
# grid is actually read (see projection.to_track). This is that moment —
# correct it, so the library table stops showing the guess.
track = self._index.get(track_id)
if track is not None:
track.grid_marker_count = len(cues.grid_markers)
return cues
# ---- playlists -------------------------------------------------------
def playlist_tree(self) -> list[PlaylistNode]:
"""Rekordbox stores the tree as a flat table with ``ParentID`` links."""
from pyrekordbox.masterdb import models as tables
rows = self._store.playlists()
folder = int(tables.PlaylistType.FOLDER)
smart = int(tables.PlaylistType.SMART_PLAYLIST)
writable = not self._cloud_synced
nodes: dict[str, PlaylistNode] = {}
parents: dict[str, str] = {}
for r in rows:
attribute = int(r.Attribute or 0)
kind = "folder" if attribute == folder else ("smart" if attribute == smart else "playlist")
node_id = str(r.ID)
nodes[node_id] = PlaylistNode(
id=node_id,
name=r.Name or "",
kind=kind,
count=(0 if kind == "folder" else len(self._store.playlist_song_ids(node_id))),
children=[],
# A smart playlist has no static entry list; a folder has no tracks.
selectable=kind == "playlist",
# Rekordbox's own working lists are filtered out by the store, so
# everything reaching here is the user's and may be edited — as
# long as the library itself is writable at all.
can_add_tracks=writable and kind == "playlist",
can_reorder=writable and kind == "playlist",
can_rename=writable,
can_delete=writable,
can_contain_children=kind == "folder",
can_move=writable,
)
parent = str(r.ParentID or "root")
parents[node_id] = "root" if parent in ("0", "", "root", "None") else parent
roots: list[PlaylistNode] = []
for node_id, node in nodes.items():
parent_id = parents.get(node_id, "root")
parent = nodes.get(parent_id)
if parent is None:
roots.append(node)
else:
parent.children.append(node)
return roots
def playlist_entries(self, node_id: str) -> list[str] | None:
ids = self._store.playlist_song_ids(node_id)
return ids if ids or self._is_playlist(node_id) else None
def playlist_tracks(self, node_id: str) -> list[Track] | None:
keys = self.playlist_entries(node_id)
if keys is None:
return None
return [t for k in keys if (t := self._index.get(k)) is not None]
def _is_playlist(self, node_id: str) -> bool:
return any(str(r.ID) == str(node_id) for r in self._store.playlists())
# ---- audio / paths ----------------------------------------------------
def audio_path(self, track_id: str):
return self._store.audio_path(track_id)
def audio_facts(self, track_ids: list[str]):
return local_audio_facts(self, track_ids)
def set_path_mapping(self, mapping: PathMapping) -> None:
self._store.set_path_mapping(mapping)
# The FILE decides a track's media kind, and the mapping moves files.
self._rebuild()
def unresolved_path_groups(self) -> list:
"""Not checked yet: the open-time missing-files check is Traktor-only
for now. Rekordbox's `FolderPath` is absolute too, so it will qualify."""
return []
def set_session_mappings(self, mappings: list[PathMapping]) -> None:
return None
def set_write_stored_paths(self, enabled: bool) -> None:
"""OPTIONAL: see `TraktorAdapter.set_write_stored_paths`."""
self._store.set_write_stored_paths(enabled)
def path_prefix_suggestions(self) -> dict:
paths = self._store.all_audio_paths()
primary = common_dir_prefix(paths)
return {"primary": primary, "groups": [{"prefix": primary, "count": len(paths)}] if primary else []}
def remap_preview(self, mapping: PathMapping) -> dict:
paths = [Path(p) for p in self._store.all_audio_paths()]
matched = [p for p in paths if mapping.matches(p)]
samples = []
for p in matched[:5]:
target = mapping.apply(p)
samples.append({"from": str(p), "to": str(target), "exists": target.exists()})
existing = sum(1 for p in matched if mapping.apply(p).exists())
return {
"total": len(paths),
"matched": len(matched),
"existing": existing,
"samples": samples,
}
def remap_locations(self, mapping: PathMapping) -> dict[str, str]:
raise Unsupported(self._readonly_reason("Rewriting stored paths"))
# ---- commands: track metadata ----------------------------------------
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None:
self._require_writable("Editing track metadata")
self._store.set_track_metadata(track_id, fields)
self._refresh(track_id)
return self._index.get(track_id)
def set_key(self, track_id: str, wheel: int, mode: str) -> Track | None:
self._require_writable("Setting the key")
self._store.set_key(track_id, wheel, mode)
self._refresh(track_id)
return self._index.get(track_id)
def set_track_color(self, track_id: str, color: str | None) -> Track | None:
self._require_writable("Setting the track colour")
self._store.set_track_color(track_id, color)
self._refresh(track_id)
return self._index.get(track_id)
# ---- commands: playlists ----------------------------------------------
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
self._require_writable("Creating playlists")
return self._store.create_playlist(name, parent_id)
def create_folder(self, name: str, parent_id: str | None = None) -> str:
self._require_writable("Creating playlist folders")
return self._store.create_folder(name, parent_id)
def rename_playlist(self, node_id: str, name: str) -> None:
self._require_writable("Renaming playlists")
self._store.rename_playlist(node_id, name)
def delete_playlist(self, node_id: str) -> None:
self._require_writable("Deleting playlists")
self._store.delete_playlist(node_id)
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
self._require_writable("Moving playlists")
return self._store.move_playlist(node_id, parent_id, index)
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
self._require_writable("Editing playlists")
return self._store.set_playlist_entries(node_id, track_ids)
# ---- commands: cues ---------------------------------------------------
def _check_cue_type(self, cue_type: str) -> None:
if cue_type not in caps.WRITABLE_CUE_TYPES:
raise Unsupported(f"Rekordbox has no cue type {cue_type!r}")
def set_cue(
self,
track_id: str,
*,
slot: int,
start_sec: float,
cue_type: str,
length_sec: float = 0.0,
role: str = "hotcue",
name: str | None = None,
) -> TrackCues:
self._require_writable("Editing cues")
if role != "hotcue":
# A memory cue has no slot to set; it has its own commands.
raise InvalidCommand("Memory cues are added with add_memory_cue, not set_cue")
self._check_cue_type(cue_type)
self._store.set_cue(
track_id, slot=slot, start_sec=start_sec, cue_type=cue_type,
length_sec=length_sec, name=name,
)
return self._refresh_cues(track_id)
def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> TrackCues:
self._require_writable("Editing cues")
self._check_cue_type(cue_type)
self._store.set_cue_type(track_id, slot, cue_type)
return self._refresh_cues(track_id)
def set_cue_color(self, track_id: str, slot: int, color: str | None) -> TrackCues:
self._require_writable("Editing cues")
code = None
if color is not None:
code = palette.swatch_code(color)
if code is None:
raise InvalidCommand(
f"{color!r} is not one of Rekordbox's hot cue colours"
)
self._store.set_cue_color(track_id, slot, code)
return self._refresh_cues(track_id)
def delete_cue(self, track_id: str, slot: int) -> TrackCues:
self._require_writable("Deleting cues")
self._store.delete_cue(track_id, slot)
return self._refresh_cues(track_id)
# ---- commands: memory cues --------------------------------------------
def _memory_code(self, color: str | None) -> int | None:
if color is None:
return None
code = memory_palette.code_for(color)
if code is None:
raise InvalidCommand(f"{color!r} is not one of rekordbox's memory cue colours")
return code
def add_memory_cue(
self,
track_id: str,
*,
start_sec: float,
cue_type: str,
length_sec: float = 0.0,
name: str | None = None,
color: str | None = None,
) -> TrackCues:
self._require_writable("Editing cues")
self._check_cue_type(cue_type)
self._store.add_memory_cue(
track_id, start_sec=start_sec, cue_type=cue_type, length_sec=length_sec,
name=name, color_code=self._memory_code(color),
)
return self._refresh_cues(track_id)
def rename_memory_cue(self, track_id: str, cue_id: str, name: str | None) -> TrackCues:
self._require_writable("Editing cues")
self._store.rename_memory_cue(track_id, cue_id, name)
return self._refresh_cues(track_id)
def set_memory_cue_type(self, track_id: str, cue_id: str, cue_type: str) -> TrackCues:
# rekordbox has one point type, so there is nothing to choose; a memory
# cue is a cue or a loop by its length.
raise Unsupported("rekordbox memory cues have no type to change")
def set_memory_cue_color(self, track_id: str, cue_id: str, color: str | None) -> TrackCues:
self._require_writable("Editing cues")
self._store.set_memory_cue_color(track_id, cue_id, self._memory_code(color))
return self._refresh_cues(track_id)
def delete_memory_cue(self, track_id: str, cue_id: str) -> TrackCues:
self._require_writable("Deleting cues")
self._store.delete_memory_cue(track_id, cue_id)
return self._refresh_cues(track_id)
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues:
self._require_writable("Placing cues")
for cue in cues:
self._check_cue_type(getattr(cue, "type", "cue"))
self._store.place_cues(track_id, cues, overwrite=overwrite)
return self._refresh_cues(track_id)
# ---- commands: beatgrid -----------------------------------------------
def _markers_from(self, markers: list) -> list:
"""Accept either GridMarkers or the (start, bpm) tuples routes send."""
out = []
for m in markers:
if isinstance(m, GridMarker):
out.append(m)
else:
start, bpm = m
out.append(GridMarker(start=float(start), bpm=float(bpm)))
return out
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> TrackCues:
self._require_writable("Editing the beatgrid")
self._store.add_grid_marker(track_id, start_sec, bpm)
return self._refresh_cues(track_id)
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> TrackCues:
self._require_writable("Editing the beatgrid")
self._store.move_grid_marker(track_id, index, start_sec)
return self._refresh_cues(track_id)
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> TrackCues:
self._require_writable("Editing the beatgrid")
self._store.set_grid_marker_bpm(track_id, index, bpm)
return self._refresh_cues(track_id)
def delete_grid_marker(self, track_id: str, index: int) -> TrackCues:
self._require_writable("Editing the beatgrid")
self._store.delete_grid_marker(track_id, index)
return self._refresh_cues(track_id)
def replace_grid(self, track_id: str, markers: list) -> TrackCues:
self._require_writable("Editing the beatgrid")
self._store.replace_grid(track_id, self._markers_from(markers))
return self._refresh_cues(track_id)
def set_analysed_grid(self, track_id: str, markers: list) -> TrackCues:
"""Write an analysis result the way Rekordbox's own analyser would.
Rekordbox pairs nothing with a grid marker — the companion cue is a
Traktor convention — so this is just a replace.
"""
return self.replace_grid(track_id, markers)
def delete_grid(self, track_id: str) -> TrackCues:
self._require_writable("Deleting the beatgrid")
self._store.delete_grid(track_id)
return self._refresh_cues(track_id)
# ---- save -------------------------------------------------------------
@property
def dirty(self) -> bool:
return self._store.dirty
def edit_summary(self) -> str:
"""OPTIONAL: this session's unsaved edits in one line ("edited 3
tracks; added 6 hotcues") — what a server tells the next computer to
open the library about the edits it is inheriting."""
return self._store._journal.summary()
def save(self):
self._require_writable("Saving")
return self._store.save()
def snapshot(self) -> bytes:
"""The library's bytes, for version history.
`master.db` alone is NOT a complete snapshot of a Rekordbox library (the
beatgrids live in separate ANLZ files, and restoring the database
wholesale would also roll back Rekordbox's own auth and sampler state),
which is why `capabilities.save.history` is False. Nothing should be
calling this.
"""
raise Unsupported("Rekordbox libraries are not versioned by Konduktor")
# ---- commands: all refused in this milestone -------------------------
def _readonly_reason(self, what: str) -> str:
if self._cloud_synced:
return (
f"{what} is not possible: this Rekordbox library is synced with "
"Rekordbox Cloud, and Konduktor will not write to a cloud-synced "
"library."
)
return f"{what} is not supported yet for Rekordbox libraries."
def _refuse(self, what: str):
raise Unsupported(self._readonly_reason(what))
def _require_writable(self, what: str) -> None:
"""Every write passes through here, so the cloud-sync refusal cannot be
forgotten by a command added later."""
if self._cloud_synced:
raise Unsupported(self._readonly_reason(what))
def analysis_lead(self, audio: Path) -> float:
"""The time-base lead `add_tracks` measures a file's waveform with —
rekordbox's clock against the decoded audio, read from the file's
header (`timebase.py`). OPTIONAL on the protocol: a platform that does
not analyse what it adds has none, and whoever prepares an analysis
for this one (a client of a server-held library) asks for it."""
return timebase.offset(Path(audio))
def add_tracks(self, items: list, *, checkpoint=None) -> list[str]:
"""Add tracks that came from somewhere else, with their prep.
Rekordbox keeps the beatgrid AND the waveforms in per-track analysis
files, and shows neither grid nor cues for a track without them — so
unlike Traktor, which re-analyses on load, every file is decoded here.
A file that brings no grid gets one from Konduktor's own detector
(decided 2026-10-01: a track should arrive ready to prep).
Two phases, and the split is the point. FIRST every file is decoded and
analysed, which is slow and may be cancelled through `checkpoint` —
before the library is touched, so a cancel leaves it as it was. THEN
each row is added and its grid and cues replayed through the ordinary
store commands (`replace_grid`, `set_cue`), so an added track inherits
their conventions and tests rather than growing a second copy.
Nothing is lost on the way in: Rekordbox has memory cues and coloured
cues, so both cross as themselves. A hot cue whose pad is out of the
bank or already taken becomes a memory cue at the same position rather
than being dropped.
"""
from ...core import audio_tags
self._require_writable("Adding tracks")
held = set(self._store.all_audio_paths())
prepared = []
total = len(items)
for n, item in enumerate(items, start=1):
audio = Path(item.audio_path)
if checkpoint is not None:
checkpoint(f"Analysing {item.track.title or audio.name} ({n}/{total})",
step=n, of=total)
if not audio.is_file():
raise InvalidCommand(f"No audio file at {audio}")
if str(audio) in held:
raise InvalidCommand(f"The library already holds {audio}")
held.add(str(audio))
markers = list(item.cues.grid_markers) if item.cues else []
if item.analysis is not None:
# Measured by whoever added it — a library held by a server is
# never asked to decode audio (see `PreparedAnalysis`).
analysed = item.analysis
if not markers:
markers = list(analysed.markers)
else:
analysed = add_analysis.prepare(audio, lead=self.analysis_lead(audio),
detect=not markers,
detect_key=item.track.key_wheel is None)
markers = markers or list(analysed.markers)
measured = analysed.measured
# A file with no key of its own gets one, as it gets a grid
# (decided: arrive ready to prep). Rekordbox's own add analyses one.
track = add_analysis.with_key(item.track, analysed.key)
art = item.art or audio_tags.read_cover(audio)
prepared.append((item, track, audio, measured, markers, art[0] if art else None))
added: list[str] = []
for item, track, audio, measured, markers, art in prepared:
track_id = self._store.add_track(
audio, track, measured=measured, with_grid=bool(markers), art=art)
self._index.add(projection.to_track(self._store.content(track_id), (),
stem=self._store.is_stem(track_id)))
if markers:
self._store.replace_grid(track_id, markers)
if item.cues is not None:
self._place_imported_cues(track_id, item.cues)
self._refresh(track_id)
added.append(track_id)
return added
def _place_imported_cues(self, track_id: str, cues) -> None:
"""Hot cues on their own pads; memory cues — and a hot cue with no
free pad — as memory cues, up to rekordbox's 10 (earliest first; the
rest are dropped, per the lossiness rule). Colour as the nearest swatch
of the palette the cue lands in: a hot cue's 16, a memory cue's 8."""
taken: set[int] = set()
memory = 0
for cue in sorted(cues.cues or [], key=lambda c: c.start):
cue_type = "loop" if getattr(cue, "length", 0) else "cue"
common = dict(start_sec=cue.start, cue_type=cue_type,
length_sec=getattr(cue, "length", 0.0) or 0.0,
name=getattr(cue, "name", None))
slot = cue.slot if cue.role == "hotcue" else None
if slot is not None and 0 <= slot < caps.HOTCUE_SLOTS and slot not in taken:
code, _rgb = palette.code_for(cue.color)
self._store.set_cue(track_id, slot=slot, color_code=code or None, **common)
taken.add(slot)
elif memory < self._store.MAX_MEMORY_CUES:
self._store.add_memory_cue(
track_id, color_code=memory_palette.nearest_code(cue.color), **common)
memory += 1
def remove_tracks(self, track_ids: list[str]) -> int:
# What goes with a track was measured in Rekordbox 7 — see the store.
self._require_writable("Removing tracks")
n = self._store.remove_tracks(track_ids)
if n:
self._rebuild()
return n
def apply_stem_swaps(self, swaps, *, add_to_playlist=None):
# Rekordbox does not play native-instruments stem files as stems.
self._refuse("Converting tracks to stems")
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
self._refuse("Editing cover art")
def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
return self._store.cover_art(track_id)
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues:
# Rekordbox has no per-track grid lock; capabilities.grid.lockable says so.
raise Unsupported("Rekordbox has no beatgrid lock")