"""Konduktor FastAPI app. The collection to work on is chosen at runtime (see /api/collection/open) — the app starts with nothing loaded and the UI gates on that. Setting KONDUKTOR_NML in the environment auto-loads that file on startup (used by dev and tests). """ from __future__ import annotations import logging import os from dataclasses import dataclass from pathlib import Path from types import SimpleNamespace from fastapi import FastAPI, File, Form, HTTPException, Query, Response, UploadFile from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse, JSONResponse from . import __version__, exporter, exports, local_push, loudness_store, prefs from .app_state import STATE from .core import auto_hotcues as ah from .core import grid_detect, key_detect, loudness, structure from .core.grid_plan import GridStep, plan_grid from . import importer from .core import export as core_export from .core import places, registry from .core.folder import FolderScanner, FolderSource from .core.adapter import ( AdapterError, InvalidCommand, LibraryAdapter, LibraryNotSupported, NotFound, Unavailable, Unsupported, ) from .core.capabilities import Capabilities from .jobs import JOBS, Job, JobBusy from .core.pathmap import PathMapping from .schemas import ( Relocation, RelocationApplied, RelocationApply, RelocationCandidate, RelocationVolume, AnalyzePreview, AnalyzeRequest, LoudnessRequest, LoudnessValue, LoudnessValues, MeasureLoudnessRequest, AutoGridBatchRequest, AutoGridRequest, AutoCueOutcome, AutoHotcue, AutoHotcuesBatchRequest, TrackIds, AutoHotcuesRequest, AutoHotcuesResult, CollectionCandidate, CollectionOptions, CollectionStatus, CreatePlaylist, EditState, LibraryInfo, PlatformOption, EditTrack, SetTrackColor, Facets, FileTagOutcome, CreateExportSet, ExportContents, ExportPlaylistOut, ExportSetMembers, ExportSetOut, ExportPreview, LocalLibrariesOut, PushPreview, Drive, DroppedFiles, DroppedPaths, FolderAddRequest, FolderTracks, FsEntry, FsListing, FsPlace, UpdateExportSet, RunExport, AddGridMarker, GridMarkerEdit, ReplaceGrid, HistoryEntry, ImportRequest, JobStatus, OpenCollection, OpenRemote, OpenSource, RemoteIn, PathMappingInfo, PlaylistNode, PrefixSuggestions, RemapPreview, RemapResult, RenamePlaylist, SaveResult, AddEntries, RemoveEntries, MovePlaylist, SetEntries, SourceCandidate, SourceStatus, SetCue, SetCueColor, SetCueType, AddMemoryCue, RenameMemoryCue, SetMemoryCueColor, SetMemoryCueType, SetGridLock, Stats, Track, TrackCues, TrackPage, StemEngineInstall, StemSideLoad, StemConvert, NormalizeRequest, ) log = logging.getLogger(__name__) app = FastAPI(title="Konduktor API", version=__version__) app.add_middleware( CORSMiddleware, allow_origins=[ "http://localhost:5173", "http://127.0.0.1:5173", # Packaged desktop app: the webview's origin when Tauri loads the built # frontend. macOS uses tauri://; Windows/Linux default to # https://tauri.localhost, but lib.rs forces the http scheme # (use_https_scheme(false)) so the sidecar is not mixed content — # without the http origin here, the Windows app reaches no API at all. "tauri://localhost", "http://tauri.localhost", "https://tauri.localhost", ], allow_methods=["*"], allow_headers=["*"], ) def require_adapter() -> LibraryAdapter: """The loaded library, or a 409. Routes talk to this and nothing else.""" if not STATE.loaded: raise HTTPException(409, "No collection loaded") assert STATE.adapter is not None return STATE.adapter @app.exception_handler(AdapterError) def _adapter_error(_request, exc: AdapterError): """Map the adapter's error vocabulary onto status codes in one place, so no route has to guess whether a given failure is a 400 or a 404.""" status = { NotFound: 404, InvalidCommand: 400, Unsupported: 422, LibraryNotSupported: 400, }.get(type(exc), 503 if isinstance(exc, Unavailable) else 400) return JSONResponse(status_code=status, content={"detail": str(exc)}) # ---- collection selection --------------------------------------------- @app.get("/api/library", response_model=CollectionStatus) def collection_status() -> CollectionStatus: if not STATE.loaded: return CollectionStatus(loaded=False) return CollectionStatus( loaded=True, path=str(STATE.path), tracks=len(require_adapter().tracks), playlists=require_adapter().playlist_count(), library=_library_info(), ) @app.post("/api/library/open", response_model=CollectionStatus) def open_collection(body: OpenCollection) -> CollectionStatus: path = Path(body.path).expanduser() # Deliberately NOT `is_file()`. A library is a file on some platforms and a # DIRECTORY on others — OneLibrary's is the drive, Serato's will be a # `_Serato_` folder — and which shapes are valid is the driver's business. # This checks only that the path is there at all; `can_open()` decides. if not path.exists(): raise HTTPException(400, f"Not found: {path}") _stop_batches() try: STATE.open(path) except AdapterError as ex: raise HTTPException(400, f"Not a valid collection: {ex}") except Exception as ex: # noqa: BLE001 raise HTTPException(400, f"Could not open that collection: {ex}") prefs.set_last_collection(str(path), require_adapter().capabilities().platform) return collection_status() @app.get("/api/library/options", response_model=CollectionOptions) def collection_options(platform: str | None = None) -> CollectionOptions: """Startup shortcuts for the picker, scoped to one platform. Scoped because the picker asks which platform first, and both shortcuts are only meaningful inside that answer: unscoped, "auto" meant "whatever the first-registered driver happened to find" — so a plugged-in USB stick could be offered as the user's collection — and "last opened" could name a library of the platform they had just declined. `recent` may no longer exist (→ `exists=False`), which the picker shows rather than hides: a library that has moved is worth saying so about. """ detected = registry.detect_for(platform) if platform else registry.detect_all() candidates = [CollectionCandidate(**d) for d in detected] recent = None last = prefs.get_last_collection(platform) if last: recent = CollectionCandidate(**registry.describe(Path(last))) return CollectionOptions( auto=candidates[0] if candidates else None, detected=candidates, recent=recent, ) # ---- remote libraries ---------------------------------------------------------- # A library held by a Konduktor server (a container on the user's NAS), opened # from the picker's "Remote" step. The saved remotes are this computer's; the # password is in the OS keychain (`adapters/remote/config.py`). def _remote_out(remote) -> dict: out = remote.public() out["has_password"] = bool(remote_cfg().password(remote.id)) return out def remote_cfg(): from .adapters.remote import config return config def _checked_remote(body: RemoteIn, remote_id: str | None): """Build the remote from the form and handshake every address. Refuses — nothing saved — when an address answers but refuses (wrong password, a version that cannot talk), or when none answers at all; an unreachable FALLBACK alone is fine (a VPN address is often unreachable at home).""" from .adapters import remote as remote_lib config = remote_cfg() host, port = config.split_host(body.host) fallback, fallback_port = config.split_host(body.fallback_host or "") previous = config.get(remote_id) if remote_id else None password = body.password if body.password else (config.password(remote_id) if remote_id else None) if not body.name.strip() or not host or not body.username.strip(): raise HTTPException(400, "A name, an address and a username are all needed") if not password: raise HTTPException(400, "Enter the server's password") remote = config.Remote( id=previous.id if previous else config.new_id(), name=body.name.strip(), host=host, port=body.port or port, fallback_host=fallback or None, fallback_port=(body.fallback_port or fallback_port) if fallback else None, username=body.username.strip(), ) results = remote_lib.handshake(remote, password) refused = [r for r in results if r["kind"] in ("auth", "version", "other")] if refused: raise HTTPException(400, {"message": refused[0]["error"], "results": results}) if not any(r["ok"] for r in results): raise HTTPException(400, {"message": results[0]["error"], "results": results}) return remote, password, results @app.get("/api/remotes") def list_remotes() -> list[dict]: return [_remote_out(r) for r in remote_cfg().remotes()] @app.post("/api/remotes") def add_remote(body: RemoteIn) -> dict: remote, password, results = _checked_remote(body, None) config = remote_cfg() config.set_password(remote.id, password) config.save(remote) return {"remote": _remote_out(remote), "results": results} @app.patch("/api/remotes/{remote_id}") def edit_remote(remote_id: str, body: RemoteIn) -> dict: config = remote_cfg() if config.get(remote_id) is None: raise HTTPException(404, "No such remote") remote, password, results = _checked_remote(body, remote_id) config.set_password(remote.id, password) config.save(remote) return {"remote": _remote_out(remote), "results": results} @app.delete("/api/remotes/{remote_id}") def delete_remote(remote_id: str) -> dict: if STATE.remote_config is not None and STATE.remote_config.id == remote_id: raise HTTPException(409, "That remote is open — open another library first") if not remote_cfg().delete(remote_id): raise HTTPException(404, "No such remote") return {"status": "deleted"} def _running_batch() -> str | None: """The kind of batch running here, for the heartbeat: another computer asking to take over is told what it would cancel.""" for kind in BATCH_JOBS + ("import", "export", local_push.JOB_KIND): if JOBS.active(kind): return kind return None def _on_remote_change(state: str) -> None: # Taken over: whatever batch is running here is now writing into a library # this computer no longer holds — cancel it, as Cancel does (finished # tracks stay as the edits the new holder inherits). if state == "taken_over": import threading threading.Thread(target=_stop_batches, name="konduktor-takeover-stop", daemon=True).start() @app.post("/api/library/open-remote", response_model=CollectionStatus) def open_remote(body: OpenRemote) -> CollectionStatus: """Connect to a saved remote and make its library THE library. 409 `{code: "in_use", machine, since, batch}` when another computer holds it — the picker asks, and retries with `takeover`. On success, the edits another computer left unsaved are reported (`pending_edits`) for the user to save or discard. """ from .adapters import remote as remote_lib remote = remote_cfg().get(body.remote_id) if remote is None: raise HTTPException(404, "No such remote") _stop_batches() try: opened = remote_lib.open_remote(remote, takeover=body.takeover, batch_probe=_running_batch) except remote_lib.InUse as ex: raise HTTPException(409, {"code": "in_use", **ex.holder}) except AdapterError as ex: raise HTTPException(400, str(ex)) STATE.open_remote(opened) opened.session.on_change(_on_remote_change) status = collection_status() status.pending_edits = opened.pending_edits return status def _require_remote(): adapter = require_adapter() if STATE.remote is None: raise HTTPException(409, "The open library is not a remote one") return adapter @app.get("/api/library/fs/list", response_model=FsListing) def library_fs_list(path: str | None = None) -> FsListing: """Folders on the machine that HOLDS the library — where an import into a remote library lands (`tracks.audio_destination == "library"`). Confined by the server to its content folder; `home` is that folder.""" adapter = _require_remote() listing = adapter.client.fs_list(path) return FsListing( path=listing["path"], parent=listing["parent"], home=listing["root"], dirs=[FsEntry(name=e["name"], path=e["path"]) for e in listing["entries"] if e["is_dir"]], files=[], ) @app.get("/api/remote-cache") def remote_cache_status() -> dict: from .adapters.remote import cache return cache.shared().usage() @app.delete("/api/remote-cache") def clear_remote_cache() -> dict: from .adapters.remote import cache return {"freed": cache.shared().clear()} @app.get("/api/library/path-mapping", response_model=PathMappingInfo) def get_path_mapping() -> PathMappingInfo: """The current collection's saved OS-path remapping (blank if none).""" require_adapter() saved = prefs.get_path_mapping(str(STATE.path)) if saved: return PathMappingInfo.model_validate({"from": saved["from"], "to": saved["to"]}) return PathMappingInfo() @app.put("/api/library/path-mapping", response_model=PathMappingInfo) def put_path_mapping(body: PathMappingInfo) -> PathMappingInfo: """Set (or, with blank prefixes, clear) the current collection's remapping. Persists to userprefs AND updates the live store so playback/analysis re-resolve immediately — no reopen needed. Never touches the .nml.""" _require_no_pending("Changing the path mapping") a = require_adapter() mapping = PathMapping.make(body.from_, body.to) prefs.set_path_mapping( str(STATE.path), mapping.from_prefix or None, mapping.to_prefix or None ) a.set_path_mapping(mapping) return PathMappingInfo.model_validate( {"from": mapping.from_prefix, "to": mapping.to_prefix} ) @app.get("/api/library/path-mapping/suggest", response_model=PrefixSuggestions) def suggest_path_prefix() -> PrefixSuggestions: """Auto-detected `from` prefix candidates (common directory per volume), so the editor can prefill the stored prefix.""" return PrefixSuggestions.model_validate(require_adapter().path_prefix_suggestions()) @app.get("/api/library/path-mapping/preview", response_model=RemapPreview) def preview_path_mapping( from_: str = Query("", alias="from"), to: str = Query("") ) -> RemapPreview: """Validate a candidate mapping before saving/committing: how many tracks match `from` and how many exist at `to`.""" return RemapPreview.model_validate( require_adapter().remap_preview(PathMapping.make(from_, to)) ) @app.post("/api/library/remap-paths", response_model=RemapResult) def remap_paths(body: PathMappingInfo) -> RemapResult: """Write-back: permanently rewrite matching track LOCATIONs (and the playlist references that join to them) to the `to` prefix, then save (a version-history commit is written). Destructive and OS-specific — the UI warns accordingly.""" _require_no_pending("Rewriting paths") mapping = PathMapping.make(body.from_, body.to) if mapping.empty: raise HTTPException(400, "Both a `from` and `to` prefix are required") adapter = require_adapter() # A Traktor track id IS its location, so a remap renames every matching id. # Follow them, or every export set referencing a remapped track would # dangle — and dangle SILENTLY, still looking curated while quietly # exporting fewer tracks than it says. The adapter returns the renames # itself: rebuilding them here from display paths (which omit the volume) # could pair up two tracks with the same folder on different drives. moved = adapter.remap_locations(mapping) if not moved: return RemapResult(rewritten=0, commit=None) if moved and STATE.library_id: exports.retarget(STATE.library_id, moved) # The files now live under `to`: carry their loudness values across (they # are keyed by the path they were measured at). Not an edit, so not saved. try: STATE.loudness.remap(mapping) except Exception: # noqa: BLE001 — bookkeeping must never fail a remap log.warning("could not move loudness values for %s", mapping, exc_info=True) # Through AppState, not the adapter: this is the one route besides /api/save # that writes, and skipping it would leave a gap in the version history. _outcome, commit = STATE.save() return RemapResult(rewritten=len(moved), commit=commit) @app.get("/api/library/relocation", response_model=Relocation) def get_relocation() -> Relocation: """The open-time missing-files check: every stored volume in which NO track resolves, and where the search found its tracks. Empty once answered, so the UI can refetch freely without re-asking. Waits briefly for the search, then reports `scanning` so a slow drive cannot hold a request open; the UI polls until it is done. """ require_adapter() check = STATE.relocation if check is None: return Relocation() if not check.wait(timeout=10): return Relocation(scanning=True) return Relocation( volumes=[ RelocationVolume( label=p.label, root=p.root, total=p.total, status=p.status, candidates=[ RelocationCandidate.model_validate( {"from": c.mapping.from_prefix, "to": c.mapping.to_prefix, "found": c.found} ) for c in p.candidates ], ) for p in check.pending ] ) @app.post("/api/library/relocation", response_model=RelocationApplied) def answer_relocation(body: RelocationApply) -> RelocationApplied: """Answer the check: apply the chosen mappings for THIS SESSION only (no mappings = "Not now"). Nothing is written to the library or to prefs, and a reopen asks again.""" _require_no_pending("Relocating files") require_adapter() check = STATE.relocation if check is None: raise HTTPException(409, "There is no missing-files check to answer") mappings = [PathMapping.make(m.from_, m.to) for m in body.mappings] try: tracks = check.answer(mappings) except ValueError as ex: raise HTTPException(400, str(ex)) return RelocationApplied(mappings=len(mappings), tracks=tracks) @app.get("/api/prefs") def get_prefs() -> dict: """The full persisted user-preferences blob (UI layout, last collection…).""" return prefs.load_prefs() @app.patch("/api/prefs") def patch_prefs(patch: dict) -> dict: """Shallow-merge the given keys into the stored prefs; returns the result.""" return prefs.update_prefs(patch) @app.get("/api/fs/places", response_model=list[FsPlace]) def fs_places(platform: str | None = None) -> list[FsPlace]: """Sidebar shortcuts for the file browser: the user's folders, then drives. Answered by the server because only it can stat a filesystem, and re-asked by the client rather than cached: drives come and go while a dialog is open, and a browser that exists to find a stick you just plugged in has to show it. `platform` adds that platform's own default location, which is the likeliest destination when browsing for one of its libraries. Only for platforms whose library sits at a fixed path — a removable one's libraries ARE the drives, which are already listed. """ out = [FsPlace(**p) for p in places.user_places()] out += [FsPlace(**p) for p in places.volume_places()] if platform: try: driver = registry.driver_by_platform(platform) except LibraryNotSupported: driver = None if driver is not None and not getattr(driver, "removable", False): seen = {p.path for p in out} try: found = driver.detect() except OSError: found = [] for candidate in found: # The place is the folder CONTAINING the library, because a # place is somewhere you navigate to, not something you pick. folder = Path(candidate["path"]).parent if str(folder) in seen or not folder.is_dir(): continue seen.add(str(folder)) out.append( FsPlace(kind="library", name=candidate.get("label") or folder.name, path=str(folder)) ) return out @app.get("/api/fs/list", response_model=FsListing) def fs_list(path: str | None = None, platform: str | None = None) -> FsListing: """List directories and openable library files for the in-app file browser. `platform` narrows the files to that platform's own: a Traktor browse that also listed `master.db` would be offering a file the chosen adapter cannot open. A platform whose library is a directory contributes no suffixes at all, so its browse shows folders only. """ base = Path(path).expanduser() if path else Path.home() if not base.exists() or not base.is_dir(): base = Path.home() base = base.resolve() suffixes = registry.browsable_suffixes(platform) dirs: list[FsEntry] = [] files: list[FsEntry] = [] try: for entry in sorted(base.iterdir(), key=lambda p: p.name.lower()): if entry.name.startswith("."): continue try: if entry.is_dir(): dirs.append(FsEntry(name=entry.name, path=str(entry))) elif entry.suffix.lower() in suffixes: files.append(FsEntry(name=entry.name, path=str(entry))) except OSError: continue except PermissionError: pass parent = str(base.parent) if base.parent != base else None return FsListing( path=str(base), parent=parent, home=str(Path.home()), dirs=dirs, files=files ) # ---- export sets ------------------------------------------------------------- # # Curation, not library data: a set is Konduktor's own record of what to export, # where to, and for which platform. Every route is scoped to the LOADED library # by its stable id, so opening a different collection shows a different shelf and # moving a collection does not orphan the sets built against it. def _require_library_id() -> str: require_adapter() if STATE.library_id is None: # pragma: no cover — loaded implies an id raise HTTPException(409, "No library is loaded") return STATE.library_id def _require_set(set_id: str): found = exports.get(_require_library_id(), set_id) if found is None: raise HTTPException(404, f"No export called {set_id}") return found @app.get("/api/exports", response_model=list[ExportSetOut]) def list_exports() -> list[ExportSetOut]: return [ExportSetOut(**s.as_dict()) for s in exports.all_sets(_require_library_id())] @app.post("/api/exports", response_model=ExportSetOut) def create_export(body: CreateExportSet) -> ExportSetOut: if body.kind == "folder" and not body.destination.strip(): raise HTTPException(400, "An export needs a destination folder") # Only platforms that can actually be WRITTEN may be targets. Gating here as # well as in the UI, because a set persists: one created against a target # that later stops being supported would otherwise fail at export time. _check_targets(body.targets, kind=body.kind) created = exports.create( _require_library_id(), name=body.name, targets=body.targets, destination=body.destination if body.kind == "folder" else "", kind=body.kind, mode=body.mode, ) return ExportSetOut(**created.as_dict()) @app.patch("/api/exports/{set_id}", response_model=ExportSetOut) def update_export(set_id: str, body: UpdateExportSet) -> ExportSetOut: found = _require_set(set_id) if body.targets is not None: _check_targets(body.targets, kind=found.kind) updated = exports.update( _require_library_id(), set_id, name=body.name, mode=body.mode, targets=body.targets, destination=body.destination, lock_grids=body.lock_grids, normalise=body.normalise, auto_gain=body.auto_gain, level=body.level.model_dump() if body.level is not None else None, ) return ExportSetOut(**updated.as_dict()) @app.delete("/api/exports/{set_id}") def delete_export(set_id: str) -> dict: """Forget a set. Deliberately does NOT touch anything at its destination.""" _require_set(set_id) return {"deleted": exports.delete(_require_library_id(), set_id)} @app.post("/api/exports/{set_id}/add", response_model=ExportSetOut) def add_to_export(set_id: str, body: ExportSetMembers) -> ExportSetOut: _require_set(set_id) updated = exports.add( _require_library_id(), set_id, track_ids=body.track_ids, playlist_ids=body.playlist_ids, ) return ExportSetOut(**updated.as_dict()) @app.post("/api/exports/{set_id}/remove", response_model=ExportSetOut) def remove_from_export(set_id: str, body: ExportSetMembers) -> ExportSetOut: """Remove loose tracks and/or WHOLE playlists. There is no per-track removal inside a referenced playlist: the reference is live, so honouring both would need an exclusion list — hidden state silently deciding what a future export contains. For a subset, add the tracks instead. """ _require_set(set_id) updated = exports.remove( _require_library_id(), set_id, track_ids=body.track_ids, playlist_ids=body.playlist_ids, ) return ExportSetOut(**updated.as_dict()) @app.get("/api/exports/{set_id}/contents", response_model=ExportContents) def export_contents(set_id: str) -> ExportContents: """What the set holds right now. Computed every call, never cached.""" found = _require_set(set_id) resolved = exports.resolve(require_adapter(), found) return ExportContents( playlists=[ ExportPlaylistOut(id=p.id, name=p.name, missing=p.missing, count=len(p.track_ids)) for p in resolved.playlists ], loose=len(resolved.loose_track_ids), tracks=len(resolved.track_ids), dangling=resolved.dangling_track_ids, destination_conflict=exports.destination_conflict( _require_library_id(), found.destination, ignore=set_id ) if found.kind == "folder" else None, ) @app.get("/api/exports/{set_id}/tracks", response_model=list[Track]) def export_tracks(set_id: str) -> list[Track]: """Every track the export would carry, deduped — the set's root view.""" found = _require_set(set_id) adapter = require_adapter() resolved = exports.resolve(adapter, found) return [t for t in (adapter.track(tid) for tid in resolved.track_ids) if t is not None] @app.get("/api/exports/{set_id}/loose", response_model=list[Track]) def export_loose_tracks(set_id: str) -> list[Track]: """Only the LOOSE tracks — the ones added individually. A separate route rather than a filter on the root view, because the two are genuinely different questions: the root is everything this export would ship (playlists included, deduped), and this is the "Other" bucket that becomes its own playlist in the exported library. A track added loosely AND supplied by a referenced playlist appears in both, which is honest — it is in the loose list, and that is what the count beside "Other" reports. """ found = _require_set(set_id) adapter = require_adapter() resolved = exports.resolve(adapter, found) return [ t for t in (adapter.track(tid) for tid in resolved.loose_track_ids) if t is not None ] @app.get("/api/exports/{set_id}/playlists/{playlist_id}/tracks", response_model=list[Track]) def export_playlist_tracks(set_id: str, playlist_id: str) -> list[Track]: """One included playlist, as it stands now. Read straight from the library rather than from the set, which is the live reference doing its job: what ships is whatever the playlist holds today. """ found = _require_set(set_id) if playlist_id not in found.playlist_ids: raise HTTPException(404, "That playlist is not in this export") tracks = require_adapter().playlist_tracks(playlist_id) if tracks is None: raise HTTPException(404, "That playlist no longer exists") return tracks def _export_options(found, body: RunExport | None) -> dict: """The run's options: the body's where given, else the set's own; a level the set does not keep comes from the app settings (Normalize's defaults).""" normalise = body.normalise if body is not None and body.normalise is not None else found.normalise auto_gain = body.auto_gain if body is not None and body.auto_gain is not None else found.auto_gain if body is not None and body.level is not None: raw = body.level.model_dump() elif found.level is not None: raw = found.level else: p = prefs.load_prefs() raw = {"measure": p.get("levelMeasure", "lufs"), "target": p.get("levelTarget", -9.0), "ceiling": p.get("levelCeiling", -1.0)} try: level = exporter.Level(measure=raw["measure"] if raw["measure"] in ("lufs", "rms") else "lufs", target=float(raw["target"]), ceiling=float(raw["ceiling"])) except (KeyError, TypeError, ValueError): level = exporter.Level() # Only where some target keeps an auto gain — a stick has none to write. writes_gain = any(getattr(core_export.for_platform(t), "writes_auto_gain", False) for t in found.targets) return {"store": STATE.loudness, "level": level if normalise else None, "auto_gain": bool(auto_gain and writes_gain)} @app.post("/api/exports/{set_id}/preview", response_model=ExportPreview) def preview_export(set_id: str, body: RunExport | None = None) -> ExportPreview: """What this export would do, right now, with the run dialog's options as ticked. Never cached — the set is live.""" found = _require_folder_set(set_id) built = exporter.plan(require_adapter(), found, **_export_options(found, body)) return ExportPreview(**built.as_dict(exporter.space_for(built))) @app.post("/api/exports/{set_id}/run", response_model=JobStatus) def run_export(set_id: str, body: RunExport | None = None) -> JobStatus: """Start the export on a background thread; poll `/api/jobs/{id}`. Planned again HERE rather than trusting whatever the preview showed: a playlist can be edited, a file deleted or a drive unplugged between looking and clicking, and the plan carries the destination-safety check. The dialog's options arrive with the click and are remembered on the set, so the next export of the same stick starts from the same answer. """ found = _require_folder_set(set_id) if body is not None: changes = {k: v for k, v in (("lock_grids", body.lock_grids), ("normalise", body.normalise), ("auto_gain", body.auto_gain)) if v is not None} if body.level is not None: changes["level"] = body.level.model_dump() if changes: found = exports.update(_require_library_id(), set_id, **changes) adapter = require_adapter() options = _export_options(found, None) built = exporter.plan(adapter, found, **options) if built.blocked: raise HTTPException(409, built.blocked) # A Konduktor setting, read when the export starts. root_folder = bool(prefs.load_prefs().get("exportRootFolder", False)) job = JOBS.submit("export", lambda handle: exporter.run( adapter, found, built, handle, root_folder=root_folder, lock_grids=found.lock_grids, **options)) return JobStatus(**job.as_dict()) # ---- pushing into this computer's DJ apps (`local_push.py`) ----------------------- def _local_level_out(level) -> dict | None: return {"measure": level.measure, "target": level.target, "ceiling": level.ceiling} if level else None @app.get("/api/local-libraries", response_model=LocalLibrariesOut) def local_libraries() -> LocalLibrariesOut: """The DJ apps' libraries on this computer a "computer" set pushes into, each with why it cannot be used, plus the shared audio folder and its level. Changed through `/api/prefs` (`localLibraries`, `localAudioRoot`, `localNormalise`, `localLevel`).""" import platformdirs return LocalLibrariesOut( libraries=[lib.as_dict() for lib in local_push.local_libraries(STATE.path)], audio_root=str(local_push.audio_root()), audio_root_default=str(Path(platformdirs.user_music_dir()) / "Konduktor"), level=_local_level_out(local_push.level()), ) def _require_computer_set(set_id: str): found = _require_set(set_id) if found.kind != "computer": raise HTTPException(400, "This set is exported into a folder, not pushed") return found def _push_options(found) -> dict: """The push's options: the set's lock and auto gain (as the run dialog left them), the shared folder's level (the app setting, not the set's).""" return {"store": STATE.loudness, "level": local_push.level(), "auto_gain": bool(found.auto_gain)} def _remember_run_options(found, body: RunExport | None): if body is None: return found changes = {k: v for k, v in (("lock_grids", body.lock_grids), ("auto_gain", body.auto_gain)) if v is not None} return exports.update(_require_library_id(), found.id, **changes) if changes else found @app.post("/api/exports/{set_id}/push/preview", response_model=PushPreview) def preview_push(set_id: str, body: RunExport | None = None) -> PushPreview: """What pushing this set would do now, with the dialog's ticks.""" found = _require_computer_set(set_id) if body is not None and body.auto_gain is not None: found.auto_gain = body.auto_gain # a look, not a change: not saved built = local_push.plan(require_adapter(), found, open_path=STATE.path, **_push_options(found)) return PushPreview(**built.as_dict()) @app.post("/api/exports/{set_id}/push", response_model=JobStatus) def run_push(set_id: str, body: RunExport | None = None) -> JobStatus: """Start the push on a background thread; poll `/api/jobs/{id}`. Planned again here (a playlist may have changed since the preview, or Traktor been started); the dialog's ticks are remembered on the set.""" found = _remember_run_options(_require_computer_set(set_id), body) adapter = require_adapter() options = _push_options(found) built = local_push.plan(adapter, found, open_path=STATE.path, **options) if built.blocked: raise HTTPException(409, built.blocked) try: job = JOBS.submit(local_push.JOB_KIND, lambda handle: local_push.run( adapter, found, built, handle, lock_grids=found.lock_grids, **options), exclusive_with=(local_push.JOB_KIND,)) except JobBusy: raise HTTPException(409, "A push is already running") return JobStatus(**job.as_dict()) def _export_targets() -> set[str]: """Platforms Konduktor can write a NEW library for. Asked of the exporter registry rather than hard-coded: reading a library and creating one from nothing are different capabilities, and a platform can have the first without the second. Registering an exporter is what makes a platform a target, so this cannot drift from what actually exists. """ return core_export.targets() def _require_folder_set(set_id: str): found = _require_set(set_id) if found.kind != "folder": raise HTTPException(400, "This set is pushed into this computer's DJ apps, not exported") return found def _check_targets(targets: list[str], *, kind: str = "folder") -> None: """Refuse a set with no targets, or one naming a platform with no exporter. Checked when the set is saved: a target that later stops being supported would otherwise fail at export time. A "computer" set pushes into the DJ apps a computer runs, which are `local_push.PLATFORMS`. """ if not targets: raise HTTPException(400, "An export needs at least one platform to export for") if kind == "computer": unsupported = [t for t in targets if t not in local_push.PLATFORMS] if unsupported: raise HTTPException(422, f"Konduktor cannot push into {', '.join(unsupported)}") return unsupported = [t for t in targets if t not in _export_targets()] if unsupported: raise HTTPException(422, f"Konduktor cannot export to {', '.join(unsupported)} yet") @app.get("/api/export-targets", response_model=list[PlatformOption]) def export_targets() -> list[PlatformOption]: """Every platform, flagged by whether it can be an export TARGET. Returns the unsupported ones too, with `installed=False` standing for "not a target yet", so the UI can show them disabled with a reason. A silently absent option reads as a missing feature; a disabled one reads as a roadmap. """ supported = _export_targets() options = [] for d in registry.drivers(): exporter = core_export.for_platform(d.platform) options.append(PlatformOption( platform=d.platform, name=getattr(exporter, "display_name", None) or d.display_name, library_label=getattr(d, "library_label", ""), selects="directory", # an export destination is always a folder installed=d.platform in supported, found=0, removable=bool(getattr(d, "removable", False)), drive_root=bool(getattr(exporter, "drive_root", False)), computer_only=bool(getattr(exporter, "computer_only", False)), locks_grids=bool(getattr(exporter, "locks_grids", False)), writes_auto_gain=bool(getattr(exporter, "writes_auto_gain", False)), )) # Targets with no reader of their own (the stick's legacy Device Library): # listed too, or registering one would not make it selectable. readers = {d.platform for d in registry.drivers()} order = {e.platform: getattr(e, "menu_order", 1000) for e in core_export.exporters()} for exporter in core_export.exporters(): if exporter.platform in readers: continue options.append(PlatformOption( platform=exporter.platform, name=getattr(exporter, "display_name", exporter.platform), library_label="", selects="directory", installed=True, found=0, removable=bool(getattr(exporter, "drive_root", False)), drive_root=bool(getattr(exporter, "drive_root", False)), computer_only=bool(getattr(exporter, "computer_only", False)), locks_grids=bool(getattr(exporter, "locks_grids", False)), writes_auto_gain=bool(getattr(exporter, "writes_auto_gain", False)), )) # Each exporter states its own place; a platform with no exporter (not yet a # target, shown disabled) goes last. Stable, so equal places keep their order. return sorted(options, key=lambda o: order.get(o.platform, 1000)) # ---- health / state --------------------------------------------------- @app.get("/api/health") def health() -> dict: return {"status": "ok", "loaded": STATE.loaded, "path": str(STATE.path) if STATE.path else None} def _library_info() -> LibraryInfo: """Identity of the loaded library, for display and for composing warnings.""" caps = require_adapter().capabilities() path = Path(str(STATE.path)) # A library's on-screen name is the driver's to give when it cares: a drive # has one library reachable by two valid paths, and the filename would name # it differently depending on which one the user happened to pick. driver = next((d for d in registry.drivers() if d.platform == caps.platform), None) namer = getattr(driver, "display_name_for", None) try: display_name = namer(path) if namer and STATE.remote_config is None else path.name except OSError: display_name = path.name remote = None if STATE.remote_config is not None: # A remote is called what the user called it, not its file's name. display_name = STATE.remote_config.name remote = {"id": STATE.remote_config.id, "name": STATE.remote_config.name, "via": STATE.remote.client.via if STATE.remote else None} return LibraryInfo( platform=caps.platform, name=caps.save.app_name, library_label=caps.save.library_label, path=str(STATE.path), display_name=display_name, version=caps.version, remote=remote, ) @app.get("/api/platforms", response_model=list[PlatformOption]) def platforms() -> list[PlatformOption]: """Every DJ platform Konduktor can open — used by the picker BEFORE a library is loaded, where capabilities are not yet available.""" out = [] for d in registry.drivers(): found = [] try: found = d.detect() except OSError: pass out.append( PlatformOption( platform=d.platform, name=d.display_name, library_label=getattr(d, "library_label", ""), selects=getattr(d, "selects", "file"), installed=bool(found), found=len(found), removable=bool(getattr(d, "removable", False)), ) ) # Registration order is an import-order accident, and this list is a MENU — # it must not reshuffle itself between two launches. Sorted so the platforms # that keep a library in a known place come before the ones that are a # plugged-in drive, which is the real distinction a chooser is making. out.sort(key=lambda o: (o.removable, o.name.lower())) # A library held by a Konduktor server — not a platform of its own (the # server says which it holds), but a way to reach one, so it is offered # last, after every platform on this computer. from .adapters.remote import config as remote_config saved = len(remote_config.remotes()) out.append(PlatformOption(platform="remote", name="Remote", library_label="remote library", selects="remote", installed=saved > 0, found=saved)) return out @app.get("/api/capabilities", response_model=Capabilities) def capabilities() -> Capabilities: """What the loaded library can persist, so the UI can gate its controls.""" return require_adapter().capabilities() @app.get("/api/state", response_model=EditState) def state() -> EditState: stem_job = JOBS.active(STEM_JOB) normalize_job = JOBS.active(NORMALIZE_JOB) pending = STATE.pending.summary() if STATE.pending is not None else None return EditState(dirty=require_adapter().dirty, library=_library_info(), pending_stems=pending if pending and pending["tracks"] else None, pending_gain=({"tracks": pending["gain_tracks"], "lossless": pending["gain_lossless"]} if pending and pending.get("gain_tracks") else None), normalize_job=normalize_job[0].id if normalize_job else None, stem_job=stem_job[0].id if stem_job else None, stem_recovery=STATE.recovery, remote=STATE.remote.describe() if STATE.remote is not None else None) # ---- stem engine (download / side-load / remove) -------------------------- # The engine and its weights live outside the app (see stems/engine_manager.py). ENGINE_JOB = "stem-engine-install" STEM_JOB = "stem-conversion" @app.get("/api/stems/engine") def stem_engine_status() -> dict: """What is installed, what this computer can run, and what a download costs.""" from .stems import engine_manager as em mgr = em.default_manager() running = JOBS.active(ENGINE_JOB) return {**mgr.status(), "device": prefs.load_prefs().get("stemDevice", "auto"), "install_job": running[0].id if running else None} @app.post("/api/stems/engine/install", response_model=JobStatus) def install_stem_engine(body: StemEngineInstall) -> JobStatus: """Download the engine (and the weights) as a job, in bytes.""" from .jobs import JobCancelled from .stems import download from .stems import engine_manager as em mgr = em.default_manager() if mgr.base_target is None: raise HTTPException(422, "There is no stem engine for this computer") target = body.target or mgr.base_target if target not in mgr.status(network=False)["offered_targets"]: raise HTTPException(400, f"The {target} engine is not offered on this computer") def run(handle): info = mgr.target_info(target) if info is None: raise em.EngineError("Could not reach the engine download — check the internet connection") installed = mgr.installed() need_engine = not (installed and installed["target"] == target) need_weights = body.weights and not mgr.weights_installed() total = (info["size"] if need_engine else 0) + (mgr.weights_size() if need_weights else 0) handle.progress(done=0, total=total, unit="bytes", message="Downloading the stem engine…") done = [0] def on_bytes(n: int) -> None: done[0] += n handle.progress(done=done[0]) try: if need_engine: mgr.install_engine(target, on_bytes=on_bytes, cancelled=lambda: handle.cancelled) if need_weights: handle.progress(message="Downloading the separation model…") mgr.install_weights(on_bytes=on_bytes, cancelled=lambda: handle.cancelled) except download.DownloadCancelled: raise JobCancelled() return {"target": target, "ready": mgr.ready()} try: job = JOBS.submit(ENGINE_JOB, run, exclusive_with=(ENGINE_JOB, STEM_JOB)) except JobBusy: raise HTTPException(409, "The stem engine is already downloading, or a conversion is running") return JobStatus(**job.as_dict()) def _require_no_pending(what: str) -> None: """Refuse an operation that would SAVE or DROP a pending file change as a side effect — import and remap save pending edits, reload and restore drop them — while converted or normalized tracks await Save/Discard, or a conversion or Normalize runs. (Remap and relocation would also move the paths the ledger is keyed by.)""" if JOBS.active(STEM_JOB): raise HTTPException(409, f"{what} is not possible while tracks are being converted to stems") if JOBS.active(NORMALIZE_JOB): raise HTTPException(409, f"{what} is not possible while tracks are being normalized") if STATE.pending is not None and STATE.pending.blocking(): raise HTTPException(409, f"{what} is not possible until the converted or normalized tracks " "are saved or discarded") def _stem_options(body): from .stems import convert # A remote library's destination is a folder ON THE SERVER: not expanded # here, where `~` is this computer's home. remote = STATE.remote is not None destination = None if body.destination: destination = Path(body.destination) if remote else Path(body.destination).expanduser() return convert.Options( mode=body.mode, destination=destination, collection=body.collection, playlist_id=body.playlist_id, new_playlist=body.new_playlist, device=prefs.load_prefs().get("stemDevice", "auto"), ) def _stem_plan(body): from .stems import convert, remote_convert adapter = require_adapter() caps = adapter.capabilities() if not (caps.writable and caps.tracks.stem_convertible): raise HTTPException(422, "This library cannot hold stem files") try: if _remote_stems(adapter): return adapter, remote_convert.plan(adapter, body.track_ids, _stem_options(body)) return adapter, convert.plan(adapter, body.track_ids, _stem_options(body), STATE.pending) except convert.ConvertError as ex: raise HTTPException(400, str(ex)) def _remote_stems(adapter) -> bool: """A library held by a server: it plans and swaps, this computer separates (`stems/remote_convert.py`).""" return hasattr(adapter, "publish_stems") def _needs_engine(planned) -> bool: if hasattr(planned, "server"): return any(i.get("reuse") is None for i in planned.items) return any(p.reuse is None for p in planned.items) @app.post("/api/tracks/stems/preview") def preview_stem_conversion(body: StemConvert) -> dict: """What a conversion would do — converted, skipped (and why), disk space.""" _adapter, planned = _stem_plan(body) return planned.as_dict() @app.post("/api/tracks/stems/convert", response_model=JobStatus) def convert_to_stems(body: StemConvert) -> JobStatus: """Convert tracks to stem files as a job; the swap lands at its end.""" from .stems import convert from .stems import engine_manager as em _require_no_batch() if JOBS.active("import"): raise HTTPException(409, "Wait for the import to finish") adapter, planned = _stem_plan(body) if planned.blocked: raise HTTPException(409, planned.blocked) if not planned.items: raise HTTPException(400, "None of these tracks can be converted") if _needs_engine(planned) and not em.default_manager().ready(): raise HTTPException(409, "The stem engine is not installed") opts = _stem_options(body) def run(handle): if _remote_stems(adapter): from .stems import remote_convert return remote_convert.run(handle, adapter, planned, opts, still_current=lambda: STATE.adapter is adapter) return convert.run(handle, adapter, planned, opts, STATE.pending, mutation=STATE.mutation, still_current=lambda: STATE.adapter is adapter) try: job = JOBS.submit(STEM_JOB, run, exclusive_with=BATCH_JOBS + (ENGINE_JOB, "import")) except JobBusy: raise HTTPException(409, "Another batch, download or import is running") return JobStatus(**job.as_dict()) @app.post("/api/stems/engine/sideload") def side_load_stem_engine(body: StemSideLoad) -> dict: """Install the engine or the weights from files the user already has.""" from .stems import engine_manager as em if JOBS.active(ENGINE_JOB) or JOBS.active(STEM_JOB): raise HTTPException(409, "Wait for the running download or conversion to finish") mgr = em.default_manager() path = Path(body.path).expanduser() if not path.exists(): raise HTTPException(400, f"Not found: {path}") try: if body.kind == "engine": mgr.side_load_engine(path) else: mgr.side_load_weights(path) except em.EngineError as ex: raise HTTPException(400, str(ex)) return stem_engine_status() @app.delete("/api/stems/engine") def remove_stem_engine() -> dict: from .stems import engine_manager as em if JOBS.active(ENGINE_JOB) or JOBS.active(STEM_JOB): raise HTTPException(409, "Wait for the running download or conversion to finish") em.default_manager().remove() return stem_engine_status() @app.post("/api/discard", response_model=EditState) def discard_changes() -> EditState: """Drop every unsaved edit — the library re-reads itself from disk. A running batch is stopped first (and waited for): it writes into the library being discarded, so it would otherwise keep adding edits to the freshly reloaded one. """ adapter = require_adapter() if not adapter.capabilities().writable: raise HTTPException(409, "This library cannot be edited, so there is nothing to discard") _stop_batches() STATE.discard() return state() @app.post("/api/reload") def reload_collection() -> dict: _require_no_pending("Reloading") if not STATE.loaded: raise HTTPException(409, "No collection loaded") if STATE.remote is not None: STATE.adapter.refresh() # a remote library is re-read from its server else: STATE.open(STATE.path) # re-parse current file from disk return {"status": "reloaded", "tracks": len(require_adapter().tracks)} @app.on_event("shutdown") def _release_remote_session() -> None: """A graceful stop hands a remote library's session back (see sidecar.py for the abrupt one).""" if STATE.remote is not None: try: STATE.remote.stop() STATE.remote.client.release(timeout=2.0) except Exception: # noqa: BLE001 pass # ---- read: stats / facets / tracks ------------------------------------ @app.get("/api/stats", response_model=Stats) def stats() -> Stats: a = require_adapter() return a.stats(playlist_count=a.playlist_count()) @app.get("/api/facets", response_model=Facets) def facets() -> Facets: return require_adapter().facets() @app.get("/api/tracks", response_model=TrackPage) def tracks( q: str | None = None, genre: str | None = None, key: str | None = None, bpm_min: float | None = None, bpm_max: float | None = None, rating_min: int | None = Query(None, ge=0, le=5), has_cues: bool | None = None, sort: str = "artist", order: str = Query("asc", pattern="^(asc|desc)$"), limit: int = Query(100, ge=1, le=20000), offset: int = Query(0, ge=0), ) -> TrackPage: return require_adapter().query_tracks( q=q, genre=genre, key=key, bpm_min=bpm_min, bpm_max=bpm_max, rating_min=rating_min, has_cues=has_cues, sort=sort, order=order, limit=limit, offset=offset, ) # ---- read: playlists -------------------------------------------------- @app.get("/api/playlists", response_model=list[PlaylistNode]) def playlists() -> list[PlaylistNode]: return require_adapter().playlist_tree() @app.get("/api/playlists/{playlist_id}/tracks", response_model=list[Track]) def playlist_tracks(playlist_id: str) -> list[Track]: tracks = require_adapter().playlist_tracks(playlist_id) if tracks is None: raise HTTPException(404, f"Playlist not found: {playlist_id}") return tracks # ---- write: playlist editing ------------------------------------------ @app.post("/api/playlists", response_model=PlaylistNode) def create_playlist(body: CreatePlaylist) -> PlaylistNode: new_id = require_adapter().create_playlist( body.name.strip() or "New Playlist", body.parent_id ) return PlaylistNode( id=new_id, name=body.name, kind="playlist", count=0, selectable=True, can_add_tracks=True, can_reorder=True, can_rename=True, can_delete=True, can_move=True, ) @app.post("/api/playlists/folders", response_model=PlaylistNode) def create_folder(body: CreatePlaylist) -> PlaylistNode: name = body.name.strip() or "New Folder" new_id = require_adapter().create_folder(name, body.parent_id) return PlaylistNode( id=new_id, name=name, kind="folder", can_contain_children=True, can_rename=True, can_delete=True, can_move=True, ) # `:path` for the same reason as delete: a folder id is a path of names. @app.patch("/api/playlists/{playlist_uuid:path}") def rename_playlist(playlist_uuid: str, body: RenamePlaylist) -> dict: require_adapter().rename_playlist(playlist_uuid, body.name.strip()) return {"status": "renamed", "id": playlist_uuid, "name": body.name} # `:path` because a folder id is a path of names (`fld:a/b`), and the slash # would otherwise end the segment. @app.delete("/api/playlists/{playlist_uuid:path}") def delete_playlist(playlist_uuid: str) -> dict: require_adapter().delete_playlist(playlist_uuid) return {"status": "deleted", "id": playlist_uuid} @app.put("/api/playlists/{playlist_uuid}/entries") def set_entries(playlist_uuid: str, body: SetEntries) -> dict: n = require_adapter().set_playlist_entries(playlist_uuid, body.track_ids) return {"status": "updated", "id": playlist_uuid, "count": n} @app.post("/api/playlists/move") def move_playlist(body: MovePlaylist) -> dict: """Move a playlist, folder or smart playlist in the tree. Answers the node's id AFTER the move, which on some platforms is not the one sent.""" new_id = require_adapter().move_playlist(body.node_id, body.parent_id, body.index) return {"status": "moved", "id": new_id} @app.post("/api/playlists/{playlist_uuid}/add") def add_entries(playlist_uuid: str, body: AddEntries) -> dict: """Append tracks to a playlist. Tracks already there are skipped, added again, or — `duplicates="ask"` — counted with nothing changed (see `AddEntries`). `duplicates` in the answer is how many there were.""" a = require_adapter() current = a.playlist_entries(playlist_uuid) if current is None: raise HTTPException(404, f"Playlist not found: {playlist_uuid}") have = set(current) dupes = [tid for tid in body.track_ids if tid in have] mode = body.duplicates if mode != "skip" and not a.capabilities().playlists.duplicates: mode = "skip" if mode == "ask" and dupes: return {"status": "duplicates", "id": playlist_uuid, "added": 0, "duplicates": len(dupes), "count": len(current)} added = list(body.track_ids) if mode == "add" else [t for t in body.track_ids if t not in have] at = len(current) if body.index is None else max(0, min(len(current), body.index)) n = a.set_playlist_entries(playlist_uuid, current[:at] + added + current[at:]) if added else len(current) return {"status": "added", "id": playlist_uuid, "added": len(added), "duplicates": len(dupes), "count": n} @app.post("/api/playlists/{playlist_uuid}/remove") def remove_entries(playlist_uuid: str, body: RemoveEntries) -> dict: """Remove tracks from a playlist — EVERY occurrence of each — without the caller holding its entry list (the track menu's Remove ▸ From playlist). Other entries keep their order, including ones whose track is missing from the collection. `tracks` = how many of the given tracks it held, `removed` = entries dropped (more, where a track was there twice).""" a = require_adapter() current = a.playlist_entries(playlist_uuid) if current is None: raise HTTPException(404, f"Playlist not found: {playlist_uuid}") gone = set(body.track_ids) kept = [t for t in current if t not in gone] held = len(gone & set(current)) removed = len(current) - len(kept) n = len(current) if removed and not body.dry_run: n = a.set_playlist_entries(playlist_uuid, kept) return {"status": "counted" if body.dry_run else "removed", "id": playlist_uuid, "tracks": held, "removed": removed, "count": n} @app.patch("/api/tracks") def edit_track(body: EditTrack) -> dict: """Edit a single track's safe metadata fields (in-memory; persisted on save).""" require_adapter().set_track_metadata(body.track_id, body.fields) return {"status": "updated", "id": body.track_id} @app.patch("/api/tracks/color") def set_track_color(body: SetTrackColor) -> dict: """Set (or clear) the colour tag of every given track (in-memory; persisted on save). Gated on `tracks.colors`: the platform's swatches.""" a = require_adapter() if not a.capabilities().tracks.colors: raise Unsupported("This library cannot store a track colour") tracks = [a.set_track_color(tid, body.color) for tid in body.track_ids] return {"status": "updated", "tracks": [t for t in tracks if t is not None]} @app.get("/api/tracks/art") def track_art(track_id: str) -> Response: """Stream a track's embedded cover art (staged replacement if unsaved).""" art = require_adapter().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"}) _AUDIO_MIME = { ".mp3": "audio/mpeg", ".m4a": "audio/mp4", ".mp4": "audio/mp4", ".aac": "audio/aac", ".flac": "audio/flac", ".wav": "audio/wav", ".aif": "audio/aiff", ".aiff": "audio/aiff", ".ogg": "audio/ogg", } def _stem_audio(path: Path, stem: int) -> FileResponse: """One stem of a stem file as a file of its own (see stems/stream_cache.py): a browser only ever decodes an MP4's first stream, which is the mix.""" from .core import stem_file from .stems import stream_cache layout = stem_file.stem_layout(path) if layout is None or not 0 <= stem < len(layout): raise HTTPException(404, "That file has no such stem") try: return FileResponse(stream_cache.stem_file_for(path, stem), media_type="audio/mp4") except (stem_file.StemFileError, OSError) as ex: raise HTTPException(500, f"Could not read the stem: {ex}") def _stem_layout_of(path: Path | None) -> dict: from .core import stem_file if path is None or not path.exists(): raise HTTPException(404, "Audio file not found") return {"stems": stem_file.stem_layout(path) or []} @app.get("/api/tracks/stems") def track_stems(track_id: str) -> dict: """The stems a track's FILE carries for playback — `[{name, color}]`, empty for anything that is not a stem file (whatever the library says).""" return _stem_layout_of(require_adapter().audio_path(track_id)) @app.get("/api/tracks/audio") def track_audio(track_id: str, stem: int | None = None) -> FileResponse: """Stream a track's audio file for playback (supports HTTP Range/seeking); with `stem`, that stem of a stem file (0-based) instead.""" path = require_adapter().audio_path(track_id) if path is None: raise HTTPException(404, "Track not found") if not path.exists(): raise HTTPException(404, f"Audio file not found: {path}") if stem is not None: return _stem_audio(path, stem) # .stem.m4a and other MP4s serve as audio/mp4; browsers play the first track. mime = _AUDIO_MIME.get(path.suffix.lower(), "application/octet-stream") # Cacheable so the waveform's decode-fetch and the