mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 18:22:53 +01:00
Begun implementing OneLibrary editing
This commit is contained in:
1 parent
2784879872
commit
775e94168c
28 files changed
+1390
-150
No files matched your search
@@ -295,9 +295,23 @@ 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.
|
||||
- `adapters/onelibrary/` — **editable when opened as THE library; read-only
|
||||
when browsed from the sidebar's Devices** (`read_only=True`, cause `browsing`).
|
||||
The cross-vendor USB export format (AlphaTheta + Algoriddim + Native
|
||||
Instruments), read by CDJ-class hardware. Editing is landing in steps toward
|
||||
parity with the Rekordbox adapter — track metadata and playlists done; cues,
|
||||
grid, adding/removing tracks and the `export.pdb` rebuild next — decided in
|
||||
[the editing discussion](.claude/discussions/discuss-onelibrary-editing-2026-10-01.md),
|
||||
which also holds what rekordbox 7 was MEASURED writing when it edits a stick
|
||||
(no update counter moves, the `cue` table stays empty, a new playlist goes on
|
||||
top). **The store never opens the database ON the drive**: it works on a copy
|
||||
in app-data and Save writes it back whole — fingerprint check (refuses if
|
||||
another app wrote the stick since open), backup to app-data, temp file beside
|
||||
the database, stale `-wal`/`-shm` deleted, rename — then writes edited text
|
||||
fields into the audio files' tags as rekordbox does (not the rating). Cue tags
|
||||
are read by Konduktor's own `rekordbox/anlz_file.py`, NOT pyrekordbox: rekordbox
|
||||
writes COMPACT cue entries when it edits (48 / 44 bytes, export: 88), and
|
||||
pyrekordbox's parser raised on the 44-byte one and lost the whole `.EXT`.
|
||||
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:
|
||||
@@ -901,6 +915,17 @@ serialization path.** It enforces:
|
||||
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.
|
||||
Also reads `fixtures/onelibrary/rekordbox-edited/` (a stick after rekordbox
|
||||
itself edited it: compact cue entries) and pins browsing vs editable mode. It
|
||||
opens a temp COPY of the fixture — a stray save once rewrote the checked-in one.
|
||||
- `test_onelibrary_fidelity.py` — the row-level diff for OneLibrary writes, on a
|
||||
temp copy of the fixture: nothing reaches the drive before Save, a no-op save
|
||||
changes zero rows, a title edit exactly `content.title` (no counter, as
|
||||
rekordbox), dates as `YYYY-MM-DD` text, lookups found-or-created with
|
||||
`nameForSearch` NULL, a new playlist on top with siblings shifted, entries
|
||||
from 1; and the stick hazards — another app's write refused, an unplugged
|
||||
drive keeps the edits, stale `-shm` deleted, the backup holds the old rows,
|
||||
the drive never held open, file tags written (title yes, rating no).
|
||||
- `test_import.py` — the import feature end to end: a drive's tracks into a temp
|
||||
copy of the real collection. Asserts the prep survives (hot cues keep their
|
||||
PAD, memory cues fill spare ones, the flexible grid crosses intact, no
|
||||
@@ -1268,15 +1293,15 @@ that number and nothing else — everything derives from it:
|
||||
library. Lossiness follows the settled rule: memory cues become hot cues in
|
||||
spare pads (earliest first), cue colour is dropped (Traktor derives it from
|
||||
type).
|
||||
- 🟡 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).
|
||||
- 🟡 OneLibrary adapter — **reading done; editing in progress** toward parity
|
||||
with Rekordbox (2026-10-01, [decisions](.claude/discussions/discuss-onelibrary-editing-2026-10-01.md)).
|
||||
A OneLibrary USB drive opens, projects, browses and searches: tracks,
|
||||
playlists, hot cues, memory cues, loops and flexible beatgrids. Done: track
|
||||
metadata (+ file tags) and playlists, Save via a working copy. Next: cues and
|
||||
grid in the ANLZ files (rekordbox blanks `PQT2` on a grid edit — measured),
|
||||
the `export.pdb` rebuild on save, adding/removing tracks, "Open for editing…"
|
||||
on a Devices row. All format research — including the schema, which has no
|
||||
public spec — is in [.claude/handoffs/onelibrary-adapter.md](.claude/handoffs/onelibrary-adapter.md).
|
||||
- 🟡 **Export/conversion** — **in progress.** Both the design AND the user flow
|
||||
are settled; see
|
||||
[the export discussion doc](.claude/discussions/discuss-export-implementation-2026-09-22.md),
|
||||
|
||||
@@ -56,3 +56,16 @@ 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.
|
||||
|
||||
## rekordbox-edited/
|
||||
|
||||
Analysis files from a SECOND stick (Goober), after rekordbox 7 itself edited it
|
||||
(2026-10-01): a hot cue added on pad E of `demo-track-2`, and a memory cue added on
|
||||
the start of `nemean`'s memory loop. Trimmed the same way as above, by dropping
|
||||
whole tags: only `PPTH`, `PCOB` and `PCO2` are kept, byte for byte.
|
||||
|
||||
They exist for one property: rekordbox writes **compact** cue entries when it
|
||||
edits (48 bytes for that hot cue, 44 with no colour for the memory cue; an export
|
||||
writes 88). pyrekordbox's parser raises on the 44-byte form, which once made the
|
||||
reader drop the whole `.EXT`, losing pads D-H and every colour. See
|
||||
`adapters/rekordbox/anlz_file.py`.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -5,18 +5,17 @@ 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.
|
||||
**Editable when opened as THE library**, with parity with the Rekordbox adapter
|
||||
as the goal (decisions: `.claude/discussions/discuss-onelibrary-editing-2026-10-01.md`).
|
||||
Opened `read_only` — as the sidebar's Devices do, beside the loaded library — it
|
||||
reports `writable=False` with cause `browsing`, and every command is refused.
|
||||
|
||||
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.
|
||||
What a write must look like was MEASURED by diffing a stick before and after
|
||||
rekordbox 7 edited it, rather than guessed: the update counters a drive carries
|
||||
do NOT move, and the `cue` table stays empty. Landing in steps — track metadata
|
||||
and playlists first; cues, grid, adding and removing tracks after — and every
|
||||
command not written yet is refused, with its capability flag False so the UI
|
||||
never offers it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -42,9 +41,10 @@ ATTRIBUTE_SMART = 4
|
||||
class OneLibraryAdapter:
|
||||
platform = "onelibrary"
|
||||
|
||||
def __init__(self, path: Path):
|
||||
def __init__(self, path: Path, *, read_only: bool = False):
|
||||
self.path = Path(path)
|
||||
self._store = OneLibraryStore(self.path)
|
||||
self.read_only = read_only
|
||||
self._store = OneLibraryStore(self.path, read_only=read_only)
|
||||
self._index = TrackIndex()
|
||||
self._rebuild()
|
||||
|
||||
@@ -72,14 +72,25 @@ class OneLibraryAdapter:
|
||||
self._store.close()
|
||||
|
||||
def reload(self) -> None:
|
||||
self._store._load()
|
||||
"""Re-read the drive, DISCARDING unsaved edits."""
|
||||
self._store.discard()
|
||||
self._rebuild()
|
||||
|
||||
def _refresh(self, track_id: str) -> None:
|
||||
"""Re-project one track after a command, so the UI cannot go stale."""
|
||||
from ...core.stem_file import is_stem_file
|
||||
|
||||
row = self._store.content(track_id)
|
||||
path = self._drive_path(row)
|
||||
self._index.replace(projection.to_track(row, path, stem=bool(path) and is_stem_file(path)))
|
||||
|
||||
# ---- identity --------------------------------------------------------
|
||||
def capabilities(self) -> Capabilities:
|
||||
return caps.capabilities_for(
|
||||
device_name=self._store.device_name,
|
||||
version=self._store.db_version,
|
||||
read_only=self.read_only,
|
||||
editable_fields=sorted(OneLibraryStore.EDITABLE_FIELDS),
|
||||
)
|
||||
|
||||
# ---- read ------------------------------------------------------------
|
||||
@@ -146,7 +157,9 @@ class OneLibraryAdapter:
|
||||
rather than an absence, and treating 0 as a real id would orphan every
|
||||
top-level playlist.
|
||||
"""
|
||||
rows = self._store.playlists()
|
||||
rows = sorted(self._store.playlists(),
|
||||
key=lambda r: (int(getattr(r, "sequenceNo", 0) or 0), int(r.playlist_id)))
|
||||
writable = not self.read_only
|
||||
nodes: dict[str, PlaylistNode] = {}
|
||||
parents: dict[str, str] = {}
|
||||
|
||||
@@ -166,12 +179,12 @@ class OneLibraryAdapter:
|
||||
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
|
||||
# Opened read-only, every 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_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(getattr(r, "playlist_id_parent", 0) or 0)
|
||||
@@ -238,21 +251,31 @@ class OneLibraryAdapter:
|
||||
# ---- 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:
|
||||
raise Unsupported("OneLibrary drives are not versioned by Konduktor")
|
||||
|
||||
# ---- commands: all refused -------------------------------------------
|
||||
# ---- commands -----------------------------------------------------------
|
||||
def _readonly_reason(self, what: str) -> str:
|
||||
if self.read_only:
|
||||
return (f"{what} is not possible while the drive is open for browsing. "
|
||||
"Open it for editing to change it.")
|
||||
return f"{what} is not supported yet for OneLibrary drives."
|
||||
|
||||
def _refuse(self, what: str):
|
||||
raise Unsupported(self._readonly_reason(what))
|
||||
|
||||
def _require_writable(self, what: str) -> None:
|
||||
"""Every write passes through here, so a command added later cannot
|
||||
forget that a browsing drive is read-only."""
|
||||
if self.read_only:
|
||||
self._refuse(what)
|
||||
|
||||
def add_tracks(self, items: list, *, checkpoint=None) -> list[str]:
|
||||
self._refuse("Adding tracks")
|
||||
|
||||
@@ -263,7 +286,10 @@ class OneLibraryAdapter:
|
||||
self._refuse("Converting tracks to stems")
|
||||
|
||||
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None:
|
||||
self._refuse("Editing track metadata")
|
||||
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_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
|
||||
self._refuse("Editing cover art")
|
||||
@@ -272,19 +298,24 @@ class OneLibraryAdapter:
|
||||
return self._store.cover_art(track_id)
|
||||
|
||||
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
|
||||
self._refuse("Creating playlists")
|
||||
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._refuse("Creating playlist folders")
|
||||
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._refuse("Renaming playlists")
|
||||
self._require_writable("Renaming playlists")
|
||||
self._store.rename_playlist(node_id, name)
|
||||
|
||||
def delete_playlist(self, node_id: str) -> None:
|
||||
self._refuse("Deleting playlists")
|
||||
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._refuse("Editing playlists")
|
||||
self._require_writable("Editing playlists")
|
||||
return self._store.set_playlist_entries(node_id, track_ids)
|
||||
|
||||
def set_cue(self, track_id: str, **kw) -> TrackCues:
|
||||
self._refuse("Editing cues")
|
||||
|
||||
@@ -28,7 +28,8 @@ __all__ = ["BPM_EPSILON", "markers_from_beats", "beats_from_pqtz", "markers_from
|
||||
|
||||
|
||||
def beats_from_pqtz(anlz) -> tuple[list[float], list[float], list[int]] | None:
|
||||
"""Per-beat ``(times_sec, bpms, beat_in_bar)`` from a parsed ANLZ file's `PQTZ` tag.
|
||||
"""Per-beat ``(times_sec, bpms, beat_in_bar)`` from a parsed ANLZ file's `PQTZ` tag
|
||||
(an `anlz_file.AnlzFile`).
|
||||
|
||||
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
|
||||
@@ -39,7 +40,7 @@ def beats_from_pqtz(anlz) -> tuple[list[float], list[float], list[int]] | None:
|
||||
for tag in getattr(anlz, "tags", []):
|
||||
if tag.type != "PQTZ":
|
||||
continue
|
||||
entries = getattr(getattr(tag.struct, "content", None), "entries", None)
|
||||
entries = tag.entries
|
||||
if not entries:
|
||||
return None
|
||||
times: list[float] = []
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
"""What a OneLibrary drive can persist: nothing, for now.
|
||||
"""What a OneLibrary drive can persist.
|
||||
|
||||
`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.
|
||||
Opened as THE library, a drive is writable, and the per-feature flags say which
|
||||
edits have landed: track metadata and playlists so far; cues, the grid, adding
|
||||
and removing tracks are still False, so the UI never offers an edit the adapter
|
||||
would refuse. Opened `read_only` — the sidebar's Devices, browsing beside the
|
||||
loaded library — `writable` is False with cause `browsing`, which the UI words
|
||||
as "open it for editing", not as a missing feature.
|
||||
|
||||
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.
|
||||
With `writable=False` the per-feature flags still report what the FORMAT
|
||||
supports rather than being blanked, because that is what the library-level flag
|
||||
is for: the UI can show a drive's cues and grid honestly and say once, in one
|
||||
place, that the 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
|
||||
@@ -40,14 +42,18 @@ from ...core.capabilities import (
|
||||
HOTCUE_SLOTS = 8
|
||||
|
||||
|
||||
def capabilities_for(device_name: str | None = None, version: str | None = None) -> Capabilities:
|
||||
def capabilities_for(
|
||||
device_name: str | None = None,
|
||||
version: str | None = None,
|
||||
*,
|
||||
read_only: bool = False,
|
||||
editable_fields: list[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",
|
||||
writable=not read_only,
|
||||
readonly_cause="browsing" if read_only else None,
|
||||
cues=CueCapabilities(
|
||||
editable=False,
|
||||
hotcue_slots=HOTCUE_SLOTS,
|
||||
@@ -68,10 +74,12 @@ def capabilities_for(device_name: str | None = None, version: str | None = None)
|
||||
grid=GridCapabilities(editable=False, flexible=True, lockable=False),
|
||||
tracks=TrackCapabilities(
|
||||
rating_max=5, # stored 0-5 directly, as in master.db
|
||||
editable_fields=[],
|
||||
# The Rekordbox adapter's set: `producer`/`mix` have no column.
|
||||
editable_fields=sorted(editable_fields or []),
|
||||
media_kinds=["audio", "stem"],
|
||||
# `artwork` gates EDITING, and a drive is read-only here. Reading
|
||||
# works: `store.cover_art` follows `content.image_id` -> `image.path`.
|
||||
# `artwork` gates EDITING, which Rekordbox does not do yet either
|
||||
# (parity). Reading works: `store.cover_art` follows
|
||||
# `content.image_id` -> `image.path`.
|
||||
artwork=False,
|
||||
artwork_note=None,
|
||||
),
|
||||
@@ -80,12 +88,16 @@ def capabilities_for(device_name: str | None = None, version: str | None = None)
|
||||
# A drive carries no smart playlists: rekordbox resolves them to
|
||||
# static lists on export, because a CDJ cannot evaluate rules.
|
||||
smart="none",
|
||||
reorder=False,
|
||||
reorder=True,
|
||||
),
|
||||
save=SaveCapabilities(
|
||||
app_name="OneLibrary",
|
||||
library_label=device_name or "exportLibrary.db",
|
||||
# Nothing is written, so nothing can be overwritten by another app.
|
||||
# Named for the DRIVE ("Save to Goober"): a person has several
|
||||
# sticks, and "Save to OneLibrary" would not say which.
|
||||
app_name=device_name or "OneLibrary",
|
||||
library_label="exportLibrary.db",
|
||||
# Another app writing the drive between open and save is CAUGHT,
|
||||
# not risked: the store fingerprints the database at open and
|
||||
# refuses to save over a change it did not make.
|
||||
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
|
||||
|
||||
@@ -47,14 +47,13 @@ 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.
|
||||
# PCO2/PCOB entry kinds. The value is the same in both tags.
|
||||
ENTRY_CUE = 1
|
||||
ENTRY_LOOP = 2
|
||||
|
||||
|
||||
def _entry_kind(value) -> int:
|
||||
"""PCOB gives an enum, PCO2 an int — one number out of either."""
|
||||
"""An entry's kind as an int, defaulting to a point cue if unreadable."""
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
@@ -70,6 +69,8 @@ def _color(entry) -> str | None:
|
||||
black. Memory cues in the reference export are exactly this case.
|
||||
"""
|
||||
try:
|
||||
# None on an entry too short to carry a colour: every PCPT, and the
|
||||
# compact 44-byte PCP2 rekordbox writes for a memory cue it added.
|
||||
r, g, b = int(entry.color_red), int(entry.color_green), int(entry.color_blue)
|
||||
except (AttributeError, TypeError, ValueError):
|
||||
return None
|
||||
@@ -130,15 +131,14 @@ def _entries(anlz, tag_type: str) -> list:
|
||||
"""
|
||||
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 [])
|
||||
if tag.type == tag_type:
|
||||
out.extend(tag.entries)
|
||||
return out
|
||||
|
||||
|
||||
def cues_from_anlz(dat, ext) -> list[CuePoint]:
|
||||
"""The track's complete cue list, from its parsed `.DAT` and `.EXT`.
|
||||
"""The track's complete cue list, from its parsed `.DAT` and `.EXT`
|
||||
(`rekordbox.anlz_file.AnlzFile`s).
|
||||
|
||||
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.
|
||||
@@ -168,18 +168,23 @@ def cues_from_anlz(dat, ext) -> list[CuePoint]:
|
||||
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.
|
||||
Identity is (role, slot, start, type, length) 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 all five while differing in how much detail they
|
||||
carry (colour, comment). The first one wins, which — given PCO2 is read
|
||||
first — is the richest.
|
||||
|
||||
Type and length are part of it because two MEMORY cues may share a position:
|
||||
rekordbox happily stores a memory cue on the start of a memory loop (seen on
|
||||
Goober), and keying on position alone silently dropped the loop.
|
||||
|
||||
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()
|
||||
seen: set[tuple] = set()
|
||||
out: list[CuePoint] = []
|
||||
for c in cues:
|
||||
key = (c.role, c.slot, round(c.start * 1000))
|
||||
key = (c.role, c.slot, round(c.start * 1000), c.type, round(c.length * 1000))
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
|
||||
@@ -73,8 +73,8 @@ class OneLibraryDriver:
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
def open(self, path: Path) -> OneLibraryAdapter:
|
||||
return OneLibraryAdapter(path)
|
||||
def open(self, path: Path, *, read_only: bool = False) -> OneLibraryAdapter:
|
||||
return OneLibraryAdapter(path, read_only=read_only)
|
||||
|
||||
def detect(self) -> list[dict]:
|
||||
return discovery.detect_libraries()
|
||||
|
||||
@@ -1,13 +1,27 @@
|
||||
"""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.
|
||||
Owns the drive's ``exportLibrary.db`` and the 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.
|
||||
|
||||
**Konduktor never opens the database ON the drive.** It works on a COPY in
|
||||
app-data (`_working`), taken at open and written back whole at Save:
|
||||
|
||||
* an unsaved edit lives in an open transaction on the copy, so nothing reaches
|
||||
the stick before Save — the same "edit in memory, Save writes" contract every
|
||||
library keeps, without a long transaction spilling pages into a file on a
|
||||
drive that may be unplugged mid-session;
|
||||
* the stick holds no open handle, so it can eject (a held handle is what made
|
||||
an earlier version's drives refuse to);
|
||||
* a save replaces the file by RENAME, so a stick pulled mid-save is left with
|
||||
the old library or the new one, never half of each;
|
||||
* the drive's file is fingerprinted at open, and Save refuses if something else
|
||||
(rekordbox) has written it since, rather than silently undoing that work.
|
||||
|
||||
**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
|
||||
@@ -16,29 +30,114 @@ 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`.
|
||||
|
||||
**What rekordbox writes when IT edits a stick was measured** (Goober,
|
||||
2026-10-01; the editing discussion log has the diff): no update counter moves
|
||||
(`hasModified`, `cueUpdateCount`, … stay as they were), the `cue` table stays
|
||||
empty, a new playlist goes on TOP (`sequenceNo` 0, siblings shift), entries are
|
||||
numbered from 1. The writes below follow that.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import tempfile
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from ...core.adapter import LibraryNotSupported, NotFound
|
||||
from ...core.adapter import FileTagResult, InvalidCommand, LibraryNotSupported, NotFound, SaveOutcome
|
||||
from ...core.edit_journal import EditJournal
|
||||
from ...core.model import CuePoint
|
||||
from ... import paths
|
||||
from . import beatgrid, cues as cue_reader
|
||||
from ..rekordbox import timebase
|
||||
from ..rekordbox import anlz_file, timebase
|
||||
from .layout import DriveLayout
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
#: SQLite's companions to a database file. rekordbox leaves both on a stick it
|
||||
#: has mounted, and a leftover WAL is REPLAYED into whatever database sits beside
|
||||
#: it — so they are copied with the database at open and deleted at save.
|
||||
_SIDECARS = ("-wal", "-shm")
|
||||
|
||||
#: Backups kept per drive (app-data, never on the stick). A gig stick is real
|
||||
#: data, unlike a Rekordbox test library; but each backup is a whole database.
|
||||
_BACKUPS_KEPT = 10
|
||||
|
||||
#: Working copies older than this are a crashed session's, and are cleared.
|
||||
_STALE_WORK_SEC = 24 * 3600
|
||||
|
||||
#: `playlist.attribute`.
|
||||
ATTRIBUTE_PLAYLIST = 0
|
||||
ATTRIBUTE_FOLDER = 1
|
||||
|
||||
_YEAR = re.compile(r"^\d{4}$")
|
||||
_DATE = re.compile(r"^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})$")
|
||||
|
||||
|
||||
def _fingerprint(db: Path) -> tuple:
|
||||
"""What the drive's database looks like on disk: size + mtime of it and its WAL.
|
||||
|
||||
Enough to notice another app writing it between open and save; not a hash,
|
||||
because reading a whole database back over USB to compare costs a save.
|
||||
"""
|
||||
out = []
|
||||
for p in (db, *(db.with_name(db.name + s) for s in _SIDECARS)):
|
||||
try:
|
||||
st = p.stat()
|
||||
out.append((p.name, st.st_size, st.st_mtime_ns))
|
||||
except FileNotFoundError:
|
||||
out.append((p.name, None, None))
|
||||
return tuple(out)
|
||||
|
||||
|
||||
def _work_root() -> Path:
|
||||
root = paths.app_data_dir() / "onelibrary" / "work"
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
return root
|
||||
|
||||
|
||||
def _backup_root(layout: DriveLayout) -> Path:
|
||||
# Keyed by the drive's mount name: a removable library has no sidecar id
|
||||
# (library_id.py), and a person looking for a backup knows their stick's name.
|
||||
name = re.sub(r"[^\w.-]+", "_", layout.root.name or "drive")
|
||||
return paths.app_data_dir() / "onelibrary" / "backups" / name
|
||||
|
||||
|
||||
class OneLibraryStore:
|
||||
def __init__(self, path: Path):
|
||||
# Metadata a OneLibrary drive can hold, matched to the Rekordbox adapter's
|
||||
# set. `producer` and `mix` have no column; `composer`/`lyricist` are
|
||||
# different fields and are not mapped onto them approximately.
|
||||
_DIRECT_FIELDS = {"title": "title", "comment": "djComment"}
|
||||
# Foreign keys into lookup tables, found-or-created by NAME.
|
||||
_LOOKUP_FIELDS = {
|
||||
"artist": ("Artist", "artist_id_artist"),
|
||||
# A remixer IS an artist — same table, different column.
|
||||
"remixer": ("Artist", "artist_id_remixer"),
|
||||
"album": ("Album", "album_id"),
|
||||
"genre": ("Genre", "genre_id"),
|
||||
"label": ("Label", "label_id"),
|
||||
}
|
||||
EDITABLE_FIELDS = set(_DIRECT_FIELDS) | set(_LOOKUP_FIELDS) | {"rating", "release_date"}
|
||||
# Written into the audio file's own tags at Save, as rekordbox does when it
|
||||
# edits a stick (measured: the title reached the MP3's TIT2, the rating did
|
||||
# not). Everything editable except the rating.
|
||||
FILE_TAG_FIELDS = EDITABLE_FIELDS - {"rating"}
|
||||
|
||||
def __init__(self, path: Path, *, read_only: bool = False):
|
||||
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.read_only = read_only
|
||||
self._db = None
|
||||
self._work: Path | None = None
|
||||
self._opened_as: tuple | None = None
|
||||
self._journal = EditJournal()
|
||||
# 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] = {}
|
||||
@@ -49,49 +148,64 @@ class OneLibraryStore:
|
||||
|
||||
# ---- open / close ----------------------------------------------------
|
||||
def _load(self) -> None:
|
||||
"""Copy the drive's database into app-data and open the copy."""
|
||||
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
|
||||
_clear_stale_work()
|
||||
work = Path(tempfile.mkdtemp(prefix="drive-", dir=_work_root()))
|
||||
try:
|
||||
self._db = DeviceLibraryPlus(str(self.path))
|
||||
self._opened_as = _fingerprint(self.path)
|
||||
working = work / self.path.name
|
||||
shutil.copyfile(self.path, working)
|
||||
for suffix in _SIDECARS[:1]: # the WAL carries data; -shm is rebuilt
|
||||
sidecar = self.path.with_name(self.path.name + suffix)
|
||||
if sidecar.is_file() and sidecar.stat().st_size:
|
||||
shutil.copyfile(sidecar, working.with_name(working.name + suffix))
|
||||
db = DeviceLibraryPlus(str(working))
|
||||
except Exception as ex: # noqa: BLE001 — surfaced as a clean 4xx
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
raise LibraryNotSupported(f"Could not open OneLibrary database: {ex}") from ex
|
||||
self._db, self._work = db, work
|
||||
self._journal.clear()
|
||||
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.
|
||||
"""Release the working copy and delete it.
|
||||
|
||||
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`.
|
||||
The drive itself is never held open (see the module docstring); the copy
|
||||
is, and `DeviceLibraryPlus.close()` only unregisters events, so the
|
||||
session and engine are closed here explicitly.
|
||||
"""
|
||||
db, self._db = self._db, None
|
||||
if db is None:
|
||||
return
|
||||
work, self._work = self._work, None
|
||||
if db is not None:
|
||||
for step in (lambda: db.session.rollback(), lambda: db.session.close(),
|
||||
lambda: db.engine.dispose()):
|
||||
try:
|
||||
db.close()
|
||||
step()
|
||||
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)
|
||||
log.debug("OneLibrary close step failed", exc_info=True)
|
||||
if work is not None:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
|
||||
def discard(self) -> None:
|
||||
"""Drop every unsaved edit: a fresh copy of the drive's database."""
|
||||
self.close()
|
||||
self._load()
|
||||
|
||||
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:
|
||||
@@ -202,9 +316,9 @@ class OneLibraryStore:
|
||||
try:
|
||||
if not target.is_file():
|
||||
return None
|
||||
from pyrekordbox.anlz import AnlzFile
|
||||
|
||||
cache[key] = AnlzFile.parse_file(str(target))
|
||||
# Our own tag reader, not pyrekordbox's: it cannot parse the compact
|
||||
# cue entries rekordbox writes when it edits a stick (see anlz_file).
|
||||
cache[key] = anlz_file.parse_file(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
|
||||
@@ -282,3 +396,354 @@ class OneLibraryStore:
|
||||
if track_id is not None:
|
||||
out.append(track_id)
|
||||
return out
|
||||
|
||||
# ---- writes: track metadata -------------------------------------------
|
||||
#
|
||||
# Each command changes the working copy inside ONE open transaction; Save
|
||||
# commits it and puts the file back on the drive (see `save`).
|
||||
def _lookup_id(self, model_name: str, name: str) -> int | None:
|
||||
"""The id of the lookup row called `name`, creating it if needed.
|
||||
|
||||
`nameForSearch` is left NULL, as on every lookup row rekordbox wrote on
|
||||
the reference stick (pyrekordbox's own `add_*` would write "").
|
||||
"""
|
||||
if not name:
|
||||
return None
|
||||
from pyrekordbox.devicelib_plus import models
|
||||
|
||||
model = getattr(models, model_name)
|
||||
pk = f"{model.__tablename__}_id"
|
||||
db = self._require_db()
|
||||
existing = db.query(model).filter_by(name=name).first()
|
||||
if existing is not None:
|
||||
return int(getattr(existing, pk))
|
||||
row = model(name=name, isComplation=0) if model_name == "Album" else model(name=name)
|
||||
db.add(row)
|
||||
db.flush()
|
||||
return int(getattr(row, pk))
|
||||
|
||||
@staticmethod
|
||||
def _release(value) -> tuple[int, str]:
|
||||
"""(`releaseYear`, `releaseDate`) for an edited release date.
|
||||
|
||||
rekordbox writes 0 and '' for "none" and keeps dates as `YYYY-MM-DD`
|
||||
text (every date column on the reference stick has that shape).
|
||||
"""
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return 0, ""
|
||||
if _YEAR.match(text):
|
||||
return int(text), ""
|
||||
m = _DATE.match(text)
|
||||
if m:
|
||||
y, mo, d = (int(g) for g in m.groups())
|
||||
try:
|
||||
return y, datetime(y, mo, d).strftime("%Y-%m-%d")
|
||||
except ValueError:
|
||||
pass
|
||||
raise InvalidCommand(f"Release date must be a year or YYYY-MM-DD, got {text!r}")
|
||||
|
||||
def set_track_metadata(self, track_id: str, fields: dict) -> None:
|
||||
from sqlalchemy import text
|
||||
|
||||
db = self._require_db()
|
||||
row = self.content(track_id)
|
||||
for key, value in fields.items():
|
||||
if key not in self.EDITABLE_FIELDS:
|
||||
continue # unknown/unsafe 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 == "release_date":
|
||||
year, date = self._release(value)
|
||||
before, new = (row.releaseYear, row.releaseDate), (year, date)
|
||||
row.releaseYear = year
|
||||
# Raw SQL, not the ORM: pyrekordbox's DateTime column would
|
||||
# store `YYYY-MM-DD HH:MM:SS.SSS +00:00`, which is not the
|
||||
# format rekordbox writes.
|
||||
db.flush()
|
||||
db.session.execute(
|
||||
text("UPDATE content SET releaseDate = :d WHERE content_id = :id"),
|
||||
{"d": date, "id": row.content_id},
|
||||
)
|
||||
elif key in self._DIRECT_FIELDS:
|
||||
column = self._DIRECT_FIELDS[key]
|
||||
before = getattr(row, column)
|
||||
# rekordbox keeps an empty text column as '', not NULL.
|
||||
new = "" if value is None else str(value)
|
||||
setattr(row, column, new)
|
||||
else:
|
||||
model_name, column = self._LOOKUP_FIELDS[key]
|
||||
before = getattr(row, column)
|
||||
new = self._lookup_id(model_name, (value or "").strip())
|
||||
setattr(row, column, new)
|
||||
self._journal.record("track", "set", track_id, key, before, new)
|
||||
# The lookups are FOREIGN KEYS: setting an id does not move the ORM's
|
||||
# cached relationship, so re-projecting now would read the OLD name back
|
||||
# and report a successful edit as a no-op. Flush, then expire the row.
|
||||
db.flush()
|
||||
db.session.expire(row)
|
||||
|
||||
# ---- writes: playlists --------------------------------------------------
|
||||
def _playlist(self, node_id: str):
|
||||
from pyrekordbox.devicelib_plus import models
|
||||
|
||||
try:
|
||||
pid = int(node_id)
|
||||
except (TypeError, ValueError):
|
||||
raise NotFound(f"No playlist {node_id!r}") from None
|
||||
row = self._require_db().query(models.Playlist).filter_by(playlist_id=pid).first()
|
||||
if row is None:
|
||||
raise NotFound(f"No playlist {node_id!r}")
|
||||
return row
|
||||
|
||||
def _siblings(self, parent_id: int, *, excluding: int | None = None) -> list:
|
||||
from pyrekordbox.devicelib_plus import models
|
||||
|
||||
rows = self._require_db().query(models.Playlist).filter_by(playlist_id_parent=parent_id).all()
|
||||
rows = [r for r in rows if r.playlist_id != excluding]
|
||||
return sorted(rows, key=lambda r: (int(r.sequenceNo or 0), int(r.playlist_id)))
|
||||
|
||||
def _create_node(self, name: str, parent_id: str | None, attribute: int) -> str:
|
||||
from pyrekordbox.devicelib_plus import models
|
||||
|
||||
name = (name or "").strip()
|
||||
noun = "folder" if attribute == ATTRIBUTE_FOLDER else "playlist"
|
||||
if not name:
|
||||
raise InvalidCommand(f"A {noun} needs a name")
|
||||
parent = 0
|
||||
if parent_id:
|
||||
folder = self._playlist(parent_id)
|
||||
if int(folder.attribute or 0) != ATTRIBUTE_FOLDER:
|
||||
raise InvalidCommand(f"A {noun} can only be created inside a folder")
|
||||
parent = int(folder.playlist_id)
|
||||
db = self._require_db()
|
||||
# MEASURED: rekordbox puts a new playlist at the TOP of its folder —
|
||||
# sequenceNo 0, every sibling moved down one. (pyrekordbox's own
|
||||
# add_playlist appends at count+1, which is not what rekordbox does.)
|
||||
for sibling in self._siblings(parent):
|
||||
sibling.sequenceNo = int(sibling.sequenceNo or 0) + 1
|
||||
row = models.Playlist(name=name, sequenceNo=0, attribute=attribute,
|
||||
playlist_id_parent=parent, image_id=None)
|
||||
db.add(row)
|
||||
db.flush()
|
||||
self._journal.record("playlist", "create-folder" if attribute == ATTRIBUTE_FOLDER
|
||||
else "create", name)
|
||||
return str(row.playlist_id)
|
||||
|
||||
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
|
||||
return self._create_node(name, parent_id, ATTRIBUTE_PLAYLIST)
|
||||
|
||||
def create_folder(self, name: str, parent_id: str | None = None) -> str:
|
||||
return self._create_node(name, parent_id, ATTRIBUTE_FOLDER)
|
||||
|
||||
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)
|
||||
before = row.name
|
||||
row.name = name
|
||||
self._require_db().flush()
|
||||
self._journal.record("playlist", "rename", name, before=before)
|
||||
|
||||
def delete_playlist(self, node_id: str) -> None:
|
||||
"""Delete a playlist, or a folder WITH everything in it, and close the gap
|
||||
its `sequenceNo` leaves among its siblings."""
|
||||
from pyrekordbox.devicelib_plus import models
|
||||
|
||||
db = self._require_db()
|
||||
row = self._playlist(node_id)
|
||||
name, parent = row.name, int(row.playlist_id_parent or 0)
|
||||
doomed, frontier = [], [row]
|
||||
while frontier:
|
||||
node = frontier.pop()
|
||||
doomed.append(node)
|
||||
frontier.extend(db.query(models.Playlist)
|
||||
.filter_by(playlist_id_parent=node.playlist_id).all())
|
||||
for node in doomed:
|
||||
for entry in db.query(models.PlaylistContent).filter_by(playlist_id=node.playlist_id).all():
|
||||
db.delete(entry)
|
||||
db.delete(node)
|
||||
db.flush()
|
||||
for n, sibling in enumerate(self._siblings(parent)):
|
||||
sibling.sequenceNo = n
|
||||
db.flush()
|
||||
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 order, numbered from 1 (measured)."""
|
||||
from pyrekordbox.devicelib_plus import models
|
||||
|
||||
db = self._require_db()
|
||||
playlist = self._playlist(node_id)
|
||||
if int(playlist.attribute or 0) != ATTRIBUTE_PLAYLIST:
|
||||
raise InvalidCommand("Only a plain playlist has an editable track list")
|
||||
self.iter_content()
|
||||
unknown = [t for t in track_ids if str(t) not in (self._by_id or {})]
|
||||
if unknown:
|
||||
raise NotFound(f"Unknown track(s): {', '.join(map(str, unknown[:3]))}")
|
||||
for entry in db.query(models.PlaylistContent).filter_by(playlist_id=playlist.playlist_id).all():
|
||||
db.delete(entry)
|
||||
db.flush()
|
||||
for n, track_id in enumerate(track_ids, start=1):
|
||||
db.add(models.PlaylistContent(playlist_id=playlist.playlist_id,
|
||||
content_id=int(self._by_id[str(track_id)].content_id),
|
||||
sequenceNo=n))
|
||||
db.flush()
|
||||
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:
|
||||
"""Write the session's edits to the drive.
|
||||
|
||||
In this order, each step a precondition for the next:
|
||||
|
||||
1. the drive is still there, and NOTHING else has written its database
|
||||
since it was opened — otherwise this would silently undo it;
|
||||
2. the working copy is committed and closed, which folds its WAL in, so
|
||||
the copy is one self-contained file;
|
||||
3. the drive's current database is backed up to app-data;
|
||||
4. the copy is written beside the drive's database under a temporary
|
||||
name, the stale `-wal`/`-shm` are deleted (SQLite would REPLAY an
|
||||
old WAL into the new file), and the copy is renamed over it — a
|
||||
stick pulled mid-save keeps one whole library or the other;
|
||||
5. edited text fields go into the audio files' own tags (best-effort,
|
||||
reported per file, never failing the save);
|
||||
6. the working copy is re-taken from what is now on the drive.
|
||||
|
||||
`snapshot` is None: a drive is a database plus analysis files plus the
|
||||
audio, so there is no single blob to version (`capabilities.save.history`).
|
||||
"""
|
||||
db = self._require_db()
|
||||
if not self.path.parent.is_dir():
|
||||
raise InvalidCommand(
|
||||
f"{self.layout.root.name} is not connected. Plug it back in and "
|
||||
"save again — your changes are still here."
|
||||
)
|
||||
if _fingerprint(self.path) != self._opened_as:
|
||||
raise InvalidCommand(
|
||||
f"Another app has changed {self.layout.root.name} since Konduktor "
|
||||
"opened it, and saving would undo that. Discard your changes and "
|
||||
"reopen the drive to edit it again."
|
||||
)
|
||||
summary = self._journal.summary()
|
||||
# Read BEFORE the session closes: the rows are useless after it.
|
||||
tag_jobs = self._tag_jobs()
|
||||
|
||||
db.session.commit()
|
||||
work, working = self._work, self._work / self.path.name
|
||||
self._db = None
|
||||
self._content_cache = None
|
||||
self._by_id = None
|
||||
for step in (db.session.close, db.engine.dispose):
|
||||
try:
|
||||
step()
|
||||
except Exception: # noqa: BLE001
|
||||
log.debug("OneLibrary close step failed", exc_info=True)
|
||||
try:
|
||||
self._backup()
|
||||
partial = self.path.with_name(f".{self.path.name}.konduktor-partial")
|
||||
shutil.copyfile(working, partial)
|
||||
with open(partial, "rb+") as f:
|
||||
os.fsync(f.fileno())
|
||||
for suffix in _SIDECARS:
|
||||
self.path.with_name(self.path.name + suffix).unlink(missing_ok=True)
|
||||
os.replace(partial, self.path)
|
||||
except BaseException:
|
||||
# The edits are still in the working copy, committed: reopen it so a
|
||||
# retry (after replugging, say) can save them.
|
||||
self._reopen_working(work)
|
||||
raise
|
||||
tag_results = self._sync_file_tags(tag_jobs)
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
self._work = None
|
||||
self._load()
|
||||
return SaveOutcome(summary=summary, snapshot=None, tag_results=tag_results)
|
||||
|
||||
def _reopen_working(self, work: Path) -> None:
|
||||
from pyrekordbox.devicelib_plus import DeviceLibraryPlus
|
||||
|
||||
self._db, self._work = DeviceLibraryPlus(str(work / self.path.name)), work
|
||||
self._content_cache = None
|
||||
self._by_id = None
|
||||
|
||||
def _backup(self) -> Path:
|
||||
"""Copy the drive's database (and a live WAL) to app-data before replacing it."""
|
||||
root = _backup_root(self.layout)
|
||||
dest = root / time.strftime("%Y%m%d-%H%M%S")
|
||||
n = 1
|
||||
while dest.exists():
|
||||
n += 1
|
||||
dest = root / f"{time.strftime('%Y%m%d-%H%M%S')}-{n}"
|
||||
dest.mkdir(parents=True)
|
||||
for p in (self.path, self.path.with_name(self.path.name + "-wal")):
|
||||
if p.is_file():
|
||||
shutil.copy2(p, dest / p.name)
|
||||
for old in sorted(d for d in root.iterdir() if d.is_dir())[:-_BACKUPS_KEPT]:
|
||||
shutil.rmtree(old, ignore_errors=True)
|
||||
return dest
|
||||
|
||||
def _tag_jobs(self) -> list[tuple[str, Path, dict]]:
|
||||
"""(track id, audio file, {field: value}) for every file-tag write a save
|
||||
owes: each edited track's edited text fields, as the library now holds them."""
|
||||
jobs = []
|
||||
for track_id in self._journal.edited_tracks():
|
||||
fields = self._journal.fields_for(track_id) & self.FILE_TAG_FIELDS
|
||||
if not fields:
|
||||
continue
|
||||
try:
|
||||
path = self.audio_path(track_id)
|
||||
except NotFound:
|
||||
continue # removed this session
|
||||
if path is not None:
|
||||
values = self._tag_values(track_id)
|
||||
jobs.append((track_id, path, {f: values.get(f) for f in fields}))
|
||||
return jobs
|
||||
|
||||
@staticmethod
|
||||
def _sync_file_tags(jobs: list[tuple[str, Path, dict]]) -> list[FileTagResult]:
|
||||
"""Write edited text fields into each audio file, as rekordbox does."""
|
||||
from ...core import audio_tags
|
||||
|
||||
results: list[FileTagResult] = []
|
||||
for track_id, path, meta in jobs:
|
||||
r = audio_tags.write_tags(path, meta)
|
||||
results.append(FileTagResult(track_id=track_id, file=str(path), ok=r.ok,
|
||||
status=r.status, detail=r.detail))
|
||||
return results
|
||||
|
||||
def _tag_values(self, track_id: str) -> dict:
|
||||
"""The fields' values as the library now holds them (from the working copy)."""
|
||||
from . import projection
|
||||
|
||||
t = projection.to_track(self.content(track_id))
|
||||
return {"title": t.title, "artist": t.artist, "album": t.album, "genre": t.genre,
|
||||
"label": t.label, "remixer": t.remixer, "comment": t.comment,
|
||||
"release_date": t.release_date}
|
||||
|
||||
|
||||
def _clear_stale_work() -> None:
|
||||
"""Remove working copies a crashed session left behind."""
|
||||
try:
|
||||
root = _work_root()
|
||||
cutoff = time.time() - _STALE_WORK_SEC
|
||||
for d in root.iterdir():
|
||||
if d.is_dir() and d.stat().st_mtime < cutoff:
|
||||
shutil.rmtree(d, ignore_errors=True)
|
||||
except OSError:
|
||||
pass
|
||||
@@ -0,0 +1,219 @@
|
||||
"""Reading an ANLZ analysis file at the TAG level, by hand.
|
||||
|
||||
The writer half is `anlz_writer`; this is its reader. Like the writer it lives
|
||||
here because the format is Pioneer's, not one product's.
|
||||
|
||||
**Why not `pyrekordbox`'s parser.** It decodes a cue entry with a FIXED layout,
|
||||
and rekordbox does not write one. An exported entry is 88 bytes, but when
|
||||
rekordbox 7 EDITS a stick it writes compact ones (measured on Goober,
|
||||
2026-10-01): a hot cue added in rekordbox was a 48-byte `PCP2` (colour, no
|
||||
padding), and a memory cue a 44-byte one (no colour bytes at all). pyrekordbox
|
||||
raises `PaddingError` on the 44-byte form, the whole `.EXT` fails to parse, and
|
||||
a reader that falls back to the `.DAT` silently loses pads D-H and every colour.
|
||||
So every entry here is read at its own `len_entry`, and a field the entry is too
|
||||
short to hold is simply absent.
|
||||
|
||||
A file is also split into its RAW tags, kept byte for byte. Editing a stick
|
||||
replaces one or two tags of a file rekordbox wrote; everything else (the
|
||||
waveforms, `PVBR`, tags nobody has decoded) must go back exactly as it was, and
|
||||
re-serialising through a parser is how bytes get lost.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import struct
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
#: `PMAI` · len_header · len_file · …
|
||||
FILE_MAGIC = b"PMAI"
|
||||
NO_LOOP = 0xFFFFFFFF
|
||||
|
||||
#: The cue-list kinds in `PCOB`/`PCO2`'s own header.
|
||||
LIST_MEMORY = 0
|
||||
LIST_HOT = 1
|
||||
|
||||
|
||||
@dataclass
|
||||
class Tag:
|
||||
"""One tag, raw. `data` is the WHOLE tag: magic, both lengths, and body."""
|
||||
|
||||
type: str
|
||||
data: bytes
|
||||
_entries: list | None = field(default=None, repr=False, compare=False)
|
||||
|
||||
@property
|
||||
def len_header(self) -> int:
|
||||
return struct.unpack_from(">I", self.data, 4)[0]
|
||||
|
||||
@property
|
||||
def list_kind(self) -> int | None:
|
||||
"""`PCOB`/`PCO2`: whether this is the hot cue or the memory list."""
|
||||
if self.type in ("PCOB", "PCO2") and len(self.data) >= 16:
|
||||
return struct.unpack_from(">I", self.data, 12)[0]
|
||||
return None
|
||||
|
||||
@property
|
||||
def entries(self) -> list:
|
||||
"""The tag's decoded entries (cues, or beats for `PQTZ`); [] otherwise."""
|
||||
if self._entries is None:
|
||||
decode = _DECODERS.get(self.type)
|
||||
self._entries = decode(self.data) if decode else []
|
||||
return self._entries
|
||||
|
||||
|
||||
@dataclass
|
||||
class AnlzFile:
|
||||
"""An analysis file split into its header and raw tags."""
|
||||
|
||||
header: bytes
|
||||
tags: list[Tag]
|
||||
|
||||
def to_bytes(self) -> bytes:
|
||||
"""Reassemble, fixing only the header's file length."""
|
||||
body = b"".join(t.data for t in self.tags)
|
||||
head = bytearray(self.header)
|
||||
struct.pack_into(">I", head, 8, len(head) + len(body))
|
||||
return bytes(head) + body
|
||||
|
||||
|
||||
class AnlzError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def parse(data: bytes) -> AnlzFile:
|
||||
"""Split a file into its tags. Raises `AnlzError` on a malformed file.
|
||||
|
||||
Lengths are trusted only as far as the file reaches: a tag claiming more
|
||||
bytes than remain ends the walk with an error rather than a short read.
|
||||
"""
|
||||
if len(data) < 12 or data[:4] != FILE_MAGIC:
|
||||
raise AnlzError("not an ANLZ file")
|
||||
len_header = struct.unpack_from(">I", data, 4)[0]
|
||||
if not 12 <= len_header <= len(data):
|
||||
raise AnlzError(f"bad file header length {len_header}")
|
||||
tags: list[Tag] = []
|
||||
off = len_header
|
||||
while off < len(data):
|
||||
if off + 12 > len(data):
|
||||
raise AnlzError(f"truncated tag at {off}")
|
||||
kind = data[off:off + 4].decode("latin-1")
|
||||
len_tag = struct.unpack_from(">I", data, off + 8)[0]
|
||||
if len_tag < 12 or off + len_tag > len(data):
|
||||
raise AnlzError(f"bad length {len_tag} for {kind} at {off}")
|
||||
tags.append(Tag(kind, data[off:off + len_tag]))
|
||||
off += len_tag
|
||||
return AnlzFile(header=data[:len_header], tags=tags)
|
||||
|
||||
|
||||
def parse_file(path) -> AnlzFile:
|
||||
with open(path, "rb") as f:
|
||||
return parse(f.read())
|
||||
|
||||
|
||||
# ---- cue entries ------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass
|
||||
class CueEntry:
|
||||
"""One `PCPT` or `PCP2` entry. Attribute names follow pyrekordbox's, which
|
||||
is what `onelibrary.cues` was written against.
|
||||
|
||||
`color_code` / RGB are None when the entry is too short to carry them (every
|
||||
`PCPT`, and rekordbox's compact 44-byte `PCP2`).
|
||||
"""
|
||||
|
||||
hot_cue: int
|
||||
type: int
|
||||
time: int
|
||||
loop_time: int
|
||||
comment: str = ""
|
||||
loop_numerator: int = 0
|
||||
loop_denominator: int = 0
|
||||
color_code: int | None = None
|
||||
color_red: int | None = None
|
||||
color_green: int | None = None
|
||||
color_blue: int | None = None
|
||||
len_entry: int = 0
|
||||
|
||||
|
||||
def _walk(data: bytes, first: int, magic: bytes, count: int):
|
||||
"""(offset, len_entry) for each entry, trusting each entry's own length."""
|
||||
off = first
|
||||
for _ in range(count):
|
||||
if off + 12 > len(data) or data[off:off + 4] != magic:
|
||||
return
|
||||
len_entry = struct.unpack_from(">I", data, off + 8)[0]
|
||||
if len_entry < 12 or off + len_entry > len(data):
|
||||
return
|
||||
yield off, len_entry
|
||||
off += len_entry
|
||||
|
||||
|
||||
def _pcob(data: bytes) -> list[CueEntry]:
|
||||
# tag prefix(12) · I list kind · H 0 · H count · i last
|
||||
count = struct.unpack_from(">H", data, 18)[0]
|
||||
out = []
|
||||
for off, n in _walk(data, 24, b"PCPT", count):
|
||||
if n < 44:
|
||||
continue
|
||||
# 4s · I len_header · I len_entry · I hot_cue · I status · I 0x10000 ·
|
||||
# H order_first · H order_last · B kind · x · H 1000 · I time · I loop
|
||||
hot_cue, = struct.unpack_from(">I", data, off + 12)
|
||||
kind = data[off + 28]
|
||||
time, loop = struct.unpack_from(">II", data, off + 32)
|
||||
out.append(CueEntry(hot_cue=hot_cue, type=kind, time=time, loop_time=loop, len_entry=n))
|
||||
return out
|
||||
|
||||
|
||||
def _pco2(data: bytes) -> list[CueEntry]:
|
||||
# tag prefix(12) · I list kind · H count · H 0
|
||||
count = struct.unpack_from(">H", data, 16)[0]
|
||||
out = []
|
||||
for off, n in _walk(data, 20, b"PCP2", count):
|
||||
if n < 28:
|
||||
continue
|
||||
hot_cue, = struct.unpack_from(">I", data, off + 12)
|
||||
kind = data[off + 16]
|
||||
time, loop = struct.unpack_from(">II", data, off + 20)
|
||||
e = CueEntry(hot_cue=hot_cue, type=kind, time=time, loop_time=loop, len_entry=n)
|
||||
if n >= 44:
|
||||
e.loop_numerator, e.loop_denominator, len_comment = struct.unpack_from(">HHI", data, off + 36)
|
||||
colour_at = off + 44 + len_comment
|
||||
if len_comment and colour_at <= off + n:
|
||||
e.comment = data[off + 44:colour_at].decode("utf-16-be", "replace").rstrip("\x00")
|
||||
if colour_at + 4 <= off + n:
|
||||
e.color_code, e.color_red, e.color_green, e.color_blue = data[colour_at:colour_at + 4]
|
||||
out.append(e)
|
||||
return out
|
||||
|
||||
|
||||
# ---- the beatgrid -----------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass
|
||||
class Beat:
|
||||
beat: int # 1-4, position in the bar
|
||||
tempo: int # BPM x 100
|
||||
time: int # ms
|
||||
|
||||
|
||||
def _pqtz(data: bytes) -> list[Beat]:
|
||||
# tag prefix(12) · I 0 · I 0x80000 · I count, then 8-byte entries
|
||||
count = struct.unpack_from(">I", data, 20)[0]
|
||||
first = struct.unpack_from(">I", data, 4)[0]
|
||||
out = []
|
||||
for i in range(count):
|
||||
off = first + 8 * i
|
||||
if off + 8 > len(data):
|
||||
break
|
||||
beat, tempo, time = struct.unpack_from(">HHI", data, off)
|
||||
out.append(Beat(beat=beat, tempo=tempo, time=time))
|
||||
return out
|
||||
|
||||
|
||||
_DECODERS = {"PCOB": _pcob, "PCO2": _pco2, "PQTZ": _pqtz}
|
||||
|
||||
|
||||
__all__ = [
|
||||
"AnlzError", "AnlzFile", "Beat", "CueEntry", "LIST_HOT", "LIST_MEMORY",
|
||||
"NO_LOOP", "Tag", "parse", "parse_file",
|
||||
]
|
||||
@@ -63,7 +63,7 @@ class RekordboxDriver:
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
def open(self, path: Path) -> RekordboxAdapter:
|
||||
def open(self, path: Path, *, read_only: bool = False) -> RekordboxAdapter:
|
||||
return RekordboxAdapter(path)
|
||||
|
||||
def detect(self) -> list[dict]:
|
||||
|
||||
@@ -25,7 +25,7 @@ class TraktorDriver:
|
||||
return False
|
||||
return b"<NML" in head and b"VERSION=" in head
|
||||
|
||||
def open(self, path: Path) -> TraktorAdapter:
|
||||
def open(self, path: Path, *, read_only: bool = False) -> TraktorAdapter:
|
||||
return TraktorAdapter(path)
|
||||
|
||||
def detect(self) -> list[dict]:
|
||||
|
||||
@@ -22,7 +22,6 @@ import copy
|
||||
import math
|
||||
import threading
|
||||
import uuid as uuidlib
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from traktor_nml_utils import (
|
||||
@@ -46,7 +45,7 @@ from traktor_nml_utils.models.collection import (
|
||||
)
|
||||
from xsdata.formats.dataclass.serializers import XmlSerializer
|
||||
|
||||
from ...core.adapter import InvalidCommand, SaveOutcome, StemSwapResult
|
||||
from ...core.adapter import FileTagResult, InvalidCommand, SaveOutcome, StemSwapResult
|
||||
from ...core.edit_journal import EditJournal
|
||||
from ...core.pathmap import common_dir_prefix
|
||||
from ...core.pathmap import PathMapping
|
||||
@@ -71,15 +70,6 @@ class PlaylistError(InvalidCommand):
|
||||
"""
|
||||
|
||||
|
||||
@dataclass
|
||||
class FileTagResult:
|
||||
track_id: str
|
||||
file: str
|
||||
ok: bool
|
||||
status: str # "written" | "file-not-found" | "unsupported-format" | "error"
|
||||
detail: str = ""
|
||||
|
||||
|
||||
class TraktorStore:
|
||||
def __init__(self, nml_path: Path):
|
||||
self.nml_path = Path(nml_path)
|
||||
|
||||
@@ -79,7 +79,7 @@ class AppState:
|
||||
rests on, and an adapter is the thing that knows whether it is true —
|
||||
so it is asserted here rather than assumed everywhere else.
|
||||
"""
|
||||
adapter = registry.open_library(path)
|
||||
adapter = registry.open_library(path, read_only=True)
|
||||
if adapter.capabilities().writable:
|
||||
if hasattr(adapter, "close"):
|
||||
try:
|
||||
@@ -87,7 +87,7 @@ class AppState:
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
raise ValueError(
|
||||
f"{path} is a writable library; only read-only sources "
|
||||
f"{path} cannot be opened read-only; only a library that can "
|
||||
"(such as a OneLibrary drive) can be opened as a source"
|
||||
)
|
||||
self.close_source()
|
||||
|
||||
@@ -28,6 +28,21 @@ from .pathmap import PathMapping
|
||||
from .relocate import PathGroup
|
||||
|
||||
|
||||
@dataclass
|
||||
class FileTagResult:
|
||||
"""One audio-file tag write a save made — the `SaveOutcome.tag_results` item.
|
||||
|
||||
Promoted from the Traktor store when OneLibrary became the second platform
|
||||
that writes edited fields into the audio files themselves.
|
||||
"""
|
||||
|
||||
track_id: str
|
||||
file: str
|
||||
ok: bool
|
||||
status: str # "written" | "file-not-found" | "unsupported-format" | "error"
|
||||
detail: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class SaveOutcome:
|
||||
"""What a save produced, in terms every platform can answer.
|
||||
@@ -274,7 +289,11 @@ class LibraryDriver(Protocol):
|
||||
selects: str
|
||||
|
||||
def can_open(self, path: Path) -> bool: ...
|
||||
def open(self, path: Path) -> LibraryAdapter: ...
|
||||
# `read_only` opens a library only to READ it, alongside the loaded one (the
|
||||
# sidebar's Devices). An adapter that honours it reports `writable=False`
|
||||
# with cause `browsing`; one that ignores it still reports writable, and the
|
||||
# caller — `AppState.open_source` — refuses it, so ignoring is safe.
|
||||
def open(self, path: Path, *, read_only: bool = False) -> LibraryAdapter: ...
|
||||
# OPTIONAL. What to call an opened library on screen. Only the adapter can
|
||||
# answer for a platform where one library has more than one valid path —
|
||||
# the filename is otherwise assumed, and that assumption is wrong for a
|
||||
|
||||
@@ -22,7 +22,10 @@ from pydantic import BaseModel
|
||||
# permanent refusal protecting their other machines.
|
||||
# `not_in_library` is a folder of loose files being browsed: nothing there is a
|
||||
# library to write to, and the way to edit one is to add it to the collection.
|
||||
ReadonlyCause = Literal["platform_incomplete", "cloud_synced", "not_in_library"]
|
||||
# `browsing` is an editable library opened only to READ alongside the loaded one
|
||||
# (a OneLibrary stick in the sidebar's Devices): the way to edit it is to open it
|
||||
# as THE library, which one SaveBar and one dirty state can then follow.
|
||||
ReadonlyCause = Literal["platform_incomplete", "cloud_synced", "not_in_library", "browsing"]
|
||||
|
||||
CueType = Literal["cue", "fade_in", "fade_out", "load", "loop"]
|
||||
CueRole = Literal["hotcue", "memory"]
|
||||
|
||||
@@ -44,8 +44,8 @@ def driver_for(path: Path) -> LibraryDriver:
|
||||
raise LibraryNotSupported(f"No DJ library Konduktor recognises at {path}")
|
||||
|
||||
|
||||
def open_library(path: Path):
|
||||
return driver_for(path).open(path)
|
||||
def open_library(path: Path, *, read_only: bool = False):
|
||||
return driver_for(path).open(path, read_only=read_only)
|
||||
|
||||
|
||||
def describe(path: Path) -> dict:
|
||||
|
||||
@@ -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_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py test_discard.py; do
|
||||
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py test_discard.py; do
|
||||
echo "──────────────────────────────────────────"
|
||||
echo "▶ $t"
|
||||
echo "──────────────────────────────────────────"
|
||||
|
||||
+15
-5
@@ -118,14 +118,24 @@ else:
|
||||
RekordboxAdapter(work).track(track.id).title == title)
|
||||
del before
|
||||
|
||||
print("== read-only ==")
|
||||
print("== a OneLibrary drive (editable as THE library) ==")
|
||||
# A COPY: an editable drive must never be the checked-in fixture.
|
||||
os.environ["KONDUKTOR_NML"] = ""
|
||||
drive = Path(tempfile.mkdtemp()) / "Dingus"
|
||||
shutil.copytree(FIXTURE, drive, ignore=shutil.ignore_patterns("rekordbox-edited"))
|
||||
db_file = drive / "PIONEER" / "rekordbox" / "exportLibrary.db"
|
||||
on_disk = db_file.read_bytes()
|
||||
track_id = "/Contents/Loopmasters/UnknownAlbum/Demo Track 1.mp3"
|
||||
with TestClient(main.app) as c:
|
||||
r = c.post("/api/library/open", json={"path": str(FIXTURE)})
|
||||
r = c.post("/api/library/open", json={"path": str(drive)})
|
||||
check("the drive opens as the library", r.status_code == 200, f"{r.status_code} {r.text[:200]}")
|
||||
if r.status_code == 200:
|
||||
check("a read-only library has nothing to discard (409)", c.post("/api/discard").status_code == 409)
|
||||
else:
|
||||
print(f" (skipped: fixture did not open: {r.status_code})")
|
||||
c.patch("/api/tracks", json={"track_id": track_id, "fields": {"title": "Thrown away"}})
|
||||
check("the edit is held", main.STATE.adapter.dirty)
|
||||
check("discard succeeds", c.post("/api/discard").status_code == 200)
|
||||
check("and drops the edit",
|
||||
main.STATE.adapter.track(track_id).title.startswith("Demo Track 1"))
|
||||
check("the drive was never written", db_file.read_bytes() == on_disk)
|
||||
|
||||
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -228,7 +228,9 @@ with TestClient(main.app, raise_server_exceptions=False) as c:
|
||||
rb.close()
|
||||
|
||||
print("== a library that cannot take tracks refuses the route ==")
|
||||
fixture = Path(__file__).resolve().parent / "fixtures" / "onelibrary"
|
||||
# A COPY: opened as THE library, a OneLibrary drive is editable.
|
||||
fixture = Path(tempfile.mkdtemp()) / "onelibrary"
|
||||
shutil.copytree(Path(__file__).resolve().parent / "fixtures" / "onelibrary", fixture)
|
||||
r = c.post("/api/library/open", json={"path": str(fixture)})
|
||||
if r.status_code == 200:
|
||||
check("the add preview is refused (422)",
|
||||
|
||||
@@ -89,7 +89,8 @@ def stage(src: OneLibraryAdapter, music: Path) -> list[NewTrack]:
|
||||
|
||||
print("== a drive's tracks land in the collection ==")
|
||||
nml, music, original = fresh_collection()
|
||||
source = OneLibraryAdapter(FIXTURE)
|
||||
# As the app opens a device: read-only (a drive opened as THE library is editable).
|
||||
source = OneLibraryAdapter(FIXTURE, read_only=True)
|
||||
dest = TraktorAdapter(nml)
|
||||
before = len(dest.tracks)
|
||||
items = stage(source, music)
|
||||
|
||||
@@ -112,9 +112,11 @@ class _Entry(dict):
|
||||
|
||||
|
||||
class _Tag:
|
||||
"""A stand-in for `anlz_file.Tag`: a type and its decoded entries."""
|
||||
|
||||
def __init__(self, tag_type, entries):
|
||||
self.type = tag_type
|
||||
self.struct = type("S", (), {"content": type("C", (), {"entries": entries})()})()
|
||||
self.entries = entries
|
||||
|
||||
|
||||
class _Anlz:
|
||||
@@ -174,6 +176,49 @@ check("nothing read from a drive claims to be editable",
|
||||
all(not c.editable for c in merged))
|
||||
|
||||
|
||||
print("== a stick rekordbox has EDITED ==")
|
||||
# rekordbox 7 writes COMPACT cue entries when it edits a stick, where an export
|
||||
# writes 88-byte ones: a hot cue it added is a 48-byte PCP2, a memory cue a
|
||||
# 44-byte one with no colour at all. pyrekordbox raised PaddingError on the
|
||||
# latter, the whole .EXT failed to parse, and the reader fell back to the .DAT —
|
||||
# losing pads D-E and every colour. These files are Goober's after Ben edited it
|
||||
# in rekordbox 7 (2026-10-01), trimmed to PPTH + the cue tags, byte for byte.
|
||||
from konduktor.adapters.rekordbox import anlz_file # noqa: E402
|
||||
|
||||
EDITED = FIXTURE / "rekordbox-edited"
|
||||
for f in sorted(FIXTURE.glob("PIONEER/USBANLZ/*/*/ANLZ*")) + sorted(EDITED.glob("*.*")):
|
||||
raw = f.read_bytes()
|
||||
if anlz_file.parse(raw).to_bytes() != raw:
|
||||
check(f"{f.name} round-trips through the tag reader byte for byte", False)
|
||||
break
|
||||
else:
|
||||
check("every analysis file round-trips through the tag reader byte for byte", True)
|
||||
|
||||
nemean = cues_from_anlz(anlz_file.parse_file(EDITED / "nemean.DAT"),
|
||||
anlz_file.parse_file(EDITED / "nemean.EXT"))
|
||||
hot = [c for c in nemean if c.role == "hotcue"]
|
||||
check("the .EXT holding a 44-byte memory entry still parses: all five pads",
|
||||
[c.slot for c in sorted(hot, key=lambda c: c.slot)] == [0, 1, 2, 3, 4],
|
||||
str([c.slot for c in hot]))
|
||||
check("and their colours survive",
|
||||
{c.slot: c.color for c in hot} == {0: "#1AFF00", 1: "#00E0FF", 2: "#FF5E00",
|
||||
3: "#B300FF", 4: "#FF0000"},
|
||||
str({c.slot: c.color for c in hot}))
|
||||
memory = sorted((c for c in nemean if c.role == "memory"), key=lambda c: (c.start, c.type))
|
||||
check("a memory cue ON a memory loop's start is not merged into it",
|
||||
[(round(c.start * 1000), c.type) for c in memory] == [(23, "cue"), (121402, "cue"), (121402, "loop")],
|
||||
str([(c.start, c.type) for c in memory]))
|
||||
check("the compact memory entry has no colour, rather than black",
|
||||
all(c.color is None for c in memory))
|
||||
|
||||
demo2 = cues_from_anlz(anlz_file.parse_file(EDITED / "demo-track-2.DAT"),
|
||||
anlz_file.parse_file(EDITED / "demo-track-2.EXT"))
|
||||
pad_e = [c for c in demo2 if c.slot == 4]
|
||||
check("a 48-byte hot cue (added in rekordbox) reads with its colour",
|
||||
len(pad_e) == 1 and pad_e[0].color == "#00FF30" and round(pad_e[0].start * 1000) == 47525,
|
||||
str(pad_e))
|
||||
|
||||
|
||||
# ---- the real drive ------------------------------------------------------
|
||||
if not (FIXTURE / "PIONEER" / "rekordbox" / "exportLibrary.db").is_file():
|
||||
print(f"\nSKIP: no fixture drive at {FIXTURE}")
|
||||
@@ -194,7 +239,13 @@ 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)
|
||||
# A drive is now WRITABLE, so the adapter under test opens a COPY — a stray save
|
||||
# here once rewrote the checked-in fixture. The copy keeps the fixture's folder
|
||||
# name, which is what the drive's label is checked against.
|
||||
DRIVE = Path(tempfile.mkdtemp(prefix="konduktor-ol-drive-")) / FIXTURE.name
|
||||
shutil.copytree(FIXTURE, DRIVE)
|
||||
FIXTURE_DB_BYTES = (FIXTURE / "PIONEER" / "rekordbox" / "exportLibrary.db").read_bytes()
|
||||
adapter = OneLibraryAdapter(DRIVE)
|
||||
check("implements the LibraryAdapter protocol", isinstance(adapter, LibraryAdapter))
|
||||
|
||||
print("== the projection ==")
|
||||
@@ -216,7 +267,7 @@ check("comment comes through", (one.comment or "").startswith("Tracks by"))
|
||||
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"))
|
||||
one.filepath == str(DRIVE / "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)
|
||||
|
||||
@@ -280,8 +331,8 @@ 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("on an editable drive a playlist offers every edit",
|
||||
all(n.can_rename and n.can_delete and n.can_add_tracks and 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 ==")
|
||||
@@ -289,9 +340,7 @@ 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("opened as THE library, a drive is writable", caps.writable is True and caps.readonly_cause is None)
|
||||
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.
|
||||
@@ -300,16 +349,34 @@ check("cue colour is free RGB here, unlike master.db's palette", caps.cues.color
|
||||
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("cues and the grid are not editable YET", not caps.cues.editable and not caps.grid.editable)
|
||||
check("the editable fields are the Rekordbox adapter's set",
|
||||
caps.tracks.editable_fields == sorted(["title", "artist", "album", "genre", "label",
|
||||
"remixer", "comment", "rating", "release_date"]),
|
||||
str(caps.tracks.editable_fields))
|
||||
check("adding and removing tracks are not offered YET",
|
||||
not caps.tracks.addable and not caps.tracks.removable)
|
||||
check("playlists can be reordered", caps.playlists.reorder is True)
|
||||
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)
|
||||
check("another app's write is caught at save, not risked", caps.save.overwrite_risk == "none")
|
||||
check("Save is named for the drive", caps.save.app_name == FIXTURE.name, caps.save.app_name)
|
||||
|
||||
print("== every command is refused ==")
|
||||
print("== opened for BROWSING (the sidebar's Devices) ==")
|
||||
browse = OneLibraryAdapter(DRIVE, read_only=True)
|
||||
bcaps = browse.capabilities()
|
||||
check("a browsing drive is read-only", bcaps.writable is False)
|
||||
check("because it is being browsed, not because the platform is incomplete",
|
||||
bcaps.readonly_cause == "browsing", str(bcaps.readonly_cause))
|
||||
check("and the registry opens it that way when asked",
|
||||
registry.open_library(DRIVE, read_only=True).capabilities().readonly_cause == "browsing")
|
||||
bnode = browse.playlist_tree()[0]
|
||||
check("its playlists offer nothing",
|
||||
not (bnode.can_add_tracks or bnode.can_reorder or bnode.can_rename or bnode.can_delete))
|
||||
|
||||
print("== what 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")),
|
||||
@@ -335,9 +402,28 @@ COMMANDS = [
|
||||
("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)
|
||||
# Browsing: EVERY command refuses — the ones that work on an editable drive too.
|
||||
BROWSE = [(n, (lambda f=f: f(browse))) for n, f in [
|
||||
("set_track_metadata", lambda a: a.set_track_metadata(one.id, {"title": "x"})),
|
||||
("create_playlist", lambda a: a.create_playlist("x")),
|
||||
("create_folder", lambda a: a.create_folder("x")),
|
||||
("rename_playlist", lambda a: a.rename_playlist(node.id, "x")),
|
||||
("delete_playlist", lambda a: a.delete_playlist(node.id)),
|
||||
("set_playlist_entries", lambda a: a.set_playlist_entries(node.id, [])),
|
||||
("save", lambda a: a.save()),
|
||||
]]
|
||||
refused = [name for name, fn in BROWSE if not _raises(fn, Unsupported)]
|
||||
check("a browsing drive refuses every edit, Save included", not refused, "; ".join(refused))
|
||||
check("and is never dirty", browse.dirty is False)
|
||||
browse.close()
|
||||
|
||||
# Editable: what has not landed yet still refuses (each with its flag False).
|
||||
LANDED = {"set_track_metadata", "create_playlist", "rename_playlist", "delete_playlist",
|
||||
"set_playlist_entries", "save"}
|
||||
pending = [(n, fn) for n, fn in COMMANDS if n not in LANDED]
|
||||
refused = [name for name, fn in pending if not _raises(fn, Unsupported)]
|
||||
check(f"the {len(pending)} commands not written yet raise Unsupported", not refused, "; ".join(refused))
|
||||
check("refusing leaves nothing dirty", adapter.dirty is False)
|
||||
check("an unknown track is a NotFound, not an Unsupported",
|
||||
_raises(lambda: adapter.audio_path("no-such-track"), NotFound))
|
||||
|
||||
@@ -360,6 +446,8 @@ check("detection of unplugged drives is empty, not an error",
|
||||
|
||||
adapter.close()
|
||||
check("closing twice is safe", adapter.close() is None)
|
||||
check("the checked-in fixture was never written",
|
||||
(FIXTURE / "PIONEER" / "rekordbox" / "exportLibrary.db").read_bytes() == FIXTURE_DB_BYTES)
|
||||
|
||||
print()
|
||||
print("RESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
|
||||
@@ -0,0 +1,354 @@
|
||||
"""OneLibrary's analogue of `test_rekordbox_fidelity.py`: an edit changes only
|
||||
what it was supposed to change, checked as a FULL TABLE DUMP before and after
|
||||
(a byte diff means nothing against SQLite), on a temp copy of the fixture drive.
|
||||
|
||||
The expected diffs are rekordbox's own, MEASURED on Goober (2026-10-01; see the
|
||||
editing discussion log): a title edit changes `content.title` and nothing else —
|
||||
no update counter moves — a new playlist goes on top with its siblings shifted
|
||||
down one, and a reorder renumbers that playlist's entries from 1.
|
||||
|
||||
And the properties a STICK needs that a desktop library does not: nothing
|
||||
reaches the drive before Save, the drive is replaced in one rename, another
|
||||
app's write since open is refused rather than undone, an unplugged drive keeps
|
||||
the edits for a retry, stale `-wal`/`-shm` files are deleted, and a backup of
|
||||
the drive's database lands in app-data first.
|
||||
"""
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
APPDATA = Path(tempfile.mkdtemp(prefix="konduktor-olfid-appdata-"))
|
||||
os.environ["KONDUKTOR_DATA_DIR"] = str(APPDATA)
|
||||
|
||||
from konduktor.adapters.onelibrary.adapter import OneLibraryAdapter # noqa: E402
|
||||
from konduktor.core.adapter import InvalidCommand # noqa: E402
|
||||
|
||||
FIXTURE = Path(__file__).resolve().parent / "fixtures" / "onelibrary"
|
||||
TRACK_1 = "/Contents/Loopmasters/UnknownAlbum/Demo Track 1.mp3"
|
||||
TRACK_2 = "/Contents/Loopmasters/UnknownAlbum/Demo Track 2.mp3"
|
||||
|
||||
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
|
||||
return False
|
||||
return False
|
||||
|
||||
|
||||
# ---- the row-level dump/diff harness -------------------------------------
|
||||
LINK_TABLES = {"playlist_content", "history_content", "myTag_content", "hotCueBankList_cue"}
|
||||
|
||||
|
||||
def dump(db: Path) -> dict:
|
||||
"""Every row of every table; keyed by primary key, or by the whole row for
|
||||
the link tables, which have none."""
|
||||
import sqlcipher3.dbapi2 as sqlcipher
|
||||
from pyrekordbox.devicelib_plus.database import BLOB
|
||||
from pyrekordbox.utils import deobfuscate
|
||||
|
||||
con = sqlcipher.connect(str(db))
|
||||
con.execute(f"PRAGMA key='{deobfuscate(BLOB)}'")
|
||||
cur = con.cursor()
|
||||
names = [r[0] for r in cur.execute(
|
||||
"SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").fetchall()]
|
||||
out: dict[str, dict] = {}
|
||||
for table in names:
|
||||
cols = [r[1] for r in cur.execute(f'PRAGMA table_info("{table}")').fetchall()]
|
||||
rows = {}
|
||||
for r in cur.execute(f'SELECT * FROM "{table}"').fetchall():
|
||||
d = dict(zip(cols, r))
|
||||
key = "|".join(map(str, r)) if table in LINK_TABLES else str(r[0])
|
||||
rows[key] = d
|
||||
out[table] = rows
|
||||
con.close()
|
||||
return out
|
||||
|
||||
|
||||
def diff(before: dict, after: dict) -> list:
|
||||
changes = []
|
||||
for table in sorted(set(before) | set(after)):
|
||||
a, b = before.get(table, {}), after.get(table, {})
|
||||
for pk in sorted(set(a) | set(b)):
|
||||
if pk not in a:
|
||||
changes.append((table, pk, "INSERT", b[pk]))
|
||||
elif pk not in b:
|
||||
changes.append((table, pk, "DELETE", a[pk]))
|
||||
else:
|
||||
fields = {k: (a[pk][k], b[pk].get(k)) for k in a[pk] if a[pk][k] != b[pk].get(k)}
|
||||
if fields:
|
||||
changes.append((table, pk, "UPDATE", fields))
|
||||
return changes
|
||||
|
||||
|
||||
def describe(changes) -> str:
|
||||
return "; ".join(f"{t}/{pk} {kind}" for t, pk, kind, _ in changes) or "(none)"
|
||||
|
||||
|
||||
def fresh_drive() -> Path:
|
||||
root = Path(tempfile.mkdtemp(prefix="konduktor-olfid-")) / "Dingus"
|
||||
shutil.copytree(FIXTURE, root, ignore=shutil.ignore_patterns("rekordbox-edited"))
|
||||
return root
|
||||
|
||||
|
||||
def db_of(root: Path) -> Path:
|
||||
return root / "PIONEER" / "rekordbox" / "exportLibrary.db"
|
||||
|
||||
|
||||
# ---- A: nothing reaches the drive until Save --------------------------------
|
||||
print("== edits stay off the drive until Save ==")
|
||||
drive = fresh_drive()
|
||||
before_bytes = db_of(drive).read_bytes()
|
||||
before = dump(db_of(drive))
|
||||
a = OneLibraryAdapter(drive)
|
||||
check("opening writes nothing", db_of(drive).read_bytes() == before_bytes)
|
||||
check("and leaves no -wal/-shm on the drive",
|
||||
not any(db_of(drive).with_name(db_of(drive).name + s).exists() for s in ("-wal", "-shm")))
|
||||
a.set_track_metadata(TRACK_1, {"title": "Edited"})
|
||||
check("an edit makes the library dirty", a.dirty is True)
|
||||
check("and the projection shows it at once", a.track(TRACK_1).title == "Edited")
|
||||
check("but the drive's database is byte-identical", db_of(drive).read_bytes() == before_bytes)
|
||||
|
||||
print("== Discard ==")
|
||||
a.reload()
|
||||
check("discarding drops the edit", a.track(TRACK_1).title.startswith("Demo Track 1"), a.track(TRACK_1).title)
|
||||
check("and leaves nothing dirty", a.dirty is False)
|
||||
check("and the drive untouched", db_of(drive).read_bytes() == before_bytes)
|
||||
|
||||
# ---- B: a no-op save ----------------------------------------------------------
|
||||
print("== a no-op save ==")
|
||||
a.save()
|
||||
check("changes zero rows", diff(before, dump(db_of(drive))) == [], describe(diff(before, dump(db_of(drive)))))
|
||||
a.close()
|
||||
|
||||
# ---- C: one field, one column ---------------------------------------------------
|
||||
print("== a one-field edit changes exactly that column ==")
|
||||
drive = fresh_drive()
|
||||
before = dump(db_of(drive))
|
||||
a = OneLibraryAdapter(drive)
|
||||
a.set_track_metadata(TRACK_1, {"title": "Edited"})
|
||||
outcome = a.save()
|
||||
changes = diff(before, dump(db_of(drive)))
|
||||
check("exactly one row changed", len(changes) == 1, describe(changes))
|
||||
check("content.title, and no update counter (measured: rekordbox moves none)",
|
||||
changes and changes[0][0] == "content" and set(changes[0][3]) == {"title"}
|
||||
and changes[0][3]["title"][1] == "Edited", str(changes))
|
||||
check("the save is not dirty afterwards", a.dirty is False)
|
||||
check("and the adapter reads the saved drive", a.track(TRACK_1).title == "Edited")
|
||||
check("the save reports a summary of the edit", bool(outcome.summary), outcome.summary)
|
||||
check("no version-history snapshot (a drive is many files)", outcome.snapshot is None)
|
||||
|
||||
backups = sorted((APPDATA / "onelibrary" / "backups" / "Dingus").iterdir())
|
||||
check("a backup was written to app-data, not the drive", len(backups) >= 1)
|
||||
check("holding the database as it was BEFORE the save",
|
||||
dump(backups[-1] / "exportLibrary.db") == before)
|
||||
check("no partial file is left beside the database",
|
||||
not list(db_of(drive).parent.glob("*.konduktor-partial")))
|
||||
a.close()
|
||||
|
||||
print("== rating, comment, release date ==")
|
||||
drive = fresh_drive()
|
||||
before = dump(db_of(drive))
|
||||
a = OneLibraryAdapter(drive)
|
||||
a.set_track_metadata(TRACK_1, {"rating": 3})
|
||||
a.set_track_metadata(TRACK_2, {"comment": "", "release_date": "2021-03-04"})
|
||||
check("an out-of-range rating is refused", _raises(lambda: a.set_track_metadata(TRACK_1, {"rating": 6}),
|
||||
InvalidCommand))
|
||||
check("a malformed date is refused", _raises(lambda: a.set_track_metadata(TRACK_1, {"release_date": "soon"}),
|
||||
InvalidCommand))
|
||||
a.save()
|
||||
changes = {(t, pk): f for t, pk, kind, f in diff(before, dump(db_of(drive)))}
|
||||
row1 = next(f for (t, pk), f in changes.items() if t == "content" and pk == "1")
|
||||
row2 = next(f for (t, pk), f in changes.items() if t == "content" and pk == "2")
|
||||
check("rating is stored 0-5 directly", row1 == {"rating": (0, 3)}, str(row1))
|
||||
check("a cleared comment is '' as rekordbox stores it, not NULL",
|
||||
row2.get("djComment", (None, None))[1] == "", str(row2))
|
||||
check("a full date sets releaseYear AND releaseDate as YYYY-MM-DD text",
|
||||
row2.get("releaseYear", (0, 0))[1] == 2021 and row2.get("releaseDate", ("", ""))[1] == "2021-03-04",
|
||||
str(row2))
|
||||
check("and reads back", a.track(TRACK_2).release_date == "2021-03-04", str(a.track(TRACK_2).release_date))
|
||||
check("nothing else changed", len(changes) == 2, str(list(changes)))
|
||||
a.set_track_metadata(TRACK_2, {"release_date": "2019"})
|
||||
check("a bare year is releaseYear with an empty releaseDate",
|
||||
a._store.content(TRACK_2).releaseYear == 2019 and a.track(TRACK_2).release_date == "2019",
|
||||
str(a.track(TRACK_2).release_date))
|
||||
a.close()
|
||||
|
||||
print("== lookups are found or created ==")
|
||||
drive = fresh_drive()
|
||||
before = dump(db_of(drive))
|
||||
a = OneLibraryAdapter(drive)
|
||||
a.set_track_metadata(TRACK_1, {"artist": "Loopmasters"}) # already there
|
||||
check("an existing name is reused, not duplicated", a.dirty and a._store.content(TRACK_1).artist_id_artist == 1)
|
||||
a.set_track_metadata(TRACK_1, {"artist": "New Artist", "genre": "Techno"})
|
||||
check("the projection reads the NEW names (not the stale relationship)",
|
||||
a.track(TRACK_1).artist == "New Artist" and a.track(TRACK_1).genre == "Techno",
|
||||
f"{a.track(TRACK_1).artist} / {a.track(TRACK_1).genre}")
|
||||
a.set_track_metadata(TRACK_2, {"label": ""})
|
||||
check("clearing a lookup unsets it", a.track(TRACK_2).label is None)
|
||||
a.save()
|
||||
changes = diff(before, dump(db_of(drive)))
|
||||
inserts = [(t, f) for t, pk, kind, f in changes if kind == "INSERT"]
|
||||
check("one new artist and one new genre row",
|
||||
sorted(t for t, _ in inserts) == ["artist", "genre"], describe(changes))
|
||||
check("with nameForSearch NULL, as rekordbox leaves it",
|
||||
all(f.get("nameForSearch") is None for t, f in inserts if t == "artist"))
|
||||
a.close()
|
||||
|
||||
# ---- D: playlists, as rekordbox writes them ---------------------------------------
|
||||
print("== playlists ==")
|
||||
drive = fresh_drive()
|
||||
before = dump(db_of(drive))
|
||||
a = OneLibraryAdapter(drive)
|
||||
demos = a.playlist_tree()[0]
|
||||
new_id = a.create_playlist("Probe")
|
||||
tree = a.playlist_tree()
|
||||
check("a new playlist is listed FIRST (rekordbox puts it on top)",
|
||||
[n.name for n in tree] == ["Probe", "demos"], str([n.name for n in tree]))
|
||||
a.set_playlist_entries(new_id, [TRACK_2])
|
||||
a.set_playlist_entries(demos.id, [TRACK_2, TRACK_1])
|
||||
check("a reorder reads back in the new order", a.playlist_entries(demos.id) == [TRACK_2, TRACK_1])
|
||||
a.save()
|
||||
changes = diff(before, dump(db_of(drive)))
|
||||
pl = {pk: (kind, f) for t, pk, kind, f in changes if t == "playlist"}
|
||||
check("the new playlist row has sequenceNo 0, attribute 0, parent 0",
|
||||
pl.get(new_id, ("", {}))[0] == "INSERT"
|
||||
and {k: pl[new_id][1][k] for k in ("sequenceNo", "attribute", "playlist_id_parent")}
|
||||
== {"sequenceNo": 0, "attribute": 0, "playlist_id_parent": 0}, str(pl.get(new_id)))
|
||||
check("and its sibling moved down one", pl.get(demos.id) == ("UPDATE", {"sequenceNo": (0, 1)})
|
||||
or pl.get(demos.id, ("", {}))[1].get("sequenceNo", (None, None))[1]
|
||||
== before["playlist"][demos.id]["sequenceNo"] + 1, str(pl.get(demos.id)))
|
||||
entries = sorted((f["playlist_id"], f["content_id"], f["sequenceNo"])
|
||||
for t, pk, kind, f in changes if t == "playlist_content" and kind == "INSERT")
|
||||
check("entries are numbered from 1 (measured)",
|
||||
entries == sorted([(int(new_id), 2, 1), (int(demos.id), 2, 1), (int(demos.id), 1, 2)]), str(entries))
|
||||
check("no other table changed", {t for t, *_ in changes} == {"playlist", "playlist_content"},
|
||||
describe(changes))
|
||||
|
||||
folder = a.create_folder("Gigs")
|
||||
inner = a.create_playlist("Friday", folder)
|
||||
a.set_playlist_entries(inner, [TRACK_1])
|
||||
check("a playlist can only be created inside a FOLDER",
|
||||
_raises(lambda: a.create_playlist("x", demos.id), InvalidCommand))
|
||||
check("a nameless playlist is refused", _raises(lambda: a.create_playlist(" "), InvalidCommand))
|
||||
a.rename_playlist(inner, "Saturday")
|
||||
gigs = next(n for n in a.playlist_tree() if n.id == folder)
|
||||
check("a folder nests its playlist", [c.name for c in gigs.children] == ["Saturday"])
|
||||
a.save()
|
||||
mid = dump(db_of(drive))
|
||||
a.delete_playlist(folder)
|
||||
a.save()
|
||||
after = dump(db_of(drive))
|
||||
changes = diff(mid, after)
|
||||
check("deleting a folder deletes what is in it, entries included",
|
||||
sorted((t, kind) for t, pk, kind, _ in changes if kind == "DELETE")
|
||||
== [("playlist", "DELETE"), ("playlist", "DELETE"), ("playlist_content", "DELETE")],
|
||||
describe(changes))
|
||||
seqs = sorted(r["sequenceNo"] for r in after["playlist"].values() if r["playlist_id_parent"] == 0)
|
||||
check("and closes the gap among its siblings", seqs == list(range(len(seqs))), str(seqs))
|
||||
a.close()
|
||||
|
||||
# ---- E: a stick's hazards ------------------------------------------------------------
|
||||
print("== another app wrote the drive since it was opened ==")
|
||||
drive = fresh_drive()
|
||||
a = OneLibraryAdapter(drive)
|
||||
a.set_track_metadata(TRACK_1, {"title": "Mine"})
|
||||
theirs = db_of(drive).read_bytes()
|
||||
time.sleep(0.01)
|
||||
os.utime(db_of(drive)) # e.g. rekordbox saving the stick meanwhile
|
||||
check("Save refuses rather than undo it", _raises(a.save, InvalidCommand))
|
||||
check("the drive is exactly as the other app left it", db_of(drive).read_bytes() == theirs)
|
||||
check("and the edit is still pending", a.dirty and a.track(TRACK_1).title == "Mine")
|
||||
a.close()
|
||||
|
||||
print("== an unplugged drive ==")
|
||||
drive = fresh_drive()
|
||||
a = OneLibraryAdapter(drive)
|
||||
a.set_track_metadata(TRACK_1, {"title": "Kept"})
|
||||
parked = drive.parent / "unplugged"
|
||||
(drive / "PIONEER").rename(parked)
|
||||
check("Save refuses cleanly", _raises(a.save, InvalidCommand))
|
||||
check("keeping the edit", a.dirty and a.track(TRACK_1).title == "Kept")
|
||||
parked.rename(drive / "PIONEER")
|
||||
a.save()
|
||||
check("and saves it once the drive is back",
|
||||
dump(db_of(drive))["content"]["1"]["title"] == "Kept" and not a.dirty)
|
||||
a.close()
|
||||
|
||||
print("== stale SQLite sidecars ==")
|
||||
drive = fresh_drive()
|
||||
shm = db_of(drive).with_name("exportLibrary.db-shm")
|
||||
shm.write_bytes(b"\0" * 32768) # rekordbox leaves one on a stick it mounted
|
||||
a = OneLibraryAdapter(drive)
|
||||
a.set_track_metadata(TRACK_1, {"title": "x"})
|
||||
a.save()
|
||||
check("a stale -shm is deleted on save (SQLite would trust it)", not shm.exists())
|
||||
check("and the saved database opens", dump(db_of(drive))["content"]["1"]["title"] == "x")
|
||||
a.close()
|
||||
|
||||
print("== the drive is never held open ==")
|
||||
drive = fresh_drive()
|
||||
a = OneLibraryAdapter(drive)
|
||||
try:
|
||||
import subprocess
|
||||
|
||||
mine = subprocess.run(["lsof", "-Fn", "-p", str(os.getpid())], capture_output=True,
|
||||
text=True).stdout
|
||||
check("no file on the drive is open in this process",
|
||||
str(db_of(drive)) not in mine, "exportLibrary.db is open")
|
||||
except FileNotFoundError:
|
||||
print(" (lsof unavailable — skipped)")
|
||||
a.close()
|
||||
|
||||
print("== a read-only (browsing) drive ==")
|
||||
drive = fresh_drive()
|
||||
b = OneLibraryAdapter(drive, read_only=True)
|
||||
check("is not writable", b.capabilities().writable is False)
|
||||
b.close()
|
||||
check("closing removes its working copy",
|
||||
not any((APPDATA / "onelibrary" / "work").iterdir()))
|
||||
|
||||
print("== file tags (decision 5: as rekordbox does) ==")
|
||||
drive = fresh_drive()
|
||||
from stem_test_support import make_mp3 # noqa: E402
|
||||
|
||||
audio = drive / TRACK_1.lstrip("/")
|
||||
make_mp3(audio) # the fixture's MP3s are 12-byte placeholders
|
||||
a = OneLibraryAdapter(drive)
|
||||
a.set_track_metadata(TRACK_1, {"title": "Tagged", "artist": "Somebody", "rating": 4})
|
||||
outcome = a.save()
|
||||
import mutagen # noqa: E402
|
||||
|
||||
tags = mutagen.File(str(audio)).tags
|
||||
check("the edited title reaches the file's TIT2", str(tags.get("TIT2")) == "Tagged", str(tags.get("TIT2")))
|
||||
check("and the artist its TPE1", str(tags.get("TPE1")) == "Somebody")
|
||||
check("the rating does NOT (rekordbox keeps it library-only)", not tags.getall("POPM"))
|
||||
check("the write is reported", any(r.ok and r.track_id == TRACK_1 for r in outcome.tag_results),
|
||||
str(outcome.tag_results))
|
||||
(drive / TRACK_2.lstrip("/")).unlink() # its audio gone from the stick
|
||||
a.set_track_metadata(TRACK_2, {"title": "Missing"})
|
||||
outcome = a.save()
|
||||
check("a missing audio file is reported, not fatal",
|
||||
[r.status for r in outcome.tag_results] == ["file-not-found"] and not a.dirty
|
||||
and dump(db_of(drive))["content"]["2"]["title"] == "Missing", str(outcome.tag_results))
|
||||
a.close()
|
||||
|
||||
print()
|
||||
print("RESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
+1
-1
@@ -225,7 +225,7 @@ export interface SaveCapabilities {
|
||||
}
|
||||
|
||||
/** Why a library cannot be edited. A fact — lib/platformCopy.ts words it. */
|
||||
export type ReadonlyCause = 'platform_incomplete' | 'cloud_synced' | 'not_in_library'
|
||||
export type ReadonlyCause = 'platform_incomplete' | 'cloud_synced' | 'not_in_library' | 'browsing'
|
||||
|
||||
export interface Capabilities {
|
||||
platform: Platform
|
||||
|
||||
@@ -55,6 +55,8 @@ export function readOnlyNotice(caps: Capabilities): string | null {
|
||||
return `This ${caps.save.app_name} library is synced with ${caps.save.app_name} Cloud, so Konduktor will not write to it — an edit it did not make could break syncing on your other devices.`
|
||||
case 'not_in_library':
|
||||
return 'This file is not in your collection yet — add it to edit its tags, cues or beatgrid.'
|
||||
case 'browsing':
|
||||
return `This ${caps.save.app_name} drive is open for browsing. Open it for editing to change it.`
|
||||
case 'platform_incomplete':
|
||||
default:
|
||||
return `Konduktor can read ${caps.save.app_name} libraries but cannot save changes to them yet.`
|
||||
|
||||
Reference in new issue
Block a user