Made UI improvements

This commit is contained in:
Ben committed 2026-07-04 22:43:00 +02:00
1 parent 2f9b1d59ae
commit d848efaf50
15 files changed
+563 -118

No files matched your search

+62
View File
@@ -0,0 +1,62 @@
"""Locate Traktor collections in their default install locations.
Traktor stores each version's data under a versioned folder:
~/Documents/Native Instruments/Traktor <version>/collection.nml
This is the same relative path on macOS and Windows (both under the user's
Documents folder), so a single glob covers both.
"""
from __future__ import annotations
import re
from pathlib import Path
_VERSION_RE = re.compile(r"(\d+(?:\.\d+)*)")
def _traktor_root() -> Path:
return Path.home() / "Documents" / "Native Instruments"
def _version_key(version: str | None) -> tuple[int, ...]:
"""Sortable tuple for a dotted version string; missing/odd → lowest."""
if not version:
return (0,)
try:
return tuple(int(p) for p in version.split("."))
except ValueError:
return (0,)
def describe(path: Path) -> dict:
"""Build a candidate record for a collection.nml path. The label/version
come from the parent folder name (e.g. 'Traktor 4.5.0')."""
parent = path.parent.name
m = _VERSION_RE.search(parent)
exists = path.is_file()
return {
"path": str(path),
"label": parent or path.name,
"version": m.group(1) if m else None,
"modified": (path.stat().st_mtime if exists else None),
"exists": exists,
}
def detect_collections() -> list[dict]:
"""All Traktor collection.nml files found in default locations, newest
Traktor version first (then most-recently-modified)."""
root = _traktor_root()
found: list[dict] = []
if not root.is_dir():
return found
for d in sorted(root.iterdir()):
if not d.is_dir() or not d.name.lower().startswith("traktor"):
continue
nml = d / "collection.nml"
if nml.is_file():
found.append(describe(nml))
found.sort(
key=lambda c: (_version_key(c["version"]), c["modified"] or 0.0),
reverse=True,
)
return found
+18
View File
@@ -13,9 +13,13 @@ from fastapi import FastAPI, File, Form, HTTPException, Query, Response, UploadF
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from . import prefs
from .collection_service import CollectionService
from .discovery import describe, detect_collections
from .playlist_store import PlaylistError, PlaylistStore
from .schemas import (
CollectionCandidate,
CollectionOptions,
CollectionStatus,
CreatePlaylist,
CuePoint,
@@ -121,9 +125,23 @@ def open_collection(body: OpenCollection) -> CollectionStatus:
raise HTTPException(400, f"Not a valid Traktor collection: {ex}")
except Exception as ex: # noqa: BLE001
raise HTTPException(400, f"Could not parse as a Traktor collection: {ex}")
prefs.set_last_collection(str(path))
return collection_status()
@app.get("/api/collection/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 = detect_collections()
auto = CollectionCandidate(**detected[0]) if detected else None
recent = None
last = prefs.get_last_collection()
if last:
recent = CollectionCandidate(**describe(Path(last)))
return CollectionOptions(auto=auto, recent=recent)
@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."""
+39
View File
@@ -0,0 +1,39 @@
"""Tiny persisted user-preferences store.
Kept as a self-contained JSON file that travels with the app (resolved relative
to this package, not a per-OS config dir) so it works the same on every platform
and when the app is moved. Best-effort: any I/O error degrades to "no prefs".
"""
from __future__ import annotations
import json
from pathlib import Path
# backend/userprefs.json — one level up from the package (konduktor/).
_PREFS_PATH = Path(__file__).resolve().parent.parent / "userprefs.json"
def load_prefs() -> dict:
try:
data = json.loads(_PREFS_PATH.read_text())
return data if isinstance(data, dict) else {}
except (OSError, ValueError):
return {}
def save_prefs(prefs: dict) -> None:
try:
_PREFS_PATH.write_text(json.dumps(prefs, indent=2))
except OSError:
pass # non-fatal — prefs are a convenience, not a requirement
def get_last_collection() -> str | None:
val = load_prefs().get("last_collection")
return val if isinstance(val, str) else None
def set_last_collection(path: str) -> None:
prefs = load_prefs()
prefs["last_collection"] = path
save_prefs(prefs)
+13
View File
@@ -178,6 +178,19 @@ class OpenCollection(BaseModel):
path: str
class CollectionCandidate(BaseModel):
path: str
label: str # folder name, e.g. "Traktor 4.5.0"
version: str | None = None # "4.5.0"
modified: float | None = None # collection.nml mtime, epoch seconds
exists: bool = True
class CollectionOptions(BaseModel):
auto: CollectionCandidate | None = None # best auto-detected (latest version)
recent: CollectionCandidate | None = None # last opened (from userprefs)
class FsEntry(BaseModel):
name: str
path: str