mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Added nml loading
This commit is contained in:
1 parent
3ace90179b
commit
cc254e9a9b
10 files changed
+400
-59
No files matched your search
@@ -21,6 +21,7 @@ frontend/dist-ssr/
|
|||||||
# Backups Konduktor will create before any write (Phase 3+).
|
# Backups Konduktor will create before any write (Phase 3+).
|
||||||
*.nml.bak
|
*.nml.bak
|
||||||
*.nml.backup
|
*.nml.backup
|
||||||
|
*.nml.*.bak
|
||||||
backups/
|
backups/
|
||||||
|
|
||||||
# ---- Editor / OS ----
|
# ---- Editor / OS ----
|
||||||
|
|||||||
@@ -20,7 +20,11 @@ Two independent apps that talk over HTTP:
|
|||||||
into `Track` objects, indexes them by primary key, and builds the playlist
|
into `Track` objects, indexes them by primary key, and builds the playlist
|
||||||
tree. All query logic (filter/sort/facets/stats) lives here.
|
tree. All query logic (filter/sort/facets/stats) lives here.
|
||||||
- `schemas.py` — Pydantic response models.
|
- `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
|
- **`frontend/`** — React + TypeScript + Vite. A dark, virtualized track
|
||||||
explorer. Entry: [frontend/src/App.tsx](frontend/src/App.tsx).
|
explorer. Entry: [frontend/src/App.tsx](frontend/src/App.tsx).
|
||||||
- `api.ts` — typed client + all API types (keep in sync with backend
|
- `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
|
model** in memory (create/rename/delete/set-entries). On `save()` it renders
|
||||||
the model, extracts only the freshly rendered `<PLAYLISTS>…</PLAYLISTS>` span,
|
the model, extracts only the freshly rendered `<PLAYLISTS>…</PLAYLISTS>` span,
|
||||||
and splices it into the original file bytes — COLLECTION stays byte-identical,
|
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
|
- **Minimal-diff is load-bearing — do NOT re-serialize with lxml.** lxml
|
||||||
reformats the whole PLAYLISTS section (~2500 changed lines). The render MUST
|
reformats the whole PLAYLISTS section (~2500 changed lines). The render MUST
|
||||||
use the library's pipeline: `XmlSerializer().render(nml)` →
|
use the library's pipeline: `XmlSerializer().render(nml)` →
|
||||||
|
|||||||
@@ -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
|
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**.
|
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
|
```bash
|
||||||
KONDUKTOR_NML=/path/to/collection.nml uvicorn konduktor.main:app --port 8000
|
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.
|
> it would clobber your changes otherwise.
|
||||||
|
|
||||||
**Safety guarantees:**
|
**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 `<PLAYLISTS>` section is rewritten; the track
|
- Saves are *surgical* — only the `<PLAYLISTS>` section is rewritten; the track
|
||||||
`COLLECTION` stays byte-for-byte identical.
|
`COLLECTION` stays byte-for-byte identical.
|
||||||
- To try it against a copy, point `KONDUKTOR_NML` at one.
|
- To try it against a copy, point `KONDUKTOR_NML` at one.
|
||||||
|
|||||||
+127
-48
@@ -1,7 +1,8 @@
|
|||||||
"""Konduktor FastAPI app.
|
"""Konduktor FastAPI app.
|
||||||
|
|
||||||
Phase 1-2: read-only collection API. Phase 3: playlist editing with
|
The collection to work on is chosen at runtime (see /api/collection/open) — the
|
||||||
surgical, backup-first saves (see playlist_store.py).
|
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
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -14,9 +15,13 @@ from fastapi.middleware.cors import CORSMiddleware
|
|||||||
from .collection_service import CollectionService
|
from .collection_service import CollectionService
|
||||||
from .playlist_store import PlaylistError, PlaylistStore
|
from .playlist_store import PlaylistError, PlaylistStore
|
||||||
from .schemas import (
|
from .schemas import (
|
||||||
|
CollectionStatus,
|
||||||
CreatePlaylist,
|
CreatePlaylist,
|
||||||
EditState,
|
EditState,
|
||||||
Facets,
|
Facets,
|
||||||
|
FsEntry,
|
||||||
|
FsListing,
|
||||||
|
OpenCollection,
|
||||||
PlaylistNode,
|
PlaylistNode,
|
||||||
RenamePlaylist,
|
RenamePlaylist,
|
||||||
SaveResult,
|
SaveResult,
|
||||||
@@ -26,11 +31,7 @@ from .schemas import (
|
|||||||
TrackPage,
|
TrackPage,
|
||||||
)
|
)
|
||||||
|
|
||||||
# The collection to read/edit. Defaults to the repo-root collection.nml.
|
app = FastAPI(title="Konduktor API", version="0.4.0")
|
||||||
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.add_middleware(
|
app.add_middleware(
|
||||||
CORSMiddleware,
|
CORSMiddleware,
|
||||||
@@ -39,26 +40,107 @@ app.add_middleware(
|
|||||||
allow_headers=["*"],
|
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:
|
STATE = AppState()
|
||||||
global _service
|
|
||||||
if _service is None:
|
# Optional auto-load for dev/tests.
|
||||||
if not NML_PATH.exists():
|
_env_nml = os.environ.get("KONDUKTOR_NML")
|
||||||
raise HTTPException(500, f"NML file not found: {NML_PATH}")
|
if _env_nml and Path(_env_nml).exists():
|
||||||
_service = CollectionService(NML_PATH)
|
try:
|
||||||
return _service
|
STATE.open(Path(_env_nml))
|
||||||
|
except Exception: # noqa: BLE001 — bad env path shouldn't crash startup
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
def get_store() -> PlaylistStore:
|
def require_service() -> CollectionService:
|
||||||
global _store
|
if not STATE.loaded:
|
||||||
if _store is None:
|
raise HTTPException(409, "No collection loaded")
|
||||||
if not NML_PATH.exists():
|
assert STATE.service is not None
|
||||||
raise HTTPException(500, f"NML file not found: {NML_PATH}")
|
return STATE.service
|
||||||
_store = PlaylistStore(NML_PATH)
|
|
||||||
return _store
|
|
||||||
|
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 ---------------------------------------------------
|
# ---- health / state ---------------------------------------------------
|
||||||
@@ -66,24 +148,21 @@ def get_store() -> PlaylistStore:
|
|||||||
|
|
||||||
@app.get("/api/health")
|
@app.get("/api/health")
|
||||||
def health() -> dict:
|
def health() -> dict:
|
||||||
return {
|
return {"status": "ok", "loaded": STATE.loaded, "path": str(STATE.path) if STATE.path else None}
|
||||||
"status": "ok",
|
|
||||||
"nml_path": str(NML_PATH),
|
|
||||||
"nml_exists": NML_PATH.exists(),
|
|
||||||
"loaded": _service is not None,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/state", response_model=EditState)
|
@app.get("/api/state", response_model=EditState)
|
||||||
def state() -> 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")
|
@app.post("/api/reload")
|
||||||
def reload_collection() -> dict:
|
def reload_collection() -> dict:
|
||||||
get_service().load()
|
if not STATE.loaded:
|
||||||
get_store()._load()
|
raise HTTPException(409, "No collection loaded")
|
||||||
return {"status": "reloaded", "tracks": len(get_service().tracks)}
|
STATE.open(STATE.path) # re-parse current file from disk
|
||||||
|
return {"status": "reloaded", "tracks": len(require_service().tracks)}
|
||||||
|
|
||||||
|
|
||||||
# ---- read: stats / facets / tracks ------------------------------------
|
# ---- read: stats / facets / tracks ------------------------------------
|
||||||
@@ -91,12 +170,12 @@ def reload_collection() -> dict:
|
|||||||
|
|
||||||
@app.get("/api/stats", response_model=Stats)
|
@app.get("/api/stats", response_model=Stats)
|
||||||
def stats() -> 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)
|
@app.get("/api/facets", response_model=Facets)
|
||||||
def facets() -> Facets:
|
def facets() -> Facets:
|
||||||
return get_service().facets()
|
return require_service().facets()
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/tracks", response_model=TrackPage)
|
@app.get("/api/tracks", response_model=TrackPage)
|
||||||
@@ -113,27 +192,27 @@ def tracks(
|
|||||||
limit: int = Query(100, ge=1, le=20000),
|
limit: int = Query(100, ge=1, le=20000),
|
||||||
offset: int = Query(0, ge=0),
|
offset: int = Query(0, ge=0),
|
||||||
) -> TrackPage:
|
) -> 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,
|
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,
|
rating_min=rating_min, has_cues=has_cues, sort=sort, order=order,
|
||||||
limit=limit, offset=offset,
|
limit=limit, offset=offset,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
# ---- read: playlists (served from the editable store) -----------------
|
# ---- read: playlists --------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/playlists", response_model=list[PlaylistNode])
|
@app.get("/api/playlists", response_model=list[PlaylistNode])
|
||||||
def playlists() -> 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])
|
@app.get("/api/playlists/{playlist_id}/tracks", response_model=list[Track])
|
||||||
def playlist_tracks(playlist_id: str) -> 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:
|
if keys is None:
|
||||||
raise HTTPException(404, f"Playlist not found: {playlist_id}")
|
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]
|
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)
|
@app.post("/api/playlists", response_model=PlaylistNode)
|
||||||
def create_playlist(body: CreatePlaylist) -> PlaylistNode:
|
def create_playlist(body: CreatePlaylist) -> PlaylistNode:
|
||||||
store = get_store()
|
store = require_store()
|
||||||
try:
|
try:
|
||||||
new_uuid = store.create_playlist(body.name.strip() or "New Playlist", body.parent_id)
|
new_uuid = store.create_playlist(body.name.strip() or "New Playlist", body.parent_id)
|
||||||
except PlaylistError as ex:
|
except PlaylistError as ex:
|
||||||
@@ -153,7 +232,7 @@ def create_playlist(body: CreatePlaylist) -> PlaylistNode:
|
|||||||
@app.patch("/api/playlists/{playlist_uuid}")
|
@app.patch("/api/playlists/{playlist_uuid}")
|
||||||
def rename_playlist(playlist_uuid: str, body: RenamePlaylist) -> dict:
|
def rename_playlist(playlist_uuid: str, body: RenamePlaylist) -> dict:
|
||||||
try:
|
try:
|
||||||
get_store().rename_playlist(playlist_uuid, body.name.strip())
|
require_store().rename_playlist(playlist_uuid, body.name.strip())
|
||||||
except PlaylistError as ex:
|
except PlaylistError as ex:
|
||||||
raise HTTPException(404, str(ex))
|
raise HTTPException(404, str(ex))
|
||||||
return {"status": "renamed", "id": playlist_uuid, "name": body.name}
|
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}")
|
@app.delete("/api/playlists/{playlist_uuid}")
|
||||||
def delete_playlist(playlist_uuid: str) -> dict:
|
def delete_playlist(playlist_uuid: str) -> dict:
|
||||||
try:
|
try:
|
||||||
get_store().delete_playlist(playlist_uuid)
|
require_store().delete_playlist(playlist_uuid)
|
||||||
except PlaylistError as ex:
|
except PlaylistError as ex:
|
||||||
raise HTTPException(404, str(ex))
|
raise HTTPException(404, str(ex))
|
||||||
return {"status": "deleted", "id": playlist_uuid}
|
return {"status": "deleted", "id": playlist_uuid}
|
||||||
@@ -170,8 +249,8 @@ def delete_playlist(playlist_uuid: str) -> dict:
|
|||||||
|
|
||||||
@app.put("/api/playlists/{playlist_uuid}/entries")
|
@app.put("/api/playlists/{playlist_uuid}/entries")
|
||||||
def set_entries(playlist_uuid: str, body: SetEntries) -> dict:
|
def set_entries(playlist_uuid: str, body: SetEntries) -> dict:
|
||||||
store = get_store()
|
store = require_store()
|
||||||
entries = get_service().entries_for(body.track_ids)
|
entries = require_service().entries_for(body.track_ids)
|
||||||
try:
|
try:
|
||||||
store.set_entries(playlist_uuid, entries)
|
store.set_entries(playlist_uuid, entries)
|
||||||
except PlaylistError as ex:
|
except PlaylistError as ex:
|
||||||
@@ -182,20 +261,20 @@ def set_entries(playlist_uuid: str, body: SetEntries) -> dict:
|
|||||||
@app.post("/api/playlists/{playlist_uuid}/add")
|
@app.post("/api/playlists/{playlist_uuid}/add")
|
||||||
def add_entries(playlist_uuid: str, body: SetEntries) -> dict:
|
def add_entries(playlist_uuid: str, body: SetEntries) -> dict:
|
||||||
"""Append tracks to a playlist (skips ids already present)."""
|
"""Append tracks to a playlist (skips ids already present)."""
|
||||||
store = get_store()
|
store = require_store()
|
||||||
current = store.entry_keys(playlist_uuid)
|
current = store.entry_keys(playlist_uuid)
|
||||||
if current is None:
|
if current is None:
|
||||||
raise HTTPException(404, f"Playlist not found: {playlist_uuid}")
|
raise HTTPException(404, f"Playlist not found: {playlist_uuid}")
|
||||||
have = set(current)
|
have = set(current)
|
||||||
added = [tid for tid in body.track_ids if tid not in have]
|
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)
|
store.set_entries(playlist_uuid, entries)
|
||||||
return {"status": "added", "id": playlist_uuid, "added": len(added), "count": len(entries)}
|
return {"status": "added", "id": playlist_uuid, "added": len(added), "count": len(entries)}
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/save", response_model=SaveResult)
|
@app.post("/api/save", response_model=SaveResult)
|
||||||
def save() -> SaveResult:
|
def save() -> SaveResult:
|
||||||
store = get_store()
|
store = require_store()
|
||||||
if not store.dirty:
|
if not store.dirty:
|
||||||
return SaveResult(saved=False, backup=None, playlists=store.count_playlists())
|
return SaveResult(saved=False, backup=None, playlists=store.count_playlists())
|
||||||
backup = store.save()
|
backup = store.save()
|
||||||
|
|||||||
@@ -240,11 +240,15 @@ class PlaylistStore:
|
|||||||
return backup
|
return backup
|
||||||
|
|
||||||
def _backup(self) -> Path:
|
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())
|
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
|
n = 1
|
||||||
while backup.exists():
|
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
|
n += 1
|
||||||
shutil.copy2(self.nml_path, backup)
|
shutil.copy2(self.nml_path, backup)
|
||||||
return backup
|
return backup
|
||||||
@@ -106,3 +106,30 @@ class SaveResult(BaseModel):
|
|||||||
class EditState(BaseModel):
|
class EditState(BaseModel):
|
||||||
dirty: bool # unsaved in-memory playlist changes exist
|
dirty: bool # unsaved in-memory playlist changes exist
|
||||||
nml_path: str
|
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
|
||||||
+40
-3
@@ -1,5 +1,5 @@
|
|||||||
import { useCallback, useMemo, useState } from 'react'
|
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 type { SortingState } from '@tanstack/react-table'
|
||||||
import { api, type Track } from './api'
|
import { api, type Track } from './api'
|
||||||
import { Sidebar, type Source } from './components/Sidebar'
|
import { Sidebar, type Source } from './components/Sidebar'
|
||||||
@@ -9,6 +9,7 @@ import { PlaylistEditor } from './components/PlaylistEditor'
|
|||||||
import { SelectionBar } from './components/SelectionBar'
|
import { SelectionBar } from './components/SelectionBar'
|
||||||
import { StatusBar } from './components/StatusBar'
|
import { StatusBar } from './components/StatusBar'
|
||||||
import { Toast, type ToastMsg } from './components/Toast'
|
import { Toast, type ToastMsg } from './components/Toast'
|
||||||
|
import { CollectionPicker } from './components/CollectionPicker'
|
||||||
|
|
||||||
function applyFilters(tracks: Track[], f: Filters): Track[] {
|
function applyFilters(tracks: Track[], f: Filters): Track[] {
|
||||||
const q = f.search.trim().toLowerCase()
|
const q = f.search.trim().toLowerCase()
|
||||||
@@ -31,26 +32,34 @@ function applyFilters(tracks: Track[], f: Filters): Track[] {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function App() {
|
export default function App() {
|
||||||
|
const qc = useQueryClient()
|
||||||
const [source, setSource] = useState<Source>({ kind: 'all' })
|
const [source, setSource] = useState<Source>({ kind: 'all' })
|
||||||
const [filters, setFilters] = useState<Filters>(emptyFilters)
|
const [filters, setFilters] = useState<Filters>(emptyFilters)
|
||||||
const [sorting, setSorting] = useState<SortingState>([])
|
const [sorting, setSorting] = useState<SortingState>([])
|
||||||
const [selected, setSelected] = useState<Set<string>>(new Set())
|
const [selected, setSelected] = useState<Set<string>>(new Set())
|
||||||
const [toast, setToast] = useState<ToastMsg | null>(null)
|
const [toast, setToast] = useState<ToastMsg | null>(null)
|
||||||
|
const [forcePicker, setForcePicker] = useState(false)
|
||||||
|
|
||||||
const notify = useCallback((kind: ToastMsg['kind'], text: string) => {
|
const notify = useCallback((kind: ToastMsg['kind'], text: string) => {
|
||||||
setToast({ id: Date.now(), kind, text })
|
setToast({ id: Date.now(), kind, text })
|
||||||
}, [])
|
}, [])
|
||||||
const onError = useCallback((msg: string) => notify('error', msg), [notify])
|
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({
|
const allTracks = useQuery({
|
||||||
queryKey: ['tracks', 'all'],
|
queryKey: ['tracks', 'all'],
|
||||||
queryFn: () => api.tracks({ limit: 20000, sort: 'artist' }),
|
queryFn: () => api.tracks({ limit: 20000, sort: 'artist' }),
|
||||||
enabled: source.kind === 'all',
|
enabled: loaded && source.kind === 'all',
|
||||||
})
|
})
|
||||||
const playlistTracks = useQuery({
|
const playlistTracks = useQuery({
|
||||||
queryKey: ['playlist', source.kind === 'playlist' ? source.id : null],
|
queryKey: ['playlist', source.kind === 'playlist' ? source.id : null],
|
||||||
queryFn: () => api.playlistTracks((source as { id: string }).id),
|
queryFn: () => api.playlistTracks((source as { id: string }).id),
|
||||||
enabled: source.kind === 'playlist',
|
enabled: loaded && source.kind === 'playlist',
|
||||||
})
|
})
|
||||||
|
|
||||||
const isAll = source.kind === 'all'
|
const isAll = source.kind === 'all'
|
||||||
@@ -62,6 +71,32 @@ export default function App() {
|
|||||||
filters,
|
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 (
|
||||||
|
<div className="flex h-screen w-screen items-center justify-center bg-ink-950 text-muted">
|
||||||
|
Loading…
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!loaded || forcePicker) {
|
||||||
|
return (
|
||||||
|
<CollectionPicker
|
||||||
|
onOpened={handleOpened}
|
||||||
|
onCancel={loaded ? () => setForcePicker(false) : undefined}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
const selectSource = (s: Source) => {
|
const selectSource = (s: Source) => {
|
||||||
setSource(s)
|
setSource(s)
|
||||||
setSorting([])
|
setSorting([])
|
||||||
@@ -143,6 +178,8 @@ export default function App() {
|
|||||||
total={tracks.length}
|
total={tracks.length}
|
||||||
sourceName={isAll ? 'All Tracks' : source.name}
|
sourceName={isAll ? 'All Tracks' : source.name}
|
||||||
loading={loading}
|
loading={loading}
|
||||||
|
collectionName={collection.data?.path?.split('/').pop() ?? null}
|
||||||
|
onChangeCollection={() => setForcePicker(true)}
|
||||||
/>
|
/>
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -101,6 +101,26 @@ export interface EditState {
|
|||||||
nml_path: string
|
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 {
|
export interface SaveResult {
|
||||||
saved: boolean
|
saved: boolean
|
||||||
backup: string | null
|
backup: string | null
|
||||||
@@ -142,6 +162,13 @@ function qs(params: Record<string, unknown>): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const api = {
|
export const api = {
|
||||||
|
// ---- collection selection ----
|
||||||
|
collection: () => getJSON<CollectionStatus>('/api/collection'),
|
||||||
|
openCollection: (path: string) =>
|
||||||
|
send<CollectionStatus>('POST', '/api/collection/open', { path }),
|
||||||
|
listDir: (path?: string) =>
|
||||||
|
getJSON<FsListing>(`/api/fs/list${path ? `?path=${encodeURIComponent(path)}` : ''}`),
|
||||||
|
|
||||||
stats: () => getJSON<Stats>('/api/stats'),
|
stats: () => getJSON<Stats>('/api/stats'),
|
||||||
facets: () => getJSON<Facets>('/api/facets'),
|
facets: () => getJSON<Facets>('/api/facets'),
|
||||||
playlists: () => getJSON<PlaylistNode[]>('/api/playlists'),
|
playlists: () => getJSON<PlaylistNode[]>('/api/playlists'),
|
||||||
|
|||||||
@@ -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<string | undefined>(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 (
|
||||||
|
<div className="flex h-screen w-screen items-center justify-center bg-ink-950 p-6">
|
||||||
|
<div className="flex h-[600px] w-full max-w-2xl flex-col overflow-hidden rounded-xl border border-line bg-ink-900 shadow-2xl">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex items-center gap-3 border-b border-line px-5 py-4">
|
||||||
|
<div className="flex h-8 w-8 items-center justify-center rounded-md bg-accent text-sm font-bold text-ink-950">
|
||||||
|
K
|
||||||
|
</div>
|
||||||
|
<div className="flex-1">
|
||||||
|
<div className="text-[15px] font-semibold tracking-tight">
|
||||||
|
Select your Traktor collection
|
||||||
|
</div>
|
||||||
|
<div className="text-xs text-muted">
|
||||||
|
Choose a <span className="text-text">collection.nml</span> file to open.
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{onCancel && (
|
||||||
|
<button
|
||||||
|
onClick={onCancel}
|
||||||
|
className="rounded-md px-2.5 py-1.5 text-sm text-muted hover:bg-ink-800 hover:text-text"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Path bar */}
|
||||||
|
<div className="flex items-center gap-2 border-b border-line bg-ink-850 px-4 py-2">
|
||||||
|
<button
|
||||||
|
title="Home"
|
||||||
|
onClick={() => setDir(data?.home)}
|
||||||
|
className="rounded px-2 py-1 text-sm text-muted hover:bg-ink-800 hover:text-text"
|
||||||
|
>
|
||||||
|
⌂
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
title="Up one level"
|
||||||
|
disabled={!data?.parent}
|
||||||
|
onClick={() => data?.parent && setDir(data.parent)}
|
||||||
|
className="rounded px-2 py-1 text-sm text-muted hover:bg-ink-800 hover:text-text disabled:cursor-not-allowed disabled:opacity-40"
|
||||||
|
>
|
||||||
|
↑
|
||||||
|
</button>
|
||||||
|
<span className="truncate font-mono text-xs text-faint" dir="rtl">
|
||||||
|
{data?.path ?? 'Loading…'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Listing */}
|
||||||
|
<div className="min-h-0 flex-1 overflow-y-auto p-2">
|
||||||
|
{listing.isLoading && <div className="p-4 text-sm text-faint">Loading…</div>}
|
||||||
|
{data && data.dirs.length === 0 && data.files.length === 0 && (
|
||||||
|
<div className="p-4 text-sm text-faint">No folders or .nml files here.</div>
|
||||||
|
)}
|
||||||
|
{data?.dirs.map((d) => (
|
||||||
|
<button
|
||||||
|
key={d.path}
|
||||||
|
onClick={() => setDir(d.path)}
|
||||||
|
className="flex w-full items-center gap-2 rounded-md px-3 py-2 text-left text-sm text-muted hover:bg-ink-800 hover:text-text"
|
||||||
|
>
|
||||||
|
<span className="text-faint">📁</span>
|
||||||
|
<span className="truncate">{d.name}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
{data?.files.map((f) => (
|
||||||
|
<button
|
||||||
|
key={f.path}
|
||||||
|
onClick={() => open.mutate(f.path)}
|
||||||
|
disabled={open.isPending}
|
||||||
|
className="flex w-full items-center gap-2 rounded-md px-3 py-2 text-left text-sm text-text hover:bg-accent-soft"
|
||||||
|
>
|
||||||
|
<span className="text-accent">♫</span>
|
||||||
|
<span className="truncate">{f.name}</span>
|
||||||
|
<span className="ml-auto text-[10px] uppercase tracking-wider text-faint">
|
||||||
|
open
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Manual path + errors */}
|
||||||
|
<div className="border-t border-line px-4 py-3">
|
||||||
|
{open.isError && (
|
||||||
|
<div className="mb-2 rounded-md border border-pink/40 bg-ink-850 px-3 py-2 text-xs text-pink">
|
||||||
|
{(open.error as Error).message}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<input
|
||||||
|
value={manual}
|
||||||
|
onChange={(e) => 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"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
disabled={!manual.trim() || open.isPending}
|
||||||
|
onClick={() => open.mutate(manual.trim())}
|
||||||
|
className="rounded-md bg-accent px-4 py-2 text-sm font-medium text-ink-950 hover:brightness-110 disabled:cursor-not-allowed disabled:opacity-40"
|
||||||
|
>
|
||||||
|
{open.isPending ? 'Opening…' : 'Open'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -3,9 +3,18 @@ interface Props {
|
|||||||
total: number
|
total: number
|
||||||
sourceName: string
|
sourceName: string
|
||||||
loading?: boolean
|
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 (
|
return (
|
||||||
<div className="flex items-center gap-3 border-t border-line bg-ink-900 px-4 py-2 text-xs text-muted">
|
<div className="flex items-center gap-3 border-t border-line bg-ink-900 px-4 py-2 text-xs text-muted">
|
||||||
<span className="font-medium text-text">{sourceName}</span>
|
<span className="font-medium text-text">{sourceName}</span>
|
||||||
@@ -23,7 +32,16 @@ export function StatusBar({ showing, total, sourceName, loading }: Props) {
|
|||||||
)}
|
)}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
<span className="ml-auto text-faint">konduktor · phase 3</span>
|
{collectionName && (
|
||||||
|
<button
|
||||||
|
onClick={onChangeCollection}
|
||||||
|
className="ml-auto flex items-center gap-1.5 rounded px-2 py-0.5 text-faint hover:bg-ink-800 hover:text-text"
|
||||||
|
title="Change collection"
|
||||||
|
>
|
||||||
|
<span className="text-[11px]">⎘</span>
|
||||||
|
<span className="max-w-[220px] truncate font-mono text-[11px]">{collectionName}</span>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user