From b130f1469e691184a31a94b91b24fe7349cbcda8 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Wed, 8 Jul 2026 21:54:58 +0200 Subject: [PATCH] Implemented path remapping --- backend/konduktor/main.py | 70 ++++ backend/konduktor/path_mapping.py | 127 +++++++ backend/konduktor/playlist_store.py | 141 +++++++- backend/konduktor/prefs.py | 29 ++ backend/konduktor/schemas.py | 44 ++- backend/test_save_fidelity.py | 126 +++++++ frontend/src/App.tsx | 10 + frontend/src/api.ts | 42 +++ frontend/src/components/PathMappingDialog.tsx | 311 ++++++++++++++++++ frontend/src/components/SettingsMenu.tsx | 64 ++++ frontend/src/components/Toast.tsx | 16 +- frontend/src/components/Toolbar.tsx | 4 + 12 files changed, 968 insertions(+), 16 deletions(-) create mode 100644 backend/konduktor/path_mapping.py create mode 100644 frontend/src/components/PathMappingDialog.tsx create mode 100644 frontend/src/components/SettingsMenu.tsx diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index a7d5885..768cf79 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -17,6 +17,7 @@ from . import auto_hotcues as ah from . import prefs from .collection_service import CollectionService from .discovery import describe, detect_collections +from .path_mapping import PathMapping from .playlist_store import PlaylistError, PlaylistStore from .schemas import ( AutoGridRequest, @@ -35,7 +36,11 @@ from .schemas import ( FsListing, GridEdit, OpenCollection, + PathMappingInfo, PlaylistNode, + PrefixSuggestions, + RemapPreview, + RemapResult, RenamePlaylist, SaveResult, SetEntries, @@ -82,6 +87,11 @@ class AppState: # only commit to the new collection if BOTH succeed. service = CollectionService(path) store = PlaylistStore(path) + # Apply this collection's saved OS-path remapping (per-machine, keyed by + # the collection's local path) so runtime translation is live on open. + saved = prefs.get_path_mapping(str(path)) + if saved: + store.set_path_mapping(PathMapping.make(saved["from"], saved["to"])) self.path, self.service, self.store = path, service, store @@ -153,6 +163,66 @@ def collection_options() -> CollectionOptions: return CollectionOptions(auto=auto, recent=recent) +@app.get("/api/collection/path-mapping", response_model=PathMappingInfo) +def get_path_mapping() -> PathMappingInfo: + """The current collection's saved OS-path remapping (blank if none).""" + require_store() + saved = prefs.get_path_mapping(str(STATE.path)) + if saved: + return PathMappingInfo.model_validate({"from": saved["from"], "to": saved["to"]}) + return PathMappingInfo() + + +@app.put("/api/collection/path-mapping", response_model=PathMappingInfo) +def put_path_mapping(body: PathMappingInfo) -> PathMappingInfo: + """Set (or, with blank prefixes, clear) the current collection's remapping. + Persists to userprefs AND updates the live store so playback/analysis + re-resolve immediately — no reopen needed. Never touches the .nml.""" + store = require_store() + mapping = PathMapping.make(body.from_, body.to) + prefs.set_path_mapping( + str(STATE.path), mapping.from_prefix or None, mapping.to_prefix or None + ) + store.set_path_mapping(mapping) + return PathMappingInfo.model_validate( + {"from": mapping.from_prefix, "to": mapping.to_prefix} + ) + + +@app.get("/api/collection/path-mapping/suggest", response_model=PrefixSuggestions) +def suggest_path_prefix() -> PrefixSuggestions: + """Auto-detected `from` prefix candidates (common directory per volume), + so the editor can prefill the stored prefix.""" + store = require_store() + return PrefixSuggestions.model_validate(store.path_prefix_suggestions()) + + +@app.get("/api/collection/path-mapping/preview", response_model=RemapPreview) +def preview_path_mapping( + from_: str = Query("", alias="from"), to: str = Query("") +) -> RemapPreview: + """Validate a candidate mapping before saving/committing: how many tracks + match `from` and how many exist at `to`.""" + store = require_store() + return RemapPreview.model_validate(store.remap_preview(PathMapping.make(from_, to))) + + +@app.post("/api/collection/remap-paths", response_model=RemapResult) +def remap_paths(body: PathMappingInfo) -> RemapResult: + """Write-back: permanently rewrite matching track LOCATIONs (and the + playlist references that join to them) to the `to` prefix, then save + (backup-first). Destructive and OS-specific — the UI warns accordingly.""" + store = require_store() + mapping = PathMapping.make(body.from_, body.to) + if mapping.empty: + raise HTTPException(400, "Both a `from` and `to` prefix are required") + count = store.remap_locations(mapping) + if count == 0: + return RemapResult(rewritten=0, backup=None) + outcome = store.save() + return RemapResult(rewritten=count, backup=str(outcome.backup)) + + @app.get("/api/prefs") def get_prefs() -> dict: """The full persisted user-preferences blob (UI layout, last collection…).""" diff --git a/backend/konduktor/path_mapping.py b/backend/konduktor/path_mapping.py new file mode 100644 index 0000000..e7efd10 --- /dev/null +++ b/backend/konduktor/path_mapping.py @@ -0,0 +1,127 @@ +"""Per-collection OS-path prefix remapping. + +A Traktor collection stores absolute audio-file paths. When the same collection +is used on another machine (a portable USB that mounts elsewhere, a relocated +library), those paths aren't reachable. A ``PathMapping`` translates a stored +path prefix (``from_prefix``) to a local one (``to_prefix``). + +This module is intentionally pure (no I/O beyond ``~`` expansion) so it can be +unit-tested and reused by both the runtime resolver (``PlaylistStore``) and the +write-back operation. See ``file_tags.resolve_path`` for the LOCATION -> OS path +step this composes with. +""" +from __future__ import annotations + +import os +import re +from dataclasses import dataclass +from pathlib import Path + +_WIN_DRIVE = re.compile(r"^([A-Za-z]:)[\\/](.*)$") +_MAC_VOLUME = re.compile(r"^/Volumes/([^/]+)/(.*)$") + + +def _norm(prefix: str | None) -> str: + """Normalize a prefix for matching: expand ``~``, strip a trailing slash.""" + if not prefix: + return "" + p = os.path.expanduser(prefix.strip()) + # Strip a single trailing separator (both / and \) but keep a bare root. + if len(p) > 1: + p = p.rstrip("/\\") + return p + + +@dataclass(frozen=True) +class PathMapping: + """A single ``from_prefix`` -> ``to_prefix`` OS-path prefix substitution.""" + + from_prefix: str = "" + to_prefix: str = "" + + @classmethod + def make(cls, from_prefix: str | None, to_prefix: str | None) -> "PathMapping": + return cls(_norm(from_prefix), _norm(to_prefix)) + + @property + def empty(self) -> bool: + return not self.from_prefix or not self.to_prefix + + def matches(self, os_path: Path) -> bool: + """True if ``os_path`` is at or under ``from_prefix`` (segment-aware, + so ``/a/b`` matches ``/a/b`` and ``/a/b/c`` but not ``/a/bc``).""" + if self.empty: + return False + s = str(os_path) + if s == self.from_prefix: + return True + return s.startswith(self.from_prefix + os.sep) or s.startswith(self.from_prefix + "/") + + def apply(self, os_path: Path) -> Path: + """Rebase ``os_path`` from ``from_prefix`` onto ``to_prefix``. Returns the + path unchanged when it doesn't match (non-matching tracks untouched).""" + if not self.matches(os_path): + return os_path + rest = str(os_path)[len(self.from_prefix):] + # `rest` starts with a separator (or is empty when the path == from_prefix). + return Path(self.to_prefix + rest) + + +def common_dir_prefix(paths: list[str]) -> str: + """Longest directory prefix shared by all ``paths`` (segment-aware). + + Operates on each path's parent directory, so the result is always a folder + (never a partial filename), and degrades to ``""`` when the paths share no + common root. Used to auto-suggest the ``from`` prefix in the remap editor. + """ + if not paths: + return "" + dirs = [p.replace("\\", "/").rsplit("/", 1)[0] for p in paths] + common: list[str] = [] + for segs in zip(*(d.split("/") for d in dirs)): + if len(set(segs)) == 1: + common.append(segs[0]) + else: + break + return "/".join(common) + + +def _traktor_dir(posix_body: str) -> str: + """Convert a POSIX directory body (leading+trailing '/', e.g. '/Music/') + to Traktor's '/:'-segmented form ('/:Music/:').""" + return posix_body.replace("/", "/:") + + +def os_path_to_location(os_path: Path) -> tuple[str, str, str]: + """Inverse of ``file_tags.resolve_path``: build a Traktor + ``(volume, dir, file)`` from an OS path, for the platform implied by the + path's shape. Round-trips with ``resolve_path``. + + Used by write-back only; the produced LOCATION is valid for the OS whose + path shape it matches (Windows drive, macOS ``/Volumes`` mount, or a POSIX + boot path -> ``Macintosh HD``). + """ + # Derive the filename from the string (not Path.name) so a Windows-style + # path is handled even when this runs on a POSIX host, and vice-versa. + s = str(os_path) + + m = _WIN_DRIVE.match(s) + if m: + volume = m.group(1) # e.g. "E:" + body = m.group(2).replace("\\", "/") # "Music/x.mp3" + name = body.rsplit("/", 1)[-1] + dir_body = "/" + body[: len(body) - len(name)] # "/Music/" + return volume, _traktor_dir(dir_body), name + + m = _MAC_VOLUME.match(s) + if m: + volume = m.group(1) # mounted volume name + body = m.group(2) # "Music/x.mp3" + name = body.rsplit("/", 1)[-1] + dir_body = "/" + body[: len(body) - len(name)] # "/Music/" + return volume, _traktor_dir(dir_body), name + + # POSIX boot volume, e.g. "/Users/you/Music/x.mp3". + name = s.rsplit("/", 1)[-1] + dir_body = s[: len(s) - len(name)] # "/Users/you/Music/" + return "Macintosh HD", _traktor_dir(dir_body), name diff --git a/backend/konduktor/playlist_store.py b/backend/konduktor/playlist_store.py index b89d7f2..2625a50 100644 --- a/backend/konduktor/playlist_store.py +++ b/backend/konduktor/playlist_store.py @@ -43,6 +43,7 @@ from traktor_nml_utils.models.collection import ( ) from xsdata.formats.dataclass.serializers import XmlSerializer +from .path_mapping import PathMapping from .schemas import PlaylistNode @@ -70,6 +71,8 @@ class PlaylistStore: self.nml_path = Path(nml_path) self._lock = threading.RLock() self.dirty = False + # Active OS-path prefix remapping (empty = identity). Survives _load(). + self._path_mapping = PathMapping() self._load() # ---- load ---------------------------------------------------------- @@ -440,6 +443,30 @@ class PlaylistStore: self._track_art[track_id] = (data, mime) self.dirty = True + def set_path_mapping(self, mapping: PathMapping) -> None: + """Set the active OS-path prefix remapping (applied at resolve time).""" + with self._lock: + self._path_mapping = mapping + + def _resolve(self, loc) -> "Path | None": + """Resolve a LOCATION to an OS path, applying the active path mapping. + + The single FS chokepoint: LOCATION -> `resolve_path` -> prefix remap. + Falls back to the un-remapped path when the remapped target doesn't + exist, so a misconfigured mapping never makes a present file unreachable. + """ + from . import file_tags + + if loc is None: + return None + base = file_tags.resolve_path(loc.volume, loc.dir, loc.file) + if self._path_mapping.empty: + return base + remapped = self._path_mapping.apply(base) + if remapped == base: + return base + return remapped if remapped.exists() else base + def cover_art(self, track_id: str) -> tuple[bytes, str] | None: """Staged replacement if present, else the file's current embedded art.""" from . import file_tags @@ -450,19 +477,116 @@ class PlaylistStore: entry = self._entry_by_key.get(track_id) if entry is None or entry.location is None: return None - loc = entry.location - return file_tags.read_cover(file_tags.resolve_path(loc.volume, loc.dir, loc.file)) + path = self._resolve(entry.location) + return file_tags.read_cover(path) if path else None def audio_path(self, track_id: str) -> "Path | None": """Resolve a track's audio file to an OS path (for playback streaming).""" - from . import file_tags - with self._lock: entry = self._entry_by_key.get(track_id) if entry is None or entry.location is None: return None - loc = entry.location - return file_tags.resolve_path(loc.volume, loc.dir, loc.file) + return self._resolve(entry.location) + + def path_prefix_suggestions(self) -> dict: + """Auto-suggest ``from`` prefixes by resolving every track's LOCATION and + finding the common directory prefix per volume. Returns a ``primary`` + (the largest group's prefix) plus per-group prefixes ranked by track + count, so the editor can prefill and offer alternatives.""" + from collections import defaultdict + + from . import file_tags + from .path_mapping import common_dir_prefix + + with self._lock: + groups: dict[str, list[str]] = defaultdict(list) + for e in self._nml.collection.entry: + loc = e.location + if not loc: + continue + groups[loc.volume or ""].append( + str(file_tags.resolve_path(loc.volume, loc.dir, loc.file)) + ) + ranked = sorted( + ( + {"prefix": common_dir_prefix(paths), "count": len(paths)} + for paths in groups.values() + ), + key=lambda g: g["count"], + reverse=True, + ) + ranked = [g for g in ranked if g["prefix"]] + return {"primary": ranked[0]["prefix"] if ranked else "", "groups": ranked[:5]} + + def remap_preview(self, mapping: PathMapping) -> dict: + """How a mapping would affect the collection, without changing anything: + total tracks, how many match ``from``, and how many exist at ``to`` + (plus a few samples). Powers the mapping editor's validation line.""" + from . import file_tags + + with self._lock: + total = matched = existing = 0 + samples: list[dict] = [] + for e in self._nml.collection.entry: + loc = e.location + if not loc: + continue + total += 1 + base = file_tags.resolve_path(loc.volume, loc.dir, loc.file) + if mapping.matches(base): + matched += 1 + target = mapping.apply(base) + ok = target.exists() + if ok: + existing += 1 + if len(samples) < 5: + 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: + """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. + """ + from . import file_tags + from .path_mapping import os_path_to_location + + if mapping.empty: + return 0 + with self._lock: + key_remap: dict[str, str] = {} + for e in self._nml.collection.entry: + loc = e.location + if not loc: + continue + base = file_tags.resolve_path(loc.volume, loc.dir, loc.file) + if not mapping.matches(base): + continue + target = mapping.apply(base) + volume, dir_, file = os_path_to_location(target) + old_key = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}" + new_key = f"{volume or ''}{dir_ or ''}{file or ''}" + if old_key == new_key: + continue # no-op (e.g. from == to); leave byte-identical + loc.volume, loc.dir, loc.file = volume, dir_, file + key_remap[old_key] = new_key + if not key_remap: + return 0 + # Rewrite playlist entry primary keys that referenced moved tracks. + for node in self._iter_nodes(self._root()): + pl = node.playlist + if pl is None or not pl.entry: + continue + for entry in pl.entry: + pk = entry.primarykey + if pk and pk.key in key_remap: + pk.key = key_remap[pk.key] + self.dirty = True + return len(key_remap) def _entry_field_value(self, entry: Entrytype, field: str): """Read a single editable field's current value from the model, in the @@ -504,8 +628,9 @@ class PlaylistStore: entry = self._entry_by_key.get(track_id) if entry is None or entry.location is None: continue - loc = entry.location - path = file_tags.resolve_path(loc.volume, loc.dir, loc.file) + path = self._resolve(entry.location) + if path is None: + continue r = None if track_id in self._track_edits: meta = {f: self._entry_field_value(entry, f) for f in self._track_edits[track_id]} diff --git a/backend/konduktor/prefs.py b/backend/konduktor/prefs.py index 7b3ff22..4c743a0 100644 --- a/backend/konduktor/prefs.py +++ b/backend/konduktor/prefs.py @@ -37,6 +37,35 @@ def update_prefs(patch: dict) -> dict: return prefs +def get_path_mapping(collection_path: str) -> dict | None: + """The saved ``{from, to}`` OS-path remapping for a collection, or None. + + Keyed by the collection's current OS path (the mapping is per-machine data, + so the local path is a natural, machine-specific key).""" + mappings = load_prefs().get("path_mappings") + if isinstance(mappings, dict): + m = mappings.get(collection_path) + if isinstance(m, dict): + return {"from": m.get("from") or "", "to": m.get("to") or ""} + return None + + +def set_path_mapping( + collection_path: str, from_prefix: str | None, to_prefix: str | None +) -> None: + """Persist (or, when either prefix is blank, clear) a collection's mapping.""" + prefs = load_prefs() + mappings = prefs.get("path_mappings") + if not isinstance(mappings, dict): + mappings = {} + if from_prefix and to_prefix: + mappings[collection_path] = {"from": from_prefix, "to": to_prefix} + else: + mappings.pop(collection_path, None) + prefs["path_mappings"] = mappings + save_prefs(prefs) + + def get_last_collection() -> str | None: val = load_prefs().get("last_collection") return val if isinstance(val, str) else None diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index 2aa4fe8..2189ffb 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -1,7 +1,7 @@ """API response models (Pydantic).""" from __future__ import annotations -from pydantic import BaseModel +from pydantic import BaseModel, ConfigDict, Field class Track(BaseModel): @@ -221,3 +221,45 @@ class FsListing(BaseModel): home: str dirs: list[FsEntry] files: list[FsEntry] # .nml files only + + +# ---- path remapping ---- +# `from` is a Python keyword, so the field is `from_` with a `from` alias +# (populate_by_name lets it be set either way; responses serialize as "from"). + + +class PathMappingInfo(BaseModel): + """A per-collection OS-path prefix remapping (blank prefixes = no mapping).""" + + model_config = ConfigDict(populate_by_name=True) + from_: str = Field(default="", alias="from") + to: str = "" + + +class RemapSample(BaseModel): + model_config = ConfigDict(populate_by_name=True) + from_: str = Field(alias="from") + to: str + exists: bool + + +class RemapPreview(BaseModel): + total: int # tracks with a resolvable location + matched: int # how many match the `from` prefix + existing: int # of matched, how many exist at the `to` target + samples: list[RemapSample] = [] + + +class RemapResult(BaseModel): + rewritten: int # tracks whose LOCATION was rewritten + backup: str | None = None # path of the .bak written before the rewrite + + +class PrefixGroup(BaseModel): + prefix: str # common directory prefix of a group of tracks + count: int # tracks sharing it + + +class PrefixSuggestions(BaseModel): + primary: str # best guess for the `from` prefix (largest group) + groups: list[PrefixGroup] = [] # alternatives, ranked by count diff --git a/backend/test_save_fidelity.py b/backend/test_save_fidelity.py index 6e335fb..5a63e54 100644 --- a/backend/test_save_fidelity.py +++ b/backend/test_save_fidelity.py @@ -386,5 +386,131 @@ check("boundary colliding with an existing hotcue is dropped", 60.0 not in [s["s # No free slots => nothing placed. check("no free slots => empty result", ah.select_hotcues(raw, bpm=BPM, anchor=ANCHOR, duration=DUR, free_slots=[], existing_times=[], max_cues=8) == []) +# ---- Invariant H: path write-back is localized + round-trips ----------- +print("== H. remap_locations rewrites LOCATIONs (+ playlist keys), localized, round-trips ==") +from collections import Counter # noqa: E402 + +from konduktor.file_tags import resolve_path # noqa: E402 +from konduktor.path_mapping import PathMapping, os_path_to_location # noqa: E402 +from traktor_nml_utils import TraktorCollection # noqa: E402 + + +def _key(loc): + return f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}" + + +def _entry_span_by_file(data: bytes, file_name: str): + marker = f'FILE="{file_name}"'.encode() + i = data.find(marker) + start = data.rfind(b"", i) + len(b"") + return start, end + + +# H1: a track NOT in any playlist -> only its own changes; revert round-trips. +with tempfile.TemporaryDirectory() as d: + work = Path(d) / "collection.nml" + shutil.copy2(REAL, work) + original = work.read_bytes() + + store = PlaylistStore(work) + pl_keys = { + k + for n in store._iter_nodes(store._root()) + if n.playlist + for k in store._entry_keys_of(n.playlist) + } + file_counts = Counter( + e.location.file for e in store._nml.collection.entry if e.location and e.location.file + ) + target = next( + e + for e in store._nml.collection.entry + if e.location + and _key(e.location) not in pl_keys + and file_counts[e.location.file] == 1 # unique filename → clean span masking + ) + loc = target.location + old_file = loc.file + 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)) + store.save() + edited = work.read_bytes() + + check("H1: exactly one track rewritten", n == 1, f"got {n}") + check("H1: file actually changed", original != edited) + + os_, oe = _entry_span_by_file(original, old_file) + es_, ee = _entry_span_by_file(edited, "remapped__unique__one.mp3") + check( + "H1: everything outside the moved ENTRY is byte-identical", + original[:os_] + b"@@" + original[oe:] == edited[:es_] + b"@@" + edited[ee:], + ) + + reparsed = TraktorCollection(path=work) + moved = next( + e + for e in reparsed.nml.collection.entry + if e.location and e.location.file == "remapped__unique__one.mp3" + ) + check("H1: moved ENTRY has the new VOLUME", moved.location.volume == "KONDUKTOR_TEST_H1") + + # Reverting (to -> from) round-trips to the original bytes exactly. + store2 = PlaylistStore(work) + store2.remap_locations(PathMapping.make(to_prefix, from_prefix)) + store2.save() + check("H1: revert round-trips to original bytes", work.read_bytes() == original) + +# H2: a track that IS in a playlist -> its PRIMARYKEY is rewritten too. +with tempfile.TemporaryDirectory() as d: + work = Path(d) / "collection.nml" + shutil.copy2(REAL, work) + + store = PlaylistStore(work) + # A collection entry whose key appears in at least one playlist. + pl_keys = { + k + for node in store._iter_nodes(store._root()) + if node.playlist + for k in store._entry_keys_of(node.playlist) + } + target = next( + e for e in store._nml.collection.entry if e.location and _key(e.location) in pl_keys + ) + loc = target.location + old_key = _key(loc) + from_prefix = str(resolve_path(loc.volume, loc.dir, loc.file)) + 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)) + store.save() + + check("H2: at least one track rewritten", n >= 1) + + reparsed = TraktorCollection(path=work) + moved = next( + ( + e + for e in reparsed.nml.collection.entry + if e.location and e.location.file == "remapped__playlist__one.mp3" + ), + None, + ) + check("H2: collection ENTRY location rewritten", moved is not None) + + store3 = PlaylistStore(work) + all_pl_keys = { + k + for node in store3._iter_nodes(store3._root()) + if node.playlist + for k in store3._entry_keys_of(node.playlist) + } + check("H2: old playlist PRIMARYKEY gone", old_key not in all_pl_keys) + check("H2: new playlist PRIMARYKEY present", new_key in all_pl_keys) + + print("\nRESULT:", "FAILED" if failed else "ALL PASSED") sys.exit(1 if failed else 0) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 41bbb7c..66729f1 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -15,6 +15,7 @@ import { Toast, type ToastMsg } from './components/Toast' import { CollectionPicker } from './components/CollectionPicker' import { ContextMenu } from './components/ContextMenu' import { EditTagsDialog } from './components/EditTagsDialog' +import { PathMappingDialog } from './components/PathMappingDialog' import { PrepStrip } from './components/PrepStrip' function applyFilters(tracks: Track[], f: Filters): Track[] { @@ -47,6 +48,7 @@ export default function App() { const [forcePicker, setForcePicker] = useState(false) const [menu, setMenu] = useState<{ track: Track; x: number; y: number } | null>(null) const [editing, setEditing] = useState(null) + const [showPaths, setShowPaths] = useState(false) const [prepTrack, setPrepTrack] = useState(null) const [playRequest, setPlayRequest] = useState(0) // bump → deck loads & auto-plays @@ -258,6 +260,13 @@ export default function App() { onError={onError} /> )} + {showPaths && ( + setShowPaths(false)} + onNotify={notify} + onError={onError} + /> + )} {/* Prep strip spans the top of the window; the library sits below it. */} @@ -273,6 +282,7 @@ export default function App() { columnVisibility={columnVisibility} onColumnVisibilityChange={setColumnVisibility} onResetColumns={resetColumns} + onOpenPathMapping={() => setShowPaths(true)} /> {!isAll && (
diff --git a/frontend/src/api.ts b/frontend/src/api.ts index bea43de..99282ac 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -158,6 +158,34 @@ export interface SaveResult { playlists: number } +export interface PathMapping { + from: string + to: string +} + +export interface RemapSample { + from: string + to: string + exists: boolean +} + +export interface RemapPreview { + total: number + matched: number + existing: number + samples: RemapSample[] +} + +export interface RemapResult { + rewritten: number + backup: string | null +} + +export interface PrefixSuggestions { + primary: string + groups: { prefix: string; count: number }[] +} + // API origin. In the packaged desktop app the frontend is served from // tauri://localhost, so it can't use relative /api paths — the Tauri shell // injects window.__KONDUKTOR_API__ (the sidecar's http://127.0.0.1:) @@ -211,6 +239,20 @@ export const api = { listDir: (path?: string) => getJSON(`/api/fs/list${path ? `?path=${encodeURIComponent(path)}` : ''}`), + // ---- path remapping (per-collection OS-path prefix translation) ---- + getPathMapping: () => getJSON('/api/collection/path-mapping'), + suggestPrefix: () => + getJSON('/api/collection/path-mapping/suggest'), + putPathMapping: (m: PathMapping) => + send('PUT', '/api/collection/path-mapping', m), + previewRemap: (from: string, to: string) => + getJSON( + `/api/collection/path-mapping/preview?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`, + ), + // Write-back: permanently rewrite matching LOCATIONs in the .nml (backup-first). + remapPaths: (from: string, to: string) => + send('POST', '/api/collection/remap-paths', { from, to }), + stats: () => getJSON('/api/stats'), facets: () => getJSON('/api/facets'), playlists: () => getJSON('/api/playlists'), diff --git a/frontend/src/components/PathMappingDialog.tsx b/frontend/src/components/PathMappingDialog.tsx new file mode 100644 index 0000000..d46f1f9 --- /dev/null +++ b/frontend/src/components/PathMappingDialog.tsx @@ -0,0 +1,311 @@ +import { useEffect, useRef, useState } from 'react' +import { useQuery, useQueryClient } from '@tanstack/react-query' +import { api, type RemapPreview } from '../api' +import type { ToastMsg } from './Toast' + +interface Props { + onClose: () => void + onNotify: (kind: ToastMsg['kind'], text: string) => void + onError: (msg: string) => void +} + +const inputCls = + 'w-full rounded-md border border-line bg-ink-850 px-2.5 py-1.5 text-sm text-text outline-none focus:border-accent placeholder:text-faint' + +/** + * Per-collection OS-path remapping editor. Lets the user translate the stored + * audio-file path prefix to a locally-reachable one (portable USB / relocated + * library). Saving the mapping is non-destructive — the .nml is never touched; + * only how Konduktor resolves files for playback/analysis/tags changes. + */ +export function PathMappingDialog({ onClose, onNotify, onError }: Props) { + const qc = useQueryClient() + const saved = useQuery({ queryKey: ['pathMapping'], queryFn: api.getPathMapping }) + const suggest = useQuery({ queryKey: ['prefixSuggest'], queryFn: api.suggestPrefix }) + + const [from, setFrom] = useState('') + const [to, setTo] = useState('') + const hydrated = useRef(false) + const [preview, setPreview] = useState(null) + const [saving, setSaving] = useState(false) + const [browsing, setBrowsing] = useState(false) + const [confirming, setConfirming] = useState(false) + const [committing, setCommitting] = useState(false) + + // Hydrate once: prefer the saved mapping; otherwise prefill `from` with the + // auto-detected prefix. Defer until the suggestion resolves when we'd need it. + useEffect(() => { + if (hydrated.current || !saved.data) return + if (!saved.data.from && suggest.isLoading) return + hydrated.current = true + setTo(saved.data.to) + setFrom(saved.data.from || suggest.data?.primary || '') + }, [saved.data, suggest.isLoading, suggest.data]) + + // Live validation preview (debounced) — how many tracks match / exist. + useEffect(() => { + if (!from.trim() || !to.trim()) { + setPreview(null) + return + } + const t = window.setTimeout(() => { + api + .previewRemap(from.trim(), to.trim()) + .then(setPreview) + .catch(() => setPreview(null)) + }, 350) + return () => window.clearTimeout(t) + }, [from, to]) + + const saveMapping = async () => { + setSaving(true) + try { + await api.putPathMapping({ from: from.trim(), to: to.trim() }) + // Re-resolve everything that depends on the file path. + qc.invalidateQueries({ queryKey: ['pathMapping'] }) + qc.invalidateQueries({ queryKey: ['tracks'] }) + const cleared = !from.trim() || !to.trim() + onNotify('success', cleared ? 'Path mapping cleared.' : 'Path mapping saved.') + onClose() + } catch (e) { + onError(e instanceof Error ? e.message : 'Failed to save mapping') + } finally { + setSaving(false) + } + } + + const commit = async () => { + setCommitting(true) + try { + const res = await api.remapPaths(from.trim(), to.trim()) + // Locations changed, so track ids changed — refetch library + state. + qc.invalidateQueries({ queryKey: ['tracks'] }) + qc.invalidateQueries({ queryKey: ['state'] }) + if (res.rewritten === 0) { + onNotify('warning', 'No tracks matched — nothing was rewritten.') + } else { + onNotify( + 'success', + `Rewrote ${res.rewritten} track path${res.rewritten === 1 ? '' : 's'}.` + + (res.backup ? ` Backup: ${res.backup.split('/').pop()}` : ''), + ) + onClose() + } + } catch (e) { + onError(e instanceof Error ? e.message : 'Failed to rewrite paths') + } finally { + setCommitting(false) + setConfirming(false) + } + } + + const canCommit = !!from.trim() && !!to.trim() + + return ( +
+
e.stopPropagation()} + > +
+
Path Remapping
+
+ Translate the collection's stored file paths to where they live on this machine. +
+
+ +
+
+ + setFrom(e.target.value)} + placeholder="/Volumes/OLD_USB/Music" + className={inputCls} + /> +
+ The path prefix as saved in the collection (may not exist on this machine). +
+ {suggest.data && suggest.data.groups.length > 0 && ( +
+ Detected: + {suggest.data.groups + .filter((g) => g.prefix && g.prefix !== from) + .map((g) => ( + + ))} +
+ )} +
+ +
+ +
+ setTo(e.target.value)} + placeholder="/Users/you/Music" + className={inputCls} + /> + +
+ {browsing && ( + { + setTo(path) + setBrowsing(false) + }} + /> + )} +
+ + {/* Validation preview */} + {preview && ( +
+ {preview.matched === 0 ? ( + + No tracks match “{from.trim()}”. Check the stored prefix. + + ) : ( + + {preview.matched} of {preview.total} tracks match; {preview.existing} of{' '} + {preview.matched} exist at the target. + + )} +
+ )} + + {/* Write-back: permanent, destructive move. Clearly separated. */} +
+
Make permanent
+

