diff --git a/backend/konduktor/adapters/onelibrary/adapter.py b/backend/konduktor/adapters/onelibrary/adapter.py index 002fdea..46919d8 100644 --- a/backend/konduktor/adapters/onelibrary/adapter.py +++ b/backend/konduktor/adapters/onelibrary/adapter.py @@ -193,6 +193,7 @@ class OneLibraryAdapter: can_rename=writable, can_delete=writable, can_contain_children=kind == "folder", + can_move=writable, ) parent = str(getattr(r, "playlist_id_parent", 0) or 0) parents[node_id] = "root" if parent in ("0", "", "None") else parent @@ -425,6 +426,10 @@ class OneLibraryAdapter: self._require_writable("Deleting playlists") self._store.delete_playlist(node_id) + def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str: + self._require_writable("Moving playlists") + return self._store.move_playlist(node_id, parent_id, index) + def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: self._require_writable("Editing playlists") return self._store.set_playlist_entries(node_id, track_ids) diff --git a/backend/konduktor/adapters/onelibrary/store.py b/backend/konduktor/adapters/onelibrary/store.py index 5923390..e36d7ff 100644 --- a/backend/konduktor/adapters/onelibrary/store.py +++ b/backend/konduktor/adapters/onelibrary/store.py @@ -652,6 +652,45 @@ class OneLibraryStore(ReplaceGridCommands): db.flush() self._journal.record("playlist", "delete", name) + def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str: + """Move a node to `index` among `parent_id`'s children, renumbering + `sequenceNo` from 0 in both parents as create and delete do. The + Device Library's playlist tree follows at Save (`device_library` + mirrors parent and sort from these rows).""" + db = self._require_db() + row = self._playlist(node_id) + dest = 0 + if parent_id: + folder = self._playlist(parent_id) + if int(folder.attribute or 0) != ATTRIBUTE_FOLDER: + raise InvalidCommand("A playlist can only be moved into a folder") + dest = int(folder.playlist_id) + ancestor = folder + while ancestor is not None: + if int(ancestor.playlist_id) == int(row.playlist_id): + raise InvalidCommand("A folder cannot be moved into itself") + up = int(ancestor.playlist_id_parent or 0) + ancestor = self._playlist(str(up)) if up else None + source = int(row.playlist_id_parent or 0) + siblings = self._siblings(dest, excluding=row.playlist_id) + index = max(0, min(int(index), len(siblings))) + order = siblings[:index] + [row] + siblings[index:] + if source == dest and [r.playlist_id for r in order] == [ + r.playlist_id for r in self._siblings(dest) + ]: + return str(row.playlist_id) + row.playlist_id_parent = dest + for n, r in enumerate(order): + if int(r.sequenceNo or 0) != n: + r.sequenceNo = n + if source != dest: + for n, r in enumerate(self._siblings(source, excluding=row.playlist_id)): + if int(r.sequenceNo or 0) != n: + r.sequenceNo = n + db.flush() + self._journal.record("playlist", "move", row.name) + return str(row.playlist_id) + def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: """Replace a playlist's contents, in order, numbered from 1 (measured).""" from pyrekordbox.devicelib_plus import models diff --git a/backend/konduktor/adapters/rekordbox/adapter.py b/backend/konduktor/adapters/rekordbox/adapter.py index df988c3..4f67706 100644 --- a/backend/konduktor/adapters/rekordbox/adapter.py +++ b/backend/konduktor/adapters/rekordbox/adapter.py @@ -172,6 +172,7 @@ class RekordboxAdapter: can_rename=writable, can_delete=writable, can_contain_children=kind == "folder", + can_move=writable, ) parent = str(r.ParentID or "root") parents[node_id] = "root" if parent in ("0", "", "root", "None") else parent @@ -276,6 +277,10 @@ class RekordboxAdapter: self._require_writable("Deleting playlists") self._store.delete_playlist(node_id) + def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str: + self._require_writable("Moving playlists") + return self._store.move_playlist(node_id, parent_id, index) + def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: self._require_writable("Editing playlists") return self._store.set_playlist_entries(node_id, track_ids) diff --git a/backend/konduktor/adapters/rekordbox/store.py b/backend/konduktor/adapters/rekordbox/store.py index e676638..7264e32 100644 --- a/backend/konduktor/adapters/rekordbox/store.py +++ b/backend/konduktor/adapters/rekordbox/store.py @@ -608,6 +608,79 @@ class RekordboxStore(ReplaceGridCommands): self._db.delete_playlist(row) self._journal.record("playlist", "delete", name) + def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str: + """Move a node to `index` among `parent_id`'s visible children. + + Not pyrekordbox's `move_playlist`: its `parent=None` means "keep the + parent", so nothing can be moved to the top level with it. The same + writes are made here — `ParentID`, the moved row's `updated_at`, and + `Seq` renumbered from 1 in both parents (only rows whose `Seq` changes + are touched) — plus `masterPlaylists6.xml`'s `ParentId`, which + pyrekordbox's version leaves stale. Rekordbox's hidden working lists + share the table and the numbering, so `index` is placed relative to + the VISIBLE siblings and the hidden ones keep their order around it.""" + import datetime + + from pyrekordbox.masterdb.database import SPECIAL_PLAYLIST_IDS + + t = self._tables + row = self._playlist(node_id) + dest = self._playlist(parent_id) if parent_id else None + if dest is not None and int(dest.Attribute or 0) != int(t.PlaylistType.FOLDER): + raise InvalidCommand("A playlist can only be moved into a folder") + ancestor = dest + while ancestor is not None: + if str(ancestor.ID) == str(row.ID): + raise InvalidCommand("A folder cannot be moved into itself") + up = str(ancestor.ParentID or "root") + ancestor = None if up in ("root", "0", "") else self._playlist(up) + + def children(key: str) -> list: + return ( + self._db.session.query(t.DjmdPlaylist) + .filter(t.DjmdPlaylist.ParentID == key) + .filter(t.DjmdPlaylist.rb_local_deleted == 0) + .order_by(t.DjmdPlaylist.Seq) + .all() + ) + + old_key = str(row.ParentID or "root") + new_key = str(dest.ID) if dest is not None else "root" + siblings = [c for c in children(new_key) if str(c.ID) != str(row.ID)] + visible = [c for c in siblings if str(c.ID) not in SPECIAL_PLAYLIST_IDS] + index = max(0, min(int(index), len(visible))) + if index < len(visible): + at = siblings.index(visible[index]) + else: + at = siblings.index(visible[-1]) + 1 if visible else len(siblings) + order = siblings[:at] + [row] + siblings[at:] + if old_key == new_key and [str(c.ID) for c in order] == [ + str(c.ID) for c in children(new_key) + ]: + return str(row.ID) + + row.ParentID = new_key + with self._db.registry.disabled(): + row.updated_at = datetime.datetime.now() + for n, c in enumerate(order, start=1): + if c.Seq != n: + c.Seq = n + if old_key != new_key: + for n, c in enumerate( + (c for c in children(old_key) if str(c.ID) != str(row.ID)), start=1 + ): + if c.Seq != n: + c.Seq = n + xml = getattr(self._db, "playlist_xml", None) + if xml is not None: + try: + xml.update(row.ID, parent_id=new_key) + except ValueError: + pass # a playlist the XML never listed: nothing to keep in step + self._db.flush() + self._journal.record("playlist", "move", row.Name) + return str(row.ID) + def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: """Replace a playlist's contents, in the given order. diff --git a/backend/konduktor/adapters/remote/adapter.py b/backend/konduktor/adapters/remote/adapter.py index 4619309..949557f 100644 --- a/backend/konduktor/adapters/remote/adapter.py +++ b/backend/konduktor/adapters/remote/adapter.py @@ -194,6 +194,9 @@ class RemoteAdapter: def delete_playlist(self, node_id): return self._call("delete_playlist", node_id=node_id) + def move_playlist(self, node_id, parent_id, index): + return self._call("move_playlist", node_id=node_id, parent_id=parent_id, index=index) + def set_playlist_entries(self, node_id, track_ids): return self._call("set_playlist_entries", node_id=node_id, track_ids=list(track_ids)) diff --git a/backend/konduktor/adapters/traktor/adapter.py b/backend/konduktor/adapters/traktor/adapter.py index 6f74b1b..d49cfaa 100644 --- a/backend/konduktor/adapters/traktor/adapter.py +++ b/backend/konduktor/adapters/traktor/adapter.py @@ -131,6 +131,10 @@ class TraktorAdapter: with _translate(): self._store.delete_playlist(node_id) + def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str: + with _translate(): + return self._store.move_playlist(node_id, parent_id, index) + def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: """Replace a playlist's contents. The adapter resolves each id to its native entry kind, so callers never see Traktor's STEM/TRACK split.""" diff --git a/backend/konduktor/adapters/traktor/capabilities.py b/backend/konduktor/adapters/traktor/capabilities.py index e967265..c4c0488 100644 --- a/backend/konduktor/adapters/traktor/capabilities.py +++ b/backend/konduktor/adapters/traktor/capabilities.py @@ -74,7 +74,12 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities: "need a manual Import Cover Art to show up." ), ), - playlists=PlaylistCapabilities(folders=True, smart="read_only", reorder=True), + playlists=PlaylistCapabilities( + folders=True, smart="read_only", reorder=True, + # A playlist's entries are a plain list of PRIMARYKEYs, and Traktor + # itself adds a track twice when asked. + duplicates=True, + ), save=SaveCapabilities( app_name="Traktor", library_label="collection.nml", diff --git a/backend/konduktor/adapters/traktor/store.py b/backend/konduktor/adapters/traktor/store.py index 670acc5..eb89e28 100644 --- a/backend/konduktor/adapters/traktor/store.py +++ b/backend/konduktor/adapters/traktor/store.py @@ -160,11 +160,13 @@ class TraktorStore: can_reorder=True, can_rename=True, can_delete=True, + can_move=True, ) if ntype == "SMARTLIST" or node.smartplaylist is not None: # Rule-based, so it has no static entry list to show or edit. return PlaylistNode( - id="sl:" + "/".join(parent_path + [name]), name=name, kind="smart" + id="sl:" + "/".join(parent_path + [name]), name=name, kind="smart", + can_move=True, ) path = parent_path + [name] return PlaylistNode( @@ -175,6 +177,7 @@ class TraktorStore: can_contain_children=True, can_rename=True, can_delete=True, + can_move=True, ) @staticmethod @@ -348,6 +351,79 @@ class TraktorStore: self._note("playlist-delete", node.name) self.dirty = True + def _find_node(self, node_id: str) -> Nodetype: + """Any node by its id: a playlist's UUID, a folder's `fld:` path or a + smart playlist's `sl:` path (its folder path plus its own name).""" + if node_id.startswith("fld:"): + return self._find_folder(node_id) + if node_id.startswith("sl:"): + *folders, name = node_id[len("sl:"):].split("/") + parent = self._find_folder("fld:" + "/".join(folders) if folders else None) + match = next( + (c for c in self._children(parent) + if (c.type == "SMARTLIST" or c.smartplaylist is not None) and c.name == name), + None, + ) + if match is None: + raise PlaylistError(f"Smart playlist not found: {node_id}") + return match + node = self._find_playlist_node(node_id) + if node is None: + raise PlaylistError(f"Playlist not found: {node_id}") + return node + + def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str: + """Move a node to `index` among `parent_id`'s children (counted without + it) and return its id afterwards — a folder's and a smart playlist's id + is their path of names, so moving one changes it (and its subtree's). + + A folder or smart playlist landing beside a namesake of its own kind is + refused, as rename refuses it: the two paths would be one, and one of + them unaddressable. Playlists are UUIDs, so their names may repeat.""" + with self._lock: + node = self._find_node(node_id) + if node is self._root(): + raise PlaylistError("Cannot move the root folder") + dest = self._find_folder(parent_id) + if dest is node or any(n is dest for n in self._iter_nodes(node)): + raise PlaylistError("A folder cannot be moved into itself") + is_folder = node.playlist is None and node.smartplaylist is None and ( + node.type or "FOLDER") == "FOLDER" + is_smart = node.type == "SMARTLIST" or node.smartplaylist is not None + if is_folder or is_smart: + kind = "folder" if is_folder else "smart playlist" + for c in self._children(dest): + same_kind = ( + (c.type or "FOLDER") == "FOLDER" and c.playlist is None + and c.smartplaylist is None + ) if is_folder else (c.type == "SMARTLIST" or c.smartplaylist is not None) + if c is not node and same_kind and c.name == node.name: + raise PlaylistError(f'There is already a {kind} called "{node.name}" there') + source = self._find_parent_of(node) + if source is None: + raise PlaylistError("Cannot move a top-level node") + siblings = [c for c in self._children(dest) if c is not node] + index = max(0, min(int(index), len(siblings))) + if source is dest and self._children(dest).index(node) == index: + return self._node_id(node, parent_id) # already there + source.subnodes.node.remove(node) + source.subnodes.count = len(source.subnodes.node) + if dest.subnodes is None: + dest.subnodes = Subnodestype(node=[], count=0) + dest.subnodes.node.insert(index, node) + dest.subnodes.count = len(dest.subnodes.node) + self._note("playlist-move", node.name) + self.dirty = True + return self._node_id(node, parent_id) + + def _node_id(self, node: Nodetype, parent_id: str | None) -> str: + """The id `_to_model` gives `node` inside the folder `parent_id`.""" + if node.playlist is not None: + return node.playlist.uuid + prefix = parent_id[len("fld:"):] if parent_id and parent_id.startswith("fld:") else "" + tag = "sl:" if (node.type == "SMARTLIST" or node.smartplaylist is not None) else "fld:" + return tag + "/".join(p for p in (prefix, node.name or "(unnamed)") if p) + def set_entries(self, playlist_uuid: str, entries: list[tuple[str, str]]) -> None: with self._lock: node = self._find_playlist_node(playlist_uuid) diff --git a/backend/konduktor/core/adapter.py b/backend/konduktor/core/adapter.py index 2c24fda..5ccf296 100644 --- a/backend/konduktor/core/adapter.py +++ b/backend/konduktor/core/adapter.py @@ -247,6 +247,12 @@ class LibraryAdapter(Protocol): def create_folder(self, name: str, parent_id: str | None = None) -> str: ... def rename_playlist(self, node_id: str, name: str) -> None: ... def delete_playlist(self, node_id: str) -> None: ... + # Move a node (playlist, folder or smart playlist) to `index` among + # `parent_id`'s children (None = the top level), counted with the moved + # node left out. Returns the node's id AFTER the move: an id is opaque, and + # on a platform that addresses a folder by its path it changes. A folder + # cannot go into itself or a descendant (InvalidCommand). + def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str: ... def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: ... # ---- commands: adding tracks ---------------------------------------- diff --git a/backend/konduktor/core/capabilities.py b/backend/konduktor/core/capabilities.py index 1c5d22b..abd065c 100644 --- a/backend/konduktor/core/capabilities.py +++ b/backend/konduktor/core/capabilities.py @@ -106,6 +106,9 @@ class PlaylistCapabilities(BaseModel): folders: bool = False smart: Literal["none", "read_only"] = "none" reorder: bool = False + # A playlist can hold the same track more than once. Where it cannot, a + # drop of tracks already there skips them rather than asking. + duplicates: bool = False class PathCapabilities(BaseModel): diff --git a/backend/konduktor/core/model.py b/backend/konduktor/core/model.py index 4dd720d..c6c9716 100644 --- a/backend/konduktor/core/model.py +++ b/backend/konduktor/core/model.py @@ -130,6 +130,9 @@ class PlaylistNode(BaseModel): can_rename: bool = False can_delete: bool = False can_contain_children: bool = False # a valid parent for a new playlist + # Can be dragged elsewhere in the tree (`move_playlist`): reordered among + # its siblings or moved into another folder. + can_move: bool = False PlaylistNode.model_rebuild() diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index 016be99..ae70bdf 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -92,6 +92,8 @@ from .schemas import ( RemapResult, RenamePlaylist, SaveResult, + AddEntries, + MovePlaylist, SetEntries, SourceCandidate, SourceStatus, @@ -1227,6 +1229,7 @@ def create_playlist(body: CreatePlaylist) -> PlaylistNode: can_reorder=True, can_rename=True, can_delete=True, + can_move=True, ) @@ -1241,6 +1244,7 @@ def create_folder(body: CreatePlaylist) -> PlaylistNode: can_contain_children=True, can_rename=True, can_delete=True, + can_move=True, ) @@ -1265,17 +1269,35 @@ def set_entries(playlist_uuid: str, body: SetEntries) -> dict: return {"status": "updated", "id": playlist_uuid, "count": n} +@app.post("/api/playlists/move") +def move_playlist(body: MovePlaylist) -> dict: + """Move a playlist, folder or smart playlist in the tree. Answers the + node's id AFTER the move, which on some platforms is not the one sent.""" + new_id = require_adapter().move_playlist(body.node_id, body.parent_id, body.index) + return {"status": "moved", "id": new_id} + + @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).""" +def add_entries(playlist_uuid: str, body: AddEntries) -> dict: + """Append tracks to a playlist. Tracks already there are skipped, added + again, or — `duplicates="ask"` — counted with nothing changed (see + `AddEntries`). `duplicates` in the answer is how many there were.""" a = require_adapter() current = a.playlist_entries(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] - n = a.set_playlist_entries(playlist_uuid, current + added) - return {"status": "added", "id": playlist_uuid, "added": len(added), "count": n} + dupes = [tid for tid in body.track_ids if tid in have] + mode = body.duplicates + if mode != "skip" and not a.capabilities().playlists.duplicates: + mode = "skip" + if mode == "ask" and dupes: + return {"status": "duplicates", "id": playlist_uuid, "added": 0, + "duplicates": len(dupes), "count": len(current)} + added = list(body.track_ids) if mode == "add" else [t for t in body.track_ids if t not in have] + n = a.set_playlist_entries(playlist_uuid, current + added) if added else len(current) + return {"status": "added", "id": playlist_uuid, "added": len(added), + "duplicates": len(dupes), "count": n} @app.patch("/api/tracks") diff --git a/backend/konduktor/remote_protocol.py b/backend/konduktor/remote_protocol.py index 30de27e..9a9b3f3 100644 --- a/backend/konduktor/remote_protocol.py +++ b/backend/konduktor/remote_protocol.py @@ -73,7 +73,7 @@ _READ = ( ) _MUTATING = ( "create_playlist", "create_folder", "rename_playlist", "delete_playlist", - "set_playlist_entries", "remove_tracks", "set_track_metadata", "set_key", "set_cue", + "move_playlist", "set_playlist_entries", "remove_tracks", "set_track_metadata", "set_key", "set_cue", "set_cue_type", "set_cue_color", "delete_cue", "place_cues", "add_grid_marker", "move_grid_marker", "set_grid_marker_bpm", "delete_grid_marker", "replace_grid", "set_analysed_grid", "delete_grid", "set_grid_lock", "add_tracks", diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index 6f9b55c..0ddbf7f 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -21,6 +21,20 @@ class SetEntries(BaseModel): track_ids: list[str] # ordered; full desired contents of the playlist +class AddEntries(BaseModel): + track_ids: list[str] + # Tracks the playlist already holds: "skip" them, "add" them again (only + # where `playlists.duplicates`, else skipped), or "ask" — change nothing and + # report how many, so the UI can ask and send again with skip/add. + duplicates: Literal["skip", "add", "ask"] = "skip" + + +class MovePlaylist(BaseModel): + node_id: str + parent_id: str | None = None # None = the top level + index: int # among the new parent's children, not counting the node + + class EditTrack(BaseModel): track_id: str fields: dict[str, str | int | None] diff --git a/backend/test_onelibrary_fidelity.py b/backend/test_onelibrary_fidelity.py index 4a8eccf..dfb2c99 100644 --- a/backend/test_onelibrary_fidelity.py +++ b/backend/test_onelibrary_fidelity.py @@ -264,6 +264,44 @@ seqs = sorted(r["sequenceNo"] for r in after["playlist"].values() if r["playlist check("and closes the gap among its siblings", seqs == list(range(len(seqs))), str(seqs)) a.close() +print("== moving playlists (sidebar drag and drop) ==") +drive = fresh_drive() +a = OneLibraryAdapter(drive) +folder = a.create_folder("Gigs") +probe = a.create_playlist("Probe") +a.save() +before = dump(db_of(drive)) +check("every node offers can_move", all(n.can_move for n in a.playlist_tree())) +demos = next(n for n in a.playlist_tree() if n.name == "demos") +a.move_playlist(demos.id, folder, 0) +a.move_playlist(probe, None, 1) +tree = a.playlist_tree() +check("a playlist moved into a folder is its child", + [c.id for c in next(n for n in tree if n.id == folder).children] == [demos.id]) +check("a playlist moves to the index asked for", [n.id for n in tree] == [folder, probe], + str([n.name for n in tree])) +check("a folder cannot be moved into itself", + _raises(lambda: a.move_playlist(folder, folder, 0), InvalidCommand)) +check("nor into a playlist", _raises(lambda: a.move_playlist(probe, demos.id, 0), InvalidCommand)) +a.save() +after = dump(db_of(drive)) +changes = diff(before, after) +check("only playlist rows change, by UPDATE", + {(t, kind) for t, _, kind, _ in changes} == {("playlist", "UPDATE")}, describe(changes)) +check("only parent and sequenceNo columns change", + {c for *_, f in changes for c in f} <= {"playlist_id_parent", "sequenceNo"}, + str([f for *_, f in changes])) +for parent in (0, int(folder)): + seqs = sorted(r["sequenceNo"] for r in after["playlist"].values() if r["playlist_id_parent"] == parent) + check(f"sequenceNo stays 0..n-1 under {parent}", seqs == list(range(len(seqs))), str(seqs)) +a.close() +reopened = OneLibraryAdapter(drive) +check("the move round-trips through a reopen", + [c.id for c in next(n for n in reopened.playlist_tree() if n.id == folder).children] == [demos.id]) +reopened.move_playlist(probe, None, 1) +check("moving a node onto its own place is not an edit", reopened.dirty is False) +reopened.close() + # ---- E: a stick's hazards ------------------------------------------------------------ print("== another app wrote the drive since it was opened ==") drive = fresh_drive() diff --git a/backend/test_phase3.py b/backend/test_phase3.py index 9a966f2..1ffed2c 100644 --- a/backend/test_phase3.py +++ b/backend/test_phase3.py @@ -172,6 +172,43 @@ check("COLLECTION still byte-identical after folder delete", check("unknown folder is 404", client.delete("/api/playlists/fld:No Such Folder").status_code == 404) +print("== drag and drop: add with duplicates, move ==") +target = client.post("/api/playlists", json={"name": "Konduktor Drop"}).json()["id"] +first, rest = track_ids[:2], track_ids[2:4] +r = client.post(f"/api/playlists/{target}/add", json={"track_ids": first}).json() +check("a plain add appends", r["added"] == 2 and r["duplicates"] == 0) +r = client.post(f"/api/playlists/{target}/add", + json={"track_ids": first[:1] + rest, "duplicates": "ask"}).json() +check("'ask' with a duplicate changes nothing and counts it", + r["status"] == "duplicates" and r["duplicates"] == 1 + and client.get(f"/api/playlists/{target}/tracks").json().__len__() == 2) +r = client.post(f"/api/playlists/{target}/add", + json={"track_ids": first[:1] + rest, "duplicates": "skip"}).json() +check("'skip' adds only the new ones", r["added"] == 2 and r["duplicates"] == 1 and r["count"] == 4) +r = client.post(f"/api/playlists/{target}/add", + json={"track_ids": first[:1], "duplicates": "add"}).json() +check("'add' adds it again (Traktor can hold a track twice)", r["added"] == 1 and r["count"] == 5) +r = client.post(f"/api/playlists/{target}/add", + json={"track_ids": track_ids[4:5], "duplicates": "ask"}).json() +check("'ask' with nothing duplicated simply adds", r["status"] == "added" and r["added"] == 1) +check("capabilities say Traktor holds duplicates", + client.get("/api/capabilities").json()["playlists"]["duplicates"] is True) + +box = client.post("/api/playlists/folders", json={"name": "Konduktor Drop Box"}).json()["id"] +r = client.post("/api/playlists/move", json={"node_id": target, "parent_id": box, "index": 0}) +check("move answers the playlist's id", r.status_code == 200 and r.json()["id"] == target) +r = client.post("/api/playlists/move", json={"node_id": box, "parent_id": None, "index": 0}) +check("moving a folder answers its (path) id", r.json()["id"] == box) +check("…and it is first at the top level", client.get("/api/playlists").json()[0]["id"] == box) +r = client.post("/api/playlists/move", json={"node_id": box, "parent_id": box, "index": 0}) +check("a folder into itself is a 400", r.status_code == 400) +r = client.post("/api/playlists/move", json={"node_id": "nope", "parent_id": None, "index": 0}) +check("an unknown node is a 404", r.status_code == 404) +client.delete(f"/api/playlists/{box}") +client.post("/api/save") +check("COLLECTION still byte-identical after drops and moves", + collection_span(WORK.read_bytes()) == collection_before) + print("== original untouched ==") check( "original collection.nml never modified", diff --git a/backend/test_rekordbox_fidelity.py b/backend/test_rekordbox_fidelity.py index 3518f4e..8fd0ae9 100644 --- a/backend/test_rekordbox_fidelity.py +++ b/backend/test_rekordbox_fidelity.py @@ -31,6 +31,7 @@ os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-rbfid-appd from konduktor.adapters.rekordbox import discovery # noqa: E402 from konduktor.adapters.rekordbox.adapter import RekordboxAdapter # noqa: E402 +from konduktor.core.adapter import InvalidCommand # noqa: E402 failed = False @@ -302,6 +303,51 @@ with tempfile.TemporaryDirectory() as d: folder_reopened.close() after_folder.close() + # ---- E2: moving nodes in the tree (sidebar drag and drop) ----------- + print("== E2: move_playlist reorders and reparents, touching only playlist rows ==") + clean_copy(REAL, work, closing=[adapter, again, final, reopened]) + adapter = RekordboxAdapter(work) + folder_id = adapter.create_folder("Konduktor Move Folder") + a_id = adapter.create_playlist("Konduktor Move A") + b_id = adapter.create_playlist("Konduktor Move B") + adapter.save() + adapter.close() + before = dump(work) + adapter = RekordboxAdapter(work) + check("every node offers can_move", all(n.can_move for n in adapter.playlist_tree())) + adapter.move_playlist(b_id, folder_id, 0) + adapter.move_playlist(a_id, None, 0) + tree = adapter.playlist_tree() + check("a playlist moved into a folder is its child", + [c.id for c in next(n for n in tree if n.id == folder_id).children] == [b_id]) + check("a playlist moved to index 0 is first at the top level", tree[0].id == a_id, + [n.name for n in tree[:3]]) + try: + adapter.move_playlist(folder_id, folder_id, 0) + check("a folder cannot be moved into itself", False) + except InvalidCommand: + check("a folder cannot be moved into itself", True) + adapter.save() + changes = diff(before, dump(work)) + check("only djmdPlaylist rows and the counter change", + {t for t, _, _, _ in changes} <= {"djmdPlaylist", "agentRegistry"}, describe(changes)) + rows = dump(work)["djmdPlaylist"] + for parent in ("root", folder_id): + seqs = sorted(int(r["Seq"]) for r in rows.values() + if str(r["ParentID"]) == parent and not r["rb_local_deleted"]) + check(f"Seq stays 1..n under {parent}", seqs == list(range(1, len(seqs) + 1)), seqs) + adapter.close() + reopened = RekordboxAdapter(work) + tree = reopened.playlist_tree() + check("the moves round-trip through a reopen", + tree[0].id == a_id + and [c.id for c in next(n for n in tree if n.id == folder_id).children] == [b_id]) + reopened.move_playlist(b_id, None, len(tree)) + check("a playlist moved out of a folder lands last at the top level", + reopened.playlist_tree()[-1].id == b_id) + reopened.close() + again = final = RekordboxAdapter(work) + # ---- F: a cue write touches the cue row AND its mirror --------------- print("== F: a hot cue write is localized, and keeps the mirror in step ==") clean_copy(REAL, work, closing=[adapter, again, final, reopened]) diff --git a/backend/test_save_fidelity.py b/backend/test_save_fidelity.py index b21d6c1..1c1af1a 100644 --- a/backend/test_save_fidelity.py +++ b/backend/test_save_fidelity.py @@ -1086,5 +1086,110 @@ with tempfile.TemporaryDirectory() as d: check("N: …and written in Camelot", target.info.key == "1A", target.info.key) +# ---- O: moving playlists in the tree ---------------------------------- +# Drag and drop in the sidebar. Moving a node relocates its whole block, so +# the guarantee is: the COLLECTION is untouched, the tree reads back as moved, +# and moving it back reproduces the original bytes exactly. +print("\n== O. move_playlist ==") + + +def _collection_span(data: bytes) -> bytes: + return data[data.find(b"")] + + +def _find(nodes, name): + for n in nodes: + if n.name == name: + return n + hit = _find(n.children, name) + if hit is not None: + return hit + return None + + +with tempfile.TemporaryDirectory() as d: + work = Path(d) / "collection.nml" + shutil.copy2(REAL, work) + before = work.read_bytes() + store = TraktorStore(work) + roots = store.tree() + folders = [n for n in roots if n.kind == "folder" and n.children] + loose = [n for n in roots if n.kind == "playlist"] + if len(folders) < 2 or len(loose) < 2: + print(" [SKIP] the reference collection has too few top-level nodes") + else: + src, dst = folders[0], folders[1] + pl = next((c for c in src.children if c.kind == "playlist"), None) or loose[0] + home = _find(roots, pl.name) + home_parent = next((f.id for f in roots if any(c.id == pl.id for c in f.children)), None) + home_index = ([c.id for c in (src.children if home_parent else roots)].index(pl.id)) + check("O: every node offers can_move", all(n.can_move for n in roots)) + + # A playlist into another folder, at a position. + new_id = store.move_playlist(pl.id, dst.id, 1) + tree = store.tree() + moved_into = next(n for n in tree if n.id == dst.id) + check("O: a playlist keeps its id when moved", new_id == pl.id, new_id) + check("O: …and lands at the index asked for", + len(moved_into.children) > 1 and moved_into.children[1].id == pl.id, + [c.name for c in moved_into.children[:3]]) + store.save() + moved = work.read_bytes() + check("O: the COLLECTION is untouched by a move", + _collection_span(moved) == _collection_span(before)) + reread = TraktorStore(work).tree() + check("O: the move round-trips through a save", + any(c.id == pl.id for c in next(n for n in reread if n.id == dst.id).children)) + + # …and back again: byte-identical to the original. + store.move_playlist(pl.id, home_parent, home_index) + store.save() + check("O: moving it back restores the original bytes", work.read_bytes() == before, + f"{diff_count(before, work.read_bytes())} lines differ") + + # A folder moves with its subtree, and its id (a path) changes with it. + new_folder = store.move_playlist(src.id, dst.id, 0) + check("O: a moved folder answers its new path id", + new_folder == f"{dst.id}/{src.name}", new_folder) + inner = next(n for n in store.tree() if n.id == dst.id).children[0] + check("O: …and its subtree moved with it", + inner.id == new_folder and len(inner.children) == len(src.children)) + child_ids = [c.id for c in inner.children] + check("O: …children keep addressable ids", + all(c.startswith((new_folder.replace("fld:", "sl:") + "/", new_folder + "/")) + or not c.startswith(("fld:", "sl:")) for c in child_ids), child_ids[:3]) + + # Into itself: refused, nothing changed. + snapshot = store._render() + try: + store.move_playlist(dst.id, new_folder, 0) + check("O: a folder cannot be moved into its own descendant", False) + except PlaylistError: + check("O: a folder cannot be moved into its own descendant", + store._render() == snapshot) + + # A namesake folder in the target: refused (two paths would be one). + store.create_folder(src.name, None) + snapshot = store._render() + try: + store.move_playlist(new_folder, None, 0) + check("O: a folder cannot land beside a namesake", False) + except PlaylistError: + check("O: a folder cannot land beside a namesake", store._render() == snapshot) + + # A smart playlist moves too, by its path id. + smart = next((c for c in inner.children if c.kind == "smart"), None) + if smart is not None: + sid = store.move_playlist(smart.id, None, 0) + check("O: a smart playlist moves and answers its new id", + sid == f"sl:{smart.name}" and store.tree()[0].id == sid, sid) + + # A no-op move leaves the store clean. + fresh = TraktorStore(work) + first = fresh.tree()[0] + fresh.move_playlist(first.id, None, 0) + check("O: moving a node onto its own place is not an edit", not fresh.dirty) + + print("\nRESULT:", "FAILED" if failed else "ALL PASSED") sys.exit(1 if failed else 0) diff --git a/frontend/src/api.ts b/frontend/src/api.ts index c967082..d5a4186 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -83,6 +83,8 @@ export interface PlaylistNode { can_rename: boolean can_delete: boolean can_contain_children: boolean + /** Can be dragged elsewhere in the tree (reordered, or into a folder). */ + can_move: boolean } export type SortField = @@ -270,7 +272,13 @@ export interface Capabilities { /** Added files can be left where they are rather than copied. */ reference: boolean } - playlists: { folders: boolean; smart: 'none' | 'read_only'; reorder: boolean } + playlists: { + folders: boolean + smart: 'none' | 'read_only' + reorder: boolean + /** A playlist can hold the same track twice (else duplicates are skipped). */ + duplicates: boolean + } /** Path mapping / rewriting / the missing-files check apply to this library. */ paths: { remappable: boolean } save: SaveCapabilities @@ -988,12 +996,23 @@ export const api = { send<{ status: string; count: number }>('PUT', `/api/playlists/${encodeURIComponent(nodeId)}/entries`, { track_ids: trackIds, }), - addEntries: (nodeId: string, trackIds: string[]) => - send<{ status: string; added: number; count: number }>( + /** Append tracks. `duplicates` decides tracks already there: skip them, + * add them again (where `playlists.duplicates`), or `ask` — nothing changes + * and the answer's `status: 'duplicates'` says how many, to ask and resend. */ + addEntries: (nodeId: string, trackIds: string[], duplicates: 'skip' | 'add' | 'ask' = 'skip') => + send<{ status: 'added' | 'duplicates'; added: number; duplicates: number; count: number }>( 'POST', `/api/playlists/${encodeURIComponent(nodeId)}/add`, - { track_ids: trackIds }, + { track_ids: trackIds, duplicates }, ), + /** Move a tree node to `index` among `parentId`'s children (null = top + * level), counted without it. Answers its id AFTER the move. */ + movePlaylist: (nodeId: string, parentId: string | null, index: number) => + send<{ status: string; id: string }>('POST', '/api/playlists/move', { + node_id: nodeId, + parent_id: parentId, + index, + }), getPrefs: () => getJSON>('/api/prefs'), patchPrefs: (patch: Record) => send>('PATCH', '/api/prefs', patch),