diff --git a/backend/konduktor/collection_service.py b/backend/konduktor/collection_service.py index 9b36f52..9ae7b32 100644 --- a/backend/konduktor/collection_service.py +++ b/backend/konduktor/collection_service.py @@ -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).""" diff --git a/backend/konduktor/file_tags.py b/backend/konduktor/file_tags.py new file mode 100644 index 0000000..c82d52e --- /dev/null +++ b/backend/konduktor/file_tags.py @@ -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/. + """ + 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() diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index fd9b0d2..26026d0 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -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], + ) diff --git a/backend/konduktor/playlist_store.py b/backend/konduktor/playlist_store.py index 5d62bc5..ca8089a 100644 --- a/backend/konduktor/playlist_store.py +++ b/backend/konduktor/playlist_store.py @@ -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_CLOSE = re.compile(rb"") - 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 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 diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index 38be8c5..b9f8a45 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -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): diff --git a/backend/requirements.txt b/backend/requirements.txt index a1585b1..8551c76 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -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 diff --git a/backend/test_save_fidelity.py b/backend/test_save_fidelity.py index e4d4e7d..c0c1995 100644 --- a/backend/test_save_fidelity.py +++ b/backend/test_save_fidelity.py @@ -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 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"", i) + len(b"") + 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) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 339ed2c..64b6926 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -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>(new Set()) const [toast, setToast] = useState(null) const [forcePicker, setForcePicker] = useState(false) + const [menu, setMenu] = useState<{ track: Track; x: number; y: number } | null>(null) + const [editing, setEditing] = useState(null) const notify = useCallback((kind: ToastMsg['kind'], text: string) => { setToast({ id: Date.now(), kind, text }) @@ -117,6 +121,22 @@ export default function App() { return (
setToast(null)} /> + {menu && ( + setEditing(menu.track) }]} + onClose={() => setMenu(null)} + /> + )} + {editing && ( + setEditing(null)} + onApplied={(msg) => notify('success', msg)} + onError={onError} + /> + )}
@@ -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 })} /> )} diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 0a2dddb..364bea9 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -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('POST', '/api/save'), + editTrack: (trackId: string, fields: Record) => + 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() + }, } diff --git a/frontend/src/components/ContextMenu.tsx b/frontend/src/components/ContextMenu.tsx new file mode 100644 index 0000000..e3171ff --- /dev/null +++ b/frontend/src/components/ContextMenu.tsx @@ -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 ( +
e.stopPropagation()} + > + {items.map((item, i) => ( + + ))} +
+ ) +} diff --git a/frontend/src/components/EditTagsDialog.tsx b/frontend/src/components/EditTagsDialog.tsx new file mode 100644 index 0000000..a6bb3c0 --- /dev/null +++ b/frontend/src/components/EditTagsDialog.tsx @@ -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>(() => { + const f: Record = {} + for (const { key } of TEXT_FIELDS) f[key] = (track[key] as string | null) ?? '' + return f + }) + const [rating, setRating] = useState(track.rating) + const [artFile, setArtFile] = useState(null) + const [artPreview, setArtPreview] = useState(null) + const [artMissing, setArtMissing] = useState(false) + const fileInput = useRef(null) + + const changedFields = () => { + const changed: Record = {} + 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 ( +
+
e.stopPropagation()} + > +
+
Edit Tags
+
+ {track.artist} — {track.title} +
+
+ +
+ {/* Album art */} +
+
+ {artPreview ? ( + cover + ) : artMissing ? ( + No art + ) : ( + cover setArtMissing(true)} + /> + )} +
+
+ + Album art + + pickArt(e.target.files?.[0] ?? null)} + /> + + {artFile && ( +
{artFile.name} (applies on Save)
+ )} +
+
+ + {TEXT_FIELDS.map(({ key, label, textarea }) => ( +