mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Added support for remote file exploring
This commit is contained in:
1 parent
966f3fe8c5
commit
40630ff78e
18 files changed
+717
-70
No files matched your search
@@ -30,6 +30,7 @@ from ... import remote_protocol as rp
|
||||
from ...core.adapter import (
|
||||
AudioFacts,
|
||||
FileTagResult,
|
||||
NotFound,
|
||||
SaveOutcome,
|
||||
Unavailable,
|
||||
Unsupported,
|
||||
@@ -39,6 +40,7 @@ from ...core.query import TrackIndex
|
||||
from .cache import RemoteAudioCache, StaleFacts
|
||||
from .cache import shared as shared_cache
|
||||
from .client import RemoteClient, SessionLost
|
||||
from .folder import ServerFile, ServerFiles
|
||||
from .session import RemoteSession
|
||||
|
||||
_NOT_HERE = "A remote library's paths are the server's configuration"
|
||||
@@ -60,6 +62,13 @@ class RemoteAdapter:
|
||||
self._facts: dict[str, AudioFacts] = {}
|
||||
#: Server path of an upload → (the local file it came from, its analysis lead).
|
||||
self._uploads: dict[str, tuple[Path, float | None]] = {}
|
||||
#: Content-folder files a listing returned, by their server path.
|
||||
self._listed: dict[str, ServerFile] = {}
|
||||
#: `str(Path(p))` → `p` for every server path this side has turned into
|
||||
#: a `Path` (an upload's target, a listed file): on Windows that
|
||||
#: conversion rewrites the separators, and the server must get its own
|
||||
#: spelling back.
|
||||
self._server_paths: dict[str, str] = {}
|
||||
self._dirty = bool(hello.get("dirty"))
|
||||
self._load()
|
||||
|
||||
@@ -260,6 +269,7 @@ class RemoteAdapter:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
self._uploads[landed["path"]] = (Path(source), landed.get("analysis_lead"))
|
||||
self._server_paths[str(Path(landed["path"]))] = landed["path"]
|
||||
return Path(landed["path"])
|
||||
|
||||
def free_space(self, path: str) -> int:
|
||||
@@ -268,8 +278,13 @@ class RemoteAdapter:
|
||||
|
||||
def delete_upload(self, path) -> None:
|
||||
"""Undo `upload_audio` (a cancelled or failed import)."""
|
||||
self._uploads.pop(str(path), None)
|
||||
self.client.delete_upload(str(path))
|
||||
key = self._server_key(path)
|
||||
self._uploads.pop(key, None)
|
||||
self.client.delete_upload(key)
|
||||
|
||||
def _server_key(self, path) -> str:
|
||||
text = str(path)
|
||||
return self._server_paths.get(text, text)
|
||||
|
||||
def add_tracks(self, items, *, checkpoint=None):
|
||||
"""Add uploaded files. Where the platform analyses what it adds (the
|
||||
@@ -279,10 +294,20 @@ class RemoteAdapter:
|
||||
|
||||
wire = []
|
||||
total = len(items)
|
||||
for n, item in enumerate(items, start=1):
|
||||
key = str(item.audio_path)
|
||||
keys = [self._server_key(item.audio_path) for item in items]
|
||||
# Files already in the content folder (added in place): the server says
|
||||
# whether the platform analyses, and only then is the file fetched.
|
||||
in_place = [k for k, item in zip(keys, items)
|
||||
if item.analysis is None and k not in self._uploads and k in self._listed]
|
||||
leads = self.client.folder_leads(in_place) if in_place else {}
|
||||
for n, (item, key) in enumerate(zip(items, keys), start=1):
|
||||
source, lead = self._uploads.get(key, (None, None))
|
||||
analysis = item.analysis
|
||||
if analysis is None and source is None and leads.get(key) is not None:
|
||||
lead = leads[key]
|
||||
if checkpoint is not None:
|
||||
checkpoint(f"Downloading {item.track.title or Path(key).name} ({n}/{total})", step=n, of=total)
|
||||
source = self.folder_audio(key)
|
||||
if analysis is None and lead is not None and source is not None:
|
||||
if checkpoint is not None:
|
||||
checkpoint(f"Analysing {item.track.title or source.name} ({n}/{total})", step=n, of=total)
|
||||
@@ -302,8 +327,8 @@ class RemoteAdapter:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
self._apply(envelope)
|
||||
for item in items:
|
||||
self._uploads.pop(str(item.audio_path), None)
|
||||
for key in keys:
|
||||
self._uploads.pop(key, None)
|
||||
return envelope["result"]
|
||||
|
||||
def apply_stem_swaps(self, swaps, *, add_to_playlist=None):
|
||||
@@ -393,6 +418,46 @@ class RemoteAdapter:
|
||||
facts = self.audio_facts([track_id]).get(track_id)
|
||||
return self.cache.get(facts) if facts else None
|
||||
|
||||
# ---- the content folder, browsed --------------------------------------------------
|
||||
def folder_listing(self, path: str | None) -> ServerFiles:
|
||||
"""The audio directly inside a content folder (None: the folder itself),
|
||||
as the server lists it — and remembered, so a file can then be played
|
||||
or added by its path."""
|
||||
listing = ServerFiles.from_wire(self, self.client.folder_tracks(path))
|
||||
with self._lock:
|
||||
self._listed = {k: f for k, f in self._listed.items() if f.folder != listing.path}
|
||||
self._listed.update(listing.files)
|
||||
self._server_paths.update({str(Path(k)): k for k in listing.files})
|
||||
return listing
|
||||
|
||||
def listed_files(self, paths) -> ServerFiles | None:
|
||||
"""The listed files among `paths` as one source (they may come from
|
||||
several folders); None when none of them was listed."""
|
||||
with self._lock:
|
||||
found = [self._listed[p] for p in paths if p in self._listed]
|
||||
return ServerFiles(self, found[0].folder, found) if found else None
|
||||
|
||||
def folder_audio(self, path: str, *, progress=None) -> Path:
|
||||
"""A local copy of a listed file, downloaded into the shared cache —
|
||||
keyed by the same facts as a library track's, so a file that is both
|
||||
downloads once."""
|
||||
for attempt in range(2):
|
||||
with self._lock:
|
||||
found = self._listed.get(path)
|
||||
if found is None:
|
||||
raise NotFound("File not found — browse to its folder first")
|
||||
cached = self.cache.get(found.facts)
|
||||
if cached is not None:
|
||||
return cached
|
||||
try:
|
||||
return self.cache.fetch(
|
||||
found.facts, lambda partial: self.client.folder_download(path, partial, progress=progress))
|
||||
except StaleFacts:
|
||||
if attempt:
|
||||
raise
|
||||
self.folder_listing(found.folder) # changed on the server: re-read it
|
||||
raise NotFound(path)
|
||||
|
||||
# ---- paths: the server's business ------------------------------------------------
|
||||
def set_path_mapping(self, mapping):
|
||||
raise Unsupported(_NOT_HERE)
|
||||
|
||||
@@ -246,6 +246,29 @@ class RemoteClient:
|
||||
def fs_list(self, path: str | None) -> dict:
|
||||
return self.request("GET", "/v1/fs/list", params={"path": path} if path else None).json()
|
||||
|
||||
def folder_tracks(self, path: str | None) -> dict:
|
||||
return self.request("GET", "/v1/folder/tracks", params={"path": path} if path else None,
|
||||
timeout=None).json()
|
||||
|
||||
def folder_leads(self, paths: list[str]) -> dict[str, float | None]:
|
||||
return self.request("POST", "/v1/folder/leads", json={"paths": paths}).json()["leads"]
|
||||
|
||||
def folder_download(self, path: str, target: Path, *, progress=None) -> dict:
|
||||
"""Stream a listed content-folder file into `target` (as `download`)."""
|
||||
with self.stream("GET", "/v1/folder/audio", params={"path": path}, timeout=None) as response:
|
||||
if response.status_code >= 400:
|
||||
response.read()
|
||||
self.check(response)
|
||||
with open(target, "wb") as out:
|
||||
for chunk in response.iter_bytes(1 << 20):
|
||||
out.write(chunk)
|
||||
if progress is not None:
|
||||
progress(len(chunk))
|
||||
return {
|
||||
"size": int(response.headers.get("X-Konduktor-Size") or 0),
|
||||
"mtime_ns": int(response.headers.get("X-Konduktor-Mtime-Ns") or 0),
|
||||
}
|
||||
|
||||
def fs_space(self, path: str | None) -> int:
|
||||
return int(self.request("GET", "/v1/fs/space", params={"path": path} if path else None).json()["free"])
|
||||
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
"""The server's content folder, browsed from this computer like a drive.
|
||||
|
||||
The sidebar's Files trees read folders on THIS computer (`core/folder.py`). On a
|
||||
remote library the music lives in the server's content folder, which this
|
||||
computer cannot see — so the server lists it (`/v1/folder/tracks`: tags, file
|
||||
facts, and which files the library already holds) and this module holds the
|
||||
answer as a read-only SOURCE, the shape the table, the deck and the importer
|
||||
already read.
|
||||
|
||||
Adding one of these files never uploads anything: it is already where the
|
||||
library can reach it, so it is added IN PLACE (`on_library_host`), and the
|
||||
importer skips both the copy and the copy-or-reference question.
|
||||
|
||||
Ids are the file's path ON THE SERVER — a string, never a `Path` on this side
|
||||
until the importer needs one, because a server path is not a path here (on a
|
||||
Windows laptop `Path("/music/x.mp3")` is `\\music\\x.mp3`).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from ...core.adapter import AudioFacts
|
||||
from ...core.model import PlaylistNode, Track, TrackCues
|
||||
|
||||
|
||||
@dataclass
|
||||
class ServerFile:
|
||||
folder: str
|
||||
track: Track
|
||||
facts: AudioFacts
|
||||
#: The library's id for this file, when it already points at it.
|
||||
held: str | None = None
|
||||
|
||||
|
||||
class ServerFiles:
|
||||
"""Files in the content folder, as the read half of a source."""
|
||||
|
||||
#: The importer's cue that these are already on the machine holding the
|
||||
#: library: added where they are, neither copied nor uploaded.
|
||||
on_library_host = True
|
||||
|
||||
def __init__(self, adapter, path: str, files: list[ServerFile]):
|
||||
self.adapter = adapter
|
||||
self.path = path
|
||||
self._files = {f.track.id: f for f in files}
|
||||
|
||||
@classmethod
|
||||
def from_wire(cls, adapter, body: dict) -> "ServerFiles":
|
||||
folder = body["path"]
|
||||
facts = body.get("files") or {}
|
||||
held = body.get("held") or {}
|
||||
files = []
|
||||
for raw in body.get("tracks") or []:
|
||||
track = Track.model_validate(raw)
|
||||
fact = facts.get(track.id)
|
||||
if fact is None:
|
||||
continue
|
||||
files.append(ServerFile(
|
||||
folder=folder, track=track,
|
||||
facts=AudioFacts(key=track.id, size=int(fact["size"]), mtime_ns=int(fact["mtime_ns"])),
|
||||
held=held.get(track.id),
|
||||
))
|
||||
return cls(adapter, folder, files)
|
||||
|
||||
@property
|
||||
def files(self) -> dict[str, ServerFile]:
|
||||
return self._files
|
||||
|
||||
@property
|
||||
def tracks(self) -> list[Track]:
|
||||
return [f.track for f in self._files.values()]
|
||||
|
||||
def track(self, track_id: str) -> Track | None:
|
||||
found = self._files.get(track_id)
|
||||
return found.track if found else None
|
||||
|
||||
def held(self, track_id: str) -> str | None:
|
||||
found = self._files.get(track_id)
|
||||
return found.held if found else None
|
||||
|
||||
def size(self, track_id: str) -> int:
|
||||
found = self._files.get(track_id)
|
||||
return found.facts.size if found else 0
|
||||
|
||||
def track_cues(self, track_id: str) -> TrackCues | None:
|
||||
return TrackCues(cues=[], grid_markers=[]) if track_id in self._files else None
|
||||
|
||||
def audio_facts(self, track_ids) -> dict[str, AudioFacts]:
|
||||
return {t: self._files[t].facts for t in track_ids if t in self._files}
|
||||
|
||||
def audio_path(self, track_id: str, *, progress=None) -> Path | None:
|
||||
"""A local copy (downloaded into the shared cache, like a library track)."""
|
||||
if track_id not in self._files:
|
||||
return None
|
||||
return self.adapter.folder_audio(track_id, progress=progress)
|
||||
|
||||
def playlist_tree(self) -> list[PlaylistNode]:
|
||||
return []
|
||||
|
||||
def playlist_tracks(self, node_id: str) -> list[Track] | None:
|
||||
return None
|
||||
@@ -191,6 +191,30 @@ def plan(source, dest, destination: Path | None, *, track_ids=None, playlist_ids
|
||||
return plan
|
||||
|
||||
|
||||
def plan_on_host(source, track_ids) -> ImportPlan:
|
||||
"""A plan for files that are already on the machine holding the library — a
|
||||
remote library's content folder, browsed from this computer
|
||||
(`source.on_library_host`). Nothing is checked on THIS disk, where those
|
||||
paths mean nothing: the source says each file's size and which ones the
|
||||
library already holds. Added in place (`run(reference=True)`), so there is
|
||||
no destination and nothing to copy.
|
||||
"""
|
||||
plan = ImportPlan(destination=None)
|
||||
for track_id in dict.fromkeys(track_ids):
|
||||
track = source.track(track_id)
|
||||
if track is None:
|
||||
continue
|
||||
name = track_id.replace("\\", "/").rsplit("/", 1)[-1]
|
||||
plan.tracks.append(PlannedTrack(
|
||||
track_id=track_id,
|
||||
title=track.title or name,
|
||||
source_path=Path(track_id),
|
||||
size=source.size(track_id),
|
||||
existing_id=source.held(track_id),
|
||||
))
|
||||
return plan
|
||||
|
||||
|
||||
def _playlist_name(source, node_id: str) -> str | None:
|
||||
for nid, name in _all_playlists(source):
|
||||
if nid == node_id:
|
||||
@@ -321,7 +345,7 @@ def run(
|
||||
# a folder on the server, instead of copied here. Nothing can be left in
|
||||
# place — the server cannot see this computer's files.
|
||||
uploads = not places and uploads_audio(dest)
|
||||
if uploads and reference:
|
||||
if uploads and reference and not getattr(source, "on_library_host", False):
|
||||
raise ValueError("A remote library cannot reference files on this computer")
|
||||
if not reference and not places and not uploads:
|
||||
assert destination is not None
|
||||
|
||||
+124
-12
@@ -2183,6 +2183,50 @@ def source_track_stems(track_id: str) -> dict:
|
||||
|
||||
FOLDERS = FolderScanner()
|
||||
|
||||
# A remote library's content folder rides the same routes. Its paths carry this
|
||||
# prefix, so a path on the server can never be taken for the same path on this
|
||||
# computer — and the UI's folder view, deck and add dialog need no second set of
|
||||
# routes. The prefix alone is the content folder itself.
|
||||
SERVER_FOLDER = "server:"
|
||||
|
||||
|
||||
def _on_server(path: str) -> str | None:
|
||||
"""The server path behind a prefixed one ('' = the content folder), else None."""
|
||||
return path[len(SERVER_FOLDER):] if path.startswith(SERVER_FOLDER) else None
|
||||
|
||||
|
||||
def _server_track(track: Track) -> Track:
|
||||
return track.model_copy(update={"id": SERVER_FOLDER + track.id})
|
||||
|
||||
|
||||
def _folder_rows(dest, tracks: list[Track], held_of) -> tuple[list[Track], dict[str, str]]:
|
||||
"""A folder's files as table rows. Where the library holds a file, the row
|
||||
IS the library's track — its key, rating, comments, cues and plays, and
|
||||
its id, so it plays, edits and drags as the collection track it is
|
||||
(decided 2026-10-10) — else the file's own tags. Also returns library id →
|
||||
the file's folder id, for the rows that are library tracks: adding still
|
||||
speaks in folder ids."""
|
||||
rows: list[Track] = []
|
||||
files: dict[str, str] = {}
|
||||
for track in tracks:
|
||||
known = held_of(track)
|
||||
held = dest.track(known) if known else None
|
||||
if held is None or held.id in files:
|
||||
rows.append(track)
|
||||
continue
|
||||
rows.append(held)
|
||||
files[held.id] = track.id
|
||||
return rows, files
|
||||
|
||||
|
||||
def _server_file(track_id: str) -> tuple[object, str]:
|
||||
"""The remote adapter and the server path of a listed content-folder file."""
|
||||
adapter = _require_remote()
|
||||
raw = _on_server(track_id) or ""
|
||||
if adapter.listed_files([raw]) is None:
|
||||
raise HTTPException(404, "Track not found — browse to its folder first")
|
||||
return adapter, raw
|
||||
|
||||
|
||||
def _drive_of(path: Path, drives: list[dict]) -> dict | None:
|
||||
"""The drive `path` lives on: the longest drive root that contains it."""
|
||||
@@ -2209,6 +2253,10 @@ def fs_drives() -> list[Drive]:
|
||||
found = places.drives()
|
||||
libraries = sources()
|
||||
out = [Drive(**d) for d in found]
|
||||
if STATE.remote is not None and STATE.remote_config is not None:
|
||||
# The server holding the library, first: its content folder is where
|
||||
# this library's music is, and this computer cannot see it otherwise.
|
||||
out.insert(0, Drive(name=STATE.remote_config.name, path=SERVER_FOLDER, kind="server"))
|
||||
externals = [d for d in found if d["path"] != "/"]
|
||||
for lib in libraries:
|
||||
home = _drive_of(Path(lib.path), externals)
|
||||
@@ -2223,6 +2271,11 @@ def fs_drives() -> list[Drive]:
|
||||
@app.get("/api/fs/folders", response_model=list[FsEntry])
|
||||
def fs_folders(path: str) -> list[FsEntry]:
|
||||
"""The visible folders directly inside `path` — one level of a Files tree."""
|
||||
raw = _on_server(path)
|
||||
if raw is not None:
|
||||
listing = _require_remote().client.fs_list(raw or None)
|
||||
return [FsEntry(name=e["name"], path=SERVER_FOLDER + e["path"])
|
||||
for e in listing["entries"] if e["is_dir"]]
|
||||
base = Path(path).expanduser()
|
||||
if not base.is_dir():
|
||||
raise HTTPException(404, f"Not a folder: {base}")
|
||||
@@ -2236,16 +2289,27 @@ def _formats() -> list[str]:
|
||||
@app.get("/api/folder/tracks", response_model=FolderTracks)
|
||||
def folder_tracks(path: str) -> FolderTracks:
|
||||
"""The audio files directly inside a folder, and which are already held."""
|
||||
raw = _on_server(path)
|
||||
if raw is not None:
|
||||
adapter = _require_remote()
|
||||
listing = adapter.folder_listing(raw or None)
|
||||
rows, files = _folder_rows(adapter, [_server_track(t) for t in listing.tracks],
|
||||
lambda t: listing.held(t.id[len(SERVER_FOLDER):]))
|
||||
return FolderTracks(path=SERVER_FOLDER + listing.path, tracks=rows,
|
||||
in_collection=list(files), files=files, removable=False)
|
||||
base = Path(path).expanduser()
|
||||
if not base.is_dir():
|
||||
raise HTTPException(404, f"Not a folder: {base}")
|
||||
source = FOLDERS.scan(base, _formats())
|
||||
held = importer._existing_files(require_adapter())
|
||||
dest = require_adapter()
|
||||
held = importer._existing_files(dest)
|
||||
rows, files = _folder_rows(dest, source.tracks, lambda t: held.get(importer._key(Path(t.id))))
|
||||
drive = _drive_of(base, places.drives())
|
||||
return FolderTracks(
|
||||
path=str(base),
|
||||
tracks=source.tracks,
|
||||
in_collection=[t.id for t in source.tracks if importer._key(Path(t.id)) in held],
|
||||
tracks=rows,
|
||||
in_collection=list(files),
|
||||
files=files,
|
||||
removable=drive is None or drive["kind"] == "external",
|
||||
)
|
||||
|
||||
@@ -2263,11 +2327,17 @@ def _folder_track(track_id: str) -> FolderSource:
|
||||
def folder_capabilities(path: str) -> Capabilities:
|
||||
from .core.folder import capabilities_for
|
||||
|
||||
raw = _on_server(path)
|
||||
if raw is not None:
|
||||
return capabilities_for(Path(raw) if raw else Path(STATE.remote_config.name if STATE.remote_config else "Server"))
|
||||
return capabilities_for(Path(path))
|
||||
|
||||
|
||||
@app.get("/api/folder/tracks/cues", response_model=TrackCues)
|
||||
def folder_track_cues(track_id: str) -> TrackCues:
|
||||
if _on_server(track_id) is not None:
|
||||
_server_file(track_id)
|
||||
return TrackCues(cues=[], grid_markers=[])
|
||||
cues = _folder_track(track_id).track_cues(track_id)
|
||||
assert cues is not None
|
||||
return cues
|
||||
@@ -2275,7 +2345,11 @@ def folder_track_cues(track_id: str) -> TrackCues:
|
||||
|
||||
@app.get("/api/folder/tracks/audio")
|
||||
def folder_track_audio(track_id: str, stem: int | None = None) -> FileResponse:
|
||||
path = _folder_track(track_id).audio_path(track_id)
|
||||
if _on_server(track_id) is not None:
|
||||
adapter, raw = _server_file(track_id)
|
||||
path = adapter.folder_audio(raw) # this computer's copy, as for a library track
|
||||
else:
|
||||
path = _folder_track(track_id).audio_path(track_id)
|
||||
if path is None or not path.is_file():
|
||||
raise HTTPException(404, "Audio file not found")
|
||||
if stem is not None:
|
||||
@@ -2286,6 +2360,9 @@ def folder_track_audio(track_id: str, stem: int | None = None) -> FileResponse:
|
||||
|
||||
@app.get("/api/folder/tracks/stems")
|
||||
def folder_track_stems(track_id: str) -> dict:
|
||||
if _on_server(track_id) is not None:
|
||||
adapter, raw = _server_file(track_id)
|
||||
return _stem_layout_of(adapter.folder_audio(raw))
|
||||
return _stem_layout_of(_folder_track(track_id).audio_path(track_id))
|
||||
|
||||
|
||||
@@ -2295,6 +2372,34 @@ def _require_addable(dest) -> None:
|
||||
raise HTTPException(422, "Tracks cannot be added to this library")
|
||||
|
||||
|
||||
def _check_add_targets(dest, body: FolderAddRequest) -> None:
|
||||
if body.playlist_id is not None and dest.playlist_entries(body.playlist_id) is None:
|
||||
raise HTTPException(404, f"Playlist not found: {body.playlist_id}")
|
||||
if body.export_id is not None:
|
||||
if STATE.library_id is None or exports.get(STATE.library_id, body.export_id) is None:
|
||||
raise HTTPException(404, f"Export not found: {body.export_id}")
|
||||
|
||||
|
||||
def _is_server_add(body: FolderAddRequest) -> bool:
|
||||
on_server = [_on_server(t) is not None for t in body.track_ids]
|
||||
if any(on_server) and not all(on_server):
|
||||
raise HTTPException(400, "Files on the server and on this computer are added separately")
|
||||
return bool(on_server) and all(on_server)
|
||||
|
||||
|
||||
def _server_add_plan(body: FolderAddRequest):
|
||||
"""Files in the remote library's content folder: already where the library
|
||||
can reach them, so they are added IN PLACE — nothing uploaded, nothing asked."""
|
||||
dest = _require_remote()
|
||||
_require_addable(dest)
|
||||
paths = [_on_server(t) for t in body.track_ids]
|
||||
source = dest.listed_files(paths)
|
||||
if source is None:
|
||||
raise HTTPException(400, "No tracks to add")
|
||||
_check_add_targets(dest, body)
|
||||
return source, dest, importer.plan_on_host(source, paths)
|
||||
|
||||
|
||||
def _folder_add_plan(body: FolderAddRequest):
|
||||
dest = require_adapter()
|
||||
_require_addable(dest)
|
||||
@@ -2315,11 +2420,7 @@ def _folder_add_plan(body: FolderAddRequest):
|
||||
if not body.destination:
|
||||
raise HTTPException(400, "Copying needs a destination folder")
|
||||
destination = Path(body.destination).expanduser()
|
||||
if body.playlist_id is not None and dest.playlist_entries(body.playlist_id) is None:
|
||||
raise HTTPException(404, f"Playlist not found: {body.playlist_id}")
|
||||
if body.export_id is not None:
|
||||
if STATE.library_id is None or exports.get(STATE.library_id, body.export_id) is None:
|
||||
raise HTTPException(404, f"Export not found: {body.export_id}")
|
||||
_check_add_targets(dest, body)
|
||||
return source, dest, destination, importer.plan(
|
||||
source, dest, destination, track_ids=[t.id for t in tracks]
|
||||
)
|
||||
@@ -2327,6 +2428,11 @@ def _folder_add_plan(body: FolderAddRequest):
|
||||
|
||||
@app.post("/api/folder/add/preview")
|
||||
def folder_add_preview(body: FolderAddRequest) -> dict:
|
||||
if _is_server_add(body):
|
||||
_source, _dest, plan = _server_add_plan(body)
|
||||
out = plan.as_dict()
|
||||
out.update(total_bytes=0, free_bytes=None, enough_space=None, removable=False)
|
||||
return out
|
||||
_source, dest, destination, plan = _folder_add_plan(body)
|
||||
out = plan.as_dict(free_bytes=importer.free_bytes(destination, dest) if destination else None)
|
||||
if importer.places_audio(dest):
|
||||
@@ -2343,10 +2449,16 @@ def folder_add_preview(body: FolderAddRequest) -> dict:
|
||||
def folder_add(body: FolderAddRequest) -> JobStatus:
|
||||
"""Add browsed files to the collection. A job, like import: copying can be long."""
|
||||
_require_no_pending_stems("Adding files")
|
||||
source, dest, destination, plan = _folder_add_plan(body)
|
||||
in_place = _is_server_add(body)
|
||||
if in_place:
|
||||
source, dest, plan = _server_add_plan(body)
|
||||
destination = None
|
||||
else:
|
||||
source, dest, destination, plan = _folder_add_plan(body)
|
||||
if not plan.importable and not plan.existing:
|
||||
raise HTTPException(400, "Nothing to add (none of those files exist)")
|
||||
if body.mode == "copy" or importer.places_audio(dest):
|
||||
# Nothing is copied in place, so there is no space to check.
|
||||
if not in_place and (body.mode == "copy" or importer.places_audio(dest)):
|
||||
free = importer.free_bytes(destination, dest)
|
||||
needed = importer.placed_bytes(dest, plan) if importer.places_audio(dest) else plan.total_bytes
|
||||
if free is not None and free < needed + importer.SPACE_HEADROOM:
|
||||
@@ -2362,7 +2474,7 @@ def folder_add(body: FolderAddRequest) -> JobStatus:
|
||||
def work(handle):
|
||||
result = importer.run(
|
||||
source, dest, plan, handle,
|
||||
reference=body.mode == "reference",
|
||||
reference=in_place or body.mode == "reference",
|
||||
into_playlist=body.playlist_id,
|
||||
)
|
||||
# Export sets are Konduktor's own data, not the library's, so they are
|
||||
|
||||
@@ -35,7 +35,8 @@ from .core.model import AutoHotcue, Track, TrackCues
|
||||
#: at least its own: minors only add. Bump the minor for an added route or
|
||||
#: method, the major for anything an older client would misread.
|
||||
#: 1.1 — `move_playlist` (sidebar drag and drop).
|
||||
API_VERSION: tuple[int, int] = (1, 1)
|
||||
#: 1.2 — `/v1/folder/*`: the content folder browsed as a Files tree.
|
||||
API_VERSION: tuple[int, int] = (1, 2)
|
||||
|
||||
#: How long a session survives without a heartbeat, and how often the holder
|
||||
#: sends one. Long enough to ride out a Wi-Fi blip or a switch to the fallback
|
||||
|
||||
@@ -521,11 +521,15 @@ class Drive(BaseModel):
|
||||
candidate `/api/sources` reports, attached to the drive it lives on so the
|
||||
sidebar can show one row per drive rather than a device list and a drive
|
||||
list that disagree about what is plugged in.
|
||||
|
||||
`server` is a remote library's content folder (path `server:`), listed
|
||||
first while a remote library is open — the one place its music can be
|
||||
browsed by folder from this computer.
|
||||
"""
|
||||
|
||||
name: str
|
||||
path: str
|
||||
kind: Literal["local", "external"]
|
||||
kind: Literal["local", "external", "server"]
|
||||
library: SourceCandidate | None = None
|
||||
|
||||
|
||||
@@ -533,9 +537,13 @@ class FolderTracks(BaseModel):
|
||||
"""The audio files directly inside one folder, projected as tracks."""
|
||||
|
||||
path: str
|
||||
# A file the collection holds is listed AS the collection's track (its id,
|
||||
# key, rating, cues…); any other file as its own tags, id = its path.
|
||||
tracks: list[Track]
|
||||
# Ids (= absolute paths) of the files the collection already points at.
|
||||
# Collection ids of the rows that are collection tracks.
|
||||
in_collection: list[str]
|
||||
# Those rows' collection id → the file's folder id, which adding takes.
|
||||
files: dict[str, str] = {}
|
||||
# On an external drive: a track referenced in place goes missing when the
|
||||
# drive is unplugged, which the add dialog has to say.
|
||||
removable: bool
|
||||
|
||||
@@ -44,6 +44,7 @@ from ..core.adapter import (
|
||||
NotFound,
|
||||
Unsupported,
|
||||
)
|
||||
from ..core.folder import FolderScanner
|
||||
from ..core.places import is_os_housekeeping
|
||||
from .config import ConfigError, ServerConfig
|
||||
from .session import InUse, Lost, SessionLock
|
||||
@@ -65,6 +66,10 @@ class Server:
|
||||
self.lock = lock or SessionLock()
|
||||
self.rev = 0
|
||||
self._rev_lock = threading.Lock()
|
||||
#: The content folder's audio as browsed from a client's Files tree —
|
||||
#: tags read once per folder state, and the gatekeeper for streaming
|
||||
#: one of those files (only a file a listing found is served).
|
||||
self.folders = FolderScanner()
|
||||
|
||||
# ---- opening ---------------------------------------------------------------
|
||||
def open(self) -> None:
|
||||
@@ -388,6 +393,73 @@ def create_app(server: Server) -> FastAPI:
|
||||
"entries": entries,
|
||||
}
|
||||
|
||||
@app.get("/v1/folder/tracks")
|
||||
def folder_tracks(path: str | None = None) -> dict:
|
||||
"""The audio directly inside a content folder, projected as tracks — the
|
||||
client's Files tree for the server, like `/api/folder/tracks` for a
|
||||
drive of its own. Tags only (no decoding). `held` maps each file the
|
||||
library already points at to the library's id for it, so the client
|
||||
can tick it off and add it to a playlist without adding it twice."""
|
||||
from .. import importer
|
||||
|
||||
folder = server.confine(path)
|
||||
if not folder.is_dir():
|
||||
raise HTTPException(404, f"Not a folder: {folder}")
|
||||
adapter = server.adapter
|
||||
source = server.folders.scan(folder, adapter.capabilities().tracks.audio_formats)
|
||||
library = importer._existing_files(adapter)
|
||||
files, held = {}, {}
|
||||
for track in source.tracks:
|
||||
try:
|
||||
st = Path(track.id).stat()
|
||||
except OSError:
|
||||
continue
|
||||
files[track.id] = {"size": st.st_size, "mtime_ns": st.st_mtime_ns}
|
||||
known = library.get(importer._key(Path(track.id)))
|
||||
if known is not None:
|
||||
held[track.id] = known
|
||||
return {
|
||||
"path": str(folder),
|
||||
"tracks": [t.model_dump(mode="json") for t in source.tracks if t.id in files],
|
||||
"files": files,
|
||||
"held": held,
|
||||
}
|
||||
|
||||
def listed_file(path: str) -> Path:
|
||||
# Confined (a symlink in a listing cannot lead out of the content
|
||||
# folder), and only a file a listing found: this is not a way to read
|
||||
# any path on the server.
|
||||
server.confine(path)
|
||||
source = server.folders.source_for_file(path)
|
||||
if source is None:
|
||||
raise HTTPException(404, "File not found — list its folder first")
|
||||
target = Path(path)
|
||||
if not target.is_file():
|
||||
raise HTTPException(404, "The audio file is missing")
|
||||
return target
|
||||
|
||||
@app.get("/v1/folder/audio")
|
||||
def folder_audio(path: str):
|
||||
target = listed_file(path)
|
||||
st = target.stat()
|
||||
media = mimetypes.guess_type(str(target))[0] or "application/octet-stream"
|
||||
return FileResponse(target, media_type=media, headers={
|
||||
"X-Konduktor-Size": str(st.st_size),
|
||||
"X-Konduktor-Mtime-Ns": str(st.st_mtime_ns),
|
||||
})
|
||||
|
||||
@app.post("/v1/folder/leads")
|
||||
def folder_leads(body: dict = Body(...)) -> dict:
|
||||
"""The analysis lead of each listed file, as an upload reports it: what
|
||||
a client adding these files IN PLACE measures with. None for every file
|
||||
when the platform does not analyse what it adds."""
|
||||
lead = getattr(server.adapter, "analysis_lead", None)
|
||||
out = {}
|
||||
for path in body.get("paths") or []:
|
||||
target = listed_file(str(path))
|
||||
out[str(path)] = lead(target) if lead else None
|
||||
return {"leads": out}
|
||||
|
||||
@app.get("/v1/fs/space")
|
||||
def fs_space(path: str | None = None) -> dict:
|
||||
folder = server.confine(path)
|
||||
|
||||
Reference in new issue
Block a user