mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Begun implementing OneLibrary editing
This commit is contained in:
1 parent
2784879872
commit
775e94168c
28 files changed
+1392
-152
No files matched your search
@@ -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
|
||||
try:
|
||||
db.close()
|
||||
except Exception: # noqa: BLE001 — closing must not raise
|
||||
log.debug("OneLibrary session close failed", exc_info=True)
|
||||
engine = getattr(db, "engine", None)
|
||||
if engine is not None:
|
||||
try:
|
||||
engine.dispose()
|
||||
except Exception: # noqa: BLE001
|
||||
log.debug("OneLibrary engine dispose failed", exc_info=True)
|
||||
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:
|
||||
step()
|
||||
except Exception: # noqa: BLE001 — closing must not raise
|
||||
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:
|
||||
|
||||
Reference in new issue
Block a user