mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Implemented basic playlist editing
This commit is contained in:
1 parent
fceaab6d78
commit
3ace90179b
20 files changed
+1523
-105
No files matched your search
@@ -48,6 +48,7 @@ class CollectionService:
|
||||
self._lock = threading.Lock()
|
||||
self.tracks: list[Track] = []
|
||||
self.by_key: dict[str, Track] = {}
|
||||
self.stem_keys: set[str] = set()
|
||||
self._playlist_entries: dict[str, list[str]] = {} # id -> ordered primary keys
|
||||
self._tree: list[PlaylistNode] = []
|
||||
self._playlist_count = 0
|
||||
@@ -59,6 +60,13 @@ class CollectionService:
|
||||
collection = TraktorCollection(path=self.nml_path)
|
||||
self.tracks = [self._to_track(e) for e in collection.nml.collection.entry]
|
||||
self.by_key = {t.id: t for t in self.tracks}
|
||||
# Tracks with stems use PRIMARYKEY TYPE="STEM" in playlists (verified
|
||||
# 945/945 against the real collection); all others use "TRACK".
|
||||
self.stem_keys = {
|
||||
_primary_key(e.location)
|
||||
for e in collection.nml.collection.entry
|
||||
if e.location and getattr(e, "stems", None) is not None
|
||||
}
|
||||
self._playlist_entries = {}
|
||||
self._playlist_count = 0
|
||||
counter = {"n": 0}
|
||||
@@ -228,7 +236,16 @@ class CollectionService:
|
||||
total_tracks=len(self.tracks),
|
||||
)
|
||||
|
||||
def stats(self) -> Stats:
|
||||
def entries_for(self, track_ids: list[str]) -> list[tuple[str, str]]:
|
||||
"""Map track ids to (key, PRIMARYKEY-type) pairs for playlist writing.
|
||||
Unknown ids are skipped (can't reference a track not in the collection)."""
|
||||
out = []
|
||||
for tid in track_ids:
|
||||
if tid in self.by_key:
|
||||
out.append((tid, "STEM" if tid in self.stem_keys else "TRACK"))
|
||||
return out
|
||||
|
||||
def stats(self, playlist_count: int | None = None) -> Stats:
|
||||
rating_breakdown = {i: 0 for i in range(6)}
|
||||
genres: dict[str, int] = {}
|
||||
bpm_buckets: dict[str, int] = {}
|
||||
@@ -259,7 +276,7 @@ class CollectionService:
|
||||
top = sorted(genres.items(), key=lambda x: -x[1])[:10]
|
||||
return Stats(
|
||||
total_tracks=total,
|
||||
total_playlists=self._playlist_count,
|
||||
total_playlists=self._playlist_count if playlist_count is None else playlist_count,
|
||||
rated=rated,
|
||||
unrated=total - rated,
|
||||
missing_key=missing_key,
|
||||
|
||||
+123
-31
@@ -1,4 +1,8 @@
|
||||
"""Konduktor FastAPI app — Phase 1 (read-only collection API)."""
|
||||
"""Konduktor FastAPI app.
|
||||
|
||||
Phase 1-2: read-only collection API. Phase 3: playlist editing with
|
||||
surgical, backup-first saves (see playlist_store.py).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
@@ -8,27 +12,35 @@ from fastapi import FastAPI, HTTPException, Query
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from .collection_service import CollectionService
|
||||
from .schemas import Facets, PlaylistNode, Stats, Track, TrackPage
|
||||
from .playlist_store import PlaylistError, PlaylistStore
|
||||
from .schemas import (
|
||||
CreatePlaylist,
|
||||
EditState,
|
||||
Facets,
|
||||
PlaylistNode,
|
||||
RenamePlaylist,
|
||||
SaveResult,
|
||||
SetEntries,
|
||||
Stats,
|
||||
Track,
|
||||
TrackPage,
|
||||
)
|
||||
|
||||
# The collection to read. Defaults to the repo-root collection.nml.
|
||||
# Reading is safe/non-destructive; writes (later phases) always use a copy.
|
||||
# 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.1.0")
|
||||
app = FastAPI(title="Konduktor API", version="0.3.0")
|
||||
|
||||
# Vite dev server runs on 5173; allow local dev origins.
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=[
|
||||
"http://localhost:5173",
|
||||
"http://127.0.0.1:5173",
|
||||
],
|
||||
allow_origins=["http://localhost:5173", "http://127.0.0.1:5173"],
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
_service: CollectionService | None = None
|
||||
_store: PlaylistStore | None = None
|
||||
|
||||
|
||||
def get_service() -> CollectionService:
|
||||
@@ -40,27 +52,46 @@ def get_service() -> CollectionService:
|
||||
return _service
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
# ---- health / state ---------------------------------------------------
|
||||
|
||||
|
||||
@app.get("/api/health")
|
||||
def health() -> dict:
|
||||
exists = NML_PATH.exists()
|
||||
return {
|
||||
"status": "ok",
|
||||
"nml_path": str(NML_PATH),
|
||||
"nml_exists": exists,
|
||||
"nml_exists": NML_PATH.exists(),
|
||||
"loaded": _service is not None,
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/state", response_model=EditState)
|
||||
def state() -> EditState:
|
||||
return EditState(dirty=get_store().dirty, nml_path=str(NML_PATH))
|
||||
|
||||
|
||||
@app.post("/api/reload")
|
||||
def reload_collection() -> dict:
|
||||
svc = get_service()
|
||||
svc.load()
|
||||
return {"status": "reloaded", "tracks": len(svc.tracks)}
|
||||
get_service().load()
|
||||
get_store()._load()
|
||||
return {"status": "reloaded", "tracks": len(get_service().tracks)}
|
||||
|
||||
|
||||
# ---- read: stats / facets / tracks ------------------------------------
|
||||
|
||||
|
||||
@app.get("/api/stats", response_model=Stats)
|
||||
def stats() -> Stats:
|
||||
return get_service().stats()
|
||||
return get_service().stats(playlist_count=get_store().count_playlists())
|
||||
|
||||
|
||||
@app.get("/api/facets", response_model=Facets)
|
||||
@@ -83,28 +114,89 @@ def tracks(
|
||||
offset: int = Query(0, ge=0),
|
||||
) -> TrackPage:
|
||||
return get_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,
|
||||
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) -----------------
|
||||
|
||||
|
||||
@app.get("/api/playlists", response_model=list[PlaylistNode])
|
||||
def playlists() -> list[PlaylistNode]:
|
||||
return get_service().playlist_tree()
|
||||
return get_store().tree()
|
||||
|
||||
|
||||
@app.get("/api/playlists/{playlist_id}/tracks", response_model=list[Track])
|
||||
def playlist_tracks(playlist_id: str) -> list[Track]:
|
||||
result = get_service().playlist_tracks(playlist_id)
|
||||
if result is None:
|
||||
keys = get_store().entry_keys(playlist_id)
|
||||
if keys is None:
|
||||
raise HTTPException(404, f"Playlist not found: {playlist_id}")
|
||||
return result
|
||||
svc = get_service()
|
||||
return [svc.by_key[k] for k in keys if k in svc.by_key]
|
||||
|
||||
|
||||
# ---- write: playlist editing ------------------------------------------
|
||||
|
||||
|
||||
@app.post("/api/playlists", response_model=PlaylistNode)
|
||||
def create_playlist(body: CreatePlaylist) -> PlaylistNode:
|
||||
store = get_store()
|
||||
try:
|
||||
new_uuid = store.create_playlist(body.name.strip() or "New Playlist", body.parent_id)
|
||||
except PlaylistError as ex:
|
||||
raise HTTPException(400, str(ex))
|
||||
return PlaylistNode(id=new_uuid, name=body.name, type="PLAYLIST", uuid=new_uuid, count=0)
|
||||
|
||||
|
||||
@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())
|
||||
except PlaylistError as ex:
|
||||
raise HTTPException(404, str(ex))
|
||||
return {"status": "renamed", "id": playlist_uuid, "name": body.name}
|
||||
|
||||
|
||||
@app.delete("/api/playlists/{playlist_uuid}")
|
||||
def delete_playlist(playlist_uuid: str) -> dict:
|
||||
try:
|
||||
get_store().delete_playlist(playlist_uuid)
|
||||
except PlaylistError as ex:
|
||||
raise HTTPException(404, str(ex))
|
||||
return {"status": "deleted", "id": playlist_uuid}
|
||||
|
||||
|
||||
@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)
|
||||
try:
|
||||
store.set_entries(playlist_uuid, entries)
|
||||
except PlaylistError as ex:
|
||||
raise HTTPException(404, str(ex))
|
||||
return {"status": "updated", "id": playlist_uuid, "count": len(entries)}
|
||||
|
||||
|
||||
@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()
|
||||
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)
|
||||
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()
|
||||
if not store.dirty:
|
||||
return SaveResult(saved=False, backup=None, playlists=store.count_playlists())
|
||||
backup = store.save()
|
||||
return SaveResult(saved=True, backup=str(backup), playlists=store.count_playlists())
|
||||
@@ -0,0 +1,250 @@
|
||||
"""Editable playlist store backed by the traktor-nml-utils dataclass model.
|
||||
|
||||
Design goals:
|
||||
* minimal diff — unedited playlists must serialize byte-for-byte as Traktor
|
||||
wrote them (the xsdata serializer used by the library reproduces Traktor's
|
||||
exact formatting; lxml does not),
|
||||
* surgical — the ~14 MB COLLECTION stays byte-identical (we splice only the
|
||||
<PLAYLISTS> span back into the original file bytes),
|
||||
* safe — a timestamped .bak is written before every save.
|
||||
|
||||
We edit the parsed dataclass model in memory (create/rename/delete/set-entries),
|
||||
then on save render the full model, extract just the freshly-rendered
|
||||
<PLAYLISTS>…</PLAYLISTS> span, and splice it into the untouched original bytes.
|
||||
|
||||
Playlists are identified by their stable UUID; folders by a synthetic path id
|
||||
(``fld:<name>/<name>``). Smart playlists are read-only.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import shutil
|
||||
import threading
|
||||
import time
|
||||
import uuid as uuidlib
|
||||
from pathlib import Path
|
||||
|
||||
from traktor_nml_utils import (
|
||||
TraktorCollection,
|
||||
format_traktor_layout,
|
||||
restore_traktor_float_format,
|
||||
)
|
||||
from traktor_nml_utils.models.collection import (
|
||||
Entrytype,
|
||||
Nodetype,
|
||||
Playlisttype,
|
||||
Primarykeytype,
|
||||
Subnodestype,
|
||||
)
|
||||
from xsdata.formats.dataclass.serializers import XmlSerializer
|
||||
|
||||
from .schemas import PlaylistNode
|
||||
|
||||
_PLAYLISTS_OPEN = re.compile(rb"<PLAYLISTS[ >]")
|
||||
_PLAYLISTS_CLOSE = re.compile(rb"</PLAYLISTS>")
|
||||
|
||||
|
||||
class PlaylistError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class PlaylistStore:
|
||||
def __init__(self, nml_path: Path):
|
||||
self.nml_path = Path(nml_path)
|
||||
self._lock = threading.RLock()
|
||||
self.dirty = False
|
||||
self._load()
|
||||
|
||||
# ---- load ----------------------------------------------------------
|
||||
def _load(self) -> None:
|
||||
self._raw = self.nml_path.read_bytes()
|
||||
mo = _PLAYLISTS_OPEN.search(self._raw)
|
||||
mc = _PLAYLISTS_CLOSE.search(self._raw)
|
||||
if not mo or not mc:
|
||||
raise PlaylistError("Could not locate <PLAYLISTS> section in NML")
|
||||
self._span = (mo.start(), mc.end())
|
||||
self._collection = TraktorCollection(path=self.nml_path)
|
||||
self._nml = self._collection.nml
|
||||
self.dirty = False
|
||||
|
||||
def _root(self) -> Nodetype:
|
||||
node = self._nml.playlists.node if self._nml.playlists else None
|
||||
if node is None:
|
||||
raise PlaylistError("PLAYLISTS has no root NODE")
|
||||
return node
|
||||
|
||||
@staticmethod
|
||||
def _children(node: Nodetype) -> list[Nodetype]:
|
||||
return list(node.subnodes.node) if node.subnodes else []
|
||||
|
||||
# ---- tree walking --------------------------------------------------
|
||||
def tree(self) -> list[PlaylistNode]:
|
||||
with self._lock:
|
||||
return [self._to_model(c, []) for c in self._children(self._root())]
|
||||
|
||||
def _to_model(self, node: Nodetype, parent_path: list[str]) -> PlaylistNode:
|
||||
ntype = node.type or "FOLDER"
|
||||
name = node.name or "(unnamed)"
|
||||
if ntype == "PLAYLIST" or node.playlist is not None:
|
||||
pl = node.playlist
|
||||
keys = self._entry_keys_of(pl) if pl is not None else []
|
||||
return PlaylistNode(
|
||||
id=pl.uuid if pl and pl.uuid else name,
|
||||
name=name,
|
||||
type="PLAYLIST",
|
||||
uuid=pl.uuid if pl else None,
|
||||
count=len(keys),
|
||||
)
|
||||
if ntype == "SMARTLIST" or node.smartplaylist is not None:
|
||||
return PlaylistNode(
|
||||
id="sl:" + "/".join(parent_path + [name]), name=name, type="SMARTLIST"
|
||||
)
|
||||
path = parent_path + [name]
|
||||
return PlaylistNode(
|
||||
id="fld:" + "/".join(path),
|
||||
name=name,
|
||||
type="FOLDER",
|
||||
children=[self._to_model(c, path) for c in self._children(node)],
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _entry_keys_of(pl: Playlisttype) -> list[str]:
|
||||
return [
|
||||
e.primarykey.key
|
||||
for e in (pl.entry or [])
|
||||
if e.primarykey and e.primarykey.key
|
||||
]
|
||||
|
||||
# ---- lookups -------------------------------------------------------
|
||||
def _iter_nodes(self, node: Nodetype):
|
||||
yield node
|
||||
for c in self._children(node):
|
||||
yield from self._iter_nodes(c)
|
||||
|
||||
def _find_playlist_node(self, playlist_uuid: str) -> Nodetype | None:
|
||||
for n in self._iter_nodes(self._root()):
|
||||
if n.playlist is not None and n.playlist.uuid == playlist_uuid:
|
||||
return n
|
||||
return None
|
||||
|
||||
def _find_parent_of(self, target: Nodetype) -> Nodetype | None:
|
||||
for n in self._iter_nodes(self._root()):
|
||||
if n.subnodes and target in n.subnodes.node:
|
||||
return n
|
||||
return None
|
||||
|
||||
def _find_folder(self, folder_id: str | None) -> Nodetype:
|
||||
root = self._root()
|
||||
if folder_id in (None, "", "fld:"):
|
||||
return root
|
||||
if not folder_id.startswith("fld:"):
|
||||
raise PlaylistError(f"Not a folder id: {folder_id}")
|
||||
cur = root
|
||||
for name in folder_id[len("fld:") :].split("/"):
|
||||
match = next(
|
||||
(
|
||||
c
|
||||
for c in self._children(cur)
|
||||
if (c.type or "FOLDER") == "FOLDER" and c.name == name
|
||||
),
|
||||
None,
|
||||
)
|
||||
if match is None:
|
||||
raise PlaylistError(f"Folder not found: {folder_id}")
|
||||
cur = match
|
||||
return cur
|
||||
|
||||
def entry_keys(self, playlist_uuid: str) -> list[str] | None:
|
||||
with self._lock:
|
||||
node = self._find_playlist_node(playlist_uuid)
|
||||
return None if node is None else self._entry_keys_of(node.playlist)
|
||||
|
||||
# ---- edits ---------------------------------------------------------
|
||||
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
|
||||
with self._lock:
|
||||
folder = self._find_folder(parent_id)
|
||||
if folder.subnodes is None:
|
||||
folder.subnodes = Subnodestype(node=[], count=0)
|
||||
new_uuid = uuidlib.uuid4().hex
|
||||
node = Nodetype(
|
||||
type="PLAYLIST",
|
||||
name=name,
|
||||
playlist=Playlisttype(entry=[], entries=0, type="LIST", uuid=new_uuid),
|
||||
)
|
||||
folder.subnodes.node.append(node)
|
||||
folder.subnodes.count = len(folder.subnodes.node)
|
||||
self.dirty = True
|
||||
return new_uuid
|
||||
|
||||
def rename_playlist(self, playlist_uuid: str, name: str) -> None:
|
||||
with self._lock:
|
||||
node = self._find_playlist_node(playlist_uuid)
|
||||
if node is None:
|
||||
raise PlaylistError(f"Playlist not found: {playlist_uuid}")
|
||||
node.name = name
|
||||
self.dirty = True
|
||||
|
||||
def delete_playlist(self, playlist_uuid: str) -> None:
|
||||
with self._lock:
|
||||
node = self._find_playlist_node(playlist_uuid)
|
||||
if node is None:
|
||||
raise PlaylistError(f"Playlist not found: {playlist_uuid}")
|
||||
parent = self._find_parent_of(node)
|
||||
if parent is None:
|
||||
raise PlaylistError("Cannot delete a top-level node")
|
||||
parent.subnodes.node.remove(node)
|
||||
parent.subnodes.count = len(parent.subnodes.node)
|
||||
self.dirty = True
|
||||
|
||||
def set_entries(self, playlist_uuid: str, entries: list[tuple[str, str]]) -> None:
|
||||
with self._lock:
|
||||
node = self._find_playlist_node(playlist_uuid)
|
||||
if node is None:
|
||||
raise PlaylistError(f"Playlist not found: {playlist_uuid}")
|
||||
pl = node.playlist
|
||||
pl.entry = [
|
||||
Entrytype(primarykey=Primarykeytype(type=ptype or "TRACK", key=key))
|
||||
for key, ptype in entries
|
||||
]
|
||||
pl.entries = len(pl.entry)
|
||||
self.dirty = True
|
||||
|
||||
def count_playlists(self) -> int:
|
||||
with self._lock:
|
||||
return sum(1 for n in self._iter_nodes(self._root()) if n.playlist is not None)
|
||||
|
||||
# ---- persistence ---------------------------------------------------
|
||||
def save(self) -> Path:
|
||||
with self._lock:
|
||||
backup = self._backup()
|
||||
# Render the full model exactly as the library's save() does — the
|
||||
# two post-processing steps restore Traktor's precise layout (expanded
|
||||
# empty tags, 6-decimal floats, newlines), so unedited playlists come
|
||||
# out byte-for-byte identical and only edited ones diff.
|
||||
serialized = XmlSerializer().render(self._nml)
|
||||
serialized = restore_traktor_float_format(serialized, self._nml)
|
||||
serialized = format_traktor_layout(serialized)
|
||||
rendered = serialized.encode("utf-8")
|
||||
ro = _PLAYLISTS_OPEN.search(rendered)
|
||||
rc = _PLAYLISTS_CLOSE.search(rendered)
|
||||
if not ro or not rc:
|
||||
raise PlaylistError("Rendered output missing PLAYLISTS section")
|
||||
new_pl = rendered[ro.start() : rc.end()]
|
||||
|
||||
s, e = self._span
|
||||
new_data = self._raw[:s] + new_pl + self._raw[e:]
|
||||
tmp = self.nml_path.with_suffix(self.nml_path.suffix + ".tmp")
|
||||
tmp.write_bytes(new_data)
|
||||
tmp.replace(self.nml_path)
|
||||
self._load()
|
||||
return backup
|
||||
|
||||
def _backup(self) -> Path:
|
||||
stamp = time.strftime("%Y%m%d-%H%M%S", time.localtime())
|
||||
backup = self.nml_path.with_name(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")
|
||||
n += 1
|
||||
shutil.copy2(self.nml_path, backup)
|
||||
return backup
|
||||
@@ -79,3 +79,30 @@ class PlaylistNode(BaseModel):
|
||||
|
||||
|
||||
PlaylistNode.model_rebuild()
|
||||
|
||||
|
||||
# ---- write request bodies ----
|
||||
|
||||
|
||||
class CreatePlaylist(BaseModel):
|
||||
name: str
|
||||
parent_id: str | None = None # folder id ("fld:..."); None = root
|
||||
|
||||
|
||||
class RenamePlaylist(BaseModel):
|
||||
name: str
|
||||
|
||||
|
||||
class SetEntries(BaseModel):
|
||||
track_ids: list[str] # ordered; full desired contents of the playlist
|
||||
|
||||
|
||||
class SaveResult(BaseModel):
|
||||
saved: bool
|
||||
backup: str | None = None
|
||||
playlists: int
|
||||
|
||||
|
||||
class EditState(BaseModel):
|
||||
dirty: bool # unsaved in-memory playlist changes exist
|
||||
nml_path: str
|
||||
Executable
+21
@@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env bash
|
||||
# Run Konduktor's backend tests against a copy of the real collection.
|
||||
# ALWAYS run this before changing anything in the save/serialization path.
|
||||
set -uo pipefail
|
||||
cd "$(dirname "${BASH_SOURCE[0]}")"
|
||||
source .venv/bin/activate
|
||||
|
||||
fail=0
|
||||
for t in test_save_fidelity.py test_phase3.py; do
|
||||
echo "──────────────────────────────────────────"
|
||||
echo "▶ $t"
|
||||
echo "──────────────────────────────────────────"
|
||||
python "$t" || fail=1
|
||||
echo
|
||||
done
|
||||
|
||||
if [ "$fail" -ne 0 ]; then
|
||||
echo "❌ TESTS FAILED"
|
||||
exit 1
|
||||
fi
|
||||
echo "✅ ALL TESTS PASSED"
|
||||
@@ -0,0 +1,141 @@
|
||||
"""End-to-end write test for Phase 3.
|
||||
|
||||
Runs against a COPY of the collection (never the original). Verifies:
|
||||
* create / add-tracks / reorder / rename / delete all work
|
||||
* save creates a backup and produces a Traktor-parseable file
|
||||
* the COLLECTION section is byte-identical after save (truly surgical)
|
||||
* changes survive a reload
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
|
||||
work_dir = Path(tempfile.mkdtemp(prefix="konduktor-test-"))
|
||||
WORK = work_dir / "collection.nml"
|
||||
shutil.copy2(REAL, WORK)
|
||||
|
||||
# Snapshot the real file up front; the test only ever touches the copy, so the
|
||||
# real file must be untouched at the end (regardless of its absolute size).
|
||||
REAL_STAT = (REAL.stat().st_size, REAL.stat().st_mtime)
|
||||
|
||||
os.environ["KONDUKTOR_NML"] = str(WORK)
|
||||
|
||||
from fastapi.testclient import TestClient # noqa: E402
|
||||
from traktor_nml_utils import TraktorCollection # noqa: E402
|
||||
import konduktor.main as m # noqa: E402
|
||||
|
||||
client = TestClient(m.app)
|
||||
|
||||
|
||||
def collection_span(data: bytes) -> bytes:
|
||||
s = re.search(rb"<COLLECTION[ >]", data).start()
|
||||
e = re.search(rb"</COLLECTION>", data).end()
|
||||
return data[s:e]
|
||||
|
||||
|
||||
def check(label, cond):
|
||||
print(f" [{'PASS' if cond else 'FAIL'}] {label}")
|
||||
if not cond:
|
||||
check.failed = True
|
||||
|
||||
|
||||
check.failed = False
|
||||
|
||||
print("== initial read ==")
|
||||
pls = client.get("/api/playlists").json()
|
||||
flat = lambda ns: [x for n in ns for x in [n] + flat(n.get("children", []))]
|
||||
playlists = [n for n in flat(pls) if n["type"] == "PLAYLIST"]
|
||||
print(f" {len(playlists)} playlists, e.g. {[p['name'] for p in playlists[:3]]}")
|
||||
donor = next(p for p in playlists if p["count"] >= 5)
|
||||
donor_tracks = client.get(f"/api/playlists/{donor['id']}/tracks").json()
|
||||
track_ids = [t["id"] for t in donor_tracks[:5]]
|
||||
print(f" donor '{donor['name']}' -> using {len(track_ids)} track ids")
|
||||
|
||||
collection_before = collection_span(WORK.read_bytes())
|
||||
|
||||
print("== create + add + reorder + rename ==")
|
||||
created = client.post("/api/playlists", json={"name": "Konduktor Test"}).json()
|
||||
new_uuid = created["uuid"]
|
||||
check("create returns uuid", bool(new_uuid))
|
||||
|
||||
r = client.put(f"/api/playlists/{new_uuid}/entries", json={"track_ids": track_ids})
|
||||
check("add 5 entries", r.json().get("count") == 5)
|
||||
|
||||
reordered = list(reversed(track_ids))
|
||||
client.put(f"/api/playlists/{new_uuid}/entries", json={"track_ids": reordered})
|
||||
|
||||
client.patch(f"/api/playlists/{new_uuid}", json={"name": "Konduktor Test 2"})
|
||||
|
||||
st = client.get("/api/state").json()
|
||||
check("state is dirty before save", st["dirty"] is True)
|
||||
|
||||
print("== save ==")
|
||||
res = client.post("/api/save").json()
|
||||
check("saved", res["saved"] is True)
|
||||
backup = Path(res["backup"])
|
||||
check("backup file exists", backup.exists())
|
||||
check("backup matches original size", backup.stat().st_size == REAL.stat().st_size)
|
||||
st = client.get("/api/state").json()
|
||||
check("state clean after save", st["dirty"] is False)
|
||||
|
||||
print("== verify saved file ==")
|
||||
data_after = WORK.read_bytes()
|
||||
check(
|
||||
"COLLECTION section byte-identical (surgical write)",
|
||||
collection_span(data_after) == collection_before,
|
||||
)
|
||||
# Re-parse with the real Traktor library (proves it stays v4-valid).
|
||||
coll = TraktorCollection(path=WORK)
|
||||
check("file re-parses with traktor-nml-utils", len(coll.nml.collection.entry) == 8485)
|
||||
|
||||
|
||||
def walk(n):
|
||||
yield n
|
||||
if n.subnodes:
|
||||
for s in n.subnodes.node:
|
||||
yield from walk(s)
|
||||
|
||||
|
||||
found = [
|
||||
n
|
||||
for n in walk(coll.nml.playlists.node)
|
||||
if n.type == "PLAYLIST" and n.playlist and n.playlist.uuid == new_uuid
|
||||
]
|
||||
check("new playlist present in saved file", len(found) == 1)
|
||||
if found:
|
||||
node = found[0]
|
||||
check("renamed correctly", node.name == "Konduktor Test 2")
|
||||
check("ENTRIES attr synced to 5", node.playlist.entries == 5)
|
||||
saved_keys = [e.primarykey.key for e in node.playlist.entry]
|
||||
check("entries reordered correctly", saved_keys == reordered)
|
||||
|
||||
print("== reload + delete ==")
|
||||
client.post("/api/reload")
|
||||
pls2 = flat(client.get("/api/playlists").json())
|
||||
check("new playlist visible after reload", any(n["id"] == new_uuid for n in pls2))
|
||||
client.delete(f"/api/playlists/{new_uuid}")
|
||||
res2 = client.post("/api/save").json()
|
||||
coll2 = TraktorCollection(path=WORK)
|
||||
still = [
|
||||
n for n in walk(coll2.nml.playlists.node)
|
||||
if n.type == "PLAYLIST" and n.playlist and n.playlist.uuid == new_uuid
|
||||
]
|
||||
check("playlist gone after delete+save", len(still) == 0)
|
||||
check("COLLECTION still byte-identical", collection_span(WORK.read_bytes()) == collection_before)
|
||||
|
||||
print("== original untouched ==")
|
||||
check(
|
||||
"original collection.nml never modified",
|
||||
(REAL.stat().st_size, REAL.stat().st_mtime) == REAL_STAT,
|
||||
)
|
||||
|
||||
shutil.rmtree(work_dir, ignore_errors=True)
|
||||
print("\nRESULT:", "FAILED" if check.failed else "ALL PASSED")
|
||||
sys.exit(1 if check.failed else 0)
|
||||
@@ -0,0 +1,133 @@
|
||||
"""Regression guard for save fidelity — keeps playlist diffs minimal.
|
||||
|
||||
This is the test that would have caught the lxml reformatting bug. It asserts
|
||||
two invariants against a COPY of the real collection:
|
||||
|
||||
A. NO-OP SAVE IS BYTE-IDENTICAL.
|
||||
Loading and saving with zero edits must reproduce the file exactly. Any
|
||||
serialization change (lxml, a different render pipeline, dropped
|
||||
float-format/layout post-processing) breaks this immediately.
|
||||
|
||||
B. AN EDIT IS FULLY LOCALIZED.
|
||||
Editing one playlist must change ONLY that playlist's block. Everything
|
||||
else in the file — other playlists, folders, smart playlists, and the
|
||||
entire COLLECTION — must stay byte-for-byte identical.
|
||||
|
||||
Run: `python test_save_fidelity.py` in the backend venv (see run_tests.sh).
|
||||
"""
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
|
||||
|
||||
from konduktor.collection_service import CollectionService # noqa: E402
|
||||
from konduktor.playlist_store import PlaylistStore # 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
|
||||
|
||||
|
||||
def playlist_block_span(data: bytes, uuid: str):
|
||||
"""Byte span of a playlist's <PLAYLIST …UUID="…">…</PLAYLIST> block."""
|
||||
i = data.find(f'UUID="{uuid}"'.encode())
|
||||
start = data.rfind(b"<PLAYLIST ", 0, i)
|
||||
end = data.find(b"</PLAYLIST>", i) + len(b"</PLAYLIST>")
|
||||
return start, end
|
||||
|
||||
|
||||
def tag_lines(b: bytes) -> list[str]:
|
||||
return b.replace(b"><", b">\n<").decode("utf-8", "replace").splitlines()
|
||||
|
||||
|
||||
def diff_count(a: bytes, b: bytes) -> int:
|
||||
import difflib
|
||||
|
||||
la, lb = tag_lines(a), tag_lines(b)
|
||||
return sum(
|
||||
1
|
||||
for d in difflib.unified_diff(la, lb, n=0)
|
||||
if d[:1] in "+-" and not d.startswith(("+++", "---"))
|
||||
)
|
||||
|
||||
|
||||
# ---- Invariant A: no-op save is byte-identical ------------------------
|
||||
print("== A. no-op save is byte-identical ==")
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
work = Path(d) / "collection.nml"
|
||||
shutil.copy2(REAL, work)
|
||||
before = work.read_bytes()
|
||||
store = PlaylistStore(work)
|
||||
store.save() # no edits
|
||||
after = work.read_bytes()
|
||||
check("whole file identical after no-op save", before == after)
|
||||
if before != after:
|
||||
for i, (x, y) in enumerate(zip(before, after)):
|
||||
if x != y:
|
||||
check.detail = i
|
||||
print(f" first byte diff @ {i}")
|
||||
print(" before:", before[max(0, i - 50) : i + 50])
|
||||
print(" after :", after[max(0, i - 50) : i + 50])
|
||||
break
|
||||
|
||||
# ---- Invariant B: an edit is fully localized --------------------------
|
||||
print("== B. edit touches only the edited playlist ==")
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
work = Path(d) / "collection.nml"
|
||||
shutil.copy2(REAL, work)
|
||||
original = work.read_bytes()
|
||||
|
||||
svc = CollectionService(work)
|
||||
store = PlaylistStore(work)
|
||||
|
||||
def walk(n):
|
||||
yield n
|
||||
if n.subnodes:
|
||||
for c in n.subnodes.node:
|
||||
yield from walk(c)
|
||||
|
||||
target = next(
|
||||
n for n in walk(store._root()) if n.playlist and n.playlist.uuid and len(n.playlist.entry or []) >= 5
|
||||
)
|
||||
uuid = target.playlist.uuid
|
||||
keys = store.entry_keys(uuid)
|
||||
|
||||
store.set_entries(uuid, svc.entries_for(list(reversed(keys))))
|
||||
store.save()
|
||||
edited = work.read_bytes()
|
||||
|
||||
check("file actually changed", original != edited)
|
||||
|
||||
# Blank out the edited playlist's block in both; the remainder must match.
|
||||
os_, oe = playlist_block_span(original, uuid)
|
||||
es_, ee = playlist_block_span(edited, uuid)
|
||||
rest_original = original[:os_] + b"@@BLOCK@@" + original[oe:]
|
||||
rest_edited = edited[:es_] + b"@@BLOCK@@" + edited[ee:]
|
||||
check(
|
||||
"everything outside the edited playlist is byte-identical",
|
||||
rest_original == rest_edited,
|
||||
)
|
||||
|
||||
# A pure reorder must preserve the exact set of lines in the block (only
|
||||
# their order changes). If the block were reformatted, the multiset differs.
|
||||
before_lines = sorted(tag_lines(original[os_:oe]))
|
||||
after_lines = sorted(tag_lines(edited[es_:ee]))
|
||||
check(
|
||||
"edited block is a pure reorder (line multiset unchanged, no reformat)",
|
||||
before_lines == after_lines,
|
||||
)
|
||||
n = diff_count(original[os_:oe], edited[es_:ee])
|
||||
print(f" edited-block changed lines: {n} (reordered {len(keys)} entries)")
|
||||
|
||||
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
Reference in new issue
Block a user