mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Implemented playlist reorganizing
This commit is contained in:
1 parent
9f79f5a849
commit
e5c7b67626
19 files changed
+515
-12
No files matched your search
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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))
|
||||
|
||||
|
||||
@@ -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."""
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 ----------------------------------------
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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]
|
||||
|
||||
Reference in new issue
Block a user