mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Implemented automatic path remapping
This commit is contained in:
1 parent
eccd352ae5
commit
99d590a051
17 files changed
+1025
-10
No files matched your search
@@ -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()
|
||||
|
||||
|
||||
@@ -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
|
||||
remapped = self._path_mapping.apply(base)
|
||||
if remapped == base:
|
||||
return base
|
||||
return remapped if remapped.exists() else base
|
||||
if not self._path_mapping.empty:
|
||||
remapped = self._path_mapping.apply(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
|
||||
|
||||
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."""
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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…)."""
|
||||
|
||||
@@ -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)
|
||||
@@ -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,
|
||||
|
||||
@@ -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 "──────────────────────────────────────────"
|
||||
|
||||
@@ -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)
|
||||
Reference in new issue
Block a user