Improved library selection flow

This commit is contained in:
patben8 committed 2026-09-23 10:44:25 +02:00
1 parent a081a7a44d
commit 8d11acd783
17 files changed
+609 -71

No files matched your search

@@ -21,6 +21,11 @@ class OneLibraryDriver:
removable = True
suffixes = (".db",)
library_label = "exportLibrary.db"
# What a user PICKS is the mount point, not the database buried three levels
# down inside it — `DriveLayout.locate()` accepts either, but only one of
# them is a thing anybody browses to. The file browser reads this to offer
# folders rather than files.
selects = "directory"
def can_open(self, path: Path) -> bool:
"""Recognise a OneLibrary drive, by layout and then by schema.
@@ -77,6 +82,17 @@ class OneLibraryDriver:
def describe(self, path: Path) -> dict:
return discovery.describe(path)
def display_name_for(self, path: Path) -> str:
"""What to call this library on screen: the DRIVE's name.
The filename is not a stable answer here. A OneLibrary library can be
opened by its mount point OR by the database three levels inside it —
`DriveLayout.locate()` accepts both on purpose — so the same stick would
be "Hardy" opened one way and "exportLibrary.db" opened the other.
"""
layout = DriveLayout.locate(Path(path))
return layout.root.name if layout is not None else Path(path).name
def restore(self, path: Path, data: bytes) -> None:
"""Not supported: a drive is a database plus analysis files plus audio.
@@ -17,6 +17,7 @@ class RekordboxDriver:
display_name = "Rekordbox"
suffixes = (".db",)
library_label = "master.db"
selects = "file"
def can_open(self, path: Path) -> bool:
"""Recognise an encrypted Rekordbox database.
@@ -12,6 +12,7 @@ class TraktorDriver:
display_name = "Traktor"
suffixes = (".nml",)
library_label = "collection.nml"
selects = "file"
def can_open(self, path: Path) -> bool:
"""Recognise an NML without parsing 14 MB of it."""
+11
View File
@@ -192,8 +192,19 @@ class LibraryDriver(Protocol):
# can offer them as import SOURCES. Optional, and False for a platform that
# does not set it, because most keep one library in a known place.
removable: bool
# Whether a user picks a FILE or a DIRECTORY for this platform. Both exist:
# Traktor's library is `collection.nml`, OneLibrary's is the drive, and
# Serato's will be a `_Serato_` folder. The file browser and the open route
# both read this rather than assuming everything is a file. Defaults to
# "file" for a driver that does not set it.
selects: str
def can_open(self, path: Path) -> bool: ...
def open(self, path: Path) -> LibraryAdapter: ...
# OPTIONAL. What to call an opened library on screen. Only the adapter can
# answer for a platform where one library has more than one valid path —
# the filename is otherwise assumed, and that assumption is wrong for a
# library that is a drive. Omitted means "the path's own name".
def display_name_for(self, path: Path) -> str: ...
def detect(self) -> list: ...
def describe(self, path: Path) -> object: ...
+11 -1
View File
@@ -177,13 +177,23 @@ class LibraryInfo(BaseModel):
class PlatformOption(BaseModel):
"""A platform the picker can offer before any library is open."""
"""A platform the picker can offer before any library is open.
Facts only, never finished sentences: `lib/platformCopy.ts` composes the
wording. The distinction that matters is `removable` — a platform with no
library found is "not installed" for Traktor and "nothing plugged in" for
OneLibrary, and only the driver knows which of those is true.
"""
platform: str
name: str
library_label: str
selects: Literal["file", "directory"] = "file"
installed: bool = False
#: How many libraries this platform has right now; `installed` is `found > 0`.
found: int = 0
#: The library lives on a plugged-in drive, so `found` changes between calls.
removable: bool = False
class RemapSample(BaseModel):
+37 -3
View File
@@ -25,6 +25,14 @@ def drivers() -> list[LibraryDriver]:
return list(_DRIVERS)
def driver_by_platform(platform: str) -> LibraryDriver:
"""The driver for a platform name, e.g. ``"traktor"``."""
for d in _DRIVERS:
if d.platform == platform:
return d
raise LibraryNotSupported(f"No adapter registered for platform {platform!r}")
def driver_for(path: Path) -> LibraryDriver:
"""The first registered driver that recognises `path`."""
for d in _DRIVERS:
@@ -64,6 +72,21 @@ def describe(path: Path) -> dict:
}
def detect_for(platform: str) -> list:
"""Every library one platform has right now, best first.
The picker asks which platform FIRST, so detection is scoped to the answer.
Unscoped detection (``detect_all``) concatenates drivers in registration
order, which made "the best candidate" mean "whatever the first-registered
driver found" — with a removable drive registered first, a plugged-in stick
could be offered as the user's collection.
"""
try:
return driver_by_platform(platform).detect()
except (LibraryNotSupported, OSError):
return []
def detect_all() -> list:
"""Every library found in the platforms' default install locations."""
out: list = []
@@ -75,10 +98,21 @@ def detect_all() -> list:
return out
def browsable_suffixes() -> tuple[str, ...]:
"""File extensions the in-app browser should show, across all platforms."""
def browsable_suffixes(platform: str | None = None) -> tuple[str, ...]:
"""File extensions the in-app browser should show, for one platform or all.
A platform that selects a DIRECTORY contributes nothing, even though it has
suffixes: its libraries are not the thing a user picks, so listing them
would offer a file the browser's Open cannot act on.
"""
try:
targets = [driver_by_platform(platform)] if platform else _DRIVERS
except LibraryNotSupported:
targets = []
seen: list[str] = []
for d in _DRIVERS:
for d in targets:
if getattr(d, "selects", "file") != "file":
continue
for suffix in d.suffixes:
if suffix not in seen:
seen.append(suffix)
+56 -15
View File
@@ -129,29 +129,46 @@ def collection_status() -> CollectionStatus:
@app.post("/api/library/open", response_model=CollectionStatus)
def open_collection(body: OpenCollection) -> CollectionStatus:
path = Path(body.path).expanduser()
if not path.exists() or not path.is_file():
raise HTTPException(400, f"File not found: {path}")
# Deliberately NOT `is_file()`. A library is a file on some platforms and a
# DIRECTORY on others — OneLibrary's is the drive, Serato's will be a
# `_Serato_` folder — and which shapes are valid is the driver's business.
# This checks only that the path is there at all; `can_open()` decides.
if not path.exists():
raise HTTPException(400, f"Not found: {path}")
try:
STATE.open(path)
except AdapterError as ex:
raise HTTPException(400, f"Not a valid collection: {ex}")
except Exception as ex: # noqa: BLE001
raise HTTPException(400, f"Could not open that collection: {ex}")
prefs.set_last_collection(str(path))
prefs.set_last_collection(str(path), require_adapter().capabilities().platform)
return collection_status()
@app.get("/api/library/options", response_model=CollectionOptions)
def collection_options() -> CollectionOptions:
"""Startup shortcuts for the picker: the best auto-detected Traktor
collection and the last one opened (may no longer exist → exists=False)."""
detected = registry.detect_all()
auto = CollectionCandidate(**detected[0]) if detected else None
def collection_options(platform: str | None = None) -> CollectionOptions:
"""Startup shortcuts for the picker, scoped to one platform.
Scoped because the picker asks which platform first, and both shortcuts are
only meaningful inside that answer: unscoped, "auto" meant "whatever the
first-registered driver happened to find" — so a plugged-in USB stick could
be offered as the user's collection — and "last opened" could name a library
of the platform they had just declined.
`recent` may no longer exist (→ `exists=False`), which the picker shows
rather than hides: a library that has moved is worth saying so about.
"""
detected = registry.detect_for(platform) if platform else registry.detect_all()
candidates = [CollectionCandidate(**d) for d in detected]
recent = None
last = prefs.get_last_collection()
last = prefs.get_last_collection(platform)
if last:
recent = CollectionCandidate(**registry.describe(Path(last)))
return CollectionOptions(auto=auto, recent=recent)
return CollectionOptions(
auto=candidates[0] if candidates else None,
detected=candidates,
recent=recent,
)
@app.get("/api/library/path-mapping", response_model=PathMappingInfo)
@@ -229,12 +246,19 @@ def patch_prefs(patch: dict) -> dict:
@app.get("/api/fs/list", response_model=FsListing)
def fs_list(path: str | None = None) -> FsListing:
"""List directories and .nml files for the in-app file browser."""
def fs_list(path: str | None = None, platform: str | None = None) -> FsListing:
"""List directories and openable library files for the in-app file browser.
`platform` narrows the files to that platform's own: a Traktor browse that
also listed `master.db` would be offering a file the chosen adapter cannot
open. A platform whose library is a directory contributes no suffixes at
all, so its browse shows folders only.
"""
base = Path(path).expanduser() if path else Path.home()
if not base.exists() or not base.is_dir():
base = Path.home()
base = base.resolve()
suffixes = registry.browsable_suffixes(platform)
dirs: list[FsEntry] = []
files: list[FsEntry] = []
try:
@@ -244,7 +268,7 @@ def fs_list(path: str | None = None) -> FsListing:
try:
if entry.is_dir():
dirs.append(FsEntry(name=entry.name, path=str(entry)))
elif entry.suffix.lower() in registry.browsable_suffixes():
elif entry.suffix.lower() in suffixes:
files.append(FsEntry(name=entry.name, path=str(entry)))
except OSError:
continue
@@ -267,12 +291,22 @@ def health() -> dict:
def _library_info() -> LibraryInfo:
"""Identity of the loaded library, for display and for composing warnings."""
caps = require_adapter().capabilities()
path = Path(str(STATE.path))
# A library's on-screen name is the driver's to give when it cares: a drive
# has one library reachable by two valid paths, and the filename would name
# it differently depending on which one the user happened to pick.
driver = next((d for d in registry.drivers() if d.platform == caps.platform), None)
namer = getattr(driver, "display_name_for", None)
try:
display_name = namer(path) if namer else path.name
except OSError:
display_name = path.name
return LibraryInfo(
platform=caps.platform,
name=caps.save.app_name,
library_label=caps.save.library_label,
path=str(STATE.path),
display_name=Path(str(STATE.path)).name,
display_name=display_name,
version=caps.version,
)
@@ -293,10 +327,17 @@ def platforms() -> list[PlatformOption]:
platform=d.platform,
name=d.display_name,
library_label=getattr(d, "library_label", ""),
selects="file",
selects=getattr(d, "selects", "file"),
installed=bool(found),
found=len(found),
removable=bool(getattr(d, "removable", False)),
)
)
# Registration order is an import-order accident, and this list is a MENU —
# it must not reshuffle itself between two launches. Sorted so the platforms
# that keep a library in a known place come before the ones that are a
# plugged-in drive, which is the real distinction a chooser is making.
out.sort(key=lambda o: (o.removable, o.name.lower()))
return out
+27 -3
View File
@@ -81,12 +81,36 @@ def set_path_mapping(
save_prefs(prefs)
def get_last_collection() -> str | None:
val = load_prefs().get("last_collection")
def get_last_collection(platform: str | None = None) -> str | None:
"""The last library opened — overall, or on one platform.
Per-platform because the picker asks which platform FIRST: offering a
Rekordbox ``master.db`` under "Open last" to someone who just chose Traktor
is an offer that cannot be taken. A platform with no record returns None
rather than falling back to the global one, for the same reason.
The flat ``last_collection`` stays: it is the global answer, and it is what
libraries opened before this existed are recorded in.
"""
prefs = load_prefs()
if platform:
by_platform = prefs.get("last_collection_by_platform")
if isinstance(by_platform, dict):
val = by_platform.get(platform)
return val if isinstance(val, str) else None
return None
val = prefs.get("last_collection")
return val if isinstance(val, str) else None
def set_last_collection(path: str) -> None:
def set_last_collection(path: str, platform: str | None = None) -> None:
"""Record a library as the last opened, globally and for its platform."""
prefs = load_prefs()
prefs["last_collection"] = path
if platform:
by_platform = prefs.get("last_collection_by_platform")
if not isinstance(by_platform, dict):
by_platform = {}
by_platform[platform] = path
prefs["last_collection_by_platform"] = by_platform
save_prefs(prefs)
+6
View File
@@ -126,6 +126,12 @@ class CollectionCandidate(BaseModel):
class CollectionOptions(BaseModel):
auto: CollectionCandidate | None = None # best auto-detected (latest version)
# EVERY library detected, best first. `auto` is simply the first of these.
# Carried in full because one platform can genuinely have several at once —
# two Traktor versions installed, or two sticks plugged in — and silently
# anointing one of them is how the old single-candidate route could open a
# USB drive as the user's collection.
detected: list[CollectionCandidate] = []
recent: CollectionCandidate | None = None # last opened (from userprefs)
+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_phase3.py test_history.py; do
for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_picker.py test_phase3.py test_history.py; do
echo "──────────────────────────────────────────"
echo "▶ $t"
echo "──────────────────────────────────────────"
+147
View File
@@ -0,0 +1,147 @@
"""The library picker's routes: platform first, then library.
Worth pinning because the bug this flow replaced was invisible. `/api/library/
options` used to flatten every driver's detections and return `[0]`, so "the
best candidate" actually meant "whatever the first-registered driver found" —
and since adapters register in import order, a plugged-in USB stick could be
offered as the user's *collection*. Nothing failed; it just opened the wrong
library. The guarantee now is scoping, and scoping is easy to lose again the
next time a route grows a shortcut.
Runs on whatever this machine has: every assertion is about the SHAPE of the
answer, so a laptop with no Traktor, no Rekordbox and nothing plugged in still
exercises the same rules. Prefs are redirected to a temp file — a test must
never rewrite the user's last-opened library.
"""
import tempfile
from pathlib import Path
from konduktor import prefs
# Redirect prefs BEFORE anything reads them.
_TMP = tempfile.TemporaryDirectory()
prefs._PREFS_PATH = Path(_TMP.name) / "userprefs.json"
prefs._LEGACY_PREFS_PATH = Path(_TMP.name) / "absent.json"
from konduktor.core import registry # noqa: E402
from konduktor.main import collection_options, fs_list, platforms # 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
opts = platforms()
by_name = {p.platform: p for p in opts}
print("== /api/platforms reports the facts the platform step needs ==")
check("every registered driver is offered", len(opts) == len(registry.drivers()),
f"{len(opts)} of {len(registry.drivers())}")
check("all three platforms present", {"traktor", "rekordbox", "onelibrary"} <= set(by_name))
check("selects is per-platform, not assumed",
by_name["traktor"].selects == "file"
and by_name["rekordbox"].selects == "file"
# A OneLibrary library is the DRIVE. Getting this wrong sends the browser
# hunting for a file three levels down that nobody would navigate to.
and by_name["onelibrary"].selects == "directory",
{p: by_name[p].selects for p in by_name})
check("only OneLibrary is removable",
by_name["onelibrary"].removable
and not by_name["traktor"].removable
and not by_name["rekordbox"].removable)
check("installed agrees with found", all((p.found > 0) == p.installed for p in opts))
# The list is a MENU. Registration order is an import-order accident, so sorting
# is what stops it reshuffling between two launches.
check("ordered fixed-location first, then by name",
[p.platform for p in opts] == [p.platform for p in
sorted(opts, key=lambda o: (o.removable, o.name.lower()))],
[p.platform for p in opts])
check("a second call gives the same order", [p.platform for p in platforms()] == [p.platform for p in opts])
print("== /api/library/options is scoped to ONE platform ==")
for plat in ("traktor", "rekordbox", "onelibrary"):
o = collection_options(plat)
driver = registry.driver_by_platform(plat)
own = {c["path"] for c in registry.detect_for(plat)}
got = {c.path for c in o.detected}
check(f"{plat}: detected is exactly that platform's own", got == own, f"{got} vs {own}")
check(f"{plat}: auto is the first detected",
(o.auto.path if o.auto else None) == (o.detected[0].path if o.detected else None))
# The old bug, stated directly: nothing removable may surface under a
# platform that keeps its library in a fixed place.
if not getattr(driver, "removable", False):
removable_paths = {c["path"] for d in registry.drivers()
if getattr(d, "removable", False) for c in d.detect()}
check(f"{plat}: no removable drive leaks in", not (got & removable_paths))
check("unscoped still answers (nothing depends on it, but it must not raise)",
collection_options() is not None)
check("an unknown platform detects nothing rather than raising",
collection_options("nonesuch").detected == [])
print("== per-platform 'open last' does not cross platforms ==")
prefs.set_last_collection("/tmp/a/collection.nml", "traktor")
prefs.set_last_collection("/tmp/b/master.db", "rekordbox")
check("traktor remembers its own", prefs.get_last_collection("traktor") == "/tmp/a/collection.nml")
check("rekordbox remembers its own", prefs.get_last_collection("rekordbox") == "/tmp/b/master.db")
# Offering a Rekordbox master.db to someone who just chose Traktor is an offer
# that cannot be taken, so an unknown platform gets None, NOT the global value.
check("a platform with no record gets None, not the global one",
prefs.get_last_collection("onelibrary") is None
and prefs.get_last_collection() == "/tmp/b/master.db")
check("the picker surfaces it as `recent`",
(collection_options("traktor").recent or None) is not None
and collection_options("traktor").recent.path == "/tmp/a/collection.nml")
check("a remembered library that has gone is offered as exists=False",
collection_options("traktor").recent.exists is False)
print("== /api/fs/list only lists what the chosen platform can open ==")
root = Path(tempfile.mkdtemp())
(root / "collection.nml").write_text("x")
(root / "master.db").write_bytes(b"x")
(root / "notes.txt").write_text("x")
(root / "SomeDrive").mkdir()
names = lambda plat: {f.name for f in fs_list(str(root), plat).files} # noqa: E731
check("traktor sees only .nml", names("traktor") == {"collection.nml"}, names("traktor"))
check("rekordbox sees only .db", names("rekordbox") == {"master.db"}, names("rekordbox"))
# Not "the .db files it might contain": its library is a folder, so listing any
# file would offer something the Open action cannot act on.
check("onelibrary, which picks a folder, sees no files at all", names("onelibrary") == set())
check("unscoped still sees the union", names(None) == {"collection.nml", "master.db"})
check("never the unopenable", all("notes.txt" not in names(p)
for p in (None, "traktor", "rekordbox", "onelibrary")))
check("folders are listed for every platform",
all({d.name for d in fs_list(str(root), p).dirs} == {"SomeDrive"}
for p in (None, "traktor", "rekordbox", "onelibrary")))
print("== a library may be a DIRECTORY, not just a file ==")
drives = registry.detect_for("onelibrary")
if drives:
# `describe()` returns the database, but the drive root is what a user picks
# in the browser. Both must name the same library or the picker and the
# last-opened shortcut would disagree about what is valid.
db = Path(drives[0]["path"])
root_dir = db.parent.parent.parent
driver = registry.driver_by_platform("onelibrary")
check("the mount point opens", driver.can_open(root_dir), str(root_dir))
check("so does the database it points at", driver.can_open(db))
# ...and both must be CALLED the same thing. The sidebar names the open
# library, and a filename would call one stick two different names purely
# by which end of it the user happened to click.
check("both ends of the drive give one display name",
driver.display_name_for(root_dir) == driver.display_name_for(db) == root_dir.name,
f"{driver.display_name_for(root_dir)!r} vs {driver.display_name_for(db)!r}")
check("a path that is not a drive falls back to its own name",
driver.display_name_for(Path("/nope/whatever.db")) == "whatever.db")
else:
print(" [SKIP] no OneLibrary drive connected")
print("\n" + ("❌ FAILED" if failed else "✅ PASSED"))
_TMP.cleanup()
raise SystemExit(1 if failed else 0)