diff --git a/CLAUDE.md b/CLAUDE.md index fc96d37..da244e4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -284,7 +284,10 @@ Two independent apps that talk over HTTP: path-derived id that `is_durable()` reports honestly. Writing beside the library is not a new intrusion — saves already create `backups/` there. - `exports.py` — **export sets**: a named, persisted slice of the library bound - to a destination. Konduktor's OWN data, never written into the user's library + to a destination and **one or more target platforms** (`targets`, never + empty; a set saved with the old single `target` loads as a one-item list). + The targets share the destination and ONE copy of the audio — their layouts + (`collection.nml`; `PIONEER/…`; `master.db` + `share/…`) do not collide. Konduktor's OWN data, never written into the user's library (a Traktor collection has nowhere to put it, and it would live in a file Traktor rewrites). Three rules shape it: references are **LIVE** (a set stores playlist *ids*, resolved at export time, so `resolve()` is computed on @@ -1004,7 +1007,17 @@ that number and nothing else — everything derives from it: tags and the `cue` table's MPEG seek columns. **Step 5 done**: `exporter.py` — plan, mirrored copy, manifest, rollback — on `jobs.py`, plus `POST /api/exports/{id}/preview` and `/run`, and the - `ExportRunDialog`. Three properties it is built around: audio is copied FIRST + `ExportRunDialog`. **Multi-target** (2026-09-27): audio is copied once, then + each target's `write()` runs in turn over it; ANY failure undoes everything, + earlier targets' libraries included — and files a failing writer never got + to report, via a snapshot of the destination taken before the first write. + The manifest lists `libraries` (plural; the old `library` key is still + cleared). Audio lives under **`Contents/`**, so a music folder with a + top-level `PIONEER/` or a `master.db` cannot land on a library's path. An + exporter's static `drive_root` (OneLibrary: a CDJ looks for `PIONEER/` only + at a stick's root) surfaces as `PlatformOption.drive_root` and the preview's + `not_drive_root` — a **warning, not a block**, since the other targets are + valid in any folder. Three properties it is built around: audio is copied FIRST and the library written LAST, so a cancel leaves **no** library file and its absence is what marks an export unfinished; rollback registers each file BEFORE writing it, so the in-flight copy is cleaned up too; and the **manifest** diff --git a/backend/konduktor/adapters/onelibrary/export.py b/backend/konduktor/adapters/onelibrary/export.py index 619d4f4..cb51401 100644 --- a/backend/konduktor/adapters/onelibrary/export.py +++ b/backend/konduktor/adapters/onelibrary/export.py @@ -86,6 +86,8 @@ class OneLibraryExporter: platform = "onelibrary" #: Relative to the drive root, which is what the destination folder is. library_filename = str(Path("PIONEER") / DB_SUBPATH) + #: A CDJ looks for `PIONEER/` at the root of the stick and nowhere else. + drive_root = True def capabilities(self): """What a drive can hold — no device, no path, no library to read. diff --git a/backend/konduktor/adapters/rekordbox/export.py b/backend/konduktor/adapters/rekordbox/export.py index c695108..8c1f88d 100644 --- a/backend/konduktor/adapters/rekordbox/export.py +++ b/backend/konduktor/adapters/rekordbox/export.py @@ -83,6 +83,7 @@ OTHER_PLAYLIST = "Other" class RekordboxExporter: platform = "rekordbox" library_filename = "master.db" + drive_root = False def capabilities(self): """What a Rekordbox library can hold, with no library to read. diff --git a/backend/konduktor/adapters/traktor/export.py b/backend/konduktor/adapters/traktor/export.py index 6063889..bcbe595 100644 --- a/backend/konduktor/adapters/traktor/export.py +++ b/backend/konduktor/adapters/traktor/export.py @@ -64,6 +64,7 @@ OTHER_PLAYLIST = "Other" class TraktorExporter: platform = "traktor" library_filename = "collection.nml" + drive_root = False def capabilities(self): """What a Traktor library can hold — answered with no library to read. diff --git a/backend/konduktor/core/export.py b/backend/konduktor/core/export.py index 1913929..9300cc5 100644 --- a/backend/konduktor/core/export.py +++ b/backend/konduktor/core/export.py @@ -105,6 +105,11 @@ class LibraryExporter(Protocol): platform: str #: What the written library file is called, e.g. "collection.nml". library_filename: str + #: The library is only found when the destination is a DRIVE'S ROOT — a + #: player looks for it there and nowhere else. Several targets can share one + #: destination, so this is a warning the UI raises, not a refusal: the other + #: targets in the same export are still perfectly valid in any folder. + drive_root: bool = False def capabilities(self) -> Capabilities: """What this target can represent — STATIC, with no library to read.""" diff --git a/backend/konduktor/core/model.py b/backend/konduktor/core/model.py index c32b8d0..3fe93a7 100644 --- a/backend/konduktor/core/model.py +++ b/backend/konduktor/core/model.py @@ -214,6 +214,8 @@ class PlatformOption(BaseModel): found: int = 0 #: The library lives on a plugged-in drive, so `found` changes between calls. removable: bool = False + #: As an export TARGET: its library is only found at a drive's root. + drive_root: bool = False class RemapSample(BaseModel): diff --git a/backend/konduktor/core/places.py b/backend/konduktor/core/places.py index b0ba148..6f94064 100644 --- a/backend/konduktor/core/places.py +++ b/backend/konduktor/core/places.py @@ -121,6 +121,18 @@ def is_boot_volume(path: Path) -> bool: return False +def is_drive_root(path: Path) -> bool: + """Whether `path` is the root of a mounted drive — `/Volumes/STICK`, `E:\\`. + + What a OneLibrary export needs, since a CDJ looks for `PIONEER/` there and + nowhere else. A folder that does not exist yet is not one. + """ + try: + return os.path.ismount(Path(path).expanduser()) + except (OSError, ValueError): + return False + + def volumes(*, include_boot: bool = False) -> list[Path]: """Mounted volumes, newest-mounted order not guaranteed. Sorted by name.""" found = [v for v in mount_points() if include_boot or not is_boot_volume(v)] diff --git a/backend/konduktor/exporter.py b/backend/konduktor/exporter.py index 50056f2..0bdb9d0 100644 --- a/backend/konduktor/exporter.py +++ b/backend/konduktor/exporter.py @@ -26,13 +26,25 @@ export writes a **manifest** of what it put there, and a destination that is non-empty without one is REFUSED rather than confirmed. Clearing then removes exactly the manifest's files — anything the user added themselves survives. -## Mirror layout +## Several targets, one copy of the audio + +An export can target several platforms at once. The audio is copied ONCE and +every target's library is written over the same files, one after another. If +any of them fails, EVERYTHING is undone — the audio and the libraries already +written — because "the libraries' absence marks an export unfinished" only +holds if a half-finished multi-target export also leaves none behind. + +## Mirror layout, under `Contents/` Audio is laid out mirroring the source tree, relative to the deepest folder all -the tracks share (`common_dir_prefix`). Mirroring absolute paths would put the -user's home directory on the stick; mirroring relative to the common root keeps -the structure recognisable and makes filename collisions impossible, since two -distinct source paths cannot share a relative path. +the tracks share (`common_dir_prefix`), inside a `Contents/` folder — the name +rekordbox itself uses on a stick. Mirroring absolute paths would put the user's +home directory on the stick; mirroring relative to the common root keeps the +structure recognisable and makes filename collisions impossible, since two +distinct source paths cannot share a relative path. `Contents/` is what keeps +the AUDIO from colliding with the LIBRARIES: without it, a music folder with a +top-level `PIONEER/` or `share/`, or a file called `master.db`, would land on +top of one. """ from __future__ import annotations @@ -42,15 +54,18 @@ from dataclasses import dataclass, field from pathlib import Path from . import exports +from .core import registry from .core.export import ExportPayload, ExportPlaylist, ExportTrack, for_platform from .core.pathmap import common_dir_prefix -from .core.places import is_os_housekeeping +from .core.places import is_drive_root, is_os_housekeeping from .importer import SPACE_HEADROOM, copy_file, free_bytes from .jobs import JobHandle log = logging.getLogger(__name__) MANIFEST_NAME = ".konduktor-export.json" +#: Every exported audio file lives under this folder, never at the root. +AUDIO_DIR = "Contents" #: Why an export cannot run. The UI words these; they are facts, not sentences. BLOCKED_OCCUPIED = "destination_not_empty" @@ -77,6 +92,10 @@ class ExportPlan: blocked: str | None = None #: Whether the destination already holds a Konduktor export to replace. replacing: bool = False + #: Targets whose library is only found at a drive's root, when the + #: destination is not one. A warning, not a block: the other targets are + #: fine anywhere, and the user may be staging a stick's contents on purpose. + not_drive_root: list[str] = field(default_factory=list) @property def exportable(self) -> list[PlannedTrack]: @@ -100,6 +119,7 @@ class ExportPlan: ), "blocked": self.blocked, "replacing": self.replacing, + "not_drive_root": list(self.not_drive_root), } @@ -155,7 +175,9 @@ def _clear(destination: Path) -> None: (destination / name).unlink() except OSError: pass - for name in (data.get("library"), MANIFEST_NAME): + # `library` is the single-target manifest an older export left behind. + libraries = list(data.get("libraries") or []) + [data.get("library")] + for name in (*libraries, MANIFEST_NAME): if name: try: (destination / name).unlink() @@ -186,7 +208,7 @@ def _read_manifest(destination: Path) -> dict: return data if isinstance(data, dict) else {} -def _write_manifest(destination: Path, *, library: str, files: list[str], name: str) -> None: +def _write_manifest(destination: Path, *, libraries: list[str], files: list[str], name: str) -> None: from . import paths paths.write_json( @@ -196,7 +218,7 @@ def _write_manifest(destination: Path, *, library: str, files: list[str], name: "so re-exporting can replace exactly those files.", "export": name, "written": time.time(), - "library": library, + "libraries": libraries, "files": files, }, ) @@ -210,7 +232,8 @@ def plan(adapter, export_set) -> ExportPlan: destination = Path(export_set.destination).expanduser() built = ExportPlan(destination=destination) - if for_platform(export_set.target) is None: + exporters = [for_platform(t) for t in export_set.targets] + if not exporters or None in exporters: built.blocked = BLOCKED_NO_TARGET return built @@ -242,7 +265,7 @@ def plan(adapter, export_set) -> ExportPlan: track_id=track.id, title=track.title or (source.name if source else track.id), source_path=source, - destination=(destination / _relative(source, root)) if exists else None, + destination=(destination / AUDIO_DIR / _relative(source, root)) if exists else None, size=size, missing=not exists, ) @@ -266,6 +289,8 @@ def plan(adapter, export_set) -> ExportPlan: else: built.blocked = destination_blocked(destination) built.replacing = is_ours(destination) + if not is_drive_root(destination): + built.not_drive_root = [e.platform for e in exporters if e.drive_root] return built @@ -299,10 +324,14 @@ def _folder_paths(adapter) -> dict[str, list[str]]: def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict: - """Copy the audio, then write the library. Rolls back everything on cancel.""" - exporter = for_platform(export_set.target) - if exporter is None: - raise ValueError(f"Konduktor cannot export to {export_set.target}") + """Copy the audio once, then write every target's library over it. + + Rolls back EVERYTHING on cancel or on any failure — including the libraries + of targets that had already been written when a later one failed. + """ + exporters = [for_platform(t) for t in export_set.targets] + if not exporters or None in exporters: + raise ValueError(f"Konduktor cannot export to {', '.join(export_set.targets)}") if built.blocked: raise ValueError(f"This export cannot run: {built.blocked}") @@ -315,6 +344,12 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict: # too. Cleaning up only completed copies leaves debris the retry then # suffixes around — a bug the import feature had. created: list[Path] = [] + # What was on disk before the libraries were written. An exporter that + # raises midway has written files it never got to REPORT (a OneLibrary + # drive's analysis files, say), so rollback also removes anything that + # appeared after this snapshot. Safe because the destination is known to + # hold only our files and the user's, and the user's predate it. + before: set[Path] | None = None done = 0 try: destination.mkdir(parents=True, exist_ok=True) @@ -344,27 +379,29 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict: ) ) - handle.raise_if_cancelled() - handle.progress(message=f"Writing the {export_set.target} library…") - written = exporter.write( - ExportPayload( - name=export_set.name, - tracks=payload_tracks, - playlists=built.playlists, - ), - destination, + payload = ExportPayload( + name=export_set.name, + tracks=payload_tracks, + playlists=built.playlists, ) - # Everything the exporter reported, not just the library: a target can - # write a database PLUS a per-track analysis file, and anything left out - # here is an orphan the next re-export cannot clear. - created.extend(written.all_paths) + before = _files(destination) + libraries: list[tuple[str, Path]] = [] + for exporter in exporters: + handle.raise_if_cancelled() + handle.progress(message=f"Writing the {_display_name(exporter.platform)} library…") + written = exporter.write(payload, destination) + # Everything the exporter reported, not just the library: a target + # can write a database PLUS a per-track analysis file, and anything + # left out here is an orphan the next re-export cannot clear. + created.extend(written.all_paths) + libraries.append((exporter.platform, written.library)) - library = written.library + library_paths = {path for _, path in libraries} _write_manifest( destination, - library=str(library.relative_to(destination)), + libraries=[str(p.relative_to(destination)) for _, p in libraries], files=sorted( - {str(p.relative_to(destination)) for p in created if p != library} + {str(p.relative_to(destination)) for p in created if p not in library_paths} ), name=export_set.name, ) @@ -373,13 +410,17 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict: "playlists": len(built.playlists), "skipped": len(built.tracks) - len(items), "destination": str(destination), - "library": str(library), + "libraries": [ + {"platform": platform, "library": str(path.relative_to(destination))} + for platform, path in libraries + ], } except BaseException: # Cancelled or failed: leave no library file and no half-written copies. # Matches import, deliberately — two features whose cancel means # different things is worse than either behaviour on its own. - for path in created: + leftovers = (_files(destination) - before) if before is not None else set() + for path in (*created, *leftovers): try: path.unlink() except OSError: @@ -392,12 +433,26 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict: raise +def _files(root: Path) -> set[Path]: + try: + return {p for p in root.rglob("*") if p.is_file()} + except OSError: + return set() + + +def _display_name(platform: str) -> str: + try: + return registry.driver_by_platform(platform).display_name + except registry.LibraryNotSupported: + return platform + + def space_for(built: ExportPlan) -> int | None: return free_bytes(Path(built.destination)) if built.destination else None __all__ = [ - "BLOCKED_EMPTY", "BLOCKED_NO_TARGET", "BLOCKED_OCCUPIED", "ExportPlan", + "AUDIO_DIR", "BLOCKED_EMPTY", "BLOCKED_NO_TARGET", "BLOCKED_OCCUPIED", "ExportPlan", "MANIFEST_NAME", "PlannedTrack", "destination_blocked", "is_ours", "plan", "run", "space_for", ] diff --git a/backend/konduktor/exports.py b/backend/konduktor/exports.py index 0db0924..5b82101 100644 --- a/backend/konduktor/exports.py +++ b/backend/konduktor/exports.py @@ -1,7 +1,12 @@ """Export sets: a named, persisted slice of the library, bound to a destination. -An export set is what the user curates before exporting — a name, a target -platform, a destination folder, and the tracks and playlists to include. It is +An export set is what the user curates before exporting — a name, one or more +target platforms, a destination folder, and the tracks and playlists to include. + +**Several targets share one destination and one copy of the audio.** Each +target's library references the same files, and none of their layouts collide +(`collection.nml`; `PIONEER/…`; `master.db` + `share/…`), so a stick carrying +both a Traktor collection and a OneLibrary library costs one copy, not two. It is **Konduktor's own data**, never written into the user's library: a Traktor collection has nowhere to put this, and putting it there would mean a concept only Konduktor understands living in a file Traktor rewrites. @@ -51,8 +56,10 @@ class ExportSet: id: str name: str - target: str # platform id of the export TARGET, e.g. "traktor" - destination: str # OS path of the folder the export is written into + #: Platform ids of the export TARGETS, e.g. ["traktor", "onelibrary"]. Never + #: empty; ordered as the user ticked them, which is the order they are written. + targets: list[str] = field(default_factory=lambda: ["traktor"]) + destination: str = "" # OS path of the folder the export is written into playlist_ids: list[str] = field(default_factory=list) track_ids: list[str] = field(default_factory=list) # loose tracks only created: float = 0.0 @@ -128,7 +135,7 @@ def _load(library_id: str) -> dict[str, ExportSet]: out[set_id] = ExportSet( id=set_id, name=values.get("name") or "Untitled", - target=values.get("target") or "traktor", + targets=_targets(values), destination=values.get("destination") or "", playlist_ids=list(values.get("playlist_ids") or []), track_ids=list(values.get("track_ids") or []), @@ -140,6 +147,16 @@ def _load(library_id: str) -> dict[str, ExportSet]: return out +def _targets(values: dict) -> list[str]: + """The set's targets, reading the single `target` sets were saved with first.""" + raw = values.get("targets") + if isinstance(raw, list): + found = [t for t in raw if isinstance(t, str) and t] + if found: + return found + return [values.get("target") or "traktor"] + + def _save(library_id: str, sets: dict[str, ExportSet]) -> None: paths.write_json( _store_path(library_id), @@ -186,13 +203,13 @@ def _normalise(destination: str) -> str: # ---- writing ----------------------------------------------------------------- -def create(library_id: str, *, name: str, target: str, destination: str) -> ExportSet: +def create(library_id: str, *, name: str, targets: list[str], destination: str) -> ExportSet: sets = _load(library_id) now = time.time() created = ExportSet( id=uuid.uuid4().hex, name=name.strip() or "Untitled", - target=target, + targets=list(dict.fromkeys(targets)), destination=destination, created=now, modified=now, @@ -208,9 +225,11 @@ def update(library_id: str, set_id: str, **fields) -> ExportSet | None: found = sets.get(set_id) if found is None: return None - for key in ("name", "target", "destination"): + for key in ("name", "destination"): if key in fields and fields[key] is not None: setattr(found, key, fields[key]) + if fields.get("targets"): + found.targets = list(dict.fromkeys(fields["targets"])) found.modified = time.time() _save(library_id, sets) return found diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index 0d01071..1e6a85a 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -442,12 +442,11 @@ def create_export(body: CreateExportSet) -> ExportSetOut: # Only platforms that can actually be WRITTEN may be targets. Gating here as # well as in the UI, because a set persists: one created against a target # that later stops being supported would otherwise fail at export time. - if body.target not in _export_targets(): - raise HTTPException(422, f"Konduktor cannot export to {body.target} yet") + _check_targets(body.targets) created = exports.create( _require_library_id(), name=body.name, - target=body.target, + targets=body.targets, destination=body.destination, ) return ExportSetOut(**created.as_dict()) @@ -456,13 +455,13 @@ def create_export(body: CreateExportSet) -> ExportSetOut: @app.patch("/api/exports/{set_id}", response_model=ExportSetOut) def update_export(set_id: str, body: UpdateExportSet) -> ExportSetOut: _require_set(set_id) - if body.target is not None and body.target not in _export_targets(): - raise HTTPException(422, f"Konduktor cannot export to {body.target} yet") + if body.targets is not None: + _check_targets(body.targets) updated = exports.update( _require_library_id(), set_id, name=body.name, - target=body.target, + targets=body.targets, destination=body.destination, ) return ExportSetOut(**updated.as_dict()) @@ -600,6 +599,19 @@ def _export_targets() -> set[str]: return core_export.targets() +def _check_targets(targets: list[str]) -> None: + """Refuse a set with no targets, or one naming a platform with no exporter. + + Checked when the set is saved: a target that later stops being supported + would otherwise fail at export time. + """ + if not targets: + raise HTTPException(400, "An export needs at least one platform to export for") + unsupported = [t for t in targets if t not in _export_targets()] + if unsupported: + raise HTTPException(422, f"Konduktor cannot export to {', '.join(unsupported)} yet") + + @app.get("/api/export-targets", response_model=list[PlatformOption]) def export_targets() -> list[PlatformOption]: """Every platform, flagged by whether it can be an export TARGET. @@ -618,6 +630,7 @@ def export_targets() -> list[PlatformOption]: installed=d.platform in supported, found=0, removable=bool(getattr(d, "removable", False)), + drive_root=bool(getattr(core_export.for_platform(d.platform), "drive_root", False)), ) for d in registry.drivers() ] diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index 87d6f5d..5fe3b88 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -196,7 +196,7 @@ class CollectionOptions(BaseModel): class ExportSetOut(BaseModel): id: str name: str - target: str # platform id of the export TARGET + targets: list[str] # platform ids of the export TARGETS, never empty destination: str playlist_ids: list[str] = [] track_ids: list[str] = [] # loose tracks only @@ -206,13 +206,13 @@ class ExportSetOut(BaseModel): class CreateExportSet(BaseModel): name: str - target: str = "traktor" + targets: list[str] = ["traktor"] destination: str class UpdateExportSet(BaseModel): name: str | None = None - target: str | None = None + targets: list[str] | None = None destination: str | None = None @@ -258,6 +258,9 @@ class ExportPreview(BaseModel): blocked: str | None = None #: The destination already holds a Konduktor export, which will be replaced. replacing: bool = False + #: Targets whose library is only found at a drive's root, when the + #: destination is not one. A warning — the export can still run. + not_drive_root: list[str] = [] class FsPlace(BaseModel): diff --git a/backend/test_export.py b/backend/test_export.py index 63bc289..2237de5 100644 --- a/backend/test_export.py +++ b/backend/test_export.py @@ -14,6 +14,7 @@ work perfectly on the machine that made it and resolve to nothing at the gig. Runs against the 8,485-entry fixture collection, so the tracks have real prep — flexible grids, hot cues on specific pads — rather than anything invented here. """ +import json import os import re import tempfile @@ -216,7 +217,7 @@ ad = STATE.adapter LIB = STATE.library_id dest = Path(tempfile.mkdtemp()) / "GIG" -eset = exports.create(LIB, name="GIG", target="traktor", destination=str(dest)) +eset = exports.create(LIB, name="GIG", targets=["traktor"], destination=str(dest)) source_pl = next(n for n in ad.playlist_tree()[0].children if n.kind == "playlist") exports.add(LIB, eset.id, playlist_ids=[source_pl.id], track_ids=[ad.tracks[3].id]) eset = exports.get(LIB, eset.id) @@ -229,14 +230,18 @@ def run_now(plan): return job -print("== the plan mirrors the source tree, relative to its shared root ==") +print("== the plan mirrors the source tree under Contents/, relative to its shared root ==") built = exporter.plan(ad, eset) check("nothing is blocking it", built.blocked is None, str(built.blocked)) check("every track has somewhere to go", all(t.destination for t in built.exportable)) rel = [str(t.destination.relative_to(dest)) for t in built.exportable] +# Under Contents/, so the audio can never land on top of a library's own path. +check("all audio lives under Contents/", + all(r.startswith(exporter.AUDIO_DIR + "/") for r in rel), rel) # Mirroring ABSOLUTE paths would put the user's home directory on the stick. check("the user's own folders are preserved", - all(r.startswith(("House/", "Techno/")) for r in rel), rel) + all(r.startswith(("Contents/House/", "Contents/Techno/")) for r in rel), rel) +check("a Traktor-only export never warns about a drive root", built.not_drive_root == []) check("and nothing above the shared root comes with them", not any("Users" in r or r.startswith("/") for r in rel), rel) check("space is checked before starting", exporter.space_for(built) is not None) @@ -338,6 +343,109 @@ check("no manifest either", not (fresh / exporter.MANIFEST_NAME).exists()) leftover = [p for p in fresh.rglob("*") if p.is_file()] if fresh.exists() else [] check("and no audio was left behind", leftover == [], [str(p) for p in leftover]) +print("== several targets share ONE copy of the audio ==") +from konduktor.adapters.onelibrary.driver import OneLibraryDriver # noqa: E402 + +multi = Path(tempfile.mkdtemp()) / "STICK" +exports.update(LIB, eset.id, destination=str(multi), targets=["traktor", "onelibrary"]) +eset = exports.get(LIB, eset.id) +check("the set keeps both targets, in order", eset.targets == ["traktor", "onelibrary"], eset.targets) +mplan = exporter.plan(ad, eset) +check("nothing is blocking it", mplan.blocked is None, str(mplan.blocked)) +# A temp folder is not a drive's root, and only OneLibrary cares. +check("only the drive-root target is warned about", mplan.not_drive_root == ["onelibrary"], + mplan.not_drive_root) +mjob = run_now(mplan) +check("it finishes", mjob.state == "done", f"{mjob.state}: {mjob.error}") +check("the result names both libraries", + [l["platform"] for l in mjob.result["libraries"]] == ["traktor", "onelibrary"], + mjob.result.get("libraries")) +mrel = [t.destination.relative_to(multi) for t in mplan.exportable] +audio_files = [p for p in multi.rglob("*") if p.is_file() and p.parts[len(multi.parts)] == "Contents"] +check("the audio was copied once, not once per target", len(audio_files) == len(mrel), + f"{len(audio_files)} files for {len(mrel)} tracks") +t_lib = TraktorDriver().open(multi / "collection.nml") +o_lib = OneLibraryDriver().open(multi) +check("the Traktor collection re-opens with every track", len(t_lib.tracks) == len(mrel)) +check("so does the OneLibrary drive", len(o_lib.tracks) == len(mrel)) +# Both libraries must point at the SAME files — a second copy would be a bug +# in the plan, and a dangling path would be one in a writer. +check("every OneLibrary track resolves to a copied file", + all(o_lib.audio_path(t.id) and o_lib.audio_path(t.id).is_file() for t in o_lib.tracks)) +check("OneLibrary paths are drive-relative under /Contents/", + all(t.id.startswith("/Contents/") for t in o_lib.tracks), [t.id for t in o_lib.tracks][:2]) +manifest = json.loads((multi / exporter.MANIFEST_NAME).read_text()) +check("the manifest lists both libraries", + sorted(manifest["libraries"]) == sorted(["collection.nml", str(Path("PIONEER/rekordbox/exportLibrary.db"))]), + manifest["libraries"]) +del t_lib, o_lib + +print("== unticking a target removes its library on the next export ==") +exports.update(LIB, eset.id, targets=["traktor"]) +eset = exports.get(LIB, eset.id) +job3 = run_now(exporter.plan(ad, eset)) +check("the re-export succeeds", job3.state == "done", f"{job3.state}: {job3.error}") +check("the OneLibrary library is gone", not (multi / "PIONEER").exists(), + sorted(str(p.relative_to(multi)) for p in (multi / "PIONEER").rglob("*")) if (multi / "PIONEER").exists() else "") +check("the Traktor one and the audio remain", + (multi / "collection.nml").is_file() and all((multi / r).is_file() for r in mrel)) + +print("== a manifest from a single-target export is still cleared ==") +old = Path(tempfile.mkdtemp()) / "OldExport" +old.mkdir() +(old / "collection.nml").write_text("stale") +(old / "House").mkdir() +(old / "House" / "stale.mp3").write_bytes(b"x") +(old / exporter.MANIFEST_NAME).write_text(json.dumps( + {"library": "collection.nml", "files": ["House/stale.mp3"]})) +exports.update(LIB, eset.id, destination=str(old)) +job4 = run_now(exporter.plan(ad, exports.get(LIB, eset.id))) +check("the re-export succeeds", job4.state == "done", f"{job4.state}: {job4.error}") +check("the old root-level audio was cleared", not (old / "House").exists()) +check("and the new collection replaced the old one", + (old / "collection.nml").read_text() != "stale") + +print("== a failing LATER target undoes everything, earlier targets included ==") +failing = Path(tempfile.mkdtemp()) / "Failing" +exports.update(LIB, eset.id, destination=str(failing), targets=["traktor", "onelibrary"]) +onelib = core_export.for_platform("onelibrary") + + +def _half_written(payload, destination): + # Writes files it never gets to REPORT, then fails — the case the rollback's + # snapshot exists for. + stray = Path(destination) / "PIONEER" / "USBANLZ" / "P000" / "0000" / "ANLZ0000.DAT" + stray.parent.mkdir(parents=True, exist_ok=True) + stray.write_bytes(b"partial") + raise RuntimeError("disk full") + + +eset = exports.get(LIB, eset.id) # run_now() runs the module-level set +onelib.write = _half_written +try: + job5 = run_now(exporter.plan(ad, eset)) +finally: + del onelib.write +check("the export fails", job5.state == "failed", job5.state) +left = sorted(str(p.relative_to(failing)) for p in failing.rglob("*")) if failing.exists() else [] +check("nothing at all is left behind — no audio, no Traktor library, no stray analysis", + left == [], left) +exports.update(LIB, eset.id, destination=str(dest), targets=["traktor"]) +eset = exports.get(LIB, eset.id) + +print("== targets are validated and migrated ==") +check("a set saved with the old single `target` loads as a list", + exports._targets({"target": "onelibrary"}) == ["onelibrary"]) +check("an empty list falls back rather than yielding a set with no target", + exports._targets({"targets": []}) == ["traktor"]) +dup = exports.create(LIB, name="Dup", targets=["traktor", "traktor"], destination=str(dest / "x")) +check("duplicate targets collapse", dup.targets == ["traktor"], dup.targets) +exports.delete(LIB, dup.id) +bad = exports.create(LIB, name="Bad", targets=["traktor", "serato"], destination=str(dest / "y")) +check("one unsupported target blocks the whole plan", + exporter.plan(ad, bad).blocked == exporter.BLOCKED_NO_TARGET) +exports.delete(LIB, bad.id) + print("== a missing file is skipped, not fatal ==") gone = Path(seed_items[0].destination) gone.unlink() diff --git a/backend/test_exports.py b/backend/test_exports.py index 79f3ec3..5933f11 100644 --- a/backend/test_exports.py +++ b/backend/test_exports.py @@ -61,7 +61,7 @@ playlist_tracks = adapter.playlist_entries(playlist.id) or [] all_tracks = [t.id for t in adapter.tracks] print("== creating, listing, updating, deleting ==") -s1 = exports.create(LIB, name="GIG", target="traktor", destination=str(work / "out")) +s1 = exports.create(LIB, name="GIG", targets=["traktor"], destination=str(work / "out")) check("a set is created with an id", bool(s1.id)) check("it lists", [s.id for s in exports.all_sets(LIB)] == [s1.id]) check("it survives a reload from disk", exports.get(LIB, s1.id).name == "GIG") @@ -128,7 +128,7 @@ check("and is NOT counted as exportable", "Macintosh HD/:nowhere/:ghost.mp3" not in gone.track_ids) exports.remove(LIB, s1.id, track_ids=["Macintosh HD/:nowhere/:ghost.mp3"]) -s2 = exports.create(LIB, name="Deleted playlist test", target="traktor", +s2 = exports.create(LIB, name="Deleted playlist test", targets=["traktor"], destination=str(work / "out2")) exports.add(LIB, s2.id, playlist_ids=["no-such-playlist"]) ghost = exports.resolve(adapter, exports.get(LIB, s2.id)) @@ -141,7 +141,7 @@ print("== two sets, one destination ==") # Caught when the destination is chosen, not when it is too late to warn. check("no conflict for distinct destinations", exports.destination_conflict(LIB, str(work / "out"), ignore=s1.id) is None) -s3 = exports.create(LIB, name="Clash", target="traktor", destination=str(work / "out")) +s3 = exports.create(LIB, name="Clash", targets=["traktor"], destination=str(work / "out")) check("a clash is reported by NAME", exports.destination_conflict(LIB, str(work / "out"), ignore=s3.id) == "Ibiza") check("a set never conflicts with itself", @@ -189,7 +189,7 @@ import konduktor.main as main # noqa: E402 ad, lib = STATE.adapter, STATE.library_id prefix = ad.path_prefix_suggestions()["primary"] loose = next(t.id for t in ad.tracks if str(ad.audio_path(t.id) or "").startswith(prefix)) -s3 = exports.create(lib, name="Remapped", target="traktor", destination=str(work / "remapped")) +s3 = exports.create(lib, name="Remapped", targets=["traktor"], destination=str(work / "remapped")) exports.add(lib, s3.id, track_ids=[loose]) r = TestClient(main.app, raise_server_exceptions=False).post( "/api/library/remap-paths", json={"from": prefix, "to": "/Volumes/KonduktorTest"} diff --git a/backend/test_folders.py b/backend/test_folders.py index f1d6858..40f6086 100644 --- a/backend/test_folders.py +++ b/backend/test_folders.py @@ -158,7 +158,7 @@ with TestClient(main.app, raise_server_exceptions=False) as c: print("== a held file is never added twice, but still reaches its target ==") library = STATE.library_id - eset = exports.create(library, name="Folder Export", target="traktor", + eset = exports.create(library, name="Folder Export", targets=["traktor"], destination=str(Path(tempfile.mkdtemp()) / "out")) req = {"track_ids": [str(one), str(two)], "mode": "reference", "playlist_id": playlist, "export_id": eset.id} diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 015560c..ad54815 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -277,6 +277,8 @@ export interface PlatformOption { /** The library lives on plugged-in media, so `found` changes between calls — * and `found === 0` means "nothing plugged in", not "not installed". */ removable: boolean + /** As an export target: its library is only found at a drive's ROOT. */ + drive_root?: boolean } export interface EditState { @@ -447,8 +449,9 @@ export interface SourceStatus { export interface ExportSet { id: string name: string - /** Platform id of the export TARGET, e.g. "traktor". */ - target: string + /** Platform ids of the export TARGETS, e.g. ["traktor", "onelibrary"]. Never + * empty. They share one destination and ONE copy of the audio. */ + targets: string[] destination: string playlist_ids: string[] /** LOOSE tracks only — tracks a referenced playlist supplies are not listed. */ @@ -492,6 +495,9 @@ export interface ExportPreview { blocked: 'destination_not_empty' | 'nothing_to_export' | 'unsupported_target' | null /** The destination already holds a Konduktor export, which will be replaced. */ replacing: boolean + /** Targets whose library is only found at a drive's root, when the destination + * is not one. A warning — the export can still run. */ + not_drive_root: string[] } export interface FsPlace { @@ -649,9 +655,9 @@ export const api = { // All scoped to the LOADED library on the server, by its stable id, so // nothing here has to carry which collection it means. exports: () => getJSON('/api/exports'), - createExport: (body: { name: string; target: string; destination: string }) => + createExport: (body: { name: string; targets: string[]; destination: string }) => send('POST', '/api/exports', body), - updateExport: (id: string, body: Partial>) => + updateExport: (id: string, body: Partial>) => send('PATCH', `/api/exports/${encodeURIComponent(id)}`, body), deleteExport: (id: string) => send<{ deleted: boolean }>('DELETE', `/api/exports/${encodeURIComponent(id)}`), diff --git a/frontend/src/components/ExportDialog.tsx b/frontend/src/components/ExportDialog.tsx index 898f1b6..09f8f09 100644 --- a/frontend/src/components/ExportDialog.tsx +++ b/frontend/src/components/ExportDialog.tsx @@ -5,7 +5,11 @@ import { api, type ExportSet } from '../api' import { FolderPicker } from './FolderPicker' /** - * Create or edit an export: its name, its target platform and where it lands. + * Create or edit an export: its name, its target platforms and where it lands. + * + * Several platforms can be ticked. They share the destination and ONE copy of + * the audio (under `Contents/`), each writing its own library beside it — so a + * stick can carry a Traktor collection and a OneLibrary library at once. * * All three are settled up front, and the destination especially is NOT a * detail deferred to export time. A Traktor `` is a volume name plus @@ -23,7 +27,7 @@ interface Props { export function ExportDialog({ editing, onClose, onSaved, onError }: Props) { const [name, setName] = useState(editing?.name ?? '') - const [target, setTarget] = useState(editing?.target ?? 'traktor') + const [chosen, setChosen] = useState(editing?.targets ?? ['traktor']) const [destination, setDestination] = useState(editing?.destination ?? '') const [browsing, setBrowsing] = useState(false) const [busy, setBusy] = useState(false) @@ -42,12 +46,29 @@ export function ExportDialog({ editing, onClose, onSaved, onError }: Props) { enabled: !!editing, }).data?.destination_conflict - const valid = name.trim() !== '' && destination.trim() !== '' + // Some targets are only found at a drive's root (a CDJ looks for `PIONEER/` + // there and nowhere else). Warned, not refused: the other targets are fine in + // any folder. Checked against the same polled drive list the sidebar uses. + const drives = useQuery({ queryKey: ['drives'], queryFn: api.drives }) + const trim = (p: string) => p.replace(/[\\/]+$/, '') || p + const atDriveRoot = + destination.trim() !== '' && + (drives.data ?? []).some((d) => trim(d.path) === trim(destination.trim())) + const needsRoot = (targets.data ?? []).filter( + (p) => p.drive_root && chosen.includes(p.platform), + ) + + const toggle = (platform: string, on: boolean) => + setChosen((prev) => + on ? [...prev.filter((t) => t !== platform), platform] : prev.filter((t) => t !== platform), + ) + + const valid = name.trim() !== '' && destination.trim() !== '' && chosen.length > 0 const save = async () => { setBusy(true) try { - const body = { name: name.trim(), target, destination: destination.trim() } + const body = { name: name.trim(), targets: chosen, destination: destination.trim() } const saved = editing ? await api.updateExport(editing.id, body) : await api.createExport(body) @@ -102,10 +123,10 @@ export function ExportDialog({ editing, onClose, onSaved, onError }: Props) { }`} > setTarget(p.platform)} + checked={chosen.includes(p.platform)} + onChange={(e) => toggle(p.platform, e.target.checked)} className="accent-accent" /> {p.name} @@ -137,9 +158,16 @@ export function ExportDialog({ editing, onClose, onSaved, onError }: Props) {
- The folder gets a collection.nml and a copy of - every track, in your own folder structure. + The folder gets a library for each platform, plus one copy of every track under{' '} + Contents/, in your own folder structure.
+ {needsRoot.length > 0 && destination.trim() !== '' && !atDriveRoot && ( +
+ {needsRoot.map((p) => p.name).join(' and ')} is only found at the top of a + drive. Choose the drive itself rather than a folder on it, or players won’t see + this export. +
+ )} {conflict && (
“{conflict}” already exports here. Exporting replaces whatever the other one diff --git a/frontend/src/components/ExportRunDialog.tsx b/frontend/src/components/ExportRunDialog.tsx index 07e7ea9..14da22f 100644 --- a/frontend/src/components/ExportRunDialog.tsx +++ b/frontend/src/components/ExportRunDialog.tsx @@ -38,6 +38,10 @@ export function ExportRunDialog({ set, onClose, onDone, onError }: Props) { const [starting, setStarting] = useState(false) const pollRef = useRef(null) + // Platform names for wording the facts the preview and result carry as ids. + const platforms = useQuery({ queryKey: ['export-targets'], queryFn: api.exportTargets }) + const nameOf = (id: string) => platforms.data?.find((p) => p.platform === id)?.name ?? id + const preview = useQuery({ queryKey: ['export-preview', set.id], queryFn: () => api.exportPreview(set.id), @@ -155,9 +159,19 @@ export function ExportRunDialog({ set, onClose, onDone, onError }: Props) { This folder already holds an export. Its files will be replaced.
)} + {/* A warning, not a block: the other targets are fine anywhere, + and staging a stick's contents in a folder is legitimate. */} + {p.not_drive_root.length > 0 && ( +
+ {p.not_drive_root.map(nameOf).join(' and ')} is only found at the top of a + drive, and this folder isn’t one — players won’t see it unless you move the + folder’s contents to a drive’s top level. +
+ )}
- Writes a collection.nml plus a copy of every - track, in your own folder structure. + Writes a library for {set.targets.map(nameOf).join(' and ')}, sharing one copy + of every track under Contents/, in your own + folder structure.
)} @@ -209,21 +223,26 @@ export function ExportRunDialog({ set, onClose, onDone, onError }: Props) { )} {job.state === 'cancelled' && (
- Cancelled. Everything this export copied was removed, and no library file was + Cancelled. Everything this export copied was removed, and no library was written.
)} - {job.state === 'failed' &&
{job.error}
} + {job.state === 'failed' && ( +
+ {job.error} — nothing was left behind: no audio, and no library for any platform. +
+ )} {job.state === 'done' && (
Done — the folder is ready.
- {/* Ben's workflow: the exported collection.nml is swapped into - a Traktor install, which REPLACES that machine's own. */} -
- To use it: quit Traktor, back up its existing{' '} - collection.nml, then put this one in its - place. -
+ {( + (job.result as { libraries?: { platform: string; library: string }[] } | null) + ?.libraries ?? [] + ).map((l) => ( +
+ {nameOf(l.platform)}: {l.library} +
+ ))}
)} diff --git a/frontend/src/components/ExportsSection.tsx b/frontend/src/components/ExportsSection.tsx index fabf39e..df39f9b 100644 --- a/frontend/src/components/ExportsSection.tsx +++ b/frontend/src/components/ExportsSection.tsx @@ -197,7 +197,7 @@ function ExportRow({