diff --git a/backend/konduktor/adapters/onelibrary/adapter.py b/backend/konduktor/adapters/onelibrary/adapter.py index d66fb1a..f7c682f 100644 --- a/backend/konduktor/adapters/onelibrary/adapter.py +++ b/backend/konduktor/adapters/onelibrary/adapter.py @@ -223,7 +223,7 @@ class OneLibraryAdapter: paths = [Path(p) for p in self._store.all_audio_paths()] return {"total": len(paths), "matched": 0, "existing": 0, "samples": []} - def remap_locations(self, mapping: PathMapping) -> int: + def remap_locations(self, mapping: PathMapping) -> dict[str, str]: raise Unsupported(self._readonly_reason("Rewriting stored paths")) # ---- save ------------------------------------------------------------- diff --git a/backend/konduktor/adapters/rekordbox/adapter.py b/backend/konduktor/adapters/rekordbox/adapter.py index aaf97a8..3fa8d33 100644 --- a/backend/konduktor/adapters/rekordbox/adapter.py +++ b/backend/konduktor/adapters/rekordbox/adapter.py @@ -220,7 +220,7 @@ class RekordboxAdapter: "samples": samples, } - def remap_locations(self, mapping: PathMapping) -> int: + def remap_locations(self, mapping: PathMapping) -> dict[str, str]: raise Unsupported(self._readonly_reason("Rewriting stored paths")) # ---- commands: track metadata ---------------------------------------- diff --git a/backend/konduktor/adapters/traktor/adapter.py b/backend/konduktor/adapters/traktor/adapter.py index 8d3b5f6..63318d9 100644 --- a/backend/konduktor/adapters/traktor/adapter.py +++ b/backend/konduktor/adapters/traktor/adapter.py @@ -369,13 +369,13 @@ class TraktorAdapter: def remap_preview(self, mapping: PathMapping) -> dict: return self._store.remap_preview(mapping) - def remap_locations(self, mapping: PathMapping) -> int: + def remap_locations(self, mapping: PathMapping) -> dict[str, str]: with _translate(): - n = self._store.remap_locations(mapping) + moved = self._store.remap_locations(mapping) # A remap rewrites LOCATIONs, so track ids themselves change — there is # no per-track patch that could express this. self._rebuild() - return n + return moved # ---- save -------------------------------------------------------------- @property diff --git a/backend/konduktor/adapters/traktor/store.py b/backend/konduktor/adapters/traktor/store.py index 6905053..fdc0510 100644 --- a/backend/konduktor/adapters/traktor/store.py +++ b/backend/konduktor/adapters/traktor/store.py @@ -1056,18 +1056,20 @@ class TraktorStore: samples.append({"from": str(base), "to": str(target), "exists": ok}) return {"total": total, "matched": matched, "existing": existing, "samples": samples} - def remap_locations(self, mapping: PathMapping) -> int: + def remap_locations(self, mapping: PathMapping) -> dict[str, str]: """Permanently rewrite matching track LOCATIONs to the mapping's ``to`` prefix — a deliberate library move (write-back). Because ``track_id`` IS the LOCATION key (``volume+dir+file``), every playlist ``PRIMARYKEY`` that referenced a moved track is rewritten too, so playlists keep pointing at their tracks. Non-matching entries are - untouched. Returns the number of tracks rewritten; the caller saves. + untouched. Returns ``{old track id: new track id}`` for every track + rewritten — callers holding ids (export sets) follow them with it, and + must not rebuild it from paths; the caller saves. """ if mapping.empty: - return 0 + return {} with self._lock: key_remap: dict[str, str] = {} for e in self._nml.collection.entry: @@ -1086,7 +1088,7 @@ class TraktorStore: loc.volume, loc.dir, loc.file = volume, dir_, file key_remap[old_key] = new_key if not key_remap: - return 0 + return {} # Rewrite playlist entry primary keys that referenced moved tracks. for node in self._iter_nodes(self._root()): pl = node.playlist @@ -1102,7 +1104,7 @@ class TraktorStore: self._journal.retarget(old_key, new_key) self._note("remap", str(len(key_remap))) self.dirty = True - return len(key_remap) + return key_remap def _entry_field_value(self, entry: Entrytype, field: str): """Read a single editable field's current value from the model, in the diff --git a/backend/konduktor/core/adapter.py b/backend/konduktor/core/adapter.py index 999924e..7f981a4 100644 --- a/backend/konduktor/core/adapter.py +++ b/backend/konduktor/core/adapter.py @@ -106,6 +106,7 @@ class LibraryAdapter(Protocol): def reload(self) -> None: ... # ---- read projection ------------------------------------------------- + @property def tracks(self) -> list[Track]: ... def track(self, track_id: str) -> Track | None: ... def query_tracks(self, **kw) -> TrackPage: ... @@ -177,7 +178,8 @@ class LibraryAdapter(Protocol): def set_path_mapping(self, mapping: PathMapping) -> None: ... def path_prefix_suggestions(self) -> dict: ... def remap_preview(self, mapping: PathMapping) -> dict: ... - def remap_locations(self, mapping: PathMapping) -> int: ... + # {old track id: new track id}; ids may change because a Traktor id IS its path. + def remap_locations(self, mapping: PathMapping) -> dict[str, str]: ... # ---- save ------------------------------------------------------------- @property diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index 78cedd8..456b1a8 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -245,26 +245,20 @@ def remap_paths(body: PathMappingInfo) -> RemapResult: raise HTTPException(400, "Both a `from` and `to` prefix are required") 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: + # 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. The adapter returns the renames + # itself: rebuilding them here from display paths (which omit the volume) + # could pair up two tracks with the same folder on different drives. + moved = adapter.remap_locations(mapping) + if not moved: 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 # that writes, and skipping it would leave a gap in the version history. _outcome, commit = STATE.save() - return RemapResult(rewritten=count, commit=commit) + return RemapResult(rewritten=len(moved), commit=commit) @app.get("/api/prefs") diff --git a/backend/test_exports.py b/backend/test_exports.py index c0e41ed..79f3ec3 100644 --- a/backend/test_exports.py +++ b/backend/test_exports.py @@ -179,6 +179,29 @@ 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("== a path rewrite carries every set's track ids with it ==") +# Through the ROUTE, not exports.retarget: the route is what joins the adapter's +# renames to the sets, and it once 500'd on every call with no test to notice. +from fastapi.testclient import TestClient # noqa: E402 + +import konduktor.main as main # noqa: E402 + +ad, lib = STATE.adapter, STATE.library_id +prefix = ad.path_prefix_suggestions()["primary"] +loose = next(t.id for t in ad.tracks if str(ad.audio_path(t.id) or "").startswith(prefix)) +s3 = exports.create(lib, name="Remapped", target="traktor", destination=str(work / "remapped")) +exports.add(lib, s3.id, track_ids=[loose]) +r = TestClient(main.app, raise_server_exceptions=False).post( + "/api/library/remap-paths", json={"from": prefix, "to": "/Volumes/KonduktorTest"} +) +check("the route answers 200", r.status_code == 200, r.text[:300]) +check("and rewrote tracks", r.status_code == 200 and r.json()["rewritten"] > 0, r.text[:300]) +followed = exports.get(lib, s3.id).track_ids +check("the set no longer holds the old id", loose not in followed, str(followed)) +check("it holds the track's NEW id", + len(followed) == 1 and ad.track(followed[0]) is not None + and str(ad.audio_path(followed[0])).startswith("/Volumes/KonduktorTest"), str(followed)) + print("\n" + ("❌ FAILED" if failed else "✅ PASSED")) _TMP.cleanup() raise SystemExit(1 if failed else 0) diff --git a/backend/test_save_fidelity.py b/backend/test_save_fidelity.py index 1c8ecab..ad57a7a 100644 --- a/backend/test_save_fidelity.py +++ b/backend/test_save_fidelity.py @@ -439,7 +439,7 @@ with tempfile.TemporaryDirectory() as d: from_prefix = str(resolve_path(loc.volume, loc.dir, loc.file)) to_prefix = "/Volumes/KONDUKTOR_TEST_H1/remapped__unique__one.mp3" - n = store.remap_locations(PathMapping.make(from_prefix, to_prefix)) + n = len(store.remap_locations(PathMapping.make(from_prefix, to_prefix))) store.save() edited = work.read_bytes() @@ -489,7 +489,7 @@ with tempfile.TemporaryDirectory() as d: to_prefix = "/Volumes/KONDUKTOR_TEST_H2/remapped__playlist__one.mp3" new_key = "".join(os_path_to_location(Path(to_prefix))) - n = store.remap_locations(PathMapping.make(from_prefix, to_prefix)) + n = len(store.remap_locations(PathMapping.make(from_prefix, to_prefix))) store.save() check("H2: at least one track rewritten", n >= 1) diff --git a/backend/test_traktor_adapter.py b/backend/test_traktor_adapter.py index c8ca39e..38c6318 100644 --- a/backend/test_traktor_adapter.py +++ b/backend/test_traktor_adapter.py @@ -168,9 +168,13 @@ with tempfile.TemporaryDirectory() as d: if (ap := adapter.audio_path(t.id)) and str(ap).startswith(prefix) } old_id = next(iter(matched)) - n = adapter.remap_locations(PathMapping.make(prefix, "/Volumes/KonduktorTest")) + moved = adapter.remap_locations(PathMapping.make(prefix, "/Volumes/KonduktorTest")) + n = len(moved) check("remap rewrote some locations", n > 0, str(n)) check("the old track id is gone from the index", adapter.track(old_id) is None) + # Export sets follow ids through a remap with exactly this mapping. + check("it reports where each track id went", + old_id in moved and adapter.track(moved[old_id]) is not None) check("the index still holds every track", len(adapter.tracks) == 8485) # ---- place_cues takes the generic spec ------------------------------------