Implemented cross-platform track color support

This commit is contained in:
patben8 committed 2026-10-17 19:50:56 +02:00
1 parent 0605dbabe6
commit 06361a851f
38 files changed
+547 -34

No files matched your search

@@ -404,6 +404,12 @@ class OneLibraryAdapter:
self._refresh(track_id)
return self._index.get(track_id)
def set_track_color(self, track_id: str, color: str | None) -> Track | None:
self._require_writable("Setting the track colour")
self._store.set_track_color(track_id, color)
self._refresh(track_id)
return self._index.get(track_id)
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
self._refuse("Editing cover art")
@@ -36,7 +36,7 @@ from ...core.capabilities import (
SaveCapabilities,
TrackCapabilities,
)
from ..rekordbox import memory_palette, palette
from ..rekordbox import memory_palette, palette, track_palette
from ..rekordbox.cue_types import MAX_MEMORY_CUES, WRITABLE_CUE_TYPES
# Pads A-H. Unlike `djmdCue.Kind`, the ANLZ slot number is a dense 1-based index,
@@ -87,6 +87,8 @@ def capabilities_for(
addable=not read_only,
removable=not read_only,
key_writable=not read_only,
# `content.color_id`, rekordbox's eight; the pdb row follows at Save.
colors=[] if read_only else list(track_palette.SWATCHES),
places_audio=True,
# `artwork` gates EDITING, which Rekordbox does not do yet either
# (parity). Reading works: `store.cover_art` follows
@@ -121,10 +121,10 @@ def rebuild(existing: bytes, session) -> bytes | None:
# ---- tracks -----------------------------------------------------------------
old_tracks = {pdb.row_id(pdb.TRACKS, r): r for r in pdb.table_rows(existing, pdb.TRACKS)}
want = {}
for (cid, title, artist, remixer, album, genre, label, rating, bpm, year, released,
for (cid, title, artist, remixer, album, genre, label, rating, color, bpm, year, released,
comment, *fresh) in session.execute(text(
"SELECT content_id, title, artist_id_artist, artist_id_remixer, album_id, genre_id, "
"label_id, rating, bpmx100, releaseYear, releaseDate, djComment, "
"label_id, rating, color_id, bpmx100, releaseYear, releaseDate, djComment, "
"path, fileName, fileSize, fileType, bitrate, bitDepth, samplingRate, length, "
"analysisDataFilePath, dateAdded, key_id, image_id FROM content")):
cid = int(cid)
@@ -134,7 +134,8 @@ def rebuild(existing: bytes, session) -> bytes | None:
fields, strings = _fresh_track(cid, *fresh)
fields = {**fields, "artist_id": artist or 0, "remixer_id": remixer or 0,
"album_id": album or 0, "genre_id": genre or 0, "label_id": label or 0,
"rating": max(0, min(5, int(rating or 0))), "tempo": int(bpm or 0),
"rating": max(0, min(5, int(rating or 0))), "color_id": int(color or 0),
"tempo": int(bpm or 0),
"year": int(year or 0)}
strings = {**strings, "title": title or "", "comment": comment or "",
"release_date": released or ""}
@@ -44,7 +44,7 @@ from pathlib import Path
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
from ...core.cue_colors import effective_color
from ..rekordbox import anlz_writer as W
from ..rekordbox import artwork, memory_palette, palette, timebase
from ..rekordbox import artwork, memory_palette, palette, timebase, track_palette
from ..rekordbox.cue_types import MAX_MEMORY_CUES
from ..rekordbox.beatgrid import beats_from_markers
from ..rekordbox.projection import render_key
@@ -209,13 +209,13 @@ class OneLibraryExporter:
con.execute(
"INSERT INTO content (content_id, title, titleForSearch, bpmx100, length, "
"trackNo, artist_id_artist, album_id, genre_id, label_id, key_id, image_id, "
"trackNo, artist_id_artist, album_id, genre_id, label_id, key_id, color_id, image_id, "
"djComment, rating, releaseDate, dateAdded, path, fileName, fileSize, "
"fileType, bitrate, bitDepth, samplingRate, isHotCueAutoLoadOn, "
"isKuvoDeliverStatusOn, masterDbId, masterContentId, "
"analysisDataFilePath, analysedBits, contentLink, hasModified, cueUpdateCount, "
"analysisDataUpdateCount, informationUpdateCount) "
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
(
content_id, track.title, (track.title or "").lower(),
int(round((track.bpm or 0) * 100)) or None, track.length,
@@ -229,6 +229,7 @@ class OneLibraryExporter:
# where the deck expects "Cm". Rendered from the parsed wheel.
self._lookup(con, "key", lookups["key"],
render_key(track.key_wheel, track.key_mode)),
track_palette.id_for(track.color),
image_id,
track.comment, track.rating or 0, track.release_date,
date.today().isoformat(), rel, item.destination.name, size,
@@ -16,6 +16,7 @@ Field conventions are read off a real rekordbox 7 export rather than guessed:
from __future__ import annotations
from ...core.model import GridMarker, Track, TrackCues
from ..rekordbox import track_palette
from ..rekordbox.projection import parse_key
@@ -106,6 +107,8 @@ def to_track(row, drive_path: str | None = None, *, stem: bool = False) -> Track
grid_locked=False, # OneLibrary has no grid lock
# What the FILE is, as the deck plays it — see the Rekordbox projection.
media_kind="stem" if stem else "audio",
color=track_palette.color_for(getattr(row, "color_id", None)),
color_hex=track_palette.hex_for(getattr(row, "color_id", None)),
)
+20 -2
View File
@@ -55,7 +55,7 @@ from ...core.grid_edit import ReplaceGridCommands
from ...core.model import CuePoint
from ... import paths
from . import beatgrid, cues as cue_reader, memory_cues
from ..rekordbox import anlz_file, palette, timebase
from ..rekordbox import anlz_file, palette, timebase, track_palette
from ..rekordbox.cue_types import MAX_MEMORY_CUES
from ..rekordbox import anlz_writer as W
from ..rekordbox import beatgrid as rb_beatgrid
@@ -566,6 +566,23 @@ class OneLibraryStore(ReplaceGridCommands):
db.flush()
db.session.expire(row)
def set_track_color(self, track_id: str, color: str | None) -> None:
"""`content.color_id`, a 1-based id into the `color` table (see
`track_palette`); 0 = none, as rekordbox exports an uncoloured track.
Not a file tag; the pdb's track row follows at Save (`device_library`)."""
new = track_palette.id_for(color)
if color is not None and not new:
raise InvalidCommand(f"Not a track colour: {color!r}")
db = self._require_db()
row = self.content(track_id)
before = row.color_id
if int(before or 0) == new:
return
row.color_id = new
self._journal.record("track", "set", track_id, "color", before, new)
db.flush()
db.session.expire(row)
# ---- writes: playlists --------------------------------------------------
def _playlist(self, node_id: str):
from pyrekordbox.onelibrary import models
@@ -1182,7 +1199,7 @@ class OneLibraryStore(ReplaceGridCommands):
"isrc, djPlayCount, isHotCueAutoLoadOn, isKuvoDeliverStatusOn, kuvoDeliveryComment, "
"masterDbId, masterContentId, analysisDataFilePath, analysedBits, contentLink, "
"hasModified) VALUES (:cid, :title, NULL, '', :bpm, :length, 0, 0, :artist, :remixer, "
":album, :genre, :label, :key, 0, :image, :comment, :rating, :year, :released, "
":album, :genre, :label, :key, :color, :image, :comment, :rating, :year, :released, "
":added, :created, :path, :file, :size, :type, :bitrate, :depth, :rate, '', 0, 1, 1, "
"'', 0, :cid, :anlz, :bits, :link, 0)"), {
"cid": cid, "title": getattr(track, "title", None) or final.stem,
@@ -1192,6 +1209,7 @@ class OneLibraryStore(ReplaceGridCommands):
"label": lookup("Label", track.label),
# Rendered from the parsed wheel: a source's "10m" means nothing here.
"key": self._key_id(track.key_wheel, track.key_mode),
"color": track_palette.id_for(getattr(track, "color", None)),
"image": image_id, "comment": track.comment or "",
"rating": max(0, min(5, int(track.rating or 0))), "year": year, "released": released,
"added": datetime.now().strftime("%Y-%m-%d"), "created": created, "path": rel,
@@ -260,6 +260,12 @@ class RekordboxAdapter:
self._refresh(track_id)
return self._index.get(track_id)
def set_track_color(self, track_id: str, color: str | None) -> Track | None:
self._require_writable("Setting the track colour")
self._store.set_track_color(track_id, color)
self._refresh(track_id)
return self._index.get(track_id)
# ---- commands: playlists ----------------------------------------------
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
self._require_writable("Creating playlists")
@@ -30,7 +30,7 @@ from ...core.capabilities import (
SaveCapabilities,
TrackCapabilities,
)
from . import memory_palette, palette
from . import memory_palette, palette, track_palette
from .cue_types import MAX_MEMORY_CUES, WRITABLE_CUE_TYPES
# Rekordbox's addressable hot cue bank. The pads are labelled A-H; the stored
@@ -93,6 +93,8 @@ def capabilities_for(
removable=True,
addable=True,
key_writable=True,
# `djmdContent.ColorID`, rekordbox's eight (see `track_palette`).
colors=list(track_palette.SWATCHES),
artwork=False,
artwork_note=None,
),
@@ -41,7 +41,7 @@ from datetime import date
from pathlib import Path
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
from . import artwork, pdb
from . import artwork, pdb, track_palette
from .projection import render_key
log = logging.getLogger(__name__)
@@ -138,6 +138,7 @@ class RekordboxDeviceExporter:
"id": n, "year": year, "sample_depth": bit_depth or 0,
"duration": min(int(track.length or 0), 0xFFFF),
"u5": ANALYSED, "rating": max(0, min(5, int(track.rating or 0))),
"color_id": track_palette.id_for(track.color),
"u6": _file_type(item.destination), "u7": 3,
},
{
@@ -58,7 +58,7 @@ from sqlalchemy import text
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
from ...core.cue_colors import effective_color
from . import memory_palette, new_content, palette
from . import memory_palette, new_content, palette, track_palette
from . import timebase
from .beatgrid import beats_from_markers
from .capabilities import capabilities_for
@@ -313,6 +313,7 @@ class RekordboxExporter:
# export would put "10m" where Rekordbox shows "Cm".
content.KeyID = self._lookup(db, "key", render_key(track.key_wheel, track.key_mode))
content.ContentLink = CONTENT_LINK
content.ColorID = str(track_palette.id_for(track.color))
db.flush()
return content
@@ -7,7 +7,7 @@ from __future__ import annotations
from ...core import musical_key
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
from . import beatgrid, memory_palette, palette, timebase
from . import beatgrid, memory_palette, palette, timebase, track_palette
from .cue_types import cue_type, kind_for, role_and_slot
# Rekordbox names keys musically ("Abm", "F", "Ebm") — but its key table also
@@ -127,6 +127,8 @@ def to_track(row, cue_kinds=(), *, stem: bool = False) -> Track:
# file's mix, but Konduktor's deck plays its stems, and the Type column
# must not disagree with the deck.
media_kind="stem" if stem else "audio",
color=track_palette.color_for(getattr(row, "ColorID", None)),
color_hex=track_palette.hex_for(getattr(row, "ColorID", None)),
)
+20 -1
View File
@@ -47,7 +47,7 @@ from ...core.adapter import (
from ...core.edit_journal import EditJournal
from ...core.grid_edit import ReplaceGridCommands
from ...core.pathmap import PathMapping, stored_form
from . import memory_palette, timebase
from . import memory_palette, timebase, track_palette
from .cue_types import MAX_MEMORY_CUES, beat_loop_size, kind_for, role_and_slot
log = logging.getLogger(__name__)
@@ -556,6 +556,24 @@ class RekordboxStore(ReplaceGridCommands):
self._db.flush()
self._db.session.expire(row)
# ---- writes: track colour ---------------------------------------------
def set_track_color(self, track_id: str, color: str | None) -> None:
"""`djmdContent.ColorID`, a 1-based id into `djmdColor` (see
`track_palette`). Cleared = "0", as on the uncoloured rows of the local
library (a few hold NULL; both read as none)."""
new = track_palette.id_for(color)
if color is not None and not new:
raise InvalidCommand(f"Not a track colour: {color!r}")
row = self.content(track_id)
before = row.ColorID
if track_palette.id_for(track_palette.color_for(before)) == new:
return
row.ColorID = str(new)
self._journal.record("track", "set", track_id, "color", before, row.ColorID)
# A foreign key into djmdColor: flush + expire, as for the others.
self._db.flush()
self._db.session.expire(row)
# ---- writes: playlists ------------------------------------------------
def _playlist(self, node_id: str):
t = self._tables
@@ -761,6 +779,7 @@ class RekordboxStore(ReplaceGridCommands):
# Rekordbox's ("10m" is "Cm" here), and a row it already has is reused.
content.KeyID = self._key_id(track.key_wheel, track.key_mode)
content.ContentLink = new_content.CONTENT_LINK
content.ColorID = str(track_palette.id_for(track.color))
if stored != audio:
# pyrekordbox reads the file where it IS; the row names it as the
# library stores every other path (the server's mapping, inverted).
@@ -0,0 +1,50 @@
"""rekordbox's TRACK colours — the eight a track can be tagged with.
Stored as a 1-based id into the `djmdColor` table (master.db `djmdContent.ColorID`,
a string: "0" = none) and OneLibrary's `color` table (`content.color_id`, an
integer, 0 = none); the stick's legacy `export.pdb` track row has a `color_id`
byte with the same numbering. Both tables list the same eight rows in the same
order: 1 Pink, 2 Red, 3 Orange, 4 Yellow, 5 Green, 6 Aqua, 7 Blue, 8 Purple —
one per generic `TrackColor`, so the mapping is one to one.
Those are the memory-cue palette's names in its order, so the display RGB is
`memory_palette.COLOURS`' (sampled from rekordbox 7's own colour menu). Nothing
stores the RGB — `djmdColor.ColorCode` is NULL in a real library.
"""
from __future__ import annotations
from ...core.capabilities import ColorSwatch, TrackColor
from . import memory_palette
#: id - 1 -> the generic colour, in rekordbox's menu order.
_NAMES: list[TrackColor] = ["pink", "red", "orange", "yellow", "green", "aqua", "blue", "purple"]
#: What `capabilities.tracks.colors` offers.
SWATCHES: list[ColorSwatch] = [
ColorSwatch(color=name, hex=memory_palette.SWATCHES[i], label=memory_palette.COLOURS[i][0])
for i, name in enumerate(_NAMES)
]
def _id(color_id: int | str | None) -> int:
try:
return int(color_id) if color_id is not None else 0
except (TypeError, ValueError):
return 0
def color_for(color_id: int | str | None) -> TrackColor | None:
"""The generic colour for a stored id; None for 0, NULL or anything unknown."""
n = _id(color_id)
return _NAMES[n - 1] if 1 <= n <= len(_NAMES) else None
def hex_for(color_id: int | str | None) -> str | None:
"""rekordbox's display colour for a stored id; None when uncoloured."""
n = _id(color_id)
return SWATCHES[n - 1].hex if 1 <= n <= len(SWATCHES) else None
def id_for(color: TrackColor | str | None) -> int:
"""The id to store for a generic colour; 0 for none (or an unknown name)."""
return _NAMES.index(color) + 1 if color in _NAMES else 0
@@ -218,6 +218,9 @@ class RemoteAdapter:
def set_key(self, track_id, wheel, mode):
return self._call("set_key", track_id=track_id, wheel=wheel, mode=mode)
def set_track_color(self, track_id, color):
return self._call("set_track_color", track_id=track_id, color=color)
def set_cue(self, track_id, *, slot, start_sec, cue_type, length_sec=0.0, role="hotcue", name=None):
return self._call("set_cue", track_id=track_id, slot=slot, start_sec=start_sec,
cue_type=cue_type, length_sec=length_sec, role=role, name=name)
@@ -156,6 +156,12 @@ class TraktorAdapter:
self._refresh(track_id)
return self._index.get(track_id)
def set_track_color(self, track_id: str, color: str | None) -> Track | None:
with _translate():
self._store.set_track_color(track_id, color)
self._refresh(track_id)
return self._index.get(track_id)
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
with _translate():
self._store.set_track_art(track_id, data, mime)
@@ -19,6 +19,7 @@ from ...core.capabilities import (
SaveCapabilities,
TrackCapabilities,
)
from . import track_palette
_VERSION_RE = re.compile(rb'<NML\s+VERSION="(\d+)"')
@@ -68,6 +69,8 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
addable=True,
stem_convertible=True,
key_writable=True,
# INFO@COLOR, seven colours (measured, see `track_palette`).
colors=list(track_palette.SWATCHES),
# `.mp4` covers stem files (`.stem.mp4`). Traktor also reads WMA,
# but only on Windows, and a file added on one OS must play on both.
audio_formats=[".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a", ".mp4", ".ogg"],
@@ -9,7 +9,7 @@ import re
from ...core import musical_key
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
from . import beatgrid, timebase
from . import beatgrid, timebase, track_palette
from .cue_types import NATIVE_TO_CUE_TYPE
# Traktor displays keys in Open Key ("10m" / "8d") or Camelot ("8A" / "8B"),
@@ -172,6 +172,8 @@ def to_track(e) -> Track:
grid_marker_count=len(markers),
grid_locked=bool(e.lock),
media_kind="stem" if getattr(e, "stems", None) is not None else "audio",
color=track_palette.color_for(info.color if info else None),
color_hex=track_palette.hex_for(info.color if info else None),
)
+25 -2
View File
@@ -53,7 +53,7 @@ from ...core.pathmap import PathMapping, stored_form
from ...core.relocate import PathGroup
from ...core.stem_file import NML_STEMS_JSON, nml_stems_for
from ...schemas import PlaylistNode
from . import beatgrid, timebase
from . import beatgrid, timebase, track_palette
from .locations import os_path_to_location, resolve_path
from ...core import musical_key
from .projection import iso_date, musical_key_value, traktor_date, with_memory_ids
@@ -446,7 +446,8 @@ class TraktorStore:
EDITABLE_FIELDS = {"title", "artist", "album", "rating", "comment2"} | _INFO_FIELDS
# Fields that live only in the collection: Traktor itself writes no file tag
# for "Comment 2" (verified on an m4a it had just edited), so neither do we.
_COLLECTION_ONLY_FIELDS = {"comment2"}
# Nor for the track colour (kit T1: no audio file's mtime moved).
_COLLECTION_ONLY_FIELDS = {"comment2", "color"}
def set_track_metadata(self, track_id: str, fields: dict) -> None:
with self._lock:
@@ -544,6 +545,27 @@ class TraktorStore:
self._journal.record("track", "set", track_id, "key", before, entry.info.key)
self.dirty = True
# ---- track colour -----------------------------------------------------
def set_track_color(self, track_id: str, color: str | None) -> None:
"""INFO@COLOR (see `track_palette`). Cleared = the attribute removed, as
every never-coloured entry has it; what Traktor itself leaves after
"None" (absent, or `COLOR="0"`) is not yet measured (kit T1 step 3)."""
code = track_palette.code_for(color)
if color is not None and code is None:
raise InvalidCommand(f"Not a track colour: {color!r}")
with self._lock:
entry = self._entry_by_key.get(track_id)
if entry is None:
raise PlaylistError(f"Track not found: {track_id}")
before = entry.info.color if entry.info is not None else None
if before == code:
return
if entry.info is None:
entry.info = Infotype()
entry.info.color = code
self._journal.record("track", "set", track_id, "color", before, code)
self.dirty = True
# ---- adding tracks --------------------------------------------------
def add_entry(self, track, audio_path: Path) -> str:
"""Append a brand-new ENTRY for `audio_path` and return its track id.
@@ -598,6 +620,7 @@ class TraktorStore:
# attribute at all rather than a zero.
ranking=(max(0, min(5, int(getattr(track, "rating", 0) or 0))) * 51) or None,
playtime=getattr(track, "length", None) or None,
color=track_palette.code_for(getattr(track, "color", None)),
)
album = None
if getattr(track, "album", None):
@@ -0,0 +1,59 @@
"""Traktor's TRACK colours — `INFO@COLOR`, an integer.
MEASURED in Traktor 4.5 (kit T1, 2026-10-17,
`.claude/discussions/discuss-track-colour-2026-10-17.md`) by colouring one track
per entry of the browser's Color menu, in its order: 1 Red · 2 Orange ·
3 Yellow · 4 Green · 5 Blue · 6 Violet · 7 Magenta. Traktor keeps it in the
collection only — it does not tag the audio file.
Mapped to the generic colours BY NAME (decided 2026-10-17): Violet is `purple`,
Magenta `pink`, and Blue is `blue` even though it LOOKS like rekordbox's Aqua —
the name is the DJ's category. Traktor has no seventh-and-a-half colour, so
`aqua` arriving from rekordbox is stored as Blue.
The RGB values are DISPLAY colours only — nothing stores them. They were
sampled from the colour dots in Traktor's own browser (a screenshot).
"""
from __future__ import annotations
from ...core.capabilities import ColorSwatch, TrackColor
#: What `capabilities.tracks.colors` offers; code - 1 -> swatch, menu order.
SWATCHES: list[ColorSwatch] = [
ColorSwatch(color="red", hex="#FB413E", label="Red"),
ColorSwatch(color="orange", hex="#F79525", label="Orange"),
ColorSwatch(color="yellow", hex="#F9F918", label="Yellow"),
ColorSwatch(color="green", hex="#52FA52", label="Green"),
ColorSwatch(color="blue", hex="#1ACBFA", label="Blue"),
ColorSwatch(color="purple", hex="#B26CFA", label="Violet"),
ColorSwatch(color="pink", hex="#FA51EB", label="Magenta"),
]
#: Generic colours Traktor has no swatch of its own for.
_FOLDED: dict[str, int] = {"aqua": 5}
def _swatch(code: int | None) -> ColorSwatch | None:
return SWATCHES[code - 1] if isinstance(code, int) and 1 <= code <= len(SWATCHES) else None
def color_for(code: int | None) -> TrackColor | None:
"""The generic colour for a stored code; None for absent, 0 or unknown."""
s = _swatch(code)
return s.color if s else None
def hex_for(code: int | None) -> str | None:
"""Traktor's display colour for a stored code; None when uncoloured."""
s = _swatch(code)
return s.hex if s else None
def code_for(color: TrackColor | str | None) -> int | None:
"""The `INFO@COLOR` to store for a generic colour; None for none."""
if color is None:
return None
for i, s in enumerate(SWATCHES, start=1):
if s.color == color:
return i
return _FOLDED.get(color)
+4 -1
View File
@@ -22,7 +22,7 @@ from dataclasses import dataclass, field
from pathlib import Path
from typing import Protocol, runtime_checkable
from .capabilities import Capabilities
from .capabilities import Capabilities, TrackColor
from .model import Facets, PlaylistNode, Stats, Track, TrackCues, TrackPage
from .pathmap import PathMapping
from .relocate import PathGroup
@@ -296,6 +296,9 @@ class LibraryAdapter(Protocol):
# analysis writes. Each platform renders it in its own notation (and its own
# analysed-key field, where it has one). Gated on `tracks.key_writable`.
def set_key(self, track_id: str, wheel: int, mode: str) -> Track | None: ...
# The track's colour tag (None clears it), mapped onto the platform's own
# palette by name. Gated on `tracks.colors` being non-empty.
def set_track_color(self, track_id: str, color: TrackColor | None) -> Track | None: ...
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None: ...
def cover_art(self, track_id: str) -> tuple[bytes, str] | None: ...
+17
View File
@@ -36,6 +36,20 @@ CueType = Literal["cue", "fade_in", "fade_out", "load", "loop"]
CueRole = Literal["hotcue", "memory"]
MediaKind = Literal["audio", "stem", "video"]
PlaylistKind = Literal["folder", "playlist", "smart"]
# A track's colour tag, as a platform-neutral IDENTITY — what crosses between
# libraries. Each adapter maps its own codes to and from these BY NAME (decided
# 2026-10-17, `.claude/discussions/discuss-track-colour-2026-10-17.md`): eight
# names because rekordbox has eight; Traktor's seven cover all but `aqua`,
# which it receives as its Blue.
TrackColor = Literal["pink", "red", "orange", "yellow", "green", "aqua", "blue", "purple"]
class ColorSwatch(BaseModel):
"""One track colour a library offers, in its own menu order."""
color: TrackColor
hex: str # the platform's own display colour
label: str # the platform's own name for it ("Violet" in Traktor)
class CueCapabilities(BaseModel):
@@ -107,6 +121,9 @@ class TrackCapabilities(BaseModel):
# Whether added files can be left where they are ("reference") rather than
# copied. False where the library cannot see this computer's files at all.
reference: bool = True
# The track colours this library can store (`set_track_color`), in its own
# menu order. Empty: the platform has no track colour.
colors: list[ColorSwatch] = []
class PlaylistCapabilities(BaseModel):
+6 -1
View File
@@ -13,7 +13,7 @@ from typing import Literal
from pydantic import BaseModel, ConfigDict, Field
from .capabilities import CueRole, CueType, MediaKind, PlaylistKind
from .capabilities import CueRole, CueType, MediaKind, PlaylistKind, TrackColor
class HotcueChip(BaseModel):
@@ -71,6 +71,11 @@ class Track(BaseModel):
grid_marker_count: int = 0
grid_locked: bool = False
media_kind: MediaKind = "audio"
# The track's colour tag: the neutral identity (what crosses platforms) and
# the platform's own display colour for it, both mapped from the stored
# code by the adapter. None = no colour.
color: TrackColor | None = None
color_hex: str | None = None
class TrackPage(BaseModel):
+12
View File
@@ -60,6 +60,7 @@ from .schemas import (
LibraryInfo,
PlatformOption,
EditTrack,
SetTrackColor,
Facets,
FileTagOutcome,
CreateExportSet,
@@ -1320,6 +1321,17 @@ def edit_track(body: EditTrack) -> dict:
return {"status": "updated", "id": body.track_id}
@app.patch("/api/tracks/color")
def set_track_color(body: SetTrackColor) -> dict:
"""Set (or clear) the colour tag of every given track (in-memory; persisted
on save). Gated on `tracks.colors`: the platform's swatches."""
a = require_adapter()
if not a.capabilities().tracks.colors:
raise Unsupported("This library cannot store a track colour")
tracks = [a.set_track_color(tid, body.color) for tid in body.track_ids]
return {"status": "updated", "tracks": [t for t in tracks if t is not None]}
@app.get("/api/tracks/art")
def track_art(track_id: str) -> Response:
"""Stream a track's embedded cover art (staged replacement if unsaved)."""
+4 -2
View File
@@ -38,7 +38,8 @@ from .core.model import AutoHotcue, Track, TrackCues
#: 1.2 — `/v1/folder/*`: the content folder browsed as a Files tree.
#: 1.3 — memory cues: `add_memory_cue`, `rename_memory_cue`,
#: `set_memory_cue_type`, `set_memory_cue_color`, `delete_memory_cue`.
API_VERSION: tuple[int, int] = (1, 3)
#: 1.4 — track colour: `set_track_color`, `Track.color` / `color_hex`.
API_VERSION: tuple[int, int] = (1, 4)
#: How long a session survives without a heartbeat, and how often the holder
#: sends one. Long enough to ride out a Wi-Fi blip or a switch to the fallback
@@ -77,7 +78,8 @@ _READ = (
)
_MUTATING = (
"create_playlist", "create_folder", "rename_playlist", "delete_playlist",
"move_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_track_color", "set_cue",
"set_cue_type", "set_cue_color", "delete_cue", "place_cues", "add_memory_cue",
"rename_memory_cue", "set_memory_cue_type", "set_memory_cue_color", "delete_memory_cue", "add_grid_marker",
"move_grid_marker", "set_grid_marker_bpm", "delete_grid_marker", "replace_grid",
+8 -1
View File
@@ -5,7 +5,7 @@ from typing import Literal
from pydantic import BaseModel, ConfigDict, Field
from .core.capabilities import CueRole, CueType
from .core.capabilities import CueRole, CueType, TrackColor
class CreatePlaylist(BaseModel):
@@ -40,6 +40,13 @@ class EditTrack(BaseModel):
fields: dict[str, str | int | None]
class SetTrackColor(BaseModel):
"""The context menu's Colour ▸: one colour (None = No Color) for a selection."""
track_ids: list[str]
color: TrackColor | None = None
class FileTagOutcome(BaseModel):
track_id: str
file: str