Implemented OneLibrary track addition and removal

This commit is contained in:
patben8 committed 2026-10-01 16:43:37 +02:00
1 parent c5280a95f2
commit 7960a5a68f
20 files changed
+822 -85

No files matched your search

@@ -28,6 +28,7 @@ from ...core.pathmap import PathMapping, common_dir_prefix
from ...core.query import TrackIndex
from ..rekordbox import palette
from ..rekordbox.cue_types import WRITABLE_CUE_TYPES
from ...exporter import MANIFEST_NAME
from . import capabilities as caps
from . import projection
from .store import OneLibraryStore
@@ -62,7 +63,9 @@ class OneLibraryAdapter:
self._index.rebuild(tracks)
def _drive_path(self, row) -> str | None:
resolved = self._store.layout.resolve(getattr(row, "path", None))
# Through the store: an added track plays from its incoming copy until
# Save puts it in place.
resolved = self._store.resolve_audio(getattr(row, "path", None))
return str(resolved) if resolved is not None else None
def close(self) -> None:
@@ -93,6 +96,8 @@ class OneLibraryAdapter:
version=self._store.db_version,
read_only=self.read_only,
editable_fields=sorted(OneLibraryStore.EDITABLE_FIELDS),
# A drive an export set wrote carries the export's manifest at its root.
managed_by_export=(self._store.layout.root / MANIFEST_NAME).is_file(),
)
# ---- read ------------------------------------------------------------
@@ -257,7 +262,11 @@ class OneLibraryAdapter:
def save(self):
self._require_writable("Saving")
return self._store.save()
outcome = self._store.save()
# Save MOVES files (an added track's audio leaves its incoming copy), so
# the projection is rebuilt from what is now on the drive.
self._rebuild()
return outcome
def snapshot(self) -> bytes:
raise Unsupported("OneLibrary drives are not versioned by Konduktor")
@@ -278,11 +287,101 @@ class OneLibraryAdapter:
if self.read_only:
self._refuse(what)
# ---- audio placement (`tracks.places_audio`) ----------------------------
def audio_home(self) -> Path:
return self._store.audio_home()
def place_audio(self, source: Path, track) -> Path | None:
self._require_writable("Adding tracks")
return self._store.place_audio(source, track)
def add_tracks(self, items: list, *, checkpoint=None) -> list[str]:
self._refuse("Adding tracks")
"""Add tracks, each arriving ready to prep — as the Rekordbox adapter does.
A drive keeps the beatgrid, cues and waveforms in per-track analysis
files, and rekordbox shows neither grid nor cues without them, so every
file is decoded ONCE here and its `.DAT`/`.EXT`/`.2EX` built by the
OneLibrary exporter's own writer — the files rekordbox 7 was verified
to read. A file with no grid of its own gets Konduktor's.
Two phases, as in Rekordbox: FIRST the slow, cancellable part (decoding,
grid detection, building the analysis and artwork bytes) before the
library is touched; THEN the rows, with hot cues replayed through the
ordinary `set_cue` so they keep its conventions. Memory cues — and a hot
cue with no free pad — cross as memory cues, written with the files.
`audio_path` is where `place_audio` said to copy it (or the file itself,
already on the stick); Save moves copies into place.
"""
from ...core import audio_tags, grid_detect, waveform
from ...core.export import ExportTrack
from ..rekordbox import artwork, timebase
from .export import OneLibraryExporter
self._require_writable("Adding tracks")
exporter = OneLibraryExporter()
prepared = []
total = len(items)
for n, item in enumerate(items, start=1):
audio = Path(item.audio_path)
if checkpoint is not None:
checkpoint(f"Analysing {item.track.title or audio.name} ({n}/{total})", step=n, of=total)
if not audio.is_file():
raise InvalidCommand(f"No audio file at {audio}")
try:
rel = self._store.drive_relative(self._store.final_of(audio))
except ValueError:
raise InvalidCommand(f"{audio} is not on this drive") from None
samples = waveform.decode(audio)
measured = waveform.analyse_samples(samples, lead=timebase.offset(audio))
markers = list(item.cues.grid_markers) if item.cues else []
if not markers and samples is not None:
try:
found = grid_detect.detect_grid(str(audio), y=samples, sr=waveform.SR)
markers = [GridMarker(start=found.anchor, bpm=found.bpm)]
except ValueError:
pass # no pulse to fit (a one-shot, silence): no grid
hot, memory, taken = [], [], set()
for cue in sorted((item.cues.cues if item.cues else []), key=lambda c: c.start):
if (cue.role == "hotcue" and cue.slot is not None
and 0 <= cue.slot < caps.HOTCUE_SLOTS and cue.slot not in taken):
hot.append(cue)
taken.add(cue.slot)
else:
memory.append(cue.model_copy(update={"role": "memory", "slot": None}))
export_track = ExportTrack(track=item.track, destination=audio,
cues=TrackCues(grid_markers=markers, cues=memory))
# Decoded once above; the writer must not decode it again.
export_track.waveform = lambda *, lead=0.0, m=measured: m
art = item.art or audio_tags.read_cover(audio)
jpegs = artwork.pioneer_jpegs(art[0]) if art else None
length = item.track.length or (int(measured.duration) if measured else None)
prepared.append((item, audio, rel, exporter.anlz_files(export_track, rel), jpegs,
markers, hot, length))
added: list[str] = []
for item, audio, rel, anlz, jpegs, markers, hot, length in prepared:
track_id = self._store.add_track(
audio, item.track, rel=rel, anlz_rel=self._store._anlz_rel(rel), anlz=anlz,
jpegs=jpegs, bpm=markers[0].bpm if markers else item.track.bpm, length=length)
for cue in hot:
self._store.set_cue(track_id, slot=cue.slot, start_sec=cue.start,
cue_type="loop" if cue.length else "cue",
length_sec=cue.length or 0.0, name=cue.name)
code, _rgb = palette.code_for(cue.color)
if cue.color and code:
self._store.set_cue_color(track_id, cue.slot, code)
added.append(track_id)
self._rebuild()
return added
def remove_tracks(self, track_ids: list[str]) -> int:
self._refuse("Removing tracks")
"""Remove tracks — and, on a stick, their audio and analysis files at Save
(decision 3: a stick's audio belongs to its library)."""
self._require_writable("Removing tracks")
n = self._store.remove_tracks(track_ids)
if n:
self._rebuild()
return n
def apply_stem_swaps(self, swaps, *, add_to_playlist=None):
self._refuse("Converting tracks to stems")
@@ -1,8 +1,8 @@
"""What a OneLibrary drive can persist.
Opened as THE library, a drive is writable, and the per-feature flags say which
edits have landed: track metadata, playlists, hot cues and the grid so far;
adding and removing tracks are still False, so the UI never offers an edit the adapter
edits have landed: track metadata, playlists, hot cues, the grid, and adding
and removing tracks, 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.
@@ -50,6 +50,7 @@ def capabilities_for(
*,
read_only: bool = False,
editable_fields: list[str] | None = None,
managed_by_export: bool = False,
) -> Capabilities:
return Capabilities(
platform="onelibrary",
@@ -78,6 +79,12 @@ def capabilities_for(
# The Rekordbox adapter's set: `producer`/`mix` have no column.
editable_fields=sorted(editable_fields or []),
media_kinds=["audio", "stem"],
# A stick's audio belongs to its library: added files are copied onto
# it (laid out as rekordbox does) and a removed track's file goes
# with it, at Save — so the library, not the user, places the audio.
addable=not read_only,
removable=not read_only,
places_audio=True,
# `artwork` gates EDITING, which Rekordbox does not do yet either
# (parity). Reading works: `store.cover_art` follows
# `content.image_id` -> `image.path`.
@@ -100,6 +107,7 @@ def capabilities_for(
# not risked: the store fingerprints the database at open and
# refuses to save over a change it did not make.
overwrite_risk="none",
managed_by_export=managed_by_export,
# A drive is a database plus N analysis files plus the audio itself,
# so there is no single blob that IS the library — the same reason
# Rekordbox libraries are not versioned.
@@ -17,24 +17,24 @@ playlist_id)`, artwork id = `image_id` — all checked on Goober. So the OneLibr
database IS the answer for every row the pdb shares with it.
**An edit, not a regeneration.** The stick's own `export.pdb` is edited in place
(`pdb.PdbEditor`): only the tracks, the four lookup tables and the playlist tree
and entries are candidates, a table is rewritten only if one of its rows changed,
(`pdb.PdbEditor`): only the tracks, the lookup tables (artist, album, genre,
label, key), artwork and the playlist tree and entries are candidates, a table is rewritten only if one of its rows changed,
and an unchanged row keeps rekordbox's bytes. A changed TRACK row is the old row
with the edited fields overwritten, so everything the pdb holds that OneLibrary
does not — the phrase-analysis strings, the `masterDbId` halves, play counts,
dates — survives. History, colours, menus, artwork, keys and `exportExt.pdb` are
never touched.
dates — survives. History, colours, menus and `exportExt.pdb` are never touched.
"""
from __future__ import annotations
import re
import struct
from pathlib import Path
from ..rekordbox import pdb
#: Tables this rebuild owns. Everything else in the file is left as it is.
_OWNED = (pdb.TRACKS, pdb.ARTISTS, pdb.ALBUMS, pdb.GENRES, pdb.LABELS,
pdb.PLAYLIST_TREE, pdb.PLAYLIST_ENTRIES)
_OWNED = (pdb.TRACKS, pdb.ARTISTS, pdb.ALBUMS, pdb.GENRES, pdb.LABELS, pdb.KEYS,
pdb.ARTWORK, pdb.PLAYLIST_TREE, pdb.PLAYLIST_ENTRIES)
def _lookup_name(table: int, row: bytes) -> str:
@@ -46,9 +46,17 @@ def _lookup_name(table: int, row: bytes) -> str:
if table == pdb.ALBUMS:
sub, _shift, _u, _artist, _rid, _u3, _b, ofs = struct.unpack_from("<HHIIIIBB", row, 0)
return pdb.read_dsql(row, ofs)
if table == pdb.KEYS:
return pdb.read_dsql(row, 8)
return pdb.read_dsql(row, 4)
def _pdb_art_path(path: str | None) -> str:
"""OneLibrary's `image.path` names the `b<n>` file; export.pdb's artwork row
the byte-identical `a<n>` beside it (as on Goober, and as rekordbox writes)."""
return re.sub(r"/b(\d+)(\.jpg)$", r"/a\1\2", path or "")
def _tree_value(row: bytes) -> tuple:
parent, _u, sort, rid, folder = struct.unpack_from("<5I", row, 0)
return parent, sort, rid, bool(folder), pdb.read_dsql(row, 20)
@@ -94,6 +102,7 @@ def rebuild(existing: bytes, session) -> bytes | None:
(pdb.ALBUMS, "SELECT album_id, name FROM album", pdb.album_row),
(pdb.GENRES, "SELECT genre_id, name FROM genre", pdb.id_string_row),
(pdb.LABELS, "SELECT label_id, name FROM label", pdb.id_string_row),
(pdb.KEYS, "SELECT key_id, name FROM key", pdb.key_row),
):
want = {int(i): (name or "", (lambda i=i, n=name, b=build: b(int(i), n or "")))
for i, name in session.execute(text(sql))}
@@ -102,6 +111,13 @@ def rebuild(existing: bytes, session) -> bytes | None:
if merged is not None:
tables[table] = merged
want = {int(i): (_pdb_art_path(path), (lambda i=i, p=path: pdb.id_string_row(int(i), _pdb_art_path(p))))
for i, path in session.execute(text("SELECT image_id, path FROM image"))}
merged = _merge(pdb.table_rows(existing, pdb.ARTWORK), want, pdb.ARTWORK,
lambda row, value: pdb.read_dsql(row, 4) == value)
if merged is not None:
tables[pdb.ARTWORK] = merged
# ---- tracks -----------------------------------------------------------------
old_tracks = {pdb.row_id(pdb.TRACKS, r): r for r in pdb.table_rows(existing, pdb.TRACKS)}
want = {}
+28 -10
View File
@@ -265,21 +265,21 @@ class OneLibraryExporter:
n = counter["next"]
folder = root / "PIONEER" / "Artwork" / "00001"
folder.mkdir(parents=True, exist_ok=True)
small, medium = jpegs
files = []
for letter in ("a", "b"):
for suffix, data in (("", small), ("_m", medium)):
path = folder / f"{letter}{n}{suffix}.jpg"
path.write_bytes(data)
files.append(path)
for rel, data in art_files(n, jpegs):
path = root / rel.lstrip("/")
path.write_bytes(data)
files.append(path)
con.execute("INSERT INTO image (image_id, path) VALUES (?, ?)",
(n, f"/PIONEER/Artwork/00001/b{n}.jpg"))
return n, files
# ---- the analysis files --------------------------------------------------
def _write_anlz(self, item: ExportTrack, rel: str, dat: Path) -> list[Path]:
"""The `.DAT`, `.EXT` and `.2EX`, as rekordbox 7 writes them.
def anlz_files(self, item: ExportTrack, rel: str) -> list[tuple[str, bytes]]:
"""The `.DAT`, `.EXT` and `.2EX` as `(suffix, bytes)`, as rekordbox 7 writes
them — built, not written, so a library adding a track to a stick can hold
them until Save (`OneLibraryStore.add_track`).
All three, and every cue list, even for a track with no cues: rekordbox
never produces a track without them, and `PCO2` — the complete list,
@@ -318,9 +318,18 @@ class OneLibraryExporter:
tags += previews
tags += W.cue_tags(cues, extended=False)
ext = [W.path_tag(rel), *ext_waves[:1], *W.cue_tags(cues, extended=True), *ext_waves[1:]]
written = [W.write_anlz(dat, tags), W.write_anlz(dat.with_suffix(".EXT"), ext)]
files = [(".DAT", W.anlz_bytes(tags)), (".EXT", W.anlz_bytes(ext))]
if two_ex:
written.append(W.write_anlz(dat.with_suffix(".2EX"), [W.path_tag(rel), *two_ex]))
files.append((".2EX", W.anlz_bytes([W.path_tag(rel), *two_ex])))
return files
def _write_anlz(self, item: ExportTrack, rel: str, dat: Path) -> list[Path]:
written = []
for suffix, data in self.anlz_files(item, rel):
path = dat.with_suffix(suffix)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
written.append(path)
return written
@staticmethod
@@ -424,6 +433,15 @@ _FILE_TYPES = {".mp3": 1, ".m4a": 4, ".mp4": 4, ".aac": 4, ".flac": 5, ".wav": 1
".aif": 12, ".aiff": 12}
def art_files(n: int, jpegs: tuple[bytes, bytes]) -> list[tuple[str, bytes]]:
"""Image `n`'s four files as `(drive-relative path, bytes)`: `a<n>`/`b<n>`
and their `_m`, byte-identical pairs, in `Artwork/00001/` (see `_write_art`).
`image.path` names the `b` file; `export.pdb`'s artwork table the `a` one."""
small, medium = jpegs
return [(f"/PIONEER/Artwork/00001/{letter}{n}{suffix}.jpg", data)
for letter in ("a", "b") for suffix, data in (("", small), ("_m", medium))]
def _file_type(path: Path) -> int:
return _FILE_TYPES.get(path.suffix.lower(), 1)
+338 -8
View File
@@ -45,6 +45,7 @@ import re
import shutil
import tempfile
import time
import uuid
from datetime import datetime
from pathlib import Path
@@ -154,7 +155,13 @@ class OneLibraryStore(ReplaceGridCommands):
# Analysis files with unsaved edits: path -> (edited file, how the
# original looked on disk when first edited). The SAME objects sit in
# the caches above, so every read sees the edit; Save writes them.
self._pending_anlz: dict[Path, tuple[anlz_file.AnlzFile, tuple]] = {}
# (`seen` is None for a file an ADDED track brings: it must not exist yet.)
self._pending_anlz: dict[Path, tuple[anlz_file.AnlzFile, tuple | None]] = {}
# Adding and removing tracks (see "writes: adding and removing tracks"):
# incoming copy -> where it will live; files to create; files to delete.
self._incoming: dict[Path, Path] = {}
self._new_files: dict[Path, bytes] = {}
self._doomed: list[Path] = []
self._content_cache: list | None = None
self._by_id: dict[str, object] | None = None
self._load()
@@ -186,6 +193,10 @@ class OneLibraryStore(ReplaceGridCommands):
self._db, self._work = db, work
self._journal.clear()
self._pending_anlz.clear()
self._new_files.clear()
self._doomed.clear()
if not self.read_only:
self._clear_incoming(crashed=True)
self._dat_cache.clear()
self._ext_cache.clear()
self._content_cache = None
@@ -200,6 +211,8 @@ class OneLibraryStore(ReplaceGridCommands):
"""
db, self._db = self._db, None
work, self._work = self._work, None
if not self.read_only:
self._clear_incoming()
if db is not None:
for step in (lambda: db.session.rollback(), lambda: db.session.close(),
lambda: db.engine.dispose()):
@@ -282,7 +295,16 @@ class OneLibraryStore(ReplaceGridCommands):
return row
def audio_path(self, track_id: str) -> Path | None:
return self.layout.resolve(getattr(self.content(track_id), "path", None))
return self.resolve_audio(getattr(self.content(track_id), "path", None))
def resolve_audio(self, drive_relative: str | None) -> Path | None:
"""A stored path on this host — or, for a track added this session whose
audio has not been published yet, its incoming copy, so it plays."""
final = self.layout.resolve(drive_relative)
if final is not None and final not in self._incoming.values():
return final
incoming = next((i for i, f in self._incoming.items() if f == final), None)
return incoming if incoming is not None and incoming.is_file() else final
def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
"""The track's artwork: `content.image_id` -> `image.path` -> the file.
@@ -302,6 +324,8 @@ class OneLibraryStore(ReplaceGridCommands):
return None
medium = small.with_name(small.stem + "_m" + small.suffix)
for path in (medium, small):
if path in self._new_files: # an added track's, not written yet
return self._new_files[path], "image/jpeg"
try:
return path.read_bytes(), "image/jpeg"
except OSError:
@@ -311,7 +335,7 @@ class OneLibraryStore(ReplaceGridCommands):
def all_audio_paths(self) -> list[str]:
out: list[str] = []
for row in self.iter_content():
resolved = self.layout.resolve(getattr(row, "path", None))
resolved = self.resolve_audio(getattr(row, "path", None))
if resolved is not None:
out.append(str(resolved))
return out
@@ -643,7 +667,8 @@ class OneLibraryStore(ReplaceGridCommands):
def _anlz_paths(self, track_id: str) -> tuple[Path, Path]:
dat = self.layout.resolve(getattr(self.content(track_id), "analysisDataFilePath", None))
if dat is None or not dat.is_file() or not self.layout.extended_anlz(dat).is_file():
exists = lambda p: p in self._pending_anlz or p.is_file() # noqa: E731
if dat is None or not exists(dat) or not exists(self.layout.extended_anlz(dat)):
raise InvalidCommand(
"This track has no analysis files on the drive, so it has nowhere to "
"store cues or a beatgrid. Analyse it in rekordbox first."
@@ -884,6 +909,261 @@ class OneLibraryStore(ReplaceGridCommands):
self._require_db().flush()
self._journal.record("grid", "replace" if ordered else "delete", track_id)
# ---- writes: adding and removing tracks -------------------------------------
#
# A stick's audio belongs to its library: added audio is COPIED onto it (a
# file already on the stick is used where it is), laid out as rekordbox lays
# a stick out, and a removed track's audio goes with it. Decisions 3, 6 and 7
# of the editing discussion; layout read off Goober:
# Contents/<Artist>/<Album>/<file> — `UnknownArtist` / `UnknownAlbum` for
# an empty field, and a file name cut to 48 characters (seen once:
# "…Sell My .mp3"). dateAdded = the day it was added, dateCreated = the
# file's own date, search columns NULL, no update counter set.
#
# Copies arrive in `<stick>/.konduktor-incoming/` and are moved into place at
# Save. Analysis files and artwork for an added track are held in memory
# until then. A crash leaves only the incoming folder, cleared on the next
# editable open.
INCOMING = ".konduktor-incoming"
_NAME_MAX = 48
_BAD_CHARS = re.compile(r'[\\/:*?"<>|\x00-\x1f]')
def audio_home(self) -> Path:
return self.layout.root
def _folder_name(self, value: str | None, fallback: str) -> str:
# FAT/exFAT refuse these characters, and a trailing dot or space.
name = self._BAD_CHARS.sub("_", (value or "").strip()).rstrip(". ")
return name or fallback
def _final_path(self, source: Path, track) -> Path:
folder = (self.layout.root / "Contents"
/ self._folder_name(getattr(track, "artist", None), "UnknownArtist")
/ self._folder_name(getattr(track, "album", None), "UnknownAlbum"))
stem, suffix = Path(self._BAD_CHARS.sub("_", source.name)).stem, source.suffix
stem = stem[:max(1, self._NAME_MAX - len(suffix))]
taken = {p.name.lower() for p in self._incoming.values() if p.parent == folder}
candidate, n = f"{stem}{suffix}", 1
while candidate.lower() in taken or (folder / candidate).exists():
n += 1
tail = f"-{n}{suffix}"
candidate = f"{stem[:max(1, self._NAME_MAX - len(tail))]}{tail}"
return folder / candidate
def place_audio(self, source: Path, track) -> Path | None:
"""Where the importer must copy `source` — or None, if it is already on
this stick and can be used where it is (decision 7)."""
try:
if Path(source).resolve().is_relative_to(self.layout.root.resolve()):
return None
except OSError:
pass
final = self._final_path(Path(source), track)
incoming = self.layout.root / self.INCOMING / f"{uuid.uuid4().hex[:12]}{final.suffix.lower()}"
self._incoming[incoming] = final
return incoming
def final_of(self, audio: Path) -> Path:
"""Where an added track's audio will live (its incoming copy's target, or
the file itself when it was already on the stick)."""
return self._incoming.get(Path(audio), Path(audio))
def drive_relative(self, path: Path) -> str:
return "/" + Path(path).relative_to(self.layout.root).as_posix()
def _clear_incoming(self, *, crashed: bool = False) -> None:
"""Delete copies this session made and never published — or, at an
editable open, whatever a crashed session left (`crashed`)."""
folder = self.layout.root / self.INCOMING
if crashed:
shutil.rmtree(folder, ignore_errors=True)
else:
for incoming in self._incoming:
incoming.unlink(missing_ok=True)
try:
folder.rmdir()
except OSError:
pass
self._incoming.clear()
def _anlz_rel(self, rel: str) -> str:
"""A fresh `/PIONEER/USBANLZ/P0xx/xxxxxxxx/ANLZ0000.DAT` for a track.
rekordbox's own hash is unpublished; the column is what players follow,
so the exporter's stable derivation is used, nudged past any clash."""
from .export import _anlz_dir
salt = 0
while True:
dat = f"{_anlz_dir(rel + ('#' * salt))}/ANLZ0000.DAT"
path = self.layout.resolve(dat)
if not path.parent.exists() and path not in self._pending_anlz:
return dat
salt += 1
def _next_id(self, table: str) -> int:
from sqlalchemy import text
value = self._require_db().session.execute(text(f"SELECT MAX({table}_id) FROM {table}")).scalar()
return int(value or 0) + 1
def _next_image(self) -> int:
n = self._next_id("image")
folder = self.layout.root / "PIONEER" / "Artwork" / "00001"
while any((folder / f"{x}{n}{s}.jpg").exists() or (folder / f"{x}{n}{s}.jpg") in self._new_files
for x in "ab" for s in ("", "_m")):
n += 1
return n
def add_track(self, audio: Path, track, *, rel: str, anlz_rel: str,
anlz: list[tuple[str, bytes]], jpegs: tuple[bytes, bytes] | None,
bpm: float | None, length: float | None) -> str:
"""Insert one track's row, and hold its analysis files and artwork for Save.
The row is filled the way rekordbox fills one on a stick (every column of
a Goober row was compared): file facts from the file, lookups found or
created by name, no update counter, `contentLink`/`analysedBits` as the
exporter writes them (verified in rekordbox 7 there).
"""
from sqlalchemy import text
from ..rekordbox.projection import render_key
from .export import ANALYSED_BITS, CONTENT_LINK, _audio_format, _file_type, _kbps, art_files
if rel in (self._by_id or {}) or any(self.track_id(r) == rel for r in self.iter_content()):
raise InvalidCommand(f"{rel} is already on this drive's library")
db = self._require_db()
final = self.layout.resolve(rel)
cid = self._next_id("content")
image_id = None
if jpegs is not None:
image_id = self._next_image()
for path_rel, data in art_files(image_id, jpegs):
self._new_files[self.layout.resolve(path_rel)] = data
db.session.execute(text("INSERT INTO image (image_id, path) VALUES (:i, :p)"),
{"i": image_id, "p": f"/PIONEER/Artwork/00001/b{image_id}.jpg"})
try:
st = Path(audio).stat()
size, created = st.st_size, datetime.fromtimestamp(st.st_mtime).strftime("%Y-%m-%d")
except OSError:
size, created = 0, None
sample_rate, bit_depth = _audio_format(Path(audio))
year, released = 0, ""
try:
year, released = self._release(getattr(track, "release_date", None))
except InvalidCommand:
pass
lookup = lambda model, value: self._lookup_id(model, (value or "").strip()) # noqa: E731
db.session.execute(text(
"INSERT INTO content (content_id, title, titleForSearch, subtitle, bpmx100, length, "
"trackNo, discNo, artist_id_artist, artist_id_remixer, album_id, genre_id, label_id, "
"key_id, color_id, image_id, djComment, rating, releaseYear, releaseDate, dateAdded, "
"dateCreated, path, fileName, fileSize, fileType, bitrate, bitDepth, samplingRate, "
"isrc, djPlayCount, isHotCueAutoLoadOn, isKuvoDeliverStatusOn, kuvoDeliveryComment, "
"masterDbId, masterContentId, analysisDataFilePath, analysedBits, contentLink, "
"hasModified) VALUES (:cid, :title, NULL, '', :bpm, :length, 0, 0, :artist, :remixer, "
":album, :genre, :label, :key, 0, :image, :comment, :rating, :year, :released, "
":added, :created, :path, :file, :size, :type, :bitrate, :depth, :rate, '', 0, 1, 1, "
"'', 0, :cid, :anlz, :bits, :link, 0)"), {
"cid": cid, "title": getattr(track, "title", None) or final.stem,
"bpm": int(round(bpm * 100)) if bpm else 0, "length": int(length or 0),
"artist": lookup("Artist", track.artist), "remixer": lookup("Artist", track.remixer),
"album": lookup("Album", track.album), "genre": lookup("Genre", track.genre),
"label": lookup("Label", track.label),
# Rendered from the parsed wheel: a source's "10m" means nothing here.
"key": lookup("Key", render_key(track.key_wheel, track.key_mode)),
"image": image_id, "comment": track.comment or "",
"rating": max(0, min(5, int(track.rating or 0))), "year": year, "released": released,
"added": datetime.now().strftime("%Y-%m-%d"), "created": created, "path": rel,
"file": final.name, "size": size, "type": _file_type(final),
"bitrate": _kbps(track.bitrate) or 0, "depth": bit_depth, "rate": sample_rate,
"anlz": anlz_rel, "bits": ANALYSED_BITS, "link": CONTENT_LINK,
})
db.session.execute(text("UPDATE property SET numberOfContents = numberOfContents + 1"))
db.flush()
dat = self.layout.resolve(anlz_rel)
for suffix, data in anlz:
path = dat.with_suffix(suffix)
if suffix == ".2EX":
self._new_files[path] = data
else:
self._pending_anlz[path] = (anlz_file.parse(data), None)
self._content_cache = None
self._by_id = None
self._dat_cache.pop(rel, None)
self._ext_cache.pop(rel, None)
self._dat_cache[rel] = self._pending_anlz[dat][0]
self._ext_cache[rel] = self._pending_anlz[dat.with_suffix(".EXT")][0]
self._journal.record("track", "add", rel)
return rel
def remove_tracks(self, track_ids: list[str]) -> int:
"""Remove tracks from the library and every list that names them; their
audio, analysis files and (unshared) artwork are deleted at Save
(decision 3). Not measured against rekordbox — it cannot delete a track
from a stick — so this removes every row that references the track, and
nothing else."""
from sqlalchemy import text
db = self._require_db()
removed = 0
for track_id in dict.fromkeys(map(str, track_ids)):
row = self.content(track_id)
cid, image_id = int(row.content_id), row.image_id
audio = self.layout.resolve(row.path)
dat = self.layout.resolve(row.analysisDataFilePath)
# Files: the audio (or its unpublished copy), the analysis files.
for incoming, final in list(self._incoming.items()):
if final == audio:
incoming.unlink(missing_ok=True)
del self._incoming[incoming]
audio = None
if audio is not None:
self._doomed.append(audio)
if dat is not None:
for suffix in (".DAT", ".EXT", ".2EX"):
path = dat.with_suffix(suffix)
# Pending edits, or an added track's never-written files, go
# with it; whatever is already on the stick is deleted at Save.
self._pending_anlz.pop(path, None)
self._new_files.pop(path, None)
if path.exists():
self._doomed.append(path)
# Rows: every table that names the content.
affected = [r[0] for r in db.session.execute(
text("SELECT DISTINCT playlist_id FROM playlist_content WHERE content_id = :c"), {"c": cid})]
for table in ("playlist_content", "history_content", "myTag_content", "cue"):
db.session.execute(text(f"DELETE FROM {table} WHERE content_id = :c"), {"c": cid})
for pid in affected:
rows = db.session.execute(text(
"SELECT rowid FROM playlist_content WHERE playlist_id = :p ORDER BY sequenceNo"),
{"p": pid}).fetchall()
for n, (rowid,) in enumerate(rows, start=1):
db.session.execute(text("UPDATE playlist_content SET sequenceNo = :n WHERE rowid = :r"),
{"n": n, "r": rowid})
db.session.execute(text("DELETE FROM content WHERE content_id = :c"), {"c": cid})
if image_id and not db.session.execute(
text("SELECT 1 FROM content WHERE image_id = :i LIMIT 1"), {"i": image_id}).first():
path = db.session.execute(text("SELECT path FROM image WHERE image_id = :i"),
{"i": image_id}).scalar()
db.session.execute(text("DELETE FROM image WHERE image_id = :i"), {"i": image_id})
small = self.layout.resolve(path)
if small is not None:
for letter in ("a", "b"):
for tail in ("", "_m"):
p = small.with_name(f"{letter}{small.stem[1:]}{tail}{small.suffix}")
if self._new_files.pop(p, None) is None and p.exists():
self._doomed.append(p)
db.session.execute(text("UPDATE property SET numberOfContents = numberOfContents - 1"))
self._dat_cache.pop(track_id, None)
self._ext_cache.pop(track_id, None)
self._journal.record("track", "remove", track_id)
removed += 1
db.flush()
db.session.expire_all()
self._content_cache = None
self._by_id = None
return removed
# ---- save ----------------------------------------------------------------
@property
def dirty(self) -> bool:
@@ -928,8 +1208,16 @@ class OneLibraryStore(ReplaceGridCommands):
)
changed_anlz = []
for path, (edited, seen) in self._pending_anlz.items():
if not path.is_file() or _fingerprint_file(path) != seen:
if seen is None: # an added track's: nothing may be there yet
if path.exists():
changed_anlz.append(path)
elif not path.is_file() or _fingerprint_file(path) != seen:
changed_anlz.append(path)
changed_anlz += [p for p in self._new_files if p.exists()]
# Added audio to publish: copies whose track is (still) in the library.
referenced = {self.layout.resolve(getattr(r, "path", None)) for r in self.iter_content()}
publish = [(i, f) for i, f in self._incoming.items() if i.is_file() and f in referenced]
changed_anlz += [f for _i, f in publish if f.exists()]
pdb_now = _fingerprint_file(self.device_library) if self.device_library.is_file() else None
if _fingerprint(self.path) != self._opened_as or changed_anlz or pdb_now != self._pdb_seen:
raise InvalidCommand(
@@ -942,8 +1230,12 @@ class OneLibraryStore(ReplaceGridCommands):
tag_jobs = self._tag_jobs()
# Only files whose bytes really changed: an edit that was undone, or a
# command that failed after reading, leaves nothing to write.
anlz_writes = [(path, data) for path, (edited, _seen) in self._pending_anlz.items()
if (data := edited.to_bytes()) != path.read_bytes()]
anlz_writes = []
for path, (edited, seen) in self._pending_anlz.items():
data = edited.to_bytes()
if seen is None or data != path.read_bytes():
anlz_writes.append((path, data))
doomed = list(dict.fromkeys(self._doomed))
# The legacy Device Library, edited to match (None: already does). Read
# inside the transaction, which sees every edit.
pdb_bytes = None
@@ -953,9 +1245,21 @@ class OneLibraryStore(ReplaceGridCommands):
db.flush()
pdb_bytes = device_library.rebuild(self.device_library.read_bytes(), db.session)
self._backup([path for path, _ in anlz_writes]
self._backup([path for path, _ in anlz_writes if path.exists()]
+ ([self.device_library] if pdb_bytes is not None else []))
# Added audio first: everything written after it points at it.
for incoming, final in publish:
final.parent.mkdir(parents=True, exist_ok=True)
os.replace(incoming, final)
del self._incoming[incoming]
for path, data in list(self._new_files.items()):
path.parent.mkdir(parents=True, exist_ok=True)
partial = path.with_name(f".{path.name}.konduktor-partial")
partial.write_bytes(data)
os.replace(partial, path)
del self._new_files[path]
for path, data in anlz_writes:
path.parent.mkdir(parents=True, exist_ok=True)
partial = path.with_name(f".{path.name}.konduktor-partial")
partial.write_bytes(data)
os.replace(partial, path)
@@ -991,6 +1295,16 @@ class OneLibraryStore(ReplaceGridCommands):
# retry (after replugging, say) can save them.
self._reopen_working(work)
raise
# The library no longer names them: removed tracks' files go now, and
# never before the database that stopped naming them is on the drive.
for path in doomed:
try:
path.unlink(missing_ok=True)
_prune_empty(path.parent, stop=self.layout.root)
except OSError as ex:
log.warning("Could not delete %s: %s", path, ex)
self._doomed.clear()
self._clear_incoming()
tag_results = self._sync_file_tags(tag_jobs)
shutil.rmtree(work, ignore_errors=True)
self._work = None
@@ -1064,6 +1378,22 @@ class OneLibraryStore(ReplaceGridCommands):
"release_date": t.release_date}
def _prune_empty(folder: Path, *, stop: Path) -> None:
"""Remove `folder` and its parents while empty, never `stop` or above, nor
the stick's top-level `Contents`/`PIONEER` folders."""
keep = {stop, stop / "Contents", stop / "PIONEER", stop / "PIONEER" / "USBANLZ"}
while folder not in keep and folder.is_relative_to(stop):
try:
if any(p for p in folder.iterdir() if not p.name.startswith("._") and p.name != ".DS_Store"):
return
for p in folder.iterdir(): # macOS's own litter does not keep a folder
p.unlink(missing_ok=True)
folder.rmdir()
except OSError:
return
folder = folder.parent
def _clear_stale_work() -> None:
"""Remove working copies a crashed session left behind."""
try:
+9 -2
View File
@@ -200,11 +200,18 @@ class LibraryAdapter(Protocol):
# is touched, so a cancel leaves it as it was. Gated on
# `capabilities().tracks.addable`.
def add_tracks(self, items: list["NewTrack"], *, checkpoint=None) -> list[str]: ...
# OPTIONAL, where `capabilities().tracks.places_audio`: the library decides
# where added audio goes. `place_audio(source, track)` returns the path the
# importer must COPY `source` to (which becomes `NewTrack.audio_path`), or
# None when the file is already where the library can use it in place;
# `audio_home()` is where that audio lands, for the free-space check.
# (A protocol member would make every adapter implement them.)
# Remove tracks from the library — and so from every playlist, since an
# entry naming a track the library no longer has is a dangling reference.
# Never touches audio files. Returns how many were removed; gated on
# `capabilities().tracks.removable`.
# Never touches audio files, except where `tracks.places_audio` (a stick's
# audio belongs to its library): there the file goes too, at Save. Returns
# how many were removed; gated on `capabilities().tracks.removable`.
def remove_tracks(self, track_ids: list[str]) -> int: ...
# Swap converted stem files into the library (see `StemSwap`), all at once:
+10 -1
View File
@@ -64,11 +64,17 @@ class TrackCapabilities(BaseModel):
editable_fields: list[str] = []
media_kinds: list[MediaKind] = ["audio"]
# Tracks can be removed from the library (and so from its playlists). The
# audio file is never touched either way.
# audio file is never touched — except where `places_audio`: a library that
# owns where its audio lives (a stick) deletes it with the track, at Save.
removable: bool = False
# Tracks can be added to the library (`add_tracks`): an import from a
# device, or browsed files added to the collection.
addable: bool = False
# The LIBRARY decides where added audio goes (`place_audio`), so the user is
# neither asked "copy or leave in place?" nor for a destination: a OneLibrary
# stick can only point at files on itself, and lays them out as rekordbox
# does. False: the user chooses, as for a desktop collection.
places_audio: bool = False
# Tracks can be converted to native-instruments STEM files, which this
# platform plays as stems (`apply_stem_swaps`).
stem_convertible: bool = False
@@ -98,6 +104,9 @@ class SaveCapabilities(BaseModel):
library_label: str
overwrite_risk: Literal["none", "on_exit", "while_running"] = "none"
history: bool = True
# The library was written by one of Konduktor's EXPORT sets, whose next run
# replaces it — so an edit made here directly is undone by the next export.
managed_by_export: bool = False
class Capabilities(BaseModel):
+36 -3
View File
@@ -290,9 +290,15 @@ def run(
destination and nothing to roll back. `into_playlist` appends every planned
track — the new ones and those the destination already held — to one of the
destination's playlists before the save, so both land in one commit.
A destination that PLACES ITS OWN AUDIO (`tracks.places_audio`: a OneLibrary
stick) overrides both: `dest.place_audio` names each copy's target, or says
the file can be used where it is, and `reference`/`plan.destination` are
ignored.
"""
destination = plan.destination
if not reference:
places = places_audio(dest)
if not reference and not places:
assert destination is not None
destination.mkdir(parents=True, exist_ok=True)
@@ -318,11 +324,18 @@ def run(
for planned in importable:
handle.raise_if_cancelled()
assert planned.source_path is not None
if reference:
if places:
target = dest.place_audio(planned.source_path, source.track(planned.track_id))
if target is None:
copied.append((planned, planned.source_path))
continue
target.parent.mkdir(parents=True, exist_ok=True)
elif reference:
copied.append((planned, planned.source_path))
continue
else:
target = _unique_target(destination, planned.source_path.name, taken)
handle.progress(message=f"Copying {planned.title}")
target = _unique_target(destination, planned.source_path.name, taken)
created.append(target) # registered BEFORE the write, so a cancel
copy_file(planned.source_path, target, handle, bump) # mid-file is cleaned
copied.append((planned, target))
@@ -399,6 +412,26 @@ def run(
raise
def places_audio(dest) -> bool:
"""Whether the destination decides where added audio goes (a stick)."""
try:
return bool(dest.capabilities().tracks.places_audio) and hasattr(dest, "place_audio")
except Exception: # noqa: BLE001
return False
def placed_bytes(dest, plan: ImportPlan) -> int:
"""What an import into a self-placing library will COPY: a file already under
its `audio_home()` is used in place and costs nothing."""
home = dest.audio_home()
total = 0
for planned in plan.importable:
path = planned.source_path
if path is not None and not path.resolve().is_relative_to(home.resolve()):
total += planned.size
return total
def _save(dest):
"""Save through AppState so the version-history commit is not skipped."""
from .app_state import STATE
+34 -11
View File
@@ -1894,7 +1894,10 @@ def _folder_add_plan(body: FolderAddRequest):
# One source across however many folders the ids came from.
source = FolderSource(Path(tracks[0].id).parent, tracks)
destination = None
if body.mode == "copy":
if importer.places_audio(dest):
# The library decides (a stick): no mode, no destination to ask for.
destination = dest.audio_home()
elif body.mode == "copy":
if not body.destination:
raise HTTPException(400, "Copying needs a destination folder")
destination = Path(body.destination).expanduser()
@@ -1910,9 +1913,11 @@ def _folder_add_plan(body: FolderAddRequest):
@app.post("/api/folder/add/preview")
def folder_add_preview(body: FolderAddRequest) -> dict:
_source, _dest, destination, plan = _folder_add_plan(body)
_source, dest, destination, plan = _folder_add_plan(body)
out = plan.as_dict(free_bytes=importer.free_bytes(destination) if destination else None)
if body.mode == "reference":
if importer.places_audio(dest):
_placed_space(out, dest, plan, destination)
elif body.mode == "reference":
# Nothing is copied, so there is no size to fit anywhere.
out.update(total_bytes=0, free_bytes=None, enough_space=None)
drive = _drive_of(Path(body.track_ids[0]), places.drives()) if body.track_ids else None
@@ -1927,12 +1932,13 @@ def folder_add(body: FolderAddRequest) -> JobStatus:
source, dest, destination, plan = _folder_add_plan(body)
if not plan.importable and not plan.existing:
raise HTTPException(400, "Nothing to add (none of those files exist)")
if body.mode == "copy":
if body.mode == "copy" or importer.places_audio(dest):
free = importer.free_bytes(destination)
if free is not None and free < plan.total_bytes + importer.SPACE_HEADROOM:
needed = importer.placed_bytes(dest, plan) if importer.places_audio(dest) else plan.total_bytes
if free is not None and free < needed + importer.SPACE_HEADROOM:
raise HTTPException(
400,
f"Not enough space: {plan.total_bytes / 1e9:.1f} GB needed, "
f"Not enough space: {needed / 1e9:.1f} GB needed, "
f"{free / 1e9:.1f} GB free at {destination}",
)
if JOBS.active("import"):
@@ -1962,10 +1968,23 @@ def folder_add(body: FolderAddRequest) -> JobStatus:
# threads rather than something fancier.
def _placed_space(out: dict, dest, plan, destination: Path) -> None:
"""A self-placing library's preview: only what is really COPIED needs room,
and the preview says how many files will be copied vs used in place."""
needed = importer.placed_bytes(dest, plan)
free = importer.free_bytes(destination)
in_place = sum(1 for t in plan.importable if t.source_path is not None
and t.source_path.resolve().is_relative_to(destination.resolve()))
out.update(total_bytes=needed, free_bytes=free,
enough_space=None if free is None else free >= needed + importer.SPACE_HEADROOM,
places_audio=True, in_place=in_place, copied=len(plan.importable) - in_place)
def _import_plan(body: ImportRequest):
source, dest = require_source(), require_adapter()
_require_addable(dest)
destination = Path(body.destination).expanduser()
destination = (dest.audio_home() if importer.places_audio(dest)
else Path(body.destination).expanduser())
return source, dest, destination, importer.plan(
source,
dest,
@@ -1982,8 +2001,11 @@ def import_preview(body: ImportRequest) -> dict:
Computed fresh on every call and never stored — a stick can be re-exported
between the preview and the import, and a stale preview is worse than none.
"""
_source, _dest, destination, plan = _import_plan(body)
return plan.as_dict(free_bytes=importer.free_bytes(destination))
_source, dest, destination, plan = _import_plan(body)
out = plan.as_dict(free_bytes=importer.free_bytes(destination))
if importer.places_audio(dest):
_placed_space(out, dest, plan, destination)
return out
@app.post("/api/import", response_model=JobStatus)
@@ -1994,10 +2016,11 @@ def start_import(body: ImportRequest) -> JobStatus:
if not plan.importable:
raise HTTPException(400, "Nothing to import (no tracks, or none of their files exist)")
free = importer.free_bytes(destination)
if free is not None and free < plan.total_bytes + importer.SPACE_HEADROOM:
needed = importer.placed_bytes(dest, plan) if importer.places_audio(dest) else plan.total_bytes
if free is not None and free < needed + importer.SPACE_HEADROOM:
raise HTTPException(
400,
f"Not enough space: {plan.total_bytes / 1e9:.1f} GB needed, "
f"Not enough space: {needed / 1e9:.1f} GB needed, "
f"{free / 1e9:.1f} GB free at {destination}",
)
# One at a time: two concurrent imports would race on filename collisions and