mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 18:22:53 +01:00
Exports can now be multiplatform
This commit is contained in:
1 parent
99d590a051
commit
c2f5191962
18 files changed
+373
-86
No files matched your search
@@ -284,7 +284,10 @@ Two independent apps that talk over HTTP:
|
|||||||
path-derived id that `is_durable()` reports honestly. Writing beside the
|
path-derived id that `is_durable()` reports honestly. Writing beside the
|
||||||
library is not a new intrusion — saves already create `backups/` there.
|
library is not a new intrusion — saves already create `backups/` there.
|
||||||
- `exports.py` — **export sets**: a named, persisted slice of the library bound
|
- `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
|
(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
|
Traktor rewrites). Three rules shape it: references are **LIVE** (a set
|
||||||
stores playlist *ids*, resolved at export time, so `resolve()` is computed on
|
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.
|
tags and the `cue` table's MPEG seek columns.
|
||||||
**Step 5 done**: `exporter.py` — plan, mirrored copy, manifest, rollback — on
|
**Step 5 done**: `exporter.py` — plan, mirrored copy, manifest, rollback — on
|
||||||
`jobs.py`, plus `POST /api/exports/{id}/preview` and `/run`, and the
|
`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
|
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
|
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**
|
BEFORE writing it, so the in-flight copy is cleaned up too; and the **manifest**
|
||||||
|
|||||||
@@ -86,6 +86,8 @@ class OneLibraryExporter:
|
|||||||
platform = "onelibrary"
|
platform = "onelibrary"
|
||||||
#: Relative to the drive root, which is what the destination folder is.
|
#: Relative to the drive root, which is what the destination folder is.
|
||||||
library_filename = str(Path("PIONEER") / DB_SUBPATH)
|
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):
|
def capabilities(self):
|
||||||
"""What a drive can hold — no device, no path, no library to read.
|
"""What a drive can hold — no device, no path, no library to read.
|
||||||
|
|||||||
@@ -83,6 +83,7 @@ OTHER_PLAYLIST = "Other"
|
|||||||
class RekordboxExporter:
|
class RekordboxExporter:
|
||||||
platform = "rekordbox"
|
platform = "rekordbox"
|
||||||
library_filename = "master.db"
|
library_filename = "master.db"
|
||||||
|
drive_root = False
|
||||||
|
|
||||||
def capabilities(self):
|
def capabilities(self):
|
||||||
"""What a Rekordbox library can hold, with no library to read.
|
"""What a Rekordbox library can hold, with no library to read.
|
||||||
|
|||||||
@@ -64,6 +64,7 @@ OTHER_PLAYLIST = "Other"
|
|||||||
class TraktorExporter:
|
class TraktorExporter:
|
||||||
platform = "traktor"
|
platform = "traktor"
|
||||||
library_filename = "collection.nml"
|
library_filename = "collection.nml"
|
||||||
|
drive_root = False
|
||||||
|
|
||||||
def capabilities(self):
|
def capabilities(self):
|
||||||
"""What a Traktor library can hold — answered with no library to read.
|
"""What a Traktor library can hold — answered with no library to read.
|
||||||
|
|||||||
@@ -105,6 +105,11 @@ class LibraryExporter(Protocol):
|
|||||||
platform: str
|
platform: str
|
||||||
#: What the written library file is called, e.g. "collection.nml".
|
#: What the written library file is called, e.g. "collection.nml".
|
||||||
library_filename: str
|
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:
|
def capabilities(self) -> Capabilities:
|
||||||
"""What this target can represent — STATIC, with no library to read."""
|
"""What this target can represent — STATIC, with no library to read."""
|
||||||
|
|||||||
@@ -214,6 +214,8 @@ class PlatformOption(BaseModel):
|
|||||||
found: int = 0
|
found: int = 0
|
||||||
#: The library lives on a plugged-in drive, so `found` changes between calls.
|
#: The library lives on a plugged-in drive, so `found` changes between calls.
|
||||||
removable: bool = False
|
removable: bool = False
|
||||||
|
#: As an export TARGET: its library is only found at a drive's root.
|
||||||
|
drive_root: bool = False
|
||||||
|
|
||||||
|
|
||||||
class RemapSample(BaseModel):
|
class RemapSample(BaseModel):
|
||||||
|
|||||||
@@ -121,6 +121,18 @@ def is_boot_volume(path: Path) -> bool:
|
|||||||
return False
|
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]:
|
def volumes(*, include_boot: bool = False) -> list[Path]:
|
||||||
"""Mounted volumes, newest-mounted order not guaranteed. Sorted by name."""
|
"""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)]
|
found = [v for v in mount_points() if include_boot or not is_boot_volume(v)]
|
||||||
|
|||||||
@@ -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
|
non-empty without one is REFUSED rather than confirmed. Clearing then removes
|
||||||
exactly the manifest's files — anything the user added themselves survives.
|
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
|
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
|
the tracks share (`common_dir_prefix`), inside a `Contents/` folder — the name
|
||||||
user's home directory on the stick; mirroring relative to the common root keeps
|
rekordbox itself uses on a stick. Mirroring absolute paths would put the user's
|
||||||
the structure recognisable and makes filename collisions impossible, since two
|
home directory on the stick; mirroring relative to the common root keeps the
|
||||||
distinct source paths cannot share a relative path.
|
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
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -42,15 +54,18 @@ from dataclasses import dataclass, field
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from . import exports
|
from . import exports
|
||||||
|
from .core import registry
|
||||||
from .core.export import ExportPayload, ExportPlaylist, ExportTrack, for_platform
|
from .core.export import ExportPayload, ExportPlaylist, ExportTrack, for_platform
|
||||||
from .core.pathmap import common_dir_prefix
|
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 .importer import SPACE_HEADROOM, copy_file, free_bytes
|
||||||
from .jobs import JobHandle
|
from .jobs import JobHandle
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
MANIFEST_NAME = ".konduktor-export.json"
|
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.
|
#: Why an export cannot run. The UI words these; they are facts, not sentences.
|
||||||
BLOCKED_OCCUPIED = "destination_not_empty"
|
BLOCKED_OCCUPIED = "destination_not_empty"
|
||||||
@@ -77,6 +92,10 @@ class ExportPlan:
|
|||||||
blocked: str | None = None
|
blocked: str | None = None
|
||||||
#: Whether the destination already holds a Konduktor export to replace.
|
#: Whether the destination already holds a Konduktor export to replace.
|
||||||
replacing: bool = False
|
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
|
@property
|
||||||
def exportable(self) -> list[PlannedTrack]:
|
def exportable(self) -> list[PlannedTrack]:
|
||||||
@@ -100,6 +119,7 @@ class ExportPlan:
|
|||||||
),
|
),
|
||||||
"blocked": self.blocked,
|
"blocked": self.blocked,
|
||||||
"replacing": self.replacing,
|
"replacing": self.replacing,
|
||||||
|
"not_drive_root": list(self.not_drive_root),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -155,7 +175,9 @@ def _clear(destination: Path) -> None:
|
|||||||
(destination / name).unlink()
|
(destination / name).unlink()
|
||||||
except OSError:
|
except OSError:
|
||||||
pass
|
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:
|
if name:
|
||||||
try:
|
try:
|
||||||
(destination / name).unlink()
|
(destination / name).unlink()
|
||||||
@@ -186,7 +208,7 @@ def _read_manifest(destination: Path) -> dict:
|
|||||||
return data if isinstance(data, dict) else {}
|
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
|
from . import paths
|
||||||
|
|
||||||
paths.write_json(
|
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.",
|
"so re-exporting can replace exactly those files.",
|
||||||
"export": name,
|
"export": name,
|
||||||
"written": time.time(),
|
"written": time.time(),
|
||||||
"library": library,
|
"libraries": libraries,
|
||||||
"files": files,
|
"files": files,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -210,7 +232,8 @@ def plan(adapter, export_set) -> ExportPlan:
|
|||||||
destination = Path(export_set.destination).expanduser()
|
destination = Path(export_set.destination).expanduser()
|
||||||
built = ExportPlan(destination=destination)
|
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
|
built.blocked = BLOCKED_NO_TARGET
|
||||||
return built
|
return built
|
||||||
|
|
||||||
@@ -242,7 +265,7 @@ def plan(adapter, export_set) -> ExportPlan:
|
|||||||
track_id=track.id,
|
track_id=track.id,
|
||||||
title=track.title or (source.name if source else track.id),
|
title=track.title or (source.name if source else track.id),
|
||||||
source_path=source,
|
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,
|
size=size,
|
||||||
missing=not exists,
|
missing=not exists,
|
||||||
)
|
)
|
||||||
@@ -266,6 +289,8 @@ def plan(adapter, export_set) -> ExportPlan:
|
|||||||
else:
|
else:
|
||||||
built.blocked = destination_blocked(destination)
|
built.blocked = destination_blocked(destination)
|
||||||
built.replacing = is_ours(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
|
return built
|
||||||
|
|
||||||
|
|
||||||
@@ -299,10 +324,14 @@ def _folder_paths(adapter) -> dict[str, list[str]]:
|
|||||||
|
|
||||||
|
|
||||||
def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict:
|
def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict:
|
||||||
"""Copy the audio, then write the library. Rolls back everything on cancel."""
|
"""Copy the audio once, then write every target's library over it.
|
||||||
exporter = for_platform(export_set.target)
|
|
||||||
if exporter is None:
|
Rolls back EVERYTHING on cancel or on any failure — including the libraries
|
||||||
raise ValueError(f"Konduktor cannot export to {export_set.target}")
|
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:
|
if built.blocked:
|
||||||
raise ValueError(f"This export cannot run: {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
|
# too. Cleaning up only completed copies leaves debris the retry then
|
||||||
# suffixes around — a bug the import feature had.
|
# suffixes around — a bug the import feature had.
|
||||||
created: list[Path] = []
|
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
|
done = 0
|
||||||
try:
|
try:
|
||||||
destination.mkdir(parents=True, exist_ok=True)
|
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()
|
payload = ExportPayload(
|
||||||
handle.progress(message=f"Writing the {export_set.target} library…")
|
name=export_set.name,
|
||||||
written = exporter.write(
|
tracks=payload_tracks,
|
||||||
ExportPayload(
|
playlists=built.playlists,
|
||||||
name=export_set.name,
|
|
||||||
tracks=payload_tracks,
|
|
||||||
playlists=built.playlists,
|
|
||||||
),
|
|
||||||
destination,
|
|
||||||
)
|
)
|
||||||
# Everything the exporter reported, not just the library: a target can
|
before = _files(destination)
|
||||||
# write a database PLUS a per-track analysis file, and anything left out
|
libraries: list[tuple[str, Path]] = []
|
||||||
# here is an orphan the next re-export cannot clear.
|
for exporter in exporters:
|
||||||
created.extend(written.all_paths)
|
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(
|
_write_manifest(
|
||||||
destination,
|
destination,
|
||||||
library=str(library.relative_to(destination)),
|
libraries=[str(p.relative_to(destination)) for _, p in libraries],
|
||||||
files=sorted(
|
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,
|
name=export_set.name,
|
||||||
)
|
)
|
||||||
@@ -373,13 +410,17 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict:
|
|||||||
"playlists": len(built.playlists),
|
"playlists": len(built.playlists),
|
||||||
"skipped": len(built.tracks) - len(items),
|
"skipped": len(built.tracks) - len(items),
|
||||||
"destination": str(destination),
|
"destination": str(destination),
|
||||||
"library": str(library),
|
"libraries": [
|
||||||
|
{"platform": platform, "library": str(path.relative_to(destination))}
|
||||||
|
for platform, path in libraries
|
||||||
|
],
|
||||||
}
|
}
|
||||||
except BaseException:
|
except BaseException:
|
||||||
# Cancelled or failed: leave no library file and no half-written copies.
|
# Cancelled or failed: leave no library file and no half-written copies.
|
||||||
# Matches import, deliberately — two features whose cancel means
|
# Matches import, deliberately — two features whose cancel means
|
||||||
# different things is worse than either behaviour on its own.
|
# 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:
|
try:
|
||||||
path.unlink()
|
path.unlink()
|
||||||
except OSError:
|
except OSError:
|
||||||
@@ -392,12 +433,26 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict:
|
|||||||
raise
|
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:
|
def space_for(built: ExportPlan) -> int | None:
|
||||||
return free_bytes(Path(built.destination)) if built.destination else None
|
return free_bytes(Path(built.destination)) if built.destination else None
|
||||||
|
|
||||||
|
|
||||||
__all__ = [
|
__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",
|
"MANIFEST_NAME", "PlannedTrack", "destination_blocked", "is_ours", "plan",
|
||||||
"run", "space_for",
|
"run", "space_for",
|
||||||
]
|
]
|
||||||
@@ -1,7 +1,12 @@
|
|||||||
"""Export sets: a named, persisted slice of the library, bound to a destination.
|
"""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
|
An export set is what the user curates before exporting — a name, one or more
|
||||||
platform, a destination folder, and the tracks and playlists to include. It is
|
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
|
**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
|
collection has nowhere to put this, and putting it there would mean a concept
|
||||||
only Konduktor understands living in a file Traktor rewrites.
|
only Konduktor understands living in a file Traktor rewrites.
|
||||||
@@ -51,8 +56,10 @@ class ExportSet:
|
|||||||
|
|
||||||
id: str
|
id: str
|
||||||
name: str
|
name: str
|
||||||
target: str # platform id of the export TARGET, e.g. "traktor"
|
#: Platform ids of the export TARGETS, e.g. ["traktor", "onelibrary"]. Never
|
||||||
destination: str # OS path of the folder the export is written into
|
#: 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)
|
playlist_ids: list[str] = field(default_factory=list)
|
||||||
track_ids: list[str] = field(default_factory=list) # loose tracks only
|
track_ids: list[str] = field(default_factory=list) # loose tracks only
|
||||||
created: float = 0.0
|
created: float = 0.0
|
||||||
@@ -128,7 +135,7 @@ def _load(library_id: str) -> dict[str, ExportSet]:
|
|||||||
out[set_id] = ExportSet(
|
out[set_id] = ExportSet(
|
||||||
id=set_id,
|
id=set_id,
|
||||||
name=values.get("name") or "Untitled",
|
name=values.get("name") or "Untitled",
|
||||||
target=values.get("target") or "traktor",
|
targets=_targets(values),
|
||||||
destination=values.get("destination") or "",
|
destination=values.get("destination") or "",
|
||||||
playlist_ids=list(values.get("playlist_ids") or []),
|
playlist_ids=list(values.get("playlist_ids") or []),
|
||||||
track_ids=list(values.get("track_ids") or []),
|
track_ids=list(values.get("track_ids") or []),
|
||||||
@@ -140,6 +147,16 @@ def _load(library_id: str) -> dict[str, ExportSet]:
|
|||||||
return out
|
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:
|
def _save(library_id: str, sets: dict[str, ExportSet]) -> None:
|
||||||
paths.write_json(
|
paths.write_json(
|
||||||
_store_path(library_id),
|
_store_path(library_id),
|
||||||
@@ -186,13 +203,13 @@ def _normalise(destination: str) -> str:
|
|||||||
# ---- writing -----------------------------------------------------------------
|
# ---- 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)
|
sets = _load(library_id)
|
||||||
now = time.time()
|
now = time.time()
|
||||||
created = ExportSet(
|
created = ExportSet(
|
||||||
id=uuid.uuid4().hex,
|
id=uuid.uuid4().hex,
|
||||||
name=name.strip() or "Untitled",
|
name=name.strip() or "Untitled",
|
||||||
target=target,
|
targets=list(dict.fromkeys(targets)),
|
||||||
destination=destination,
|
destination=destination,
|
||||||
created=now,
|
created=now,
|
||||||
modified=now,
|
modified=now,
|
||||||
@@ -208,9 +225,11 @@ def update(library_id: str, set_id: str, **fields) -> ExportSet | None:
|
|||||||
found = sets.get(set_id)
|
found = sets.get(set_id)
|
||||||
if found is None:
|
if found is None:
|
||||||
return None
|
return None
|
||||||
for key in ("name", "target", "destination"):
|
for key in ("name", "destination"):
|
||||||
if key in fields and fields[key] is not None:
|
if key in fields and fields[key] is not None:
|
||||||
setattr(found, key, fields[key])
|
setattr(found, key, fields[key])
|
||||||
|
if fields.get("targets"):
|
||||||
|
found.targets = list(dict.fromkeys(fields["targets"]))
|
||||||
found.modified = time.time()
|
found.modified = time.time()
|
||||||
_save(library_id, sets)
|
_save(library_id, sets)
|
||||||
return found
|
return found
|
||||||
|
|||||||
@@ -442,12 +442,11 @@ def create_export(body: CreateExportSet) -> ExportSetOut:
|
|||||||
# Only platforms that can actually be WRITTEN may be targets. Gating here as
|
# 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
|
# 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.
|
# that later stops being supported would otherwise fail at export time.
|
||||||
if body.target not in _export_targets():
|
_check_targets(body.targets)
|
||||||
raise HTTPException(422, f"Konduktor cannot export to {body.target} yet")
|
|
||||||
created = exports.create(
|
created = exports.create(
|
||||||
_require_library_id(),
|
_require_library_id(),
|
||||||
name=body.name,
|
name=body.name,
|
||||||
target=body.target,
|
targets=body.targets,
|
||||||
destination=body.destination,
|
destination=body.destination,
|
||||||
)
|
)
|
||||||
return ExportSetOut(**created.as_dict())
|
return ExportSetOut(**created.as_dict())
|
||||||
@@ -456,13 +455,13 @@ def create_export(body: CreateExportSet) -> ExportSetOut:
|
|||||||
@app.patch("/api/exports/{set_id}", response_model=ExportSetOut)
|
@app.patch("/api/exports/{set_id}", response_model=ExportSetOut)
|
||||||
def update_export(set_id: str, body: UpdateExportSet) -> ExportSetOut:
|
def update_export(set_id: str, body: UpdateExportSet) -> ExportSetOut:
|
||||||
_require_set(set_id)
|
_require_set(set_id)
|
||||||
if body.target is not None and body.target not in _export_targets():
|
if body.targets is not None:
|
||||||
raise HTTPException(422, f"Konduktor cannot export to {body.target} yet")
|
_check_targets(body.targets)
|
||||||
updated = exports.update(
|
updated = exports.update(
|
||||||
_require_library_id(),
|
_require_library_id(),
|
||||||
set_id,
|
set_id,
|
||||||
name=body.name,
|
name=body.name,
|
||||||
target=body.target,
|
targets=body.targets,
|
||||||
destination=body.destination,
|
destination=body.destination,
|
||||||
)
|
)
|
||||||
return ExportSetOut(**updated.as_dict())
|
return ExportSetOut(**updated.as_dict())
|
||||||
@@ -600,6 +599,19 @@ def _export_targets() -> set[str]:
|
|||||||
return core_export.targets()
|
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])
|
@app.get("/api/export-targets", response_model=list[PlatformOption])
|
||||||
def export_targets() -> list[PlatformOption]:
|
def export_targets() -> list[PlatformOption]:
|
||||||
"""Every platform, flagged by whether it can be an export TARGET.
|
"""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,
|
installed=d.platform in supported,
|
||||||
found=0,
|
found=0,
|
||||||
removable=bool(getattr(d, "removable", False)),
|
removable=bool(getattr(d, "removable", False)),
|
||||||
|
drive_root=bool(getattr(core_export.for_platform(d.platform), "drive_root", False)),
|
||||||
)
|
)
|
||||||
for d in registry.drivers()
|
for d in registry.drivers()
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -196,7 +196,7 @@ class CollectionOptions(BaseModel):
|
|||||||
class ExportSetOut(BaseModel):
|
class ExportSetOut(BaseModel):
|
||||||
id: str
|
id: str
|
||||||
name: str
|
name: str
|
||||||
target: str # platform id of the export TARGET
|
targets: list[str] # platform ids of the export TARGETS, never empty
|
||||||
destination: str
|
destination: str
|
||||||
playlist_ids: list[str] = []
|
playlist_ids: list[str] = []
|
||||||
track_ids: list[str] = [] # loose tracks only
|
track_ids: list[str] = [] # loose tracks only
|
||||||
@@ -206,13 +206,13 @@ class ExportSetOut(BaseModel):
|
|||||||
|
|
||||||
class CreateExportSet(BaseModel):
|
class CreateExportSet(BaseModel):
|
||||||
name: str
|
name: str
|
||||||
target: str = "traktor"
|
targets: list[str] = ["traktor"]
|
||||||
destination: str
|
destination: str
|
||||||
|
|
||||||
|
|
||||||
class UpdateExportSet(BaseModel):
|
class UpdateExportSet(BaseModel):
|
||||||
name: str | None = None
|
name: str | None = None
|
||||||
target: str | None = None
|
targets: list[str] | None = None
|
||||||
destination: str | None = None
|
destination: str | None = None
|
||||||
|
|
||||||
|
|
||||||
@@ -258,6 +258,9 @@ class ExportPreview(BaseModel):
|
|||||||
blocked: str | None = None
|
blocked: str | None = None
|
||||||
#: The destination already holds a Konduktor export, which will be replaced.
|
#: The destination already holds a Konduktor export, which will be replaced.
|
||||||
replacing: bool = False
|
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):
|
class FsPlace(BaseModel):
|
||||||
|
|||||||
+111
-3
@@ -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 —
|
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.
|
flexible grids, hot cues on specific pads — rather than anything invented here.
|
||||||
"""
|
"""
|
||||||
|
import json
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import tempfile
|
import tempfile
|
||||||
@@ -216,7 +217,7 @@ ad = STATE.adapter
|
|||||||
LIB = STATE.library_id
|
LIB = STATE.library_id
|
||||||
|
|
||||||
dest = Path(tempfile.mkdtemp()) / "GIG"
|
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")
|
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])
|
exports.add(LIB, eset.id, playlist_ids=[source_pl.id], track_ids=[ad.tracks[3].id])
|
||||||
eset = exports.get(LIB, eset.id)
|
eset = exports.get(LIB, eset.id)
|
||||||
@@ -229,14 +230,18 @@ def run_now(plan):
|
|||||||
return job
|
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)
|
built = exporter.plan(ad, eset)
|
||||||
check("nothing is blocking it", built.blocked is None, str(built.blocked))
|
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))
|
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]
|
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.
|
# Mirroring ABSOLUTE paths would put the user's home directory on the stick.
|
||||||
check("the user's own folders are preserved",
|
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",
|
check("and nothing above the shared root comes with them",
|
||||||
not any("Users" in r or r.startswith("/") for r in rel), rel)
|
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)
|
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 []
|
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])
|
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 ==")
|
print("== a missing file is skipped, not fatal ==")
|
||||||
gone = Path(seed_items[0].destination)
|
gone = Path(seed_items[0].destination)
|
||||||
gone.unlink()
|
gone.unlink()
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ playlist_tracks = adapter.playlist_entries(playlist.id) or []
|
|||||||
all_tracks = [t.id for t in adapter.tracks]
|
all_tracks = [t.id for t in adapter.tracks]
|
||||||
|
|
||||||
print("== creating, listing, updating, deleting ==")
|
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("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 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")
|
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)
|
"Macintosh HD/:nowhere/:ghost.mp3" not in gone.track_ids)
|
||||||
exports.remove(LIB, s1.id, track_ids=["Macintosh HD/:nowhere/:ghost.mp3"])
|
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"))
|
destination=str(work / "out2"))
|
||||||
exports.add(LIB, s2.id, playlist_ids=["no-such-playlist"])
|
exports.add(LIB, s2.id, playlist_ids=["no-such-playlist"])
|
||||||
ghost = exports.resolve(adapter, exports.get(LIB, s2.id))
|
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.
|
# Caught when the destination is chosen, not when it is too late to warn.
|
||||||
check("no conflict for distinct destinations",
|
check("no conflict for distinct destinations",
|
||||||
exports.destination_conflict(LIB, str(work / "out"), ignore=s1.id) is None)
|
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",
|
check("a clash is reported by NAME",
|
||||||
exports.destination_conflict(LIB, str(work / "out"), ignore=s3.id) == "Ibiza")
|
exports.destination_conflict(LIB, str(work / "out"), ignore=s3.id) == "Ibiza")
|
||||||
check("a set never conflicts with itself",
|
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
|
ad, lib = STATE.adapter, STATE.library_id
|
||||||
prefix = ad.path_prefix_suggestions()["primary"]
|
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))
|
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])
|
exports.add(lib, s3.id, track_ids=[loose])
|
||||||
r = TestClient(main.app, raise_server_exceptions=False).post(
|
r = TestClient(main.app, raise_server_exceptions=False).post(
|
||||||
"/api/library/remap-paths", json={"from": prefix, "to": "/Volumes/KonduktorTest"}
|
"/api/library/remap-paths", json={"from": prefix, "to": "/Volumes/KonduktorTest"}
|
||||||
|
|||||||
@@ -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 ==")
|
print("== a held file is never added twice, but still reaches its target ==")
|
||||||
library = STATE.library_id
|
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"))
|
destination=str(Path(tempfile.mkdtemp()) / "out"))
|
||||||
req = {"track_ids": [str(one), str(two)], "mode": "reference",
|
req = {"track_ids": [str(one), str(two)], "mode": "reference",
|
||||||
"playlist_id": playlist, "export_id": eset.id}
|
"playlist_id": playlist, "export_id": eset.id}
|
||||||
|
|||||||
+10
-4
@@ -277,6 +277,8 @@ export interface PlatformOption {
|
|||||||
/** The library lives on plugged-in media, so `found` changes between calls —
|
/** The library lives on plugged-in media, so `found` changes between calls —
|
||||||
* and `found === 0` means "nothing plugged in", not "not installed". */
|
* and `found === 0` means "nothing plugged in", not "not installed". */
|
||||||
removable: boolean
|
removable: boolean
|
||||||
|
/** As an export target: its library is only found at a drive's ROOT. */
|
||||||
|
drive_root?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface EditState {
|
export interface EditState {
|
||||||
@@ -447,8 +449,9 @@ export interface SourceStatus {
|
|||||||
export interface ExportSet {
|
export interface ExportSet {
|
||||||
id: string
|
id: string
|
||||||
name: string
|
name: string
|
||||||
/** Platform id of the export TARGET, e.g. "traktor". */
|
/** Platform ids of the export TARGETS, e.g. ["traktor", "onelibrary"]. Never
|
||||||
target: string
|
* empty. They share one destination and ONE copy of the audio. */
|
||||||
|
targets: string[]
|
||||||
destination: string
|
destination: string
|
||||||
playlist_ids: string[]
|
playlist_ids: string[]
|
||||||
/** LOOSE tracks only — tracks a referenced playlist supplies are not listed. */
|
/** 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
|
blocked: 'destination_not_empty' | 'nothing_to_export' | 'unsupported_target' | null
|
||||||
/** The destination already holds a Konduktor export, which will be replaced. */
|
/** The destination already holds a Konduktor export, which will be replaced. */
|
||||||
replacing: boolean
|
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 {
|
export interface FsPlace {
|
||||||
@@ -649,9 +655,9 @@ export const api = {
|
|||||||
// All scoped to the LOADED library on the server, by its stable id, so
|
// All scoped to the LOADED library on the server, by its stable id, so
|
||||||
// nothing here has to carry which collection it means.
|
// nothing here has to carry which collection it means.
|
||||||
exports: () => getJSON<ExportSet[]>('/api/exports'),
|
exports: () => getJSON<ExportSet[]>('/api/exports'),
|
||||||
createExport: (body: { name: string; target: string; destination: string }) =>
|
createExport: (body: { name: string; targets: string[]; destination: string }) =>
|
||||||
send<ExportSet>('POST', '/api/exports', body),
|
send<ExportSet>('POST', '/api/exports', body),
|
||||||
updateExport: (id: string, body: Partial<Pick<ExportSet, 'name' | 'target' | 'destination'>>) =>
|
updateExport: (id: string, body: Partial<Pick<ExportSet, 'name' | 'targets' | 'destination'>>) =>
|
||||||
send<ExportSet>('PATCH', `/api/exports/${encodeURIComponent(id)}`, body),
|
send<ExportSet>('PATCH', `/api/exports/${encodeURIComponent(id)}`, body),
|
||||||
deleteExport: (id: string) =>
|
deleteExport: (id: string) =>
|
||||||
send<{ deleted: boolean }>('DELETE', `/api/exports/${encodeURIComponent(id)}`),
|
send<{ deleted: boolean }>('DELETE', `/api/exports/${encodeURIComponent(id)}`),
|
||||||
|
|||||||
@@ -5,7 +5,11 @@ import { api, type ExportSet } from '../api'
|
|||||||
import { FolderPicker } from './FolderPicker'
|
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
|
* All three are settled up front, and the destination especially is NOT a
|
||||||
* detail deferred to export time. A Traktor `<LOCATION>` is a volume name plus
|
* detail deferred to export time. A Traktor `<LOCATION>` is a volume name plus
|
||||||
@@ -23,7 +27,7 @@ interface Props {
|
|||||||
|
|
||||||
export function ExportDialog({ editing, onClose, onSaved, onError }: Props) {
|
export function ExportDialog({ editing, onClose, onSaved, onError }: Props) {
|
||||||
const [name, setName] = useState(editing?.name ?? '')
|
const [name, setName] = useState(editing?.name ?? '')
|
||||||
const [target, setTarget] = useState(editing?.target ?? 'traktor')
|
const [chosen, setChosen] = useState<string[]>(editing?.targets ?? ['traktor'])
|
||||||
const [destination, setDestination] = useState(editing?.destination ?? '')
|
const [destination, setDestination] = useState(editing?.destination ?? '')
|
||||||
const [browsing, setBrowsing] = useState(false)
|
const [browsing, setBrowsing] = useState(false)
|
||||||
const [busy, setBusy] = useState(false)
|
const [busy, setBusy] = useState(false)
|
||||||
@@ -42,12 +46,29 @@ export function ExportDialog({ editing, onClose, onSaved, onError }: Props) {
|
|||||||
enabled: !!editing,
|
enabled: !!editing,
|
||||||
}).data?.destination_conflict
|
}).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 () => {
|
const save = async () => {
|
||||||
setBusy(true)
|
setBusy(true)
|
||||||
try {
|
try {
|
||||||
const body = { name: name.trim(), target, destination: destination.trim() }
|
const body = { name: name.trim(), targets: chosen, destination: destination.trim() }
|
||||||
const saved = editing
|
const saved = editing
|
||||||
? await api.updateExport(editing.id, body)
|
? await api.updateExport(editing.id, body)
|
||||||
: await api.createExport(body)
|
: await api.createExport(body)
|
||||||
@@ -102,10 +123,10 @@ export function ExportDialog({ editing, onClose, onSaved, onError }: Props) {
|
|||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
<input
|
<input
|
||||||
type="radio"
|
type="checkbox"
|
||||||
disabled={!p.installed}
|
disabled={!p.installed}
|
||||||
checked={target === p.platform}
|
checked={chosen.includes(p.platform)}
|
||||||
onChange={() => setTarget(p.platform)}
|
onChange={(e) => toggle(p.platform, e.target.checked)}
|
||||||
className="accent-accent"
|
className="accent-accent"
|
||||||
/>
|
/>
|
||||||
<span className={p.installed ? 'text-text' : 'text-faint'}>{p.name}</span>
|
<span className={p.installed ? 'text-text' : 'text-faint'}>{p.name}</span>
|
||||||
@@ -137,9 +158,16 @@ export function ExportDialog({ editing, onClose, onSaved, onError }: Props) {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-1 text-[11px] text-faint">
|
<div className="mt-1 text-[11px] text-faint">
|
||||||
The folder gets a <span className="font-mono">collection.nml</span> and a copy of
|
The folder gets a library for each platform, plus one copy of every track under{' '}
|
||||||
every track, in your own folder structure.
|
<span className="font-mono">Contents/</span>, in your own folder structure.
|
||||||
</div>
|
</div>
|
||||||
|
{needsRoot.length > 0 && destination.trim() !== '' && !atDriveRoot && (
|
||||||
|
<div className="mt-2 rounded well px-3 py-2 text-xs text-gold">
|
||||||
|
{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.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
{conflict && (
|
{conflict && (
|
||||||
<div className="mt-2 rounded well px-3 py-2 text-xs text-gold">
|
<div className="mt-2 rounded well px-3 py-2 text-xs text-gold">
|
||||||
“{conflict}” already exports here. Exporting replaces whatever the other one
|
“{conflict}” already exports here. Exporting replaces whatever the other one
|
||||||
|
|||||||
@@ -38,6 +38,10 @@ export function ExportRunDialog({ set, onClose, onDone, onError }: Props) {
|
|||||||
const [starting, setStarting] = useState(false)
|
const [starting, setStarting] = useState(false)
|
||||||
const pollRef = useRef<number | null>(null)
|
const pollRef = useRef<number | null>(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<ExportPreview>({
|
const preview = useQuery<ExportPreview>({
|
||||||
queryKey: ['export-preview', set.id],
|
queryKey: ['export-preview', set.id],
|
||||||
queryFn: () => api.exportPreview(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.
|
This folder already holds an export. Its files will be replaced.
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
{/* 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 && (
|
||||||
|
<div className="rounded well px-3 py-2 text-xs text-gold">
|
||||||
|
{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.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
<div className="text-xs text-faint">
|
<div className="text-xs text-faint">
|
||||||
Writes a <span className="font-mono">collection.nml</span> plus a copy of every
|
Writes a library for {set.targets.map(nameOf).join(' and ')}, sharing one copy
|
||||||
track, in your own folder structure.
|
of every track under <span className="font-mono">Contents/</span>, in your own
|
||||||
|
folder structure.
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -209,21 +223,26 @@ export function ExportRunDialog({ set, onClose, onDone, onError }: Props) {
|
|||||||
)}
|
)}
|
||||||
{job.state === 'cancelled' && (
|
{job.state === 'cancelled' && (
|
||||||
<div className="text-xs text-muted">
|
<div className="text-xs text-muted">
|
||||||
Cancelled. Everything this export copied was removed, and no library file was
|
Cancelled. Everything this export copied was removed, and no library was
|
||||||
written.
|
written.
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{job.state === 'failed' && <div className="text-xs text-pink">{job.error}</div>}
|
{job.state === 'failed' && (
|
||||||
|
<div className="text-xs text-pink">
|
||||||
|
{job.error} — nothing was left behind: no audio, and no library for any platform.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
{job.state === 'done' && (
|
{job.state === 'done' && (
|
||||||
<div className="space-y-1 text-xs text-mint">
|
<div className="space-y-1 text-xs text-mint">
|
||||||
<div>Done — the folder is ready.</div>
|
<div>Done — the folder is ready.</div>
|
||||||
{/* Ben's workflow: the exported collection.nml is swapped into
|
{(
|
||||||
a Traktor install, which REPLACES that machine's own. */}
|
(job.result as { libraries?: { platform: string; library: string }[] } | null)
|
||||||
<div className="text-faint">
|
?.libraries ?? []
|
||||||
To use it: quit Traktor, back up its existing{' '}
|
).map((l) => (
|
||||||
<span className="font-mono">collection.nml</span>, then put this one in its
|
<div key={l.platform} className="text-faint">
|
||||||
place.
|
{nameOf(l.platform)}: <span className="font-mono">{l.library}</span>
|
||||||
</div>
|
</div>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -197,7 +197,7 @@ function ExportRow({
|
|||||||
</span>
|
</span>
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
title="Edit name, target and destination"
|
title="Edit name, platforms and destination"
|
||||||
onClick={onEdit}
|
onClick={onEdit}
|
||||||
className="shrink-0 px-1 text-xs text-faint opacity-0 hover:text-text group-hover:opacity-100"
|
className="shrink-0 px-1 text-xs text-faint opacity-0 hover:text-text group-hover:opacity-100"
|
||||||
>
|
>
|
||||||
|
|||||||
Reference in new issue
Block a user