From cc254e9a9ba9132acbe707bf3af1e994a09b4dc6 Mon Sep 17 00:00:00 2001 From: Ben Date: Fri, 3 Jul 2026 16:40:40 +0200 Subject: [PATCH] Added nml loading --- .gitignore | 1 + CLAUDE.md | 9 +- README.md | 12 +- backend/konduktor/main.py | 175 ++++++++++++++----- backend/konduktor/playlist_store.py | 8 +- backend/konduktor/schemas.py | 27 +++ frontend/src/App.tsx | 43 ++++- frontend/src/api.ts | 27 +++ frontend/src/components/CollectionPicker.tsx | 135 ++++++++++++++ frontend/src/components/StatusBar.tsx | 22 ++- 10 files changed, 400 insertions(+), 59 deletions(-) create mode 100644 frontend/src/components/CollectionPicker.tsx diff --git a/.gitignore b/.gitignore index b15f726..37209fa 100644 --- a/.gitignore +++ b/.gitignore @@ -21,6 +21,7 @@ frontend/dist-ssr/ # Backups Konduktor will create before any write (Phase 3+). *.nml.bak *.nml.backup +*.nml.*.bak backups/ # ---- Editor / OS ---- diff --git a/CLAUDE.md b/CLAUDE.md index 97dbf26..f41b711 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -20,7 +20,11 @@ Two independent apps that talk over HTTP: into `Track` objects, indexes them by primary key, and builds the playlist tree. All query logic (filter/sort/facets/stats) lives here. - `schemas.py` — Pydantic response models. - - `main.py` — FastAPI routes (all under `/api`). + - `main.py` — FastAPI routes (all under `/api`). Holds an `AppState` with the + currently-loaded collection; it starts **unloaded** and the collection is + chosen at runtime via `POST /api/collection/open` (data routes 409 until + then). `GET /api/fs/list` powers the in-app file browser. Setting + `KONDUKTOR_NML` auto-loads on startup (dev/tests). - **`frontend/`** — React + TypeScript + Vite. A dark, virtualized track explorer. Entry: [frontend/src/App.tsx](frontend/src/App.tsx). - `api.ts` — typed client + all API types (keep in sync with backend @@ -111,7 +115,8 @@ frontend at `http://localhost:5173`. model** in memory (create/rename/delete/set-entries). On `save()` it renders the model, extracts only the freshly rendered `…` span, and splices it into the original file bytes — COLLECTION stays byte-identical, - and a timestamped `.bak` is written first. + and a timestamped `.bak` is written first (into a `backups/` folder next to + the collection). - **Minimal-diff is load-bearing — do NOT re-serialize with lxml.** lxml reformats the whole PLAYLISTS section (~2500 changed lines). The render MUST use the library's pipeline: `XmlSerializer().render(nml)` → diff --git a/README.md b/README.md index a89263e..e4acac3 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,14 @@ cd frontend && npm run dev The Vite dev server proxies `/api` to the backend on port 8000, so both must be running. API docs (Swagger UI): **http://localhost:8000/docs**. -To point at a different collection file: +## Choosing your collection + +On launch, Konduktor asks you to pick a `collection.nml` — browse to it in the +in-app file picker (or paste a full path). You can switch collections any time +via the file name shown in the bottom-right status bar. + +To skip the picker and auto-load a file on startup (handy for development), set +`KONDUKTOR_NML`: ```bash KONDUKTOR_NML=/path/to/collection.nml uvicorn konduktor.main:app --port 8000 @@ -83,7 +90,8 @@ UI. Click **Save to Traktor** to write them to `collection.nml`. > it would clobber your changes otherwise. **Safety guarantees:** -- Every save writes a timestamped `.bak` backup first. +- Every save writes a timestamped `.bak` backup first, into a `backups/` folder + next to your collection. - Saves are *surgical* — only the `` section is rewritten; the track `COLLECTION` stays byte-for-byte identical. - To try it against a copy, point `KONDUKTOR_NML` at one. diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index c75ff81..fd9b0d2 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -1,7 +1,8 @@ """Konduktor FastAPI app. -Phase 1-2: read-only collection API. Phase 3: playlist editing with -surgical, backup-first saves (see playlist_store.py). +The collection to work on is chosen at runtime (see /api/collection/open) — the +app starts with nothing loaded and the UI gates on that. Setting KONDUKTOR_NML +in the environment auto-loads that file on startup (used by dev and tests). """ from __future__ import annotations @@ -14,9 +15,13 @@ from fastapi.middleware.cors import CORSMiddleware from .collection_service import CollectionService from .playlist_store import PlaylistError, PlaylistStore from .schemas import ( + CollectionStatus, CreatePlaylist, EditState, Facets, + FsEntry, + FsListing, + OpenCollection, PlaylistNode, RenamePlaylist, SaveResult, @@ -26,11 +31,7 @@ from .schemas import ( TrackPage, ) -# The collection to read/edit. Defaults to the repo-root collection.nml. -DEFAULT_NML = Path(__file__).resolve().parents[2] / "collection.nml" -NML_PATH = Path(os.environ.get("KONDUKTOR_NML", DEFAULT_NML)) - -app = FastAPI(title="Konduktor API", version="0.3.0") +app = FastAPI(title="Konduktor API", version="0.4.0") app.add_middleware( CORSMiddleware, @@ -39,26 +40,107 @@ app.add_middleware( allow_headers=["*"], ) -_service: CollectionService | None = None -_store: PlaylistStore | None = None + +class AppState: + """Holds the currently-loaded collection (selectable at runtime).""" + + def __init__(self) -> None: + self.path: Path | None = None + self.service: CollectionService | None = None + self.store: PlaylistStore | None = None + + @property + def loaded(self) -> bool: + return self.service is not None + + def open(self, path: Path) -> None: + # Both raise on an invalid/parse-incompatible or playlist-less file; + # only commit to the new collection if BOTH succeed. + service = CollectionService(path) + store = PlaylistStore(path) + self.path, self.service, self.store = path, service, store -def get_service() -> CollectionService: - global _service - if _service is None: - if not NML_PATH.exists(): - raise HTTPException(500, f"NML file not found: {NML_PATH}") - _service = CollectionService(NML_PATH) - return _service +STATE = AppState() + +# Optional auto-load for dev/tests. +_env_nml = os.environ.get("KONDUKTOR_NML") +if _env_nml and Path(_env_nml).exists(): + try: + STATE.open(Path(_env_nml)) + except Exception: # noqa: BLE001 — bad env path shouldn't crash startup + pass -def get_store() -> PlaylistStore: - global _store - if _store is None: - if not NML_PATH.exists(): - raise HTTPException(500, f"NML file not found: {NML_PATH}") - _store = PlaylistStore(NML_PATH) - return _store +def require_service() -> CollectionService: + if not STATE.loaded: + raise HTTPException(409, "No collection loaded") + assert STATE.service is not None + return STATE.service + + +def require_store() -> PlaylistStore: + if not STATE.loaded: + raise HTTPException(409, "No collection loaded") + assert STATE.store is not None + return STATE.store + + +# ---- collection selection --------------------------------------------- + + +@app.get("/api/collection", response_model=CollectionStatus) +def collection_status() -> CollectionStatus: + if not STATE.loaded: + return CollectionStatus(loaded=False) + return CollectionStatus( + loaded=True, + path=str(STATE.path), + tracks=len(require_service().tracks), + playlists=require_store().count_playlists(), + ) + + +@app.post("/api/collection/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}") + try: + STATE.open(path) + except PlaylistError as ex: + 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}") + return collection_status() + + +@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.""" + base = Path(path).expanduser() if path else Path.home() + if not base.exists() or not base.is_dir(): + base = Path.home() + base = base.resolve() + dirs: list[FsEntry] = [] + files: list[FsEntry] = [] + try: + for entry in sorted(base.iterdir(), key=lambda p: p.name.lower()): + if entry.name.startswith("."): + continue + try: + if entry.is_dir(): + dirs.append(FsEntry(name=entry.name, path=str(entry))) + elif entry.suffix.lower() == ".nml": + files.append(FsEntry(name=entry.name, path=str(entry))) + except OSError: + continue + except PermissionError: + pass + parent = str(base.parent) if base.parent != base else None + return FsListing( + path=str(base), parent=parent, home=str(Path.home()), dirs=dirs, files=files + ) # ---- health / state --------------------------------------------------- @@ -66,24 +148,21 @@ def get_store() -> PlaylistStore: @app.get("/api/health") def health() -> dict: - return { - "status": "ok", - "nml_path": str(NML_PATH), - "nml_exists": NML_PATH.exists(), - "loaded": _service is not None, - } + return {"status": "ok", "loaded": STATE.loaded, "path": str(STATE.path) if STATE.path else None} @app.get("/api/state", response_model=EditState) def state() -> EditState: - return EditState(dirty=get_store().dirty, nml_path=str(NML_PATH)) + store = require_store() + return EditState(dirty=store.dirty, nml_path=str(STATE.path)) @app.post("/api/reload") def reload_collection() -> dict: - get_service().load() - get_store()._load() - return {"status": "reloaded", "tracks": len(get_service().tracks)} + if not STATE.loaded: + raise HTTPException(409, "No collection loaded") + STATE.open(STATE.path) # re-parse current file from disk + return {"status": "reloaded", "tracks": len(require_service().tracks)} # ---- read: stats / facets / tracks ------------------------------------ @@ -91,12 +170,12 @@ def reload_collection() -> dict: @app.get("/api/stats", response_model=Stats) def stats() -> Stats: - return get_service().stats(playlist_count=get_store().count_playlists()) + return require_service().stats(playlist_count=require_store().count_playlists()) @app.get("/api/facets", response_model=Facets) def facets() -> Facets: - return get_service().facets() + return require_service().facets() @app.get("/api/tracks", response_model=TrackPage) @@ -113,27 +192,27 @@ def tracks( limit: int = Query(100, ge=1, le=20000), offset: int = Query(0, ge=0), ) -> TrackPage: - return get_service().query_tracks( + return require_service().query_tracks( q=q, genre=genre, key=key, bpm_min=bpm_min, bpm_max=bpm_max, rating_min=rating_min, has_cues=has_cues, sort=sort, order=order, limit=limit, offset=offset, ) -# ---- read: playlists (served from the editable store) ----------------- +# ---- read: playlists -------------------------------------------------- @app.get("/api/playlists", response_model=list[PlaylistNode]) def playlists() -> list[PlaylistNode]: - return get_store().tree() + return require_store().tree() @app.get("/api/playlists/{playlist_id}/tracks", response_model=list[Track]) def playlist_tracks(playlist_id: str) -> list[Track]: - keys = get_store().entry_keys(playlist_id) + keys = require_store().entry_keys(playlist_id) if keys is None: raise HTTPException(404, f"Playlist not found: {playlist_id}") - svc = get_service() + svc = require_service() return [svc.by_key[k] for k in keys if k in svc.by_key] @@ -142,7 +221,7 @@ def playlist_tracks(playlist_id: str) -> list[Track]: @app.post("/api/playlists", response_model=PlaylistNode) def create_playlist(body: CreatePlaylist) -> PlaylistNode: - store = get_store() + store = require_store() try: new_uuid = store.create_playlist(body.name.strip() or "New Playlist", body.parent_id) except PlaylistError as ex: @@ -153,7 +232,7 @@ def create_playlist(body: CreatePlaylist) -> PlaylistNode: @app.patch("/api/playlists/{playlist_uuid}") def rename_playlist(playlist_uuid: str, body: RenamePlaylist) -> dict: try: - get_store().rename_playlist(playlist_uuid, body.name.strip()) + require_store().rename_playlist(playlist_uuid, body.name.strip()) except PlaylistError as ex: raise HTTPException(404, str(ex)) return {"status": "renamed", "id": playlist_uuid, "name": body.name} @@ -162,7 +241,7 @@ def rename_playlist(playlist_uuid: str, body: RenamePlaylist) -> dict: @app.delete("/api/playlists/{playlist_uuid}") def delete_playlist(playlist_uuid: str) -> dict: try: - get_store().delete_playlist(playlist_uuid) + require_store().delete_playlist(playlist_uuid) except PlaylistError as ex: raise HTTPException(404, str(ex)) return {"status": "deleted", "id": playlist_uuid} @@ -170,8 +249,8 @@ def delete_playlist(playlist_uuid: str) -> dict: @app.put("/api/playlists/{playlist_uuid}/entries") def set_entries(playlist_uuid: str, body: SetEntries) -> dict: - store = get_store() - entries = get_service().entries_for(body.track_ids) + store = require_store() + entries = require_service().entries_for(body.track_ids) try: store.set_entries(playlist_uuid, entries) except PlaylistError as ex: @@ -182,20 +261,20 @@ def set_entries(playlist_uuid: str, body: SetEntries) -> dict: @app.post("/api/playlists/{playlist_uuid}/add") def add_entries(playlist_uuid: str, body: SetEntries) -> dict: """Append tracks to a playlist (skips ids already present).""" - store = get_store() + store = require_store() current = store.entry_keys(playlist_uuid) if current is None: raise HTTPException(404, f"Playlist not found: {playlist_uuid}") have = set(current) added = [tid for tid in body.track_ids if tid not in have] - entries = get_service().entries_for(current + added) + entries = require_service().entries_for(current + added) store.set_entries(playlist_uuid, entries) return {"status": "added", "id": playlist_uuid, "added": len(added), "count": len(entries)} @app.post("/api/save", response_model=SaveResult) def save() -> SaveResult: - store = get_store() + store = require_store() if not store.dirty: return SaveResult(saved=False, backup=None, playlists=store.count_playlists()) backup = store.save() diff --git a/backend/konduktor/playlist_store.py b/backend/konduktor/playlist_store.py index cd4a98d..5d62bc5 100644 --- a/backend/konduktor/playlist_store.py +++ b/backend/konduktor/playlist_store.py @@ -240,11 +240,15 @@ class PlaylistStore: return backup def _backup(self) -> Path: + # Backups live in a `backups/` folder next to the collection, not beside + # the file itself (keeps the collection's directory clean). stamp = time.strftime("%Y%m%d-%H%M%S", time.localtime()) - backup = self.nml_path.with_name(f"{self.nml_path.name}.{stamp}.bak") + backup_dir = self.nml_path.parent / "backups" + backup_dir.mkdir(exist_ok=True) + backup = backup_dir / f"{self.nml_path.name}.{stamp}.bak" n = 1 while backup.exists(): - backup = self.nml_path.with_name(f"{self.nml_path.name}.{stamp}-{n}.bak") + backup = backup_dir / f"{self.nml_path.name}.{stamp}-{n}.bak" n += 1 shutil.copy2(self.nml_path, backup) return backup diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index 936f82f..38be8c5 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -106,3 +106,30 @@ class SaveResult(BaseModel): class EditState(BaseModel): dirty: bool # unsaved in-memory playlist changes exist nml_path: str + + +# ---- collection selection ---- + + +class CollectionStatus(BaseModel): + loaded: bool + path: str | None = None + tracks: int | None = None + playlists: int | None = None + + +class OpenCollection(BaseModel): + path: str + + +class FsEntry(BaseModel): + name: str + path: str + + +class FsListing(BaseModel): + path: str + parent: str | None # None when at filesystem root + home: str + dirs: list[FsEntry] + files: list[FsEntry] # .nml files only diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 7a93266..339ed2c 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,5 +1,5 @@ import { useCallback, useMemo, useState } from 'react' -import { useQuery } from '@tanstack/react-query' +import { useQuery, useQueryClient } from '@tanstack/react-query' import type { SortingState } from '@tanstack/react-table' import { api, type Track } from './api' import { Sidebar, type Source } from './components/Sidebar' @@ -9,6 +9,7 @@ import { PlaylistEditor } from './components/PlaylistEditor' import { SelectionBar } from './components/SelectionBar' import { StatusBar } from './components/StatusBar' import { Toast, type ToastMsg } from './components/Toast' +import { CollectionPicker } from './components/CollectionPicker' function applyFilters(tracks: Track[], f: Filters): Track[] { const q = f.search.trim().toLowerCase() @@ -31,26 +32,34 @@ function applyFilters(tracks: Track[], f: Filters): Track[] { } export default function App() { + const qc = useQueryClient() const [source, setSource] = useState({ kind: 'all' }) const [filters, setFilters] = useState(emptyFilters) const [sorting, setSorting] = useState([]) const [selected, setSelected] = useState>(new Set()) const [toast, setToast] = useState(null) + const [forcePicker, setForcePicker] = useState(false) const notify = useCallback((kind: ToastMsg['kind'], text: string) => { setToast({ id: Date.now(), kind, text }) }, []) const onError = useCallback((msg: string) => notify('error', msg), [notify]) + const collection = useQuery({ queryKey: ['collection'], queryFn: api.collection }) + const loaded = collection.data?.loaded ?? false + + // NOTE: all hooks must run on every render (Rules of Hooks). Data queries are + // gated with `enabled: loaded` so they don't fire before a collection is open; + // the loading/picker early-returns live AFTER every hook below. const allTracks = useQuery({ queryKey: ['tracks', 'all'], queryFn: () => api.tracks({ limit: 20000, sort: 'artist' }), - enabled: source.kind === 'all', + enabled: loaded && source.kind === 'all', }) const playlistTracks = useQuery({ queryKey: ['playlist', source.kind === 'playlist' ? source.id : null], queryFn: () => api.playlistTracks((source as { id: string }).id), - enabled: source.kind === 'playlist', + enabled: loaded && source.kind === 'playlist', }) const isAll = source.kind === 'all' @@ -62,6 +71,32 @@ export default function App() { filters, ]) + const handleOpened = () => { + setForcePicker(false) + setSource({ kind: 'all' }) + setSelected(new Set()) + setFilters(emptyFilters) + setSorting([]) + qc.invalidateQueries() // refetch everything for the newly-opened collection + } + + if (collection.isLoading) { + return ( +
+ Loading… +
+ ) + } + + if (!loaded || forcePicker) { + return ( + setForcePicker(false) : undefined} + /> + ) + } + const selectSource = (s: Source) => { setSource(s) setSorting([]) @@ -143,6 +178,8 @@ export default function App() { total={tracks.length} sourceName={isAll ? 'All Tracks' : source.name} loading={loading} + collectionName={collection.data?.path?.split('/').pop() ?? null} + onChangeCollection={() => setForcePicker(true)} /> diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 597ed08..0a2dddb 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -101,6 +101,26 @@ export interface EditState { nml_path: string } +export interface CollectionStatus { + loaded: boolean + path: string | null + tracks: number | null + playlists: number | null +} + +export interface FsEntry { + name: string + path: string +} + +export interface FsListing { + path: string + parent: string | null + home: string + dirs: FsEntry[] + files: FsEntry[] +} + export interface SaveResult { saved: boolean backup: string | null @@ -142,6 +162,13 @@ function qs(params: Record): string { } export const api = { + // ---- collection selection ---- + collection: () => getJSON('/api/collection'), + openCollection: (path: string) => + send('POST', '/api/collection/open', { path }), + listDir: (path?: string) => + getJSON(`/api/fs/list${path ? `?path=${encodeURIComponent(path)}` : ''}`), + stats: () => getJSON('/api/stats'), facets: () => getJSON('/api/facets'), playlists: () => getJSON('/api/playlists'), diff --git a/frontend/src/components/CollectionPicker.tsx b/frontend/src/components/CollectionPicker.tsx new file mode 100644 index 0000000..27efc33 --- /dev/null +++ b/frontend/src/components/CollectionPicker.tsx @@ -0,0 +1,135 @@ +import { useState } from 'react' +import { useMutation, useQuery } from '@tanstack/react-query' +import { api, type CollectionStatus } from '../api' + +interface Props { + onOpened: (status: CollectionStatus) => void + onCancel?: () => void // shown only when switching from an already-loaded collection +} + +export function CollectionPicker({ onOpened, onCancel }: Props) { + const [dir, setDir] = useState(undefined) // undefined => home + const [manual, setManual] = useState('') + + const listing = useQuery({ + queryKey: ['fs', dir ?? '~'], + queryFn: () => api.listDir(dir), + }) + + const open = useMutation({ + mutationFn: (path: string) => api.openCollection(path), + onSuccess: (status) => onOpened(status), + }) + + const data = listing.data + + return ( +
+
+ {/* Header */} +
+
+ K +
+
+
+ Select your Traktor collection +
+
+ Choose a collection.nml file to open. +
+
+ {onCancel && ( + + )} +
+ + {/* Path bar */} +
+ + + + {data?.path ?? 'Loading…'} + +
+ + {/* Listing */} +
+ {listing.isLoading &&
Loading…
} + {data && data.dirs.length === 0 && data.files.length === 0 && ( +
No folders or .nml files here.
+ )} + {data?.dirs.map((d) => ( + + ))} + {data?.files.map((f) => ( + + ))} +
+ + {/* Manual path + errors */} +
+ {open.isError && ( +
+ {(open.error as Error).message} +
+ )} +
+ setManual(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter' && manual.trim()) open.mutate(manual.trim()) + }} + placeholder="…or paste a full path to collection.nml" + className="min-w-0 flex-1 rounded-md border border-line bg-ink-850 px-3 py-2 font-mono text-xs text-text outline-none placeholder:text-faint focus:border-accent" + /> + +
+
+
+
+ ) +} diff --git a/frontend/src/components/StatusBar.tsx b/frontend/src/components/StatusBar.tsx index 61ca7af..b69a887 100644 --- a/frontend/src/components/StatusBar.tsx +++ b/frontend/src/components/StatusBar.tsx @@ -3,9 +3,18 @@ interface Props { total: number sourceName: string loading?: boolean + collectionName?: string | null + onChangeCollection?: () => void } -export function StatusBar({ showing, total, sourceName, loading }: Props) { +export function StatusBar({ + showing, + total, + sourceName, + loading, + collectionName, + onChangeCollection, +}: Props) { return (
{sourceName} @@ -23,7 +32,16 @@ export function StatusBar({ showing, total, sourceName, loading }: Props) { )} )} - konduktor · phase 3 + {collectionName && ( + + )}
) }