Implemented metadata editing

This commit is contained in:
Ben committed 2026-07-04 14:53:13 +02:00
1 parent cc254e9a9b
commit 279e5ac34f
13 files changed
+943 -35

No files matched your search

+13
View File
@@ -90,6 +90,7 @@ class CollectionService:
label=info.label if info else None,
remixer=info.remixer if info else None,
producer=info.producer if info else None,
mix=info.mix if info else None,
comment=info.comment if info else None,
bpm=e.tempo.bpm if e.tempo else None,
key=info.key if info else None,
@@ -236,6 +237,18 @@ class CollectionService:
total_tracks=len(self.tracks),
)
def replace_track(self, track_id: str, entry) -> None:
"""Refresh the read projection for one track from its (edited) model
entry, mutating the existing Track object in place so both `tracks` and
`by_key` reflect it. Bridges the store (edit model) and this read model
until they're consolidated."""
old = self.by_key.get(track_id)
if old is None:
return
new = self._to_track(entry)
for field in type(new).model_fields:
setattr(old, field, getattr(new, field))
def entries_for(self, track_ids: list[str]) -> list[tuple[str, str]]:
"""Map track ids to (key, PRIMARYKEY-type) pairs for playlist writing.
Unknown ids are skipped (can't reference a track not in the collection)."""
+321
View File
@@ -0,0 +1,321 @@
"""Write track metadata into audio files' embedded tags (best-effort).
Konduktor's source of truth is the `.nml`; this module additionally syncs the
safe metadata fields into the audio file itself so the data travels with the
file (portability to other apps). It is best-effort: if the file isn't present
(e.g. the drive isn't mounted) or the format doesn't support a field, it reports
that rather than failing the whole save.
Field writes are frame/atom-level, so unrelated tags (cover art, beatgrid BPM,
key, track number, private frames) are preserved — verified against real files.
"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
# The safe, editable metadata we sync to files (mirrors PlaylistStore.EDITABLE_FIELDS).
# rating is 0–5 stars.
TagMeta = dict # keys: title, artist, album, genre, label, remixer, producer,
# comment, mix, release_date, rating
@dataclass
class TagResult:
ok: bool
status: str # "written" | "file-not-found" | "unsupported-format" | "error"
detail: str = ""
def resolve_path(volume: str | None, dir_: str | None, file: str | None) -> Path:
"""Map a Traktor LOCATION to an OS path.
Paths are trusted (per project decision): boot volume 'Macintosh HD' -> '/',
a Windows drive like 'X:' stays a drive path, other volumes -> /Volumes/<v>.
"""
d = (dir_ or "").replace("/:", "/")
name = file or ""
vol = volume or ""
if vol.endswith(":"): # Windows drive letter, e.g. "X:"
return Path(vol + d + name)
if vol and vol != "Macintosh HD": # other mounted volume (macOS/*nix)
return Path("/Volumes") / vol / (d.lstrip("/") + name)
return Path(d + name) # boot volume
def read_cover(path: Path) -> tuple[bytes, str] | None:
"""Return (image_bytes, mime) of the file's embedded front cover, or None."""
if not path.exists():
return None
ext = path.suffix.lower()
try:
if ext in (".mp3", ".aif", ".aiff"):
from mutagen.id3 import ID3, ID3NoHeaderError
try:
id3 = ID3(path)
except ID3NoHeaderError:
return None
apics = id3.getall("APIC")
if not apics:
return None
front = next((a for a in apics if a.type == 3), apics[0])
return bytes(front.data), (front.mime or "image/jpeg")
if ext in (".m4a", ".mp4"):
from mutagen.mp4 import MP4
covr = MP4(path).tags.get("covr") if MP4(path).tags else None
if not covr:
return None
c = covr[0]
from mutagen.mp4 import MP4Cover
mime = "image/png" if c.imageformat == MP4Cover.FORMAT_PNG else "image/jpeg"
return bytes(c), mime
if ext == ".flac":
from mutagen.flac import FLAC
pics = FLAC(path).pictures
if not pics:
return None
front = next((p for p in pics if p.type == 3), pics[0])
return bytes(front.data), (front.mime or "image/jpeg")
except Exception: # noqa: BLE001
return None
return None
def write_cover(path: Path, data: bytes, mime: str) -> TagResult:
"""Replace the file's embedded front cover art. Best-effort."""
if not path.exists():
return TagResult(False, "file-not-found", str(path))
ext = path.suffix.lower()
mime = mime if mime in ("image/jpeg", "image/png") else "image/jpeg"
try:
if ext in (".mp3", ".aif", ".aiff"):
from mutagen.id3 import APIC
if ext == ".mp3":
from mutagen.id3 import ID3, ID3NoHeaderError
try:
tags = ID3(path)
except ID3NoHeaderError:
tags = ID3()
tags.delall("APIC")
tags.add(APIC(encoding=3, mime=mime, type=3, desc="", data=data))
tags.save(path)
else:
from mutagen.aiff import AIFF
audio = AIFF(path)
if audio.tags is None:
audio.add_tags()
audio.tags.delall("APIC")
audio.tags.add(APIC(encoding=3, mime=mime, type=3, desc="", data=data))
audio.save()
elif ext in (".m4a", ".mp4"):
from mutagen.mp4 import MP4, MP4Cover
audio = MP4(path)
if audio.tags is None:
audio.add_tags()
fmt = MP4Cover.FORMAT_PNG if mime == "image/png" else MP4Cover.FORMAT_JPEG
audio.tags["covr"] = [MP4Cover(data, imageformat=fmt)]
audio.save()
elif ext == ".flac":
from mutagen.flac import FLAC, Picture
audio = FLAC(path)
audio.clear_pictures()
pic = Picture()
pic.type = 3
pic.mime = mime
pic.data = data
audio.add_picture(pic)
audio.save()
else:
return TagResult(False, "unsupported-format", ext)
except Exception as ex: # noqa: BLE001
return TagResult(False, "error", f"{type(ex).__name__}: {ex}")
return TagResult(True, "written")
def _clean(v) -> str | None:
if v is None:
return None
s = str(v).strip()
return s or None
def write_tags(path: Path, meta: TagMeta) -> TagResult:
if not path.exists():
return TagResult(False, "file-not-found", str(path))
ext = path.suffix.lower()
try:
if ext == ".mp3":
_write_id3(path, meta, id3_only=False)
elif ext in (".aif", ".aiff"):
_write_aiff(path, meta)
elif ext in (".m4a", ".mp4") or path.name.lower().endswith(".stem.m4a"):
_write_mp4(path, meta)
elif ext == ".flac":
_write_flac(path, meta)
else:
# WAV and anything else: tag support is weak/inconsistent — skip.
return TagResult(False, "unsupported-format", ext)
except Exception as ex: # noqa: BLE001 — best-effort; report, don't crash save
return TagResult(False, "error", f"{type(ex).__name__}: {ex}")
return TagResult(True, "written")
# ---- ID3 (mp3 / aiff) --------------------------------------------------
def _apply_id3(id3, meta: TagMeta) -> None:
from mutagen.id3 import (
COMM,
POPM,
TALB,
TCON,
TDRC,
TIT2,
TIT3,
TPE1,
TPE4,
TPUB,
TXXX,
)
simple = {
"title": TIT2,
"artist": TPE1,
"album": TALB,
"genre": TCON,
"label": TPUB,
"remixer": TPE4,
"mix": TIT3,
"release_date": TDRC,
}
for field, frame in simple.items():
if field in meta:
val = _clean(meta[field])
id3.delall(frame.__name__)
if val is not None:
id3.add(frame(encoding=3, text=[val]))
if "producer" in meta:
id3.delall("TXXX:PRODUCER")
val = _clean(meta["producer"])
if val is not None:
id3.add(TXXX(encoding=3, desc="PRODUCER", text=[val]))
if "comment" in meta:
id3.delall("COMM")
val = _clean(meta["comment"])
if val is not None:
id3.add(COMM(encoding=3, lang="eng", desc="", text=[val]))
if "rating" in meta:
id3.delall("POPM")
stars = int(meta["rating"] or 0)
if stars > 0:
id3.add(
POPM(
email="traktor@native-instruments.de",
rating=max(0, min(5, stars)) * 51,
count=0,
)
)
def _write_id3(path: Path, meta: TagMeta, id3_only: bool) -> None:
from mutagen.id3 import ID3, ID3NoHeaderError
try:
id3 = ID3(path)
except ID3NoHeaderError:
id3 = ID3()
_apply_id3(id3, meta)
id3.save(path)
def _write_aiff(path: Path, meta: TagMeta) -> None:
from mutagen.aiff import AIFF
audio = AIFF(path)
if audio.tags is None:
audio.add_tags()
_apply_id3(audio.tags, meta)
audio.save()
# ---- MP4 (m4a / stem) --------------------------------------------------
def _write_mp4(path: Path, meta: TagMeta) -> None:
from mutagen.mp4 import MP4, MP4FreeForm
audio = MP4(path)
if audio.tags is None:
audio.add_tags()
t = audio.tags
standard = {
"title": "\xa9nam",
"artist": "\xa9ART",
"album": "\xa9alb",
"genre": "\xa9gen",
"comment": "\xa9cmt",
"release_date": "\xa9day",
}
for field, atom in standard.items():
if field in meta:
val = _clean(meta[field])
if val is None:
t.pop(atom, None)
else:
t[atom] = [val]
# No standard MP4 atoms for these — use iTunes-style freeform atoms.
freeform = {"label": "LABEL", "remixer": "REMIXER", "producer": "PRODUCER", "mix": "MIX"}
for field, name in freeform.items():
if field in meta:
key = f"----:com.apple.iTunes:{name}"
val = _clean(meta[field])
if val is None:
t.pop(key, None)
else:
t[key] = [MP4FreeForm(val.encode("utf-8"))]
if "rating" in meta:
key = "----:com.apple.iTunes:RATING"
stars = int(meta["rating"] or 0)
if stars > 0:
t[key] = [MP4FreeForm(str(max(0, min(5, stars)) * 51).encode("utf-8"))]
else:
t.pop(key, None)
audio.save()
# ---- FLAC --------------------------------------------------------------
def _write_flac(path: Path, meta: TagMeta) -> None:
from mutagen.flac import FLAC
audio = FLAC(path)
mapping = {
"title": "title",
"artist": "artist",
"album": "album",
"genre": "genre",
"label": "label",
"remixer": "remixer",
"producer": "producer",
"comment": "comment",
"mix": "mixname",
"release_date": "date",
}
for field, vc in mapping.items():
if field in meta:
val = _clean(meta[field])
if val is None:
audio.pop(vc, None)
else:
audio[vc] = [val]
if "rating" in meta:
stars = int(meta["rating"] or 0)
if stars > 0:
audio["rating"] = [str(max(0, min(5, stars)) * 51)]
else:
audio.pop("rating", None)
audio.save()
+50 -3
View File
@@ -9,7 +9,7 @@ from __future__ import annotations
import os
from pathlib import Path
from fastapi import FastAPI, HTTPException, Query
from fastapi import FastAPI, File, Form, HTTPException, Query, Response, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from .collection_service import CollectionService
@@ -18,7 +18,9 @@ from .schemas import (
CollectionStatus,
CreatePlaylist,
EditState,
EditTrack,
Facets,
FileTagOutcome,
FsEntry,
FsListing,
OpenCollection,
@@ -272,10 +274,55 @@ def add_entries(playlist_uuid: str, body: SetEntries) -> dict:
return {"status": "added", "id": playlist_uuid, "added": len(added), "count": len(entries)}
@app.patch("/api/tracks")
def edit_track(body: EditTrack) -> dict:
"""Edit a single track's safe metadata fields (in-memory; persisted on save)."""
store = require_store()
try:
store.set_track_metadata(body.track_id, body.fields)
except PlaylistError as ex:
raise HTTPException(404, str(ex))
# Keep the read projection in sync so the edit shows immediately.
entry = store.model_entry(body.track_id)
if entry is not None:
require_service().replace_track(body.track_id, entry)
return {"status": "updated", "id": body.track_id}
@app.get("/api/tracks/art")
def track_art(track_id: str) -> Response:
"""Stream a track's embedded cover art (staged replacement if unsaved)."""
art = require_store().cover_art(track_id)
if art is None:
raise HTTPException(404, "No cover art")
data, mime = art
return Response(content=data, media_type=mime, headers={"Cache-Control": "no-store"})
@app.put("/api/tracks/art")
async def set_track_art(track_id: str = Form(...), file: UploadFile = File(...)) -> dict:
"""Stage replacement cover art for a track (written to the file on save)."""
store = require_store()
data = await file.read()
if not data:
raise HTTPException(400, "Empty image")
mime = file.content_type or "image/jpeg"
try:
store.set_track_art(track_id, data, mime)
except PlaylistError as ex:
raise HTTPException(404, str(ex))
return {"status": "staged", "id": track_id, "bytes": len(data)}
@app.post("/api/save", response_model=SaveResult)
def save() -> SaveResult:
store = require_store()
if not store.dirty:
return SaveResult(saved=False, backup=None, playlists=store.count_playlists())
backup = store.save()
return SaveResult(saved=True, backup=str(backup), playlists=store.count_playlists())
outcome = store.save()
return SaveResult(
saved=True,
backup=str(outcome.backup),
playlists=store.count_playlists(),
file_tags=[FileTagOutcome(**r.__dict__) for r in outcome.tag_results],
)
+146 -29
View File
@@ -17,11 +17,11 @@ Playlists are identified by their stable UUID; folders by a synthetic path id
"""
from __future__ import annotations
import re
import shutil
import threading
import time
import uuid as uuidlib
from dataclasses import dataclass
from pathlib import Path
from traktor_nml_utils import (
@@ -30,7 +30,9 @@ from traktor_nml_utils import (
restore_traktor_float_format,
)
from traktor_nml_utils.models.collection import (
Albumtype,
Entrytype,
Infotype,
Nodetype,
Playlisttype,
Primarykeytype,
@@ -40,14 +42,26 @@ from xsdata.formats.dataclass.serializers import XmlSerializer
from .schemas import PlaylistNode
_PLAYLISTS_OPEN = re.compile(rb"<PLAYLISTS[ >]")
_PLAYLISTS_CLOSE = re.compile(rb"</PLAYLISTS>")
class PlaylistError(Exception):
pass
@dataclass
class FileTagResult:
track_id: str
file: str
ok: bool
status: str # "written" | "file-not-found" | "unsupported-format" | "error"
detail: str = ""
@dataclass
class SaveOutcome:
backup: Path
tag_results: list[FileTagResult]
class PlaylistStore:
def __init__(self, nml_path: Path):
self.nml_path = Path(nml_path)
@@ -57,14 +71,20 @@ class PlaylistStore:
# ---- load ----------------------------------------------------------
def _load(self) -> None:
self._raw = self.nml_path.read_bytes()
mo = _PLAYLISTS_OPEN.search(self._raw)
mc = _PLAYLISTS_CLOSE.search(self._raw)
if not mo or not mc:
raise PlaylistError("Could not locate <PLAYLISTS> section in NML")
self._span = (mo.start(), mc.end())
self._collection = TraktorCollection(path=self.nml_path)
self._nml = self._collection.nml
# Index collection entries by their Traktor primary key (volume+dir+file)
# so track-metadata edits can find their ENTRY in O(1).
self._entry_by_key: dict[str, Entrytype] = {}
for e in self._nml.collection.entry:
loc = e.location
if loc:
key = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}"
self._entry_by_key[key] = e
# track_id -> set of field names edited this session (drives file-tag sync)
self._track_edits: dict[str, set[str]] = {}
# track_id -> (image_bytes, mime) of staged replacement cover art
self._track_art: dict[str, tuple[bytes, str]] = {}
self.dirty = False
def _root(self) -> Nodetype:
@@ -209,35 +229,132 @@ class PlaylistStore:
pl.entries = len(pl.entry)
self.dirty = True
# ---- track metadata editing ---------------------------------------
# Safe, free-text-ish fields only. Deliberately NOT editable here: file path
# (it's the primary key), bpm/key (audio/grid territory), and read-only info
# like bitrate/playcount.
_INFO_FIELDS = {"genre", "label", "remixer", "producer", "comment", "mix", "release_date"}
EDITABLE_FIELDS = {"title", "artist", "album", "rating"} | _INFO_FIELDS
def set_track_metadata(self, track_id: str, fields: dict) -> None:
with self._lock:
entry = self._entry_by_key.get(track_id)
if entry is None:
raise PlaylistError(f"Track not found: {track_id}")
if entry.info is None:
entry.info = Infotype()
for k, v in fields.items():
if k in ("title", "artist"):
setattr(entry, k, v or None)
elif k == "album":
if entry.album is None:
entry.album = Albumtype()
entry.album.title = v or None
elif k in self._INFO_FIELDS:
setattr(entry.info, k, v or None)
elif k == "rating":
stars = max(0, min(5, int(v))) if v is not None else 0
# Traktor RANKING = stars * 51; unrated has no RANKING attr.
entry.info.ranking = stars * 51 or None
else:
continue # unknown / read-only fields are ignored
self._track_edits.setdefault(track_id, set()).add(k)
self.dirty = True
def model_entry(self, track_id: str) -> Entrytype | None:
with self._lock:
return self._entry_by_key.get(track_id)
# ---- cover art -----------------------------------------------------
def set_track_art(self, track_id: str, data: bytes, mime: str) -> None:
with self._lock:
if track_id not in self._entry_by_key:
raise PlaylistError(f"Track not found: {track_id}")
self._track_art[track_id] = (data, mime)
self.dirty = True
def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
"""Staged replacement if present, else the file's current embedded art."""
from . import file_tags
with self._lock:
if track_id in self._track_art:
return self._track_art[track_id]
entry = self._entry_by_key.get(track_id)
if entry is None or entry.location is None:
return None
loc = entry.location
return file_tags.read_cover(file_tags.resolve_path(loc.volume, loc.dir, loc.file))
def _entry_field_value(self, entry: Entrytype, field: str):
"""Read a single editable field's current value from the model, in the
shape file_tags expects (rating as 0–5 stars)."""
if field == "title":
return entry.title
if field == "artist":
return entry.artist
if field == "album":
return entry.album.title if entry.album else None
if field == "rating":
r = entry.info.ranking if entry.info else None
return round(r / 51) if r else 0
return getattr(entry.info, field, None) if entry.info else None
def count_playlists(self) -> int:
with self._lock:
return sum(1 for n in self._iter_nodes(self._root()) if n.playlist is not None)
# ---- persistence ---------------------------------------------------
def save(self) -> Path:
def save(self) -> "SaveOutcome":
with self._lock:
backup = self._backup()
# Render the full model exactly as the library's save() does — the
# two post-processing steps restore Traktor's precise layout (expanded
# empty tags, 6-decimal floats, newlines), so unedited playlists come
# out byte-for-byte identical and only edited ones diff.
serialized = XmlSerializer().render(self._nml)
serialized = restore_traktor_float_format(serialized, self._nml)
serialized = format_traktor_layout(serialized)
rendered = serialized.encode("utf-8")
ro = _PLAYLISTS_OPEN.search(rendered)
rc = _PLAYLISTS_CLOSE.search(rendered)
if not ro or not rc:
raise PlaylistError("Rendered output missing PLAYLISTS section")
new_pl = rendered[ro.start() : rc.end()]
s, e = self._span
new_data = self._raw[:s] + new_pl + self._raw[e:]
new_data = self._render()
tmp = self.nml_path.with_suffix(self.nml_path.suffix + ".tmp")
tmp.write_bytes(new_data)
tmp.replace(self.nml_path)
self._load()
return backup
# Best-effort: sync the edited fields into each edited track's file.
tag_results = self._sync_file_tags()
self._load() # clears dirty + _track_edits
return SaveOutcome(backup=backup, tag_results=tag_results)
def _sync_file_tags(self) -> list["FileTagResult"]:
from . import file_tags
results: list[FileTagResult] = []
# Union of tracks with edited fields and/or replaced art.
for track_id in self._track_edits.keys() | self._track_art.keys():
entry = self._entry_by_key.get(track_id)
if entry is None or entry.location is None:
continue
loc = entry.location
path = file_tags.resolve_path(loc.volume, loc.dir, loc.file)
r = None
if track_id in self._track_edits:
meta = {f: self._entry_field_value(entry, f) for f in self._track_edits[track_id]}
r = file_tags.write_tags(path, meta)
if track_id in self._track_art:
data, mime = self._track_art[track_id]
r = file_tags.write_cover(path, data, mime)
if r is not None:
results.append(
FileTagResult(
track_id=track_id, file=str(path), ok=r.ok, status=r.status, detail=r.detail
)
)
return results
def _render(self) -> bytes:
"""Render the whole model exactly as the library's save() does.
The two post-processing steps restore Traktor's precise layout (expanded
empty tags, 6-decimal floats, newlines), so a no-op render reproduces the
file byte-for-byte and only the objects we actually edited (playlists
AND/OR track entries) diff. Verified by backend/test_save_fidelity.py.
"""
s = XmlSerializer().render(self._nml)
s = restore_traktor_float_format(s, self._nml)
s = format_traktor_layout(s)
return s.encode("utf-8")
def _backup(self) -> Path:
# Backups live in a `backups/` folder next to the collection, not beside
+15
View File
@@ -15,6 +15,7 @@ class Track(BaseModel):
label: str | None = None
remixer: str | None = None
producer: str | None = None
mix: str | None = None
comment: str | None = None
bpm: float | None = None
key: str | None = None # Traktor display key, e.g. "10m"
@@ -97,10 +98,24 @@ class SetEntries(BaseModel):
track_ids: list[str] # ordered; full desired contents of the playlist
class EditTrack(BaseModel):
track_id: str
fields: dict[str, str | int | None]
class FileTagOutcome(BaseModel):
track_id: str
file: str
ok: bool
status: str
detail: str = ""
class SaveResult(BaseModel):
saved: bool
backup: str | None = None
playlists: int
file_tags: list[FileTagOutcome] = []
class EditState(BaseModel):
+2
View File
@@ -3,6 +3,8 @@
fastapi>=0.115
uvicorn[standard]>=0.34
pydantic>=2.11
mutagen>=1.47 # embedded audio-file tag read/write (ID3/MP4/FLAC/AIFF)
python-multipart>=0.0.9 # multipart form parsing for cover-art upload
# Traktor Pro 4 (NML v20) support requires the GitHub master (v4.0.0),
# NOT the stale PyPI release (3.1.0), which cannot parse v4 files.
traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git
+46
View File
@@ -129,5 +129,51 @@ with tempfile.TemporaryDirectory() as d:
n = diff_count(original[os_:oe], edited[es_:ee])
print(f" edited-block changed lines: {n} (reordered {len(keys)} entries)")
# ---- Invariant C: a track-metadata edit is fully localized -------------
print("== C. track metadata edit touches only that track's ENTRY ==")
with tempfile.TemporaryDirectory() as d:
work = Path(d) / "collection.nml"
shutil.copy2(REAL, work)
original = work.read_bytes()
store = PlaylistStore(work)
# pick the first track that has a resolvable primary key
entry = store._nml.collection.entry[0]
loc = entry.location
track_id = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}"
store.set_track_metadata(track_id, {"genre": "KONDUKTOR-FIDELITY-TEST", "rating": 4})
store.save()
edited = work.read_bytes()
check("file actually changed", original != edited)
# The edited ENTRY's <INFO> block is where the change lands. Blank out the
# whole entry span in both and require the remainder to be byte-identical.
def entry_span(data: bytes, file_name: str):
marker = f'FILE="{file_name}"'.encode()
i = data.find(marker)
start = data.rfind(b"<ENTRY ", 0, i)
end = data.find(b"</ENTRY>", i) + len(b"</ENTRY>")
return start, end
os_, oe = entry_span(original, loc.file)
es_, ee = entry_span(edited, loc.file)
check(
"everything outside the edited track's ENTRY is byte-identical",
original[:os_] + b"@@" + original[oe:] == edited[:es_] + b"@@" + edited[ee:],
)
n = diff_count(original[os_:oe], edited[es_:ee])
check("edited ENTRY diff is tiny (<= 6 tag-lines)", n <= 6, f"got {n}")
print(f" edited-ENTRY changed tag-lines: {n}")
# Re-parses and the edit persisted.
from traktor_nml_utils import TraktorCollection
reparsed = TraktorCollection(path=work)
e0 = reparsed.nml.collection.entry[0]
check("re-parses + genre persisted", e0.info.genre == "KONDUKTOR-FIDELITY-TEST")
check("rating persisted (4 stars => RANKING 204)", e0.info.ranking == 204)
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+22
View File
@@ -10,6 +10,8 @@ import { SelectionBar } from './components/SelectionBar'
import { StatusBar } from './components/StatusBar'
import { Toast, type ToastMsg } from './components/Toast'
import { CollectionPicker } from './components/CollectionPicker'
import { ContextMenu } from './components/ContextMenu'
import { EditTagsDialog } from './components/EditTagsDialog'
function applyFilters(tracks: Track[], f: Filters): Track[] {
const q = f.search.trim().toLowerCase()
@@ -39,6 +41,8 @@ export default function App() {
const [selected, setSelected] = useState<Set<string>>(new Set())
const [toast, setToast] = useState<ToastMsg | null>(null)
const [forcePicker, setForcePicker] = useState(false)
const [menu, setMenu] = useState<{ track: Track; x: number; y: number } | null>(null)
const [editing, setEditing] = useState<Track | null>(null)
const notify = useCallback((kind: ToastMsg['kind'], text: string) => {
setToast({ id: Date.now(), kind, text })
@@ -117,6 +121,22 @@ export default function App() {
return (
<div className="flex h-screen w-screen overflow-hidden bg-ink-950">
<Toast toast={toast} onClose={() => setToast(null)} />
{menu && (
<ContextMenu
x={menu.x}
y={menu.y}
items={[{ label: 'Edit Tags…', onClick: () => setEditing(menu.track) }]}
onClose={() => setMenu(null)}
/>
)}
{editing && (
<EditTagsDialog
track={editing}
onClose={() => setEditing(null)}
onApplied={(msg) => notify('success', msg)}
onError={onError}
/>
)}
<Sidebar source={source} onSelect={selectSource} onError={onError} />
<main className="relative flex min-w-0 flex-1 flex-col">
@@ -152,6 +172,7 @@ export default function App() {
onToggleAll: toggleAll,
allSelected: selected.size > 0 && selected.size === filtered.length,
}}
onRowContextMenu={(track, x, y) => setMenu({ track, x, y })}
/>
)
) : (
@@ -159,6 +180,7 @@ export default function App() {
uuid={(source as { id: string }).id}
tracks={tracks}
onError={onError}
onRowContextMenu={(track, x, y) => setMenu({ track, x, y })}
/>
)}
+12
View File
@@ -9,6 +9,7 @@ export interface Track {
label: string | null
remixer: string | null
producer: string | null
mix: string | null
comment: string | null
bpm: number | null
key: string | null
@@ -196,4 +197,15 @@ export const api = {
{ track_ids: trackIds },
),
save: () => send<SaveResult>('POST', '/api/save'),
editTrack: (trackId: string, fields: Record<string, string | number | null>) =>
send<{ status: string }>('PATCH', '/api/tracks', { track_id: trackId, fields }),
artUrl: (trackId: string) => `/api/tracks/art?track_id=${encodeURIComponent(trackId)}`,
uploadArt: async (trackId: string, file: File) => {
const fd = new FormData()
fd.append('track_id', trackId)
fd.append('file', file)
const res = await fetch('/api/tracks/art', { method: 'PUT', body: fd })
if (!res.ok) throw new Error(`Cover upload failed (${res.status})`)
return res.json()
},
}
+62
View File
@@ -0,0 +1,62 @@
import { useEffect } from 'react'
export interface MenuItem {
label: string
onClick: () => void
danger?: boolean
}
interface Props {
x: number
y: number
items: MenuItem[]
onClose: () => void
}
// Lightweight fixed-position menu. Closes on outside click, scroll, or Escape.
export function ContextMenu({ x, y, items, onClose }: Props) {
useEffect(() => {
const close = () => onClose()
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
// Defer attaching outside-dismiss listeners by a tick so the very
// right-click/click that opened the menu can't immediately close it.
const id = setTimeout(() => {
window.addEventListener('click', close)
window.addEventListener('contextmenu', close)
window.addEventListener('scroll', close, true)
window.addEventListener('keydown', onKey)
}, 0)
return () => {
clearTimeout(id)
window.removeEventListener('click', close)
window.removeEventListener('contextmenu', close)
window.removeEventListener('scroll', close, true)
window.removeEventListener('keydown', onKey)
}
}, [onClose])
return (
<div
className="fixed z-50 min-w-[160px] overflow-hidden rounded-lg border border-line bg-ink-850 py-1 shadow-2xl"
style={{ top: Math.min(y, window.innerHeight - 100), left: Math.min(x, window.innerWidth - 180) }}
onClick={(e) => e.stopPropagation()}
>
{items.map((item, i) => (
<button
key={i}
onClick={() => {
item.onClick()
onClose()
}}
className={`block w-full px-3 py-1.5 text-left text-sm ${
item.danger
? 'text-pink hover:bg-ink-800'
: 'text-muted hover:bg-ink-800 hover:text-text'
}`}
>
{item.label}
</button>
))}
</div>
)
}
+231
View File
@@ -0,0 +1,231 @@
import { useRef, useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api, type Track } from '../api'
import { formatBpm, formatDuration } from '../lib/format'
interface Props {
track: Track
onClose: () => void
onApplied: (msg: string) => void
onError: (msg: string) => void
}
// Editable free-text fields (mirrors the backend's safe set). Rating is separate.
const TEXT_FIELDS: { key: keyof Track; label: string; textarea?: boolean }[] = [
{ key: 'title', label: 'Title' },
{ key: 'artist', label: 'Artist' },
{ key: 'album', label: 'Album' },
{ key: 'genre', label: 'Genre' },
{ key: 'label', label: 'Label' },
{ key: 'remixer', label: 'Remixer' },
{ key: 'producer', label: 'Producer' },
{ key: 'mix', label: 'Mix' },
{ key: 'release_date', label: 'Release date' },
{ key: 'comment', label: 'Comment', textarea: true },
]
export function EditTagsDialog({ track, onClose, onApplied, onError }: Props) {
const qc = useQueryClient()
const { data: facets } = useQuery({ queryKey: ['facets'], queryFn: api.facets })
const [form, setForm] = useState<Record<string, string>>(() => {
const f: Record<string, string> = {}
for (const { key } of TEXT_FIELDS) f[key] = (track[key] as string | null) ?? ''
return f
})
const [rating, setRating] = useState<number>(track.rating)
const [artFile, setArtFile] = useState<File | null>(null)
const [artPreview, setArtPreview] = useState<string | null>(null)
const [artMissing, setArtMissing] = useState(false)
const fileInput = useRef<HTMLInputElement>(null)
const changedFields = () => {
const changed: Record<string, string | number | null> = {}
for (const { key } of TEXT_FIELDS) {
const orig = (track[key] as string | null) ?? ''
if (form[key] !== orig) changed[key] = form[key]
}
if (rating !== track.rating) changed.rating = rating
return changed
}
const apply = useMutation({
mutationFn: async () => {
if (artFile) await api.uploadArt(track.id, artFile)
const changed = changedFields()
if (Object.keys(changed).length > 0) await api.editTrack(track.id, changed)
},
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['tracks'] })
qc.invalidateQueries({ queryKey: ['playlist'] })
qc.invalidateQueries({ queryKey: ['state'] })
qc.invalidateQueries({ queryKey: ['facets'] })
qc.invalidateQueries({ queryKey: ['stats'] })
onApplied(`Updated “${form.title || track.title || 'track'}” — Save to write to Traktor`)
onClose()
},
onError: (e: Error) => onError(e.message),
})
const pickArt = (f: File | null) => {
if (!f) return
setArtFile(f)
setArtPreview(URL.createObjectURL(f))
setArtMissing(false)
}
const submit = () => {
if (!artFile && Object.keys(changedFields()).length === 0) {
onClose()
return
}
apply.mutate()
}
return (
<div
className="fixed inset-0 z-40 flex items-center justify-center bg-black/60 p-6"
onClick={onClose}
>
<div
className="flex max-h-[85vh] w-full max-w-lg flex-col overflow-hidden rounded-xl border border-line bg-ink-900 shadow-2xl"
onClick={(e) => e.stopPropagation()}
>
<div className="border-b border-line px-5 py-4">
<div className="text-[15px] font-semibold tracking-tight">Edit Tags</div>
<div className="truncate text-xs text-muted">
{track.artist} — {track.title}
</div>
</div>
<div className="min-h-0 flex-1 space-y-3 overflow-y-auto px-5 py-4">
{/* Album art */}
<div className="flex items-center gap-4">
<div className="flex h-24 w-24 shrink-0 items-center justify-center overflow-hidden rounded-md border border-line bg-ink-850">
{artPreview ? (
<img src={artPreview} alt="cover" className="h-full w-full object-cover" />
) : artMissing ? (
<span className="text-[10px] uppercase tracking-wider text-faint">No art</span>
) : (
<img
src={api.artUrl(track.id)}
alt="cover"
className="h-full w-full object-cover"
onError={() => setArtMissing(true)}
/>
)}
</div>
<div className="min-w-0">
<span className="mb-1 block text-[11px] font-semibold uppercase tracking-wider text-faint">
Album art
</span>
<input
ref={fileInput}
type="file"
accept="image/jpeg,image/png"
className="hidden"
onChange={(e) => pickArt(e.target.files?.[0] ?? null)}
/>
<button
onClick={() => fileInput.current?.click()}
className="rounded-md border border-line bg-ink-850 px-3 py-1.5 text-sm text-text hover:border-ink-600"
>
{artFile ? 'Change image…' : 'Replace…'}
</button>
{artFile && (
<div className="mt-1 truncate text-[11px] text-mint">{artFile.name} (applies on Save)</div>
)}
</div>
</div>
{TEXT_FIELDS.map(({ key, label, textarea }) => (
<label key={key} className="block">
<span className="mb-1 block text-[11px] font-semibold uppercase tracking-wider text-faint">
{label}
</span>
{textarea ? (
<textarea
value={form[key]}
onChange={(e) => setForm({ ...form, [key]: e.target.value })}
rows={2}
className="w-full resize-y rounded-md border border-line bg-ink-850 px-2.5 py-1.5 text-sm text-text outline-none focus:border-accent"
/>
) : (
<input
value={form[key]}
onChange={(e) => setForm({ ...form, [key]: e.target.value })}
list={key === 'genre' ? 'genre-suggestions' : undefined}
className="w-full rounded-md border border-line bg-ink-850 px-2.5 py-1.5 text-sm text-text outline-none focus:border-accent"
/>
)}
</label>
))}
<datalist id="genre-suggestions">
{facets?.genres.map((g) => <option key={g.name} value={g.name} />)}
</datalist>
{/* Rating */}
<div>
<span className="mb-1 block text-[11px] font-semibold uppercase tracking-wider text-faint">
Rating
</span>
<div className="flex items-center gap-1 text-xl">
{[1, 2, 3, 4, 5].map((i) => (
<button
key={i}
onClick={() => setRating(i === rating ? 0 : i)}
className={i <= rating ? 'text-gold' : 'text-ink-600 hover:text-faint'}
>
★
</button>
))}
{rating > 0 && (
<button
onClick={() => setRating(0)}
className="ml-2 text-xs text-faint hover:text-text"
>
clear
</button>
)}
</div>
</div>
{/* Read-only technical fields */}
<div className="mt-2 grid grid-cols-2 gap-x-4 gap-y-1 rounded-md bg-ink-850 px-3 py-2 text-xs text-muted">
<div>BPM: <span className="tabular-nums text-text">{formatBpm(track.bpm)}</span></div>
<div>Key: <span className="text-text">{track.key ?? '—'}</span></div>
<div>Length: <span className="tabular-nums text-text">{formatDuration(track.length)}</span></div>
<div>Bitrate: <span className="tabular-nums text-text">{track.bitrate ? Math.round(track.bitrate / 1000) + 'k' : '—'}</span></div>
<div>Plays: <span className="tabular-nums text-text">{track.playcount ?? 0}</span></div>
<div>Cues: <span className="tabular-nums text-text">{track.cue_count}</span></div>
<div className="col-span-2 truncate" title={track.filepath ?? ''}>
Path: <span className="text-text">{track.filepath ?? '—'}</span>
</div>
</div>
<p className="text-[11px] leading-snug text-faint">
BPM, key and path aren’t editable here. Changes apply in-app; click
<span className="text-muted"> Save to Traktor</span> to write them to disk.
New album art is written into the file; Traktor may need a manual
“Import Cover Art” to refresh its own cached thumbnail.
</p>
</div>
<div className="flex items-center justify-end gap-2 border-t border-line px-5 py-3">
<button
onClick={onClose}
className="rounded-md px-3 py-1.5 text-sm text-muted hover:bg-ink-800 hover:text-text"
>
Cancel
</button>
<button
onClick={submit}
disabled={apply.isPending}
className="rounded-md bg-accent px-4 py-1.5 text-sm font-medium text-ink-950 hover:brightness-110 disabled:opacity-50"
>
{apply.isPending ? 'Applying…' : 'Apply'}
</button>
</div>
</div>
</div>
)
}
+16 -2
View File
@@ -24,16 +24,19 @@ interface Props {
uuid: string
tracks: Track[]
onError: (msg: string) => void
onRowContextMenu?: (track: Track, x: number, y: number) => void
}
function Row({
track,
index,
onRemove,
onContextMenu,
}: {
track: Track
index: number
onRemove: (id: string) => void
onContextMenu?: (track: Track, x: number, y: number) => void
}) {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } =
useSortable({ id: track.id })
@@ -45,6 +48,11 @@ function Row({
className={`flex items-center border-b border-ink-850 text-sm ${
isDragging ? 'z-10 bg-ink-800 shadow-lg' : 'hover:bg-ink-850'
}`}
onContextMenu={(e) => {
if (!onContextMenu) return
e.preventDefault()
onContextMenu(track, e.clientX, e.clientY)
}}
>
<button
{...attributes}
@@ -90,7 +98,7 @@ function Row({
)
}
export function PlaylistEditor({ uuid, tracks, onError }: Props) {
export function PlaylistEditor({ uuid, tracks, onError, onRowContextMenu }: Props) {
const qc = useQueryClient()
const [items, setItems] = useState<Track[]>(tracks)
@@ -157,7 +165,13 @@ export function PlaylistEditor({ uuid, tracks, onError }: Props) {
>
<SortableContext items={items.map((t) => t.id)} strategy={verticalListSortingStrategy}>
{items.map((t, i) => (
<Row key={t.id} track={t} index={i} onRemove={remove} />
<Row
key={t.id}
track={t}
index={i}
onRemove={remove}
onContextMenu={onRowContextMenu}
/>
))}
</SortableContext>
</DndContext>
+7 -1
View File
@@ -108,9 +108,10 @@ interface Props {
sorting: SortingState
onSortingChange: (s: SortingState) => void
selection?: Selection
onRowContextMenu?: (track: Track, x: number, y: number) => void
}
export function TrackTable({ tracks, sorting, onSortingChange, selection }: Props) {
export function TrackTable({ tracks, sorting, onSortingChange, selection, onRowContextMenu }: Props) {
const table = useReactTable({
data: tracks,
columns,
@@ -191,6 +192,11 @@ export function TrackTable({ tracks, sorting, onSortingChange, selection }: Prop
height: vr.size,
width: '100%',
}}
onContextMenu={(e) => {
if (!onRowContextMenu) return
e.preventDefault()
onRowContextMenu(row.original, e.clientX, e.clientY)
}}
>
{selection ? (
<span className="flex w-10 shrink-0 items-center justify-center">