mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-12-03 18:32:51 +01:00
Extended Rekordbox support
This commit is contained in:
1 parent
010f67cd2d
commit
43e712afbd
17 files changed
+837
-100
No files matched your search
@@ -5,14 +5,17 @@ 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.
|
||||
|
||||
**Read-only milestone.** Every mutating command raises `Unsupported`, and
|
||||
`capabilities()` reports nothing as editable, so a correct UI never offers one
|
||||
in the first place; the raise is the backstop, not the mechanism.
|
||||
**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 for a second, permanent reason on a cloud-synced library:
|
||||
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. That check lives here so it cannot be bypassed by a
|
||||
future command path forgetting it.
|
||||
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
|
||||
|
||||
@@ -48,6 +51,25 @@ class RekordboxAdapter:
|
||||
]
|
||||
)
|
||||
|
||||
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.
|
||||
"""
|
||||
counts = self._store.cue_counts()
|
||||
row = self._store.content(track_id)
|
||||
self._index.replace(projection.to_track(row, counts.get(str(row.ID), (0, 0))))
|
||||
|
||||
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:
|
||||
self._store._load()
|
||||
self._cloud_synced = self._store.cloud_synced
|
||||
@@ -55,7 +77,11 @@ class RekordboxAdapter:
|
||||
|
||||
# ---- identity --------------------------------------------------------
|
||||
def capabilities(self) -> Capabilities:
|
||||
return caps.capabilities_for(self.path, cloud_synced=self._cloud_synced)
|
||||
return caps.capabilities_for(
|
||||
self.path,
|
||||
cloud_synced=self._cloud_synced,
|
||||
editable_fields=sorted(RekordboxStore.EDITABLE_FIELDS),
|
||||
)
|
||||
|
||||
@property
|
||||
def cloud_synced(self) -> bool:
|
||||
@@ -107,6 +133,7 @@ class RekordboxAdapter:
|
||||
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] = {}
|
||||
@@ -122,10 +149,13 @@ class RekordboxAdapter:
|
||||
children=[],
|
||||
# A smart playlist has no static entry list; a folder has no tracks.
|
||||
selectable=kind == "playlist",
|
||||
can_add_tracks=False,
|
||||
can_reorder=False,
|
||||
can_rename=False,
|
||||
can_delete=False,
|
||||
# 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",
|
||||
)
|
||||
parent = str(r.ParentID or "root")
|
||||
@@ -184,13 +214,38 @@ class RekordboxAdapter:
|
||||
def remap_locations(self, mapping: PathMapping) -> int:
|
||||
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)
|
||||
|
||||
# ---- 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 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 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)
|
||||
|
||||
# ---- save -------------------------------------------------------------
|
||||
@property
|
||||
def dirty(self) -> bool:
|
||||
return False
|
||||
return self._store.dirty
|
||||
|
||||
def save(self):
|
||||
raise Unsupported(self._readonly_reason("Saving"))
|
||||
self._require_writable("Saving")
|
||||
return self._store.save()
|
||||
|
||||
def snapshot(self) -> bytes:
|
||||
"""The library's bytes, for version history.
|
||||
@@ -216,20 +271,11 @@ class RekordboxAdapter:
|
||||
def _refuse(self, what: str):
|
||||
raise Unsupported(self._readonly_reason(what))
|
||||
|
||||
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_track_metadata(self, track_id: str, fields: dict) -> Track | None:
|
||||
self._refuse("Editing track metadata")
|
||||
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 set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
|
||||
self._refuse("Editing cover art")
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
"""What a Rekordbox library can persist.
|
||||
|
||||
**Milestone 1 reports everything as read-only.** The spike verified that
|
||||
Rekordbox accepts writes that maintain its USN columns (see the handoff's
|
||||
Findings), but the write path is not built yet, and the capability system exists
|
||||
precisely so the UI never offers an edit that will not persist. Every flag here
|
||||
is therefore false/empty until milestone 2 turns them on one at a time.
|
||||
**Track metadata and playlists are writable; cues and the beatgrid are not.**
|
||||
The spike verified that Rekordbox accepts writes which maintain its USN columns
|
||||
(see the handoff's Findings), and those two write paths use `pyrekordbox`, which
|
||||
maintains them. Cues and the grid are separate hand-written stores and stay
|
||||
false until milestone 3 — the capability system exists precisely so the UI never
|
||||
offers an edit that will not persist.
|
||||
|
||||
A **cloud-synced** library reports `writable=False` regardless: Konduktor will
|
||||
not write one at all.
|
||||
|
||||
Two facts are already known and encoded, because getting them wrong later would
|
||||
be a silent data bug rather than a missing feature:
|
||||
@@ -35,7 +39,11 @@ HOTCUE_SLOTS = 8
|
||||
|
||||
|
||||
def capabilities_for(
|
||||
path, version: str | None = None, *, cloud_synced: bool = False
|
||||
path,
|
||||
version: str | None = None,
|
||||
*,
|
||||
cloud_synced: bool = False,
|
||||
editable_fields: list[str] | None = None,
|
||||
) -> Capabilities:
|
||||
# A cloud-synced library is refused PERMANENTLY, not pending a milestone:
|
||||
# a local edit the server did not issue could propagate a broken sync state
|
||||
@@ -43,9 +51,12 @@ def capabilities_for(
|
||||
return Capabilities(
|
||||
platform="rekordbox",
|
||||
version=version,
|
||||
writable=False,
|
||||
readonly_cause="cloud_synced" if cloud_synced else "platform_incomplete",
|
||||
writable=not cloud_synced,
|
||||
readonly_cause="cloud_synced" if cloud_synced else None,
|
||||
cues=CueCapabilities(
|
||||
# Milestone 3: the cue store is hand-written (djmdCue rows plus the
|
||||
# contentCue JSON mirror, kept consistent) and does not exist yet.
|
||||
editable=False,
|
||||
hotcue_slots=HOTCUE_SLOTS,
|
||||
slot_labels="letter",
|
||||
# Rekordbox is the only platform with memory cues, so they are
|
||||
@@ -61,12 +72,15 @@ def capabilities_for(
|
||||
grid=GridCapabilities(editable=False, flexible=True, lockable=False),
|
||||
tracks=TrackCapabilities(
|
||||
rating_max=5, # Rekordbox stores 0-5 directly, unlike Traktor's /51
|
||||
editable_fields=[], # read-only in this milestone
|
||||
# Narrower than Traktor's: `producer` and `mix` have no Rekordbox
|
||||
# column (its Composer is a different field), so they are absent
|
||||
# rather than mapped onto something approximate.
|
||||
editable_fields=sorted(editable_fields or []),
|
||||
media_kinds=["audio"],
|
||||
artwork=False,
|
||||
artwork_note=None,
|
||||
),
|
||||
playlists=PlaylistCapabilities(folders=True, smart="read_only", reorder=False),
|
||||
playlists=PlaylistCapabilities(folders=True, smart="read_only", reorder=True),
|
||||
save=SaveCapabilities(
|
||||
app_name="Rekordbox",
|
||||
library_label="master.db",
|
||||
|
||||
@@ -3,8 +3,16 @@
|
||||
This is the only module that knows ``pyrekordbox`` exists. It owns the decrypted
|
||||
SQLCipher session, the ANLZ analysis files, and the caches the projection reads.
|
||||
|
||||
**Read-only in this milestone.** The write path is deliberately absent rather
|
||||
than stubbed: a store that cannot write cannot half-write.
|
||||
**Writes cover track metadata and playlists.** Cues and the beatgrid are
|
||||
deliberately absent rather than stubbed — they are separate stores (two DB tables
|
||||
kept consistent, and the ANLZ analysis files) and a store that cannot write them
|
||||
cannot half-write them.
|
||||
|
||||
Edits accumulate in the SQLAlchemy session and are only made permanent by
|
||||
`save()`, which maps exactly onto Konduktor's "edit in memory, Save writes to
|
||||
disk" model. `pyrekordbox`'s `commit()` is what assigns Rekordbox's update
|
||||
sequence numbers, and a real Rekordbox was verified to accept and continue from
|
||||
the result — see the handoff's Findings.
|
||||
|
||||
Two things here are not obvious and are load-bearing:
|
||||
|
||||
@@ -24,7 +32,8 @@ from pathlib import Path
|
||||
from sqlalchemy import func, select, text
|
||||
from sqlalchemy.orm import joinedload
|
||||
|
||||
from ...core.adapter import LibraryNotSupported, NotFound
|
||||
from ...core.adapter import InvalidCommand, LibraryNotSupported, NotFound, SaveOutcome
|
||||
from ...core.edit_journal import EditJournal
|
||||
from ...core.pathmap import PathMapping
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
@@ -37,6 +46,7 @@ class RekordboxStore:
|
||||
self.path = Path(path)
|
||||
self._mapping = PathMapping()
|
||||
self._grid_cache: dict[str, tuple[list[float], list[float]] | None] = {}
|
||||
self._journal = EditJournal()
|
||||
self._load()
|
||||
|
||||
# ---- open ------------------------------------------------------------
|
||||
@@ -54,10 +64,22 @@ class RekordboxStore:
|
||||
self._by_id: dict[str, object] | None = None
|
||||
|
||||
def close(self) -> None:
|
||||
"""Release the session AND the pooled connection.
|
||||
|
||||
`pyrekordbox`'s own `close()` only closes the SQLAlchemy session, which
|
||||
returns the connection to the engine's pool — the OS file handle stays
|
||||
open. Disposing the engine is what actually releases `master.db`, and
|
||||
without it the file cannot be replaced (a restore, or a test copying a
|
||||
fresh library over it) on any platform that locks open files.
|
||||
"""
|
||||
try:
|
||||
self._db.close()
|
||||
except Exception: # noqa: BLE001 — closing must never raise
|
||||
pass
|
||||
try:
|
||||
self._db.engine.dispose()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
# ---- identity --------------------------------------------------------
|
||||
@property
|
||||
@@ -253,3 +275,165 @@ class RekordboxStore:
|
||||
return [
|
||||
str(c.FolderPath) for c in self.iter_content() if getattr(c, "FolderPath", None)
|
||||
]
|
||||
|
||||
# ---- writes: track metadata -----------------------------------------
|
||||
#
|
||||
# Deliberately NOT editable: the file path (it is the track's identity),
|
||||
# BPM and key (audio/grid territory), and Rekordbox's own read-only
|
||||
# bookkeeping. `producer` and `mix` are Traktor concepts with no Rekordbox
|
||||
# column — Rekordbox has a Composer, which is not the same field — so they
|
||||
# are simply absent from the set rather than mapped to something close.
|
||||
_DIRECT_FIELDS = {
|
||||
"title": "Title",
|
||||
"comment": "Commnt",
|
||||
"release_date": "ReleaseDate",
|
||||
}
|
||||
# Fields stored as a foreign key into a lookup table, which must be
|
||||
# found-or-created: `add_*` in pyrekordbox RAISES on an existing name.
|
||||
_LOOKUP_FIELDS = {
|
||||
"artist": ("DjmdArtist", "ArtistID", "add_artist"),
|
||||
"album": ("DjmdAlbum", "AlbumID", "add_album"),
|
||||
"genre": ("DjmdGenre", "GenreID", "add_genre"),
|
||||
"label": ("DjmdLabel", "LabelID", "add_label"),
|
||||
# A remixer IS an artist in Rekordbox — same table, different column.
|
||||
"remixer": ("DjmdArtist", "RemixerID", "add_artist"),
|
||||
}
|
||||
EDITABLE_FIELDS = set(_DIRECT_FIELDS) | set(_LOOKUP_FIELDS) | {"rating"}
|
||||
|
||||
def _lookup_id(self, table_name: str, adder: str, name: str) -> str | None:
|
||||
"""The id of the lookup row called `name`, creating it if needed."""
|
||||
if not name:
|
||||
return None
|
||||
table = getattr(self._tables, table_name)
|
||||
existing = self._db.session.query(table).filter_by(Name=name).first()
|
||||
if existing is not None:
|
||||
return str(existing.ID)
|
||||
row = getattr(self._db, adder)(name)
|
||||
return str(row.ID)
|
||||
|
||||
def set_track_metadata(self, track_id: str, fields: dict) -> None:
|
||||
row = self.content(track_id)
|
||||
for key, value in fields.items():
|
||||
if key not in self.EDITABLE_FIELDS:
|
||||
continue # unknown/!safe fields are ignored, never guessed at
|
||||
if key == "rating":
|
||||
try:
|
||||
stars = int(value or 0)
|
||||
except (TypeError, ValueError):
|
||||
raise InvalidCommand(f"Rating must be a number, got {value!r}") from None
|
||||
if not 0 <= stars <= 5:
|
||||
raise InvalidCommand(f"Rating must be 0-5, got {stars}")
|
||||
before, new = row.Rating, stars
|
||||
row.Rating = stars
|
||||
elif key in self._DIRECT_FIELDS:
|
||||
column = self._DIRECT_FIELDS[key]
|
||||
before = getattr(row, column)
|
||||
new = (value or None) if isinstance(value, str) else value
|
||||
setattr(row, column, new)
|
||||
else:
|
||||
table_name, column, adder = self._LOOKUP_FIELDS[key]
|
||||
before = getattr(row, column)
|
||||
new = self._lookup_id(table_name, adder, (value or "").strip())
|
||||
setattr(row, column, new)
|
||||
self._journal.record("track", "set", track_id, key, before, new)
|
||||
# Artist/album/genre/label are FOREIGN KEYS. Setting the id does not move
|
||||
# the ORM's cached relationship, so re-projecting the row immediately
|
||||
# would read the OLD name back and report a successful edit as a no-op.
|
||||
# Flush pushes the ids into the transaction; expiring the row makes the
|
||||
# next attribute access reload the joined rows with them.
|
||||
self._db.flush()
|
||||
self._db.session.expire(row)
|
||||
|
||||
# ---- writes: playlists ------------------------------------------------
|
||||
def _playlist(self, node_id: str):
|
||||
t = self._tables
|
||||
row = (
|
||||
self._db.session.query(t.DjmdPlaylist)
|
||||
.filter(t.DjmdPlaylist.ID == str(node_id))
|
||||
.first()
|
||||
)
|
||||
if row is None:
|
||||
raise NotFound(f"No playlist {node_id!r}")
|
||||
return row
|
||||
|
||||
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
|
||||
name = (name or "").strip()
|
||||
if not name:
|
||||
raise InvalidCommand("A playlist needs a name")
|
||||
parent = self._playlist(parent_id) if parent_id else None
|
||||
if parent is not None and int(parent.Attribute or 0) != int(
|
||||
self._tables.PlaylistType.FOLDER
|
||||
):
|
||||
raise InvalidCommand("A playlist can only be created inside a folder")
|
||||
row = self._db.create_playlist(name, parent=parent)
|
||||
self._journal.record("playlist", "create", name)
|
||||
return str(row.ID)
|
||||
|
||||
def rename_playlist(self, node_id: str, name: str) -> None:
|
||||
name = (name or "").strip()
|
||||
if not name:
|
||||
raise InvalidCommand("A playlist needs a name")
|
||||
row = self._playlist(node_id)
|
||||
self._db.rename_playlist(row, name)
|
||||
self._journal.record("playlist", "rename", name)
|
||||
|
||||
def delete_playlist(self, node_id: str) -> None:
|
||||
row = self._playlist(node_id)
|
||||
name = row.Name
|
||||
self._db.delete_playlist(row)
|
||||
self._journal.record("playlist", "delete", name)
|
||||
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
|
||||
"""Replace a playlist's contents, in the given order.
|
||||
|
||||
Rekordbox keys order by `DjmdSongPlaylist.TrackNo`, and there is no
|
||||
bulk reorder — so this clears the list and re-adds it. `add_to_playlist`
|
||||
is used one row at a time because it is what maintains Rekordbox's own
|
||||
USN ordering for these rows.
|
||||
"""
|
||||
t = self._tables
|
||||
playlist = self._playlist(node_id)
|
||||
if int(playlist.Attribute or 0) != int(t.PlaylistType.PLAYLIST):
|
||||
raise InvalidCommand("Only a plain playlist has an editable track list")
|
||||
known = {tid for tid in track_ids if self._by_id and str(tid) in self._by_id}
|
||||
unknown = [tid for tid in track_ids if tid not in known]
|
||||
if unknown:
|
||||
raise NotFound(f"Unknown track(s): {', '.join(map(str, unknown[:3]))}")
|
||||
existing = (
|
||||
self._db.session.query(t.DjmdSongPlaylist)
|
||||
.filter(t.DjmdSongPlaylist.PlaylistID == str(node_id))
|
||||
.all()
|
||||
)
|
||||
for song in existing:
|
||||
self._db.remove_from_playlist(playlist, song)
|
||||
for n, track_id in enumerate(track_ids, start=1):
|
||||
self._db.add_to_playlist(playlist, str(track_id), track_no=n)
|
||||
self._journal.record("playlist", "entries", playlist.Name, after=len(track_ids))
|
||||
return len(track_ids)
|
||||
|
||||
# ---- save --------------------------------------------------------------
|
||||
@property
|
||||
def dirty(self) -> bool:
|
||||
return self._journal.dirty
|
||||
|
||||
def edited_fields(self, track_id: str) -> set[str]:
|
||||
return self._journal.fields_for(track_id)
|
||||
|
||||
def save(self) -> SaveOutcome:
|
||||
"""Make the session's edits permanent.
|
||||
|
||||
`commit(autoinc=True)` is what assigns Rekordbox's update sequence
|
||||
numbers — one increment per change, stamped onto each changed row. A real
|
||||
Rekordbox was verified to accept a library written this way and to carry
|
||||
on from the counter it was left at.
|
||||
|
||||
`snapshot` is None: a Rekordbox library is `master.db` plus its analysis
|
||||
files plus a playlist XML, so there is no single blob to version, and
|
||||
`capabilities.save.history` says so.
|
||||
"""
|
||||
summary = self._journal.summary()
|
||||
self._db.commit(autoinc=True)
|
||||
self._journal.clear()
|
||||
# Reads go through the same session, so nothing needs re-projecting from
|
||||
# scratch — but the grid cache is keyed by track and survives a save.
|
||||
return SaveOutcome(summary=summary, snapshot=None, tag_results=[])
|
||||
Reference in new issue
Block a user