Implemented traktor utility fixes

This commit is contained in:
patben8 committed 2026-10-01 10:54:27 +02:00
1 parent 08c53e1150
commit 2c02019bb2
5 files changed
+150 -2

No files matched your search

@@ -17,6 +17,9 @@ from .cue_types import NATIVE_TO_CUE_TYPE
_OPEN_KEY = re.compile(r"^(\d{1,2})\s*([md])$", re.I) _OPEN_KEY = re.compile(r"^(\d{1,2})\s*([md])$", re.I)
_CAMELOT = re.compile(r"^(\d{1,2})\s*([ab])$", re.I) _CAMELOT = re.compile(r"^(\d{1,2})\s*([ab])$", re.I)
_DATE = re.compile(r"^(\d{4})/(\d{1,2})/(\d{1,2})$") _DATE = re.compile(r"^(\d{4})/(\d{1,2})/(\d{1,2})$")
# "YYYY", "YYYY-MM" or "YYYY-MM-DD", optionally followed by a time (a
# timestamp's date part is the date).
_ISO_DATE = re.compile(r"^(\d{4})(?:-(\d{1,2})(?:-(\d{1,2}))?)?(?:[T ].*)?$")
def parse_key(key: str | None) -> tuple[int | None, str | None]: def parse_key(key: str | None) -> tuple[int | None, str | None]:
@@ -50,6 +53,28 @@ def iso_date(value: str | None) -> str | None:
return f"{y}-{int(mo):02d}-{int(d):02d}" return f"{y}-{int(mo):02d}-{int(d):02d}"
def traktor_date(value: str | None) -> str | None:
"""The inverse of `iso_date`: an ISO-8601 date as Traktor writes it.
Traktor's form is unpadded "YYYY/M/D" — every one of the 16,000-odd dates
in the real collection. A year alone becomes "YYYY/1/1", as Traktor itself
records a year-only release date (2,094 of 2,122 there). Anything that is
neither ISO nor already Traktor's form passes through unchanged, as
`iso_date` does in the other direction: losing a date is worse than
carrying one Traktor may not parse.
"""
if not value:
return None
s = value.strip()
if m := _DATE.match(s):
y, mo, d = m.groups()
return f"{y}/{int(mo)}/{int(d)}"
if m := _ISO_DATE.match(s):
y, mo, d = m.groups()
return f"{y}/{int(mo or 1)}/{int(d or 1)}"
return value
def primary_key(location) -> str: def primary_key(location) -> str:
"""Reconstruct the Traktor primary key used by playlist entries.""" """Reconstruct the Traktor primary key used by playlist entries."""
vol = location.volume or "" vol = location.volume or ""
+20 -2
View File
@@ -51,6 +51,7 @@ from ...core.relocate import PathGroup
from ...schemas import PlaylistNode from ...schemas import PlaylistNode
from . import beatgrid from . import beatgrid
from .locations import os_path_to_location, resolve_path from .locations import os_path_to_location, resolve_path
from .projection import iso_date, traktor_date
# Traktor's POPM frame owner: an ID3 rating is per-owner, so writing under # Traktor's POPM frame owner: an ID3 rating is per-owner, so writing under
# this email is what makes the stars show up in Traktor itself. # this email is what makes the stars show up in Traktor itself.
@@ -385,6 +386,10 @@ class TraktorStore:
if entry.album is None: if entry.album is None:
entry.album = Albumtype() entry.album = Albumtype()
entry.album.title = v or None entry.album.title = v or None
elif k == "release_date":
# Edited as ISO (that is what the projection shows); stored
# as Traktor's "YYYY/M/D".
entry.info.release_date = traktor_date(v)
elif k in self._INFO_FIELDS: elif k in self._INFO_FIELDS:
setattr(entry.info, k, v or None) setattr(entry.info, k, v or None)
elif k == "comment2": elif k == "comment2":
@@ -440,8 +445,9 @@ class TraktorStore:
key=getattr(track, "key", None) or None, key=getattr(track, "key", None) or None,
bitrate=getattr(track, "bitrate", None) or None, bitrate=getattr(track, "bitrate", None) or None,
playcount=getattr(track, "playcount", None) or None, playcount=getattr(track, "playcount", None) or None,
release_date=getattr(track, "release_date", None) or None, # The generic model carries ISO dates; Traktor writes "YYYY/M/D".
import_date=getattr(track, "import_date", None) or None, release_date=traktor_date(getattr(track, "release_date", None)),
import_date=traktor_date(getattr(track, "import_date", None)),
# Traktor's RANKING is stars x 51; an unrated track has no # Traktor's RANKING is stars x 51; an unrated track has no
# attribute at all rather than a zero. # attribute at all rather than a zero.
ranking=(max(0, min(5, int(getattr(track, "rating", 0) or 0))) * 51) or None, ranking=(max(0, min(5, int(getattr(track, "rating", 0) or 0))) * 51) or None,
@@ -1137,6 +1143,15 @@ class TraktorStore:
continue # no-op (e.g. from == to); leave byte-identical continue # no-op (e.g. from == to); leave byte-identical
loc.volume, loc.dir, loc.file = volume, dir_, file loc.volume, loc.dir, loc.file = volume, dir_, file
key_remap[old_key] = new_key key_remap[old_key] = new_key
# Re-key the index too. Everything that finds an ENTRY by track
# id goes through it — later edits, and the file-tag sync on
# save, which would otherwise silently skip every edit made to
# this track before the remap.
if self._entry_by_key.get(old_key) is e:
del self._entry_by_key[old_key]
self._entry_by_key[new_key] = e
if old_key in self._track_art:
self._track_art[new_key] = self._track_art.pop(old_key)
if not key_remap: if not key_remap:
return {} return {}
# Rewrite playlist entry primary keys that referenced moved tracks. # Rewrite playlist entry primary keys that referenced moved tracks.
@@ -1170,6 +1185,9 @@ class TraktorStore:
return round(r / 51) if r else 0 return round(r / 51) if r else 0
if field == "comment2": if field == "comment2":
return entry.info.rating if entry.info else None return entry.info.rating if entry.info else None
if field == "release_date":
# A file tag wants ISO, not the NML's "YYYY/M/D".
return iso_date(entry.info.release_date) if entry.info else None
return getattr(entry.info, field, None) if entry.info else None return getattr(entry.info, field, None) if entry.info else None
def count_playlists(self) -> int: def count_playlists(self) -> int:
+4
View File
@@ -452,6 +452,10 @@ class JobStatus(BaseModel):
state: str # running | done | failed | cancelled state: str # running | done | failed | cancelled
total: int total: int
done: int done: int
# What done/total count ("bytes" / "tracks"; "" when unspecified). Declared
# here or the response model silently drops the one field the status bar
# needs to tell a byte count from a track count.
unit: str = ""
message: str message: str
result: dict | None = None result: dict | None = None
error: str | None = None error: str | None = None
+5
View File
@@ -198,6 +198,11 @@ with tempfile.TemporaryDirectory() as d:
check("nothing was written to disk (edits stay in memory until Save)", check("nothing was written to disk (edits stay in memory until Save)",
work.read_bytes() == REAL.read_bytes()) work.read_bytes() == REAL.read_bytes())
# The status bar tells a byte count from a track count by `unit`; the
# response model once dropped it on every job route.
jid = main.JOBS.submit("unit-probe", lambda h: h.progress(done=1, total=2, unit="bytes")).id
check("a job's unit reaches the client", wait(c, jid).get("unit") == "bytes")
print() print()
print("FAILED" if failed else "RESULT: ALL PASSED") print("FAILED" if failed else "RESULT: ALL PASSED")
raise SystemExit(1 if failed else 0) raise SystemExit(1 if failed else 0)
+96
View File
@@ -515,6 +515,56 @@ with tempfile.TemporaryDirectory() as d:
check("H2: old playlist PRIMARYKEY gone", old_key not in all_pl_keys) check("H2: old playlist PRIMARYKEY gone", old_key not in all_pl_keys)
check("H2: new playlist PRIMARYKEY present", new_key in all_pl_keys) check("H2: new playlist PRIMARYKEY present", new_key in all_pl_keys)
# H3: a remap re-keys the entry index, so the track is still reachable by its
# NEW id before any save — and a tag edit made BEFORE the remap still reaches
# the file on save (it was silently dropped when the index kept the old key).
with tempfile.TemporaryDirectory() as d:
work = Path(d) / "collection.nml"
shutil.copy2(REAL, work)
store = TraktorStore(work)
target = next(e for e in store._nml.collection.entry if e.location and e.location.file)
old_key = _key(target.location)
from_prefix = str(resolve_path(target.location.volume, target.location.dir, target.location.file))
to_prefix = "/Volumes/KONDUKTOR_TEST_H3/remapped__rekey__one.mp3"
new_key = "".join(os_path_to_location(Path(to_prefix)))
store.set_track_metadata(old_key, {"genre": "H3 before remap"})
store.set_track_art(old_key, b"\xff\xd8H3", "image/jpeg")
moved = store.remap_locations(PathMapping.make(from_prefix, to_prefix))
check("H3: the remap reports the new id", moved.get(old_key) == new_key, str(moved))
check("H3: the index finds the ENTRY by its new id", store._entry_by_key.get(new_key) is target)
check("H3: …and no longer by its old one", old_key not in store._entry_by_key)
check("H3: staged cover art follows the track", new_key in store._track_art and old_key not in store._track_art)
try:
store.set_track_metadata(new_key, {"label": "H3 after remap"})
check("H3: an edit by the new id works before saving", target.info.label == "H3 after remap")
except PlaylistError as exc:
check("H3: an edit by the new id works before saving", False, str(exc))
# The tag sync must visit the moved track with BOTH edits. Stub the file
# side: this is about which tracks it reaches, not about mutagen.
import konduktor.core.audio_tags as _tags # noqa: E402
written = []
real_write_tags, real_write_cover = _tags.write_tags, _tags.write_cover
ok = SimpleNamespace(ok=True, status="ok", detail=None)
_tags.write_tags = lambda path, meta, **k: (written.append(("tags", meta)), ok)[1]
_tags.write_cover = lambda path, data, mime: (written.append(("cover", data)), ok)[1]
store._resolve = lambda loc: Path(to_prefix)
try:
results = store._sync_file_tags()
finally:
_tags.write_tags, _tags.write_cover = real_write_tags, real_write_cover
tag_meta = next((m for kind, m in written if kind == "tags"), {})
check("H3: the file-tag sync reaches the remapped track",
[r.track_id for r in results] == [new_key, new_key], str([r.track_id for r in results]))
check("H3: …with the edit made before the remap AND the one after",
tag_meta.get("genre") == "H3 before remap" and tag_meta.get("label") == "H3 after remap",
str(tag_meta))
check("H3: …and the staged cover art", ("cover", b"\xff\xd8H3") in written)
# ---- Invariant I: flexible (multi-marker) beatgrids round-trip --------- # ---- Invariant I: flexible (multi-marker) beatgrids round-trip ---------
print("== I. flexible beatgrid: add/move/delete markers, localized + reversible ==") print("== I. flexible beatgrid: add/move/delete markers, localized + reversible ==")
@@ -736,5 +786,51 @@ with tempfile.TemporaryDirectory() as d:
all((n.playlist.entries or 0) == len(n.playlist.entry or []) for n in pl_nodes(re))) all((n.playlist.entries or 0) == len(n.playlist.entry or []) for n in pl_nodes(re)))
# ---- Invariant M: dates cross in Traktor's own form -----------------------
# The projection turns Traktor's "YYYY/M/D" into ISO; everything that writes a
# date back must turn it round again, or the NML ends up holding a notation
# Traktor never writes.
print("== M. dates are written as Traktor's YYYY/M/D, tags get ISO ==")
from konduktor.adapters.traktor.projection import iso_date, traktor_date # noqa: E402
for given, want in [
("2021-03-04", "2021/3/4"), ("2021-12-25", "2021/12/25"), ("2021", "2021/1/1"),
("2021-07", "2021/7/1"), ("2021-03-04T10:20:30", "2021/3/4"), ("2021/03/04", "2021/3/4"),
("2021/3/4", "2021/3/4"), ("sometime", "sometime"), ("", None), (None, None),
]:
check(f"M: traktor_date({given!r}) == {want!r}", traktor_date(given) == want, repr(traktor_date(given)))
check("M: every date in the collection round-trips through ISO",
all(traktor_date(iso_date(v)) == v
for e in TraktorCollection(path=REAL).nml.collection.entry if e.info
for v in (e.info.release_date, e.info.import_date, e.info.last_played) if v))
with tempfile.TemporaryDirectory() as d:
work = Path(d) / "collection.nml"
shutil.copy2(REAL, work)
store = TraktorStore(work)
target = next(e for e in store._nml.collection.entry
if e.location and e.info and e.info.release_date)
key = store._key_of(target)
original = store._render()
store.set_track_metadata(key, {"release_date": "2019-06-07"})
check("M: an ISO edit is stored as Traktor's form", target.info.release_date == "2019/6/7",
target.info.release_date)
check("M: …and the file tag is given ISO",
store._entry_field_value(target, "release_date") == "2019-06-07")
changed = [dl for dl in difflib.unified_diff(tag_lines(original), tag_lines(store._render()), n=0)
if dl[:1] in "+-" and dl[:3] not in ("+++", "---")]
check("M: only that ENTRY's INFO line changes", len(changed) == 2 and "RELEASE_DATE=\"2019/6/7\"" in changed[1],
"\n".join(changed[:4]))
new_id = store.add_entry(
SimpleNamespace(title="M dates", release_date="2020", import_date="2026-09-30"),
Path("/Volumes/KONDUKTOR_TEST_M/dates.mp3"),
)
info = store._entry_by_key[new_id].info
check("M: an added track's dates are Traktor's form",
(info.release_date, info.import_date) == ("2020/1/1", "2026/9/30"),
f"{info.release_date!r} {info.import_date!r}")
print("\nRESULT:", "FAILED" if failed else "ALL PASSED") print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0) sys.exit(1 if failed else 0)