diff --git a/CLAUDE.md b/CLAUDE.md index 24de5ce..a2b664e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -436,6 +436,13 @@ serialization path.** It enforces: at the gig. Also that a flexible multi-marker grid and hot-cue PADS survive, grids are not locked, loose tracks get their "Other" playlist, and re-exporting into the same folder replaces rather than appends. + It then runs a real export end to end (the source library is built with the + exporter itself, so its LOCATIONs point at audio that exists) and pins the + safety rules with teeth: a folder Konduktor did NOT write is refused, and + `run()` refuses a blocked plan even when called directly; a re-export replaces + its own files and leaves the user's alone; a cancel leaves no library file and + **no audio at all**, including the file being written; a missing source file is + skipped rather than fatal. - `test_library_id.py` — the property no other suite covers: **a library that moves keeps its identity**. Also that two libraries in one folder stay two, a removable library is never written beside, an unwritable location falls back @@ -637,6 +644,30 @@ that number and nothing else — everything derives from it: is a folder-deletion hazard, so an export writes a `.konduktor-export.json` manifest and **refuses to clear any folder that lacks one** — Konduktor only ever deletes what Konduktor wrote. + **Step 5 done**: `exporter.py` — plan, mirrored copy, manifest, rollback — on + `jobs.py`, plus `POST /api/exports/{id}/preview` and `/run`, and the + `ExportRunDialog`. Three properties it is built around: audio is copied FIRST + and the library written LAST, so a cancel leaves **no** library file and its + absence is what marks an export unfinished; rollback registers each file + BEFORE writing it, so the in-flight copy is cleaned up too; and the **manifest** + (`.konduktor-export.json`) means clearing removes exactly what the last export + wrote, so a file the user put in the folder survives a re-export. Audio mirrors + the source tree **relative to `common_dir_prefix`** — mirroring absolute paths + would put the user's home directory on the stick, and relative paths make + filename collisions impossible. A destination Konduktor did not write is + **refused, not confirmed**: there is no "do it anyway". + **Step 4 done**: `core/export.py` (the `LibraryExporter` protocol, its own + registry, and the strictly-generic `ExportPayload` — so a Rekordbox collection + exports to Traktor with no exporter knowing Rekordbox exists) and + `adapters/traktor/export.py`. The writer **creates then replays**: it writes a + minimal valid NML skeleton, opens a `TraktorAdapter` on it and populates it + with the ordinary commands. That amends the original design note, which + rejected create-then-replay on the grounds that the write target must always be + a native model parsed from a real file — here it literally is, a skeleton + Konduktor just wrote, and the alternative was a second definition of "Track + + cues + grid → ENTRY" that would drift from `add_entry` and inherit none of its + tests. Exporters declare **static** capabilities: no instance, no path, because + the library being described does not exist yet. **Steps 1–3 done**: `library_id.py`; `exports.py` + 10 routes + `api.ts`; and the UI (`ExportsSection`, `ExportDialog`, export views in `App`, "Add to…" on `SelectionBar`, the track context menu and each sidebar playlist row). diff --git a/backend/konduktor/exporter.py b/backend/konduktor/exporter.py new file mode 100644 index 0000000..848d324 --- /dev/null +++ b/backend/konduktor/exporter.py @@ -0,0 +1,387 @@ +"""Running an export: plan it, copy the audio, write the library. + +App-level, like `importer.py`, and for the same reason — it coordinates a source +library, a destination folder and an exporter, and none of those should know +about the others. + +**`core` plans and copies; the exporter only writes the library file.** Layout, +collision and dedup rules are platform-independent and must not drift between +targets, and the exporter cannot write a Traktor `` before the +destination path is known anyway. + +## Ordering is the safety property + +Audio is copied FIRST and the library written LAST, so a cancel during the long +part leaves no library file — its absence is what marks an export unfinished — +and everything copied is removed on the way out. The rollback tracks files +BEFORE each write, not after: cleaning up only COMPLETED copies leaves the +in-flight one behind, which is a bug the import feature had and was fixed there. + +## Konduktor only deletes what Konduktor wrote + +A re-export clears its destination first, which combined with "the user picks +the destination" is a folder-deletion hazard: point an export at `~/Documents` +and a confirm dialog is the only thing between a click and real loss. So every +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 + +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. +""" +from __future__ import annotations + +import logging +import time +from dataclasses import dataclass, field +from pathlib import Path + +from . import exports +from .core.export import ExportPayload, ExportPlaylist, ExportTrack, for_platform +from .core.pathmap import common_dir_prefix +from .importer import SPACE_HEADROOM, copy_file, free_bytes +from .jobs import JobHandle + +log = logging.getLogger(__name__) + +MANIFEST_NAME = ".konduktor-export.json" + +#: Why an export cannot run. The UI words these; they are facts, not sentences. +BLOCKED_OCCUPIED = "destination_not_empty" +BLOCKED_EMPTY = "nothing_to_export" +BLOCKED_NO_TARGET = "unsupported_target" + + +@dataclass +class PlannedTrack: + track_id: str + title: str + source_path: Path | None + destination: Path | None + size: int = 0 + missing: bool = False + + +@dataclass +class ExportPlan: + tracks: list[PlannedTrack] = field(default_factory=list) + playlists: list[ExportPlaylist] = field(default_factory=list) + destination: Path | None = None + #: One of the BLOCKED_* facts, or None when the export can run. + blocked: str | None = None + #: Whether the destination already holds a Konduktor export to replace. + replacing: bool = False + + @property + def exportable(self) -> list[PlannedTrack]: + return [t for t in self.tracks if not t.missing] + + @property + def total_bytes(self) -> int: + return sum(t.size for t in self.exportable) + + def as_dict(self, free: int | None = None) -> dict: + return { + "tracks": len(self.tracks), + "exportable": len(self.exportable), + "missing": [t.title for t in self.tracks if t.missing], + "playlists": [p.name for p in self.playlists], + "total_bytes": self.total_bytes, + "destination": str(self.destination) if self.destination else None, + "free_bytes": free, + "enough_space": ( + None if free is None else free >= self.total_bytes + SPACE_HEADROOM + ), + "blocked": self.blocked, + "replacing": self.replacing, + } + + +# ---- the destination --------------------------------------------------------- + + +def manifest_path(destination: Path) -> Path: + return Path(destination) / MANIFEST_NAME + + +def is_ours(destination: Path) -> bool: + """Whether this folder holds an export Konduktor wrote.""" + try: + return manifest_path(destination).is_file() + except OSError: + return False + + +def destination_blocked(destination: Path) -> str | None: + """Why this folder cannot be exported into, or None. + + A folder that does not exist yet, or is empty, or carries our manifest, is + fine. Anything else is REFUSED — not confirmed — because an export clears + its destination and Konduktor must never delete what it did not write. + """ + destination = Path(destination) + try: + if not destination.exists(): + return None + if not destination.is_dir(): + return BLOCKED_OCCUPIED + if is_ours(destination): + return None + return BLOCKED_OCCUPIED if any(destination.iterdir()) else None + except OSError: + return BLOCKED_OCCUPIED + + +def _clear(destination: Path) -> None: + """Remove the previous export, and only it. + + Driven by the manifest rather than by wiping the folder: the manifest lists + everything the last export wrote, so anything the user put there themselves + survives. Empty directories are pruned afterwards so a re-export does not + inherit the last one's folder skeleton. + """ + data = _read_manifest(destination) + for name in data.get("files", []): + try: + (destination / name).unlink() + except OSError: + pass + for name in (data.get("library"), MANIFEST_NAME): + if name: + try: + (destination / name).unlink() + except OSError: + pass + _prune_empty(destination) + + +def _prune_empty(root: Path) -> None: + try: + for folder in sorted( + (p for p in root.rglob("*") if p.is_dir()), + key=lambda p: len(p.parts), + reverse=True, + ): + try: + folder.rmdir() + except OSError: + pass # not empty — the user's own files live here + except OSError: + pass + + +def _read_manifest(destination: Path) -> dict: + from . import paths + + data = paths.read_json(manifest_path(destination), {}) + return data if isinstance(data, dict) else {} + + +def _write_manifest(destination: Path, *, library: str, files: list[str], name: str) -> None: + from . import paths + + paths.write_json( + manifest_path(destination), + { + "note": "Written by Konduktor. It lists what this export put here, " + "so re-exporting can replace exactly those files.", + "export": name, + "written": time.time(), + "library": library, + "files": files, + }, + ) + + +# ---- planning ---------------------------------------------------------------- + + +def plan(adapter, export_set) -> ExportPlan: + """Resolve the set and work out where every file lands. Reads only.""" + destination = Path(export_set.destination).expanduser() + built = ExportPlan(destination=destination) + + if for_platform(export_set.target) is None: + built.blocked = BLOCKED_NO_TARGET + return built + + resolved = exports.resolve(adapter, export_set) + tracks = [t for t in (adapter.track(i) for i in resolved.track_ids) if t is not None] + + # Mirror relative to the deepest shared folder, so the export carries the + # user's structure without carrying their home directory. + present = [t.filepath for t in tracks if t.filepath] + root = common_dir_prefix(present) if present else "" + + for track in tracks: + source = Path(track.filepath) if track.filepath else None + exists = False + size = 0 + try: + exists = bool(source and source.is_file()) + size = source.stat().st_size if exists else 0 + except OSError: + exists = False + built.tracks.append( + PlannedTrack( + 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, + size=size, + missing=not exists, + ) + ) + + names = {p.id: p for p in resolved.playlists} + folders = _folder_paths(adapter) + for playlist in resolved.playlists: + if playlist.missing or not playlist.track_ids: + continue + built.playlists.append( + ExportPlaylist( + name=names[playlist.id].name, + track_ids=list(playlist.track_ids), + folders=folders.get(playlist.id, []), + ) + ) + + if not built.exportable: + built.blocked = BLOCKED_EMPTY + else: + built.blocked = destination_blocked(destination) + built.replacing = is_ours(destination) + return built + + +def _relative(source: Path, root: str) -> Path: + """Where `source` sits under the export root, mirroring its own folders.""" + text = str(source).replace("\\", "/") + if root and text.startswith(root + "/"): + return Path(text[len(root) + 1:]) + # No shared root (tracks on different volumes): keep the full path minus its + # leading separator, which is ugly but never collides. + return Path(text.lstrip("/")) + + +def _folder_paths(adapter) -> dict[str, list[str]]: + """Each playlist's folder chain, outermost first.""" + out: dict[str, list[str]] = {} + + def walk(nodes, path: list[str]) -> None: + for node in nodes or []: + if node.kind == "folder": + walk(getattr(node, "children", None), path + [node.name]) + else: + out[node.id] = path + walk(getattr(node, "children", None), path) + + walk(adapter.playlist_tree(), []) + return out + + +# ---- running ----------------------------------------------------------------- + + +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}") + if built.blocked: + raise ValueError(f"This export cannot run: {built.blocked}") + + destination = Path(built.destination) + items = built.exportable + total = sum(t.size for t in items) + handle.progress(done=0, total=total, message="Preparing…") + + # Registered BEFORE each write, so a cancel mid-file removes the partial one + # too. Cleaning up only completed copies leaves debris the retry then + # suffixes around — a bug the import feature had. + created: list[Path] = [] + done = 0 + try: + destination.mkdir(parents=True, exist_ok=True) + if is_ours(destination): + handle.progress(message="Replacing the previous export…") + _clear(destination) + + payload_tracks: list[ExportTrack] = [] + for planned in items: + handle.raise_if_cancelled() + handle.progress(message=f"Copying {planned.title}") + target = Path(planned.destination) + target.parent.mkdir(parents=True, exist_ok=True) + created.append(target) + + def advance(n: int) -> None: + nonlocal done + done += n + handle.progress(done=done) + + copy_file(planned.source_path, target, handle, advance) + payload_tracks.append( + ExportTrack( + track=adapter.track(planned.track_id), + destination=target, + cues=adapter.track_cues(planned.track_id), + ) + ) + + handle.raise_if_cancelled() + handle.progress(message=f"Writing the {export_set.target} library…") + library = exporter.write( + ExportPayload( + name=export_set.name, + tracks=payload_tracks, + playlists=built.playlists, + ), + destination, + ) + created.append(library) + + _write_manifest( + destination, + library=library.name, + files=[str(p.relative_to(destination)) for p in created if p != library], + name=export_set.name, + ) + return { + "tracks": len(payload_tracks), + "playlists": len(built.playlists), + "skipped": len(built.tracks) - len(items), + "destination": str(destination), + "library": str(library), + } + 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: + try: + path.unlink() + except OSError: + pass + try: + manifest_path(destination).unlink() + except OSError: + pass + _prune_empty(destination) + raise + + +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", + "MANIFEST_NAME", "PlannedTrack", "destination_blocked", "is_ours", "plan", + "run", "space_for", +] diff --git a/backend/konduktor/importer.py b/backend/konduktor/importer.py index 7c845f3..f72b1d6 100644 --- a/backend/konduktor/importer.py +++ b/backend/konduktor/importer.py @@ -205,8 +205,14 @@ def _unique_target(folder: Path, name: str, taken: set[str]) -> Path: return folder / candidate -def _copy(src: Path, dst: Path, handle: JobHandle, on_bytes) -> None: - """Copy a file, checking for cancellation between chunks.""" +def copy_file(src: Path, dst: Path, handle: JobHandle, on_bytes) -> None: + """Copy a file, checking for cancellation between chunks. + + Public because export copies audio the same way and for the same reason: a + second chunked-copy loop would be a second place for the cancel check to be + forgotten, and a forgotten cancel check is invisible until someone tries to + stop a multi-gigabyte copy. + """ with src.open("rb") as fin, dst.open("wb") as fout: while True: handle.raise_if_cancelled() @@ -259,7 +265,7 @@ def run(source, dest, plan: ImportPlan, handle: JobHandle, *, folder_name: str | assert planned.source_path is not None target = _unique_target(destination, planned.source_path.name, taken) created.append(target) # registered BEFORE the write, so a cancel - _copy(planned.source_path, target, handle, bump) # mid-file is cleaned + copy_file(planned.source_path, target, handle, bump) # mid-file is cleaned copied.append((planned, target)) handle.raise_if_cancelled() diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index 7ef7cab..59a699a 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -13,10 +13,11 @@ from fastapi import FastAPI, File, Form, HTTPException, Query, Response, UploadF from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse, JSONResponse -from . import __version__, exports, history, prefs +from . import __version__, exporter, exports, history, prefs from .app_state import STATE from .core import auto_hotcues as ah from . import importer +from .core import export as core_export from .core import places, registry from .core.adapter import ( AdapterError, @@ -48,6 +49,7 @@ from .schemas import ( ExportPlaylistOut, ExportSetMembers, ExportSetOut, + ExportPreview, FsEntry, FsListing, FsPlace, @@ -498,15 +500,40 @@ def export_playlist_tracks(set_id: str, playlist_id: str) -> list[Track]: return tracks +@app.post("/api/exports/{set_id}/preview", response_model=ExportPreview) +def preview_export(set_id: str) -> ExportPreview: + """What this export would do, right now. Never cached — the set is live.""" + found = _require_set(set_id) + built = exporter.plan(require_adapter(), found) + return ExportPreview(**built.as_dict(exporter.space_for(built))) + + +@app.post("/api/exports/{set_id}/run", response_model=JobStatus) +def run_export(set_id: str) -> JobStatus: + """Start the export on a background thread; poll `/api/jobs/{id}`. + + Planned again HERE rather than trusting whatever the preview showed: a + playlist can be edited, a file deleted or a drive unplugged between looking + and clicking, and the plan carries the destination-safety check. + """ + found = _require_set(set_id) + adapter = require_adapter() + built = exporter.plan(adapter, found) + if built.blocked: + raise HTTPException(409, built.blocked) + job = JOBS.submit("export", lambda handle: exporter.run(adapter, found, built, handle)) + return JobStatus(**job.as_dict()) + + def _export_targets() -> set[str]: """Platforms Konduktor can write a NEW library for. - Deliberately narrower than the platforms it can OPEN. Reading a library and - creating one from nothing are different capabilities, and only Traktor has - the second today — a Rekordbox target needs a from-scratch SQLCipher - master.db plus generated ANLZ analysis files. + Asked of the exporter registry rather than hard-coded: reading a library and + creating one from nothing are different capabilities, and a platform can + have the first without the second. Registering an exporter is what makes a + platform a target, so this cannot drift from what actually exists. """ - return {"traktor"} + return core_export.targets() @app.get("/api/export-targets", response_model=list[PlatformOption]) diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index 9346f5e..369da80 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -190,6 +190,24 @@ class ExportContents(BaseModel): destination_conflict: str | None = None +class ExportPreview(BaseModel): + """What an export would do if run now. Computed fresh; never stored.""" + + tracks: int = 0 + exportable: int = 0 + missing: list[str] = [] + playlists: list[str] = [] + total_bytes: int = 0 + destination: str | None = None + free_bytes: int | None = None + enough_space: bool | None = None + #: A FACT, not a sentence — the UI words it. One of `destination_not_empty`, + #: `nothing_to_export`, `unsupported_target`, or null when it can run. + blocked: str | None = None + #: The destination already holds a Konduktor export, which will be replaced. + replacing: bool = False + + class FsPlace(BaseModel): """A shortcut in the file browser's sidebar. diff --git a/backend/test_export.py b/backend/test_export.py index ec32d66..1881cf0 100644 --- a/backend/test_export.py +++ b/backend/test_export.py @@ -175,5 +175,156 @@ check("the entry count did not double", check("and the tree did not duplicate", len(TraktorDriver().open(again).playlist_tree()) == 1) +# ============================================================================== +# Running an export: the copy, the safety rules, and the rollback. +# ============================================================================== +import tempfile as _tf # noqa: E402 +import time # noqa: E402 + +os.environ.setdefault("KONDUKTOR_DATA_DIR", _tf.mkdtemp()) +from konduktor import exporter, exports # noqa: E402 +from konduktor.app_state import STATE # noqa: E402 +from konduktor.core.export import ExportPayload as _Payload # noqa: E402 +from konduktor.jobs import JOBS, JobCancelled # noqa: E402 + +# A SOURCE library whose audio genuinely exists on disk — built with the very +# exporter tested above, which is the cheapest way to get real LOCATIONs. +lib_root = Path(tempfile.mkdtemp()) / "MyMusic" +seed_items = [] +for i, track in enumerate(src.tracks[:4]): + audio = lib_root / ("House" if i % 2 else "Techno") / Path(track.filepath).name + audio.parent.mkdir(parents=True, exist_ok=True) + audio.write_bytes(b"\0" * 300_000) + seed_items.append(ExportTrack(track=track, destination=audio, cues=src.track_cues(track.id))) +exporter_obj = core_export.for_platform("traktor") +exporter_obj.write( + _Payload(name="Source", tracks=seed_items, + playlists=[ExportPlaylist(name="Peak Time", + track_ids=[src.tracks[0].id, src.tracks[1].id])]), + lib_root, +) +STATE.open(lib_root / "collection.nml") +ad = STATE.adapter +LIB = STATE.library_id + +dest = Path(tempfile.mkdtemp()) / "GIG" +eset = exports.create(LIB, name="GIG", target="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) + + +def run_now(plan): + job = JOBS.submit("export", lambda h: exporter.run(ad, eset, plan, h)) + while not job.finished: + time.sleep(0.02) + return job + + +print("== the plan mirrors the source tree, 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] +# 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) +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) + +print("== running it ==") +job = run_now(built) +check("it finishes", job.state == "done", f"{job.state}: {job.error}") +check("every track was copied", job.result["tracks"] == len(built.exportable)) +check("the library was written", (dest / "collection.nml").is_file()) +check("and a manifest beside it", (dest / exporter.MANIFEST_NAME).is_file()) +check("the audio is really there", + all((dest / r).stat().st_size == 300_000 for r in rel)) +check("the result re-opens as a library", + len(TraktorDriver().open(dest / "collection.nml").tracks) == len(built.exportable)) + +print("== Konduktor only ever deletes what Konduktor wrote ==") +mine = dest / "MY OWN NOTES.txt" +mine.write_text("do not delete") +again = exporter.plan(ad, exports.get(LIB, eset.id)) +# The folder is now non-empty AND has a manifest, so it is ours to replace. +check("a folder we wrote is not blocked", again.blocked is None) +check("and is reported as a replacement", again.replacing) +job2 = run_now(again) +check("the re-export succeeds", job2.state == "done", f"{job2.state}: {job2.error}") +check("a file the USER put there survives", mine.is_file() and mine.read_text() == "do not delete") +check("the audio did not double up", + len([p for p in dest.rglob("*") if p.is_file()]) == len(rel) + 3, # + nml, manifest, notes + sorted(str(p.relative_to(dest)) for p in dest.rglob("*") if p.is_file())) + +print("== a folder we did NOT write is refused, not confirmed ==") +foreign = Path(tempfile.mkdtemp()) / "Documents" +foreign.mkdir() +(foreign / "tax return.pdf").write_text("important") +exports.update(LIB, eset.id, destination=str(foreign)) +blocked = exporter.plan(ad, exports.get(LIB, eset.id)) +check("it is blocked", blocked.blocked == exporter.BLOCKED_OCCUPIED, str(blocked.blocked)) +check("the user's file is untouched", (foreign / "tax return.pdf").read_text() == "important") +# There is deliberately no "do it anyway": run() refuses a blocked plan even if +# a caller ignored the preview. +try: + exporter.run(ad, exports.get(LIB, eset.id), blocked, None) + check("run refuses a blocked plan", False, "it ran") +except ValueError: + check("run refuses a blocked plan even when asked directly", True) +check("and still nothing was deleted", (foreign / "tax return.pdf").is_file()) +# An EMPTY folder is fine — there is nothing there to lose. +empty = Path(tempfile.mkdtemp()) / "Empty" +empty.mkdir() +check("an empty folder is allowed", exporter.destination_blocked(empty) is None) +check("a folder that does not exist yet is allowed", + exporter.destination_blocked(empty / "nested" / "deeper") is None) + +print("== cancelling rolls back, leaving an empty folder ==") +fresh = Path(tempfile.mkdtemp()) / "Cancelled" +exports.update(LIB, eset.id, destination=str(fresh)) +cancel_plan = exporter.plan(ad, exports.get(LIB, eset.id)) + + +class _CancelAfter: + """Deterministic cancellation: stop partway through the second file.""" + + def __init__(self, after): + self.n, self.after = 0, after + + def progress(self, **kw): + pass + + @property + def cancelled(self): + return self.n >= self.after + + def raise_if_cancelled(self): + self.n += 1 + if self.cancelled: + raise JobCancelled() + + +try: + exporter.run(ad, exports.get(LIB, eset.id), cancel_plan, _CancelAfter(3)) + check("it stops", False, "it did not raise") +except JobCancelled: + check("it stops", True) +check("NO library file was written", not (fresh / "collection.nml").exists()) +check("no manifest either", not (fresh / exporter.MANIFEST_NAME).exists()) +# Including the file being written when the cancel landed. Cleaning up only +# COMPLETED copies leaves the in-flight one behind — the bug import had. +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("== a missing file is skipped, not fatal ==") +gone = Path(seed_items[0].destination) +gone.unlink() +partial = exporter.plan(ad, exports.get(LIB, eset.id)) +check("it is reported", len([t for t in partial.tracks if t.missing]) == 1) +check("the rest still export", len(partial.exportable) == len(built.exportable) - 1) +check("and it is not blocking", partial.blocked is None) + print("\n" + ("❌ FAILED" if failed else "✅ PASSED")) raise SystemExit(1 if failed else 0) diff --git a/frontend/src/api.ts b/frontend/src/api.ts index b87de28..740cef8 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -364,6 +364,22 @@ export interface ExportContents { destination_conflict: string | null } +/** What an export would do if run now. Computed fresh every time. */ +export interface ExportPreview { + tracks: number + exportable: number + missing: string[] + playlists: string[] + total_bytes: number + destination: string | null + free_bytes: number | null + enough_space: boolean | null + /** A FACT, not a sentence — the UI words it. Null when the export can run. */ + blocked: 'destination_not_empty' | 'nothing_to_export' | 'unsupported_target' | null + /** The destination already holds a Konduktor export, which will be replaced. */ + replacing: boolean +} + export interface FsPlace { /** Groups the row and picks its icon. Never a finished sentence. */ kind: 'home' | 'music' | 'desktop' | 'documents' | 'downloads' | 'volume' | 'library' @@ -518,6 +534,10 @@ export const api = { // reason rather than hiding them — an absent option reads as a missing // feature, a disabled one reads as a roadmap. exportTargets: () => getJSON('/api/export-targets'), + exportPreview: (id: string) => + send('POST', `/api/exports/${encodeURIComponent(id)}/preview`, {}), + runExport: (id: string) => + send('POST', `/api/exports/${encodeURIComponent(id)}/run`, {}), // ---- path remapping (per-collection OS-path prefix translation) ---- getPathMapping: () => getJSON('/api/library/path-mapping'), diff --git a/frontend/src/components/ExportRunDialog.tsx b/frontend/src/components/ExportRunDialog.tsx new file mode 100644 index 0000000..22d59c7 --- /dev/null +++ b/frontend/src/components/ExportRunDialog.tsx @@ -0,0 +1,265 @@ +import { useEffect, useRef, useState } from 'react' +import { useQuery, useQueryClient } from '@tanstack/react-query' +import { api, type ExportPreview, type ExportSet, type JobStatus } from '../api' + +/** + * Run an export: confirm what is about to happen, then watch it happen. + * + * The preview is fetched fresh every time and never cached. An export set holds + * LIVE references, so what it would ship genuinely changes between two looks — + * and a stale preview is worse than none when the next click copies gigabytes. + * + * `blocked` arrives as a fact, not a sentence, and is worded here. The one that + * matters is `destination_not_empty`: an export clears its destination, so a + * folder Konduktor did not write is REFUSED rather than confirmed. There is no + * "do it anyway" — the whole point is that Konduktor never deletes what it did + * not put there. + */ + +const POLL_MS = 300 + +function gb(bytes: number): string { + if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(1)} GB` + if (bytes >= 1e6) return `${(bytes / 1e6).toFixed(0)} MB` + return `${(bytes / 1e3).toFixed(0)} kB` +} + +interface Props { + set: ExportSet + onClose: () => void + onDone: (msg: string) => void + onError: (msg: string) => void +} + +export function ExportRunDialog({ set, onClose, onDone, onError }: Props) { + const qc = useQueryClient() + const [job, setJob] = useState(null) + const [starting, setStarting] = useState(false) + const pollRef = useRef(null) + + const preview = useQuery({ + queryKey: ['export-preview', set.id], + queryFn: () => api.exportPreview(set.id), + enabled: !job, + staleTime: 0, + gcTime: 0, + }) + + useEffect(() => { + if (!job || job.state !== 'running') return + pollRef.current = window.setInterval(async () => { + try { + const next = await api.job(job.id) + setJob(next) + if (next.state !== 'running') { + if (pollRef.current) window.clearInterval(pollRef.current) + if (next.state === 'done') { + const r = next.result as { tracks?: number; playlists?: number } | null + qc.invalidateQueries({ queryKey: ['export-contents', set.id] }) + onDone( + `Exported ${r?.tracks ?? 0} track${r?.tracks === 1 ? '' : 's'}` + + (r?.playlists ? ` and ${r.playlists} playlist${r.playlists === 1 ? '' : 's'}` : ''), + ) + } else if (next.state === 'failed') { + onError(next.error || 'Export failed') + } + } + } catch (e) { + onError((e as Error).message) + if (pollRef.current) window.clearInterval(pollRef.current) + } + }, POLL_MS) + return () => { + if (pollRef.current) window.clearInterval(pollRef.current) + } + }, [job, qc, set.id, onDone, onError]) + + const start = async () => { + setStarting(true) + try { + setJob(await api.runExport(set.id)) + } catch (e) { + onError((e as Error).message) + } finally { + setStarting(false) + } + } + + const cancel = async () => { + if (!job) return + try { + await api.cancelJob(job.id) + } catch (e) { + onError((e as Error).message) + } + } + + const p = preview.data + const running = job?.state === 'running' + const finished = job != null && job.state !== 'running' + const pct = job && job.total > 0 ? Math.min(100, (job.done / job.total) * 100) : null + const blocked = p?.blocked ?? null + + return ( +
+
+
+

