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
+127
-48
@@ -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()
|
||||
|
||||
Reference in new issue
Block a user