mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 18:22:53 +01:00
Implemented export status
This commit is contained in:
1 parent
ba3e7c251e
commit
ed9dfc9d6b
12 files changed
+929
-7
No files matched your search
@@ -251,6 +251,9 @@ class OneLibraryAdapter:
|
||||
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
|
||||
self._refuse("Creating playlists")
|
||||
|
||||
def create_folder(self, name: str, parent_id: str | None = None) -> str:
|
||||
self._refuse("Creating playlist folders")
|
||||
|
||||
def rename_playlist(self, node_id: str, name: str) -> None:
|
||||
self._refuse("Renaming playlists")
|
||||
|
||||
|
||||
@@ -235,6 +235,13 @@ class RekordboxAdapter:
|
||||
self._require_writable("Creating playlists")
|
||||
return self._store.create_playlist(name, parent_id)
|
||||
|
||||
def create_folder(self, name: str, parent_id: str | None = None) -> str:
|
||||
# Rekordbox CAN hold folders (`capabilities.playlists.folders` is
|
||||
# True, and pyrekordbox has `add_playlist_folder`), so this is a
|
||||
# gap rather than a refusal in principle. Traktor is the only
|
||||
# import target for now, so it is the only one that needed it.
|
||||
self._refuse("Creating playlist folders")
|
||||
|
||||
def rename_playlist(self, node_id: str, name: str) -> None:
|
||||
self._require_writable("Renaming playlists")
|
||||
self._store.rename_playlist(node_id, name)
|
||||
|
||||
@@ -116,6 +116,10 @@ class TraktorAdapter:
|
||||
with _translate():
|
||||
return self._store.create_playlist(name, parent_id)
|
||||
|
||||
def create_folder(self, name: str, parent_id: str | None = None) -> str:
|
||||
with _translate():
|
||||
return self._store.create_folder(name, parent_id)
|
||||
|
||||
def rename_playlist(self, node_id: str, name: str) -> None:
|
||||
with _translate():
|
||||
self._store.rename_playlist(node_id, name)
|
||||
|
||||
@@ -240,6 +240,42 @@ class TraktorStore:
|
||||
self.dirty = True
|
||||
return new_uuid
|
||||
|
||||
def create_folder(self, name: str, parent_id: str | None = None) -> str:
|
||||
"""Create a playlist FOLDER and return its synthetic id.
|
||||
|
||||
A folder has no UUID of its own in the NML — it is identified by its path
|
||||
of names — so the id is built the same way `_to_model` builds it, and the
|
||||
two must agree or the folder will be invisible to the very next call.
|
||||
|
||||
An existing folder of the same name in the same parent is RETURNED rather
|
||||
than duplicated. Import creates a folder named after the drive, and a
|
||||
second import from the same stick should land beside the first rather
|
||||
than next to an identically-named twin.
|
||||
"""
|
||||
with self._lock:
|
||||
parent = self._find_folder(parent_id)
|
||||
existing = next(
|
||||
(
|
||||
c
|
||||
for c in self._children(parent)
|
||||
if (c.type or "FOLDER") == "FOLDER" and c.name == name
|
||||
),
|
||||
None,
|
||||
)
|
||||
prefix = parent_id[len("fld:"):] if parent_id and parent_id.startswith("fld:") else ""
|
||||
folder_id = "fld:" + "/".join([p for p in (prefix, name) if p])
|
||||
if existing is not None:
|
||||
return folder_id
|
||||
if parent.subnodes is None:
|
||||
parent.subnodes = Subnodestype(node=[], count=0)
|
||||
parent.subnodes.node.append(
|
||||
Nodetype(type="FOLDER", name=name, subnodes=Subnodestype(node=[], count=0))
|
||||
)
|
||||
parent.subnodes.count = len(parent.subnodes.node)
|
||||
self._note("playlist-create-folder", name)
|
||||
self.dirty = True
|
||||
return folder_id
|
||||
|
||||
def rename_playlist(self, playlist_uuid: str, name: str) -> None:
|
||||
with self._lock:
|
||||
node = self._find_playlist_node(playlist_uuid)
|
||||
|
||||
@@ -118,6 +118,10 @@ class LibraryAdapter(Protocol):
|
||||
|
||||
# ---- commands: playlists --------------------------------------------
|
||||
def create_playlist(self, name: str, parent_id: str | None = None) -> str: ...
|
||||
# Folders are a separate verb rather than a flag on create_playlist: a
|
||||
# platform can support one and not the other, and `capabilities.playlists
|
||||
# .folders` is what the UI gates on.
|
||||
def create_folder(self, name: str, parent_id: str | None = None) -> str: ...
|
||||
def rename_playlist(self, node_id: str, name: str) -> None: ...
|
||||
def delete_playlist(self, node_id: str) -> None: ...
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: ...
|
||||
|
||||
@@ -126,20 +126,24 @@ class EditJournal:
|
||||
for c in self.changes:
|
||||
if c.scope == "playlist" and c.target:
|
||||
pl_names.setdefault(c.op, []).append(c.target)
|
||||
for op, verb in (
|
||||
("create", "created"),
|
||||
("rename", "renamed"),
|
||||
("delete", "deleted"),
|
||||
("entries", "reordered"),
|
||||
# A folder is its own op so the message does not call it a playlist —
|
||||
# "created playlists 'Hardy', 'demos'" reads as two playlists when one is
|
||||
# the folder the other went into.
|
||||
for op, verb, noun in (
|
||||
("create", "created", "playlist"),
|
||||
("create-folder", "created", "folder"),
|
||||
("rename", "renamed", "playlist"),
|
||||
("delete", "deleted", "playlist"),
|
||||
("entries", "reordered", "playlist"),
|
||||
):
|
||||
names = pl_names.get(op, [])
|
||||
if not names:
|
||||
continue
|
||||
if len(names) <= 2:
|
||||
joined = ", ".join(f"'{n}'" for n in names)
|
||||
parts.append(f"{verb} playlist{'' if len(names) == 1 else 's'} {joined}")
|
||||
parts.append(f"{verb} {noun}{'' if len(names) == 1 else 's'} {joined}")
|
||||
else:
|
||||
parts.append(f"{verb} {len(names)} playlists")
|
||||
parts.append(f"{verb} {len(names)} {noun}s")
|
||||
|
||||
# --- hotcues: net change in count, scoped by how many tracks were touched ---
|
||||
hc_add = hc_del = 0
|
||||
|
||||
@@ -0,0 +1,346 @@
|
||||
"""Importing tracks from a source library into the loaded one.
|
||||
|
||||
App-level, not adapter-level, and deliberately so: this coordinates TWO
|
||||
libraries, and neither adapter should know the other exists. The source is asked
|
||||
for generic tracks and cues; the destination is handed generic `NewTrack`s. The
|
||||
only thing this module adds is everything in between — the audio copy, the
|
||||
pre-scan, and the playlist reconstruction.
|
||||
|
||||
**The copy is this module's job, not the adapter's.** `NewTrack.audio_path` must
|
||||
already exist when it reaches the destination, because a file copy that failed
|
||||
halfway is not something a library write should be discovering.
|
||||
|
||||
Scope, chosen deliberately: **everything is added as a new entry**. Nothing is
|
||||
matched against tracks the destination already holds, so there is no merge policy
|
||||
and no cross-platform identity problem. Re-importing the same stick duplicates,
|
||||
and a preview warns about that rather than preventing it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import shutil
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from .core.adapter import NewTrack
|
||||
from .jobs import JobHandle
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
# Copy in chunks so a cancel lands within a few milliseconds rather than at the
|
||||
# end of a 50 MB file, and so progress can move within one big track.
|
||||
COPY_CHUNK = 1024 * 1024
|
||||
|
||||
# Leave the destination some room rather than filling it exactly. A disk with
|
||||
# zero bytes free is a broken machine, not a successful import.
|
||||
SPACE_HEADROOM = 64 * 1024 * 1024
|
||||
|
||||
|
||||
@dataclass
|
||||
class PlannedTrack:
|
||||
track_id: str # the id in the SOURCE library
|
||||
title: str
|
||||
source_path: Path | None
|
||||
size: int = 0
|
||||
missing: bool = False
|
||||
# True when the destination already holds a track with this filename. Only a
|
||||
# warning: the user chose "add everything as new entries".
|
||||
duplicate: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class ImportPlan:
|
||||
tracks: list[PlannedTrack] = field(default_factory=list)
|
||||
playlists: list[tuple[str, str]] = field(default_factory=list) # (id, name)
|
||||
destination: Path | None = None
|
||||
|
||||
@property
|
||||
def importable(self) -> list[PlannedTrack]:
|
||||
return [t for t in self.tracks if not t.missing]
|
||||
|
||||
@property
|
||||
def total_bytes(self) -> int:
|
||||
return sum(t.size for t in self.importable)
|
||||
|
||||
def as_dict(self, free_bytes: int | None = None) -> dict:
|
||||
return {
|
||||
"tracks": len(self.tracks),
|
||||
"importable": len(self.importable),
|
||||
"missing": [t.title for t in self.tracks if t.missing],
|
||||
"duplicates": [t.title for t in self.tracks if t.duplicate],
|
||||
"playlists": [name for _, name in self.playlists],
|
||||
"total_bytes": self.total_bytes,
|
||||
"destination": str(self.destination) if self.destination else None,
|
||||
"free_bytes": free_bytes,
|
||||
"enough_space": (
|
||||
None if free_bytes is None
|
||||
else free_bytes >= self.total_bytes + SPACE_HEADROOM
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _existing_filenames(dest) -> set[str]:
|
||||
out: set[str] = set()
|
||||
for track in dest.tracks:
|
||||
path = getattr(track, "filepath", None)
|
||||
if path:
|
||||
out.add(Path(path).name.lower())
|
||||
return out
|
||||
|
||||
|
||||
def plan(source, dest, destination: Path, *, track_ids=None, playlist_ids=None) -> ImportPlan:
|
||||
"""Work out what an import would do, WITHOUT doing any of it.
|
||||
|
||||
Computed fresh every time and never stored. Playlist membership on the source
|
||||
can change between planning and importing (a stick can be re-exported), and a
|
||||
stale preview is worse than no preview.
|
||||
|
||||
Playlist selection AUTO-INCLUDES the tracks in those playlists, and the whole
|
||||
set is deduplicated, so a track in three chosen playlists is copied once.
|
||||
"""
|
||||
plan = ImportPlan(destination=destination)
|
||||
wanted: list[str] = []
|
||||
seen: set[str] = set()
|
||||
|
||||
def want(track_id: str) -> None:
|
||||
if track_id not in seen:
|
||||
seen.add(track_id)
|
||||
wanted.append(track_id)
|
||||
|
||||
for node_id in playlist_ids or []:
|
||||
node_tracks = source.playlist_tracks(node_id) or []
|
||||
for t in node_tracks:
|
||||
want(t.id)
|
||||
name = _playlist_name(source, node_id)
|
||||
if name:
|
||||
plan.playlists.append((node_id, name))
|
||||
|
||||
for track_id in track_ids or []:
|
||||
want(track_id)
|
||||
|
||||
# Neither given: the whole drive.
|
||||
if not (track_ids or playlist_ids):
|
||||
for t in source.tracks:
|
||||
want(t.id)
|
||||
for node_id, name in _all_playlists(source):
|
||||
plan.playlists.append((node_id, name))
|
||||
|
||||
existing = _existing_filenames(dest)
|
||||
for track_id in wanted:
|
||||
track = source.track(track_id)
|
||||
if track is None:
|
||||
continue
|
||||
raw = getattr(track, "filepath", None)
|
||||
path = Path(raw) if raw else None
|
||||
planned = PlannedTrack(
|
||||
track_id=track_id,
|
||||
title=track.title or (path.name if path else track_id),
|
||||
source_path=path,
|
||||
)
|
||||
try:
|
||||
if path is not None and path.is_file():
|
||||
planned.size = path.stat().st_size
|
||||
planned.duplicate = path.name.lower() in existing
|
||||
else:
|
||||
planned.missing = True
|
||||
except OSError:
|
||||
planned.missing = True
|
||||
plan.tracks.append(planned)
|
||||
return plan
|
||||
|
||||
|
||||
def _playlist_name(source, node_id: str) -> str | None:
|
||||
for nid, name in _all_playlists(source):
|
||||
if nid == node_id:
|
||||
return name
|
||||
return None
|
||||
|
||||
|
||||
def _all_playlists(source) -> list[tuple[str, str]]:
|
||||
"""Every selectable playlist on the source, flattened.
|
||||
|
||||
Folders are dropped rather than recreated. The destination gets ONE folder,
|
||||
named after the drive, and nesting a stick's folder tree inside it would bury
|
||||
the playlists a user is trying to find.
|
||||
"""
|
||||
out: list[tuple[str, str]] = []
|
||||
|
||||
def walk(nodes):
|
||||
for n in nodes:
|
||||
if n.kind == "playlist":
|
||||
out.append((n.id, n.name))
|
||||
walk(n.children or [])
|
||||
|
||||
walk(source.playlist_tree())
|
||||
return out
|
||||
|
||||
|
||||
def free_bytes(path: Path) -> int | None:
|
||||
try:
|
||||
target = path if path.exists() else path.parent
|
||||
return shutil.disk_usage(target).free
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def _unique_target(folder: Path, name: str, taken: set[str]) -> Path:
|
||||
"""A free filename in `folder`, suffixing on collision.
|
||||
|
||||
`taken` covers names claimed earlier in THIS run, which the filesystem cannot
|
||||
answer for — two sticks can both hold `Track.mp3`, and the first copy has not
|
||||
necessarily been written yet when the second is planned.
|
||||
|
||||
Known consequence of suffixing by processing order (accepted in the export
|
||||
design): re-importing may assign a different suffix to the same track.
|
||||
"""
|
||||
stem, dot, ext = name.rpartition(".")
|
||||
if not dot:
|
||||
stem, ext = name, ""
|
||||
candidate = name
|
||||
n = 1
|
||||
while candidate.lower() in taken or (folder / candidate).exists():
|
||||
n += 1
|
||||
candidate = f"{stem}-{n}{'.' + ext if ext else ''}"
|
||||
taken.add(candidate.lower())
|
||||
return folder / candidate
|
||||
|
||||
|
||||
def _copy(src: Path, dst: Path, handle: JobHandle, on_bytes) -> None:
|
||||
"""Copy a file, checking for cancellation between chunks."""
|
||||
with src.open("rb") as fin, dst.open("wb") as fout:
|
||||
while True:
|
||||
handle.raise_if_cancelled()
|
||||
chunk = fin.read(COPY_CHUNK)
|
||||
if not chunk:
|
||||
break
|
||||
fout.write(chunk)
|
||||
on_bytes(len(chunk))
|
||||
shutil.copystat(src, dst, follow_symlinks=True)
|
||||
|
||||
|
||||
def run(source, dest, plan: ImportPlan, handle: JobHandle, *, folder_name: str | None = None) -> dict:
|
||||
"""Perform the import. Returns a summary dict for the job result.
|
||||
|
||||
Ordering is the safety property. Audio is copied FIRST and the library is
|
||||
written LAST, so a cancel or a failure during the long part leaves the
|
||||
collection untouched and the copied files are removed on the way out. Once
|
||||
copying is done the library write is fast and is allowed to finish.
|
||||
|
||||
This is a COMMITTED action — it saves at the end — rather than an in-memory
|
||||
edit the Save button flushes. A multi-gigabyte copy is not a pending tweak,
|
||||
and audio on disk with unsaved entries pointing at it is the worst of both.
|
||||
"""
|
||||
destination = plan.destination
|
||||
assert destination is not None
|
||||
destination.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
importable = plan.importable
|
||||
total = plan.total_bytes or len(importable)
|
||||
handle.progress(done=0, total=total, message="Copying audio…")
|
||||
|
||||
copied: list[tuple[PlannedTrack, Path]] = []
|
||||
# Every path this run has opened for writing, including the one being written
|
||||
# when a cancel lands. `copied` holds only COMPLETED copies, so cleaning up
|
||||
# from it leaves the half-written file behind — which then makes the next
|
||||
# attempt suffix around a file that is not really there.
|
||||
created: list[Path] = []
|
||||
taken: set[str] = set()
|
||||
moved = 0
|
||||
|
||||
def bump(n: int) -> None:
|
||||
nonlocal moved
|
||||
moved += n
|
||||
handle.progress(done=moved)
|
||||
|
||||
try:
|
||||
for planned in importable:
|
||||
handle.raise_if_cancelled()
|
||||
handle.progress(message=f"Copying {planned.title}")
|
||||
assert planned.source_path is not None
|
||||
target = _unique_target(destination, planned.source_path.name, taken)
|
||||
created.append(target) # registered BEFORE the write, so a cancel
|
||||
_copy(planned.source_path, target, handle, bump) # mid-file is cleaned
|
||||
copied.append((planned, target))
|
||||
|
||||
handle.raise_if_cancelled()
|
||||
handle.progress(message="Adding tracks to the library…")
|
||||
|
||||
items: list[NewTrack] = []
|
||||
for planned, target in copied:
|
||||
track = source.track(planned.track_id)
|
||||
if track is None:
|
||||
continue
|
||||
cues = None
|
||||
try:
|
||||
cues = source.track_cues(planned.track_id)
|
||||
except Exception: # noqa: BLE001 — prep is a bonus, not a blocker
|
||||
log.debug("could not read cues for %s", planned.track_id, exc_info=True)
|
||||
items.append(NewTrack(track=track, audio_path=target, cues=cues))
|
||||
|
||||
new_ids = dest.add_tracks(items)
|
||||
by_source = {
|
||||
planned.track_id: new_id
|
||||
for (planned, _), new_id in zip(copied, new_ids)
|
||||
}
|
||||
|
||||
playlists_made = _rebuild_playlists(
|
||||
source, dest, plan, by_source, folder_name, handle
|
||||
)
|
||||
|
||||
handle.progress(message="Saving…")
|
||||
outcome, _commit = _save(dest)
|
||||
return {
|
||||
"tracks": len(new_ids),
|
||||
"playlists": playlists_made,
|
||||
"skipped_missing": len(plan.tracks) - len(importable),
|
||||
"destination": str(destination),
|
||||
"summary": getattr(outcome, "summary", ""),
|
||||
}
|
||||
except BaseException:
|
||||
# A cancelled or failed import must not leave orphaned audio behind: the
|
||||
# library was never written, so those files reference nothing.
|
||||
for target in created:
|
||||
try:
|
||||
target.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
log.debug("could not clean up %s", target, exc_info=True)
|
||||
raise
|
||||
|
||||
|
||||
def _save(dest):
|
||||
"""Save through AppState so the version-history commit is not skipped."""
|
||||
from .app_state import STATE
|
||||
|
||||
if STATE.adapter is dest:
|
||||
return STATE.save()
|
||||
return dest.save(), None
|
||||
|
||||
|
||||
def _rebuild_playlists(source, dest, plan, by_source, folder_name, handle) -> int:
|
||||
"""Recreate the source's playlists in the destination.
|
||||
|
||||
They go into ONE folder named after the drive, so a re-import is easy to find
|
||||
and easy to delete, and the collection's root does not accumulate. A platform
|
||||
that cannot make folders puts them at the root instead — the capability says
|
||||
which, rather than this guessing.
|
||||
"""
|
||||
if not plan.playlists:
|
||||
return 0
|
||||
parent = None
|
||||
if folder_name and dest.capabilities().playlists.folders:
|
||||
try:
|
||||
parent = dest.create_folder(folder_name)
|
||||
except Exception: # noqa: BLE001 — a missing folder is not worth failing over
|
||||
log.debug("could not create folder %r", folder_name, exc_info=True)
|
||||
|
||||
made = 0
|
||||
for node_id, name in plan.playlists:
|
||||
handle.progress(message=f"Recreating playlist {name}")
|
||||
source_tracks = source.playlist_tracks(node_id) or []
|
||||
ids = [by_source[t.id] for t in source_tracks if t.id in by_source]
|
||||
if not ids:
|
||||
continue
|
||||
new_id = dest.create_playlist(name, parent)
|
||||
dest.set_playlist_entries(new_id, ids)
|
||||
made += 1
|
||||
return made
|
||||
@@ -0,0 +1,176 @@
|
||||
"""Long-running operations, with progress and a working cancel.
|
||||
|
||||
Every route in this app is a synchronous `def` that finishes in milliseconds,
|
||||
which has been fine while every operation was "edit an object in memory". Import
|
||||
is not: it copies audio off a USB stick, and a DJ's stick is tens of gigabytes.
|
||||
A synchronous copy would hold an HTTP request open for minutes and give the user
|
||||
no way to stop it or see how far it had got.
|
||||
|
||||
So this is the smallest thing that fixes that, and deliberately no more:
|
||||
|
||||
* a **thread per job** — the work is IO-bound (file copying), so threads are
|
||||
the right shape and asyncio would mean rewriting the routes;
|
||||
* **polling**, not SSE or websockets — a progress bar wants a number a few
|
||||
times a second, and adding a streaming transport to an app that has none is
|
||||
a lot of new failure modes for a smoother number;
|
||||
* **cooperative cancel** — the job checks a flag between units of work. There
|
||||
is no way to kill a thread in Python, and there should not be: a copy
|
||||
interrupted mid-file needs to clean up after itself, which it can only do if
|
||||
it is the one deciding to stop.
|
||||
|
||||
Jobs are kept in memory and die with the process. That is correct rather than
|
||||
lazy: a job describes work happening right now, and a "running" job whose thread
|
||||
no longer exists would be a lie that survived a restart.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Callable, Literal
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
JobState = Literal["running", "done", "failed", "cancelled"]
|
||||
|
||||
# Finished jobs are kept so a client that polls a moment late still sees the
|
||||
# result. Bounded, so a long session cannot grow this without limit.
|
||||
MAX_FINISHED = 20
|
||||
|
||||
|
||||
@dataclass
|
||||
class Job:
|
||||
id: str
|
||||
kind: str
|
||||
state: JobState = "running"
|
||||
# `total` is 0 until the job knows its size — a copy has to scan first — and
|
||||
# the UI is expected to show an indeterminate bar until it is positive.
|
||||
total: int = 0
|
||||
done: int = 0
|
||||
message: str = ""
|
||||
result: Any = None
|
||||
error: str | None = None
|
||||
started_at: float = field(default_factory=time.time)
|
||||
finished_at: float | None = None
|
||||
_cancel: threading.Event = field(default_factory=threading.Event, repr=False)
|
||||
|
||||
@property
|
||||
def finished(self) -> bool:
|
||||
return self.state in ("done", "failed", "cancelled")
|
||||
|
||||
def as_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"kind": self.kind,
|
||||
"state": self.state,
|
||||
"total": self.total,
|
||||
"done": self.done,
|
||||
"message": self.message,
|
||||
"result": self.result,
|
||||
"error": self.error,
|
||||
"started_at": self.started_at,
|
||||
"finished_at": self.finished_at,
|
||||
}
|
||||
|
||||
|
||||
class JobHandle:
|
||||
"""What the running work is given: report progress, ask whether to stop.
|
||||
|
||||
Deliberately the only thing a job function touches, so the work cannot reach
|
||||
into the registry and, say, mark itself done — that is the registry's call,
|
||||
and it is what makes "the state always reflects the thread" true.
|
||||
"""
|
||||
|
||||
def __init__(self, job: Job) -> None:
|
||||
self._job = job
|
||||
|
||||
def progress(self, done: int | None = None, total: int | None = None,
|
||||
message: str | None = None) -> None:
|
||||
if done is not None:
|
||||
self._job.done = done
|
||||
if total is not None:
|
||||
self._job.total = total
|
||||
if message is not None:
|
||||
self._job.message = message
|
||||
|
||||
@property
|
||||
def cancelled(self) -> bool:
|
||||
return self._job._cancel.is_set()
|
||||
|
||||
def raise_if_cancelled(self) -> None:
|
||||
if self.cancelled:
|
||||
raise JobCancelled()
|
||||
|
||||
|
||||
class JobCancelled(Exception):
|
||||
"""Raised inside a job when the user asked it to stop.
|
||||
|
||||
An exception rather than a return value so a job can unwind through whatever
|
||||
it was doing — and so its cleanup can be an ordinary `finally`.
|
||||
"""
|
||||
|
||||
|
||||
class JobRegistry:
|
||||
def __init__(self) -> None:
|
||||
self._jobs: dict[str, Job] = {}
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def submit(self, kind: str, fn: Callable[[JobHandle], Any]) -> Job:
|
||||
job = Job(id=uuid.uuid4().hex, kind=kind)
|
||||
with self._lock:
|
||||
self._jobs[job.id] = job
|
||||
self._prune()
|
||||
|
||||
def run() -> None:
|
||||
handle = JobHandle(job)
|
||||
try:
|
||||
job.result = fn(handle)
|
||||
job.state = "cancelled" if handle.cancelled else "done"
|
||||
except JobCancelled:
|
||||
job.state = "cancelled"
|
||||
except Exception as ex: # noqa: BLE001 — surfaced to the client
|
||||
log.exception("job %s (%s) failed", job.id, kind)
|
||||
job.state = "failed"
|
||||
job.error = str(ex) or ex.__class__.__name__
|
||||
finally:
|
||||
job.finished_at = time.time()
|
||||
|
||||
threading.Thread(target=run, name=f"job-{kind}-{job.id[:8]}", daemon=True).start()
|
||||
return job
|
||||
|
||||
def get(self, job_id: str) -> Job | None:
|
||||
with self._lock:
|
||||
return self._jobs.get(job_id)
|
||||
|
||||
def cancel(self, job_id: str) -> bool:
|
||||
"""Ask a job to stop. Returns False for an unknown or finished job.
|
||||
|
||||
Only a REQUEST: the job stops at its next checkpoint and cleans up after
|
||||
itself, so the state does not become "cancelled" here.
|
||||
"""
|
||||
job = self.get(job_id)
|
||||
if job is None or job.finished:
|
||||
return False
|
||||
job._cancel.set()
|
||||
return True
|
||||
|
||||
def active(self, kind: str | None = None) -> list[Job]:
|
||||
with self._lock:
|
||||
return [
|
||||
j for j in self._jobs.values()
|
||||
if not j.finished and (kind is None or j.kind == kind)
|
||||
]
|
||||
|
||||
def _prune(self) -> None:
|
||||
"""Drop the oldest finished jobs. Caller holds the lock."""
|
||||
finished = sorted(
|
||||
(j for j in self._jobs.values() if j.finished),
|
||||
key=lambda j: j.finished_at or 0.0,
|
||||
)
|
||||
for job in finished[: max(0, len(finished) - MAX_FINISHED)]:
|
||||
self._jobs.pop(job.id, None)
|
||||
|
||||
|
||||
JOBS = JobRegistry()
|
||||
@@ -16,6 +16,7 @@ from fastapi.responses import FileResponse, JSONResponse
|
||||
from . import __version__, history, prefs
|
||||
from .app_state import STATE
|
||||
from .core import auto_hotcues as ah
|
||||
from . import importer
|
||||
from .core import registry
|
||||
from .core.adapter import (
|
||||
AdapterError,
|
||||
@@ -26,6 +27,7 @@ from .core.adapter import (
|
||||
Unsupported,
|
||||
)
|
||||
from .core.capabilities import Capabilities
|
||||
from .jobs import JOBS
|
||||
from .core.pathmap import PathMapping
|
||||
from .schemas import (
|
||||
AutoGridRequest,
|
||||
@@ -47,6 +49,8 @@ from .schemas import (
|
||||
GridMarkerEdit,
|
||||
ReplaceGrid,
|
||||
HistoryEntry,
|
||||
ImportRequest,
|
||||
JobStatus,
|
||||
OpenCollection,
|
||||
OpenSource,
|
||||
PathMappingInfo,
|
||||
@@ -833,3 +837,84 @@ def source_track_audio(track_id: str) -> FileResponse:
|
||||
raise HTTPException(404, f"Audio file not found: {path}")
|
||||
mime = _AUDIO_MIME.get(path.suffix.lower(), "application/octet-stream")
|
||||
return FileResponse(path, media_type=mime)
|
||||
|
||||
|
||||
# ---- import -----------------------------------------------------------
|
||||
#
|
||||
# The only operation in the app that can run for minutes, so it is the only one
|
||||
# that is a JOB rather than a request. See `jobs.py` for why that is polling and
|
||||
# threads rather than something fancier.
|
||||
|
||||
|
||||
def _import_plan(body: ImportRequest):
|
||||
source, dest = require_source(), require_adapter()
|
||||
destination = Path(body.destination).expanduser()
|
||||
return source, dest, destination, importer.plan(
|
||||
source,
|
||||
dest,
|
||||
destination,
|
||||
track_ids=body.track_ids,
|
||||
playlist_ids=body.playlist_ids,
|
||||
)
|
||||
|
||||
|
||||
@app.post("/api/import/preview")
|
||||
def import_preview(body: ImportRequest) -> dict:
|
||||
"""What an import would do: counts, size, missing files, duplicates, space.
|
||||
|
||||
Computed fresh on every call and never stored — a stick can be re-exported
|
||||
between the preview and the import, and a stale preview is worse than none.
|
||||
"""
|
||||
_source, _dest, destination, plan = _import_plan(body)
|
||||
return plan.as_dict(free_bytes=importer.free_bytes(destination))
|
||||
|
||||
|
||||
@app.post("/api/import", response_model=JobStatus)
|
||||
def start_import(body: ImportRequest) -> JobStatus:
|
||||
"""Start an import. Returns immediately; poll the job for progress."""
|
||||
source, dest, destination, plan = _import_plan(body)
|
||||
if not plan.importable:
|
||||
raise HTTPException(400, "Nothing to import (no tracks, or none of their files exist)")
|
||||
free = importer.free_bytes(destination)
|
||||
if free is not None and free < plan.total_bytes + importer.SPACE_HEADROOM:
|
||||
raise HTTPException(
|
||||
400,
|
||||
f"Not enough space: {plan.total_bytes / 1e9:.1f} GB needed, "
|
||||
f"{free / 1e9:.1f} GB free at {destination}",
|
||||
)
|
||||
# One at a time: two concurrent imports would race on filename collisions and
|
||||
# on the destination library's save.
|
||||
if JOBS.active("import"):
|
||||
raise HTTPException(409, "An import is already running")
|
||||
|
||||
folder_name = body.folder_name
|
||||
if folder_name is None and STATE.source is not None:
|
||||
folder_name = STATE.source.capabilities().save.library_label
|
||||
|
||||
job = JOBS.submit(
|
||||
"import",
|
||||
lambda handle: importer.run(source, dest, plan, handle, folder_name=folder_name),
|
||||
)
|
||||
return JobStatus(**job.as_dict())
|
||||
|
||||
|
||||
@app.get("/api/jobs/{job_id}", response_model=JobStatus)
|
||||
def job_status(job_id: str) -> JobStatus:
|
||||
job = JOBS.get(job_id)
|
||||
if job is None:
|
||||
raise HTTPException(404, f"No such job: {job_id}")
|
||||
return JobStatus(**job.as_dict())
|
||||
|
||||
|
||||
@app.post("/api/jobs/{job_id}/cancel", response_model=JobStatus)
|
||||
def cancel_job(job_id: str) -> JobStatus:
|
||||
"""Ask a job to stop.
|
||||
|
||||
A REQUEST, not a kill: the job stops at its next checkpoint and cleans up
|
||||
after itself, so the status stays "running" until it has actually done so.
|
||||
"""
|
||||
job = JOBS.get(job_id)
|
||||
if job is None:
|
||||
raise HTTPException(404, f"No such job: {job_id}")
|
||||
JOBS.cancel(job_id)
|
||||
return JobStatus(**job.as_dict())
|
||||
@@ -212,3 +212,32 @@ class SourceStatus(BaseModel):
|
||||
|
||||
class OpenSource(BaseModel):
|
||||
path: str
|
||||
|
||||
|
||||
class ImportRequest(BaseModel):
|
||||
"""What to import, and where its audio should land.
|
||||
|
||||
Empty `track_ids` AND empty `playlist_ids` means the whole drive — an
|
||||
explicit "import everything" rather than a mistake, matching the settled
|
||||
export design's separate "export entire library" action.
|
||||
"""
|
||||
|
||||
destination: str # folder the audio is copied into
|
||||
track_ids: list[str] = []
|
||||
playlist_ids: list[str] = []
|
||||
# Playlists land in a folder named after the drive. Null keeps them at the
|
||||
# root; the default is filled in from the source's label.
|
||||
folder_name: str | None = None
|
||||
|
||||
|
||||
class JobStatus(BaseModel):
|
||||
id: str
|
||||
kind: str
|
||||
state: str # running | done | failed | cancelled
|
||||
total: int
|
||||
done: int
|
||||
message: str
|
||||
result: dict | None = None
|
||||
error: str | None = None
|
||||
started_at: float
|
||||
finished_at: float | None = None
|
||||
@@ -14,10 +14,13 @@ guarding, and they pull in opposite directions:
|
||||
Runs against a temp copy of the real Traktor collection (gotcha 2: it is real,
|
||||
irreplaceable data) and the checked-in OneLibrary fixture drive.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import warnings
|
||||
from difflib import unified_diff
|
||||
from pathlib import Path
|
||||
@@ -272,6 +275,177 @@ check("closing releases the source", not state.source_loaded)
|
||||
check("but not the destination", state.loaded)
|
||||
check("closing twice is safe", state.close_source() is None)
|
||||
|
||||
print("== folders ==")
|
||||
# Imported playlists land in a folder named after the drive, and the protocol had
|
||||
# no folder verb until this feature needed one.
|
||||
nml4, _, _ = fresh_collection()
|
||||
dest4 = TraktorAdapter(nml4)
|
||||
fid = dest4.create_folder("Hardy")
|
||||
check("a folder can be created", fid.startswith("fld:"), fid)
|
||||
# Re-importing the same stick must land BESIDE the first import, not next to an
|
||||
# identically-named twin.
|
||||
check("creating it again returns the same folder", dest4.create_folder("Hardy") == fid)
|
||||
pid = dest4.create_playlist("demos", fid)
|
||||
node = next((n for n in dest4.playlist_tree() if n.id == fid), None)
|
||||
check("the folder is in the tree", node is not None and node.kind == "folder")
|
||||
check("and the playlist is inside it",
|
||||
node is not None and [c.name for c in node.children] == ["demos"])
|
||||
check("read-only sources refuse to make folders",
|
||||
_raises(lambda: source.create_folder("x"), Unsupported))
|
||||
|
||||
print("== the job registry ==")
|
||||
from konduktor.jobs import JobCancelled, JobRegistry # noqa: E402
|
||||
|
||||
reg = JobRegistry()
|
||||
job = reg.submit("test", lambda h: 41 + 1)
|
||||
for _ in range(200):
|
||||
if job.finished:
|
||||
break
|
||||
time.sleep(0.01)
|
||||
check("a job runs and reports its result", job.state == "done" and job.result == 42)
|
||||
|
||||
def boom(h):
|
||||
raise RuntimeError("nope")
|
||||
|
||||
|
||||
# The registry logs a traceback for a failed job, which is right in production
|
||||
# and alarming in test output — a deliberate failure should not look like a
|
||||
# real one to someone scanning the suite.
|
||||
logging.getLogger("konduktor.jobs").setLevel(logging.CRITICAL)
|
||||
failing = reg.submit("test", boom)
|
||||
for _ in range(200):
|
||||
if failing.finished:
|
||||
break
|
||||
time.sleep(0.01)
|
||||
check("a failing job is reported, not swallowed",
|
||||
failing.state == "failed" and "nope" in (failing.error or ""))
|
||||
logging.getLogger("konduktor.jobs").setLevel(logging.NOTSET)
|
||||
|
||||
# Cancel is a REQUEST: the job stops at its next checkpoint, so the state must
|
||||
# not flip until the work has actually unwound and cleaned up.
|
||||
started = threading.Event()
|
||||
|
||||
def slow(h):
|
||||
started.set()
|
||||
while True:
|
||||
h.raise_if_cancelled()
|
||||
time.sleep(0.01)
|
||||
|
||||
running = reg.submit("test", slow)
|
||||
started.wait(2)
|
||||
check("cancel is accepted while running", reg.cancel(running.id))
|
||||
for _ in range(400):
|
||||
if running.finished:
|
||||
break
|
||||
time.sleep(0.01)
|
||||
check("and the job ends up cancelled", running.state == "cancelled")
|
||||
check("cancelling a finished job does nothing", not reg.cancel(running.id))
|
||||
check("cancelling an unknown job does nothing", not reg.cancel("nope"))
|
||||
|
||||
print("== import: plan and run ==")
|
||||
from konduktor import importer # noqa: E402
|
||||
|
||||
nml5, music5, _ = fresh_collection()
|
||||
dest5 = TraktorAdapter(nml5)
|
||||
plan5 = importer.plan(source, dest5, music5)
|
||||
check("the plan covers the whole drive when nothing is selected", len(plan5.tracks) == 2)
|
||||
check("it finds the playlist", [n for _, n in plan5.playlists] == ["demos"])
|
||||
check("it sizes the copy", plan5.total_bytes > 0)
|
||||
check("nothing is missing", plan5.importable == plan5.tracks)
|
||||
|
||||
# Selecting a playlist AUTO-INCLUDES its tracks, deduplicated.
|
||||
pl_id = importer._all_playlists(source)[0][0]
|
||||
plan_pl = importer.plan(source, dest5, music5, playlist_ids=[pl_id])
|
||||
check("selecting a playlist pulls in its tracks", len(plan_pl.tracks) == 2)
|
||||
plan_both = importer.plan(
|
||||
source, dest5, music5, playlist_ids=[pl_id],
|
||||
track_ids=[t.id for t in source.tracks],
|
||||
)
|
||||
check("a track in both a selection and a playlist is copied once",
|
||||
len(plan_both.tracks) == 2, str(len(plan_both.tracks)))
|
||||
|
||||
|
||||
class _Handle:
|
||||
"""A JobHandle stand-in, so the import can be driven without a thread."""
|
||||
|
||||
def __init__(self, cancel_after=None):
|
||||
self.messages = []
|
||||
self.done = 0
|
||||
self.total = 0
|
||||
self._cancel_after = cancel_after
|
||||
self.cancelled = False
|
||||
|
||||
def progress(self, done=None, total=None, message=None):
|
||||
if done is not None:
|
||||
self.done = done
|
||||
if total is not None:
|
||||
self.total = total
|
||||
if message is not None:
|
||||
self.messages.append(message)
|
||||
if self._cancel_after is not None and self.done >= self._cancel_after:
|
||||
self.cancelled = True
|
||||
|
||||
def raise_if_cancelled(self):
|
||||
if self.cancelled:
|
||||
raise JobCancelled()
|
||||
|
||||
|
||||
handle = _Handle()
|
||||
result = importer.run(source, dest5, plan5, handle, folder_name="Hardy")
|
||||
check("the import reports what it did", result["tracks"] == 2 and result["playlists"] == 1)
|
||||
check("progress reached the total", handle.total > 0 and handle.done == handle.total,
|
||||
f"{handle.done}/{handle.total}")
|
||||
check("it said what it was doing", any("Copying" in m for m in handle.messages))
|
||||
check("the audio really was copied",
|
||||
sorted(p.name for p in music5.iterdir()) == ["Demo Track 1.mp3", "Demo Track 2.mp3"])
|
||||
check("the tracks are in the collection", len(dest5.tracks) == 8485 + 2)
|
||||
tree5 = dest5.playlist_tree()
|
||||
folder = next((n for n in tree5 if n.name == "Hardy"), None)
|
||||
check("the playlist landed in a folder named after the drive",
|
||||
folder is not None and [c.name for c in folder.children] == ["demos"])
|
||||
check("and the playlist has its tracks",
|
||||
folder is not None and folder.children[0].count == 2)
|
||||
|
||||
print("== import: cancelling rolls back ==")
|
||||
nml6, music6, original6 = fresh_collection()
|
||||
dest6 = TraktorAdapter(nml6)
|
||||
plan6 = importer.plan(source, dest6, music6)
|
||||
# Cancel mid-copy — which is the case that used to leave a half-written file
|
||||
# behind, because cleanup only covered COMPLETED copies.
|
||||
cancelling = _Handle(cancel_after=1)
|
||||
cancelled_ok = _raises(
|
||||
lambda: importer.run(source, dest6, plan6, cancelling, folder_name="Hardy"),
|
||||
JobCancelled,
|
||||
)
|
||||
check("a cancelled import raises rather than half-finishing", cancelled_ok)
|
||||
left = sorted(p.name for p in music6.iterdir()) if music6.exists() else []
|
||||
check("no audio is left orphaned, including the file being written", left == [], str(left))
|
||||
check("the collection on disk is untouched", nml6.read_bytes() == original6)
|
||||
check("and nothing was added in memory either", len(dest6.tracks) == 8485)
|
||||
# The retry must not have to suffix around debris from the cancelled run.
|
||||
retry = _Handle()
|
||||
importer.run(source, dest6, plan6, retry, folder_name="Hardy")
|
||||
check("a retry after a cancel copies under the original names",
|
||||
sorted(p.name for p in music6.iterdir()) == ["Demo Track 1.mp3", "Demo Track 2.mp3"],
|
||||
str(sorted(p.name for p in music6.iterdir())))
|
||||
|
||||
print("== import: missing audio ==")
|
||||
nml7, music7, _ = fresh_collection()
|
||||
dest7 = TraktorAdapter(nml7)
|
||||
plan7 = importer.plan(source, dest7, music7)
|
||||
plan7.tracks[0].missing = True
|
||||
check("a missing file is excluded from the copy", len(plan7.importable) == 1)
|
||||
check("but still reported", len(plan7.as_dict()["missing"]) == 1)
|
||||
r7 = importer.run(source, dest7, plan7, _Handle(), folder_name="Hardy")
|
||||
check("the import proceeds without it", r7["tracks"] == 1 and r7["skipped_missing"] == 1)
|
||||
|
||||
print("== import: duplicate detection ==")
|
||||
plan8 = importer.plan(source, dest5, music5)
|
||||
check("re-importing flags the tracks as already present",
|
||||
all(t.duplicate for t in plan8.tracks), str([t.duplicate for t in plan8.tracks]))
|
||||
check("but does not refuse them — the user chose to add everything",
|
||||
len(plan8.importable) == 2)
|
||||
|
||||
print()
|
||||
print("RESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -250,6 +250,51 @@ export interface CollectionOptions {
|
||||
// never the fallback when nothing is loaded, and sharing a type would invite
|
||||
// components to treat the two as interchangeable.
|
||||
|
||||
// ---- import ----
|
||||
//
|
||||
// Import is the only operation that can run for minutes, so it is the only one
|
||||
// that is a JOB rather than a request: start it, then poll the job.
|
||||
|
||||
export interface ImportRequest {
|
||||
/** Folder the audio is copied into. */
|
||||
destination: string
|
||||
/** Empty track_ids AND empty playlist_ids means the whole drive. */
|
||||
track_ids?: string[]
|
||||
playlist_ids?: string[]
|
||||
/** Playlists land in a folder named this; null keeps them at the root. */
|
||||
folder_name?: string | null
|
||||
}
|
||||
|
||||
export interface ImportPreview {
|
||||
tracks: number
|
||||
importable: number
|
||||
/** Titles whose audio file is not there — reported, then skipped. */
|
||||
missing: string[]
|
||||
/** Titles the collection already has by filename. A warning, not a block. */
|
||||
duplicates: string[]
|
||||
playlists: string[]
|
||||
total_bytes: number
|
||||
destination: string | null
|
||||
free_bytes: number | null
|
||||
enough_space: boolean | null
|
||||
}
|
||||
|
||||
export type JobState = 'running' | 'done' | 'failed' | 'cancelled'
|
||||
|
||||
export interface JobStatus {
|
||||
id: string
|
||||
kind: string
|
||||
state: JobState
|
||||
/** 0 until the job knows its size — show an indeterminate bar until positive. */
|
||||
total: number
|
||||
done: number
|
||||
message: string
|
||||
result: Record<string, unknown> | null
|
||||
error: string | null
|
||||
started_at: number
|
||||
finished_at: number | null
|
||||
}
|
||||
|
||||
export interface SourceCandidate {
|
||||
path: string
|
||||
/** What a person recognises, e.g. "OneLibrary — Hardy". */
|
||||
@@ -509,6 +554,15 @@ export const api = {
|
||||
/** Audition a track off the stick before importing it. */
|
||||
sourceAudioUrl: (trackId: string) =>
|
||||
`${API_BASE}/api/source/tracks/audio?track_id=${encodeURIComponent(trackId)}`,
|
||||
// ---- import ----
|
||||
importPreview: (body: ImportRequest) => send<ImportPreview>('POST', '/api/import/preview', body),
|
||||
/** Starts the job and returns immediately — poll `job()` for progress. */
|
||||
startImport: (body: ImportRequest) => send<JobStatus>('POST', '/api/import', body),
|
||||
job: (id: string) => getJSON<JobStatus>(`/api/jobs/${encodeURIComponent(id)}`),
|
||||
/** A request, not a kill: the job stops at its next checkpoint and cleans up,
|
||||
* so expect `state` to stay 'running' for a moment after this resolves. */
|
||||
cancelJob: (id: string) =>
|
||||
send<JobStatus>('POST', `/api/jobs/${encodeURIComponent(id)}/cancel`),
|
||||
uploadArt: async (trackId: string, file: File) => {
|
||||
const fd = new FormData()
|
||||
fd.append('track_id', trackId)
|
||||
|
||||
Reference in new issue
Block a user