Export “{set.name}”

+
+ +
+ {!job && ( + <> +
+ To +
+ {set.destination} +
+
+ + {preview.isLoading &&
Checking…
} + {preview.isError && ( +
{(preview.error as Error).message}
+ )} + + {p && !blocked && ( +
+
+ {p.exportable} track{p.exportable === 1 ? '' : 's'} + {p.playlists.length > 0 && + ` · ${p.playlists.length} playlist${p.playlists.length === 1 ? '' : 's'}`} + · {gb(p.total_bytes)} to copy +
+ {p.free_bytes != null && ( +
+ {gb(p.free_bytes)} free + {p.enough_space === false && ' — not enough space'} +
+ )} + {/* Reported and skipped, not a failure halfway through a long + copy. A gig stick short four tracks must never be silent. */} + {p.missing.length > 0 && ( +
+ {p.missing.length} track{p.missing.length === 1 ? '' : 's'} will be skipped — + the audio file is not on this disk: +
{p.missing.slice(0, 4).join(', ')}
+
+ )} + {p.replacing && ( +
+ This folder already holds an export. Its files will be replaced. +
+ )} +
+ Writes a collection.nml plus a copy of every + track, in your own folder structure. +
+
+ )} + + {blocked === 'destination_not_empty' && ( +
+ That folder already has files in it that Konduktor didn’t put there. An export + replaces what it wrote last time, so it will only write into an empty folder or + one of its own. Edit the export and choose somewhere else. +
+ )} + {blocked === 'nothing_to_export' && ( +
+ There’s nothing to export yet — add some tracks or a playlist. +
+ )} + {blocked === 'unsupported_target' && ( +
+ Konduktor can’t write that kind of library yet. +
+ )} + + )} + + {job && ( +
+
{job.message || 'Working…'}
+
+
+
+ {pct != null && running && ( +
+ {gb(job.done)} of {gb(job.total)} +
+ )} + {job.state === 'cancelled' && ( +
+ Cancelled. Everything this export copied was removed, and no library file was + written. +
+ )} + {job.state === 'failed' &&
{job.error}
} + {job.state === 'done' && ( +
+
Done — the folder is ready.
+ {/* Ben's workflow: the exported collection.nml is swapped into + a Traktor install, which REPLACES that machine's own. */} +
+ To use it: quit Traktor, back up its existing{' '} + collection.nml, then put this one in its + place. +
+
+ )} +
+ )} +
+ +
+ {running ? ( + <> + + + + ) : ( + <> + + {!finished && ( + + )} + + )} +
+
+
+ ) +} diff --git a/frontend/src/components/ExportsSection.tsx b/frontend/src/components/ExportsSection.tsx index f493953..f294ed1 100644 --- a/frontend/src/components/ExportsSection.tsx +++ b/frontend/src/components/ExportsSection.tsx @@ -2,6 +2,7 @@ import { useState } from 'react' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { api, type ExportSet } from '../api' import { ExportDialog } from './ExportDialog' +import { ExportRunDialog } from './ExportRunDialog' import type { Source } from './Sidebar' /** @@ -29,6 +30,7 @@ interface Props { export function ExportsSection({ source, onSelect, onDone, onError }: Props) { const qc = useQueryClient() const [dialog, setDialog] = useState<{ editing: ExportSet | null } | null>(null) + const [running, setRunning] = useState(null) const sets = useQuery({ queryKey: ['exports'], queryFn: api.exports }) @@ -65,6 +67,15 @@ export function ExportsSection({ source, onSelect, onDone, onError }: Props) { /> )} + {running && ( + setRunning(null)} + onDone={onDone} + onError={onError} + /> + )} +
Exports @@ -91,6 +102,7 @@ export function ExportsSection({ source, onSelect, onDone, onError }: Props) { source={source} onSelect={onSelect} onEdit={() => setDialog({ editing: set })} + onRun={() => setRunning(set)} onDelete={() => { // Deleting a set never touches its destination folder — the files // already exported are the user's, not Konduktor's to clean up. @@ -110,6 +122,7 @@ function ExportRow({ source, onSelect, onEdit, + onRun, onDelete, onError, }: { @@ -117,6 +130,7 @@ function ExportRow({ source: Source onSelect: (s: Source) => void onEdit: () => void + onRun: () => void onDelete: () => void onError: (msg: string) => void }) { @@ -268,6 +282,16 @@ function ExportRow({ Empty — select tracks and use “Add to…”.
)} + + {!!data?.tracks && ( + + )} )}