Implemented automatic path remapping

This commit is contained in:
patben8 committed 2026-09-27 13:39:17 +02:00
1 parent eccd352ae5
commit 99d590a051
17 files changed
+1023 -8

No files matched your search

+34
View File
@@ -47,6 +47,19 @@ Two independent apps that talk over HTTP:
- `registry.py` — adapter selection by **`can_open()` probe**, not extension
(Rekordbox is a `.db`, Serato is a directory).
- `audio_tags.py`, `pathmap.py` — format-agnostic helpers.
- `relocate.py` — **auto path remapping's search** (see `relocation.py`).
Fixes ONE thing: a stored prefix changed and the layout under it did not
(a collection built on Windows with the SSD as `X:`, opened on a Mac where
it is `/Volumes/MiniSSD` — the real case, 8,359 of 8,365 found). It
SAMPLES ~50 tracks per group against each candidate root (drives, home,
Music), dropping leading folders at the shallowest level that hits, and
verifies the winner over the WHOLE group — it never walks a drive. At
least one folder must survive the drop (a bare filename at a drive root
is a coincidence), and a runner-up resolving ≥50% of the winner's count
makes the group **ambiguous** — a drive and its backup clone are a
question, not a ranking. Which groups to search is the adapter's call
(`unresolved_path_groups()`): only volumes in which **NO** track resolves,
so a few deleted files never prompt.
- `structure.py` + `auto_hotcues.py` — **Auto Hotcues** (the deck's ✨ Auto
button → `AutoCueDialog` → `POST /api/tracks/cue/auto`). The user binds each
slot to an EVENT (`first_beat`, `intro_end`, `build_n`, `drop_n`,
@@ -283,6 +296,20 @@ Two independent apps that talk over HTTP:
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.
- `relocation.py` — the **open-time missing-files check**. `AppState.open()`
starts a `RelocationCheck` thread (after the saved mapping is applied, so
a volume it fixes is not asked about); `GET /api/library/relocation`
serves the proposals until `POST` answers them (no mappings = Not now),
then serves nothing — "ask once per open" lives here, not in the UI,
which would re-ask on every refetch. Answers are **session-only**
(`set_session_mappings`, applied in `TraktorStore._resolve` BENEATH the
saved mapping and only for a file not found as stored): never written to
the library, which would change every Traktor track id, nor to prefs, so
a reopen asks again. Only a mapping the search proposed is accepted.
**Traktor only for now**; Rekordbox/OneLibrary return no groups.
`RelocateDialog` always asks — found volumes ticked, ambiguous ones a
radio with nothing preselected, missing ones "Not connected" with a
"Map by hand…" link to `PathMappingDialog`; no backdrop-click dismiss.
- `prefs.py` — persisted user prefs (`userprefs.json` in the per-OS app-data
dir). Last-opened collection (global AND per-platform), library column
layout, prep-deck zoom, import destination. Best-effort.
@@ -651,6 +678,13 @@ serialization path.** It enforces:
multi-tempo grid survives expansion to per-beat and collapse back. Both are read
back with Konduktor's own adapters, which is the strongest check short of the
hardware: the reader was written against real rekordbox output.
- `test_relocate.py` — auto path remapping: `relocate.search` on temp folders
(drive-letter change, clone = ambiguous, partial copy loses, bare filename is
no match, dropped home folders), then the Traktor path through the routes on
a collection re-homed to `X:`/`E:`: a resolving volume is never asked about,
nothing applies before the answer and only a proposed mapping does, the
collection and prefs are untouched, a reopen asks again, and a saved manual
mapping's volume is left out.
- `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
@@ -211,6 +211,13 @@ class OneLibraryAdapter:
"""
return None
def unresolved_path_groups(self) -> list:
"""None, ever: a drive's paths are relative to its own mount point."""
return []
def set_session_mappings(self, mappings: list[PathMapping]) -> None:
return None
def path_prefix_suggestions(self) -> dict:
paths = self._store.all_audio_paths()
primary = common_dir_prefix(paths)
@@ -200,6 +200,14 @@ class RekordboxAdapter:
def set_path_mapping(self, mapping: PathMapping) -> None:
self._store.set_path_mapping(mapping)
def unresolved_path_groups(self) -> list:
"""Not checked yet: the open-time missing-files check is Traktor-only
for now. Rekordbox's `FolderPath` is absolute too, so it will qualify."""
return []
def set_session_mappings(self, mappings: list[PathMapping]) -> None:
return None
def path_prefix_suggestions(self) -> dict:
paths = self._store.all_audio_paths()
primary = common_dir_prefix(paths)
@@ -20,6 +20,7 @@ from ...core.capabilities import Capabilities
from ...core.model import PlaylistNode, Track, TrackCues
from ...core.pathmap import PathMapping
from ...core.query import TrackIndex
from ...core.relocate import PathGroup
from . import capabilities as caps
from . import projection
from .cue_types import CUE_TYPE_TO_NATIVE
@@ -363,6 +364,12 @@ class TraktorAdapter:
def set_path_mapping(self, mapping: PathMapping) -> None:
self._store.set_path_mapping(mapping)
def set_session_mappings(self, mappings: list[PathMapping]) -> None:
self._store.set_session_mappings(mappings)
def unresolved_path_groups(self) -> list[PathGroup]:
return self._store.unresolved_path_groups()
def path_prefix_suggestions(self) -> dict:
return self._store.path_prefix_suggestions()
+49 -7
View File
@@ -47,6 +47,7 @@ from ...core.adapter import InvalidCommand, SaveOutcome
from ...core.edit_journal import EditJournal
from ...core.pathmap import common_dir_prefix
from ...core.pathmap import PathMapping
from ...core.relocate import PathGroup
from ...schemas import PlaylistNode
from . import beatgrid
from .locations import os_path_to_location, resolve_path
@@ -81,6 +82,9 @@ class TraktorStore:
self.dirty = False
# Active OS-path prefix remapping (empty = identity). Survives _load().
self._path_mapping = PathMapping()
# Mappings the user confirmed in the open-time missing-files check.
# Session-only: never saved, re-derived on every open.
self._session_mappings: list[PathMapping] = []
self._load()
# ---- load ----------------------------------------------------------
@@ -973,23 +977,61 @@ class TraktorStore:
with self._lock:
self._path_mapping = mapping
def set_session_mappings(self, mappings: list[PathMapping]) -> None:
"""Set the mappings confirmed for this session (applied at resolve time)."""
with self._lock:
self._session_mappings = [m for m in mappings if not m.empty]
def _resolve(self, loc) -> "Path | None":
"""Resolve a LOCATION to an OS path, applying the active path mapping.
"""Resolve a LOCATION to an OS path, applying the active path mappings.
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.
The saved mapping is tried first, then — only for a file still not
found — the session's. Falls back to the un-remapped path when no
remapped target exists, so a misconfigured mapping never makes a
present file unreachable.
"""
if loc is None:
return None
base = resolve_path(loc.volume, loc.dir, loc.file)
if self._path_mapping.empty:
return base
if not self._path_mapping.empty:
remapped = self._path_mapping.apply(base)
if remapped == base:
if remapped != base and remapped.exists():
return remapped
if self._session_mappings and not base.exists():
for mapping in self._session_mappings:
remapped = mapping.apply(base)
if remapped != base and remapped.exists():
return remapped
return base
return remapped if remapped.exists() else base
def unresolved_path_groups(self) -> list[PathGroup]:
"""Each stored VOLUME in which not one track resolves, with its tracks'
stored paths — the input to the open-time missing-files search.
"Not one" is the threshold: a volume missing a few deleted files is a
library with a few deleted files, not a library that needs remapping.
The stats happen outside the lock; checking stops at a volume's first
present file, and a missing path fails fast, so this is cheap either way.
"""
with self._lock:
by_volume: dict[str, list] = {}
for e in self._nml.collection.entry:
if e.location is not None and e.location.file:
by_volume.setdefault(e.location.volume or "", []).append(e.location)
groups = []
for volume, locs in by_volume.items():
if any(self._resolve(loc).exists() for loc in locs):
continue
groups.append(
PathGroup(
label=volume,
root=str(resolve_path(volume, "/:", "")),
paths=[str(resolve_path(l.volume, l.dir, l.file)) for l in locs],
)
)
return groups
def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
"""Staged replacement if present, else the file's current embedded art."""
+7
View File
@@ -31,6 +31,7 @@ from . import __version__, adapters, history, library_id, prefs # noqa: F401
from .core import registry
from .core.adapter import LibraryAdapter
from .core.pathmap import PathMapping
from .relocation import RelocationCheck
class AppState:
@@ -47,6 +48,9 @@ class AppState:
# module docstring for why it is not symmetrical with `adapter`.
self.source_path: Path | None = None
self.source: LibraryAdapter | None = None
# This open's missing-files check (see `relocation.py`). A new one per
# open, which is what makes the dialog ask again on a reopen.
self.relocation: RelocationCheck | None = None
@property
def loaded(self) -> bool:
@@ -114,6 +118,9 @@ class AppState:
if saved:
adapter.set_path_mapping(PathMapping.make(saved["from"], saved["to"]))
self.path, self.adapter = path, adapter
# Started after the saved mapping is applied, so a volume that mapping
# already fixes is not asked about.
self.relocation = RelocationCheck(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
+7
View File
@@ -25,6 +25,7 @@ from typing import Protocol, runtime_checkable
from .capabilities import Capabilities
from .model import Facets, PlaylistNode, Stats, Track, TrackCues, TrackPage
from .pathmap import PathMapping
from .relocate import PathGroup
@dataclass
@@ -176,6 +177,12 @@ class LibraryAdapter(Protocol):
# ---- audio / paths ---------------------------------------------------
def audio_path(self, track_id: str) -> Path | None: ...
def set_path_mapping(self, mapping: PathMapping) -> None: ...
# The open-time missing-files check (`core/relocate.py`): the stored volumes
# in which NO track resolves, and the mappings the user confirmed for them —
# session-only, applied beneath the saved mapping. An adapter that does not
# take part returns no groups, so its library is never checked.
def unresolved_path_groups(self) -> list[PathGroup]: ...
def set_session_mappings(self, mappings: list[PathMapping]) -> None: ...
def path_prefix_suggestions(self) -> dict: ...
def remap_preview(self, mapping: PathMapping) -> dict: ...
# {old track id: new track id}; ids may change because a Traktor id IS its path.
+40
View File
@@ -238,3 +238,43 @@ class PrefixGroup(BaseModel):
class PrefixSuggestions(BaseModel):
primary: str # best guess for the `from` prefix (largest group)
groups: list[PrefixGroup] = [] # alternatives, ranked by count
class RelocationCandidate(BaseModel):
"""One place a volume's tracks were found, as a mapping the user can pick."""
model_config = ConfigDict(populate_by_name=True)
from_: str = Field(alias="from")
to: str
found: int # of the volume's tracks, how many exist under this mapping
class RelocationVolume(BaseModel):
"""A stored volume in which NO track resolves, and where its tracks are now.
`ambiguous` means more than one candidate resolves most of the volume (a
drive and its backup clone): the user chooses, nothing is preselected.
"""
label: str # how the library names the place, e.g. Traktor's "X:"
root: str # the stored OS-path prefix
total: int
status: Literal["found", "ambiguous", "not_found"]
candidates: list[RelocationCandidate] = []
class Relocation(BaseModel):
"""The open-time missing-files check, pending until the user answers it.
`scanning` while the search is still running; afterwards `volumes` is empty
when there is nothing to ask — every volume resolves, the platform does not
take part, or the user has already answered for this open.
"""
scanning: bool = False
volumes: list[RelocationVolume] = []
class RelocationApplied(BaseModel):
mappings: int
tracks: int # how many tracks the applied mappings resolve
+187
View File
@@ -0,0 +1,187 @@
"""Finding where a library's audio went: the search behind auto path remapping.
A library stores absolute paths, and they go stale in ways a DJ does not think
of as "moving" anything: the collection on an SSD was built on Windows where the
drive was `X:`, and on a Mac the same drive is `/Volumes/MiniSSD`. Every track
then reads as missing, though nothing moved. That is what this module fixes,
and ALL it fixes — a prefix changed, the layout underneath did not. A user who
reorganised their folders needs a relocate-by-filename feature, which this is
not.
The search is by SAMPLING, never by walking a drive: a drive can hold hundreds
of thousands of files, and a stat of a path that is not there costs next to
nothing. For each group of tracks that share a stored root, a sample of tracks
is tried against each candidate root (the mounted drives, the home folder),
dropping leading folders one at a time, and the roots that resolve them are
counted. The winner is then verified against the WHOLE group, because a count
the user is asked to confirm should be the real one.
Which groups to search is the adapter's business, not this module's: only the
adapter knows how its stored paths resolve, including through a mapping the
user already saved. It hands over the groups in which NO track resolves — the
threshold is "none", so a volume missing a few deleted files never prompts.
Two candidates that both resolve most of a group (a drive and its backup clone)
are reported as AMBIGUOUS rather than ranked: which one the user meant is not a
question sample counts can answer, and a wrong guess would silently play and
tag files on the wrong drive.
"""
from __future__ import annotations
import re
from dataclasses import dataclass, field
from pathlib import Path
from .pathmap import PathMapping
#: Tracks sampled per group. Enough that a drive holding a partial copy loses
#: clearly to one holding all of it; few enough that a group costs milliseconds.
SAMPLE = 50
#: How many leading folders may be dropped from a stored path. Covers
#: `/Users/<name>/Music/<library>`-deep moves with room to spare.
MAX_DROP = 8
#: A runner-up resolving at least this share of the winner's tracks makes the
#: group ambiguous.
AMBIGUOUS_SHARE = 0.5
_SEP = re.compile(r"[\\/]")
@dataclass
class PathGroup:
"""Tracks whose stored paths share a root the library names as one place.
`root` is the OS-path prefix every path starts with (`X:`, `/Volumes/SSD`,
`/`); `label` is how the library itself names that place, for the UI.
`paths` are the STORED paths — before any mapping.
"""
label: str
root: str
paths: list[str]
@dataclass
class Candidate:
"""A mapping that resolves some of a group, with how many it resolves."""
mapping: PathMapping
found: int
@dataclass
class Proposal:
"""What the search concluded about one group."""
label: str
root: str
total: int
#: Best first. Empty when nothing was found.
candidates: list[Candidate] = field(default_factory=list)
@property
def status(self) -> str:
if not self.candidates:
return "not_found"
if len(self.candidates) > 1:
return "ambiguous"
return "found"
def _split(path: str, root: str) -> tuple[list[str], str] | None:
"""A stored path's folders below `root`, and its filename."""
if not path.startswith(root):
return None
segs = [s for s in _SEP.split(path[len(root):]) if s]
if not segs:
return None
return segs[:-1], segs[-1]
def _from_prefix(root: str, path: str, dropped: list[str]) -> str:
"""The stored prefix a mapping must replace: `root` plus the dropped folders,
spelled with the separator the stored path uses, so it matches it."""
if not dropped:
return root
rest = path[len(root):]
sep = "\\" if "\\" in rest and "/" not in rest else "/"
return root.rstrip("/\\") + sep + sep.join(dropped)
def _sample(paths: list[str], n: int) -> list[str]:
"""`n` paths spread evenly over the group, so one album is not the sample."""
if len(paths) <= n:
return list(paths)
step = len(paths) / n
return [paths[int(i * step)] for i in range(n)]
def _hits(path: str, root: str, roots: list[Path]) -> set[tuple[str, str]]:
"""Every (from, to) mapping that resolves this one stored path, at the
SHALLOWEST drop that resolves it at all — dropping more folders only makes a
match likelier to be a coincidence."""
split = _split(path, root)
if split is None:
return set()
dirs, name = split
# A bare filesystem root cannot be a mapping's `from` (it would match every
# path), so a group rooted at `/` starts by dropping one folder. And at
# least one folder must survive the drop: a filename alone at a drive's
# root is far too weak to call a match.
first = 1 if not root.strip("/\\") else 0
last = min(MAX_DROP, max(len(dirs) - 1, 0))
for drop in range(first, last + 1):
found = set()
for base in roots:
try:
if base.joinpath(*dirs[drop:], name).exists():
found.add((_from_prefix(root, path, dirs[:drop]), str(base)))
except OSError:
continue
if found:
return found
return set()
def _resolves(mapping: PathMapping, paths: list[str]) -> int:
n = 0
for p in paths:
target = mapping.apply(Path(p))
try:
if str(target) != p and target.exists():
n += 1
except OSError:
continue
return n
def search(groups: list[PathGroup], roots: list[Path]) -> list[Proposal]:
"""Where each group's tracks are now, if anywhere among `roots`."""
roots = list(dict.fromkeys(Path(r) for r in roots))
out: list[Proposal] = []
for group in groups:
sample = _sample(group.paths, SAMPLE)
votes: dict[tuple[str, str], int] = {}
for p in sample:
for hit in _hits(p, group.root, roots):
votes[hit] = votes.get(hit, 0) + 1
# One sampled track is a coincidence (a common filename in a common
# folder name); a group too small to sample three is taken on one.
floor = min(3, len(sample))
ranked = sorted(
(h for h, n in votes.items() if n >= floor), key=lambda h: -votes[h]
)[:3]
candidates = []
for from_, to in ranked:
mapping = PathMapping.make(from_, to)
found = _resolves(mapping, group.paths)
if found:
candidates.append(Candidate(mapping, found))
candidates.sort(key=lambda c: -c.found)
if candidates:
best = candidates[0].found
candidates = [c for c in candidates if c.found >= best * AMBIGUOUS_SHARE]
out.append(Proposal(group.label, group.root, len(group.paths), candidates))
return out
+56
View File
@@ -33,6 +33,11 @@ from .core.capabilities import Capabilities
from .jobs import JOBS
from .core.pathmap import PathMapping
from .schemas import (
Relocation,
RelocationApplied,
RelocationApply,
RelocationCandidate,
RelocationVolume,
AutoGridBatchRequest,
AutoGridRequest,
AutoCueOutcome,
@@ -265,6 +270,57 @@ def remap_paths(body: PathMappingInfo) -> RemapResult:
return RemapResult(rewritten=len(moved), commit=commit)
@app.get("/api/library/relocation", response_model=Relocation)
def get_relocation() -> Relocation:
"""The open-time missing-files check: every stored volume in which NO track
resolves, and where the search found its tracks. Empty once answered, so the
UI can refetch freely without re-asking.
Waits briefly for the search, then reports `scanning` so a slow drive
cannot hold a request open; the UI polls until it is done.
"""
require_adapter()
check = STATE.relocation
if check is None:
return Relocation()
if not check.wait(timeout=10):
return Relocation(scanning=True)
return Relocation(
volumes=[
RelocationVolume(
label=p.label,
root=p.root,
total=p.total,
status=p.status,
candidates=[
RelocationCandidate.model_validate(
{"from": c.mapping.from_prefix, "to": c.mapping.to_prefix, "found": c.found}
)
for c in p.candidates
],
)
for p in check.pending
]
)
@app.post("/api/library/relocation", response_model=RelocationApplied)
def answer_relocation(body: RelocationApply) -> RelocationApplied:
"""Answer the check: apply the chosen mappings for THIS SESSION only (no
mappings = "Not now"). Nothing is written to the library or to prefs, and a
reopen asks again."""
require_adapter()
check = STATE.relocation
if check is None:
raise HTTPException(409, "There is no missing-files check to answer")
mappings = [PathMapping.make(m.from_, m.to) for m in body.mappings]
try:
tracks = check.answer(mappings)
except ValueError as ex:
raise HTTPException(400, str(ex))
return RelocationApplied(mappings=len(mappings), tracks=tracks)
@app.get("/api/prefs")
def get_prefs() -> dict:
"""The full persisted user-preferences blob (UI layout, last collection…)."""
+103
View File
@@ -0,0 +1,103 @@
"""The open-time missing-files check: search on open, ask once, apply for the session.
When a library opens, a thread asks the adapter which stored volumes resolve
nothing and searches for where their tracks went (`core/relocate.py`). The
result waits here until the user answers the confirmation dialog — Apply or
Not now — and is then settled for the rest of this open. Reopening the library
creates a new adapter and so a new check, which is how "ask again when the
library is reopened" holds without anything being remembered.
It lives on `AppState` rather than in the UI because "once per open" is a fact
about the open, which happens here: a UI deciding it would re-ask on every
refetch of the query that shows the dialog.
The mappings it applies are session-only by design. They are never written to
the library (that would change every Traktor track id) nor to prefs; the saved
mapping in the Path Remapping dialog is the way to make one stick.
"""
from __future__ import annotations
import logging
import threading
from pathlib import Path
from .core import places
from .core.pathmap import PathMapping
from .core.relocate import Proposal, search
log = logging.getLogger(__name__)
def candidate_roots() -> list[Path]:
"""Where a library's missing audio might now be: every drive, plus the
user's home and Music folders (a library copied into ~/Music keeps its own
layout beneath it)."""
roots = [Path(d["path"]) for d in places.drives()]
roots += [Path(p["path"]) for p in places.user_places() if p["kind"] in ("home", "music")]
return roots
class RelocationCheck:
"""One library open's check. Starts searching as soon as it is made."""
def __init__(self, adapter) -> None:
self.adapter = adapter
self._done = threading.Event()
self._proposals: list[Proposal] = []
self._answered = False
self._lock = threading.Lock()
threading.Thread(target=self._run, name="relocation-check", daemon=True).start()
def _run(self) -> None:
try:
groups = self.adapter.unresolved_path_groups()
if groups:
self._proposals = search(groups, candidate_roots())
except Exception: # noqa: BLE001 — a failed check must never break an open
log.exception("missing-files check failed")
finally:
self._done.set()
def wait(self, timeout: float) -> bool:
"""Whether the search has finished, waiting up to `timeout` seconds."""
return self._done.wait(timeout)
@property
def pending(self) -> list[Proposal]:
"""What still needs the user's answer: nothing once answered."""
if not self._done.is_set() or self._answered:
return []
return self._proposals
def answer(self, mappings: list[PathMapping]) -> int:
"""Apply the user's choice (empty = Not now) and settle the check.
Returns how many tracks the applied mappings resolve. Refuses a mapping
the search did not propose, and two for one volume.
"""
with self._lock:
if not self._done.is_set():
raise ValueError("The missing-files check is still running")
if self._answered:
raise ValueError("The missing-files check has already been answered")
chosen = []
volumes: set[str] = set()
for m in mappings:
match = next(
(
(p, c)
for p in self._proposals
for c in p.candidates
if c.mapping == m
),
None,
)
if match is None:
raise ValueError(f"Not a proposed mapping: {m.from_prefix} → {m.to_prefix}")
if match[0].root in volumes:
raise ValueError(f"Two mappings chosen for {match[0].label}")
volumes.add(match[0].root)
chosen.append(match[1])
self.adapter.set_session_mappings([c.mapping for c in chosen])
self._answered = True
return sum(c.found for c in chosen)
+14
View File
@@ -299,6 +299,16 @@ class PathMappingInfo(BaseModel):
to: str = ""
class RelocationApply(BaseModel):
"""The user's answer to the open-time missing-files check. Empty = "Not now".
Each mapping must be one the check proposed: this route applies an answer,
it is not a second way to set an arbitrary mapping.
"""
mappings: list[PathMappingInfo] = []
class RemapResult(BaseModel):
rewritten: int # tracks whose LOCATION was rewritten
commit: str | None = None # sha of the version-history commit for the rewrite
@@ -318,6 +328,10 @@ from .core.model import ( # noqa: E402,F401
PlaylistNode,
PrefixGroup,
PrefixSuggestions,
Relocation,
RelocationApplied,
RelocationCandidate,
RelocationVolume,
RemapPreview,
RemapSample,
Stats,
+1 -1
View File
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
source .venv/bin/activate
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_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_library_id.py test_exports.py test_export.py test_export_pioneer.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_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_phase3.py test_history.py; do
echo "──────────────────────────────────────────"
echo "▶ $t"
echo "──────────────────────────────────────────"
+207
View File
@@ -0,0 +1,207 @@
"""Auto path remapping: the open-time missing-files check.
Two layers. `core.relocate.search` on temp folders, where where-the-files-are is
known; then the Traktor path end to end through the routes, on a collection
built here whose stored volume is a Windows drive letter — the real case that
motivated this (a collection made on Windows with the SSD as `X:`, opened on a
Mac where it is `/Volumes/<name>`).
Pins the things that would fail SILENTLY:
* a drive and its clone are AMBIGUOUS, never ranked — a wrong guess would play
and tag files on the wrong drive;
* a filename alone at a drive's root is not a match;
* a volume in which even ONE track resolves is never asked about;
* nothing is applied before the user answers, and only a proposed mapping is;
* the answer is session-only: the collection and prefs are untouched, and a
reopen asks again;
* a saved manual mapping is respected — its volume is not asked about.
"""
from __future__ import annotations
import os
import re
import shutil
import tempfile
from pathlib import Path
_DATA = tempfile.TemporaryDirectory()
os.environ["KONDUKTOR_DATA_DIR"] = _DATA.name
os.environ.pop("KONDUKTOR_NML", None)
from konduktor.core.pathmap import PathMapping # noqa: E402
from konduktor.core.relocate import PathGroup, search # 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 touch(path: Path) -> Path:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(b"")
return path
tmp = Path(tempfile.mkdtemp())
ssd = tmp / "SSD"
rel = [f"Music Library/{g}/t{i}.mp3" for g in ("EDM", "House", "DnB") for i in range(20)]
for r in rel:
touch(ssd / r)
(ssd / rel[7]).unlink() # one track genuinely deleted
stored = [f"X:/{r}" for r in rel]
x = PathGroup(label="X:", root="X:", paths=stored)
print("== a changed drive letter is found ==")
[p] = search([x], [ssd, tmp / "Nowhere"])
check("found, with one candidate", p.status == "found", p.status)
c = p.candidates[0]
check("maps the drive letter onto the drive", c.mapping == PathMapping.make("X:", str(ssd)), str(c.mapping))
check("the count is verified over the WHOLE group", c.found == 59 and p.total == 60, f"{c.found}/{p.total}")
print("== a drive and its clone are ambiguous ==")
clone = tmp / "Clone"
shutil.copytree(ssd, clone)
[p] = search([x], [ssd, clone])
check("ambiguous, both offered", p.status == "ambiguous" and len(p.candidates) == 2, p.status)
check("both targets named", {c.mapping.to_prefix for c in p.candidates} == {str(ssd), str(clone)})
print("== a partial copy loses to the whole one ==")
partial = tmp / "Partial"
for r in rel[:8]:
touch(partial / r)
[p] = search([x], [ssd, partial])
check("found on the full drive only",
p.status == "found" and p.candidates[0].mapping.to_prefix == str(ssd), p.status)
print("== nothing found ==")
[p] = search([PathGroup("E:", "E:", ["E:/Gone/a.mp3", "E:/Gone/b.mp3"])], [ssd])
check("not found, no candidates", p.status == "not_found" and not p.candidates)
print("== a filename alone at a drive's root is not a match ==")
bare = tmp / "Bare"
for i in range(5):
touch(bare / f"solo{i}.mp3")
[p] = search([PathGroup("X:", "X:", [f"X:/Deep/Folder/solo{i}.mp3" for i in range(5)])], [bare])
check("not found", p.status == "not_found", p.status)
print("== leading folders are dropped: another user's home ==")
home = tmp / "home"
for i in range(5):
touch(home / "Music" / "Lib" / f"x{i}.mp3")
[p] = search([PathGroup("Macintosh HD", "/", [f"/Users/alice/Music/Lib/x{i}.mp3" for i in range(5)])], [home])
check("found", p.status == "found", p.status)
check("maps the old home onto the new one",
p.status == "found" and p.candidates[0].mapping == PathMapping.make("/Users/alice", str(home)),
str(p.candidates[0].mapping) if p.candidates else "")
print("== a one-track group is taken on one ==")
[p] = search([PathGroup("X:", "X:", [stored[0]])], [ssd])
check("found", p.status == "found" and p.candidates[0].found == 1, p.status)
# ---- the Traktor path, through the routes --------------------------------------
from konduktor import relocation # noqa: E402
# Search only the fake SSD: the real drives would make the answer depend on the machine.
relocation.candidate_roots = lambda: [ssd]
from konduktor.adapters.traktor.adapter import TraktorAdapter # noqa: E402
from konduktor.adapters.traktor.export import SKELETON # noqa: E402
from konduktor.adapters.traktor.locations import os_path_to_location # noqa: E402
from konduktor.core.adapter import NewTrack # noqa: E402
from konduktor.core.model import Track # noqa: E402
lib = tmp / "lib" / "collection.nml"
lib.parent.mkdir()
lib.write_text(SKELETON, encoding="utf-8")
on_ssd = [ssd / r for r in rel[:3]]
local = touch(tmp / "Local" / "keep.mp3") # stays where it is: its volume resolves
gone = touch(tmp / "Gone" / "lost.mp3")
a = TraktorAdapter(lib)
a.add_tracks([NewTrack(track=Track(id="", title=p.stem), audio_path=p) for p in [*on_ssd, local, gone]])
a.save()
# Re-home the stored locations as a Windows machine would have written them.
text = lib.read_text(encoding="utf-8")
ssd_dir = os_path_to_location(ssd / "x")[1] # "/:…/:SSD/:"
gone_dir = os_path_to_location(gone)[1]
text = re.sub(rf'DIR="{re.escape(ssd_dir)}([^"]*)" (FILE="[^"]*") VOLUME="[^"]*"', r'DIR="/:\1" \2 VOLUME="X:"', text)
text = re.sub(rf'DIR="{re.escape(gone_dir)}" (FILE="[^"]*") VOLUME="[^"]*"', r'DIR="/:Gone/:" \1 VOLUME="E:"', text)
lib.write_text(text, encoding="utf-8")
original = lib.read_bytes()
check("the fixture has X: and E: locations", 'VOLUME="X:"' in text and 'VOLUME="E:"' in text)
from fastapi.testclient import TestClient # noqa: E402
import konduktor.main as main # noqa: E402
from konduktor import prefs # noqa: E402
def ssd_ids():
return [t.id for t in main.require_adapter().tracks if t.id.startswith("X:")]
def plays(c, tid):
return c.get("/api/tracks/audio", params={"track_id": tid}).status_code == 200
with TestClient(main.app, raise_server_exceptions=False) as c:
check("opens", c.post("/api/library/open", json={"path": str(lib)}).status_code == 200)
print("== the check proposes, and applies nothing yet ==")
r = c.get("/api/library/relocation")
check("answers 200", r.status_code == 200, r.text[:300])
vols = {v["label"]: v for v in r.json()["volumes"]}
check("asks about X: and E: only — the volume that resolves is left alone",
set(vols) == {"X:", "E:"}, str(sorted(vols)))
xv = vols.get("X:", {})
check("X: found on the SSD, 3 of 3",
xv.get("status") == "found" and xv["candidates"][0]["to"] == str(ssd)
and xv["candidates"][0]["found"] == 3, str(xv))
check("E: not found", vols.get("E:", {}).get("status") == "not_found")
tid = ssd_ids()[0]
check("before answering, an SSD track does not play", not plays(c, tid))
print("== only a proposed mapping is accepted ==")
r = c.post("/api/library/relocation", json={"mappings": [{"from": "X:", "to": str(tmp)}]})
check("an unproposed mapping is a 400", r.status_code == 400, r.text[:200])
print("== Apply ==")
r = c.post("/api/library/relocation", json={"mappings": [{"from": "X:", "to": str(ssd)}]})
check("answers 200 with the track count", r.status_code == 200 and r.json()["tracks"] == 3, r.text[:200])
check("the SSD tracks now play", all(plays(c, t) for t in ssd_ids()))
check("the check is settled", c.get("/api/library/relocation").json()["volumes"] == [])
check("a second answer is refused",
c.post("/api/library/relocation", json={"mappings": []}).status_code == 400)
check("track ids are unchanged (nothing was rewritten)", tid in ssd_ids() and len(ssd_ids()) == 3)
check("the collection file is untouched", lib.read_bytes() == original)
check("nothing is saved to prefs", prefs.get_path_mapping(str(lib)) is None)
print("== session-only: a reopen asks again ==")
c.post("/api/library/open", json={"path": str(lib)})
vols = {v["label"] for v in c.get("/api/library/relocation").json()["volumes"]}
check("asked again", vols == {"X:", "E:"}, str(vols))
check("and the mapping is gone", not plays(c, tid))
print("== Not now ==")
r = c.post("/api/library/relocation", json={"mappings": []})
check("answers 200", r.status_code == 200, r.text[:200])
check("settled, nothing applied",
c.get("/api/library/relocation").json()["volumes"] == [] and not plays(c, tid))
print("== a saved manual mapping is respected ==")
c.put("/api/library/path-mapping", json={"from": "X:", "to": str(ssd)})
c.post("/api/library/open", json={"path": str(lib)})
vols = {v["label"] for v in c.get("/api/library/relocation").json()["volumes"]}
check("only E: is asked about", vols == {"E:"}, str(vols))
c.put("/api/library/path-mapping", json={"from": "", "to": ""})
shutil.rmtree(tmp, ignore_errors=True)
print("\nFAILED" if failed else "\nALL PASSED")
raise SystemExit(1 if failed else 0)
+29
View File
@@ -21,6 +21,7 @@ import { AnalyzeGridDialog } from './components/AnalyzeGridDialog'
import { AutoCueDialog } from './components/AutoCueDialog'
import { ConfirmDialog, type ConfirmRequest } from './components/ConfirmDialog'
import { PathMappingDialog } from './components/PathMappingDialog'
import { RelocateDialog } from './components/RelocateDialog'
import { HistoryPanel } from './components/HistoryPanel'
import { PrepStrip } from './components/PrepStrip'
import { ImportDialog } from './components/ImportDialog'
@@ -166,6 +167,16 @@ export default function App() {
staleTime: Infinity,
})
const save = capabilities.data?.save
// The open-time missing-files check. The backend searches as the library
// opens and holds the result until it is answered, then serves nothing — so
// "ask once per open" is the backend's fact, and refetching cannot re-ask.
const relocation = useQuery({
queryKey: ['relocation'],
queryFn: api.relocation,
enabled: loaded,
refetchInterval: (q) => (q.state.data?.scanning ? 1500 : false),
refetchOnWindowFocus: false,
})
// From the adapter, not a path split: a Serato library is a directory.
const libraryName = collection.data?.library?.display_name ?? null
const writeHintText = save ? writeHint(save) : 'save to write it to disk'
@@ -951,6 +962,24 @@ export default function App() {
onClose={() => setGridConfirm(null)}
/>
)}
{!!relocation.data?.volumes.length && (
<RelocateDialog
volumes={relocation.data.volumes}
onAnswered={(applied) => {
qc.setQueryData(['relocation'], { scanning: false, volumes: [] })
if (!applied) return
// Every file-backed answer can change: audio, art, the Files
// tree's "already in the collection" marks.
qc.invalidateQueries()
notify(
'success',
`Found ${applied.tracks.toLocaleString()} track${applied.tracks === 1 ? '' : 's'} — remapped for this session`,
)
}}
onOpenManual={() => setShowPaths(true)}
onError={onError}
/>
)}
{showPaths && (
<PathMappingDialog
onClose={() => setShowPaths(false)}
+38
View File
@@ -544,6 +544,38 @@ export interface RemapPreview {
samples: RemapSample[]
}
/** One place a stored volume's tracks were found — a mapping the user can pick. */
export interface RelocationCandidate {
from: string
to: string
/** Of the volume's tracks, how many exist under this mapping. */
found: number
}
/** A stored volume in which NO track resolves, and where its tracks are now.
* `ambiguous`: more than one candidate resolves most of it (a drive and its
* backup clone) — the user chooses, nothing is preselected. */
export interface RelocationVolume {
/** How the library names the place, e.g. Traktor's "X:". */
label: string
root: string
total: number
status: 'found' | 'ambiguous' | 'not_found'
candidates: RelocationCandidate[]
}
/** The open-time missing-files check. `volumes` is empty once answered, so it
* is safe to refetch. */
export interface Relocation {
scanning: boolean
volumes: RelocationVolume[]
}
export interface RelocationApplied {
mappings: number
tracks: number
}
export interface RemapResult {
rewritten: number
commit: string | null
@@ -667,6 +699,12 @@ export const api = {
remapPaths: (from: string, to: string) =>
send<RemapResult>('POST', '/api/library/remap-paths', { from, to }),
// The open-time missing-files check; answering with no mappings is "Not now".
// Applied mappings last for this session only.
relocation: () => getJSON<Relocation>('/api/library/relocation'),
answerRelocation: (mappings: PathMapping[]) =>
send<RelocationApplied>('POST', '/api/library/relocation', { mappings }),
capabilities: () => getJSON<Capabilities>('/api/capabilities'),
platforms: () => getJSON<PlatformOption[]>('/api/platforms'),
facets: () => getJSON<Facets>('/api/facets'),
+229
View File
@@ -0,0 +1,229 @@
import { createPortal } from 'react-dom'
import { useEffect, useState } from 'react'
import { api, type PathMapping, type RelocationVolume } from '../api'
interface Props {
volumes: RelocationVolume[]
/** Called once the backend has the answer (Apply or Not now). */
onAnswered: (applied: { mappings: number; tracks: number } | null) => void
/** "Not now", then the manual Path Remapping dialog. */
onOpenManual: () => void
onError: (msg: string) => void
}
const n = (v: number) => v.toLocaleString()
/**
* The open-time missing-files check: shown when a stored volume resolves NONE
* of its tracks, after the backend has searched for where they went. It always
* asks — nothing is applied until Apply — and what it applies lasts for this
* session only; the library and prefs are never touched, and a reopen asks
* again. A volume with one clear location is ticked; two likely locations (a
* drive and its backup clone) are a choice with nothing preselected, because a
* wrong guess would play and tag files on the wrong drive.
*/
export function RelocateDialog({ volumes, onAnswered, onOpenManual, onError }: Props) {
// Per volume root: the chosen candidate's `to`, or null to leave it missing.
const [choice, setChoice] = useState<Record<string, string | null>>(() =>
Object.fromEntries(
volumes.map((v) => [v.root, v.status === 'found' ? v.candidates[0].to : null]),
),
)
const [busy, setBusy] = useState(false)
const chosen: PathMapping[] = volumes.flatMap((v) => {
const to = choice[v.root]
const c = v.candidates.find((c) => c.to === to)
return c ? [{ from: c.from, to: c.to }] : []
})
const anyFound = volumes.some((v) => v.candidates.length > 0)
const anyMissing = volumes.some((v) => v.status === 'not_found')
const answer = async (mappings: PathMapping[], then?: () => void) => {
setBusy(true)
try {
const res = await api.answerRelocation(mappings)
onAnswered(mappings.length ? res : null)
then?.()
} catch (e) {
onError(e instanceof Error ? e.message : 'Failed to apply the remapping')
setBusy(false)
}
}
useEffect(() => {
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && !busy && answer([])
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
})
const set = (root: string, to: string | null) => setChoice((c) => ({ ...c, [root]: to }))
return createPortal(
// No close on a backdrop click: dismissing lasts until the library is
// reopened, which is too much for a stray click to decide.
<div
aria-modal="true"
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6"
>
<div className="flex max-h-[85vh] w-full max-w-xl flex-col overflow-hidden glass-overlay">
<div className="border-b border-line px-5 py-4">
<div className="text-[15px] font-semibold tracking-tight">Tracks not found</div>
<div className="text-xs text-muted">
None of the tracks on {volumes.length === 1 ? 'this drive are' : 'these drives are'} where
the collection says.
{anyFound ? ' Konduktor looked for them on this computer:' : ' They were not found on this computer.'}
</div>
</div>
<div className="min-h-0 flex-1 space-y-2 overflow-y-auto px-5 py-4">
{volumes.map((v) => (
<VolumeRow key={v.root} volume={v} choice={choice[v.root]} onChoose={(to) => set(v.root, to)} />
))}
<p className="pt-1 text-[11px] leading-relaxed text-faint">
Remapping applies for this session only. Nothing is written to your collection, and
you'll be asked again the next time you open it.
</p>
</div>
<div className="flex items-center gap-2 border-t border-line px-5 py-3">
{anyMissing && (
<button
onClick={() => answer([], onOpenManual)}
disabled={busy}
className="mr-auto rounded-md px-2 py-1.5 text-xs text-muted hover:bg-ink-800 hover:text-text disabled:opacity-50"
>
Map by hand…
</button>
)}
<div className="ml-auto flex items-center gap-2">
<button
onClick={() => answer([])}
disabled={busy}
className="rounded-md px-3 py-1.5 text-sm text-muted hover:bg-ink-800 hover:text-text disabled:opacity-50"
>
Not now
</button>
{anyFound && (
<button
onClick={() => answer(chosen)}
disabled={busy || chosen.length === 0}
className="rounded-full btn-primary px-4 py-1.5 text-sm font-semibold disabled:opacity-50"
>
{busy ? 'Applying…' : 'Apply'}
</button>
)}
</div>
</div>
</div>
</div>,
document.body,
)
}
function VolumeRow({
volume: v,
choice,
onChoose,
}: {
volume: RelocationVolume
choice: string | null | undefined
onChoose: (to: string | null) => void
}) {
const heading = (
<span className="min-w-0 flex-1">
<span className="block truncate text-sm text-text">
{v.label || v.root}
{v.root !== v.label && <span className="ml-1.5 text-xs text-faint">{v.root}</span>}
</span>
<span className="block text-xs text-faint">
{n(v.total)} track{v.total === 1 ? '' : 's'}
</span>
</span>
)
if (v.status === 'not_found') {
return (
<div className="flex items-start gap-3 rounded-md border border-line px-3 py-2.5">
{heading}
<span className="shrink-0 pt-0.5 text-xs text-gold">Not connected</span>
</div>
)
}
if (v.status === 'found') {
const c = v.candidates[0]
return (
<label
className={`flex cursor-pointer items-start gap-3 rounded-md border border-line px-3 py-2.5 ${
choice ? 'is-selected' : 'hover:bg-ink-850'
}`}
>
<input
type="checkbox"
checked={!!choice}
onChange={(e) => onChoose(e.target.checked ? c.to : null)}
className="mt-1 accent-accent"
/>
{heading}
<Target to={c.to} found={c.found} total={v.total} />
</label>
)
}
// Ambiguous: a choice, with nothing preselected.
return (
<div className="rounded-md border border-line px-3 py-2.5">
<div className="flex items-start gap-3">
{heading}
<span className="shrink-0 pt-0.5 text-xs text-gold">Found in {v.candidates.length} places</span>
</div>
<div className="mt-2 space-y-1">
{v.candidates.map((c) => (
<label
key={c.to}
className={`flex cursor-pointer items-center gap-3 rounded-md px-2 py-1.5 ${
choice === c.to ? 'is-selected' : 'hover:bg-ink-850'
}`}
>
<input
type="radio"
name={`relocate-${v.root}`}
checked={choice === c.to}
onChange={() => onChoose(c.to)}
className="accent-accent"
/>
<Target to={c.to} found={c.found} total={v.total} wide />
</label>
))}
<label
className={`flex cursor-pointer items-center gap-3 rounded-md px-2 py-1.5 ${
!choice ? 'is-selected' : 'hover:bg-ink-850'
}`}
>
<input
type="radio"
name={`relocate-${v.root}`}
checked={!choice}
onChange={() => onChoose(null)}
className="accent-accent"
/>
<span className="text-sm text-muted">Leave missing</span>
</label>
</div>
</div>
)
}
function Target({ to, found, total, wide }: { to: string; found: number; total: number; wide?: boolean }) {
return (
<span className={`min-w-0 text-right ${wide ? 'flex flex-1 items-baseline justify-between gap-3' : 'max-w-[55%]'}`}>
<span className="block truncate text-sm text-text" title={to}>
<span className="text-faint">→</span> {to}
</span>
<span className={`block text-xs tabular-nums ${found === total ? 'text-mint' : 'text-faint'}`}>
{n(found)} of {n(total)} found
</span>
</span>
)
}