From 7960a5a68f46173ee328506b74f00977d8203642 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Thu, 1 Oct 2026 16:43:37 +0200 Subject: [PATCH] Implemented OneLibrary track addition and removal --- CLAUDE.md | 55 ++- .../konduktor/adapters/onelibrary/adapter.py | 107 +++++- .../adapters/onelibrary/capabilities.py | 12 +- .../adapters/onelibrary/device_library.py | 28 +- .../konduktor/adapters/onelibrary/export.py | 38 +- .../konduktor/adapters/onelibrary/store.py | 346 +++++++++++++++++- backend/konduktor/core/adapter.py | 11 +- backend/konduktor/core/capabilities.py | 11 +- backend/konduktor/importer.py | 39 +- backend/konduktor/main.py | 45 ++- backend/test_folders.py | 22 +- backend/test_onelibrary_adapter.py | 6 +- frontend/src/App.tsx | 25 +- frontend/src/api.ts | 9 + frontend/src/components/AddFilesDialog.tsx | 47 ++- frontend/src/components/DevicesSection.tsx | 43 ++- frontend/src/components/ImportDialog.tsx | 17 +- frontend/src/components/SaveBar.tsx | 9 +- frontend/src/components/Sidebar.tsx | 4 + frontend/src/lib/platformCopy.ts | 33 ++ 20 files changed, 822 insertions(+), 85 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 7731aa2..ebe1778 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -305,8 +305,9 @@ Two independent apps that talk over HTTP: The cross-vendor USB export format (AlphaTheta + Algoriddim + Native Instruments), read by CDJ-class hardware. Editing is landing in steps toward parity with the Rekordbox adapter — track metadata, playlists, hot cues and - the beatgrid done; adding/removing tracks and the `export.pdb` rebuild next — - decided in + the beatgrid, and the `export.pdb` rebuild done and VERIFIED in rekordbox 7 + (both library views matched); adding/removing tracks done (not yet checked + in rekordbox) and the UI ("Open for editing…" on a Devices row) — decided in [the editing discussion](.claude/discussions/discuss-onelibrary-editing-2026-10-01.md), which also holds what rekordbox 7 was MEASURED writing when it edits a stick (no update counter moves, the `cue` table stays empty, a new playlist goes on @@ -333,6 +334,38 @@ Two independent apps that talk over HTTP: the first edit — readers prefer `PCO2`, so a one-pad list would hide the rest. A track with no analysis files refuses cue/grid edits. Memory cues stay preserved-but-uneditable. + **`device_library.py` keeps the stick's legacy `export.pdb` in step** at + every Save (rekordbox's own edits let its playlists drift — measured). The + stick's own pdb is EDITED (`pdb.PdbEditor`), not regenerated: ids are + mirrored from OneLibrary (rekordbox exports both from the same ids), only the + tracks / lookup / playlist tables are candidates, a table is rewritten only if + a row changed, an unchanged row keeps rekordbox's bytes, and a changed track + row is the old row with the edited fields overwritten — so phrase strings, + `masterDbId` halves and play counts survive. A track row ends at its last + string (`pdb.track_extent`), NOT at the next row: rekordbox's heap holds stale + tails between rows. Keys and artwork are mirrored too (pdb artwork row = + `a.jpg` beside OneLibrary's `b`); history and `exportExt.pdb` are + untouched. + **Adding and removing tracks** (`tracks.places_audio`: the LIBRARY places + added audio, so the importer asks `place_audio` instead of the user, and the + routes check space at `audio_home()`): a file already on the stick is used in + place, anything else is copied to `Contents///` (rekordbox's + layout: `UnknownArtist`/`UnknownAlbum`, file names cut to 48 characters) via + `/.konduktor-incoming/`, playable from there until Save moves it into + place; Discard deletes it, and a crashed session's incoming folder is cleared + on the next EDITABLE open (never a browsing one). Each added track is decoded + once and gets the OneLibrary exporter's own `.DAT`/`.EXT`/`.2EX` + (`OneLibraryExporter.anlz_files` builds bytes rather than writing) and art + (`art_files`), held in memory and written at Save; hot cues replay through + `set_cue`, memory cues (and a hot cue with no free pad) cross as memory cues. + The row copies a rekordbox stick row column for column (search columns NULL, + no counters) and `property.numberOfContents` follows. Removing deletes every + row naming the track (playlist entries renumbered from 1) and, AFTER the + database is saved, its audio, analysis files and unshared artwork, pruning + emptied folders. The adapter re-projects after every save, since Save moves + files. `save.managed_by_export` is set when the drive's root carries an + export set's `.konduktor-export.json`, and SaveBar warns that the next export + run replaces edits made in place. Full research, incl. the schema, is in [.claude/handoffs/onelibrary-adapter.md](.claude/handoffs/onelibrary-adapter.md); the four things that make it unlike the Rekordbox adapter: @@ -602,12 +635,20 @@ Two independent apps that talk over HTTP: clicking a folder is the `folder` source kind — its audio in the ordinary table, read-only via `readonly_cause: 'not_in_library'`, with files the collection already holds checked off in the # column (`TrackTable`'s - `marked`). Capped at 40% of the sidebar and self-scrolling so a deep tree + `marked`). A browsed device is read-only (cause `browsing`); **"Open for + editing…"** — the drive row's right-click menu, and a button while browsing + a device whose caps say `browsing` — opens it as THE library via App's + `openForEditing` (unsaved-edits confirm, source closed, library opened). + Capped at 40% of the sidebar and self-scrolling so a deep tree gives way before the playlists do) + `AddFilesDialog` (copy vs. leave in place is **asked every time with nothing preselected** — the answer depends on the drive — and warns that a referenced file on an external drive goes missing on unplug. A playlist/export target adds to the collection first - and says so; it runs through `importer.run(reference=…, into_playlist=…)`), + and says so; it runs through `importer.run(reference=…, into_playlist=…)`. + A library with `tracks.places_audio` (a stick) is the exception: no + question and no destination — the dialog STATES how many files are copied + and how many stay in place (`platformCopy.placedAudioSummary`), and + `ImportDialog` drops its destination folder the same way), `CollectionPicker` (**two steps: which PLATFORM, then which library** — Automatic / Open last / Find manually, the last revealing a file browser. The platform comes first because every later answer depends on it: @@ -1319,9 +1360,9 @@ that number and nothing else — everything derives from it: A OneLibrary USB drive opens, projects, browses and searches: tracks, playlists, hot cues, memory cues, loops and flexible beatgrids. Done: track metadata (+ file tags), playlists, hot cues and the beatgrid (in the ANLZ - files, each rule matching rekordbox's measured edit), Save via a working copy. - Next: the `export.pdb` rebuild on save, adding/removing tracks, "Open for - editing…" on a Devices row. All format research — including the schema, which has no + files, each rule matching rekordbox's measured edit), the `export.pdb` rebuild + on save, Save via a working copy — verified in rekordbox 7. Next: adding and + removing tracks, "Open for editing…" on a Devices row. All format research — including the schema, which has no public spec — is in [.claude/handoffs/onelibrary-adapter.md](.claude/handoffs/onelibrary-adapter.md). - 🟡 **Export/conversion** — **in progress.** Both the design AND the user flow are settled; see diff --git a/backend/konduktor/adapters/onelibrary/adapter.py b/backend/konduktor/adapters/onelibrary/adapter.py index d31021d..e89f131 100644 --- a/backend/konduktor/adapters/onelibrary/adapter.py +++ b/backend/konduktor/adapters/onelibrary/adapter.py @@ -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") diff --git a/backend/konduktor/adapters/onelibrary/capabilities.py b/backend/konduktor/adapters/onelibrary/capabilities.py index 6911fc9..3f241ef 100644 --- a/backend/konduktor/adapters/onelibrary/capabilities.py +++ b/backend/konduktor/adapters/onelibrary/capabilities.py @@ -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. diff --git a/backend/konduktor/adapters/onelibrary/device_library.py b/backend/konduktor/adapters/onelibrary/device_library.py index f23f8b6..347df58 100644 --- a/backend/konduktor/adapters/onelibrary/device_library.py +++ b/backend/konduktor/adapters/onelibrary/device_library.py @@ -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(" str: + """OneLibrary's `image.path` names the `b` file; export.pdb's artwork row + the byte-identical `a` 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 = {} diff --git a/backend/konduktor/adapters/onelibrary/export.py b/backend/konduktor/adapters/onelibrary/export.py index 90c18c5..c7ec9ea 100644 --- a/backend/konduktor/adapters/onelibrary/export.py +++ b/backend/konduktor/adapters/onelibrary/export.py @@ -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`/`b` + 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) diff --git a/backend/konduktor/adapters/onelibrary/store.py b/backend/konduktor/adapters/onelibrary/store.py index 8bcfaad..ad47643 100644 --- a/backend/konduktor/adapters/onelibrary/store.py +++ b/backend/konduktor/adapters/onelibrary/store.py @@ -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/// — `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 `/.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: diff --git a/backend/konduktor/core/adapter.py b/backend/konduktor/core/adapter.py index 5b4cbd6..3a4e988 100644 --- a/backend/konduktor/core/adapter.py +++ b/backend/konduktor/core/adapter.py @@ -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: diff --git a/backend/konduktor/core/capabilities.py b/backend/konduktor/core/capabilities.py index 301585e..e920835 100644 --- a/backend/konduktor/core/capabilities.py +++ b/backend/konduktor/core/capabilities.py @@ -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): diff --git a/backend/konduktor/importer.py b/backend/konduktor/importer.py index 21448b9..ab2456e 100644 --- a/backend/konduktor/importer.py +++ b/backend/konduktor/importer.py @@ -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 diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index a24bbfe..c2ff9a1 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -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 diff --git a/backend/test_folders.py b/backend/test_folders.py index 6cfe7a5..1047c8a 100644 --- a/backend/test_folders.py +++ b/backend/test_folders.py @@ -227,15 +227,29 @@ with TestClient(main.app, raise_server_exceptions=False) as c: check("and saved, not left pending", not rb.dirty) rb.close() - print("== a library that cannot take tracks refuses the route ==") + print("== a stick places its own audio; a library that cannot add refuses ==") # A COPY: opened as THE library, a OneLibrary drive is editable. fixture = Path(tempfile.mkdtemp()) / "onelibrary" shutil.copytree(Path(__file__).resolve().parent / "fixtures" / "onelibrary", fixture) r = c.post("/api/library/open", json={"path": str(fixture)}) if r.status_code == 200: - check("the add preview is refused (422)", - c.post("/api/folder/add/preview", - json={"track_ids": [str(two)], "mode": "reference"}).status_code == 422) + # No mode and no destination: the library decides (decision 7). + r = c.post("/api/folder/add/preview", json={"track_ids": [str(two)], "mode": "copy"}) + body = r.json() if r.status_code == 200 else {} + check("a stick's preview needs no destination, and counts the copy", + r.status_code == 200 and body.get("places_audio") and body.get("copied") == 1 + and body.get("in_place") == 0, f"{r.status_code} {r.text[:200]}") + adapter = main.STATE.adapter + real = adapter.capabilities + caps = real() + adapter.capabilities = lambda: caps.model_copy( + update={"tracks": caps.tracks.model_copy(update={"addable": False})}) + try: + check("a library whose capabilities say it cannot add refuses the route (422)", + c.post("/api/folder/add/preview", + json={"track_ids": [str(two)], "mode": "reference"}).status_code == 422) + finally: + adapter.capabilities = real else: print(f" (skipped: fixture did not open — {r.status_code})") diff --git a/backend/test_onelibrary_adapter.py b/backend/test_onelibrary_adapter.py index 5d8e895..5dad24d 100644 --- a/backend/test_onelibrary_adapter.py +++ b/backend/test_onelibrary_adapter.py @@ -360,8 +360,8 @@ check("the editable fields are the Rekordbox adapter's set", caps.tracks.editable_fields == sorted(["title", "artist", "album", "genre", "label", "remixer", "comment", "rating", "release_date"]), str(caps.tracks.editable_fields)) -check("adding and removing tracks are not offered YET", - not caps.tracks.addable and not caps.tracks.removable) +check("tracks can be added and removed, the library placing the audio", + caps.tracks.addable and caps.tracks.removable and caps.tracks.places_audio) check("playlists can be reordered", caps.playlists.reorder is True) check("ratings are 0-5", caps.tracks.rating_max == 5) check("folders are supported by the format", caps.playlists.folders is True) @@ -428,7 +428,7 @@ LANDED = {"set_track_metadata", "create_playlist", "rename_playlist", "delete_pl "set_playlist_entries", "save", "set_cue", "set_cue_type", "set_cue_color", "delete_cue", "place_cues", "add_grid_marker", "move_grid_marker", "set_grid_marker_bpm", "delete_grid_marker", - "replace_grid", "set_analysed_grid", "delete_grid"} + "replace_grid", "set_analysed_grid", "delete_grid", "remove_tracks"} pending = [(n, fn) for n, fn in COMMANDS if n not in LANDED] refused = [name for name, fn in pending if not _raises(fn, Unsupported)] check(f"the {len(pending)} commands not written yet raise Unsupported", not refused, "; ".join(refused)) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 8c35c6c..591e923 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -2,7 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useQuery, useQueryClient } from '@tanstack/react-query' import type { ColumnSizingState, SortingState, VisibilityState } from '@tanstack/react-table' import { CapabilitiesContext, slotLabeller } from './lib/capabilities' -import { writeHint } from './lib/platformCopy' +import { removalNote, writeHint } from './lib/platformCopy' import { invalidateTrackLists } from './lib/trackQueries' import { api, type CueBatchResult, type GridBatchResult, type AutoCueSlot, type PlaylistNode, type StemBatchResult, type Track, type TrackOrigin } from './api' import { confirmDiscardUnsaved } from './lib/unsaved' @@ -578,6 +578,21 @@ export default function App() { qc.invalidateQueries() // refetch everything for the newly-opened collection } + // "Open for editing…" on a device: the drive becomes THE library — one library, + // one dirty state, one SaveBar (decided 2026-10-01). Unsaved edits to the + // current library are confirmed first, as switching library always is, and the + // browsing copy is closed so the drive is not open twice. + const openForEditing = async (path: string) => { + if (!(await confirmDiscardUnsaved())) return + try { + await api.closeSource() + await api.openCollection(path) + handleOpened() + } catch (e) { + onError((e as Error).message) + } + } + // ---- Convert to Stems ------------------------------------------------------ const canStems = canEdit && !viewForeign && !!capabilities.data?.tracks.stem_convertible const finishStemBatch = (state: string, r: StemBatchResult | null, error: string | null) => { @@ -841,12 +856,7 @@ export default function App() {

Remove {trackNoun(ids)} from the collection and from every playlist?

-

- The audio {ids.length === 1 ? 'file stays' : 'files stay'} on disk. Nothing is written until you - save{capabilities.data?.save.history - ? ', and a save can be rolled back from version history.' - : ', and that save cannot be undone.'} -

+ {capabilities.data &&

{removalNote(capabilities.data, ids.length)}

} ), confirmLabel: `Remove ${nTracks(ids.length)}`, @@ -1161,6 +1171,7 @@ export default function App() { onOpenHistory={() => setShowHistory(true)} onImport={() => setImporting(true)} onSwitchLibrary={() => setForcePicker(true)} + onOpenLibrary={(path) => void openForEditing(path)} onDone={(msg) => notify('success', msg)} onOpenPathMapping={() => setShowPaths(true)} onDiscarded={() => afterBulk(prepTrack ? [prepTrack.id] : [], true)} diff --git a/frontend/src/api.ts b/frontend/src/api.ts index adfa5c6..1f8b6d7 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -222,6 +222,8 @@ export interface SaveCapabilities { library_label: string overwrite_risk: 'none' | 'on_exit' | 'while_running' history: boolean + /** Written by a Konduktor export set, whose next run replaces it. */ + managed_by_export: boolean } /** Why a library cannot be edited. A fact — lib/platformCopy.ts words it. */ @@ -249,6 +251,8 @@ export interface Capabilities { removable: boolean /** Tracks can be added to the library (import, add browsed files). */ addable: boolean + /** The library decides where added audio goes — no copy/in-place question. */ + places_audio: boolean /** Tracks can be converted to native-instruments STEM files. */ stem_convertible: boolean /** Lower-case suffixes this library can hold — what a browsed folder lists. */ @@ -361,6 +365,11 @@ export interface ImportPreview { destination: string | null free_bytes: number | null enough_space: boolean | null + /** Set when the library places its own audio (`tracks.places_audio`): how + * many files will be copied onto it, and how many are already there. */ + places_audio?: boolean + copied?: number + in_place?: number } // ---- drives and folders ---- diff --git a/frontend/src/components/AddFilesDialog.tsx b/frontend/src/components/AddFilesDialog.tsx index ff2a95b..d808468 100644 --- a/frontend/src/components/AddFilesDialog.tsx +++ b/frontend/src/components/AddFilesDialog.tsx @@ -2,12 +2,18 @@ import { createPortal } from 'react-dom' import { useEffect, useRef, useState, type ReactNode } from 'react' import { useQuery, useQueryClient } from '@tanstack/react-query' import { api, type FolderAddPreview, type FolderAddRequest, type JobStatus } from '../api' +import { useCaps } from '../lib/capabilities' +import { placedAudioSummary } from '../lib/platformCopy' import { FolderPicker } from './FolderPicker' /** * Add browsed files to the collection — and, optionally, to a playlist or export. * - * Copy vs. leave-in-place is ASKED every time, with nothing preselected: the + * A library that places its own audio (`tracks.places_audio`, a OneLibrary + * stick) is the exception: only files already on it can stay in place, so the + * dialog STATES what will happen instead of asking (decided 2026-10-01). + * + * Otherwise copy vs. leave-in-place is ASKED every time, with nothing preselected: the * right answer depends on the drive (a stick is about to be unplugged) and on * how the DJ keeps their music, and a remembered default would quietly apply * last week's answer to a different drive. @@ -42,6 +48,11 @@ interface Props { export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: Props) { const qc = useQueryClient() + // The LIBRARY's capabilities (this dialog is mounted outside the browsed + // view's swapped context). A library that places its own audio — a stick — + // decides copy vs in place itself, so there is nothing to ask. + const caps = useCaps() + const places = caps.tracks.places_audio const [mode, setMode] = useState<'copy' | 'reference' | null>(null) const [folder, setFolder] = useState('') const [browsing, setBrowsing] = useState(false) @@ -62,16 +73,16 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P track_ids: trackIds, // The preview needs A mode to size anything; "reference" costs nothing to // ask about and is replaced as soon as the user picks. - mode: mode ?? 'reference', - destination: mode === 'copy' ? folder : null, + mode: places ? 'copy' : (mode ?? 'reference'), + destination: !places && mode === 'copy' ? folder : null, playlist_id: target?.kind === 'playlist' ? target.id : null, export_id: target?.kind === 'export' ? target.id : null, } const preview = useQuery({ - queryKey: ['folder-add-preview', trackIds, mode, folder, target?.id], + queryKey: ['folder-add-preview', trackIds, places ? 'placed' : mode, folder, target?.id], queryFn: () => api.folderAddPreview(body), - enabled: !job && (mode !== 'copy' || !!folder), + enabled: !job && (places || mode !== 'copy' || !!folder), staleTime: 0, gcTime: 0, }) @@ -146,13 +157,15 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P const pct = job && job.total > 0 ? Math.min(100, (job.done / job.total) * 100) : null const n = trackIds.length const newCount = p?.importable ?? 0 + const shown = places ? 'placed' : mode + const libraryName = places ? caps.save.app_name : 'your collection' const canAdd = - !starting && mode !== null && !!p && (newCount > 0 || (!!target && p.existing.length > 0)) && + !starting && shown !== null && !!p && (newCount > 0 || (!!target && p.existing.length > 0)) && p.enough_space !== false const title = target ? `Add ${n} track${n === 1 ? '' : 's'} to ${target.name}` - : `Add ${n} track${n === 1 ? '' : 's'} to your collection` + : `Add ${n} track${n === 1 ? '' : 's'} to ${libraryName}` const option = (value: 'copy' | 'reference', label: string, detail: ReactNode) => (