Begun adding export support

This commit is contained in:
patben8 committed 2026-09-23 14:46:58 +02:00
1 parent 93ec2ef425
commit 805b95fe5e
11 files changed
+1295 -10

No files matched your search

+70 -6
View File
@@ -177,6 +177,33 @@ Two independent apps that talk over HTTP:
- `app_state.py` — the one loaded library, and the **version-history commit**. - `app_state.py` — the one loaded library, and the **version-history commit**.
History is app-level: the adapter returns the bytes it wrote plus a summary, History is app-level: the adapter returns the bytes it wrote plus a summary,
and `AppState.save()` versions them. Every write path must go through it. and `AppState.save()` versions them. Every write path must go through it.
- `library_id.py` — a **stable identity for a library that survives it being
moved**. Everything else keys off the OS path (`history` hashes it, `prefs`
stores it), which is fine for things a user shrugs at losing and NOT fine for
export sets, which are curated work holding references into one library. Two
halves, only the first authoritative: a hidden `.konduktor-library.json`
**sidecar beside the library**, which moves with it, plus a disposable
`libraries.json` index in app-data. The id is **random** — deriving it from
the path defeats the point and from the contents would change on every save.
The sidecar is keyed **by filename**, because one folder can hold two
libraries and a single id per folder would hand both the same identity.
A **removable** library gets no sidecar (writing to a user's USB stick for
Konduktor's bookkeeping is not a trade worth making) and falls back to a
path-derived id that `is_durable()` reports honestly. Writing beside the
library is not a new intrusion — saves already create `backups/` there.
- `exports.py` — **export sets**: a named, persisted slice of the library bound
to a destination. Konduktor's OWN data, never written into the user's library
(a Traktor collection has nowhere to put it, and it would live in a file
Traktor rewrites). Three rules shape it: references are **LIVE** (a set
stores playlist *ids*, resolved at export time, so `resolve()` is computed on
every call and NEVER cached); a playlist is **removable only as a whole**
(a live reference plus per-track removal needs an exclusion list, i.e. hidden
state silently deciding what a future export contains); and it is **keyed by
`library_id`**, not path. `resolve()` dedupes across playlists and loose
tracks — one track, one file copy — and SURFACES what is gone rather than
dropping it, because a gig stick quietly missing four tracks is this
feature's worst failure. `retarget()` follows ids through a path remap, which
`/api/library/remap-paths` calls with a before/after snapshot.
- `prefs.py` — persisted user prefs (`userprefs.json` in the per-OS app-data - `prefs.py` — persisted user prefs (`userprefs.json` in the per-OS app-data
dir). Last-opened collection (global AND per-platform), library column dir). Last-opened collection (global AND per-platform), library column
layout, prep-deck zoom, import destination. Best-effort. layout, prep-deck zoom, import destination. Best-effort.
@@ -384,6 +411,17 @@ serialization path.** It enforces:
as a drive, and that the adapter and the browser share ONE mount scanner. Needs nothing installed: every assertion is about the SHAPE of the as a drive, and that the adapter and the browser share ONE mount scanner. Needs nothing installed: every assertion is about the SHAPE of the
answer, and prefs are redirected to a temp file so a test can never rewrite answer, and prefs are redirected to a temp file so a test can never rewrite
the user's last-opened library. the user's last-opened library.
- `test_exports.py` — export sets against a temp copy of the real collection.
Pins the things that would fail SILENTLY: a live reference picks up a playlist
edited AFTER curation; contents dedupe across playlists and loose tracks; a
deleted playlist or track is surfaced, not dropped; sets are per-library; two
sets sharing a destination are caught (an export clears its destination, so the
second would wipe the first); and deleting a set never touches its folder.
- `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
rather than failing, and `paths.write_json` is atomic (curated user work, so
`prefs.py`'s best-effort "any I/O error degrades to no prefs" is NOT adequate).
- `test_layering.py` — `core/` imports nothing platform-specific, and no adapter - `test_layering.py` — `core/` imports nothing platform-specific, and no adapter
imports another platform's library (checked on real imports via AST, so merely imports another platform's library (checked on real imports via AST, so merely
naming a platform in a comment is fine). Rekordbox and OneLibrary deliberately naming a platform in a comment is fine). Rekordbox and OneLibrary deliberately
@@ -553,12 +591,38 @@ that number and nothing else — everything derives from it:
update counters), so read-only is a deliberate boundary rather than an update counters), so read-only is a deliberate boundary rather than an
unfinished one. All research — including the schema, which has no public spec — unfinished one. All research — including the schema, which has no public spec —
is in [.claude/handoffs/onelibrary-adapter.md](.claude/handoffs/onelibrary-adapter.md). is in [.claude/handoffs/onelibrary-adapter.md](.claude/handoffs/onelibrary-adapter.md).
- ⬜ **Export/conversion** — next up, brought forward ahead of Serato. Design is - 🟡 **Export/conversion** — **in progress.** Both the design AND the user flow
settled in the discussion doc; current state, the architectural gap (no adapter are settled; see
can create a library from nothing) and the landmines are written up in [the export discussion doc](.claude/discussions/discuss-export-implementation-2026-09-22.md),
[.claude/handoffs/export.md](.claude/handoffs/export.md). Note the OneLibrary whose 2026-09-23 section is the current one, plus
work already demonstrated creating an `exportLibrary.db` from nothing, and [.claude/handoffs/export.md](.claude/handoffs/export.md) for the landmines.
`fixtures/onelibrary/schema.sql` is the DDL to do it with. An **export** is a named, persisted object in the sidebar carrying its name,
target platform and destination; tracks and playlists are added to it; an
Export button copies the audio and writes the library. Settled: **Traktor-only
target** for v1, source is whatever library is loaded, **mirror the source
folder structure** (so filename collisions cannot happen), playlists are **live
links removable only as a whole**, re-export **clears the destination first**,
cancel **rolls back**, key notation **mirrors the source**, grids are **not
locked**, no whole-library export.
Verified against the real collection: Traktor stores `VOLUME="Hardy"` plus a
**volume-relative** `DIR`, never a host path — so a USB export is portable by
construction, and the `.nml` cannot be written until the destination is known.
Also settled: loose tracks land in an **"Other" playlist**, playlist folders
are preserved, and the export is a **standalone `collection.nml`** the user
swaps into a Traktor install — so it needs the full skeleton, verified from the
real file: `<NML VERSION="20">`, `<HEAD>`, `<COLLECTION ENTRIES>`,
`<SETS ENTRIES="0">`, `<PLAYLISTS>` wrapping a `$ROOT` FOLDER node with a
`SUBNODES COUNT`, and `<INDEXING><SORTING_INFO PATH="$COLLECTION">`. There is
**no `<MUSICFOLDERS>` element**, so it is not required.
**Safety**: "clear the destination first" plus "the user picks the destination"
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.
**Steps 1–2 done**: `library_id.py`, then `exports.py` + 10 routes + `api.ts`.
Next: the UI, then `core/exporter.py` + the Traktor writer on top of `jobs.py`
and `importer.py`'s copy machinery. Note the OneLibrary work already demonstrated
creating an `exportLibrary.db` from nothing, and `fixtures/onelibrary/schema.sql`
is the DDL to do it with.
- ⬜ Serato adapter - ⬜ Serato adapter
- ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging - ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging
+18 -1
View File
@@ -27,7 +27,7 @@ from __future__ import annotations
import os import os
from pathlib import Path from pathlib import Path
from . import __version__, adapters, history, prefs # noqa: F401 — registers adapters from . import __version__, adapters, history, library_id, prefs # noqa: F401 — registers adapters
from .core import registry from .core import registry
from .core.adapter import LibraryAdapter from .core.adapter import LibraryAdapter
from .core.pathmap import PathMapping from .core.pathmap import PathMapping
@@ -39,6 +39,10 @@ class AppState:
def __init__(self) -> None: def __init__(self) -> None:
self.path: Path | None = None self.path: Path | None = None
self.adapter: LibraryAdapter | None = None self.adapter: LibraryAdapter | None = None
# This library's stable identity, which survives it being moved. What
# export sets are keyed by; see `library_id.py` for why a path is not
# good enough for curated user work.
self.library_id: str | None = None
# The library being read FROM, if any. Read-only by contract; see the # The library being read FROM, if any. Read-only by contract; see the
# module docstring for why it is not symmetrical with `adapter`. # module docstring for why it is not symmetrical with `adapter`.
self.source_path: Path | None = None self.source_path: Path | None = None
@@ -110,6 +114,19 @@ class AppState:
if saved: if saved:
adapter.set_path_mapping(PathMapping.make(saved["from"], saved["to"])) adapter.set_path_mapping(PathMapping.make(saved["from"], saved["to"]))
self.path, self.adapter = path, adapter self.path, self.adapter = path, adapter
caps = adapter.capabilities()
# No sidecar beside a removable library: writing to a user's USB stick to
# satisfy Konduktor's own bookkeeping is not a trade worth making. Those
# get a path-derived id instead, which `is_durable()` reports honestly.
driver = next(
(d for d in registry.drivers() if d.platform == caps.platform), None
)
self.library_id = library_id.for_path(
path,
platform=caps.platform,
label=Path(str(path)).name,
sidecar=not getattr(driver, "removable", False),
)
# Version history: record an "as I found it" baseline (deduped, so # Version history: record an "as I found it" baseline (deduped, so
# re-opening an unchanged library is a no-op). Best-effort. # re-opening an unchanged library is a no-op). Best-effort.
history.ensure_baseline(path) history.ensure_baseline(path)
+335
View File
@@ -0,0 +1,335 @@
"""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
**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.
Three things shape the design:
**References are LIVE.** A set stores playlist *ids*, not the tracks that were in
them when you dragged one in. They are resolved at export time, so adding a track
to a playlist next week means the next export picks it up. The consequence is
that the contents of a set can never be cached — `resolve()` asks the adapter
every time, and the UI's count changes underneath the user by design.
**A playlist is removable only as a whole.** A live reference and per-track
removal are in tension: honouring both needs an exclusion list, i.e. hidden state
that silently decides what a future export contains. Loose tracks are removable
individually; for a subset of a playlist, add the tracks instead of the playlist.
**Keyed by library id, not path.** These are curated work. Keying them on the
library's OS path — as everything else in the app still does — would orphan every
set the moment the user moves their collection. See `library_id.py`.
Storage is one JSON file per library under the app-data dir, written atomically
via `paths.write_json`. Deliberately NOT `prefs.py`, whose best-effort "any I/O
error degrades to no prefs" is right for a window size and wrong for this.
"""
from __future__ import annotations
import logging
import time
import uuid
from dataclasses import asdict, dataclass, field
from pathlib import Path
from . import paths
log = logging.getLogger(__name__)
@dataclass
class ExportSet:
"""One curated export. `destination` is bound at creation, not at run time.
Bound early because it is not merely convenient: a Traktor `<LOCATION>` is a
volume name plus a volume-relative path, both derived from where the export
lands, so the library file cannot be written until the destination is known.
"""
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
playlist_ids: list[str] = field(default_factory=list)
track_ids: list[str] = field(default_factory=list) # loose tracks only
created: float = 0.0
modified: float = 0.0
def as_dict(self) -> dict:
return asdict(self)
@dataclass
class ResolvedPlaylist:
"""A referenced playlist, as it stands right now."""
id: str
name: str
missing: bool # the playlist has since been deleted
track_ids: list[str] = field(default_factory=list)
@dataclass
class ResolvedSet:
"""What an export set contains at this instant.
Never stored. The references are live, so a cached answer would be a lie the
moment the user edits a playlist.
"""
playlists: list[ResolvedPlaylist] = field(default_factory=list)
loose_track_ids: list[str] = field(default_factory=list)
# Ids in the set that the library no longer has. Surfaced rather than
# silently dropped: a gig stick quietly missing four tracks is the worst
# failure this feature has.
dangling_track_ids: list[str] = field(default_factory=list)
@property
def track_ids(self) -> list[str]:
"""Every track this export would carry, DEDUPED, in a stable order.
A track referenced both loosely and through a playlist is one track and
one file copy. Playlists come first so the order follows the tree the
user sees.
"""
seen: set[str] = set()
out: list[str] = []
for playlist in self.playlists:
for track_id in playlist.track_ids:
if track_id not in seen:
seen.add(track_id)
out.append(track_id)
for track_id in self.loose_track_ids:
if track_id not in seen:
seen.add(track_id)
out.append(track_id)
return out
# ---- storage -----------------------------------------------------------------
def _store_path(library_id: str) -> Path:
return paths.app_data_dir() / "exports" / f"{library_id}.json"
def _load(library_id: str) -> dict[str, ExportSet]:
data = paths.read_json(_store_path(library_id), {})
raw = data.get("sets") if isinstance(data, dict) else None
out: dict[str, ExportSet] = {}
if isinstance(raw, dict):
for set_id, values in raw.items():
if not isinstance(values, dict):
continue
try:
out[set_id] = ExportSet(
id=set_id,
name=values.get("name") or "Untitled",
target=values.get("target") or "traktor",
destination=values.get("destination") or "",
playlist_ids=list(values.get("playlist_ids") or []),
track_ids=list(values.get("track_ids") or []),
created=float(values.get("created") or 0.0),
modified=float(values.get("modified") or 0.0),
)
except (TypeError, ValueError):
log.warning("skipping unreadable export set %s", set_id)
return out
def _save(library_id: str, sets: dict[str, ExportSet]) -> None:
paths.write_json(
_store_path(library_id),
{"library_id": library_id, "sets": {k: v.as_dict() for k, v in sets.items()}},
)
# ---- reading -----------------------------------------------------------------
def all_sets(library_id: str) -> list[ExportSet]:
"""Every export set for one library, oldest first so the list is stable."""
return sorted(_load(library_id).values(), key=lambda s: (s.created, s.name.lower()))
def get(library_id: str, set_id: str) -> ExportSet | None:
return _load(library_id).get(set_id)
def destination_conflict(library_id: str, destination: str, *, ignore: str | None = None) -> str | None:
"""The name of another set already pointing at `destination`, if any.
An export CLEARS its destination before writing, so two sets sharing one
folder means the second silently wipes the first's output. Caught when the
destination is chosen rather than at run time, where it would already be too
late to be a warning.
"""
target = _normalise(destination)
if not target:
return None
for existing in _load(library_id).values():
if existing.id != ignore and _normalise(existing.destination) == target:
return existing.name
return None
def _normalise(destination: str) -> str:
try:
return str(Path(destination).expanduser().resolve())
except (OSError, ValueError):
return destination.strip()
# ---- writing -----------------------------------------------------------------
def create(library_id: str, *, name: str, target: str, destination: str) -> ExportSet:
sets = _load(library_id)
now = time.time()
created = ExportSet(
id=uuid.uuid4().hex,
name=name.strip() or "Untitled",
target=target,
destination=destination,
created=now,
modified=now,
)
sets[created.id] = created
_save(library_id, sets)
return created
def update(library_id: str, set_id: str, **fields) -> ExportSet | None:
"""Rename, retarget or relocate a set. Unknown fields are ignored."""
sets = _load(library_id)
found = sets.get(set_id)
if found is None:
return None
for key in ("name", "target", "destination"):
if key in fields and fields[key] is not None:
setattr(found, key, fields[key])
found.modified = time.time()
_save(library_id, sets)
return found
def delete(library_id: str, set_id: str) -> bool:
"""Forget a set. Deliberately does NOT touch its destination folder."""
sets = _load(library_id)
if sets.pop(set_id, None) is None:
return False
_save(library_id, sets)
return True
def add(library_id: str, set_id: str, *, track_ids=None, playlist_ids=None) -> ExportSet | None:
"""Add tracks and/or playlists, preserving order and ignoring duplicates."""
sets = _load(library_id)
found = sets.get(set_id)
if found is None:
return None
for incoming, existing in (
(track_ids or [], found.track_ids),
(playlist_ids or [], found.playlist_ids),
):
have = set(existing)
for item in incoming:
if item not in have:
have.add(item)
existing.append(item)
found.modified = time.time()
_save(library_id, sets)
return found
def remove(library_id: str, set_id: str, *, track_ids=None, playlist_ids=None) -> ExportSet | None:
"""Remove loose tracks and/or whole playlists.
There is no "remove a track from a referenced playlist": see the module
docstring. A track id passed here is dropped from the LOOSE list only, so
removing one that a referenced playlist also supplies is a no-op — which is
honest, because the playlist still puts it in the export.
"""
sets = _load(library_id)
found = sets.get(set_id)
if found is None:
return None
if track_ids:
drop = set(track_ids)
found.track_ids = [t for t in found.track_ids if t not in drop]
if playlist_ids:
drop = set(playlist_ids)
found.playlist_ids = [p for p in found.playlist_ids if p not in drop]
found.modified = time.time()
_save(library_id, sets)
return found
def retarget(library_id: str, mapping: dict[str, str]) -> None:
"""Follow track ids that changed, e.g. after an OS-path remap.
A Traktor track id IS its path, so a remap renames every id in the library.
Without this a set's references would dangle silently — and silently is the
problem, since the set would still look fine and export fewer tracks.
"""
if not mapping:
return
sets = _load(library_id)
touched = False
for found in sets.values():
renamed = [mapping.get(t, t) for t in found.track_ids]
if renamed != found.track_ids:
found.track_ids = renamed
found.modified = time.time()
touched = True
if touched:
_save(library_id, sets)
# ---- resolution --------------------------------------------------------------
def resolve(adapter, export_set: ExportSet) -> ResolvedSet:
"""What this set contains RIGHT NOW, against the loaded library.
Computed on every call and never stored, because the references are live —
the whole point is that a playlist edited after curation is picked up.
"""
resolved = ResolvedSet()
names = _playlist_names(adapter)
for playlist_id in export_set.playlist_ids:
entries = adapter.playlist_entries(playlist_id)
resolved.playlists.append(
ResolvedPlaylist(
id=playlist_id,
name=names.get(playlist_id, playlist_id),
# A playlist deleted since curation. Shown, not dropped: the set
# is the user's record of intent and losing it silently is worse
# than showing something broken.
missing=entries is None,
track_ids=list(entries or []),
)
)
for track_id in export_set.track_ids:
if adapter.track(track_id) is None:
resolved.dangling_track_ids.append(track_id)
else:
resolved.loose_track_ids.append(track_id)
return resolved
def _playlist_names(adapter) -> dict[str, str]:
out: dict[str, str] = {}
def walk(nodes) -> None:
for node in nodes or []:
out[node.id] = node.name
walk(getattr(node, "children", None))
walk(adapter.playlist_tree())
return out
+208
View File
@@ -0,0 +1,208 @@
"""A stable identity for a library, surviving a move or a rename.
Everything Konduktor persists ABOUT a library currently keys off its OS path:
`history` hashes the resolved path to pick a repo directory, `prefs` stores
`path_mappings` and `last_collection` as path strings. That is fine for things
the user can shrug at losing. It is not fine for **export sets**, which are
curated work holding references into one specific library — moving a collection
would silently orphan every one of them.
## How identity survives a move
Two halves, and only the first is authoritative:
1. **A sidecar beside the library** — `.konduktor-library.json`, holding a random
id. It lives in the library's own folder, so it MOVES WITH IT. Rename the
folder, drag it to another disk, restore it from a backup: same id.
2. **A registry in app-data** — `libraries.json`, mapping id → last known path,
platform and label. Derived and disposable; it exists so Konduktor can answer
"which libraries do I know about" without touching every disk, and it is
rebuilt from the sidecar whenever a library is opened.
The id is **random**, not derived. Deriving it from the path defeats the whole
purpose, and deriving it from the contents would change on every save.
## When a sidecar cannot be written
A removable or read-only library gets no sidecar — writing to a user's USB stick
to satisfy Konduktor's bookkeeping is not a trade worth making. Those fall back
to a **path-derived** id, which is stable for as long as the drive mounts at the
same place and is marked as such so nothing mistakes it for the durable kind.
Writing beside the user's library is not a new intrusion: saves already create a
`backups/` folder there. The sidecar is a hidden dotfile, so it does not show up
in the app's own file browser, which skips dotfiles.
"""
from __future__ import annotations
import hashlib
import logging
import time
import uuid
from pathlib import Path
from . import paths
log = logging.getLogger(__name__)
SIDECAR_NAME = ".konduktor-library.json"
_REGISTRY_NAME = "libraries.json"
# Path-derived ids carry this prefix so "durable" and "only as stable as this
# mount point" can never be confused — they behave differently on a move, and a
# caller that cares can ask.
VOLATILE_PREFIX = "path-"
def _registry_path() -> Path:
return paths.app_data_dir() / _REGISTRY_NAME
def _sidecar_path(library_path: Path) -> Path:
"""Where the sidecar lives for a library.
A library is a FILE on some platforms and a DIRECTORY on others, so the
sidecar goes inside a directory library and beside a file one — either way,
in the folder that travels with it.
"""
library_path = Path(library_path)
try:
folder = library_path if library_path.is_dir() else library_path.parent
except OSError:
folder = library_path.parent
return folder / SIDECAR_NAME
def _sidecar_key(library_path: Path) -> str:
"""Which entry in the sidecar belongs to this library.
One sidecar per FOLDER, keyed by filename, because a folder can legitimately
hold more than one library — a `collection.nml` beside an older one someone
kept. A single id per folder would hand both the same identity and, once
export sets exist, show one library's curated sets against another.
A directory library is the folder itself, so it keys on ".".
"""
library_path = Path(library_path)
try:
return "." if library_path.is_dir() else library_path.name
except OSError:
return library_path.name
def _volatile_id(library_path: Path) -> str:
digest = hashlib.sha256(str(Path(library_path).resolve()).encode()).hexdigest()
return f"{VOLATILE_PREFIX}{digest[:16]}"
def is_durable(library_id: str) -> bool:
"""Whether this id survives the library being moved."""
return not library_id.startswith(VOLATILE_PREFIX)
# ---- the registry ------------------------------------------------------------
def known() -> dict[str, dict]:
"""Every library Konduktor has seen, by id. Derived data — safe to lose."""
data = paths.read_json(_registry_path(), {})
return data if isinstance(data, dict) else {}
def describe(library_id: str) -> dict | None:
return known().get(library_id)
def _remember(library_id: str, library_path: Path, platform: str | None, label: str | None) -> None:
registry = known()
entry = registry.get(library_id) or {}
entry.update(
{
"path": str(library_path),
"platform": platform or entry.get("platform"),
"label": label or entry.get("label") or Path(library_path).name,
"last_seen": time.time(),
}
)
entry.setdefault("first_seen", entry["last_seen"])
registry[library_id] = entry
try:
paths.write_json(_registry_path(), registry)
except OSError:
# The registry is a convenience index; the sidecar is the source of
# truth, so failing to write it must not fail opening a library.
log.warning("could not update the library registry", exc_info=True)
def forget(library_id: str) -> None:
"""Drop a library from the registry. Does NOT touch its sidecar."""
registry = known()
if registry.pop(library_id, None) is not None:
try:
paths.write_json(_registry_path(), registry)
except OSError:
log.warning("could not update the library registry", exc_info=True)
# ---- identity ----------------------------------------------------------------
def for_path(
library_path: Path,
*,
platform: str | None = None,
label: str | None = None,
sidecar: bool = True,
) -> str:
"""This library's id, creating and recording one on first sight.
`sidecar=False` for a library Konduktor should not write next to — a
removable drive, or one opened read-only. Those get a path-derived id.
"""
library_path = Path(library_path)
found = read_sidecar(library_path) if sidecar else None
if found is None and sidecar:
found = uuid.uuid4().hex
if not _write_sidecar(library_path, found):
found = None # unwritable, e.g. a locked or read-only folder
library_id = found or _volatile_id(library_path)
_remember(library_id, library_path, platform, label)
return library_id
def read_sidecar(library_path: Path) -> str | None:
"""The id recorded beside this library, or None."""
entry = _sidecar_entries(library_path).get(_sidecar_key(library_path))
if isinstance(entry, dict):
value = entry.get("id")
if isinstance(value, str) and value:
return value
return None
def _sidecar_entries(library_path: Path) -> dict:
data = paths.read_json(_sidecar_path(library_path), {})
entries = data.get("libraries") if isinstance(data, dict) else None
return entries if isinstance(entries, dict) else {}
def _write_sidecar(library_path: Path, library_id: str) -> bool:
"""Record an id beside the library. False when the location refuses it."""
entries = _sidecar_entries(library_path)
entries[_sidecar_key(library_path)] = {"id": library_id, "created": time.time()}
try:
paths.write_json(
_sidecar_path(library_path),
{
# Only so a human finding this file knows what it is for. Never
# read back: the path is exactly what must not be trusted here.
"note": "Konduktor library ids. Keep this beside the library.",
"libraries": entries,
},
)
return True
except OSError:
log.info("no sidecar for %s — falling back to a path-derived id", library_path)
return False
+194 -2
View File
@@ -13,7 +13,7 @@ from fastapi import FastAPI, File, Form, HTTPException, Query, Response, UploadF
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse from fastapi.responses import FileResponse, JSONResponse
from . import __version__, history, prefs from . import __version__, exports, history, prefs
from .app_state import STATE from .app_state import STATE
from .core import auto_hotcues as ah from .core import auto_hotcues as ah
from . import importer from . import importer
@@ -43,9 +43,15 @@ from .schemas import (
EditTrack, EditTrack,
Facets, Facets,
FileTagOutcome, FileTagOutcome,
CreateExportSet,
ExportContents,
ExportPlaylistOut,
ExportSetMembers,
ExportSetOut,
FsEntry, FsEntry,
FsListing, FsListing,
FsPlace, FsPlace,
UpdateExportSet,
AddGridMarker, AddGridMarker,
GridMarkerEdit, GridMarkerEdit,
ReplaceGrid, ReplaceGrid,
@@ -225,9 +231,24 @@ def remap_paths(body: PathMappingInfo) -> RemapResult:
mapping = PathMapping.make(body.from_, body.to) mapping = PathMapping.make(body.from_, body.to)
if mapping.empty: if mapping.empty:
raise HTTPException(400, "Both a `from` and `to` prefix are required") raise HTTPException(400, "Both a `from` and `to` prefix are required")
count = require_adapter().remap_locations(mapping) adapter = require_adapter()
# A Traktor track id IS its location, so a remap renames every matching id.
# Snapshot before/after and follow them, or every export set referencing a
# remapped track would dangle — and dangle SILENTLY, still looking curated
# while quietly exporting fewer tracks than it says.
before = {t.id: t.filepath for t in adapter.tracks() if t.filepath}
count = adapter.remap_locations(mapping)
if count == 0: if count == 0:
return RemapResult(rewritten=0, commit=None) return RemapResult(rewritten=0, commit=None)
after = {t.filepath: t.id for t in adapter.tracks() if t.filepath}
moved = {
old_id: after[str(mapping.apply(Path(old_path)))]
for old_id, old_path in before.items()
if str(mapping.apply(Path(old_path))) in after
and after[str(mapping.apply(Path(old_path)))] != old_id
}
if moved and STATE.library_id:
exports.retarget(STATE.library_id, moved)
# Through AppState, not the adapter: this is the one route besides /api/save # Through AppState, not the adapter: this is the one route besides /api/save
# that writes, and skipping it would leave a gap in the version history. # that writes, and skipping it would leave a gap in the version history.
_outcome, commit = STATE.save() _outcome, commit = STATE.save()
@@ -321,6 +342,177 @@ def fs_list(path: str | None = None, platform: str | None = None) -> FsListing:
) )
# ---- export sets -------------------------------------------------------------
#
# Curation, not library data: a set is Konduktor's own record of what to export,
# where to, and for which platform. Every route is scoped to the LOADED library
# by its stable id, so opening a different collection shows a different shelf and
# moving a collection does not orphan the sets built against it.
def _require_library_id() -> str:
require_adapter()
if STATE.library_id is None: # pragma: no cover — loaded implies an id
raise HTTPException(409, "No library is loaded")
return STATE.library_id
def _require_set(set_id: str):
found = exports.get(_require_library_id(), set_id)
if found is None:
raise HTTPException(404, f"No export called {set_id}")
return found
@app.get("/api/exports", response_model=list[ExportSetOut])
def list_exports() -> list[ExportSetOut]:
return [ExportSetOut(**s.as_dict()) for s in exports.all_sets(_require_library_id())]
@app.post("/api/exports", response_model=ExportSetOut)
def create_export(body: CreateExportSet) -> ExportSetOut:
if not body.destination.strip():
raise HTTPException(400, "An export needs a destination folder")
# 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")
created = exports.create(
_require_library_id(),
name=body.name,
target=body.target,
destination=body.destination,
)
return ExportSetOut(**created.as_dict())
@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")
updated = exports.update(
_require_library_id(),
set_id,
name=body.name,
target=body.target,
destination=body.destination,
)
return ExportSetOut(**updated.as_dict())
@app.delete("/api/exports/{set_id}")
def delete_export(set_id: str) -> dict:
"""Forget a set. Deliberately does NOT touch anything at its destination."""
_require_set(set_id)
return {"deleted": exports.delete(_require_library_id(), set_id)}
@app.post("/api/exports/{set_id}/add", response_model=ExportSetOut)
def add_to_export(set_id: str, body: ExportSetMembers) -> ExportSetOut:
_require_set(set_id)
updated = exports.add(
_require_library_id(), set_id,
track_ids=body.track_ids, playlist_ids=body.playlist_ids,
)
return ExportSetOut(**updated.as_dict())
@app.post("/api/exports/{set_id}/remove", response_model=ExportSetOut)
def remove_from_export(set_id: str, body: ExportSetMembers) -> ExportSetOut:
"""Remove loose tracks and/or WHOLE playlists.
There is no per-track removal inside a referenced playlist: the reference is
live, so honouring both would need an exclusion list — hidden state silently
deciding what a future export contains. For a subset, add the tracks instead.
"""
_require_set(set_id)
updated = exports.remove(
_require_library_id(), set_id,
track_ids=body.track_ids, playlist_ids=body.playlist_ids,
)
return ExportSetOut(**updated.as_dict())
@app.get("/api/exports/{set_id}/contents", response_model=ExportContents)
def export_contents(set_id: str) -> ExportContents:
"""What the set holds right now. Computed every call, never cached."""
found = _require_set(set_id)
resolved = exports.resolve(require_adapter(), found)
return ExportContents(
playlists=[
ExportPlaylistOut(id=p.id, name=p.name, missing=p.missing, count=len(p.track_ids))
for p in resolved.playlists
],
loose=len(resolved.loose_track_ids),
tracks=len(resolved.track_ids),
dangling=resolved.dangling_track_ids,
destination_conflict=exports.destination_conflict(
_require_library_id(), found.destination, ignore=set_id
),
)
@app.get("/api/exports/{set_id}/tracks", response_model=list[Track])
def export_tracks(set_id: str) -> list[Track]:
"""Every track the export would carry, deduped — the set's root view."""
found = _require_set(set_id)
adapter = require_adapter()
resolved = exports.resolve(adapter, found)
return [t for t in (adapter.track(tid) for tid in resolved.track_ids) if t is not None]
@app.get("/api/exports/{set_id}/playlists/{playlist_id}/tracks", response_model=list[Track])
def export_playlist_tracks(set_id: str, playlist_id: str) -> list[Track]:
"""One included playlist, as it stands now.
Read straight from the library rather than from the set, which is the live
reference doing its job: what ships is whatever the playlist holds today.
"""
found = _require_set(set_id)
if playlist_id not in found.playlist_ids:
raise HTTPException(404, "That playlist is not in this export")
tracks = require_adapter().playlist_tracks(playlist_id)
if tracks is None:
raise HTTPException(404, "That playlist no longer exists")
return tracks
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.
"""
return {"traktor"}
@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.
Returns the unsupported ones too, with `installed=False` standing for "not a
target yet", so the UI can show them disabled with a reason. A silently
absent option reads as a missing feature; a disabled one reads as a roadmap.
"""
supported = _export_targets()
return [
PlatformOption(
platform=d.platform,
name=d.display_name,
library_label=getattr(d, "library_label", ""),
selects="directory", # an export destination is always a folder
installed=d.platform in supported,
found=0,
removable=bool(getattr(d, "removable", False)),
)
for d in registry.drivers()
]
# ---- health / state --------------------------------------------------- # ---- health / state ---------------------------------------------------
+32
View File
@@ -16,6 +16,7 @@ anyway; callers already treat all data I/O as best-effort.
""" """
from __future__ import annotations from __future__ import annotations
import json
import os import os
from pathlib import Path from pathlib import Path
@@ -25,6 +26,37 @@ _APP_NAME = "Konduktor"
_APP_AUTHOR = "Liquid Ice Studios" _APP_AUTHOR = "Liquid Ice Studios"
def write_json(path: Path, data) -> None:
"""Write JSON so a crash mid-write cannot leave a truncated file.
Deliberately NOT best-effort, unlike `prefs.save_prefs`: this is for data the
user CURATED — export sets, library identity — where losing it is real work
lost, not a forgotten window size. Failures raise so a caller can say so.
Written to a temp file in the SAME directory and then `os.replace`d, which is
atomic on POSIX and on Windows: a reader sees either the whole old file or
the whole new one, never half of either.
"""
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(f".{path.name}.tmp{os.getpid()}")
try:
tmp.write_text(json.dumps(data, indent=2))
os.replace(tmp, path)
finally:
try:
tmp.unlink()
except OSError:
pass # already replaced, which is the success path
def read_json(path: Path, default=None):
"""Read JSON, or `default` if it is missing or unreadable."""
try:
return json.loads(path.read_text())
except (OSError, ValueError):
return default
def app_data_dir() -> Path: def app_data_dir() -> Path:
"""The user-writable directory for Konduktor's persisted app data.""" """The user-writable directory for Konduktor's persisted app data."""
override = os.environ.get("KONDUKTOR_DATA_DIR") override = os.environ.get("KONDUKTOR_DATA_DIR")
+55
View File
@@ -135,6 +135,61 @@ class CollectionOptions(BaseModel):
recent: CollectionCandidate | None = None # last opened (from userprefs) recent: CollectionCandidate | None = None # last opened (from userprefs)
# ---- export sets -------------------------------------------------------------
#
# Konduktor's own data, never written into the user's library, and keyed by the
# library's stable ID rather than its path. See `exports.py`.
class ExportSetOut(BaseModel):
id: str
name: str
target: str # platform id of the export TARGET
destination: str
playlist_ids: list[str] = []
track_ids: list[str] = [] # loose tracks only
created: float = 0.0
modified: float = 0.0
class CreateExportSet(BaseModel):
name: str
target: str = "traktor"
destination: str
class UpdateExportSet(BaseModel):
name: str | None = None
target: str | None = None
destination: str | None = None
class ExportSetMembers(BaseModel):
track_ids: list[str] = []
playlist_ids: list[str] = []
class ExportPlaylistOut(BaseModel):
id: str
name: str
#: The playlist has been deleted since it was added to the set.
missing: bool = False
count: int = 0
class ExportContents(BaseModel):
"""What a set holds RIGHT NOW. Never cached — the references are live."""
playlists: list[ExportPlaylistOut] = []
loose: int = 0
#: Deduped across playlists and loose tracks: one track, one file copy.
tracks: int = 0
#: Track ids the library no longer has, surfaced rather than dropped.
dangling: list[str] = []
#: Another set already writes to this destination, and an export CLEARS it.
destination_conflict: str | None = None
class FsPlace(BaseModel): class FsPlace(BaseModel):
"""A shortcut in the file browser's sidebar. """A shortcut in the file browser's sidebar.
+1 -1
View File
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
source .venv/bin/activate source .venv/bin/activate
fail=0 fail=0
for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_picker.py test_phase3.py test_history.py; do for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_picker.py test_library_id.py test_exports.py test_phase3.py test_history.py; do
echo "──────────────────────────────────────────" echo "──────────────────────────────────────────"
echo "▶ $t" echo "▶ $t"
echo "──────────────────────────────────────────" echo "──────────────────────────────────────────"
+171
View File
@@ -0,0 +1,171 @@
"""Export sets: curation that outlives the session, keyed to a library.
The properties worth pinning are the ones that fail SILENTLY:
* a **live** playlist reference picks up later edits — a set that quietly
froze at curation time would still look right and ship the wrong tracks;
* contents **dedupe** across playlists and loose tracks, so one track is one
file copy;
* a deleted playlist or track is **surfaced**, never dropped — a gig stick
missing four tracks with no warning is this feature's worst failure;
* sets are **per library**, so opening another collection shows another shelf;
* two sets pointing at one destination are **caught**, because an export
CLEARS its destination and would wipe the other's output.
Runs against a temp COPY of the real collection, and a temp app-data dir, so it
touches neither the user's library nor their real export sets.
"""
import os
import shutil
import tempfile
from pathlib import Path
_TMP = tempfile.TemporaryDirectory()
os.environ["KONDUKTOR_DATA_DIR"] = _TMP.name
from konduktor import exports # noqa: E402
from konduktor.app_state import STATE # noqa: E402
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
work = Path(tempfile.mkdtemp())
shutil.copy2(REAL, work / "collection.nml")
STATE.open(work / "collection.nml")
adapter = STATE.adapter
LIB = STATE.library_id
check("opening a library issues an id", bool(LIB))
# A real playlist with tracks in it, to reference.
def _first_playlist(nodes):
for node in nodes or []:
if node.kind == "playlist" and (node.count or 0) >= 2:
return node
found = _first_playlist(getattr(node, "children", None))
if found:
return found
return None
playlist = _first_playlist(adapter.playlist_tree())
assert playlist is not None, "the fixture collection has no playlist with 2+ tracks"
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"))
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")
exports.update(LIB, s1.id, name="Ibiza")
check("rename persists", exports.get(LIB, s1.id).name == "Ibiza")
check("and bumps modified", exports.get(LIB, s1.id).modified >= s1.created)
print("== membership: ordered, deduped, and removable ==")
exports.add(LIB, s1.id, track_ids=[all_tracks[0], all_tracks[1]])
exports.add(LIB, s1.id, track_ids=[all_tracks[1], all_tracks[2]])
check("duplicates are ignored, order kept",
exports.get(LIB, s1.id).track_ids == all_tracks[:3],
exports.get(LIB, s1.id).track_ids)
exports.add(LIB, s1.id, playlist_ids=[playlist.id, playlist.id])
check("a playlist is added once", exports.get(LIB, s1.id).playlist_ids == [playlist.id])
exports.remove(LIB, s1.id, track_ids=[all_tracks[1]])
check("a loose track is removable",
exports.get(LIB, s1.id).track_ids == [all_tracks[0], all_tracks[2]])
print("== resolution is LIVE and deduped ==")
resolved = exports.resolve(adapter, exports.get(LIB, s1.id))
check("the referenced playlist resolves by name",
resolved.playlists[0].name == playlist.name and not resolved.playlists[0].missing)
check("with its CURRENT tracks", resolved.playlists[0].track_ids == playlist_tracks)
# The whole point of a reference: what ships is what the playlist holds at
# export time, not what it held when it was dragged in.
spare = next(t for t in all_tracks if t not in playlist_tracks)
adapter.set_playlist_entries(playlist.id, playlist_tracks + [spare])
again = exports.resolve(adapter, exports.get(LIB, s1.id))
check("a track added to the playlist LATER is picked up",
spare in again.playlists[0].track_ids)
check("without the set itself changing",
exports.get(LIB, s1.id).playlist_ids == [playlist.id])
adapter.set_playlist_entries(playlist.id, playlist_tracks) # put it back
# One track, one file copy — even when it is both loose and in a playlist.
exports.add(LIB, s1.id, track_ids=[playlist_tracks[0]])
deduped = exports.resolve(adapter, exports.get(LIB, s1.id)).track_ids
check("a track in a playlist AND loose appears once",
deduped.count(playlist_tracks[0]) == 1, deduped)
check("the total is the union, not the sum",
len(deduped) == len(set(deduped)) and len(deduped) >= len(playlist_tracks))
exports.remove(LIB, s1.id, track_ids=[playlist_tracks[0]])
print("== what is gone is SURFACED, never silently dropped ==")
exports.add(LIB, s1.id, track_ids=["Macintosh HD/:nowhere/:ghost.mp3"])
gone = exports.resolve(adapter, exports.get(LIB, s1.id))
check("a track the library no longer has is reported",
gone.dangling_track_ids == ["Macintosh HD/:nowhere/:ghost.mp3"])
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",
destination=str(work / "out2"))
exports.add(LIB, s2.id, playlist_ids=["no-such-playlist"])
ghost = exports.resolve(adapter, exports.get(LIB, s2.id))
check("a deleted playlist is shown as missing, not dropped",
len(ghost.playlists) == 1 and ghost.playlists[0].missing)
check("and contributes no tracks", ghost.track_ids == [])
print("== two sets, one destination ==")
# An export CLEARS its destination, so the second would wipe the first's output.
# 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"))
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",
exports.destination_conflict(LIB, str(work / "out"), ignore=s1.id) == "Clash")
check("paths are compared normalised, not as strings",
exports.destination_conflict(LIB, str(work / "out") + "/./", ignore=s3.id) == "Ibiza")
exports.delete(LIB, s3.id)
print("== following track ids that change under a path remap ==")
exports.retarget(LIB, {all_tracks[0]: "Macintosh HD/:Moved/:one.mp3"})
check("a renamed id is followed",
"Macintosh HD/:Moved/:one.mp3" in exports.get(LIB, s1.id).track_ids)
check("and the old one is gone", all_tracks[0] not in exports.get(LIB, s1.id).track_ids)
exports.retarget(LIB, {"Macintosh HD/:Moved/:one.mp3": all_tracks[0]})
check("an empty mapping is a no-op",
(exports.retarget(LIB, {}), exports.get(LIB, s1.id).track_ids[0])[1] == all_tracks[0])
print("== sets belong to ONE library ==")
other = Path(tempfile.mkdtemp()) / "Other"
other.mkdir()
shutil.copy2(REAL, other / "collection.nml")
STATE.open(other / "collection.nml")
check("a different library has a different id", STATE.library_id != LIB)
check("and an empty shelf", exports.all_sets(STATE.library_id) == [])
check("the first library's sets are untouched", len(exports.all_sets(LIB)) == 2)
# Stored per library, so one shelf cannot be read through the other's id.
check("stores are separate files",
exports._store_path(LIB) != exports._store_path(STATE.library_id))
print("== deleting a set leaves the destination alone ==")
dest = work / "out"
dest.mkdir(parents=True, exist_ok=True)
(dest / "already-there.txt").write_text("x")
exports.delete(LIB, s1.id)
check("the set is gone", exports.get(LIB, s1.id) is None)
check("the destination folder is NOT touched", (dest / "already-there.txt").is_file())
print("\n" + ("❌ FAILED" if failed else "✅ PASSED"))
_TMP.cleanup()
raise SystemExit(1 if failed else 0)
+139
View File
@@ -0,0 +1,139 @@
"""Stable library identity: the thing export sets are keyed by.
The property under test is one no other suite covers: **a library that moves
keeps its identity**. Everything Konduktor persists about a library keys off its
OS path today, so moving a collection silently orphans its history repo and its
path mapping. That is tolerable for those; it is not tolerable for export sets,
which are curated user work.
Runs entirely on temp directories and a temp app-data dir — it never touches a
real library, and `KONDUKTOR_DATA_DIR` keeps the registry out of the user's own.
"""
import json
import os
import tempfile
from pathlib import Path
# Isolate the app-data dir BEFORE anything reads it.
_TMP = tempfile.TemporaryDirectory()
os.environ["KONDUKTOR_DATA_DIR"] = _TMP.name
from konduktor import library_id, paths # noqa: E402
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
def a_library(folder: Path, name: str = "collection.nml") -> Path:
folder.mkdir(parents=True, exist_ok=True)
lib = folder / name
lib.write_text("<NML/>")
return lib
root = Path(tempfile.mkdtemp())
print("== an id is stable, and written beside the library ==")
lib = a_library(root / "Traktor 4.5.0")
first = library_id.for_path(lib, platform="traktor", label="collection.nml")
check("an id is issued", bool(first))
check("asking again gives the same id", library_id.for_path(lib) == first)
check("a sidecar is written", (lib.parent / library_id.SIDECAR_NAME).is_file())
# The app's own file browser skips dotfiles, so the sidecar must be one or it
# shows up in the picker as a mystery file next to the user's collection.
check("the sidecar is hidden", library_id.SIDECAR_NAME.startswith("."))
check("the id is durable", library_id.is_durable(first))
# Used as a filename by the export-set store, so it must not need escaping.
check("the id is filesystem-safe", first.replace("-", "").isalnum(), first)
print("== the whole point: it survives a move ==")
moved = root / "Somewhere Else"
lib.parent.rename(moved)
after_move = library_id.for_path(moved / "collection.nml")
check("a moved library keeps its id", after_move == first, f"{after_move} vs {first}")
check("the registry follows it to the new path",
library_id.describe(first)["path"] == str(moved / "collection.nml"))
check("and it is still one library, not two", len(library_id.known()) == 1,
list(library_id.known()))
print("== two libraries in ONE folder are two libraries ==")
# The flaw this found: one sidecar per folder holding a single id would hand a
# `collection.nml` and an older one kept beside it the SAME identity — and then
# show one library's export sets against the other.
second = a_library(moved, "collection-2023.nml")
other = library_id.for_path(second, platform="traktor")
check("a sibling library gets its own id", other != first, f"{other} vs {first}")
check("one sidecar holds both", len(json.loads(
(moved / library_id.SIDECAR_NAME).read_text())["libraries"]) == 2)
check("each keeps its own on a re-read",
library_id.for_path(moved / "collection.nml") == first
and library_id.for_path(second) == other)
print("== separate folders are separate libraries ==")
elsewhere = a_library(root / "Traktor 3.11.0")
third = library_id.for_path(elsewhere, platform="traktor")
check("a different folder gets a different id", len({first, other, third}) == 3)
print("== a library Konduktor must not write beside ==")
# A removable drive: writing to a user's USB stick for Konduktor's own
# bookkeeping is not a trade worth making, so those get a path-derived id.
stick = root / "GIG"
stick_lib = a_library(stick)
volatile = library_id.for_path(stick_lib, platform="onelibrary", sidecar=False)
check("no sidecar is written", not (stick / library_id.SIDECAR_NAME).exists())
check("the id is reported as NOT durable", not library_id.is_durable(volatile))
check("it is still stable for a given path", library_id.for_path(stick_lib, sidecar=False) == volatile)
check("it is still registered", library_id.describe(volatile) is not None)
print("== a directory library keys on the folder itself ==")
drive = root / "DriveLibrary"
drive.mkdir()
drive_id = library_id.for_path(drive, platform="onelibrary")
check("a directory library gets an id", bool(drive_id))
check("keyed as '.', not by a filename",
"." in json.loads((drive / library_id.SIDECAR_NAME).read_text())["libraries"])
check("and is stable", library_id.for_path(drive) == drive_id)
print("== an unwritable location falls back rather than failing ==")
locked = root / "ReadOnly"
locked_lib = a_library(locked)
os.chmod(locked, 0o500) # r-x: cannot create the sidecar
try:
fallback = library_id.for_path(locked_lib, platform="traktor")
check("an id is still issued", bool(fallback))
check("and it says it is not durable", not library_id.is_durable(fallback))
finally:
os.chmod(locked, 0o700)
print("== the registry is an index, and disposable ==")
before = len(library_id.known())
library_id.forget(third)
check("forget removes it", library_id.describe(third) is None)
check("and only it", len(library_id.known()) == before - 1)
# The sidecar is the source of truth, so re-opening reissues the SAME id rather
# than a new one. A registry that could be lost and silently renumber libraries
# would be worse than no registry.
check("re-opening restores it from the sidecar",
library_id.for_path(elsewhere) == third)
print("== atomic writes: a reader never sees half a file ==")
target = Path(_TMP.name) / "atomic.json"
paths.write_json(target, {"a": 1})
paths.write_json(target, {"a": 2, "b": 3})
check("the second write replaced the first whole", paths.read_json(target) == {"a": 2, "b": 3})
check("no temp files left behind",
not [p for p in target.parent.iterdir() if p.name.startswith(".atomic.json.tmp")],
[p.name for p in target.parent.iterdir()])
check("a missing file reads as the default", paths.read_json(target.with_name("nope.json"), "x") == "x")
check("so does a corrupt one",
(target.write_text("{not json"), paths.read_json(target, "x"))[1] == "x")
print("\n" + ("❌ FAILED" if failed else "✅ PASSED"))
_TMP.cleanup()
raise SystemExit(1 if failed else 0)
+72
View File
@@ -324,6 +324,46 @@ export interface SourceStatus {
playlists: number | null playlists: number | null
} }
// ---- export sets ----
//
// Konduktor's own curation, never written into the user's library, and keyed by
// the library's stable ID rather than its path — so moving a collection does not
// orphan the sets built against it.
export interface ExportSet {
id: string
name: string
/** Platform id of the export TARGET, e.g. "traktor". */
target: string
destination: string
playlist_ids: string[]
/** LOOSE tracks only — tracks a referenced playlist supplies are not listed. */
track_ids: string[]
created: number
modified: number
}
export interface ExportPlaylist {
id: string
name: string
/** Deleted from the library since it was added to the set. */
missing: boolean
count: number
}
/** What a set holds RIGHT NOW. Never cache it: the references are live, so a
* playlist edited after curation changes what this returns. */
export interface ExportContents {
playlists: ExportPlaylist[]
loose: number
/** Deduped across playlists and loose tracks: one track, one file copy. */
tracks: number
/** Track ids the library no longer has. Shown, never silently dropped. */
dangling: string[]
/** Another set already writes here, and an export CLEARS its destination. */
destination_conflict: string | null
}
export interface FsPlace { export interface FsPlace {
/** Groups the row and picks its icon. Never a finished sentence. */ /** Groups the row and picks its icon. Never a finished sentence. */
kind: 'home' | 'music' | 'desktop' | 'documents' | 'downloads' | 'volume' | 'library' kind: 'home' | 'music' | 'desktop' | 'documents' | 'downloads' | 'volume' | 'library'
@@ -442,6 +482,38 @@ export const api = {
// Re-asked rather than cached: drives come and go while a dialog is open. // Re-asked rather than cached: drives come and go while a dialog is open.
places: (platform?: string) => getJSON<FsPlace[]>(`/api/fs/places${qs({ platform })}`), places: (platform?: string) => getJSON<FsPlace[]>(`/api/fs/places${qs({ platform })}`),
// ---- export sets ----
//
// All scoped to the LOADED library on the server, by its stable id, so
// nothing here has to carry which collection it means.
exports: () => getJSON<ExportSet[]>('/api/exports'),
createExport: (body: { name: string; target: string; destination: string }) =>
send<ExportSet>('POST', '/api/exports', body),
updateExport: (id: string, body: Partial<Pick<ExportSet, 'name' | 'target' | 'destination'>>) =>
send<ExportSet>('PATCH', `/api/exports/${encodeURIComponent(id)}`, body),
deleteExport: (id: string) =>
send<{ deleted: boolean }>('DELETE', `/api/exports/${encodeURIComponent(id)}`),
addToExport: (id: string, body: { track_ids?: string[]; playlist_ids?: string[] }) =>
send<ExportSet>('POST', `/api/exports/${encodeURIComponent(id)}/add`, body),
// Removes LOOSE tracks and WHOLE playlists. There is deliberately no way to
// remove one track from a referenced playlist: the reference is live, so that
// would need an exclusion list — hidden state deciding future exports.
removeFromExport: (id: string, body: { track_ids?: string[]; playlist_ids?: string[] }) =>
send<ExportSet>('POST', `/api/exports/${encodeURIComponent(id)}/remove`, body),
exportContents: (id: string) =>
getJSON<ExportContents>(`/api/exports/${encodeURIComponent(id)}/contents`),
exportTracks: (id: string) =>
getJSON<Track[]>(`/api/exports/${encodeURIComponent(id)}/tracks`),
exportPlaylistTracks: (id: string, playlistId: string) =>
getJSON<Track[]>(
`/api/exports/${encodeURIComponent(id)}/playlists/${encodeURIComponent(playlistId)}/tracks`,
),
// Every platform, with `installed` standing for "can be an export target".
// Unsupported ones are returned too, so the UI shows them disabled with a
// reason rather than hiding them — an absent option reads as a missing
// feature, a disabled one reads as a roadmap.
exportTargets: () => getJSON<PlatformOption[]>('/api/export-targets'),
// ---- path remapping (per-collection OS-path prefix translation) ---- // ---- path remapping (per-collection OS-path prefix translation) ----
getPathMapping: () => getJSON<PathMapping>('/api/library/path-mapping'), getPathMapping: () => getJSON<PathMapping>('/api/library/path-mapping'),
suggestPrefix: () => suggestPrefix: () =>