+ Rewrites the matching file paths directly in the collection (a backup is + written first). Use this only when you've moved the library for good — it + bakes in this machine's paths and will + break the collection on other machines/OSes. +

+ {confirming ? ( +
+ Rewrite {preview?.matched ?? 0} paths? + + +
+ ) : ( + + )} +
+
+ +
+ + +
+
+
+ ) +} + +/** A compact directory-only browser for choosing the local prefix. */ +function FolderBrowser({ + initial, + onPick, +}: { + initial?: string + onPick: (path: string) => void +}) { + const [dir, setDir] = useState(initial) + const listing = useQuery({ queryKey: ['fs', dir ?? '~'], queryFn: () => api.listDir(dir) }) + const data = listing.data + + return ( +
+
+ + + + {data?.path ?? '…'} + +
+
+ {data?.dirs.length ? ( + data.dirs.map((d) => ( + + )) + ) : ( +
No subfolders.
+ )} +
+
+ +
+
+ ) +} diff --git a/frontend/src/components/SettingsMenu.tsx b/frontend/src/components/SettingsMenu.tsx new file mode 100644 index 0000000..34f44c0 --- /dev/null +++ b/frontend/src/components/SettingsMenu.tsx @@ -0,0 +1,64 @@ +import { useEffect, useRef, useState } from 'react' + +interface Props { + onOpenPathMapping: () => void +} + +/** Overflow menu for low-frequency, collection-level settings. Currently holds + * path remapping; the natural home for future advanced settings. */ +export function SettingsMenu({ onOpenPathMapping }: Props) { + const [open, setOpen] = useState(false) + const ref = useRef(null) + + useEffect(() => { + if (!open) return + const onDoc = (e: MouseEvent) => { + if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false) + } + document.addEventListener('mousedown', onDoc) + return () => document.removeEventListener('mousedown', onDoc) + }, [open]) + + const item = + 'flex w-full flex-col items-start rounded px-2 py-1.5 text-left hover:bg-ink-800' + + return ( +
+ + {open && ( +
+ +
+ )} +
+ ) +} diff --git a/frontend/src/components/Toast.tsx b/frontend/src/components/Toast.tsx index 7aac3d3..668dd8d 100644 --- a/frontend/src/components/Toast.tsx +++ b/frontend/src/components/Toast.tsx @@ -2,14 +2,20 @@ import { useEffect } from 'react' export interface ToastMsg { id: number - kind: 'success' | 'error' + kind: 'success' | 'error' | 'warning' text: string } +const KIND_CLS: Record = { + error: 'border-pink/40 bg-ink-800 text-pink', + warning: 'border-gold/40 bg-ink-800 text-gold', + success: 'border-mint/40 bg-ink-800 text-mint', +} + export function Toast({ toast, onClose }: { toast: ToastMsg | null; onClose: () => void }) { useEffect(() => { if (!toast) return - const t = setTimeout(onClose, toast.kind === 'error' ? 6000 : 4000) + const t = setTimeout(onClose, toast.kind === 'success' ? 4000 : 6000) return () => clearTimeout(t) }, [toast, onClose]) @@ -17,11 +23,7 @@ export function Toast({ toast, onClose }: { toast: ToastMsg | null; onClose: () return (
{toast.text}
diff --git a/frontend/src/components/Toolbar.tsx b/frontend/src/components/Toolbar.tsx index 3e5009e..c138c63 100644 --- a/frontend/src/components/Toolbar.tsx +++ b/frontend/src/components/Toolbar.tsx @@ -2,6 +2,7 @@ import { useQuery } from '@tanstack/react-query' import type { VisibilityState } from '@tanstack/react-table' import { api } from '../api' import { ColumnsMenu } from './ColumnsMenu' +import { SettingsMenu } from './SettingsMenu' export interface Filters { search: string @@ -29,6 +30,7 @@ interface Props { columnVisibility: VisibilityState onColumnVisibilityChange: (v: VisibilityState) => void onResetColumns: () => void + onOpenPathMapping: () => void } const selectCls = @@ -40,6 +42,7 @@ export function Toolbar({ columnVisibility, onColumnVisibilityChange, onResetColumns, + onOpenPathMapping, }: Props) { const { data: facets } = useQuery({ queryKey: ['facets'], queryFn: api.facets }) const set = (patch: Partial) => onChange({ ...filters, ...patch }) @@ -145,6 +148,7 @@ export function Toolbar({ onChange={onColumnVisibilityChange} onReset={onResetColumns} /> +
)