Files
konduktor/backend/konduktor/schemas.py
T

576 lines
17 KiB
Python

"""API response models (Pydantic)."""
from __future__ import annotations
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field
from .core.capabilities import CueRole, CueType
class CreatePlaylist(BaseModel):
name: str
parent_id: str | None = None # folder id ("fld:..."); None = root
class RenamePlaylist(BaseModel):
name: str
class SetEntries(BaseModel):
track_ids: list[str] # ordered; full desired contents of the playlist
class AddEntries(BaseModel):
track_ids: list[str]
# Tracks the playlist already holds: "skip" them, "add" them again (only
# where `playlists.duplicates`, else skipped), or "ask" — change nothing and
# report how many, so the UI can ask and send again with skip/add.
duplicates: Literal["skip", "add", "ask"] = "skip"
class MovePlaylist(BaseModel):
node_id: str
parent_id: str | None = None # None = the top level
index: int # among the new parent's children, not counting the node
class EditTrack(BaseModel):
track_id: str
fields: dict[str, str | int | None]
class FileTagOutcome(BaseModel):
track_id: str
file: str
ok: bool
status: str
detail: str = ""
class SaveResult(BaseModel):
saved: bool
commit: str | None = None # sha of the version-history commit (None if deduped)
playlists: int
file_tags: list[FileTagOutcome] = []
class HistoryEntry(BaseModel):
id: str # commit sha
timestamp: str # ISO 8601, UTC
summary: str # human-readable edit summary
class AddGridMarker(BaseModel):
track_id: str
start: float # seconds
bpm: float | None = None # unset = inherit the tempo governing that position
class GridMarkerEdit(BaseModel):
track_id: str
index: int # into the start-ordered marker list
start: float | None = None # move it (clamped between its neighbours)
bpm: float | None = None # retempo the section it opens
class ReplaceGrid(BaseModel):
track_id: str
markers: list[GridMarker] = [] # [] is equivalent to deleting the grid
class SetGridLock(BaseModel):
track_id: str
locked: bool
class SetCue(BaseModel):
track_id: str
slot: int # bank slot; capabilities.cues.hotcue_slots bounds it
start: float # seconds
type: CueType = "cue"
role: CueRole = "hotcue"
length: float = 0.0 # seconds (>0 for a loop cue)
name: str | None = None
color: str | None = None
AutoCueEvent = Literal[
"first_beat", "intro_end",
"build_1", "drop_1", "breakdown_1",
"build_2", "drop_2", "breakdown_2",
"build_3", "drop_3", "breakdown_3",
"outro", "last_beat",
]
AutoCueStatus = Literal["placed", "not_found", "out_of_range", "occupied", "protected", "duplicate"]
class AutoCueSlot(BaseModel):
"""One row of the Auto Hotcues template: bind a slot to a structural event."""
slot: int
event: AutoCueEvent
offset_beats: int = 0
overwrite: bool = False # replace a cue already in this slot
class AutoHotcuesRequest(BaseModel):
track_id: str
slots: list[AutoCueSlot]
class TrackIds(BaseModel):
"""A body naming a set of tracks — the bulk Remove commands."""
track_ids: list[str]
class AutoHotcuesBatchRequest(BaseModel):
"""The same template applied to every track. `overwrite` on a slot means
"replace this slot's cue on every track that has one"."""
track_ids: list[str]
slots: list[AutoCueSlot]
class AutoCueOutcome(BaseModel):
slot: int
event: AutoCueEvent
status: AutoCueStatus
start: float | None = None # seconds, when placed
name: str | None = None
duplicate_of: int | None = None # for "duplicate": the slot whose cue (kept or new) has this beat
class AutoGridRequest(BaseModel):
track_id: str
class AnalyzeRequest(BaseModel):
"""The Analyze dialog's choices. BPM and Grid are independent halves of a
beatgrid (`core/grid_plan`); `replace_grid` only guards a FULL re-analysis
(both ticked), since with one tick adjusting the grid is the point.
`replace_key` lets detection overwrite a key the track already has."""
track_ids: list[str]
bpm: bool = True
grid: bool = True
key: bool = False
replace_grid: bool = False
replace_key: bool = False
class AnalyzePreview(BaseModel):
"""What an Analyze run WOULD do, for the dialog. Counted from the
projection, so on a platform whose marker counts are lazy (Rekordbox,
OneLibrary: 1 for any track with a BPM) a flexible grid is only found when
the run reads the real grid — it is then skipped and reported."""
total: int
tracks_to_analyze: int = 0 # tracks with anything to do (grid and key overlap)
# Grid: what `plan_grid` decides per track — full / bpm / phase / skipped.
grid_full: int = 0
grid_bpm: int = 0
grid_phase: int = 0
grid_locked: int = 0
grid_existing: int = 0 # skipped: has a grid, Replace not ticked
grid_flexible: int = 0
with_grid: int = 0 # unlocked tracks that have a grid (the Replace tick's count)
# Key.
key_set: int = 0
key_existing: int = 0 # skipped: has a key, Replace not ticked
with_key: int = 0 # tracks that have a key (the Replace tick's count)
class AutoGridBatchRequest(BaseModel):
track_ids: list[str]
# False skips tracks that already have a grid. Locked grids are skipped
# either way: a lock is the user saying "never re-analyse this".
replace_existing: bool = False
class SetCueType(BaseModel):
track_id: str
slot: int
type: CueType
class SetCueColor(BaseModel):
track_id: str
slot: int
color: str | None = None # a capabilities.cues.palette entry; None = uncoloured
class StemEngineInstall(BaseModel):
# None = this computer's default engine; "windows-x64-cuda" to take the GPU one.
target: str | None = None
# Also fetch the model weights (the engine is useless without them).
weights: bool = True
class StemSideLoad(BaseModel):
path: str
kind: Literal["engine", "weights"]
class StemConvert(BaseModel):
track_ids: list[str]
# "replace": the stem file supersedes the original where it lives (the
# original is parked until Save deletes it); "destination": a chosen folder,
# originals never touched.
mode: Literal["replace", "destination"]
destination: str | None = None
# "repoint": the entry now names the stem file; "add": a new entry beside it
# (destination mode only).
collection: Literal["repoint", "add"] = "repoint"
playlist_id: str | None = None # add mode: into this existing playlist…
new_playlist: str | None = None # …or a new one with this name
class EditState(BaseModel):
dirty: bool # unsaved in-memory changes exist
library: LibraryInfo
# Converted tracks awaiting Save/Discard: {tracks, parked, bytes}.
pending_stems: dict | None = None
# A running stem conversion's job id, so a reloaded page finds it again.
stem_job: str | None = None
# What this open's crash recovery did about an interrupted conversion.
stem_recovery: dict | None = None
# A remote library's connection: {state, via, machine}. None when local.
remote: dict | None = None
# ---- collection selection ----
class CollectionStatus(BaseModel):
loaded: bool
path: str | None = None
tracks: int | None = None
playlists: int | None = None
# Identity of the loaded library, so the UI can name it without parsing the
# path (a Serato library is a directory, not a file).
library: LibraryInfo | None = None
# Opening a remote library: the unsaved edits another computer left there,
# {machine, summary} — the user chooses to save or discard them.
pending_edits: dict | None = None
class OpenCollection(BaseModel):
path: str
class RemoteIn(BaseModel):
"""A remote's settings as the picker's form sends them. `password` may be
omitted on an edit, which keeps the saved one."""
name: str
host: str
port: int | None = None
fallback_host: str | None = None
fallback_port: int | None = None
username: str
password: str | None = None
class OpenRemote(BaseModel):
remote_id: str
# Take the session from the computer holding it (the user confirmed).
takeover: bool = False
class CollectionCandidate(BaseModel):
path: str
label: str # folder name, e.g. "Traktor 4.5.0"
version: str | None = None # "4.5.0"
modified: float | None = None # collection.nml mtime, epoch seconds
exists: bool = True
class CollectionOptions(BaseModel):
auto: CollectionCandidate | None = None # best auto-detected (latest version)
# EVERY library detected, best first. `auto` is simply the first of these.
# Carried in full because one platform can genuinely have several at once —
# two Traktor versions installed, or two sticks plugged in — and silently
# anointing one of them is how the old single-candidate route could open a
# USB drive as the user's collection.
detected: list[CollectionCandidate] = []
recent: CollectionCandidate | None = None # last opened (from userprefs)
# ---- export sets -------------------------------------------------------------
#
# Konduktor's own data, never written into the user's library, and keyed by the
# library's stable ID rather than its path. See `exports.py`.
class ExportSetOut(BaseModel):
id: str
name: str
targets: list[str] # platform ids of the export TARGETS, never empty
destination: str
playlist_ids: list[str] = []
track_ids: list[str] = [] # loose tracks only
created: float = 0.0
modified: float = 0.0
class CreateExportSet(BaseModel):
name: str
targets: list[str] = ["traktor"]
destination: str
class UpdateExportSet(BaseModel):
name: str | None = None
targets: list[str] | None = None
destination: str | None = None
class ExportSetMembers(BaseModel):
track_ids: list[str] = []
playlist_ids: list[str] = []
class ExportPlaylistOut(BaseModel):
id: str
name: str
#: The playlist has been deleted since it was added to the set.
missing: bool = False
count: int = 0
class ExportContents(BaseModel):
"""What a set holds RIGHT NOW. Never cached — the references are live."""
playlists: list[ExportPlaylistOut] = []
loose: int = 0
#: Deduped across playlists and loose tracks: one track, one file copy.
tracks: int = 0
#: Track ids the library no longer has, surfaced rather than dropped.
dangling: list[str] = []
#: Another set already writes to this destination, and an export CLEARS it.
destination_conflict: str | None = None
class ExportPreview(BaseModel):
"""What an export would do if run now. Computed fresh; never stored."""
tracks: int = 0
exportable: int = 0
missing: list[str] = []
playlists: list[str] = []
total_bytes: int = 0
destination: str | None = None
free_bytes: int | None = None
enough_space: bool | None = None
#: A FACT, not a sentence — the UI words it. One of `destination_not_empty`,
#: `nothing_to_export`, `unsupported_target`, or null when it can run.
blocked: str | None = None
#: The destination already holds a Konduktor export, which will be replaced.
replacing: bool = False
#: Targets whose library is only found at a drive's root, when the
#: destination is not one. A warning — the export can still run.
not_drive_root: list[str] = []
class FsPlace(BaseModel):
"""A shortcut in the file browser's sidebar.
`kind` groups it and picks its icon; it is never a finished sentence, and
the browser decides what "volume" looks like. A place is always a DIRECTORY
that exists right now — one that does not is omitted rather than disabled.
"""
kind: str # home | music | desktop | documents | downloads | volume | library
name: str
path: str
class FsEntry(BaseModel):
name: str
path: str
class FsListing(BaseModel):
path: str
parent: str | None # None when at filesystem root
home: str
dirs: list[FsEntry]
files: list[FsEntry] # .nml files only
# ---- path remapping ----
# `from` is a Python keyword, so the field is `from_` with a `from` alias
# (populate_by_name lets it be set either way; responses serialize as "from").
class PathMappingInfo(BaseModel):
"""A per-collection OS-path prefix remapping (blank prefixes = no mapping)."""
model_config = ConfigDict(populate_by_name=True)
from_: str = Field(default="", alias="from")
to: str = ""
class RelocationApply(BaseModel):
"""The user's answer to the open-time missing-files check. Empty = "Not now".
Each mapping must be one the check proposed: this route applies an answer,
it is not a second way to set an arbitrary mapping.
"""
mappings: list[PathMappingInfo] = []
class RemapResult(BaseModel):
rewritten: int # tracks whose LOCATION was rewritten
commit: str | None = None # sha of the version-history commit for the rewrite
# The generic model lives in core.model; re-exported here so the HTTP layer has
# one import site. The dependency runs schemas -> core, never the reverse.
from .core.model import ( # noqa: E402,F401
AutoHotcue,
LibraryInfo,
PlatformOption,
CuePoint,
Facets,
GenreCount,
GridMarker,
HotcueChip,
PlaylistNode,
PrefixGroup,
PrefixSuggestions,
Relocation,
RelocationApplied,
RelocationCandidate,
RelocationVolume,
RemapPreview,
RemapSample,
Stats,
Track,
TrackCues,
TrackPage,
)
class AutoHotcuesResult(BaseModel):
"""The refreshed cues, plus what happened to every requested slot."""
cues: TrackCues
outcomes: list[AutoCueOutcome]
# ---- import sources ---------------------------------------------------
#
# A SOURCE is a library being read FROM — a plugged-in OneLibrary stick whose
# tracks are about to be imported. It is deliberately not a `CollectionStatus`:
# a source is never saved, never edited and never the fallback when nothing is
# loaded, so reusing the loaded-library shape would invite routes to treat the
# two as interchangeable.
class SourceCandidate(BaseModel):
"""A removable library Konduktor can currently see."""
path: str
label: str # what a person recognises, e.g. "OneLibrary — Hardy"
platform: str
tracks: int | None = None # None until it is opened; a probe would be slow
modified: float | None = None
class SourceStatus(BaseModel):
loaded: bool
path: str | None = None
label: str | None = None
platform: str | None = None
tracks: int | None = None
playlists: int | None = None
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
# Device tracks dropped on a collection playlist / an export (drag and
# drop): every imported track — and every one the collection already
# holds — goes into it, as folder add does.
into_playlist: str | None = None
export_id: str | None = None
class Drive(BaseModel):
"""A drive in the sidebar, under Devices (`external`) or Local Storage.
`library` is the OneLibrary database on it, when there is one — the same
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.
"""
name: str
path: str
kind: Literal["local", "external"]
library: SourceCandidate | None = None
class FolderTracks(BaseModel):
"""The audio files directly inside one folder, projected as tracks."""
path: str
tracks: list[Track]
# Ids (= absolute paths) of the files the collection already points at.
in_collection: list[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
class FolderAddRequest(BaseModel):
"""Add browsed files to the collection, and optionally to a playlist/export.
`mode` is asked every time rather than defaulted, because the right answer
depends on the drive and on how the DJ keeps their music.
"""
track_ids: list[str]
mode: Literal["copy", "reference"]
destination: str | None = None # required for `copy`
playlist_id: str | None = None
export_id: str | None = None
class JobStatus(BaseModel):
id: str
kind: str
state: str # running | done | failed | cancelled
total: int
done: int
# What done/total count ("bytes" / "tracks"; "" when unspecified). Declared
# here or the response model silently drops the one field the status bar
# needs to tell a byte count from a track count.
unit: str = ""
message: str
# The current item's own progress (0..1) and what it is doing — see jobs.Job.
fraction: float = 0.0
status: str = ""
result: dict | None = None
error: str | None = None
started_at: float
finished_at: float | None = None