mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +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
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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."""
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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",
|
||||
]
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
]
|
||||
|
||||
@@ -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):
|
||||
|
||||
+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 —
|
||||
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()
|
||||
|
||||
@@ -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"}
|
||||
|
||||
@@ -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}
|
||||
|
||||
Reference in new issue
Block a user