mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Implemented metadata editing
This commit is contained in:
1 parent
cc254e9a9b
commit
279e5ac34f
13 files changed
+943
-35
No files matched your search
@@ -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)."""
|
||||
|
||||
@@ -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()
|
||||
@@ -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],
|
||||
)
|
||||
@@ -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,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):
|
||||
|
||||
@@ -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
|
||||
@@ -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)
|
||||
Reference in new issue
Block a user