codetta 0.8.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- codetta/CHANGELOG.md +153 -0
- codetta/__init__.py +8 -0
- codetta/__main__.py +5 -0
- codetta/cli/__init__.py +0 -0
- codetta/cli/__main__.py +59 -0
- codetta/cli/run.py +129 -0
- codetta/core/__init__.py +0 -0
- codetta/core/acoustid.py +225 -0
- codetta/core/activity.py +161 -0
- codetta/core/artwork.py +238 -0
- codetta/core/auth.py +362 -0
- codetta/core/avatar.py +92 -0
- codetta/core/changelog.py +51 -0
- codetta/core/connections.py +159 -0
- codetta/core/describe.py +69 -0
- codetta/core/engine.py +470 -0
- codetta/core/health.py +520 -0
- codetta/core/inbox.py +195 -0
- codetta/core/index.py +672 -0
- codetta/core/library.py +177 -0
- codetta/core/musicbrainz.py +662 -0
- codetta/core/notifications.py +77 -0
- codetta/core/onboarding.py +39 -0
- codetta/core/organize.py +490 -0
- codetta/core/plugins.py +183 -0
- codetta/core/presets.py +452 -0
- codetta/core/providers.py +203 -0
- codetta/core/rawtags.py +135 -0
- codetta/core/slskd.py +650 -0
- codetta/core/tagmap.py +538 -0
- codetta/core/undo.py +186 -0
- codetta/core/updates.py +132 -0
- codetta/plugins/__init__.py +63 -0
- codetta/plugins/builtin/__init__.py +3 -0
- codetta/plugins/builtin/tidy.py +70 -0
- codetta/web/__init__.py +0 -0
- codetta/web/app.py +2909 -0
- codetta/web/security.py +170 -0
- codetta/web/static/app.css +2684 -0
- codetta/web/static/app.js +5694 -0
- codetta/web/static/apple-touch-icon.png +0 -0
- codetta/web/static/fonts/LICENSE-Inter.txt +93 -0
- codetta/web/static/fonts/LICENSE-SchibstedGrotesk.txt +93 -0
- codetta/web/static/fonts/inter-cyrillic.woff2 +0 -0
- codetta/web/static/fonts/schibsted-grotesk.woff2 +0 -0
- codetta/web/static/icon.svg +1 -0
- codetta/web/static/icons/codetta-dark.png +0 -0
- codetta/web/static/icons/codetta-dark.svg +1 -0
- codetta/web/static/icons/codetta-dark.webp +0 -0
- codetta/web/static/icons/codetta-light.png +0 -0
- codetta/web/static/icons/codetta-light.svg +1 -0
- codetta/web/static/icons/codetta-light.webp +0 -0
- codetta/web/static/icons/codetta.png +0 -0
- codetta/web/static/icons/codetta.svg +1 -0
- codetta/web/static/icons/codetta.webp +0 -0
- codetta/web/static/index.html +473 -0
- codetta/web/static/theme.js +12 -0
- codetta-0.8.1.dist-info/METADATA +282 -0
- codetta-0.8.1.dist-info/RECORD +63 -0
- codetta-0.8.1.dist-info/WHEEL +5 -0
- codetta-0.8.1.dist-info/entry_points.txt +2 -0
- codetta-0.8.1.dist-info/licenses/LICENSE +661 -0
- codetta-0.8.1.dist-info/top_level.txt +1 -0
codetta/web/app.py
ADDED
|
@@ -0,0 +1,2909 @@
|
|
|
1
|
+
"""Codetta's web app: a JSON API plus the single-page UI.
|
|
2
|
+
|
|
3
|
+
Run locally:
|
|
4
|
+
CODETTA_MUSIC_DIR=~/Music uvicorn codetta.web.app:app --reload --port 8111
|
|
5
|
+
|
|
6
|
+
Settings (environment variables):
|
|
7
|
+
CODETTA_MUSIC_DIR the music library to edit (default: /music)
|
|
8
|
+
CODETTA_CONFIG_DIR where presets, the activity log and the account are
|
|
9
|
+
stored (default: ./config)
|
|
10
|
+
CODETTA_USERNAME optional: set the account here instead of the setup screen
|
|
11
|
+
CODETTA_PASSWORD (both must be set; the password can't then be changed in the UI)
|
|
12
|
+
CODETTA_AUTH "off" disables sign-in entirely, e.g. behind a reverse proxy
|
|
13
|
+
that already handles it (default: on)
|
|
14
|
+
|
|
15
|
+
Codetta is fully offline unless you opt in. Online features ("connections")
|
|
16
|
+
are off until turned on in the app (first-run card or Account → Connections)
|
|
17
|
+
or here. Setting one of these locks its switch in the app:
|
|
18
|
+
CODETTA_OFFLINE "on" blocks every connection, whatever else is set
|
|
19
|
+
CODETTA_MUSICBRAINZ "on"/"off": Match on MusicBrainz + Cover Art Archive
|
|
20
|
+
CODETTA_MUSICBRAINZ_URL a self-hosted MusicBrainz mirror, e.g. http://mb:5000
|
|
21
|
+
(no rate limit; http is allowed for this one)
|
|
22
|
+
CODETTA_ACOUSTID "on"/"off": Identify by sound (AcoustID; needs MusicBrainz too)
|
|
23
|
+
CODETTA_ACOUSTID_KEY your own AcoustID application key instead of Codetta's
|
|
24
|
+
CODETTA_FPCALC path to Chromaprint's fpcalc (default: found on PATH)
|
|
25
|
+
CODETTA_INBOX_DIR a downloads folder outside the music folder (e.g. slskd's) for
|
|
26
|
+
the import inbox; /inbox in the Docker image (mount it there)
|
|
27
|
+
CODETTA_LYRICS_LOOKUP "on"/"off": Find lyrics (asks lrclib.net, only when pressed)
|
|
28
|
+
CODETTA_UPDATE_CHECK "on"/"off": twice-daily check for new releases on GitHub
|
|
29
|
+
CODETTA_UPDATE_REPO where to look for releases (default: gavndev/codetta)
|
|
30
|
+
|
|
31
|
+
CODETTA_ALLOW_PUBLIC_SETUP "on" lets the first-run setup screen be used from a
|
|
32
|
+
public (internet) address; by default only home networks,
|
|
33
|
+
Tailscale and this machine can create the account
|
|
34
|
+
CODETTA_ALLOWED_HOSTS optional comma-separated host names Codetta answers to
|
|
35
|
+
(e.g. "music-server,192.168.1.50"); blocks DNS rebinding
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
from __future__ import annotations
|
|
39
|
+
|
|
40
|
+
import logging
|
|
41
|
+
import os
|
|
42
|
+
import re
|
|
43
|
+
import threading
|
|
44
|
+
import time
|
|
45
|
+
from collections import OrderedDict
|
|
46
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
47
|
+
from contextlib import asynccontextmanager
|
|
48
|
+
from dataclasses import dataclass
|
|
49
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
50
|
+
from pathlib import Path
|
|
51
|
+
from typing import Literal
|
|
52
|
+
from urllib.parse import urlsplit
|
|
53
|
+
|
|
54
|
+
from fastapi import FastAPI, HTTPException, Query, Request
|
|
55
|
+
from fastapi.concurrency import run_in_threadpool
|
|
56
|
+
from fastapi.responses import FileResponse, JSONResponse, Response
|
|
57
|
+
from fastapi.staticfiles import StaticFiles
|
|
58
|
+
from pydantic import BaseModel, Field
|
|
59
|
+
|
|
60
|
+
from codetta.core.activity import ActivityLog
|
|
61
|
+
from codetta.core.artwork import sniff_image_type
|
|
62
|
+
from codetta.core.avatar import AvatarError, AvatarStore
|
|
63
|
+
from codetta.core.auth import (
|
|
64
|
+
SESSION_DAYS,
|
|
65
|
+
AccountStore,
|
|
66
|
+
AuthError,
|
|
67
|
+
BusyError,
|
|
68
|
+
LoginRateLimiter,
|
|
69
|
+
SessionStore,
|
|
70
|
+
needs_rehash,
|
|
71
|
+
)
|
|
72
|
+
from codetta.core.engine import MetadataEngine, MetadataError, TrackMetadata
|
|
73
|
+
from codetta.core.health import CATEGORIES as HEALTH_CATEGORIES
|
|
74
|
+
from codetta.core.health import CHECKS as HEALTH_CHECKS
|
|
75
|
+
from codetta.core.health import EDITION_RE, MB_RELEASE_KEYS, HealthStore, folder_has_image
|
|
76
|
+
from codetta.core.health import _base_artist as base_artist
|
|
77
|
+
from codetta.core.health import fold as health_fold
|
|
78
|
+
from codetta.core.health import run as health_run
|
|
79
|
+
from codetta.core.describe import describe_file, describe_many
|
|
80
|
+
from codetta.core.plugins import ActionError, PluginManager
|
|
81
|
+
from codetta.core.index import LibraryIndex, parse_query
|
|
82
|
+
from codetta.core import changelog
|
|
83
|
+
from codetta.core.notifications import Notifications
|
|
84
|
+
from codetta.core.onboarding import OnboardingStore
|
|
85
|
+
from codetta.core.inbox import (
|
|
86
|
+
DOWNLOADING,
|
|
87
|
+
ERROR as INBOX_ERROR,
|
|
88
|
+
FILED,
|
|
89
|
+
LOCAL,
|
|
90
|
+
MATCHING,
|
|
91
|
+
NO_MATCH,
|
|
92
|
+
READY,
|
|
93
|
+
REVIEW,
|
|
94
|
+
SKIPPED,
|
|
95
|
+
WAITING,
|
|
96
|
+
InboxStore,
|
|
97
|
+
)
|
|
98
|
+
from codetta.core.inbox import signature as inbox_signature
|
|
99
|
+
from codetta.core.library import INBOX as INBOX_ALIAS
|
|
100
|
+
from codetta.core.library import Library, LibraryPathError, TooManyFilesError, audio_files, count_contents
|
|
101
|
+
from codetta.core.organize import (
|
|
102
|
+
DEFAULT_PATTERN,
|
|
103
|
+
PRESETS as ORGANIZE_PRESETS,
|
|
104
|
+
Move,
|
|
105
|
+
PatternError,
|
|
106
|
+
Source,
|
|
107
|
+
apply_moves,
|
|
108
|
+
check_pattern,
|
|
109
|
+
remove_empty_dirs,
|
|
110
|
+
load_pattern,
|
|
111
|
+
plan_moves,
|
|
112
|
+
prune_replaced,
|
|
113
|
+
render,
|
|
114
|
+
safe_name,
|
|
115
|
+
save_pattern,
|
|
116
|
+
)
|
|
117
|
+
from codetta.core.acoustid import DEFAULT_KEY as ACOUSTID_KEY
|
|
118
|
+
from codetta.core.acoustid import LOOKUP_URL as ACOUSTID_URL
|
|
119
|
+
from codetta.core.acoustid import AcoustID, Fingerprinter, FingerprintError, find_fpcalc, rank_releases
|
|
120
|
+
from codetta.core.artwork import MAX_ART_BYTES
|
|
121
|
+
from codetta.core.connections import BY_ID as CONNECTION_BY_ID
|
|
122
|
+
from codetta.core.connections import ConnectionStore, parse_switch
|
|
123
|
+
from codetta.core.musicbrainz import (
|
|
124
|
+
ALL_FIELDS as MB_FIELDS,
|
|
125
|
+
FIELD_GROUPS as MB_FIELD_GROUPS,
|
|
126
|
+
ID_LABELS as MB_ID_LABELS,
|
|
127
|
+
MAX_MB_BYTES,
|
|
128
|
+
MB_BASE,
|
|
129
|
+
MBID_RE,
|
|
130
|
+
DEFAULT_OFF as MB_DEFAULT_OFF,
|
|
131
|
+
FileInfo,
|
|
132
|
+
MusicBrainz,
|
|
133
|
+
album_tags,
|
|
134
|
+
cover_url,
|
|
135
|
+
default_fields as mb_default_fields,
|
|
136
|
+
number,
|
|
137
|
+
pair_files,
|
|
138
|
+
parse_release_id,
|
|
139
|
+
release_tracks,
|
|
140
|
+
score_candidate,
|
|
141
|
+
summarize,
|
|
142
|
+
track_tags,
|
|
143
|
+
artist_links,
|
|
144
|
+
artist_summary,
|
|
145
|
+
group_summary,
|
|
146
|
+
pick_release,
|
|
147
|
+
tracklist,
|
|
148
|
+
)
|
|
149
|
+
from codetta.core.providers import LRCLib, ProviderError, TrackQuery, http_get, http_get_json, http_post_json
|
|
150
|
+
from codetta.core.rawtags import read_raw
|
|
151
|
+
from codetta.core.slskd import (
|
|
152
|
+
ARRIVED as SK_ARRIVED,
|
|
153
|
+
CANCELLED as SK_CANCELLED,
|
|
154
|
+
DOWNLOADING as SK_DOWNLOADING,
|
|
155
|
+
FAILED as SK_FAILED,
|
|
156
|
+
IMPORTED as SK_IMPORTED,
|
|
157
|
+
NOTHING as SK_NOTHING,
|
|
158
|
+
SlskdError,
|
|
159
|
+
Soulseek,
|
|
160
|
+
SoulseekStore,
|
|
161
|
+
basenames as sk_basenames,
|
|
162
|
+
check as slskd_check,
|
|
163
|
+
clean_url as slskd_clean_url,
|
|
164
|
+
folder_progress,
|
|
165
|
+
http_request as slskd_http_request,
|
|
166
|
+
)
|
|
167
|
+
from codetta.core.presets import (
|
|
168
|
+
PLACEHOLDERS,
|
|
169
|
+
FileResult,
|
|
170
|
+
Preset,
|
|
171
|
+
PresetError,
|
|
172
|
+
PresetNotFoundError,
|
|
173
|
+
PresetStore,
|
|
174
|
+
apply_preset,
|
|
175
|
+
apply_preset_to_folder,
|
|
176
|
+
slugify,
|
|
177
|
+
)
|
|
178
|
+
from codetta.core.tagmap import FIELDS, is_tag_supported
|
|
179
|
+
from codetta.core.undo import ArtStore, art_hashes, sha256, undo_change
|
|
180
|
+
from codetta.core.updates import DEFAULT_REPO, Fetcher, UpdateChecker, fetch_latest_release
|
|
181
|
+
from codetta.web.security import GuardMiddleware, SelectiveGZip
|
|
182
|
+
|
|
183
|
+
STATIC_DIR = Path(__file__).parent / "static"
|
|
184
|
+
SESSION_COOKIE = "codetta_session"
|
|
185
|
+
log = logging.getLogger("codetta")
|
|
186
|
+
if not log.handlers: # show Codetta's own messages (sign-ins etc.) next to uvicorn's
|
|
187
|
+
_handler = logging.StreamHandler()
|
|
188
|
+
_handler.setFormatter(logging.Formatter("%(levelname)s: codetta: %(message)s"))
|
|
189
|
+
log.addHandler(_handler)
|
|
190
|
+
log.setLevel(logging.INFO)
|
|
191
|
+
log.propagate = False
|
|
192
|
+
|
|
193
|
+
try:
|
|
194
|
+
VERSION = version("codetta")
|
|
195
|
+
except PackageNotFoundError: # running from a source checkout without install
|
|
196
|
+
VERSION = "dev"
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def env(name: str, default: str | None = None) -> str | None:
|
|
200
|
+
"""Read CODETTA_<name>, falling back to the old CODA_<name> (Codetta's earlier name)."""
|
|
201
|
+
return os.environ.get(f"CODETTA_{name}") or os.environ.get(f"CODA_{name}") or default
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
@dataclass
|
|
205
|
+
class Settings:
|
|
206
|
+
music_dir: Path
|
|
207
|
+
config_dir: Path
|
|
208
|
+
auth: bool = True
|
|
209
|
+
username: str | None = None # from CODETTA_USERNAME (with password: overrides setup)
|
|
210
|
+
password: str | None = None
|
|
211
|
+
# Connections: None = the user decides in the app (off until they opt in);
|
|
212
|
+
# True/False = set by the environment, and the app's switch is locked.
|
|
213
|
+
offline: bool = False # CODETTA_OFFLINE: blocks every connection
|
|
214
|
+
update_check: bool | None = None
|
|
215
|
+
lyrics_lookup: bool | None = None # "Find lyrics" (asks LRCLIB only when pressed)
|
|
216
|
+
musicbrainz: bool | None = None # "Match on MusicBrainz" + Cover Art Archive
|
|
217
|
+
musicbrainz_url: str | None = None # self-hosted mirror instead of musicbrainz.org
|
|
218
|
+
acoustid: bool | None = None # "Identify by sound" (fingerprints looked up on AcoustID)
|
|
219
|
+
acoustid_key: str | None = None # an own application key instead of Codetta's
|
|
220
|
+
fpcalc: str | None = None # Chromaprint's fpcalc; None = look on PATH
|
|
221
|
+
slskd: bool | None = None # Soulseek through the user's slskd
|
|
222
|
+
slskd_url: str | None = None # CODETTA_SLSKD_URL / _API_KEY: set (and lock) the connection details
|
|
223
|
+
slskd_api_key: str | None = None
|
|
224
|
+
inbox_dir: Path | None = None # a downloads folder outside the library (e.g. slskd's), used as "@inbox"
|
|
225
|
+
inbox_settle_seconds: float = 120 # wait this long after a file changes (downloads still arriving)
|
|
226
|
+
slskd_poll_seconds: float = 4 # how often a Soulseek request under way is checked on
|
|
227
|
+
index_workers: int = 0 # processes that help a big index scan (0: one fewer than the CPUs, up to 4)
|
|
228
|
+
update_repo: str = DEFAULT_REPO
|
|
229
|
+
allowed_hosts: tuple[str, ...] = () # empty = answer to any host name
|
|
230
|
+
allow_public_setup: bool = False # first-run setup only from private addresses
|
|
231
|
+
|
|
232
|
+
@classmethod
|
|
233
|
+
def from_env(cls) -> Settings:
|
|
234
|
+
return cls(
|
|
235
|
+
music_dir=Path(env("MUSIC_DIR", "/music")).expanduser(),
|
|
236
|
+
config_dir=Path(env("CONFIG_DIR", "config")).expanduser(),
|
|
237
|
+
auth=env("AUTH", "on").strip().lower() not in ("off", "false", "0", "no"),
|
|
238
|
+
username=env("USERNAME"),
|
|
239
|
+
password=env("PASSWORD"),
|
|
240
|
+
offline=parse_switch(env("OFFLINE")) is True,
|
|
241
|
+
update_check=parse_switch(env("UPDATE_CHECK")),
|
|
242
|
+
lyrics_lookup=parse_switch(env("LYRICS_LOOKUP")),
|
|
243
|
+
musicbrainz=parse_switch(env("MUSICBRAINZ")),
|
|
244
|
+
musicbrainz_url=(env("MUSICBRAINZ_URL") or "").strip() or None,
|
|
245
|
+
acoustid=parse_switch(env("ACOUSTID")),
|
|
246
|
+
acoustid_key=(env("ACOUSTID_KEY") or "").strip() or None,
|
|
247
|
+
fpcalc=(env("FPCALC") or "").strip() or None,
|
|
248
|
+
index_workers=int(env("INDEX_WORKERS") or 0) if (env("INDEX_WORKERS") or "0").isdigit() else 0,
|
|
249
|
+
slskd=parse_switch(env("SLSKD")),
|
|
250
|
+
slskd_url=(env("SLSKD_URL") or "").strip() or None,
|
|
251
|
+
slskd_api_key=(env("SLSKD_API_KEY") or "").strip() or None,
|
|
252
|
+
inbox_dir=Path(env("INBOX_DIR")).expanduser() if env("INBOX_DIR") else None,
|
|
253
|
+
update_repo=env("UPDATE_REPO", DEFAULT_REPO),
|
|
254
|
+
allowed_hosts=tuple(h.strip() for h in (env("ALLOWED_HOSTS") or "").split(",") if h.strip()),
|
|
255
|
+
allow_public_setup=(env("ALLOW_PUBLIC_SETUP") or "").strip().lower() in ("on", "true", "1", "yes"),
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
# --- API models -------------------------------------------------------------------
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
class Credentials(BaseModel):
|
|
263
|
+
username: str = Field(max_length=200)
|
|
264
|
+
password: str = Field(max_length=2000)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
class PasswordChange(BaseModel):
|
|
268
|
+
current_password: str = Field(max_length=2000)
|
|
269
|
+
new_password: str = Field(max_length=2000)
|
|
270
|
+
|
|
271
|
+
TagValueIn = str | list[str] | None
|
|
272
|
+
MAX_PATH_CHARS = 4096 # longer than any real path (Linux allows 4096 bytes)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
class ArtInfo(BaseModel):
|
|
276
|
+
hash: str # SHA-256 of the image: identical covers share one URL, so they load once
|
|
277
|
+
width: int | None = None
|
|
278
|
+
height: int | None = None
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
class TrackOut(BaseModel):
|
|
282
|
+
path: str
|
|
283
|
+
name: str
|
|
284
|
+
format: str | None = None
|
|
285
|
+
tags: dict[str, list[str]] = {}
|
|
286
|
+
duration: float | None = None
|
|
287
|
+
bitrate: int | None = None
|
|
288
|
+
sample_rate: int | None = None
|
|
289
|
+
channels: int | None = None
|
|
290
|
+
mtime: int | None = None # changes whenever the file does (used to refresh cover art)
|
|
291
|
+
art: ArtInfo | None = None # embedded cover, if any
|
|
292
|
+
error: str | None = None # set if the file couldn't be read
|
|
293
|
+
partial: bool = False # from the search index: long/technical tags left out (editor reloads)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
class Crumb(BaseModel):
|
|
297
|
+
name: str
|
|
298
|
+
path: str
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
class FolderOut(BaseModel):
|
|
302
|
+
name: str
|
|
303
|
+
path: str
|
|
304
|
+
folders: int | None = None # subfolders inside it (None if unreadable)
|
|
305
|
+
tracks: int | None = None # audio files directly inside it
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
class BrowseOut(BaseModel):
|
|
309
|
+
path: str
|
|
310
|
+
name: str
|
|
311
|
+
breadcrumbs: list[Crumb]
|
|
312
|
+
folders: list[FolderOut]
|
|
313
|
+
skipped: int = 0 # items whose names aren't valid UTF-8
|
|
314
|
+
tracks: list[TrackOut]
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
class ClauseOut(BaseModel):
|
|
318
|
+
key: str
|
|
319
|
+
label: str
|
|
320
|
+
values: list[str]
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
class SearchInfo(BaseModel):
|
|
324
|
+
query: str
|
|
325
|
+
words: list[str]
|
|
326
|
+
clauses: list[ClauseOut]
|
|
327
|
+
total: int # all matches; ``tracks`` holds the first ``limit``
|
|
328
|
+
indexing: bool # the first scan of the library is still running
|
|
329
|
+
indexed: int # files in the index so far
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
class SearchOut(BrowseOut):
|
|
333
|
+
search: SearchInfo
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
MAX_PATHS_PER_REQUEST = 1000 # the UI sends bigger jobs in batches
|
|
337
|
+
# Audio types for the in-browser player, by extension (only Codetta's audio files are served).
|
|
338
|
+
STREAM_TYPES = {
|
|
339
|
+
".flac": "audio/flac", ".mp3": "audio/mpeg", ".mp2": "audio/mpeg", ".m4a": "audio/mp4", ".m4b": "audio/mp4",
|
|
340
|
+
".ogg": "audio/ogg", ".oga": "audio/ogg", ".opus": "audio/ogg", ".spx": "audio/ogg", ".wav": "audio/wav",
|
|
341
|
+
".aif": "audio/aiff", ".aiff": "audio/aiff", ".aifc": "audio/aiff", ".wma": "audio/x-ms-wma",
|
|
342
|
+
".wv": "audio/x-wavpack", ".dsf": "audio/x-dsf", ".tta": "audio/x-tta",
|
|
343
|
+
}
|
|
344
|
+
MAX_IDENTIFY = 200
|
|
345
|
+
MAX_ORGANIZE = 5000 # files planned/moved in one request # files fingerprinted in one request (each takes a moment to decode)
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def _unique(paths: list[str]) -> list[str]:
|
|
349
|
+
"""Drop repeated paths (keeping order), so a file is never processed twice."""
|
|
350
|
+
return list(dict.fromkeys(paths))
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
class UpdateIn(BaseModel):
|
|
354
|
+
paths: list[str] = Field(min_length=1, max_length=MAX_PATHS_PER_REQUEST)
|
|
355
|
+
# Tag name -> new value(s). null, "" or [] removes the tag.
|
|
356
|
+
changes: dict[str, TagValueIn] = Field(max_length=200)
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
class UpdateResult(BaseModel):
|
|
360
|
+
path: str
|
|
361
|
+
ok: bool
|
|
362
|
+
error: str | None = None
|
|
363
|
+
track: TrackOut | None = None
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
class PresetOut(BaseModel):
|
|
367
|
+
name: str
|
|
368
|
+
slug: str
|
|
369
|
+
description: str
|
|
370
|
+
tags: dict[str, list[str]]
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
class PresetIn(BaseModel):
|
|
374
|
+
name: str = Field(min_length=1, max_length=100)
|
|
375
|
+
description: str = Field("", max_length=1000)
|
|
376
|
+
tags: dict[str, str | list[str]] = Field(default={}, max_length=200)
|
|
377
|
+
# When editing, the preset's name before the edit (handles renames).
|
|
378
|
+
previous_name: str | None = Field(default=None, max_length=100)
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
class ApplyIn(BaseModel):
|
|
382
|
+
name: str = Field(min_length=1, max_length=100)
|
|
383
|
+
paths: list[str] = Field(default=[], max_length=MAX_PATHS_PER_REQUEST) # apply to these files...
|
|
384
|
+
folder: str | None = Field(default=None, max_length=MAX_PATH_CHARS) # ...or to every audio file in this folder
|
|
385
|
+
recursive: bool = False
|
|
386
|
+
mode: Literal["fill", "overwrite"] = "fill"
|
|
387
|
+
dry_run: bool = True # preview by default; send false to actually write
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
class ApplyResultOut(BaseModel):
|
|
391
|
+
path: str
|
|
392
|
+
applied: dict[str, list[str]]
|
|
393
|
+
kept_existing: list[str]
|
|
394
|
+
unsupported: list[str]
|
|
395
|
+
error: str | None = None
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
class OrganizeIn(BaseModel):
|
|
399
|
+
paths: list[str] = Field(default=[], max_length=MAX_PATHS_PER_REQUEST) # these files...
|
|
400
|
+
folder: str | None = Field(default=None, max_length=MAX_PATH_CHARS) # ...or the audio files in this folder
|
|
401
|
+
recursive: bool = False # ...and its subfolders
|
|
402
|
+
pattern: str | None = Field(default=None, max_length=400) # None: the saved pattern
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
class InboxSettingsIn(BaseModel):
|
|
406
|
+
folder: str = Field(max_length=1000)
|
|
407
|
+
auto: bool = False
|
|
408
|
+
organize: bool = True
|
|
409
|
+
watch: bool = False
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
class NotificationsReadIn(BaseModel):
|
|
413
|
+
ids: list[int] | None = Field(default=None, max_length=500) # None: all
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
class InboxActionIn(BaseModel):
|
|
417
|
+
key: str = Field(max_length=2000)
|
|
418
|
+
release: str | None = Field(default=None, max_length=500) # file with this release instead of the found one
|
|
419
|
+
recordings: dict[str, list[str]] = Field(default={}, max_length=MAX_PATHS_PER_REQUEST)
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
class SlskdSettingsIn(BaseModel):
|
|
423
|
+
url: str = Field("", max_length=500)
|
|
424
|
+
api_key: str | None = Field(default=None, max_length=500) # None: keep the saved key
|
|
425
|
+
review: bool = True
|
|
426
|
+
lossless_only: bool = False
|
|
427
|
+
min_bitrate: int = Field(320, ge=0, le=3000)
|
|
428
|
+
search_seconds: int = Field(20, ge=5, le=120)
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
class SlskdSearchIn(BaseModel):
|
|
432
|
+
query: str = Field(min_length=2, max_length=300)
|
|
433
|
+
upgrade: str = Field("", max_length=2000) # a library folder this download should replace
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
class SlskdNextIn(BaseModel):
|
|
437
|
+
block: bool = True # blocklist the folder that came (else just try the next one)
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
class SlskdImportIn(BaseModel):
|
|
441
|
+
release: str | None = Field(default=None, max_length=500) # file with this release instead of the found one
|
|
442
|
+
recordings: dict[str, list[str]] = Field(default={}, max_length=MAX_PATHS_PER_REQUEST)
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
REPLACE_FIELDS = ("title", "artist", "album", "albumartist", "genre", "composer", "comment", "label", "grouping")
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
class ReplaceIn(BaseModel):
|
|
449
|
+
paths: list[str] = Field(default=[], max_length=MAX_PATHS_PER_REQUEST) # these files...
|
|
450
|
+
folder: str | None = Field(default=None, max_length=MAX_PATH_CHARS) # ...or the audio files in this folder
|
|
451
|
+
find: str = Field(min_length=1, max_length=200)
|
|
452
|
+
replace: str = Field("", max_length=500)
|
|
453
|
+
fields: list[str] | None = Field(default=None, max_length=40) # None: the usual text fields
|
|
454
|
+
regex: bool = False
|
|
455
|
+
match_case: bool = False
|
|
456
|
+
dry_run: bool = True
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
class ActionRunIn(BaseModel):
|
|
460
|
+
paths: list[str] = Field(default=[], max_length=MAX_PATHS_PER_REQUEST) # these files...
|
|
461
|
+
folder: str | None = Field(default=None, max_length=MAX_PATH_CHARS) # ...or the audio files in this folder
|
|
462
|
+
dry_run: bool = True
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
class PluginToggleIn(BaseModel):
|
|
466
|
+
enabled: bool
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
class FolderRenameIn(BaseModel):
|
|
470
|
+
path: str = Field(min_length=1, max_length=MAX_PATH_CHARS)
|
|
471
|
+
name: str = Field(min_length=1, max_length=255)
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
class HealthSettingsIn(BaseModel):
|
|
475
|
+
enabled: bool | None = None # the whole feature; None: leave as is
|
|
476
|
+
disabled: list[str] | None = Field(default=None, max_length=100) # check ids switched off; None: leave as is
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
class HealthIssueIn(BaseModel):
|
|
480
|
+
id: str = Field(pattern=r"^[0-9a-f]{12}$")
|
|
481
|
+
ignore: bool = True
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
class SlskdPickIn(BaseModel):
|
|
485
|
+
index: int = Field(ge=0, le=100)
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
class PatternIn(BaseModel):
|
|
489
|
+
pattern: str = Field(max_length=400)
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
class ConnectionsIn(BaseModel):
|
|
493
|
+
enabled: dict[str, bool] = Field(default={}, max_length=50) # connection id -> on/off
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
class MBTarget(BaseModel):
|
|
497
|
+
paths: list[str] = Field(default=[], max_length=MAX_PATHS_PER_REQUEST) # these files...
|
|
498
|
+
folder: str | None = Field(default=None, max_length=MAX_PATH_CHARS) # ...or the audio files directly in this folder (one album)
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
class MBSearchIn(MBTarget):
|
|
502
|
+
album: str = Field("", max_length=500)
|
|
503
|
+
artist: str = Field("", max_length=500)
|
|
504
|
+
release: str = Field("", max_length=500) # a release link or ID instead of a search
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
class MBProposalIn(MBTarget):
|
|
508
|
+
release: str = Field(max_length=500)
|
|
509
|
+
pairs: dict[str, str | None] = Field(default={}, max_length=MAX_PATHS_PER_REQUEST) # path -> track id (None: skip)
|
|
510
|
+
fields: list[str] | None = Field(default=None, max_length=200) # None: the default set
|
|
511
|
+
# From Identify by sound: recording IDs heard in each file (pairs files exactly).
|
|
512
|
+
recordings: dict[str, list[str]] = Field(default={}, max_length=MAX_PATHS_PER_REQUEST)
|
|
513
|
+
mode: Literal["overwrite", "fill"] = "overwrite" # fill: only tags that are empty now
|
|
514
|
+
cover: Literal["missing", "all", "none"] = "missing"
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
# --- App ----------------------------------------------------------------------------
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
def _migrate_presets_folder(config_dir: Path) -> None:
|
|
521
|
+
"""Tag Presets used to be called Tag Loadouts, kept in config/loadouts/. Move them over once."""
|
|
522
|
+
old, new = config_dir / "loadouts", config_dir / "presets"
|
|
523
|
+
try:
|
|
524
|
+
if old.is_dir() and not new.exists():
|
|
525
|
+
old.rename(new)
|
|
526
|
+
log.info("Moved your Tag Presets from %s to %s", old, new)
|
|
527
|
+
except OSError as exc: # read-only config folder: presets just start fresh
|
|
528
|
+
log.warning("Couldn't move %s to %s: %s", old, new, exc)
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
def create_app(settings: Settings | None = None, fetch_release: Fetcher = fetch_latest_release,
|
|
532
|
+
fetch_json=None, fetch_mb=None, fetch_art=None, post_acoustid=None, run_fpcalc=None,
|
|
533
|
+
slskd_request=None) -> FastAPI:
|
|
534
|
+
"""``fetch_*`` replace the network in tests: LRCLIB and MusicBrainz take
|
|
535
|
+
(url) -> parsed JSON or None, the Cover Art Archive (url) -> bytes or None,
|
|
536
|
+
AcoustID (form) -> parsed JSON; ``run_fpcalc`` replaces running fpcalc;
|
|
537
|
+
``slskd_request`` (method, url, headers, body) -> (status, body) stands in for slskd."""
|
|
538
|
+
settings = settings or Settings.from_env()
|
|
539
|
+
if settings.index_workers <= 0:
|
|
540
|
+
settings.index_workers = max(1, min(4, (os.cpu_count() or 2) - 1))
|
|
541
|
+
connections = ConnectionStore(
|
|
542
|
+
settings.config_dir / "connections.json", offline=settings.offline,
|
|
543
|
+
forced={"updates": settings.update_check, "lyrics": settings.lyrics_lookup, "musicbrainz": settings.musicbrainz,
|
|
544
|
+
"acoustid": settings.acoustid, "slskd": settings.slskd},
|
|
545
|
+
)
|
|
546
|
+
updates = UpdateChecker(VERSION, settings.update_repo, lambda: connections.enabled("updates"), fetch_release)
|
|
547
|
+
library = Library(settings.music_dir, settings.inbox_dir, settings.config_dir / "replaced")
|
|
548
|
+
_migrate_presets_folder(settings.config_dir)
|
|
549
|
+
store = PresetStore(settings.config_dir / "presets")
|
|
550
|
+
engine = MetadataEngine()
|
|
551
|
+
activity = ActivityLog(settings.config_dir / "activity.jsonl")
|
|
552
|
+
art_store = ArtStore(settings.config_dir / "undo-art")
|
|
553
|
+
avatars = AvatarStore(settings.config_dir / "avatars")
|
|
554
|
+
accounts = AccountStore(settings.config_dir / "auth.json", settings.username, settings.password)
|
|
555
|
+
sessions = SessionStore(settings.config_dir / "sessions.json")
|
|
556
|
+
limiter = LoginRateLimiter()
|
|
557
|
+
user_agent = f"Codetta/{VERSION} (https://github.com/gavndev/codetta)"
|
|
558
|
+
notices = Notifications(settings.config_dir / "notifications.json")
|
|
559
|
+
lrclib = LRCLib(fetch_json or (lambda url: http_get_json(url, user_agent)))
|
|
560
|
+
mb_mirror = settings.musicbrainz_url.rstrip("/") if settings.musicbrainz_url else None
|
|
561
|
+
if mb_mirror and not mb_mirror.endswith("/ws/2"):
|
|
562
|
+
mb_mirror += "/ws/2"
|
|
563
|
+
mb = MusicBrainz(
|
|
564
|
+
fetch_mb or (lambda url: http_get_json(url, user_agent, max_bytes=MAX_MB_BYTES, service="MusicBrainz",
|
|
565
|
+
allow_http=mb_mirror is not None)),
|
|
566
|
+
base=mb_mirror or MB_BASE,
|
|
567
|
+
min_interval=0 if mb_mirror else 1.0, # musicbrainz.org allows one request a second
|
|
568
|
+
)
|
|
569
|
+
fpcalc_path = find_fpcalc(settings.fpcalc) or ("fpcalc" if run_fpcalc else None)
|
|
570
|
+
fingerprinter = Fingerprinter(fpcalc_path, **({"run": run_fpcalc} if run_fpcalc else {}))
|
|
571
|
+
acoustid = AcoustID(post_acoustid or (lambda form: http_post_json(ACOUSTID_URL, user_agent, form, service="AcoustID")),
|
|
572
|
+
key=settings.acoustid_key or ACOUSTID_KEY)
|
|
573
|
+
download_art = fetch_art or (lambda url: http_get(url, user_agent, accept="image/*", max_bytes=MAX_ART_BYTES,
|
|
574
|
+
service="the Cover Art Archive"))
|
|
575
|
+
|
|
576
|
+
lib_index = LibraryIndex(settings.music_dir, settings.config_dir / "library-index.sqlite3", describe_file,
|
|
577
|
+
parallel=describe_many, workers=settings.index_workers)
|
|
578
|
+
if not settings.auth:
|
|
579
|
+
log.warning("Sign-in is turned OFF (CODETTA_AUTH=off). Anyone who can reach Codetta can edit your music.")
|
|
580
|
+
|
|
581
|
+
@asynccontextmanager
|
|
582
|
+
async def lifespan(app: FastAPI):
|
|
583
|
+
# On startup (not on import), add the starter presets if missing.
|
|
584
|
+
try:
|
|
585
|
+
store.install_defaults()
|
|
586
|
+
except OSError:
|
|
587
|
+
pass # read-only config folder: presets just won't be saved
|
|
588
|
+
# Drop saved album art that no remembered change refers to any more.
|
|
589
|
+
try:
|
|
590
|
+
art_store.prune(h for rec in activity.undo_records() for h in art_hashes(rec))
|
|
591
|
+
except OSError:
|
|
592
|
+
pass
|
|
593
|
+
lib_index.start() # builds/refreshes the search index in the background
|
|
594
|
+
prune_replaced(settings.config_dir / "replaced") # upgrades' old albums, after 30 days
|
|
595
|
+
watcher = threading.Thread(target=app.state.inbox_watch, name="codetta-inbox-watch", daemon=True)
|
|
596
|
+
watcher.start() # sleeps; only looks at the inbox if "check every 15 minutes" is on
|
|
597
|
+
app.state.soulseek_start() # carries on with downloads that were under way
|
|
598
|
+
yield
|
|
599
|
+
inbox_wake.set()
|
|
600
|
+
app.state.soulseek_stop()
|
|
601
|
+
try:
|
|
602
|
+
soulseek_store.save() # the latest download progress (written to disk only now and then)
|
|
603
|
+
except OSError:
|
|
604
|
+
pass
|
|
605
|
+
lib_index.stop()
|
|
606
|
+
|
|
607
|
+
app = FastAPI(
|
|
608
|
+
title="Codetta", version=VERSION, docs_url="/docs", redoc_url=None, lifespan=lifespan
|
|
609
|
+
)
|
|
610
|
+
app.state.index = lib_index
|
|
611
|
+
|
|
612
|
+
# Map Codetta's errors to HTTP status codes, with a readable message.
|
|
613
|
+
def _error(status: int):
|
|
614
|
+
async def handler(request: Request, exc: Exception) -> JSONResponse:
|
|
615
|
+
return JSONResponse(status_code=status, content={"detail": str(exc)})
|
|
616
|
+
|
|
617
|
+
return handler
|
|
618
|
+
|
|
619
|
+
app.add_exception_handler(LibraryPathError, _error(400))
|
|
620
|
+
app.add_exception_handler(FileNotFoundError, _error(404))
|
|
621
|
+
app.add_exception_handler(MetadataError, _error(422))
|
|
622
|
+
app.add_exception_handler(PresetNotFoundError, _error(404))
|
|
623
|
+
app.add_exception_handler(PresetError, _error(422))
|
|
624
|
+
|
|
625
|
+
# --- Sign-in --------------------------------------------------------------------------
|
|
626
|
+
|
|
627
|
+
# Everything needs a signed-in session except the page shell, its static
|
|
628
|
+
# files, the sign-in endpoints themselves, and the health check.
|
|
629
|
+
PUBLIC_PATHS = {"/", "/api/health", "/api/changelog"} # the changelog is the public CHANGELOG.md
|
|
630
|
+
PUBLIC_PREFIXES = ("/static/", "/api/auth/")
|
|
631
|
+
|
|
632
|
+
@app.middleware("http")
|
|
633
|
+
async def require_sign_in(request: Request, call_next):
|
|
634
|
+
path = request.url.path
|
|
635
|
+
if settings.auth and not (path in PUBLIC_PATHS or path.startswith(PUBLIC_PREFIXES)):
|
|
636
|
+
if sessions.lookup(request.cookies.get(SESSION_COOKIE)) is None:
|
|
637
|
+
return JSONResponse(status_code=401, content={"detail": "Sign in required"})
|
|
638
|
+
return await call_next(request)
|
|
639
|
+
|
|
640
|
+
def client_key(request: Request) -> str:
|
|
641
|
+
return request.client.host if request.client else "unknown"
|
|
642
|
+
|
|
643
|
+
def start_session(request: Request, response: Response, username: str) -> None:
|
|
644
|
+
token = sessions.create(username)
|
|
645
|
+
response.set_cookie(
|
|
646
|
+
SESSION_COOKIE, token,
|
|
647
|
+
max_age=SESSION_DAYS * 86400,
|
|
648
|
+
httponly=True, # not readable by JavaScript
|
|
649
|
+
samesite="lax", # not sent with other sites' form posts
|
|
650
|
+
secure=request.url.scheme == "https" or request.headers.get("x-forwarded-proto") == "https",
|
|
651
|
+
path="/",
|
|
652
|
+
)
|
|
653
|
+
|
|
654
|
+
def check_rate_limit(request: Request) -> None:
|
|
655
|
+
wait = limiter.retry_after(client_key(request))
|
|
656
|
+
if wait:
|
|
657
|
+
raise HTTPException(
|
|
658
|
+
429, f"Too many attempts. Try again in {wait} seconds.", headers={"Retry-After": str(wait)}
|
|
659
|
+
)
|
|
660
|
+
|
|
661
|
+
@app.get("/api/changelog")
|
|
662
|
+
def get_changelog() -> dict:
|
|
663
|
+
"""What's new in each version (also shown on the sign-in screen)."""
|
|
664
|
+
return {"current": VERSION, "versions": changelog.load()}
|
|
665
|
+
|
|
666
|
+
@app.get("/api/health", include_in_schema=False)
|
|
667
|
+
def health() -> dict:
|
|
668
|
+
return {"ok": True}
|
|
669
|
+
|
|
670
|
+
@app.get("/api/auth/status")
|
|
671
|
+
def auth_status(request: Request) -> dict:
|
|
672
|
+
user = sessions.lookup(request.cookies.get(SESSION_COOKIE)) if settings.auth else None
|
|
673
|
+
return {
|
|
674
|
+
"version": VERSION,
|
|
675
|
+
"auth_enabled": settings.auth,
|
|
676
|
+
"setup_required": settings.auth and accounts.setup_required,
|
|
677
|
+
"signed_in": (not settings.auth) or user is not None,
|
|
678
|
+
"username": user,
|
|
679
|
+
"managed_by_env": accounts.managed_by_env,
|
|
680
|
+
# Changes when the profile picture does; None if there isn't one.
|
|
681
|
+
"avatar": avatars.version(user) if user else None,
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
@app.post("/api/auth/setup")
|
|
685
|
+
def auth_setup(body: Credentials, request: Request, response: Response) -> dict:
|
|
686
|
+
"""First run only: create the account and sign in."""
|
|
687
|
+
if not settings.auth:
|
|
688
|
+
raise HTTPException(400, "Sign-in is turned off")
|
|
689
|
+
if not accounts.setup_required:
|
|
690
|
+
raise HTTPException(409, "Codetta is already set up. Sign in instead.")
|
|
691
|
+
if not settings.allow_public_setup and _is_public_address(client_key(request)):
|
|
692
|
+
# Someone on the internet must never be able to claim a fresh install.
|
|
693
|
+
log.warning("Refused first-run setup from public address %s", client_key(request))
|
|
694
|
+
raise HTTPException(403, "For safety, set up Codetta from your home network or Tailscale "
|
|
695
|
+
"(or set CODETTA_ALLOW_PUBLIC_SETUP=on).")
|
|
696
|
+
try:
|
|
697
|
+
account = accounts.create(body.username, body.password)
|
|
698
|
+
except BusyError as exc:
|
|
699
|
+
raise HTTPException(503, str(exc), headers={"Retry-After": "5"}) from exc
|
|
700
|
+
except AuthError as exc:
|
|
701
|
+
raise HTTPException(422, str(exc)) from exc
|
|
702
|
+
except OSError as exc:
|
|
703
|
+
raise HTTPException(500, f"Could not save the account to the config folder: {exc}") from exc
|
|
704
|
+
log.info("Account %r created", account.username)
|
|
705
|
+
start_session(request, response, account.username)
|
|
706
|
+
return {"username": account.username}
|
|
707
|
+
|
|
708
|
+
@app.post("/api/auth/login")
|
|
709
|
+
def auth_login(body: Credentials, request: Request, response: Response) -> dict:
|
|
710
|
+
if not settings.auth:
|
|
711
|
+
return {"username": None}
|
|
712
|
+
check_rate_limit(request)
|
|
713
|
+
try:
|
|
714
|
+
account = accounts.check(body.username, body.password)
|
|
715
|
+
except BusyError as exc:
|
|
716
|
+
raise HTTPException(503, str(exc), headers={"Retry-After": "5"}) from exc
|
|
717
|
+
if account is None:
|
|
718
|
+
limiter.failed(client_key(request))
|
|
719
|
+
log.warning("Failed sign-in for %r from %s", body.username, client_key(request))
|
|
720
|
+
raise HTTPException(401, "Wrong username or password")
|
|
721
|
+
limiter.succeeded(client_key(request))
|
|
722
|
+
if needs_rehash(account.password_hash) and not accounts.managed_by_env:
|
|
723
|
+
try: # upgrade older, weaker password hashes now that we have the password
|
|
724
|
+
accounts.set_password(account.username, body.password)
|
|
725
|
+
except (AuthError, OSError):
|
|
726
|
+
pass
|
|
727
|
+
start_session(request, response, account.username)
|
|
728
|
+
return {"username": account.username}
|
|
729
|
+
|
|
730
|
+
@app.post("/api/auth/logout")
|
|
731
|
+
def auth_logout(request: Request, response: Response) -> dict:
|
|
732
|
+
sessions.revoke(request.cookies.get(SESSION_COOKIE))
|
|
733
|
+
response.delete_cookie(SESSION_COOKIE, path="/")
|
|
734
|
+
return {"ok": True}
|
|
735
|
+
|
|
736
|
+
@app.post("/api/auth/password")
|
|
737
|
+
def auth_change_password(body: PasswordChange, request: Request) -> dict:
|
|
738
|
+
"""Change the password; every other signed-in device is signed out."""
|
|
739
|
+
token = request.cookies.get(SESSION_COOKIE)
|
|
740
|
+
user = sessions.lookup(token)
|
|
741
|
+
if not settings.auth or user is None:
|
|
742
|
+
raise HTTPException(401, "Sign in required")
|
|
743
|
+
check_rate_limit(request)
|
|
744
|
+
try:
|
|
745
|
+
current_ok = accounts.check(user, body.current_password) is not None
|
|
746
|
+
except BusyError as exc:
|
|
747
|
+
raise HTTPException(503, str(exc), headers={"Retry-After": "5"}) from exc
|
|
748
|
+
if not current_ok:
|
|
749
|
+
limiter.failed(client_key(request))
|
|
750
|
+
raise HTTPException(401, "Your current password is wrong")
|
|
751
|
+
try:
|
|
752
|
+
accounts.set_password(user, body.new_password)
|
|
753
|
+
except BusyError as exc:
|
|
754
|
+
raise HTTPException(503, str(exc), headers={"Retry-After": "5"}) from exc
|
|
755
|
+
except AuthError as exc:
|
|
756
|
+
raise HTTPException(422, str(exc)) from exc
|
|
757
|
+
sessions.revoke_all(keep=token)
|
|
758
|
+
log.info("Password changed for %r", user)
|
|
759
|
+
return {"ok": True}
|
|
760
|
+
|
|
761
|
+
# --- Profile picture ------------------------------------------------------------------
|
|
762
|
+
|
|
763
|
+
def current_user(request: Request) -> str:
|
|
764
|
+
user = sessions.lookup(request.cookies.get(SESSION_COOKIE)) if settings.auth else "codetta"
|
|
765
|
+
if user is None:
|
|
766
|
+
raise HTTPException(401, "Sign in required")
|
|
767
|
+
return user
|
|
768
|
+
|
|
769
|
+
@app.get("/api/account/avatar", responses={200: {"content": {"image/webp": {}, "image/jpeg": {}, "image/png": {}}}})
|
|
770
|
+
def get_avatar(request: Request):
|
|
771
|
+
found = avatars.get(current_user(request))
|
|
772
|
+
if found is None:
|
|
773
|
+
raise HTTPException(404, "No profile picture")
|
|
774
|
+
data, mime = found
|
|
775
|
+
# The UI adds ?v=<version> to the URL, so a new picture gets a new URL.
|
|
776
|
+
return Response(data, media_type=mime, headers={"Cache-Control": "private, max-age=31536000, immutable"})
|
|
777
|
+
|
|
778
|
+
@app.put("/api/account/avatar")
|
|
779
|
+
async def set_avatar(request: Request) -> dict:
|
|
780
|
+
"""Body: a square JPEG, PNG or WebP image (the browser crops and resizes it)."""
|
|
781
|
+
user = current_user(request)
|
|
782
|
+
data = await request.body() # size already capped by GuardMiddleware
|
|
783
|
+
try:
|
|
784
|
+
await run_in_threadpool(avatars.save, user, data)
|
|
785
|
+
except AvatarError as exc:
|
|
786
|
+
raise HTTPException(422, str(exc)) from exc
|
|
787
|
+
except OSError as exc:
|
|
788
|
+
raise HTTPException(500, f"Could not save the picture: {exc}") from exc
|
|
789
|
+
return {"avatar": avatars.version(user)}
|
|
790
|
+
|
|
791
|
+
@app.delete("/api/account/avatar")
|
|
792
|
+
def delete_avatar(request: Request) -> dict:
|
|
793
|
+
avatars.delete(current_user(request))
|
|
794
|
+
return {"avatar": None}
|
|
795
|
+
|
|
796
|
+
def require_library() -> None:
|
|
797
|
+
if not library.exists():
|
|
798
|
+
raise HTTPException(
|
|
799
|
+
503,
|
|
800
|
+
f"Music folder not found: {library.root}. "
|
|
801
|
+
"Set CODETTA_MUSIC_DIR (or mount your music at /music in Docker).",
|
|
802
|
+
)
|
|
803
|
+
|
|
804
|
+
# Embedded-art fingerprints, remembered per (file, version) so re-opening a
|
|
805
|
+
# folder doesn't re-read every cover.
|
|
806
|
+
# Small tuples (hash, width, height), not models: this can hold thousands of entries.
|
|
807
|
+
art_cache: dict[tuple[str, int], tuple[str, int | None, int | None] | None] = {}
|
|
808
|
+
|
|
809
|
+
def art_info(rel: str, target: Path, mtime: int | None) -> ArtInfo | None:
|
|
810
|
+
key = (rel, mtime or 0)
|
|
811
|
+
if mtime is not None and key in art_cache:
|
|
812
|
+
hit = art_cache[key]
|
|
813
|
+
return ArtInfo(hash=hit[0], width=hit[1], height=hit[2]) if hit else None
|
|
814
|
+
try:
|
|
815
|
+
art = engine.read_artwork(target)
|
|
816
|
+
except (MetadataError, OSError):
|
|
817
|
+
art = None
|
|
818
|
+
info = (sha256(art.data)[:16], art.width, art.height) if art else None
|
|
819
|
+
if mtime is not None:
|
|
820
|
+
if len(art_cache) > 10000:
|
|
821
|
+
art_cache.clear()
|
|
822
|
+
art_cache[key] = info
|
|
823
|
+
return ArtInfo(hash=info[0], width=info[1], height=info[2]) if info else None
|
|
824
|
+
|
|
825
|
+
def to_out(rel: str, meta: TrackMetadata) -> TrackOut:
|
|
826
|
+
target = library.resolve(rel)
|
|
827
|
+
try:
|
|
828
|
+
mtime = target.stat().st_mtime_ns
|
|
829
|
+
except OSError:
|
|
830
|
+
mtime = None
|
|
831
|
+
out = _to_track_out(rel, meta, mtime)
|
|
832
|
+
out.art = art_info(rel, target, mtime)
|
|
833
|
+
return out
|
|
834
|
+
|
|
835
|
+
def folder_out(rel: str) -> FolderOut:
|
|
836
|
+
counts = count_contents(library.resolve(rel))
|
|
837
|
+
return FolderOut(
|
|
838
|
+
name=rel.rsplit("/", 1)[-1], path=rel,
|
|
839
|
+
folders=counts[0] if counts else None, tracks=counts[1] if counts else None,
|
|
840
|
+
)
|
|
841
|
+
|
|
842
|
+
# Tags of files that haven't changed since they were last read (same modification
|
|
843
|
+
# time, size and inode; every save through the engine replaces the file, so all
|
|
844
|
+
# three change). Opening a folder again then skips reading every file.
|
|
845
|
+
track_memory: OrderedDict[str, tuple[tuple[int, int, int], TrackOut]] = OrderedDict()
|
|
846
|
+
TRACK_MEMORY = 3000
|
|
847
|
+
track_memory_lock = threading.Lock() # requests run in a thread pool
|
|
848
|
+
|
|
849
|
+
def track_out(rel: str) -> TrackOut:
|
|
850
|
+
name = rel.rsplit("/", 1)[-1]
|
|
851
|
+
try:
|
|
852
|
+
target = library.resolve(rel)
|
|
853
|
+
st = target.stat()
|
|
854
|
+
stamp = (st.st_mtime_ns, st.st_size, st.st_ino)
|
|
855
|
+
with track_memory_lock:
|
|
856
|
+
hit = track_memory.get(rel)
|
|
857
|
+
if hit is not None and hit[0] == stamp:
|
|
858
|
+
track_memory.move_to_end(rel)
|
|
859
|
+
return hit[1]
|
|
860
|
+
out = to_out(rel, engine.load_metadata(target))
|
|
861
|
+
with track_memory_lock:
|
|
862
|
+
track_memory[rel] = (stamp, out)
|
|
863
|
+
while len(track_memory) > TRACK_MEMORY:
|
|
864
|
+
track_memory.popitem(last=False)
|
|
865
|
+
return out
|
|
866
|
+
except (MetadataError, OSError) as exc:
|
|
867
|
+
with track_memory_lock:
|
|
868
|
+
track_memory.pop(rel, None)
|
|
869
|
+
return TrackOut(path=rel, name=name, error=str(exc))
|
|
870
|
+
|
|
871
|
+
def tracks_out(rels: list[str]) -> list[TrackOut]:
|
|
872
|
+
"""A folder's tracks. Files the search index already knows unchanged (same modification
|
|
873
|
+
time and size) come from the index: a folder of thousands opens without reading a file."""
|
|
874
|
+
known = lib_index.stored(rels) if len(rels) > 20 else {}
|
|
875
|
+
out = []
|
|
876
|
+
for rel in rels:
|
|
877
|
+
hit = known.get(rel)
|
|
878
|
+
if hit is not None:
|
|
879
|
+
try:
|
|
880
|
+
st = library.resolve(rel).stat()
|
|
881
|
+
if (st.st_mtime_ns, st.st_size) == (hit[0], hit[1]) and not hit[2].get("error"):
|
|
882
|
+
out.append(TrackOut(**hit[2]))
|
|
883
|
+
continue
|
|
884
|
+
except (OSError, LibraryPathError, ValueError):
|
|
885
|
+
pass
|
|
886
|
+
out.append(track_out(rel))
|
|
887
|
+
return out
|
|
888
|
+
|
|
889
|
+
def result_out(r: FileResult) -> ApplyResultOut:
|
|
890
|
+
return ApplyResultOut(
|
|
891
|
+
path=library.relative(r.path),
|
|
892
|
+
applied=r.applied,
|
|
893
|
+
kept_existing=r.kept_existing,
|
|
894
|
+
unsupported=r.unsupported,
|
|
895
|
+
error=r.error,
|
|
896
|
+
)
|
|
897
|
+
|
|
898
|
+
# --- Status & vocabulary ----------------------------------------------------------
|
|
899
|
+
|
|
900
|
+
@app.get("/api/update")
|
|
901
|
+
def update_status(force: bool = Query(False, description="Check GitHub now instead of using the cached answer")) -> dict:
|
|
902
|
+
"""Installed version and, if enabled, the latest release on GitHub."""
|
|
903
|
+
result = updates.status(force=force)
|
|
904
|
+
if result.get("update_available") and result.get("latest"):
|
|
905
|
+
notices.add("update", f"Codetta {result['latest']} is out",
|
|
906
|
+
"See what's new and how to update in Account.", {"open": "account"},
|
|
907
|
+
key=f"update:{result['latest']}")
|
|
908
|
+
return result
|
|
909
|
+
|
|
910
|
+
# --- Notifications -------------------------------------------------------------------
|
|
911
|
+
|
|
912
|
+
@app.get("/api/notifications")
|
|
913
|
+
def get_notifications(after_id: int = Query(0, ge=0)) -> dict:
|
|
914
|
+
"""Newest first. ``after_id`` returns only newer ones (for the bell's pop-ups)."""
|
|
915
|
+
return notices.recent(after_id)
|
|
916
|
+
|
|
917
|
+
@app.post("/api/notifications/read")
|
|
918
|
+
def read_notifications(body: NotificationsReadIn) -> dict:
|
|
919
|
+
notices.mark_read(body.ids)
|
|
920
|
+
return notices.recent()
|
|
921
|
+
|
|
922
|
+
@app.delete("/api/notifications")
|
|
923
|
+
def clear_notifications() -> dict:
|
|
924
|
+
notices.clear()
|
|
925
|
+
return notices.recent()
|
|
926
|
+
|
|
927
|
+
@app.get("/api/status")
|
|
928
|
+
def status() -> dict:
|
|
929
|
+
return {
|
|
930
|
+
"version": VERSION,
|
|
931
|
+
"music_dir": str(library.root),
|
|
932
|
+
"music_dir_found": library.exists(),
|
|
933
|
+
"music_dir_writable": library.exists() and os.access(library.root, os.W_OK),
|
|
934
|
+
"lyrics_lookup": connections.enabled("lyrics"),
|
|
935
|
+
"musicbrainz": connections.enabled("musicbrainz"),
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
# --- Connections (online features, all opt-in) ---------------------------------------
|
|
939
|
+
|
|
940
|
+
def connections_out() -> dict:
|
|
941
|
+
out = connections.status()
|
|
942
|
+
for c in out["connections"]:
|
|
943
|
+
if c["id"] == "acoustid" and not fingerprinter.available:
|
|
944
|
+
c["unavailable"] = ("The fingerprint tool isn't installed on this server (fpcalc, from "
|
|
945
|
+
"Chromaprint; it's included in the Docker image).")
|
|
946
|
+
if mb_mirror:
|
|
947
|
+
from urllib.parse import urlsplit
|
|
948
|
+
|
|
949
|
+
for c in out["connections"]:
|
|
950
|
+
if c["id"] == "musicbrainz":
|
|
951
|
+
c["hosts"] = [urlsplit(mb_mirror).netloc or mb_mirror, "coverartarchive.org"]
|
|
952
|
+
c["mirror"] = True
|
|
953
|
+
return out
|
|
954
|
+
|
|
955
|
+
@app.get("/api/connections")
|
|
956
|
+
def get_connections() -> dict:
|
|
957
|
+
"""Which online features are on, who decided (the user or an env var), and
|
|
958
|
+
whether the first-run choice has been made."""
|
|
959
|
+
return connections_out()
|
|
960
|
+
|
|
961
|
+
@app.put("/api/connections")
|
|
962
|
+
def put_connections(body: ConnectionsIn) -> dict:
|
|
963
|
+
unknown = [k for k in body.enabled if k not in CONNECTION_BY_ID]
|
|
964
|
+
if unknown:
|
|
965
|
+
raise HTTPException(422, f"Unknown connection: {unknown[0]}")
|
|
966
|
+
try:
|
|
967
|
+
connections.save(body.enabled)
|
|
968
|
+
except OSError as exc:
|
|
969
|
+
raise HTTPException(500, f"Could not save to the config folder: {exc}") from exc
|
|
970
|
+
on = [CONNECTION_BY_ID[c["id"]].name for c in connections.status()["connections"] if c["enabled"]]
|
|
971
|
+
log.info("Connections: %s", ", ".join(on) if on else "none (offline)")
|
|
972
|
+
return connections_out()
|
|
973
|
+
|
|
974
|
+
def require_connection(cid: str) -> None:
|
|
975
|
+
if connections.enabled(cid):
|
|
976
|
+
return
|
|
977
|
+
name = CONNECTION_BY_ID[cid].name
|
|
978
|
+
if settings.offline:
|
|
979
|
+
raise HTTPException(403, f"{name} is unavailable: Codetta is set to stay offline (CODETTA_OFFLINE).")
|
|
980
|
+
locked = connections.locked_by(cid)
|
|
981
|
+
where = f"it's turned off by {locked}" if locked else "turn it on in Account → Connections"
|
|
982
|
+
raise HTTPException(403, f"{name} is off: {where}.")
|
|
983
|
+
|
|
984
|
+
@app.get("/api/fields")
|
|
985
|
+
def fields() -> dict:
|
|
986
|
+
"""The editor's known tags (in display order) and preset placeholders."""
|
|
987
|
+
return {
|
|
988
|
+
"fields": [
|
|
989
|
+
{"key": f.key, "label": f.label, "group": f.group, "multi": f.multi}
|
|
990
|
+
for f in FIELDS
|
|
991
|
+
],
|
|
992
|
+
"placeholders": sorted(PLACEHOLDERS),
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
# --- Library ---------------------------------------------------------------------
|
|
996
|
+
|
|
997
|
+
@app.get("/api/browse", response_model=BrowseOut)
|
|
998
|
+
def browse(path: str = Query("", max_length=MAX_PATH_CHARS, description="Folder, relative to the music folder")):
|
|
999
|
+
"""One folder: its subfolders and the tags of its audio files."""
|
|
1000
|
+
require_library()
|
|
1001
|
+
listing = library.list_folder(path)
|
|
1002
|
+
crumbs = [Crumb(name="Library", path="")]
|
|
1003
|
+
parts = listing.path.split("/") if listing.path else []
|
|
1004
|
+
for i, part in enumerate(parts):
|
|
1005
|
+
crumbs.append(Crumb(name=part, path="/".join(parts[: i + 1])))
|
|
1006
|
+
return BrowseOut(
|
|
1007
|
+
path=listing.path,
|
|
1008
|
+
name=crumbs[-1].name,
|
|
1009
|
+
breadcrumbs=crumbs,
|
|
1010
|
+
folders=[folder_out(f) for f in listing.folders],
|
|
1011
|
+
skipped=listing.skipped,
|
|
1012
|
+
tracks=tracks_out(listing.files),
|
|
1013
|
+
)
|
|
1014
|
+
|
|
1015
|
+
@app.get("/api/track", response_model=TrackOut)
|
|
1016
|
+
def get_track(path: str = Query(..., max_length=MAX_PATH_CHARS, description="File, relative to the music folder")):
|
|
1017
|
+
require_library()
|
|
1018
|
+
return to_out(path, engine.load_metadata(library.resolve(path)))
|
|
1019
|
+
|
|
1020
|
+
@app.get("/api/stream", responses={200: {"content": {"audio/*": {}}}, 206: {"description": "Part of the file"}})
|
|
1021
|
+
def stream(path: str = Query(..., max_length=MAX_PATH_CHARS, description="File, relative to the music folder")):
|
|
1022
|
+
"""The audio file itself, for the in-browser player. Supports seeking
|
|
1023
|
+
(HTTP range requests); nothing is converted or cached."""
|
|
1024
|
+
require_library()
|
|
1025
|
+
target = library.resolve(path)
|
|
1026
|
+
mime = STREAM_TYPES.get(target.suffix.lower())
|
|
1027
|
+
if mime is None or not target.is_file():
|
|
1028
|
+
raise HTTPException(404, "No such audio file")
|
|
1029
|
+
# The type comes from Codetta's own list (always audio/*), never from the file.
|
|
1030
|
+
return FileResponse(target, media_type=mime, content_disposition_type="inline",
|
|
1031
|
+
headers={"Cache-Control": "private, max-age=3600"})
|
|
1032
|
+
|
|
1033
|
+
LRC_LINE = re.compile(r"^\s*\[\d{1,3}:\d{2}(?:[.:]\d{1,3})?\]")
|
|
1034
|
+
|
|
1035
|
+
@app.get("/api/lyrics")
|
|
1036
|
+
def get_lyrics(path: str = Query(..., max_length=MAX_PATH_CHARS, description="File, relative to the music folder")) -> dict:
|
|
1037
|
+
"""The track's lyrics for the player: the lyrics tag, else a ``.lrc`` file next to it
|
|
1038
|
+
(as Navidrome reads them). ``synced`` when it's timed LRC."""
|
|
1039
|
+
require_library()
|
|
1040
|
+
target = library.resolve(path)
|
|
1041
|
+
text, source = "", None
|
|
1042
|
+
try:
|
|
1043
|
+
text = "\n".join(engine.load_metadata(target).tags.get("lyrics", [])).strip()
|
|
1044
|
+
source = "tag" if text else None
|
|
1045
|
+
except (MetadataError, OSError):
|
|
1046
|
+
pass
|
|
1047
|
+
if not text:
|
|
1048
|
+
side = target.with_suffix(".lrc")
|
|
1049
|
+
try:
|
|
1050
|
+
if side.is_file() and side.stat().st_size <= 512 * 1024:
|
|
1051
|
+
text, source = side.read_text("utf-8", errors="replace").strip(), "file"
|
|
1052
|
+
except OSError:
|
|
1053
|
+
pass
|
|
1054
|
+
synced = sum(1 for line in text.splitlines() if LRC_LINE.match(line)) >= 2
|
|
1055
|
+
return {"lyrics": text, "source": source, "synced": synced}
|
|
1056
|
+
|
|
1057
|
+
@app.get("/api/lyrics/lookup")
|
|
1058
|
+
def lyrics_lookup(path: str = Query(..., max_length=MAX_PATH_CHARS, description="File, relative to the music folder")) -> dict:
|
|
1059
|
+
"""Look up lyrics for a track on LRCLIB (sends artist, title, album and length only).
|
|
1060
|
+
Returns a suggestion; nothing is written."""
|
|
1061
|
+
require_connection("lyrics")
|
|
1062
|
+
require_library()
|
|
1063
|
+
meta = engine.load_metadata(library.resolve(path))
|
|
1064
|
+
first = lambda key: (meta.tags.get(key) or [""])[0].strip() # noqa: E731
|
|
1065
|
+
artist = first("artist") or first("albumartist")
|
|
1066
|
+
title = first("title")
|
|
1067
|
+
if not artist or not title:
|
|
1068
|
+
raise HTTPException(422, "Add the artist and title first, so the right song can be found.")
|
|
1069
|
+
try:
|
|
1070
|
+
result = lrclib.lyrics(TrackQuery(artist=artist, title=title, album=first("album"), duration=meta.duration))
|
|
1071
|
+
except ProviderError as exc:
|
|
1072
|
+
raise HTTPException(502, str(exc)) from exc
|
|
1073
|
+
return {"found": result is not None, "result": result.to_dict() if result else None}
|
|
1074
|
+
|
|
1075
|
+
# --- MusicBrainz ---------------------------------------------------------------------
|
|
1076
|
+
|
|
1077
|
+
def mb_targets(body: MBTarget) -> list[str]:
|
|
1078
|
+
if body.folder is not None:
|
|
1079
|
+
rels = library.list_folder(body.folder).files
|
|
1080
|
+
else:
|
|
1081
|
+
rels = _unique(body.paths)
|
|
1082
|
+
if not rels:
|
|
1083
|
+
raise HTTPException(400, "Choose an album folder or some tracks first.")
|
|
1084
|
+
if len(rels) > MAX_PATHS_PER_REQUEST:
|
|
1085
|
+
raise HTTPException(422, f"Too many files for one album (max {MAX_PATHS_PER_REQUEST}).")
|
|
1086
|
+
return rels
|
|
1087
|
+
|
|
1088
|
+
def mb_read(rels: list[str]) -> tuple[list[FileInfo], dict[str, TrackMetadata], dict[str, str]]:
|
|
1089
|
+
infos, metas, errors = [], {}, {}
|
|
1090
|
+
for rel in rels:
|
|
1091
|
+
try:
|
|
1092
|
+
meta = engine.load_metadata(library.resolve(rel))
|
|
1093
|
+
except (MetadataError, LibraryPathError, OSError) as exc:
|
|
1094
|
+
errors[rel] = str(exc)
|
|
1095
|
+
continue
|
|
1096
|
+
metas[rel] = meta
|
|
1097
|
+
one = lambda key: (meta.tags.get(key) or [""])[0].strip() # noqa: E731
|
|
1098
|
+
infos.append(FileInfo(
|
|
1099
|
+
path=rel, title=one("title"), artist=one("artist"), album=one("album"),
|
|
1100
|
+
albumartist=one("albumartist"), tracknumber=number(one("tracknumber")),
|
|
1101
|
+
discnumber=number(one("discnumber")), duration=meta.duration, albumid=one("musicbrainz_albumid").lower(),
|
|
1102
|
+
))
|
|
1103
|
+
return infos, metas, errors
|
|
1104
|
+
|
|
1105
|
+
def most_common(values) -> str:
|
|
1106
|
+
counts: dict[str, int] = {}
|
|
1107
|
+
for v in values:
|
|
1108
|
+
if v:
|
|
1109
|
+
counts[v] = counts.get(v, 0) + 1
|
|
1110
|
+
return max(counts, key=counts.get) if counts else ""
|
|
1111
|
+
|
|
1112
|
+
def mb_release_id(text: str) -> str:
|
|
1113
|
+
mbid = parse_release_id(text)
|
|
1114
|
+
if not mbid:
|
|
1115
|
+
raise HTTPException(422, "Paste a MusicBrainz release link (musicbrainz.org/release/…) or its ID.")
|
|
1116
|
+
return mbid
|
|
1117
|
+
|
|
1118
|
+
@app.post("/api/musicbrainz/search")
|
|
1119
|
+
def mb_search(body: MBSearchIn) -> dict:
|
|
1120
|
+
"""Find releases that could be this album. Sends only the album/artist
|
|
1121
|
+
names (or the release ID you pasted) to MusicBrainz."""
|
|
1122
|
+
require_connection("musicbrainz")
|
|
1123
|
+
require_library()
|
|
1124
|
+
rels = mb_targets(body)
|
|
1125
|
+
infos, _, _ = mb_read(rels)
|
|
1126
|
+
album = body.album.strip() or most_common(f.album for f in infos)
|
|
1127
|
+
artist = body.artist.strip() or most_common(f.albumartist or f.artist for f in infos)
|
|
1128
|
+
current = most_common(f.albumid for f in infos if MBID_RE.match(f.albumid))
|
|
1129
|
+
try:
|
|
1130
|
+
if body.release.strip():
|
|
1131
|
+
found = [mb.release(mb_release_id(body.release))]
|
|
1132
|
+
else:
|
|
1133
|
+
found = mb.search(album, artist) if (album or artist) else []
|
|
1134
|
+
if current and not body.album.strip() and not body.artist.strip() and all(r.get("id") != current for r in found):
|
|
1135
|
+
try: # already tagged with a release: offer it first
|
|
1136
|
+
found.insert(0, mb.release(current))
|
|
1137
|
+
except ProviderError:
|
|
1138
|
+
pass
|
|
1139
|
+
except ProviderError as exc:
|
|
1140
|
+
raise HTTPException(502, str(exc)) from exc
|
|
1141
|
+
candidates = []
|
|
1142
|
+
for r in found:
|
|
1143
|
+
c = summarize(r)
|
|
1144
|
+
c["score"] = score_candidate(c, infos, album, artist)
|
|
1145
|
+
c["current"] = c["id"] == current
|
|
1146
|
+
candidates.append(c)
|
|
1147
|
+
if not body.release.strip():
|
|
1148
|
+
candidates.sort(key=lambda c: (not c["current"], -c["score"]))
|
|
1149
|
+
return {"query": {"album": album, "artist": artist, "files": len(rels)}, "current": current or None,
|
|
1150
|
+
"candidates": candidates}
|
|
1151
|
+
|
|
1152
|
+
@app.post("/api/musicbrainz/identify")
|
|
1153
|
+
def mb_identify(body: MBTarget) -> dict:
|
|
1154
|
+
"""Recognise the files by their sound: fingerprint them here, ask AcoustID
|
|
1155
|
+
which recordings they are, and offer the releases holding most of them."""
|
|
1156
|
+
require_connection("musicbrainz")
|
|
1157
|
+
require_connection("acoustid")
|
|
1158
|
+
require_library()
|
|
1159
|
+
if not fingerprinter.available:
|
|
1160
|
+
raise HTTPException(503, "The fingerprint tool (fpcalc) isn't installed on this server. "
|
|
1161
|
+
"It's included in the Docker image; elsewhere install Chromaprint.")
|
|
1162
|
+
rels = mb_targets(body)
|
|
1163
|
+
if len(rels) > MAX_IDENTIFY:
|
|
1164
|
+
raise HTTPException(422, f"Identify by sound works on up to {MAX_IDENTIFY} tracks at a time "
|
|
1165
|
+
"(one album). Select fewer tracks.")
|
|
1166
|
+
infos, _, read_errors = mb_read(rels)
|
|
1167
|
+
readable = [f.path for f in infos]
|
|
1168
|
+
prints = fingerprinter.many([library.resolve(r) for r in readable])
|
|
1169
|
+
ok = [(rel, fp) for rel, fp in zip(readable, prints) if not isinstance(fp, FingerprintError)]
|
|
1170
|
+
try:
|
|
1171
|
+
found = acoustid.lookup([fp for _, fp in ok]) if ok else []
|
|
1172
|
+
except ProviderError as exc:
|
|
1173
|
+
raise HTTPException(502, str(exc)) from exc
|
|
1174
|
+
heard = {rel: recs for (rel, _), recs in zip(ok, found)}
|
|
1175
|
+
files = []
|
|
1176
|
+
for rel in rels:
|
|
1177
|
+
if rel in read_errors:
|
|
1178
|
+
files.append({"path": rel, "status": "error", "error": read_errors[rel]})
|
|
1179
|
+
continue
|
|
1180
|
+
fp = prints[readable.index(rel)]
|
|
1181
|
+
if isinstance(fp, FingerprintError):
|
|
1182
|
+
files.append({"path": rel, "status": "error", "error": str(fp)})
|
|
1183
|
+
elif heard.get(rel):
|
|
1184
|
+
top = heard[rel][0]
|
|
1185
|
+
files.append({"path": rel, "status": "identified", "recording": {
|
|
1186
|
+
"id": top.id, "title": top.title, "artist": top.artist, "score": round(top.score * 100)}})
|
|
1187
|
+
else:
|
|
1188
|
+
files.append({"path": rel, "status": "unknown"})
|
|
1189
|
+
ranked = rank_releases(heard, limit=25)
|
|
1190
|
+
try:
|
|
1191
|
+
found_releases = mb.releases_by_id([rid for rid, _ in ranked]) if ranked else []
|
|
1192
|
+
except ProviderError as exc:
|
|
1193
|
+
raise HTTPException(502, str(exc)) from exc
|
|
1194
|
+
covered = dict(ranked)
|
|
1195
|
+
n = len(rels)
|
|
1196
|
+
candidates = []
|
|
1197
|
+
for r in found_releases:
|
|
1198
|
+
c = summarize(r)
|
|
1199
|
+
tracks = c.get("track_count") or 0
|
|
1200
|
+
fit = 1.0 if tracks == n else max(0.0, 1 - abs(tracks - n) / max(n, tracks or 1) * 2)
|
|
1201
|
+
c["heard"] = covered.get(c["id"], 0)
|
|
1202
|
+
c["score"] = round(100 * (0.75 * c["heard"] / max(1, n) + 0.25 * fit))
|
|
1203
|
+
c["current"] = False
|
|
1204
|
+
candidates.append(c)
|
|
1205
|
+
candidates.sort(key=lambda c: -c["score"])
|
|
1206
|
+
identified = sum(f["status"] == "identified" for f in files)
|
|
1207
|
+
return {
|
|
1208
|
+
"query": {"album": "", "artist": "", "files": n},
|
|
1209
|
+
"identified": identified, "total": n,
|
|
1210
|
+
"files": files,
|
|
1211
|
+
"recordings": {rel: [r.id for r in recs[:20]] for rel, recs in heard.items() if recs},
|
|
1212
|
+
"candidates": candidates[:15],
|
|
1213
|
+
}
|
|
1214
|
+
|
|
1215
|
+
def mb_proposal(body: MBProposalIn) -> tuple[dict, dict]:
|
|
1216
|
+
"""What applying this release would change, per file. Returns (proposal, release)."""
|
|
1217
|
+
require_connection("musicbrainz")
|
|
1218
|
+
require_library()
|
|
1219
|
+
rels = mb_targets(body)
|
|
1220
|
+
mbid = mb_release_id(body.release)
|
|
1221
|
+
try:
|
|
1222
|
+
release = mb.release(mbid)
|
|
1223
|
+
except ProviderError as exc:
|
|
1224
|
+
raise HTTPException(502, str(exc)) from exc
|
|
1225
|
+
tracks = release_tracks(release)
|
|
1226
|
+
if not tracks:
|
|
1227
|
+
raise HTTPException(422, "This release has no track list on MusicBrainz yet.")
|
|
1228
|
+
infos, metas, errors = mb_read(rels)
|
|
1229
|
+
heard = {p: [r for r in ids[:20] if MBID_RE.match(r)] for p, ids in body.recordings.items() if p in metas}
|
|
1230
|
+
pairs = pair_files(infos, tracks, {p: t for p, t in body.pairs.items() if p in metas}, heard)
|
|
1231
|
+
album = album_tags(release)
|
|
1232
|
+
wanted = set(mb_default_fields() if body.fields is None else body.fields) & set(MB_FIELDS)
|
|
1233
|
+
summary = summarize(release)
|
|
1234
|
+
files = []
|
|
1235
|
+
for rel in rels:
|
|
1236
|
+
if rel in errors:
|
|
1237
|
+
files.append({"path": rel, "error": errors[rel], "track": None, "changes": {}})
|
|
1238
|
+
continue
|
|
1239
|
+
meta, pairing = metas[rel], pairs[rel]
|
|
1240
|
+
changes, unsupported = {}, []
|
|
1241
|
+
if pairing.track:
|
|
1242
|
+
for key, new in track_tags(release, pairing.track, album).items():
|
|
1243
|
+
if key not in wanted:
|
|
1244
|
+
continue
|
|
1245
|
+
if not is_tag_supported(meta.format or "", key):
|
|
1246
|
+
unsupported.append(key)
|
|
1247
|
+
continue
|
|
1248
|
+
old = meta.tags.get(key, [])
|
|
1249
|
+
if body.mode == "fill" and any(v.strip() for v in old):
|
|
1250
|
+
continue
|
|
1251
|
+
if old != new:
|
|
1252
|
+
changes[key] = {"old": old, "new": new}
|
|
1253
|
+
target = library.resolve(rel)
|
|
1254
|
+
try:
|
|
1255
|
+
mtime = target.stat().st_mtime_ns
|
|
1256
|
+
except OSError:
|
|
1257
|
+
mtime = None
|
|
1258
|
+
has_art = art_info(rel, target, mtime) is not None
|
|
1259
|
+
files.append({
|
|
1260
|
+
"path": rel, "error": None,
|
|
1261
|
+
"track": pairing.track.to_dict() if pairing.track else None,
|
|
1262
|
+
"confidence": pairing.confidence, "notes": pairing.notes,
|
|
1263
|
+
"duration": meta.duration, "title": (meta.tags.get("title") or [""])[0],
|
|
1264
|
+
"changes": changes, "unsupported": unsupported, "has_art": has_art,
|
|
1265
|
+
"cover": bool(pairing.track) and summary["has_cover"] is not False
|
|
1266
|
+
and (body.cover == "all" or (body.cover == "missing" and not has_art)),
|
|
1267
|
+
})
|
|
1268
|
+
labels = {f.key: f.label for f in FIELDS}
|
|
1269
|
+
groups = [
|
|
1270
|
+
{"id": gid, "label": label, "default": not set(keys) <= MB_DEFAULT_OFF,
|
|
1271
|
+
"fields": [{"key": k, "label": labels.get(k) or MB_ID_LABELS.get(k, k)} for k in keys]}
|
|
1272
|
+
for gid, label, keys in MB_FIELD_GROUPS
|
|
1273
|
+
]
|
|
1274
|
+
return {
|
|
1275
|
+
"release": summary,
|
|
1276
|
+
"tracks": [t.to_dict() for t in tracks],
|
|
1277
|
+
"files": files,
|
|
1278
|
+
"groups": groups,
|
|
1279
|
+
"fields": sorted(wanted),
|
|
1280
|
+
"mode": body.mode, "cover": body.cover,
|
|
1281
|
+
}, release
|
|
1282
|
+
|
|
1283
|
+
@app.post("/api/musicbrainz/preview")
|
|
1284
|
+
def mb_preview(body: MBProposalIn) -> dict:
|
|
1285
|
+
"""Pair the files with a release's tracks and show what would change. Writes nothing."""
|
|
1286
|
+
return mb_proposal(body)[0]
|
|
1287
|
+
|
|
1288
|
+
cover_cache: OrderedDict[tuple[str, int | None], bytes | None] = OrderedDict()
|
|
1289
|
+
cover_lock = threading.Lock()
|
|
1290
|
+
|
|
1291
|
+
def fetch_cover(mbid: str, size: int | None) -> bytes | None:
|
|
1292
|
+
key = (mbid, size)
|
|
1293
|
+
with cover_lock:
|
|
1294
|
+
if key in cover_cache:
|
|
1295
|
+
cover_cache.move_to_end(key)
|
|
1296
|
+
return cover_cache[key]
|
|
1297
|
+
kind = "release"
|
|
1298
|
+
if mbid.startswith("rg:"):
|
|
1299
|
+
kind, mbid = "release-group", mbid[3:]
|
|
1300
|
+
data = download_art(cover_url(mbid, size, kind=kind))
|
|
1301
|
+
if data is not None and sniff_image_type(data) not in ("image/jpeg", "image/png"):
|
|
1302
|
+
data = None # only real JPEG/PNG covers are used (and served to the page)
|
|
1303
|
+
if size and size <= 500: # only small thumbnails are kept (the candidate list)
|
|
1304
|
+
with cover_lock:
|
|
1305
|
+
cover_cache[key] = data
|
|
1306
|
+
while len(cover_cache) > 48:
|
|
1307
|
+
cover_cache.popitem(last=False)
|
|
1308
|
+
return data
|
|
1309
|
+
|
|
1310
|
+
@app.get("/api/musicbrainz/cover/{mbid}", responses={200: {"content": {"image/jpeg": {}, "image/png": {}}}})
|
|
1311
|
+
def mb_cover(mbid: str, size: int = Query(250, description="250 or 500 pixels"),
|
|
1312
|
+
kind: Literal["release", "release-group"] = "release"):
|
|
1313
|
+
"""A release's (or release group's) front cover from the Cover Art Archive, fetched
|
|
1314
|
+
by the server (so the page never loads anything from another site)."""
|
|
1315
|
+
require_connection("musicbrainz")
|
|
1316
|
+
if not MBID_RE.match(mbid) or size not in (250, 500):
|
|
1317
|
+
raise HTTPException(422, "Not a release ID or thumbnail size")
|
|
1318
|
+
try:
|
|
1319
|
+
data = fetch_cover(("rg:" if kind == "release-group" else "") + mbid, size)
|
|
1320
|
+
except ProviderError as exc:
|
|
1321
|
+
raise HTTPException(502, str(exc)) from exc
|
|
1322
|
+
if data is None:
|
|
1323
|
+
raise HTTPException(404, "No cover art for this release")
|
|
1324
|
+
return Response(data, media_type=sniff_image_type(data), headers={"Cache-Control": "private, max-age=86400"})
|
|
1325
|
+
|
|
1326
|
+
@app.post("/api/musicbrainz/apply")
|
|
1327
|
+
def mb_apply(body: MBProposalIn) -> dict:
|
|
1328
|
+
"""Write the release's tags (and cover) to the paired files: one activity
|
|
1329
|
+
entry, undoable as a whole."""
|
|
1330
|
+
proposal, release = mb_proposal(body)
|
|
1331
|
+
summary = proposal["release"]
|
|
1332
|
+
art, art_error = None, None
|
|
1333
|
+
if any(f.get("cover") for f in proposal["files"]):
|
|
1334
|
+
try:
|
|
1335
|
+
art = fetch_cover(summary["id"], 1200) or fetch_cover(summary["id"], None)
|
|
1336
|
+
if art is None:
|
|
1337
|
+
art_error = "This release has no cover art on the Cover Art Archive"
|
|
1338
|
+
except ProviderError as exc:
|
|
1339
|
+
art_error = str(exc)
|
|
1340
|
+
tag_undo, art_undo, results = {}, {}, []
|
|
1341
|
+
for f in proposal["files"]:
|
|
1342
|
+
rel = f["path"]
|
|
1343
|
+
if f["error"]:
|
|
1344
|
+
results.append({"path": rel, "ok": False, "error": f["error"]})
|
|
1345
|
+
continue
|
|
1346
|
+
set_art = bool(f["cover"] and art)
|
|
1347
|
+
if not f["changes"] and not set_art:
|
|
1348
|
+
continue
|
|
1349
|
+
target = library.resolve(rel)
|
|
1350
|
+
errors = []
|
|
1351
|
+
if f["changes"]:
|
|
1352
|
+
try:
|
|
1353
|
+
meta = engine.update_tags(target, {k: c["new"] for k, c in f["changes"].items()})
|
|
1354
|
+
tag_undo[rel] = {"before": {k: c["old"] for k, c in f["changes"].items()},
|
|
1355
|
+
"after": {k: meta.tags.get(k, []) for k in f["changes"]}}
|
|
1356
|
+
except (MetadataError, LibraryPathError, OSError) as exc:
|
|
1357
|
+
errors.append(str(exc))
|
|
1358
|
+
if set_art and not errors:
|
|
1359
|
+
try:
|
|
1360
|
+
old = engine.read_artwork(target)
|
|
1361
|
+
new = engine.update_artwork(target, art)
|
|
1362
|
+
try:
|
|
1363
|
+
before, after = art_store.save(old.data if old else None), art_store.save(new.data if new else None)
|
|
1364
|
+
if before != after:
|
|
1365
|
+
art_undo[rel] = {"before": before, "after": after}
|
|
1366
|
+
except OSError:
|
|
1367
|
+
pass # couldn't keep a copy: the cover part just won't be undoable
|
|
1368
|
+
except (MetadataError, LibraryPathError, OSError) as exc:
|
|
1369
|
+
errors.append(f"Cover art: {exc}")
|
|
1370
|
+
results.append({"path": rel, "ok": not errors, "error": "; ".join(errors) or None,
|
|
1371
|
+
"tags": len(f["changes"]), "cover": set_art and not errors})
|
|
1372
|
+
parts = [p for p in ({"type": "tags", "files": tag_undo}, {"type": "art", "files": art_undo}) if p["files"]]
|
|
1373
|
+
undo = parts[0] if len(parts) == 1 else {"type": "multi", "parts": parts} if parts else None
|
|
1374
|
+
if results:
|
|
1375
|
+
_log_musicbrainz(activity, summary, proposal["files"], results, bool(art_undo), undo)
|
|
1376
|
+
lib_index.mark_dirty(r["path"] for r in results if r["ok"])
|
|
1377
|
+
return {
|
|
1378
|
+
"release": summary,
|
|
1379
|
+
"results": results,
|
|
1380
|
+
"updated": sum(r["ok"] for r in results),
|
|
1381
|
+
"failed": sum(not r["ok"] for r in results),
|
|
1382
|
+
"cover_error": art_error,
|
|
1383
|
+
}
|
|
1384
|
+
|
|
1385
|
+
@app.get("/api/track/raw")
|
|
1386
|
+
def get_track_raw(path: str = Query(..., max_length=MAX_PATH_CHARS, description="File, relative to the music folder")) -> dict:
|
|
1387
|
+
"""Advanced mode: every stored field exactly as the file has it (read-only)."""
|
|
1388
|
+
require_library()
|
|
1389
|
+
return read_raw(engine, library.resolve(path))
|
|
1390
|
+
|
|
1391
|
+
@app.get("/api/search", response_model=SearchOut)
|
|
1392
|
+
def search(
|
|
1393
|
+
q: str = Query(..., max_length=500, description='e.g. "genre: rap, hip-hop artist: drake" or plain words'),
|
|
1394
|
+
limit: int = Query(500, ge=1, le=MAX_PATHS_PER_REQUEST),
|
|
1395
|
+
):
|
|
1396
|
+
"""Search the whole library by tag. Commas mean "or"; clauses and words must all match."""
|
|
1397
|
+
require_library()
|
|
1398
|
+
query = parse_query(q, lib_index.has_key)
|
|
1399
|
+
tracks, total = lib_index.search(query, limit)
|
|
1400
|
+
lib_index.request_rescan() # pick up music added outside Codetta (in the background)
|
|
1401
|
+
status = lib_index.status()
|
|
1402
|
+
return SearchOut(
|
|
1403
|
+
path="", name="Search", breadcrumbs=[Crumb(name="Library", path="")], folders=[], tracks=tracks,
|
|
1404
|
+
search=SearchInfo(
|
|
1405
|
+
query=q, words=query.words, total=total, indexing=not status.ready, indexed=status.files,
|
|
1406
|
+
clauses=[ClauseOut(key=c.key, label=c.label, values=c.values) for c in query.clauses if c.values],
|
|
1407
|
+
),
|
|
1408
|
+
)
|
|
1409
|
+
|
|
1410
|
+
@app.patch("/api/tracks", response_model=list[UpdateResult])
|
|
1411
|
+
def update_tracks(body: UpdateIn):
|
|
1412
|
+
"""Apply the same tag changes to one or more files.
|
|
1413
|
+
|
|
1414
|
+
Each file succeeds or fails on its own; check ``ok`` per result.
|
|
1415
|
+
"""
|
|
1416
|
+
require_library()
|
|
1417
|
+
before: dict[str, dict[str, list[str]]] = {} # for the activity log
|
|
1418
|
+
|
|
1419
|
+
paths = _unique(body.paths)
|
|
1420
|
+
# A tag edit never touches the embedded cover: reuse what the index knows about it
|
|
1421
|
+
# instead of opening every file once more just to hash its picture again.
|
|
1422
|
+
known_art = {p: (t.get("art"),) for p, (_, _, t) in lib_index.stored(paths).items()} if len(paths) > 8 else {}
|
|
1423
|
+
|
|
1424
|
+
def write(rel: str) -> UpdateResult:
|
|
1425
|
+
try:
|
|
1426
|
+
target = library.resolve(rel)
|
|
1427
|
+
was: dict = {}
|
|
1428
|
+
meta = engine.update_tags(target, body.changes, before=was) # safe write: copy, check, swap
|
|
1429
|
+
before[rel] = was["tags"]
|
|
1430
|
+
if rel in known_art:
|
|
1431
|
+
try:
|
|
1432
|
+
mtime = target.stat().st_mtime_ns
|
|
1433
|
+
except OSError:
|
|
1434
|
+
mtime = None
|
|
1435
|
+
out = _to_track_out(rel, meta, mtime)
|
|
1436
|
+
art = known_art[rel][0]
|
|
1437
|
+
out.art = ArtInfo(**art) if art else None
|
|
1438
|
+
return UpdateResult(path=rel, ok=True, track=out)
|
|
1439
|
+
return UpdateResult(path=rel, ok=True, track=to_out(rel, meta))
|
|
1440
|
+
except (MetadataError, LibraryPathError, OSError) as exc:
|
|
1441
|
+
return UpdateResult(path=rel, ok=False, error=str(exc))
|
|
1442
|
+
|
|
1443
|
+
if len(paths) > 8:
|
|
1444
|
+
# Most of a safe write is waiting for the disk, so a few at once is ~1.6x faster
|
|
1445
|
+
# (more on hard drives). Each file still has its own lock and its own safe write.
|
|
1446
|
+
with ThreadPoolExecutor(max_workers=4, thread_name_prefix="codetta-write") as pool:
|
|
1447
|
+
results = list(pool.map(write, paths))
|
|
1448
|
+
else:
|
|
1449
|
+
results = [write(rel) for rel in paths]
|
|
1450
|
+
keys = {k.lower() for k in body.changes}
|
|
1451
|
+
undo_files = {}
|
|
1452
|
+
for r in results:
|
|
1453
|
+
if r.ok and r.path in before:
|
|
1454
|
+
b = {k: before[r.path].get(k, []) for k in keys}
|
|
1455
|
+
a = {k: r.track.tags.get(k, []) for k in keys}
|
|
1456
|
+
changed = [k for k in keys if b[k] != a[k]]
|
|
1457
|
+
if changed:
|
|
1458
|
+
undo_files[r.path] = {"before": {k: b[k] for k in changed}, "after": {k: a[k] for k in changed}}
|
|
1459
|
+
_log_edit(activity, body.changes, results, before,
|
|
1460
|
+
undo={"type": "tags", "files": undo_files} if undo_files else None)
|
|
1461
|
+
lib_index.mark_dirty(r.path for r in results if r.ok)
|
|
1462
|
+
return results
|
|
1463
|
+
|
|
1464
|
+
# --- Album art ---------------------------------------------------------------------
|
|
1465
|
+
|
|
1466
|
+
@app.get("/api/art", responses={200: {"content": {"image/jpeg": {}, "image/png": {}}}})
|
|
1467
|
+
def get_art(path: str = Query(..., max_length=MAX_PATH_CHARS, description="File, relative to the music folder")):
|
|
1468
|
+
"""The track's embedded cover image (404 if it has none)."""
|
|
1469
|
+
require_library()
|
|
1470
|
+
art = engine.read_artwork(library.resolve(path))
|
|
1471
|
+
if art is None:
|
|
1472
|
+
raise HTTPException(404, "This track has no album art")
|
|
1473
|
+
# The type is decided from the image's actual bytes, never from what the
|
|
1474
|
+
# file claims ("image/jpeg" holding HTML, "text/html", SVG...). Anything
|
|
1475
|
+
# that isn't a real JPEG/PNG/WebP/GIF is sent as a download, so a
|
|
1476
|
+
# booby-trapped file can never run a script inside Codetta.
|
|
1477
|
+
mime = sniff_image_type(art.data)
|
|
1478
|
+
if mime:
|
|
1479
|
+
return Response(art.data, media_type=mime, headers={"Cache-Control": "private, max-age=31536000, immutable"})
|
|
1480
|
+
return Response(art.data, media_type="application/octet-stream", headers={
|
|
1481
|
+
"Content-Disposition": 'attachment; filename="cover.bin"', "Cache-Control": "no-store"})
|
|
1482
|
+
|
|
1483
|
+
@app.put("/api/art", response_model=list[UpdateResult])
|
|
1484
|
+
async def set_art(request: Request, path: list[str] = Query(..., description="One or more files")):
|
|
1485
|
+
"""Embed the request body (a JPEG or PNG image) as album art in each file."""
|
|
1486
|
+
require_library()
|
|
1487
|
+
if len(path) > MAX_PATHS_PER_REQUEST:
|
|
1488
|
+
raise HTTPException(422, f"Too many files in one request (max {MAX_PATHS_PER_REQUEST})")
|
|
1489
|
+
image = await request.body() # size already capped by GuardMiddleware
|
|
1490
|
+
return await run_in_threadpool(_change_art, _unique(path), image)
|
|
1491
|
+
|
|
1492
|
+
@app.delete("/api/art", response_model=list[UpdateResult])
|
|
1493
|
+
def delete_art(path: list[str] = Query(..., description="One or more files")):
|
|
1494
|
+
"""Remove all embedded pictures from each file."""
|
|
1495
|
+
require_library()
|
|
1496
|
+
if len(path) > MAX_PATHS_PER_REQUEST:
|
|
1497
|
+
raise HTTPException(422, f"Too many files in one request (max {MAX_PATHS_PER_REQUEST})")
|
|
1498
|
+
return _change_art(_unique(path), None)
|
|
1499
|
+
|
|
1500
|
+
def _change_art(paths: list[str], image: bytes | None) -> list[UpdateResult]:
|
|
1501
|
+
results, had_art = [], 0
|
|
1502
|
+
art = None
|
|
1503
|
+
undo_files = {}
|
|
1504
|
+
for rel in paths:
|
|
1505
|
+
try:
|
|
1506
|
+
target = library.resolve(rel)
|
|
1507
|
+
old = engine.read_artwork(target)
|
|
1508
|
+
had_art += old is not None
|
|
1509
|
+
art = engine.update_artwork(target, image)
|
|
1510
|
+
# Keep both images so the change can be undone (and redone).
|
|
1511
|
+
try:
|
|
1512
|
+
before = art_store.save(old.data if old else None)
|
|
1513
|
+
after = art_store.save(art.data if art else None)
|
|
1514
|
+
if before != after:
|
|
1515
|
+
undo_files[rel] = {"before": before, "after": after}
|
|
1516
|
+
except OSError:
|
|
1517
|
+
pass # couldn't keep a copy: this change just won't be undoable
|
|
1518
|
+
results.append(UpdateResult(path=rel, ok=True, track=to_out(rel, engine.load_metadata(target))))
|
|
1519
|
+
except (MetadataError, LibraryPathError, OSError) as exc:
|
|
1520
|
+
results.append(UpdateResult(path=rel, ok=False, error=str(exc)))
|
|
1521
|
+
_log_art(activity, image is not None, art, had_art, results,
|
|
1522
|
+
undo={"type": "art", "files": undo_files} if undo_files else None)
|
|
1523
|
+
lib_index.mark_dirty(r.path for r in results if r.ok)
|
|
1524
|
+
return results
|
|
1525
|
+
|
|
1526
|
+
# --- Organize ---------------------------------------------------------------------
|
|
1527
|
+
|
|
1528
|
+
pattern_file = settings.config_dir / "organize.json"
|
|
1529
|
+
|
|
1530
|
+
def organize_plan(body: OrganizeIn) -> tuple[str, list[Move]]:
|
|
1531
|
+
require_library()
|
|
1532
|
+
try:
|
|
1533
|
+
pattern = check_pattern(body.pattern) if body.pattern is not None else load_pattern(pattern_file)
|
|
1534
|
+
except PatternError as exc:
|
|
1535
|
+
raise HTTPException(422, str(exc)) from exc
|
|
1536
|
+
if body.folder is not None:
|
|
1537
|
+
try:
|
|
1538
|
+
rels = audio_files(library, body.folder, body.recursive, MAX_ORGANIZE)
|
|
1539
|
+
except TooManyFilesError as exc:
|
|
1540
|
+
raise HTTPException(422, str(exc)) from exc
|
|
1541
|
+
else:
|
|
1542
|
+
rels = _unique(body.paths)
|
|
1543
|
+
sources, errors = [], []
|
|
1544
|
+
for rel in rels:
|
|
1545
|
+
try:
|
|
1546
|
+
meta = engine.load_metadata(library.resolve(rel))
|
|
1547
|
+
sources.append(Source(rel, meta.tags, meta.format or ""))
|
|
1548
|
+
except (MetadataError, LibraryPathError, OSError) as exc:
|
|
1549
|
+
errors.append(Move(rel, rel, "error", str(exc)))
|
|
1550
|
+
return pattern, plan_moves(library.resolve, sources, pattern) + errors
|
|
1551
|
+
|
|
1552
|
+
@app.get("/api/organize/settings")
|
|
1553
|
+
def organize_settings() -> dict:
|
|
1554
|
+
return {"pattern": load_pattern(pattern_file), "default": DEFAULT_PATTERN,
|
|
1555
|
+
"presets": [{"name": n, "pattern": p} for n, p in ORGANIZE_PRESETS]}
|
|
1556
|
+
|
|
1557
|
+
@app.put("/api/organize/settings")
|
|
1558
|
+
def save_organize_settings(body: PatternIn) -> dict:
|
|
1559
|
+
try:
|
|
1560
|
+
save_pattern(pattern_file, body.pattern)
|
|
1561
|
+
except PatternError as exc:
|
|
1562
|
+
raise HTTPException(422, str(exc)) from exc
|
|
1563
|
+
except OSError as exc:
|
|
1564
|
+
raise HTTPException(500, f"Could not save to the config folder: {exc}") from exc
|
|
1565
|
+
return organize_settings()
|
|
1566
|
+
|
|
1567
|
+
@app.post("/api/organize/example")
|
|
1568
|
+
def organize_example(body: PatternIn) -> dict:
|
|
1569
|
+
"""What the pattern makes of a sample track (for the live example while typing)."""
|
|
1570
|
+
try:
|
|
1571
|
+
check_pattern(body.pattern)
|
|
1572
|
+
except PatternError as exc:
|
|
1573
|
+
return {"ok": False, "error": str(exc)}
|
|
1574
|
+
sample = Source("Some Folder/track.flac", {
|
|
1575
|
+
"albumartist": ["Kōsei Mori"], "artist": ["Kōsei Mori"], "album": ["Northern Signal"],
|
|
1576
|
+
"title": ["Harbour Lights"], "tracknumber": ["3/10"], "discnumber": ["2/2"], "date": ["2021-04-09"],
|
|
1577
|
+
"genre": ["Ambient"], "label": ["Low Orbit Records"],
|
|
1578
|
+
}, "flac")
|
|
1579
|
+
return {"ok": True, "single": render(body.pattern, sample, False), "multi": render(body.pattern, sample, True)}
|
|
1580
|
+
|
|
1581
|
+
@app.post("/api/organize/preview")
|
|
1582
|
+
def organize_preview(body: OrganizeIn) -> dict:
|
|
1583
|
+
"""Where each file would go. Nothing is moved."""
|
|
1584
|
+
pattern, moves = organize_plan(body)
|
|
1585
|
+
counts = {k: sum(m.status == k for m in moves) for k in ("move", "same", "conflict", "error")}
|
|
1586
|
+
return {"pattern": pattern, "counts": counts, "extras": sum(len(m.companions) for m in moves),
|
|
1587
|
+
"moves": [m.to_dict() for m in moves]}
|
|
1588
|
+
|
|
1589
|
+
@app.post("/api/organize/apply")
|
|
1590
|
+
def organize_apply(body: OrganizeIn) -> dict:
|
|
1591
|
+
"""Rename and move the files (and their extras). One undoable activity entry."""
|
|
1592
|
+
pattern, moves = organize_plan(body)
|
|
1593
|
+
results = apply_moves(library.resolve, moves)
|
|
1594
|
+
moved = [pair for r in results if r.ok for pair in r.moved]
|
|
1595
|
+
ok = [r for r in results if r.ok]
|
|
1596
|
+
failed = [r for r in results if not r.ok]
|
|
1597
|
+
if results:
|
|
1598
|
+
target = _name(ok[0].dst) if len(ok) == 1 else f"{len(ok)} tracks"
|
|
1599
|
+
message = (f"Organized {target}" if not failed else
|
|
1600
|
+
f"Organized {len(ok)} of {len(results)} tracks" if ok else "Couldn't organize the tracks")
|
|
1601
|
+
activity.add(
|
|
1602
|
+
"organize", message, ok=not failed,
|
|
1603
|
+
files=[r.dst for r in ok] + [r.src for r in failed],
|
|
1604
|
+
changes=[{"key": "location", "old": ok[0].src, "new": ok[0].dst}] if len(ok) == 1 else
|
|
1605
|
+
[{"key": "pattern", "old": "", "new": pattern}],
|
|
1606
|
+
errors=[{"path": r.src, "error": r.error or ""} for r in failed],
|
|
1607
|
+
undo={"type": "moves", "moves": [list(p) for p in moved]} if moved else None,
|
|
1608
|
+
)
|
|
1609
|
+
lib_index.mark_dirty([p for pair in moved for p in pair if not p.startswith("@")]) # the index covers the library only
|
|
1610
|
+
art_cache.clear()
|
|
1611
|
+
return {
|
|
1612
|
+
"moved": len(ok), "failed": len(failed), "extras": len(moved) - len(ok),
|
|
1613
|
+
"results": [{"src": r.src, "dst": r.dst, "ok": r.ok, "error": r.error} for r in results],
|
|
1614
|
+
# Not attempted: the name is taken (maybe a duplicate) or the file couldn't be read.
|
|
1615
|
+
"held": [{"src": m.src, "dst": m.dst, "reason": m.reason} for m in moves if m.status in ("conflict", "error")],
|
|
1616
|
+
}
|
|
1617
|
+
|
|
1618
|
+
# --- First-run setup -----------------------------------------------------------------
|
|
1619
|
+
|
|
1620
|
+
onboarding = OnboardingStore(settings.config_dir / "onboarding.json")
|
|
1621
|
+
|
|
1622
|
+
@app.get("/api/onboarding")
|
|
1623
|
+
def get_onboarding() -> dict:
|
|
1624
|
+
"""Setup steps still to show (new installs: all; after an update: only new ones)."""
|
|
1625
|
+
steps = []
|
|
1626
|
+
if connections.needs_choice:
|
|
1627
|
+
steps.append("connections")
|
|
1628
|
+
steps += [s for s in ("organize", "inbox", "health", "slskd") if s not in onboarding.done]
|
|
1629
|
+
return {"steps": steps}
|
|
1630
|
+
|
|
1631
|
+
@app.post("/api/onboarding/{step}")
|
|
1632
|
+
def finish_onboarding_step(step: str) -> dict:
|
|
1633
|
+
if step == "connections":
|
|
1634
|
+
return get_onboarding() # finished by saving the connections
|
|
1635
|
+
try:
|
|
1636
|
+
onboarding.mark(step)
|
|
1637
|
+
except ValueError as exc:
|
|
1638
|
+
raise HTTPException(404, str(exc)) from exc
|
|
1639
|
+
except OSError as exc:
|
|
1640
|
+
raise HTTPException(500, f"Could not save to the config folder: {exc}") from exc
|
|
1641
|
+
return get_onboarding()
|
|
1642
|
+
|
|
1643
|
+
# --- Import inbox ------------------------------------------------------------------
|
|
1644
|
+
|
|
1645
|
+
inbox = InboxStore(settings.config_dir / "inbox.json", settings.inbox_settle_seconds)
|
|
1646
|
+
inbox_worker: dict = {"thread": None}
|
|
1647
|
+
inbox_wake = threading.Event()
|
|
1648
|
+
|
|
1649
|
+
def inbox_tags(paths: list[str]) -> tuple[str, str]:
|
|
1650
|
+
infos, _, _ = mb_read(paths[:50])
|
|
1651
|
+
return (most_common(f.album for f in infos),
|
|
1652
|
+
most_common(f.albumartist or f.artist for f in infos))
|
|
1653
|
+
|
|
1654
|
+
def inbox_match(key: str) -> None:
|
|
1655
|
+
g = inbox.update(key, status=MATCHING, note="")
|
|
1656
|
+
if g is None:
|
|
1657
|
+
return
|
|
1658
|
+
title, artist = inbox_tags(g.paths)
|
|
1659
|
+
if not connections.enabled("musicbrainz"):
|
|
1660
|
+
inbox.update(key, status=LOCAL, title=title, artist=artist,
|
|
1661
|
+
note="Online lookups are off, so this files by its own tags.")
|
|
1662
|
+
return
|
|
1663
|
+
try:
|
|
1664
|
+
found = mb_search(MBSearchIn(paths=g.paths)) if (title or artist) else {"candidates": []}
|
|
1665
|
+
cands, recordings = found["candidates"], {}
|
|
1666
|
+
sound = connections.enabled("acoustid") and fingerprinter.available and len(g.paths) <= MAX_IDENTIFY
|
|
1667
|
+
if sound and (not cands or cands[0]["score"] < 85):
|
|
1668
|
+
heard = mb_identify(MBTarget(paths=g.paths))
|
|
1669
|
+
if heard["candidates"] and (not cands or heard["candidates"][0]["score"] >= cands[0]["score"]):
|
|
1670
|
+
cands, recordings = heard["candidates"], heard["recordings"]
|
|
1671
|
+
if not cands:
|
|
1672
|
+
inbox.update(key, status=NO_MATCH, title=title, artist=artist,
|
|
1673
|
+
note="Not found on MusicBrainz. Review it to search by hand, or file it by its own tags.")
|
|
1674
|
+
return
|
|
1675
|
+
best = cands[0]
|
|
1676
|
+
proposal = mb_preview(MBProposalIn(paths=g.paths, release=best["id"], recordings=recordings))
|
|
1677
|
+
files = [f for f in proposal["files"] if not f["error"]]
|
|
1678
|
+
exact = (all(f["track"] and f["confidence"] == "high" for f in files)
|
|
1679
|
+
and best.get("track_count") == len(files) and best["score"] >= 85)
|
|
1680
|
+
inbox.update(key, status=READY if exact else REVIEW, title=best["title"], artist=best["artist"],
|
|
1681
|
+
release=best, score=best["score"], recordings=recordings,
|
|
1682
|
+
note="" if exact else "Check the match: not every track lines up for certain.")
|
|
1683
|
+
if exact and inbox_auto(key):
|
|
1684
|
+
inbox_file(key, automatic=True)
|
|
1685
|
+
except HTTPException as exc:
|
|
1686
|
+
inbox.update(key, status=INBOX_ERROR, title=title, artist=artist, note=str(exc.detail))
|
|
1687
|
+
|
|
1688
|
+
def inbox_auto(key: str) -> bool:
|
|
1689
|
+
"""File a confident match without asking? Soulseek downloads follow the
|
|
1690
|
+
Soulseek setting (review by default), everything else the inbox's."""
|
|
1691
|
+
g = inbox.groups.get(key)
|
|
1692
|
+
if g is not None and g.source:
|
|
1693
|
+
return not soulseek_store.settings.review
|
|
1694
|
+
return inbox.settings.auto
|
|
1695
|
+
|
|
1696
|
+
def inbox_file(key: str, release: str | None = None, recordings: dict | None = None, automatic: bool = False) -> dict:
|
|
1697
|
+
g = inbox.groups.get(key)
|
|
1698
|
+
if g is None:
|
|
1699
|
+
raise HTTPException(404, "That album is no longer in the inbox")
|
|
1700
|
+
release = release or (g.release or {}).get("id")
|
|
1701
|
+
notes, moved_to = [], None
|
|
1702
|
+
if release:
|
|
1703
|
+
res = mb_apply(MBProposalIn(paths=g.paths, release=release, recordings=recordings or g.recordings))
|
|
1704
|
+
if res["failed"]:
|
|
1705
|
+
notes.append(f"{res['failed']} track(s) couldn't be tagged")
|
|
1706
|
+
if g.upgrade and not notes:
|
|
1707
|
+
notes.extend(set_aside(g.upgrade))
|
|
1708
|
+
if inbox.settings.organize or g.upgrade:
|
|
1709
|
+
org = organize_apply(OrganizeIn(paths=g.paths))
|
|
1710
|
+
ok = [r for r in org["results"] if r["ok"]]
|
|
1711
|
+
if ok:
|
|
1712
|
+
moved_to = ok[0]["dst"].rsplit("/", 1)[0]
|
|
1713
|
+
stuck = org["failed"] + len(org["held"])
|
|
1714
|
+
if stuck:
|
|
1715
|
+
notes.append(f"{stuck} file(s) couldn't move: a file with that name is already in your library (a duplicate?)")
|
|
1716
|
+
status = FILED if not notes else INBOX_ERROR
|
|
1717
|
+
if automatic:
|
|
1718
|
+
name = " by ".join(x for x in (f"“{g.title}”" if g.title else g.key.rsplit("/", 1)[-1], g.artist) if x)
|
|
1719
|
+
if status == FILED:
|
|
1720
|
+
notices.add("inbox", f"Filed {name}", f"Matched on MusicBrainz and moved to {moved_to or 'your library'}.",
|
|
1721
|
+
{"open": "folder", "path": moved_to} if moved_to else {"open": "inbox"})
|
|
1722
|
+
else:
|
|
1723
|
+
notices.add("inbox", f"Couldn't file {name}", "; ".join(notes), {"open": "inbox"})
|
|
1724
|
+
inbox.update(key, status=status, dest=moved_to or "",
|
|
1725
|
+
note="; ".join(notes) or (f"Filed in {moved_to}" if moved_to else "Tagged"),
|
|
1726
|
+
release=g.release if not release or (g.release or {}).get("id") == release else {"id": release})
|
|
1727
|
+
job = soulseek_store.jobs.get(g.source) if g.source else None
|
|
1728
|
+
if job is not None and status == FILED:
|
|
1729
|
+
soulseek_store.update(job, status=SK_IMPORTED, note=f"Filed in {moved_to}" if moved_to else "Filed")
|
|
1730
|
+
return {"status": status, "moved_to": moved_to, "note": "; ".join(notes)}
|
|
1731
|
+
|
|
1732
|
+
def set_aside(folder: str) -> list[str]:
|
|
1733
|
+
"""An upgrade: move the album it replaces out of the library, into the
|
|
1734
|
+
config folder ("@replaced"), as one undoable activity entry. Returns problems."""
|
|
1735
|
+
try:
|
|
1736
|
+
top = library.resolve(folder)
|
|
1737
|
+
except LibraryPathError as exc:
|
|
1738
|
+
return [str(exc)]
|
|
1739
|
+
if folder.startswith("@") or not folder or not top.is_dir():
|
|
1740
|
+
return [] # nothing there (any more): the download is simply new
|
|
1741
|
+
stamp = time.strftime("%Y%m%d-%H%M%S")
|
|
1742
|
+
moves = []
|
|
1743
|
+
for dirpath, _, names in os.walk(top):
|
|
1744
|
+
for name in names:
|
|
1745
|
+
rel = library.relative(Path(dirpath) / name)
|
|
1746
|
+
moves.append(Move(rel, f"@replaced/{stamp}/{rel}", "move"))
|
|
1747
|
+
results = apply_moves(library.resolve, moves)
|
|
1748
|
+
moved = [pair for r in results if r.ok for pair in r.moved]
|
|
1749
|
+
failed = [r for r in results if not r.ok]
|
|
1750
|
+
if moved:
|
|
1751
|
+
activity.add("organize", f"Set aside {_name(folder)} for its upgrade", ok=not failed,
|
|
1752
|
+
files=[a for a, _ in moved], changes=[{"key": "location", "old": folder, "new": "(replaced)"}],
|
|
1753
|
+
errors=[{"path": r.src, "error": r.error or ""} for r in failed],
|
|
1754
|
+
undo={"type": "moves", "moves": [list(p) for p in moved]})
|
|
1755
|
+
lib_index.mark_dirty([a for a, _ in moved])
|
|
1756
|
+
art_cache.clear()
|
|
1757
|
+
return [f"{len(failed)} file(s) of the old album couldn't be moved aside"] if failed else []
|
|
1758
|
+
|
|
1759
|
+
def inbox_run() -> None:
|
|
1760
|
+
done: list[str] = []
|
|
1761
|
+
while True:
|
|
1762
|
+
with inbox.lock:
|
|
1763
|
+
nxt = next((g.key for g in inbox.groups.values() if g.status == WAITING), None)
|
|
1764
|
+
if nxt is None:
|
|
1765
|
+
inbox_summary(done)
|
|
1766
|
+
return
|
|
1767
|
+
done.append(nxt)
|
|
1768
|
+
try:
|
|
1769
|
+
inbox_match(nxt)
|
|
1770
|
+
soulseek_matched(nxt)
|
|
1771
|
+
except Exception as exc: # never let one album stop the queue
|
|
1772
|
+
log.warning("Inbox: couldn't look up %s: %s", nxt, exc)
|
|
1773
|
+
inbox.update(nxt, status=INBOX_ERROR, note="Something went wrong looking this up")
|
|
1774
|
+
|
|
1775
|
+
def inbox_summary(keys: list[str]) -> None:
|
|
1776
|
+
"""One notification when a round of lookups ends (auto-filed albums have their own)."""
|
|
1777
|
+
groups = [g for k in keys if (g := inbox.groups.get(k))]
|
|
1778
|
+
ready = [g for g in groups if g.status in (READY, LOCAL)]
|
|
1779
|
+
look = [g for g in groups if g.status in (REVIEW, NO_MATCH, INBOX_ERROR)]
|
|
1780
|
+
if not ready and not look:
|
|
1781
|
+
return
|
|
1782
|
+
parts = []
|
|
1783
|
+
if ready:
|
|
1784
|
+
parts.append(f"{len(ready)} ready to file")
|
|
1785
|
+
if look:
|
|
1786
|
+
parts.append(f"{len(look)} need{'s' if len(look) == 1 else ''} a look")
|
|
1787
|
+
names = ", ".join(g.title or g.key.rsplit("/", 1)[-1] for g in (ready + look)[:3])
|
|
1788
|
+
more = len(ready) + len(look) - 3
|
|
1789
|
+
notices.add("inbox", f"Inbox: {' · '.join(parts)}", names + (f" and {more} more" if more > 0 else ""),
|
|
1790
|
+
{"open": "inbox"})
|
|
1791
|
+
|
|
1792
|
+
def inbox_start() -> None:
|
|
1793
|
+
t = inbox_worker["thread"]
|
|
1794
|
+
if t is None or not t.is_alive():
|
|
1795
|
+
inbox_worker["thread"] = threading.Thread(target=inbox_run, name="codetta-inbox", daemon=True)
|
|
1796
|
+
inbox_worker["thread"].start()
|
|
1797
|
+
|
|
1798
|
+
def inbox_watch() -> None:
|
|
1799
|
+
last_prune = time.time()
|
|
1800
|
+
while not inbox_wake.wait(15 * 60):
|
|
1801
|
+
if time.time() - last_prune > 86400:
|
|
1802
|
+
last_prune = time.time()
|
|
1803
|
+
prune_replaced(settings.config_dir / "replaced")
|
|
1804
|
+
if inbox.settings.watch and inbox.settings.folder and library.exists():
|
|
1805
|
+
try:
|
|
1806
|
+
inbox.sync(library)
|
|
1807
|
+
inbox_start()
|
|
1808
|
+
except (OSError, LibraryPathError) as exc:
|
|
1809
|
+
log.warning("Inbox check failed: %s", exc)
|
|
1810
|
+
|
|
1811
|
+
app.state.inbox_watch = inbox_watch # started in lifespan
|
|
1812
|
+
|
|
1813
|
+
sk_transfers: dict = {"at": 0.0, "list": []}
|
|
1814
|
+
|
|
1815
|
+
def inbox_transfers() -> list[dict]:
|
|
1816
|
+
"""slskd's downloads, while something in the inbox is still arriving (for its progress bar)."""
|
|
1817
|
+
if not any(g.status == DOWNLOADING for g in list(inbox.groups.values())):
|
|
1818
|
+
return []
|
|
1819
|
+
if not (connections.enabled("slskd") and soulseek_store.configured):
|
|
1820
|
+
return []
|
|
1821
|
+
if time.time() - sk_transfers["at"] > 3:
|
|
1822
|
+
try:
|
|
1823
|
+
sk_transfers["list"] = soulseek.client().all_downloads()
|
|
1824
|
+
except SlskdError:
|
|
1825
|
+
sk_transfers["list"] = []
|
|
1826
|
+
sk_transfers["at"] = time.time()
|
|
1827
|
+
return sk_transfers["list"]
|
|
1828
|
+
|
|
1829
|
+
def inbox_out() -> dict:
|
|
1830
|
+
transfers = inbox_transfers()
|
|
1831
|
+
with inbox.lock:
|
|
1832
|
+
groups = sorted(inbox.groups.values(), key=lambda g: (g.status == FILED, -g.updated if g.status == FILED else 0, g.key))
|
|
1833
|
+
counts = {}
|
|
1834
|
+
for g in groups:
|
|
1835
|
+
counts[g.status] = counts.get(g.status, 0) + 1
|
|
1836
|
+
folder = inbox.settings.folder
|
|
1837
|
+
running = bool(inbox_worker["thread"] and inbox_worker["thread"].is_alive())
|
|
1838
|
+
try:
|
|
1839
|
+
exists = bool(folder) and library.resolve(folder).is_dir()
|
|
1840
|
+
except LibraryPathError:
|
|
1841
|
+
exists = False
|
|
1842
|
+
return {
|
|
1843
|
+
# A downloads folder mounted outside the music folder (e.g. slskd's), offered first.
|
|
1844
|
+
"external": {"available": library.inbox_available(),
|
|
1845
|
+
"path": str(settings.inbox_dir) if settings.inbox_dir else None},
|
|
1846
|
+
"downloading": sum(g.status == DOWNLOADING for g in groups),
|
|
1847
|
+
"settings": {"folder": folder, "auto": inbox.settings.auto, "organize": inbox.settings.organize,
|
|
1848
|
+
"watch": inbox.settings.watch},
|
|
1849
|
+
"folder_exists": exists,
|
|
1850
|
+
"online": connections.enabled("musicbrainz"),
|
|
1851
|
+
"running": running, "counts": counts,
|
|
1852
|
+
"groups": [{"key": g.key, "files": len(g.paths), "paths": g.paths[:1000], "status": g.status,
|
|
1853
|
+
"title": g.title, "artist": g.artist, "release": g.release, "score": g.score,
|
|
1854
|
+
"recordings": g.recordings, "note": g.note, "dest": g.dest,
|
|
1855
|
+
"transfer": folder_progress(transfers, {p.rsplit("/", 1)[-1] for p in g.paths})
|
|
1856
|
+
if transfers and g.status == DOWNLOADING else None} for g in groups],
|
|
1857
|
+
}
|
|
1858
|
+
|
|
1859
|
+
@app.get("/api/inbox")
|
|
1860
|
+
def get_inbox() -> dict:
|
|
1861
|
+
"""The inbox: re-read its folder and look up anything new (in the background)."""
|
|
1862
|
+
require_library()
|
|
1863
|
+
if inbox.settings.folder:
|
|
1864
|
+
try:
|
|
1865
|
+
inbox.sync(library)
|
|
1866
|
+
except (OSError, LibraryPathError) as exc:
|
|
1867
|
+
raise HTTPException(500, f"Couldn't read the inbox folder: {exc}") from exc
|
|
1868
|
+
inbox_start()
|
|
1869
|
+
return inbox_out()
|
|
1870
|
+
|
|
1871
|
+
@app.put("/api/inbox/settings")
|
|
1872
|
+
def put_inbox_settings(body: InboxSettingsIn) -> dict:
|
|
1873
|
+
require_library()
|
|
1874
|
+
folder = body.folder.strip().strip("/")
|
|
1875
|
+
if folder.startswith("@") and folder != INBOX_ALIAS and not folder.startswith(INBOX_ALIAS + "/"):
|
|
1876
|
+
raise HTTPException(422, "The inbox can be your downloads folder or a folder in your music folder.")
|
|
1877
|
+
if not folder:
|
|
1878
|
+
raise HTTPException(422, "Choose your downloads folder, or a folder inside your music folder (not the whole library).")
|
|
1879
|
+
if not library.resolve(folder).is_dir():
|
|
1880
|
+
raise HTTPException(422, "The downloads folder isn't mounted (see CODETTA_INBOX_DIR)." if folder.startswith("@")
|
|
1881
|
+
else f"There's no folder called “{folder}” in your music folder.")
|
|
1882
|
+
with inbox.lock:
|
|
1883
|
+
if folder != inbox.settings.folder:
|
|
1884
|
+
inbox.groups.clear()
|
|
1885
|
+
inbox.settings.folder, inbox.settings.auto = folder, body.auto
|
|
1886
|
+
inbox.settings.organize, inbox.settings.watch = body.organize, body.watch
|
|
1887
|
+
try:
|
|
1888
|
+
inbox.save()
|
|
1889
|
+
except OSError as exc:
|
|
1890
|
+
raise HTTPException(500, f"Could not save to the config folder: {exc}") from exc
|
|
1891
|
+
return get_inbox()
|
|
1892
|
+
|
|
1893
|
+
@app.post("/api/inbox/accept")
|
|
1894
|
+
def inbox_file_route(body: InboxActionIn) -> dict:
|
|
1895
|
+
"""File one album: write its MusicBrainz tags (if matched) and organize it into the library."""
|
|
1896
|
+
require_library()
|
|
1897
|
+
release = None
|
|
1898
|
+
if body.release:
|
|
1899
|
+
release = parse_release_id(body.release)
|
|
1900
|
+
if not release:
|
|
1901
|
+
raise HTTPException(422, "That isn't a MusicBrainz release.")
|
|
1902
|
+
result = inbox_file(body.key, release, body.recordings or None)
|
|
1903
|
+
return {**result, "inbox": inbox_out()}
|
|
1904
|
+
|
|
1905
|
+
@app.post("/api/inbox/accept-ready")
|
|
1906
|
+
def inbox_file_ready() -> dict:
|
|
1907
|
+
"""File every confident match in one go."""
|
|
1908
|
+
require_library()
|
|
1909
|
+
keys = [g.key for g in list(inbox.groups.values()) if g.status == READY]
|
|
1910
|
+
filed = sum(inbox_file(k)["status"] == FILED for k in keys)
|
|
1911
|
+
return {"filed": filed, "total": len(keys), "inbox": inbox_out()}
|
|
1912
|
+
|
|
1913
|
+
@app.post("/api/inbox/skip")
|
|
1914
|
+
def inbox_skip(body: InboxActionIn) -> dict:
|
|
1915
|
+
if inbox.update(body.key, status=SKIPPED, note="Skipped: left where it is") is None:
|
|
1916
|
+
raise HTTPException(404, "That album is no longer in the inbox")
|
|
1917
|
+
return inbox_out()
|
|
1918
|
+
|
|
1919
|
+
@app.post("/api/inbox/rematch")
|
|
1920
|
+
def inbox_rematch(body: InboxActionIn) -> dict:
|
|
1921
|
+
if inbox.update(body.key, status=WAITING, note="", release=None, score=None) is None:
|
|
1922
|
+
raise HTTPException(404, "That album is no longer in the inbox")
|
|
1923
|
+
inbox_start()
|
|
1924
|
+
return inbox_out()
|
|
1925
|
+
|
|
1926
|
+
# --- Soulseek through slskd -------------------------------------------------------------
|
|
1927
|
+
|
|
1928
|
+
soulseek_store = SoulseekStore(settings.config_dir / "slskd.json", settings.slskd_url, settings.slskd_api_key)
|
|
1929
|
+
soulseek = Soulseek(soulseek_store, request=slskd_request or slskd_http_request,
|
|
1930
|
+
notify=lambda title, body, action: notices.add("soulseek", title, body, action))
|
|
1931
|
+
sk_worker: dict = {"thread": None, "check": None}
|
|
1932
|
+
sk_wake = threading.Event()
|
|
1933
|
+
|
|
1934
|
+
def sk_ready() -> None:
|
|
1935
|
+
if not connections.enabled("slskd"):
|
|
1936
|
+
raise HTTPException(403, "Soulseek is off. Turn it on in Account → Connections.")
|
|
1937
|
+
if not soulseek_store.configured:
|
|
1938
|
+
raise HTTPException(409, "Connect your slskd first: Account → Connections → Soulseek.")
|
|
1939
|
+
|
|
1940
|
+
def sk_job(job_id: str):
|
|
1941
|
+
if not re.fullmatch(r"[0-9a-f-]{32,36}", job_id or ""):
|
|
1942
|
+
raise HTTPException(404, "That Soulseek request is gone")
|
|
1943
|
+
job = soulseek_store.jobs.get(job_id)
|
|
1944
|
+
if job is None:
|
|
1945
|
+
raise HTTPException(404, "That Soulseek request is gone")
|
|
1946
|
+
return job
|
|
1947
|
+
|
|
1948
|
+
def sk_locate(job) -> str | None:
|
|
1949
|
+
"""Find a finished download in the inbox (by its file names) and hand it over."""
|
|
1950
|
+
names = set(sk_basenames(job))
|
|
1951
|
+
if not names or not inbox.settings.folder:
|
|
1952
|
+
return None
|
|
1953
|
+
best = None
|
|
1954
|
+
for g in inbox.sync(library):
|
|
1955
|
+
if g.status == FILED or (g.source and g.source != job.id):
|
|
1956
|
+
continue # filed already, or another request's download
|
|
1957
|
+
hit = len(names & {p.rsplit("/", 1)[-1] for p in g.paths})
|
|
1958
|
+
# Most of what was asked for, and most of what's there (an older album that happens
|
|
1959
|
+
# to share names like "01.flac" must never be taken for it: blocklisting deletes it).
|
|
1960
|
+
if hit < max(1, int(len(names) * 0.8)) or hit < int(len(g.paths) * 0.8):
|
|
1961
|
+
continue
|
|
1962
|
+
if inbox_signature(library, g.paths)[1] < job.created - 60:
|
|
1963
|
+
continue # these files were there before the request
|
|
1964
|
+
if best is None or hit > best[0]:
|
|
1965
|
+
best = (hit, g.key)
|
|
1966
|
+
if best is None:
|
|
1967
|
+
return None
|
|
1968
|
+
# slskd says it's complete, so no need to wait for the files to settle.
|
|
1969
|
+
inbox.update(best[1], source=job.id, upgrade=job.upgrade, status=WAITING, note="", release=None, score=None)
|
|
1970
|
+
inbox_start()
|
|
1971
|
+
return best[1]
|
|
1972
|
+
|
|
1973
|
+
def soulseek_matched(key: str) -> None:
|
|
1974
|
+
"""A Soulseek download has been matched: ask for a review (unless it filed itself)."""
|
|
1975
|
+
g = inbox.groups.get(key)
|
|
1976
|
+
job = soulseek_store.jobs.get(g.source) if g and g.source else None
|
|
1977
|
+
if job is None or g.status in (FILED, MATCHING, WAITING):
|
|
1978
|
+
return
|
|
1979
|
+
name = g.title or job.query
|
|
1980
|
+
soulseek_store.update(job, note="Downloaded: have a look")
|
|
1981
|
+
notices.add("soulseek", f"Soulseek: “{name}” is here",
|
|
1982
|
+
f"{(job.current or {}).get('quality', '')} from {(job.current or {}).get('username', '')}. "
|
|
1983
|
+
"Import it, or blocklist it and try the next one.",
|
|
1984
|
+
{"open": "soulseek", "job": job.id}, key=f"sk-review:{job.id}:{job.pick}")
|
|
1985
|
+
|
|
1986
|
+
def sk_run() -> None:
|
|
1987
|
+
while soulseek_store.active():
|
|
1988
|
+
try:
|
|
1989
|
+
soulseek.tick(sk_locate)
|
|
1990
|
+
except Exception as exc: # keep going whatever one job does
|
|
1991
|
+
log.warning("Soulseek: %s", exc)
|
|
1992
|
+
if sk_wake.wait(settings.slskd_poll_seconds):
|
|
1993
|
+
return
|
|
1994
|
+
|
|
1995
|
+
def sk_start() -> None:
|
|
1996
|
+
t = sk_worker["thread"]
|
|
1997
|
+
if soulseek_store.active() and (t is None or not t.is_alive()):
|
|
1998
|
+
sk_wake.clear()
|
|
1999
|
+
sk_worker["thread"] = threading.Thread(target=sk_run, name="codetta-soulseek", daemon=True)
|
|
2000
|
+
sk_worker["thread"].start()
|
|
2001
|
+
|
|
2002
|
+
app.state.soulseek_start = sk_start
|
|
2003
|
+
app.state.soulseek_stop = sk_wake.set
|
|
2004
|
+
|
|
2005
|
+
def sk_drop_download(job) -> None:
|
|
2006
|
+
"""Remove what a job brought into the inbox (when it's blocklisted or swapped)."""
|
|
2007
|
+
g = inbox.groups.get(job.inbox_key) if job.inbox_key else None
|
|
2008
|
+
if g is None or g.status == FILED:
|
|
2009
|
+
return
|
|
2010
|
+
folders = []
|
|
2011
|
+
for rel in g.paths:
|
|
2012
|
+
if not rel.startswith(inbox.settings.folder + "/"):
|
|
2013
|
+
continue # only ever inside the inbox
|
|
2014
|
+
try:
|
|
2015
|
+
library.resolve(rel).unlink(missing_ok=True)
|
|
2016
|
+
folders.append(rel.rsplit("/", 1)[0])
|
|
2017
|
+
except (OSError, LibraryPathError):
|
|
2018
|
+
pass
|
|
2019
|
+
if g.key != inbox.settings.folder and g.key.startswith(inbox.settings.folder + "/"):
|
|
2020
|
+
try: # the folder slskd made: its leftovers (cover.jpg, .nfo...) go too
|
|
2021
|
+
top = library.resolve(g.key)
|
|
2022
|
+
for p in sorted(top.rglob("*"), key=lambda p: -len(p.parts)):
|
|
2023
|
+
p.unlink() if p.is_file() or p.is_symlink() else p.rmdir()
|
|
2024
|
+
top.rmdir()
|
|
2025
|
+
except (OSError, LibraryPathError):
|
|
2026
|
+
pass
|
|
2027
|
+
remove_empty_dirs(library.resolve, folders)
|
|
2028
|
+
with inbox.lock:
|
|
2029
|
+
inbox.groups.pop(g.key, None)
|
|
2030
|
+
inbox.save()
|
|
2031
|
+
|
|
2032
|
+
def sk_job_out(job) -> dict:
|
|
2033
|
+
g = inbox.groups.get(job.inbox_key) if job.inbox_key else None
|
|
2034
|
+
def cand(i, c):
|
|
2035
|
+
return {k: c[k] for k in ("username", "folder", "name", "tracks", "size", "quality", "lossless",
|
|
2036
|
+
"free_slot", "speed", "queue", "score")} | {"index": i, "tried": i in job.tried}
|
|
2037
|
+
cur = job.current
|
|
2038
|
+
return {
|
|
2039
|
+
"id": job.id, "query": job.query, "status": job.status, "note": job.note, "progress": job.progress,
|
|
2040
|
+
"eta": job.eta,
|
|
2041
|
+
"created": job.created, "updated": job.updated, "upgrade": job.upgrade,
|
|
2042
|
+
"current": cand(job.pick, cur) | {"files": [split_name(f["filename"]) for f in cur.get("files", [])]} if cur else None,
|
|
2043
|
+
"candidates": [cand(i, c) for i, c in enumerate(job.candidates)],
|
|
2044
|
+
"inbox": {"key": g.key, "status": g.status, "title": g.title, "artist": g.artist, "release": g.release,
|
|
2045
|
+
"score": g.score, "note": g.note, "paths": g.paths[:200], "recordings": g.recordings,
|
|
2046
|
+
"dest": g.dest}
|
|
2047
|
+
if g else None,
|
|
2048
|
+
}
|
|
2049
|
+
|
|
2050
|
+
def split_name(remote: str) -> str:
|
|
2051
|
+
return remote.replace("\\", "/").rsplit("/", 1)[-1]
|
|
2052
|
+
|
|
2053
|
+
def soulseek_out(check_result: dict | None = None) -> dict:
|
|
2054
|
+
with soulseek_store.lock:
|
|
2055
|
+
jobs = sorted(soulseek_store.jobs.values(), key=lambda j: -j.created)
|
|
2056
|
+
st = soulseek_store.settings
|
|
2057
|
+
return {
|
|
2058
|
+
"enabled": connections.enabled("slskd"),
|
|
2059
|
+
"configured": soulseek_store.configured,
|
|
2060
|
+
"url": soulseek_store.url, "has_key": bool(soulseek_store.api_key),
|
|
2061
|
+
"locked": {"url": soulseek_store.env_url is not None, "api_key": soulseek_store.env_key is not None},
|
|
2062
|
+
"settings": {"review": st.review, "lossless_only": st.lossless_only, "min_bitrate": st.min_bitrate,
|
|
2063
|
+
"search_seconds": st.search_seconds},
|
|
2064
|
+
"inbox": {"folder": inbox.settings.folder, "external": library.inbox_available()},
|
|
2065
|
+
"blocked": len(soulseek_store.blocked),
|
|
2066
|
+
"check": check_result if check_result is not None else sk_worker["check"],
|
|
2067
|
+
"jobs": [sk_job_out(j) for j in jobs[:50]],
|
|
2068
|
+
}
|
|
2069
|
+
|
|
2070
|
+
def sk_check() -> dict:
|
|
2071
|
+
if not soulseek_store.configured:
|
|
2072
|
+
return {"ok": False, "error": "Add your slskd's address and an API key."}
|
|
2073
|
+
result = slskd_check(soulseek.client())
|
|
2074
|
+
sk_worker["check"] = result
|
|
2075
|
+
return result
|
|
2076
|
+
|
|
2077
|
+
@app.get("/api/slskd")
|
|
2078
|
+
def get_soulseek() -> dict:
|
|
2079
|
+
"""Soulseek: connection details (never the API key), settings and requests."""
|
|
2080
|
+
return soulseek_out()
|
|
2081
|
+
|
|
2082
|
+
@app.put("/api/slskd/settings")
|
|
2083
|
+
def put_soulseek_settings(body: SlskdSettingsIn) -> dict:
|
|
2084
|
+
url = slskd_clean_url(body.url)
|
|
2085
|
+
if url:
|
|
2086
|
+
parts = urlsplit(url)
|
|
2087
|
+
if (parts.scheme not in ("http", "https") or not parts.hostname or parts.username or parts.password
|
|
2088
|
+
or any(c.isspace() for c in url) or parts.query or parts.fragment):
|
|
2089
|
+
raise HTTPException(422, "slskd's address should look like http://slskd:5030 or http://192.168.1.50:5030")
|
|
2090
|
+
try:
|
|
2091
|
+
parts.port # a port that isn't a number raises
|
|
2092
|
+
except ValueError:
|
|
2093
|
+
raise HTTPException(422, "The port in slskd's address should be a number, like :5030") from None
|
|
2094
|
+
if body.api_key is not None and body.api_key.strip():
|
|
2095
|
+
key = body.api_key.strip()
|
|
2096
|
+
if any(c.isspace() for c in key) or not key.isprintable() or len(key) < 8:
|
|
2097
|
+
raise HTTPException(422, "That doesn't look like an slskd API key (at least 8 characters, no spaces).")
|
|
2098
|
+
with soulseek_store.lock:
|
|
2099
|
+
st = soulseek_store.settings
|
|
2100
|
+
if soulseek_store.env_url is None:
|
|
2101
|
+
st.url = url
|
|
2102
|
+
if body.api_key is not None and soulseek_store.env_key is None:
|
|
2103
|
+
st.api_key = body.api_key.strip()
|
|
2104
|
+
st.review, st.lossless_only = body.review, body.lossless_only
|
|
2105
|
+
st.min_bitrate, st.search_seconds = body.min_bitrate, body.search_seconds
|
|
2106
|
+
try:
|
|
2107
|
+
soulseek_store.save()
|
|
2108
|
+
except OSError as exc:
|
|
2109
|
+
raise HTTPException(500, f"Could not save to the config folder: {exc}") from exc
|
|
2110
|
+
return soulseek_out(sk_check() if soulseek_store.configured else None)
|
|
2111
|
+
|
|
2112
|
+
@app.post("/api/slskd/test")
|
|
2113
|
+
def test_soulseek() -> dict:
|
|
2114
|
+
return soulseek_out(sk_check())
|
|
2115
|
+
|
|
2116
|
+
@app.post("/api/slskd/search")
|
|
2117
|
+
def soulseek_search(body: SlskdSearchIn) -> dict:
|
|
2118
|
+
"""Ask slskd to search; the best match is downloaded into the inbox."""
|
|
2119
|
+
sk_ready()
|
|
2120
|
+
if not inbox.settings.folder:
|
|
2121
|
+
raise HTTPException(409, "Set up the inbox first: Soulseek downloads arrive there.")
|
|
2122
|
+
upgrade = body.upgrade.strip().strip("/")
|
|
2123
|
+
if upgrade:
|
|
2124
|
+
try:
|
|
2125
|
+
if upgrade.startswith("@") or not library.resolve(upgrade).is_dir():
|
|
2126
|
+
raise HTTPException(422, "That album folder isn't in your library.")
|
|
2127
|
+
except LibraryPathError as exc:
|
|
2128
|
+
raise HTTPException(422, str(exc)) from exc
|
|
2129
|
+
try:
|
|
2130
|
+
job = soulseek.search(body.query, upgrade)
|
|
2131
|
+
except SlskdError as exc:
|
|
2132
|
+
raise HTTPException(502, str(exc)) from exc
|
|
2133
|
+
sk_start()
|
|
2134
|
+
return {"job": sk_job_out(job), **soulseek_out()}
|
|
2135
|
+
|
|
2136
|
+
@app.post("/api/slskd/jobs/{job_id}/next")
|
|
2137
|
+
def soulseek_next(job_id: str, body: SlskdNextIn) -> dict:
|
|
2138
|
+
"""Not this one: (blocklist it and) download the next best candidate."""
|
|
2139
|
+
sk_ready()
|
|
2140
|
+
job = sk_job(job_id)
|
|
2141
|
+
cur = job.current
|
|
2142
|
+
if cur is None:
|
|
2143
|
+
raise HTTPException(409, "Nothing has been downloaded for this request yet.")
|
|
2144
|
+
if body.block:
|
|
2145
|
+
soulseek.blocklist(cur["username"], cur["folder"])
|
|
2146
|
+
try:
|
|
2147
|
+
if job.status == SK_DOWNLOADING:
|
|
2148
|
+
soulseek.cancel_transfers(job)
|
|
2149
|
+
sk_drop_download(job)
|
|
2150
|
+
soulseek.next_candidate(job, f"Blocklisted {cur['name']} from {cur['username']}." if body.block else "")
|
|
2151
|
+
except SlskdError as exc:
|
|
2152
|
+
raise HTTPException(502, str(exc)) from exc
|
|
2153
|
+
sk_start()
|
|
2154
|
+
return soulseek_out()
|
|
2155
|
+
|
|
2156
|
+
@app.post("/api/slskd/jobs/{job_id}/pick")
|
|
2157
|
+
def soulseek_pick(job_id: str, body: SlskdPickIn) -> dict:
|
|
2158
|
+
"""Download a candidate of your choosing instead."""
|
|
2159
|
+
sk_ready()
|
|
2160
|
+
job = sk_job(job_id)
|
|
2161
|
+
if body.index >= len(job.candidates):
|
|
2162
|
+
raise HTTPException(404, "That result is gone")
|
|
2163
|
+
try:
|
|
2164
|
+
if job.status == SK_DOWNLOADING:
|
|
2165
|
+
soulseek.cancel_transfers(job)
|
|
2166
|
+
if job.status == SK_ARRIVED:
|
|
2167
|
+
sk_drop_download(job)
|
|
2168
|
+
soulseek.start(job, body.index)
|
|
2169
|
+
except SlskdError as exc:
|
|
2170
|
+
raise HTTPException(502, str(exc)) from exc
|
|
2171
|
+
sk_start()
|
|
2172
|
+
return soulseek_out()
|
|
2173
|
+
|
|
2174
|
+
@app.post("/api/slskd/jobs/{job_id}/import")
|
|
2175
|
+
def soulseek_import(job_id: str, body: SlskdImportIn | None = None) -> dict:
|
|
2176
|
+
"""Keep it: file the download into the library (replacing the album it upgrades)."""
|
|
2177
|
+
require_library()
|
|
2178
|
+
job = sk_job(job_id)
|
|
2179
|
+
if job.status != SK_ARRIVED or job.inbox_key not in inbox.groups:
|
|
2180
|
+
raise HTTPException(409, "This download isn't in the inbox (yet).")
|
|
2181
|
+
release = None
|
|
2182
|
+
if body and body.release:
|
|
2183
|
+
release = parse_release_id(body.release)
|
|
2184
|
+
if not release:
|
|
2185
|
+
raise HTTPException(422, "That isn't a MusicBrainz release.")
|
|
2186
|
+
result = inbox_file(job.inbox_key, release, (body.recordings if body else None) or None)
|
|
2187
|
+
return {**result, **soulseek_out()}
|
|
2188
|
+
|
|
2189
|
+
@app.post("/api/slskd/jobs/{job_id}/cancel")
|
|
2190
|
+
def soulseek_cancel(job_id: str) -> dict:
|
|
2191
|
+
job = sk_job(job_id)
|
|
2192
|
+
if job.status == SK_DOWNLOADING and soulseek_store.configured:
|
|
2193
|
+
try:
|
|
2194
|
+
soulseek.cancel_transfers(job)
|
|
2195
|
+
except SlskdError:
|
|
2196
|
+
pass
|
|
2197
|
+
if job.status in (SK_DOWNLOADING, "searching", "fetched"):
|
|
2198
|
+
soulseek_store.update(job, status=SK_CANCELLED, note="Cancelled")
|
|
2199
|
+
return soulseek_out()
|
|
2200
|
+
|
|
2201
|
+
@app.delete("/api/slskd/jobs/{job_id}")
|
|
2202
|
+
def soulseek_forget(job_id: str) -> dict:
|
|
2203
|
+
"""Take a finished request off the list (the files stay wherever they are)."""
|
|
2204
|
+
job = sk_job(job_id)
|
|
2205
|
+
if job.status not in (SK_IMPORTED, SK_NOTHING, SK_FAILED, SK_CANCELLED, SK_ARRIVED):
|
|
2206
|
+
raise HTTPException(409, "Cancel it first.")
|
|
2207
|
+
with soulseek_store.lock:
|
|
2208
|
+
soulseek_store.jobs.pop(job.id, None)
|
|
2209
|
+
soulseek_store.save()
|
|
2210
|
+
return soulseek_out()
|
|
2211
|
+
|
|
2212
|
+
@app.delete("/api/slskd/blocklist")
|
|
2213
|
+
def soulseek_clear_blocklist() -> dict:
|
|
2214
|
+
with soulseek_store.lock:
|
|
2215
|
+
soulseek_store.blocked.clear()
|
|
2216
|
+
soulseek_store.save()
|
|
2217
|
+
return soulseek_out()
|
|
2218
|
+
|
|
2219
|
+
# --- Explore MusicBrainz (the !mb bang) -------------------------------------------------------
|
|
2220
|
+
|
|
2221
|
+
owned_cache: dict = {"key": None, "albums": {}}
|
|
2222
|
+
|
|
2223
|
+
def owned_albums() -> dict[str, dict[str, str]]:
|
|
2224
|
+
"""Albums in the library: artist (folded) -> album name (folded, also without
|
|
2225
|
+
"(Deluxe)"-style suffixes) -> folder. From the index, rebuilt when it changes."""
|
|
2226
|
+
key = lib_index.version
|
|
2227
|
+
if owned_cache["key"] != key:
|
|
2228
|
+
albums: dict[str, dict[str, str]] = {}
|
|
2229
|
+
for path, track in lib_index.iter_tracks():
|
|
2230
|
+
tags = track.get("tags") or {}
|
|
2231
|
+
album = next((v for v in tags.get("album", []) if v.strip()), "")
|
|
2232
|
+
who = next((v for v in tags.get("albumartist", []) + tags.get("artist", []) if v.strip()), "")
|
|
2233
|
+
if not album or not who:
|
|
2234
|
+
continue
|
|
2235
|
+
folder = path.rsplit("/", 1)[0] if "/" in path else ""
|
|
2236
|
+
names = albums.setdefault(health_fold(base_artist(who)), {})
|
|
2237
|
+
for name in {health_fold(album), health_fold(EDITION_RE.sub("", album))}:
|
|
2238
|
+
names.setdefault(name, folder)
|
|
2239
|
+
owned_cache.update(key=key, albums=albums)
|
|
2240
|
+
return owned_cache["albums"]
|
|
2241
|
+
|
|
2242
|
+
def owned_folder(artist: str, title: str) -> str | None:
|
|
2243
|
+
names = owned_albums().get(health_fold(base_artist(artist)))
|
|
2244
|
+
if not names:
|
|
2245
|
+
return None
|
|
2246
|
+
return names.get(health_fold(title)) or names.get(health_fold(EDITION_RE.sub("", title)))
|
|
2247
|
+
|
|
2248
|
+
def with_owned(g: dict) -> dict:
|
|
2249
|
+
return {**g, "in_library": owned_folder(g["artist"], g["title"]) if g["artist"] else None}
|
|
2250
|
+
|
|
2251
|
+
def explore(call, mbid: str | None = None):
|
|
2252
|
+
if mbid is not None and not MBID_RE.match(mbid):
|
|
2253
|
+
raise HTTPException(422, "That isn't a MusicBrainz ID.")
|
|
2254
|
+
require_connection("musicbrainz")
|
|
2255
|
+
try:
|
|
2256
|
+
return call()
|
|
2257
|
+
except ProviderError as exc:
|
|
2258
|
+
raise HTTPException(502, str(exc)) from exc
|
|
2259
|
+
|
|
2260
|
+
@app.get("/api/mb/search")
|
|
2261
|
+
def mb_explore_search(q: str = Query(..., min_length=1, max_length=200)) -> dict:
|
|
2262
|
+
"""Artists and releases on MusicBrainz matching ``q`` (two requests: about two seconds)."""
|
|
2263
|
+
q = " ".join(q.split())
|
|
2264
|
+
if sum(c.isalnum() for c in q) < 2:
|
|
2265
|
+
raise HTTPException(422, "Type at least two letters or numbers to search MusicBrainz.")
|
|
2266
|
+
def run():
|
|
2267
|
+
artists = [artist_summary(a) for a in mb.search_artists(q)]
|
|
2268
|
+
groups = [with_owned(group_summary(g)) for g in mb.search_release_groups(q)]
|
|
2269
|
+
return {"query": q, "artists": [a for a in artists if (a["score"] or 0) >= 60][:8],
|
|
2270
|
+
"releases": [g for g in groups if (g["score"] or 0) >= 60][:15]}
|
|
2271
|
+
return explore(run)
|
|
2272
|
+
|
|
2273
|
+
@app.get("/api/mb/artist/{mbid}")
|
|
2274
|
+
def mb_explore_artist(mbid: str) -> dict:
|
|
2275
|
+
"""An artist: who they are, links, and their albums, EPs and singles."""
|
|
2276
|
+
def run():
|
|
2277
|
+
a = mb.artist(mbid)
|
|
2278
|
+
groups = [group_summary(g) for g in mb.artist_release_groups(mbid)]
|
|
2279
|
+
name = a.get("name") or ""
|
|
2280
|
+
for g in groups:
|
|
2281
|
+
g["artist"] = g["artist"] or name
|
|
2282
|
+
g["in_library"] = owned_folder(name, g["title"])
|
|
2283
|
+
genres = sorted((x for x in a.get("genres") or [] if isinstance(x, dict)), key=lambda x: -(x.get("count") or 0))
|
|
2284
|
+
return {**artist_summary(a), "links": artist_links(a), "genres": [x.get("name") for x in genres[:6]],
|
|
2285
|
+
"groups": groups}
|
|
2286
|
+
return explore(run, mbid)
|
|
2287
|
+
|
|
2288
|
+
@app.get("/api/mb/release-group/{mbid}")
|
|
2289
|
+
def mb_explore_group(mbid: str) -> dict:
|
|
2290
|
+
"""A release: what it is, its first official edition's tracklist and label."""
|
|
2291
|
+
def run():
|
|
2292
|
+
g = mb.release_group(mbid)
|
|
2293
|
+
out = with_owned(group_summary(g))
|
|
2294
|
+
pick = pick_release(g)
|
|
2295
|
+
out["editions"] = len(g.get("releases") or [])
|
|
2296
|
+
genres = sorted((x for x in g.get("genres") or [] if isinstance(x, dict)), key=lambda x: -(x.get("count") or 0))
|
|
2297
|
+
out["genres"] = [x.get("name") for x in genres[:6]]
|
|
2298
|
+
out["release"] = None
|
|
2299
|
+
if pick:
|
|
2300
|
+
rel = mb.release_tracks_summary(pick["id"])
|
|
2301
|
+
labels = [li for li in rel.get("label-info") or [] if isinstance(li, dict)]
|
|
2302
|
+
media = [m for m in rel.get("media") or [] if isinstance(m, dict)]
|
|
2303
|
+
out["release"] = {
|
|
2304
|
+
"id": rel.get("id"), "date": rel.get("date") or "", "country": rel.get("country") or "",
|
|
2305
|
+
"label": next(((li.get("label") or {}).get("name") for li in labels if li.get("label")), ""),
|
|
2306
|
+
"catno": next((li.get("catalog-number") for li in labels if li.get("catalog-number")), ""),
|
|
2307
|
+
"format": " + ".join(dict.fromkeys(m.get("format") or "Digital" for m in media)),
|
|
2308
|
+
"tracks": tracklist(rel),
|
|
2309
|
+
}
|
|
2310
|
+
return out
|
|
2311
|
+
return explore(run, mbid)
|
|
2312
|
+
|
|
2313
|
+
# --- Library health -------------------------------------------------------------------------
|
|
2314
|
+
|
|
2315
|
+
health_store = HealthStore(settings.config_dir / "health.json")
|
|
2316
|
+
health_cache: dict = {"key": None, "data": None, "at": 0.0, "fixed": {}}
|
|
2317
|
+
health_lock = threading.Lock()
|
|
2318
|
+
|
|
2319
|
+
health_compute_lock = threading.Lock()
|
|
2320
|
+
health_worker: dict = {"thread": None}
|
|
2321
|
+
|
|
2322
|
+
def health_compute() -> None:
|
|
2323
|
+
with health_compute_lock:
|
|
2324
|
+
key = lib_index.version
|
|
2325
|
+
inbox_folder = inbox.settings.folder
|
|
2326
|
+
skip = [inbox_folder] if inbox_folder and not inbox_folder.startswith("@") else []
|
|
2327
|
+
data = health_run(lib_index.iter_tracks(), folder_has_image(library.resolve),
|
|
2328
|
+
lib_index.paths_with_any(MB_RELEASE_KEYS), skip)
|
|
2329
|
+
with health_lock:
|
|
2330
|
+
health_cache.update(data=data, key=key, at=time.time())
|
|
2331
|
+
|
|
2332
|
+
def health_data() -> dict:
|
|
2333
|
+
"""Every issue. The first check waits for the answer; after that, a change to the library
|
|
2334
|
+
(or 10 minutes, for cover files) re-checks in the background while the last answer is
|
|
2335
|
+
shown, so a big library never makes anyone wait twice."""
|
|
2336
|
+
with health_lock:
|
|
2337
|
+
data = health_cache["data"]
|
|
2338
|
+
stale = health_cache["key"] != lib_index.version or time.time() - health_cache["at"] > 600
|
|
2339
|
+
if data is None:
|
|
2340
|
+
health_compute()
|
|
2341
|
+
elif stale and not (health_worker["thread"] and health_worker["thread"].is_alive()):
|
|
2342
|
+
health_worker["thread"] = threading.Thread(target=health_compute, name="codetta-health", daemon=True)
|
|
2343
|
+
health_worker["thread"].start()
|
|
2344
|
+
return health_cache["data"]
|
|
2345
|
+
|
|
2346
|
+
def health_public(issue: dict) -> dict:
|
|
2347
|
+
"""What the page needs: never the file lists or the planned changes themselves."""
|
|
2348
|
+
fix = issue.get("fix")
|
|
2349
|
+
return {k: v for k, v in issue.items() if k not in ("paths", "fix")} | {
|
|
2350
|
+
"fix": {"label": fix["label"], "summary": fix["summary"]} if fix else None}
|
|
2351
|
+
|
|
2352
|
+
def health_visible() -> tuple[dict, list[dict], list[dict]]:
|
|
2353
|
+
data = health_data()
|
|
2354
|
+
# A fixed issue stays hidden until a check made after the fix confirms it's gone.
|
|
2355
|
+
fixed = {i for i, v in health_cache["fixed"].items() if (health_cache["key"] or 0) <= v}
|
|
2356
|
+
shown, ignored = [], []
|
|
2357
|
+
for issue in data["issues"]:
|
|
2358
|
+
if issue["check"] in health_store.disabled or issue["id"] in fixed:
|
|
2359
|
+
continue
|
|
2360
|
+
(ignored if issue["id"] in health_store.ignored else shown).append(issue)
|
|
2361
|
+
return data, shown, ignored
|
|
2362
|
+
|
|
2363
|
+
HEALTH_PAGE = 200 # issues per answer; "Show more" asks for the next ones
|
|
2364
|
+
|
|
2365
|
+
@app.get("/api/library-health")
|
|
2366
|
+
def get_health_route(category: str = Query("all", max_length=20), offset: int = Query(0, ge=0, le=1_000_000),
|
|
2367
|
+
limit: int = Query(HEALTH_PAGE, ge=1, le=1000)) -> dict:
|
|
2368
|
+
"""Library health: things worth fixing, found from the search index. Issues come a page
|
|
2369
|
+
at a time (a big library can have thousands); ``count`` and the category counts are totals."""
|
|
2370
|
+
return get_health(category, offset, limit)
|
|
2371
|
+
|
|
2372
|
+
def get_health(category: str = "all", offset: int = 0, limit: int = HEALTH_PAGE) -> dict:
|
|
2373
|
+
require_library()
|
|
2374
|
+
if not health_store.enabled: # switched off: nothing is checked at all
|
|
2375
|
+
return {"enabled": False, "indexing": False, "albums": 0, "tracks": 0, "unmatched": None, "count": 0,
|
|
2376
|
+
"categories": [], "checks": [], "issues": [], "ignored": []}
|
|
2377
|
+
data, shown, ignored = health_visible()
|
|
2378
|
+
return {
|
|
2379
|
+
"enabled": True,
|
|
2380
|
+
"indexing": not lib_index.status().ready,
|
|
2381
|
+
"albums": data["albums"], "tracks": data["tracks"],
|
|
2382
|
+
"unmatched": data["unmatched"] if connections.enabled("musicbrainz") else None,
|
|
2383
|
+
"count": len(shown),
|
|
2384
|
+
"categories": [{"id": c, "label": label, "count": sum(i["category"] == c for i in shown)}
|
|
2385
|
+
for c, label in HEALTH_CATEGORIES.items()],
|
|
2386
|
+
"checks": [{"id": c.id, "category": c.category, "label": c.label, "about": c.about,
|
|
2387
|
+
"enabled": c.id not in health_store.disabled} for c in HEALTH_CHECKS],
|
|
2388
|
+
"category": category, "offset": offset,
|
|
2389
|
+
"issues": [health_public(i) for i in (shown if category == "all" else [x for x in shown if x["category"] == category])[offset:offset + limit]],
|
|
2390
|
+
"shown_total": len(shown) if category == "all" else sum(x["category"] == category for x in shown),
|
|
2391
|
+
"ignored": [health_public(i) for i in ignored[:limit]],
|
|
2392
|
+
"ignored_total": len(ignored),
|
|
2393
|
+
}
|
|
2394
|
+
|
|
2395
|
+
@app.get("/api/library-health/summary")
|
|
2396
|
+
def get_health_summary() -> dict:
|
|
2397
|
+
"""Just the count (for the card on the Library page)."""
|
|
2398
|
+
require_library()
|
|
2399
|
+
if not health_store.enabled:
|
|
2400
|
+
return {"enabled": False, "count": 0, "indexing": False}
|
|
2401
|
+
_, shown, _ = health_visible()
|
|
2402
|
+
return {"enabled": True, "count": len(shown), "indexing": not lib_index.status().ready}
|
|
2403
|
+
|
|
2404
|
+
@app.put("/api/library-health/settings")
|
|
2405
|
+
def put_health_settings(body: HealthSettingsIn) -> dict:
|
|
2406
|
+
known = {c.id for c in HEALTH_CHECKS}
|
|
2407
|
+
with health_store.lock:
|
|
2408
|
+
if body.enabled is not None:
|
|
2409
|
+
health_store.enabled = body.enabled
|
|
2410
|
+
if body.disabled is not None:
|
|
2411
|
+
health_store.disabled = {c for c in body.disabled if c in known}
|
|
2412
|
+
try:
|
|
2413
|
+
health_store.save()
|
|
2414
|
+
except OSError as exc:
|
|
2415
|
+
raise HTTPException(500, f"Could not save to the config folder: {exc}") from exc
|
|
2416
|
+
return get_health()
|
|
2417
|
+
|
|
2418
|
+
@app.post("/api/library-health/ignore")
|
|
2419
|
+
def health_ignore(body: HealthIssueIn) -> dict:
|
|
2420
|
+
with health_store.lock:
|
|
2421
|
+
(health_store.ignored.add if body.ignore else health_store.ignored.discard)(body.id)
|
|
2422
|
+
try:
|
|
2423
|
+
health_store.save()
|
|
2424
|
+
except OSError as exc:
|
|
2425
|
+
raise HTTPException(500, f"Could not save to the config folder: {exc}") from exc
|
|
2426
|
+
return get_health()
|
|
2427
|
+
|
|
2428
|
+
@app.post("/api/library-health/fix")
|
|
2429
|
+
def health_fix(body: HealthIssueIn) -> dict:
|
|
2430
|
+
"""Apply an issue's one-tap fix: ordinary safe tag writes, one undoable activity entry."""
|
|
2431
|
+
require_library()
|
|
2432
|
+
if not health_store.enabled:
|
|
2433
|
+
raise HTTPException(409, "Library health is switched off.")
|
|
2434
|
+
issue = next((i for i in health_data()["issues"] if i["id"] == body.id), None)
|
|
2435
|
+
if issue is None:
|
|
2436
|
+
raise HTTPException(404, "That issue is gone (fixed already?)")
|
|
2437
|
+
fix = issue.get("fix")
|
|
2438
|
+
if not fix:
|
|
2439
|
+
raise HTTPException(409, "This one needs a look by hand.")
|
|
2440
|
+
version = lib_index.version
|
|
2441
|
+
done, failed = apply_per_file(fix["per_file"], f"Library health: {fix['summary']}")
|
|
2442
|
+
if not failed:
|
|
2443
|
+
health_cache["fixed"][issue["id"]] = version # hidden until the index has the new tags
|
|
2444
|
+
return {"fixed": len(done), "failed": len(failed), "errors": failed[:20], "health": get_health()}
|
|
2445
|
+
|
|
2446
|
+
# --- Plugins and actions -------------------------------------------------------------------
|
|
2447
|
+
|
|
2448
|
+
plugins = PluginManager(settings.config_dir)
|
|
2449
|
+
|
|
2450
|
+
@app.get("/api/plugins")
|
|
2451
|
+
def list_plugins() -> dict:
|
|
2452
|
+
"""Installed plugins (built-in ones, and folders in <config>/plugins), and their actions."""
|
|
2453
|
+
with plugins.lock:
|
|
2454
|
+
return {"folder": str(plugins.dir), "plugins": [p.public() for p in plugins.plugins.values()],
|
|
2455
|
+
"actions": [{"id": a.id, "label": a.label, "description": a.description, "fields": list(a.fields),
|
|
2456
|
+
"plugin": a.plugin} for a in plugins.actions.values()]}
|
|
2457
|
+
|
|
2458
|
+
@app.put("/api/plugins/{plugin_id}")
|
|
2459
|
+
def toggle_plugin(plugin_id: str, body: PluginToggleIn) -> dict:
|
|
2460
|
+
"""Turn a plugin on (its code is imported) or off."""
|
|
2461
|
+
try:
|
|
2462
|
+
info = plugins.set_enabled(plugin_id, body.enabled)
|
|
2463
|
+
except KeyError:
|
|
2464
|
+
raise HTTPException(404, "There's no plugin with that id (built-in ones are always on).") from None
|
|
2465
|
+
except OSError as exc:
|
|
2466
|
+
raise HTTPException(500, f"Could not save to the config folder: {exc}") from exc
|
|
2467
|
+
if info.error and body.enabled:
|
|
2468
|
+
raise HTTPException(422, f"{info.name} couldn't load: {info.error}")
|
|
2469
|
+
return list_plugins()
|
|
2470
|
+
|
|
2471
|
+
@app.post("/api/actions/{action_id}/run")
|
|
2472
|
+
def run_action(action_id: str, body: ActionRunIn) -> dict:
|
|
2473
|
+
"""Run an action (built-in or from a plugin) on tracks. ``dry_run`` (the default) shows
|
|
2474
|
+
what would change; otherwise it writes, as one undoable activity entry."""
|
|
2475
|
+
require_library()
|
|
2476
|
+
if action_id not in plugins.actions:
|
|
2477
|
+
raise HTTPException(404, "That action isn't available (is its plugin turned on?).")
|
|
2478
|
+
targets = _unique(body.paths) if body.paths else (
|
|
2479
|
+
audio_files(library, body.folder.strip("/"), False, MAX_PATHS_PER_REQUEST) if body.folder is not None else [])
|
|
2480
|
+
if not targets:
|
|
2481
|
+
raise HTTPException(422, "Choose some tracks or a folder.")
|
|
2482
|
+
plan, preview, unreadable = {}, [], 0
|
|
2483
|
+
for rel in targets:
|
|
2484
|
+
try:
|
|
2485
|
+
tags = engine.load_metadata(library.resolve(rel)).tags
|
|
2486
|
+
except (MetadataError, LibraryPathError, OSError):
|
|
2487
|
+
unreadable += 1
|
|
2488
|
+
continue
|
|
2489
|
+
try:
|
|
2490
|
+
changes = plugins.run_action(action_id, tags)
|
|
2491
|
+
except ActionError as exc:
|
|
2492
|
+
raise HTTPException(422, str(exc)) from exc
|
|
2493
|
+
if changes:
|
|
2494
|
+
plan[rel] = changes
|
|
2495
|
+
if len(preview) < 200:
|
|
2496
|
+
preview.append({"path": rel, "changes": [{"key": k, "old": "; ".join(tags.get(k, [])),
|
|
2497
|
+
"new": "; ".join(v or [])} for k, v in changes.items()]})
|
|
2498
|
+
out = {"tracks": len(targets), "changing": len(plan), "unreadable": unreadable, "preview": preview}
|
|
2499
|
+
if body.dry_run or not plan:
|
|
2500
|
+
return out
|
|
2501
|
+
label = plugins.actions[action_id].label
|
|
2502
|
+
done, failed = apply_per_file(plan, f"{label}: {len(plan)} track{'s' if len(plan) != 1 else ''}")
|
|
2503
|
+
return {**out, "changed": len(done), "failed": len(failed), "errors": failed[:20]}
|
|
2504
|
+
|
|
2505
|
+
@app.post("/api/tracks/replace")
|
|
2506
|
+
def replace_in_tags(body: ReplaceIn) -> dict:
|
|
2507
|
+
"""Find & replace in the tags of many tracks (these files, or a folder's). ``dry_run`` (the
|
|
2508
|
+
default) only shows what would change; otherwise it writes, as one undoable activity entry."""
|
|
2509
|
+
require_library()
|
|
2510
|
+
targets = _unique(body.paths) if body.paths else (
|
|
2511
|
+
audio_files(library, body.folder.strip("/"), False, MAX_PATHS_PER_REQUEST) if body.folder is not None else [])
|
|
2512
|
+
if not targets:
|
|
2513
|
+
raise HTTPException(422, "Choose some tracks or a folder.")
|
|
2514
|
+
try:
|
|
2515
|
+
pattern = re.compile(body.find if body.regex else re.escape(body.find), 0 if body.match_case else re.IGNORECASE)
|
|
2516
|
+
if body.regex:
|
|
2517
|
+
pattern.sub(body.replace, "") # a bad \1 reference fails here, not half-way through
|
|
2518
|
+
except re.error as exc:
|
|
2519
|
+
raise HTTPException(422, f"That pattern doesn't work: {exc}") from exc
|
|
2520
|
+
fields = [f.lower() for f in body.fields] if body.fields else list(REPLACE_FIELDS)
|
|
2521
|
+
swap = (lambda m: m.expand(body.replace)) if body.regex else (lambda m: body.replace)
|
|
2522
|
+
plan: dict[str, dict] = {}
|
|
2523
|
+
preview, unreadable = [], 0
|
|
2524
|
+
for rel in targets:
|
|
2525
|
+
try:
|
|
2526
|
+
tags = engine.load_metadata(library.resolve(rel)).tags
|
|
2527
|
+
except (MetadataError, LibraryPathError, OSError):
|
|
2528
|
+
unreadable += 1
|
|
2529
|
+
continue
|
|
2530
|
+
changes, shown = {}, []
|
|
2531
|
+
for key in fields:
|
|
2532
|
+
old = tags.get(key) or []
|
|
2533
|
+
new = [pattern.sub(swap, v) for v in old]
|
|
2534
|
+
if new != old:
|
|
2535
|
+
changes[key] = [v for v in new if v.strip()] or None
|
|
2536
|
+
shown.append({"key": key, "old": "; ".join(old), "new": "; ".join(v for v in new if v.strip())})
|
|
2537
|
+
if changes:
|
|
2538
|
+
plan[rel] = changes
|
|
2539
|
+
if len(preview) < 200:
|
|
2540
|
+
preview.append({"path": rel, "changes": shown})
|
|
2541
|
+
out = {"tracks": len(targets), "changing": len(plan), "unreadable": unreadable, "preview": preview}
|
|
2542
|
+
if body.dry_run or not plan:
|
|
2543
|
+
return out
|
|
2544
|
+
what = f"“{body.find}” → “{body.replace}”" if body.replace else f"removed “{body.find}”"
|
|
2545
|
+
done, failed = apply_per_file(plan, f"Find & replace: {what} in {len(plan)} track{'s' if len(plan) != 1 else ''}")
|
|
2546
|
+
return {**out, "changed": len(done), "failed": len(failed), "errors": failed[:20]}
|
|
2547
|
+
|
|
2548
|
+
@app.post("/api/folders/rename")
|
|
2549
|
+
def rename_folder(body: FolderRenameIn) -> dict:
|
|
2550
|
+
"""Rename a folder (each file is moved like Organize does: nothing overwritten, one undo)."""
|
|
2551
|
+
require_library()
|
|
2552
|
+
folder = body.path.strip().strip("/")
|
|
2553
|
+
if not folder or folder.startswith("@"):
|
|
2554
|
+
raise HTTPException(422, "Choose a folder inside your music folder.")
|
|
2555
|
+
src = library.resolve(folder)
|
|
2556
|
+
if not src.is_dir():
|
|
2557
|
+
raise HTTPException(404, "That folder isn't there any more.")
|
|
2558
|
+
name = safe_name(body.name)
|
|
2559
|
+
parent = folder.rsplit("/", 1)[0] if "/" in folder else ""
|
|
2560
|
+
dest = f"{parent}/{name}" if parent else name
|
|
2561
|
+
if dest == folder:
|
|
2562
|
+
return {"path": folder, "moved": 0, "failed": 0}
|
|
2563
|
+
target = library.resolve(dest)
|
|
2564
|
+
if target.exists() and not (dest.casefold() == folder.casefold() and target.samefile(src)):
|
|
2565
|
+
raise HTTPException(409, f"There's already a folder called “{name}” there.")
|
|
2566
|
+
moves = []
|
|
2567
|
+
for dirpath, _, names in os.walk(src):
|
|
2568
|
+
for n in sorted(names):
|
|
2569
|
+
rel = library.relative(Path(dirpath) / n)
|
|
2570
|
+
moves.append(Move(rel, dest + rel[len(folder):], "move"))
|
|
2571
|
+
if dest.casefold() == folder.casefold(): # only the case changes: go via a temporary name
|
|
2572
|
+
tmp = f"{dest}.codetta-rename"
|
|
2573
|
+
first = apply_moves(library.resolve, [Move(m.src, tmp + m.src[len(folder):], "move") for m in moves])
|
|
2574
|
+
moves = [Move(tmp + m.src[len(folder):], m.dst, "move") for m in moves]
|
|
2575
|
+
results = apply_moves(library.resolve, moves)
|
|
2576
|
+
pairs = [(a, d) for r1, r2 in zip(first, results) if r1.ok and r2.ok
|
|
2577
|
+
for (a, _), (_, d) in zip(r1.moved, r2.moved)]
|
|
2578
|
+
else:
|
|
2579
|
+
results = apply_moves(library.resolve, moves)
|
|
2580
|
+
pairs = [pair for r in results if r.ok for pair in r.moved]
|
|
2581
|
+
failed = [r for r in results if not r.ok]
|
|
2582
|
+
for dirpath, _, _ in sorted(os.walk(src), key=lambda x: -len(x[0])): # tidy what's left (empty folders)
|
|
2583
|
+
try:
|
|
2584
|
+
os.rmdir(dirpath)
|
|
2585
|
+
except OSError:
|
|
2586
|
+
pass
|
|
2587
|
+
if pairs:
|
|
2588
|
+
activity.add("organize", f"Renamed folder “{folder.rsplit('/', 1)[-1]}” to “{name}”", ok=not failed,
|
|
2589
|
+
files=[b for _, b in pairs], changes=[{"key": "folder", "old": folder, "new": dest}],
|
|
2590
|
+
errors=[{"path": r.src, "error": r.error or ""} for r in failed],
|
|
2591
|
+
undo={"type": "moves", "moves": [list(p) for p in pairs]})
|
|
2592
|
+
lib_index.mark_dirty([p for pair in pairs for p in pair])
|
|
2593
|
+
art_cache.clear()
|
|
2594
|
+
return {"path": dest, "moved": len(pairs), "failed": len(failed)}
|
|
2595
|
+
|
|
2596
|
+
def apply_per_file(per_file: dict[str, dict], message: str) -> tuple[list[str], list[dict]]:
|
|
2597
|
+
"""Write different tag changes to each file (safe writes, a few at once) and log them as
|
|
2598
|
+
one undoable activity entry. Returns (files done, failures)."""
|
|
2599
|
+
undo_files: dict = {}
|
|
2600
|
+
|
|
2601
|
+
def one(item):
|
|
2602
|
+
rel, changes = item
|
|
2603
|
+
try:
|
|
2604
|
+
target = library.resolve(rel)
|
|
2605
|
+
was: dict = {}
|
|
2606
|
+
after = engine.update_tags(target, changes, before=was).tags
|
|
2607
|
+
before = was["tags"]
|
|
2608
|
+
keys = {k.lower() for k in changes}
|
|
2609
|
+
diff = [k for k in keys if before.get(k, []) != after.get(k, [])]
|
|
2610
|
+
if diff:
|
|
2611
|
+
undo_files[rel] = {"before": {k: before.get(k, []) for k in diff},
|
|
2612
|
+
"after": {k: after.get(k, []) for k in diff}}
|
|
2613
|
+
return rel, None
|
|
2614
|
+
except (MetadataError, LibraryPathError, OSError) as exc:
|
|
2615
|
+
return rel, str(exc)
|
|
2616
|
+
|
|
2617
|
+
items = list(per_file.items())
|
|
2618
|
+
if len(items) > 8:
|
|
2619
|
+
with ThreadPoolExecutor(max_workers=4, thread_name_prefix="codetta-write") as pool:
|
|
2620
|
+
results = list(pool.map(one, items))
|
|
2621
|
+
else:
|
|
2622
|
+
results = [one(i) for i in items]
|
|
2623
|
+
done = [r for r, e in results if e is None]
|
|
2624
|
+
failed = [{"path": r, "error": e} for r, e in results if e is not None]
|
|
2625
|
+
keys = sorted({k for c in per_file.values() for k in c})
|
|
2626
|
+
news = {k: {str(c.get(k)) for c in per_file.values() if k in c} for k in keys}
|
|
2627
|
+
activity.add(
|
|
2628
|
+
"edit", message if not failed else f"{message.split(':')[0]}: changed {len(done)} of {len(items)} tracks",
|
|
2629
|
+
ok=not failed, files=done + [f["path"] for f in failed],
|
|
2630
|
+
changes=[{"key": k, "old": "", "new": news[k].pop() if len(news[k]) == 1 else "various"} for k in keys],
|
|
2631
|
+
errors=failed, undo={"type": "tags", "files": undo_files} if undo_files else None,
|
|
2632
|
+
)
|
|
2633
|
+
lib_index.mark_dirty(done)
|
|
2634
|
+
return done, failed
|
|
2635
|
+
|
|
2636
|
+
@app.post("/api/activity/{entry_id}/undo")
|
|
2637
|
+
def undo(entry_id: int) -> dict:
|
|
2638
|
+
"""Reverse a logged change. Files edited again since are left alone."""
|
|
2639
|
+
require_library()
|
|
2640
|
+
entry = activity.get(entry_id)
|
|
2641
|
+
if entry is None:
|
|
2642
|
+
raise HTTPException(404, "That change is no longer in the activity log")
|
|
2643
|
+
if not entry.get("undo"):
|
|
2644
|
+
raise HTTPException(422, "This change can't be undone")
|
|
2645
|
+
if activity.is_undone(entry_id):
|
|
2646
|
+
raise HTTPException(409, "This change has already been undone")
|
|
2647
|
+
outcome = undo_change(engine, library.resolve, art_store, entry["undo"])
|
|
2648
|
+
lib_index.mark_dirty(r.path for r in outcome.results if r.ok)
|
|
2649
|
+
if entry["undo"].get("type") == "moves" and outcome.reverse:
|
|
2650
|
+
lib_index.mark_dirty(p for pair in outcome.reverse["moves"] for p in pair if not p.startswith("@"))
|
|
2651
|
+
art_cache.clear()
|
|
2652
|
+
done = [r for r in outcome.results if r.ok]
|
|
2653
|
+
skipped = [r for r in outcome.results if r.skipped]
|
|
2654
|
+
failed = [r for r in outcome.results if not r.ok and not r.skipped]
|
|
2655
|
+
n = len(outcome.results)
|
|
2656
|
+
# Name the original change, however many times it's been undone/redone.
|
|
2657
|
+
what = entry.get("root_message") or entry["message"]
|
|
2658
|
+
redo = entry.get("kind") == "undo" and not entry.get("redo")
|
|
2659
|
+
verb = "Redid" if redo else "Undid"
|
|
2660
|
+
if not done:
|
|
2661
|
+
message = f"Couldn't {'redo' if redo else 'undo'} “{what}”"
|
|
2662
|
+
elif len(done) == n:
|
|
2663
|
+
message = f"{verb} “{what}”"
|
|
2664
|
+
else:
|
|
2665
|
+
message = f"{verb} “{what}” on {len(done)} of {n} files"
|
|
2666
|
+
if done:
|
|
2667
|
+
activity.add(
|
|
2668
|
+
"undo", message, ok=not failed,
|
|
2669
|
+
files=[r.path for r in done],
|
|
2670
|
+
changes=[{"key": c["key"], "old": c["new"], "new": c["old"]} for c in entry.get("changes", [])
|
|
2671
|
+
if c.get("old") != "various"],
|
|
2672
|
+
errors=[{"path": r.path, "error": r.error or ""} for r in skipped + failed],
|
|
2673
|
+
undo=outcome.reverse, undoes=entry_id,
|
|
2674
|
+
extra={"root_message": what, "redo": redo},
|
|
2675
|
+
)
|
|
2676
|
+
return {
|
|
2677
|
+
"message": message,
|
|
2678
|
+
"undone": len(done), "skipped": len(skipped), "failed": len(failed),
|
|
2679
|
+
"results": [{"path": r.path, "ok": r.ok, "skipped": r.skipped, "error": r.error} for r in outcome.results],
|
|
2680
|
+
}
|
|
2681
|
+
|
|
2682
|
+
# --- Activity -------------------------------------------------------------------------
|
|
2683
|
+
|
|
2684
|
+
@app.get("/api/activity")
|
|
2685
|
+
def get_activity(limit: int = Query(50, ge=1, le=500), after_id: int = Query(0, ge=0)) -> list[dict]:
|
|
2686
|
+
"""Recent changes, newest first. Pass ``after_id`` to get only newer ones."""
|
|
2687
|
+
return activity.recent(limit=limit, after_id=after_id)
|
|
2688
|
+
|
|
2689
|
+
# --- Presets --------------------------------------------------------------------
|
|
2690
|
+
|
|
2691
|
+
@app.get("/api/presets", response_model=list[PresetOut])
|
|
2692
|
+
def list_presets():
|
|
2693
|
+
return [_to_preset_out(lo) for lo in store.list()]
|
|
2694
|
+
|
|
2695
|
+
@app.post("/api/presets", response_model=PresetOut)
|
|
2696
|
+
def save_preset(body: PresetIn):
|
|
2697
|
+
"""Create a preset, or edit one (pass ``previous_name`` when editing)."""
|
|
2698
|
+
preset = Preset(name=body.name, tags=body.tags, description=body.description)
|
|
2699
|
+
editing = body.previous_name is not None
|
|
2700
|
+
renamed = editing and slugify(body.previous_name) != preset.slug
|
|
2701
|
+
if (not editing or renamed) and _exists(store, preset.name):
|
|
2702
|
+
raise HTTPException(409, f"A preset named '{preset.name}' already exists")
|
|
2703
|
+
try:
|
|
2704
|
+
store.save(preset)
|
|
2705
|
+
except OSError as exc:
|
|
2706
|
+
raise HTTPException(500, f"Could not save preset: {exc}") from exc
|
|
2707
|
+
if renamed and _exists(store, body.previous_name):
|
|
2708
|
+
store.delete(body.previous_name)
|
|
2709
|
+
return _to_preset_out(preset)
|
|
2710
|
+
|
|
2711
|
+
@app.delete("/api/presets/{name}", status_code=204)
|
|
2712
|
+
def delete_preset(name: str):
|
|
2713
|
+
store.delete(name)
|
|
2714
|
+
|
|
2715
|
+
@app.post("/api/presets/apply", response_model=list[ApplyResultOut])
|
|
2716
|
+
def apply(body: ApplyIn):
|
|
2717
|
+
"""Apply a preset to files or a folder. ``dry_run`` (default) only previews."""
|
|
2718
|
+
require_library()
|
|
2719
|
+
preset = store.get(body.name)
|
|
2720
|
+
if body.folder is not None:
|
|
2721
|
+
results = apply_preset_to_folder(
|
|
2722
|
+
engine,
|
|
2723
|
+
preset,
|
|
2724
|
+
library.resolve(body.folder),
|
|
2725
|
+
mode=body.mode,
|
|
2726
|
+
recursive=body.recursive,
|
|
2727
|
+
dry_run=body.dry_run,
|
|
2728
|
+
)
|
|
2729
|
+
elif body.paths:
|
|
2730
|
+
paths = [library.resolve(p) for p in _unique(body.paths)]
|
|
2731
|
+
results = apply_preset(engine, preset, paths, mode=body.mode, dry_run=body.dry_run)
|
|
2732
|
+
else:
|
|
2733
|
+
raise HTTPException(400, "Choose some files or a folder to apply the preset to")
|
|
2734
|
+
out = [result_out(r) for r in results]
|
|
2735
|
+
if not body.dry_run:
|
|
2736
|
+
undo_files = {
|
|
2737
|
+
library.relative(r.path): {"before": r.previous, "after": r.applied}
|
|
2738
|
+
for r in results if not r.error and r.applied
|
|
2739
|
+
}
|
|
2740
|
+
_log_preset(activity, preset.name, body.mode, out,
|
|
2741
|
+
undo={"type": "tags", "files": undo_files} if undo_files else None)
|
|
2742
|
+
lib_index.mark_dirty(o.path for o in out if not o.error and o.applied)
|
|
2743
|
+
return out
|
|
2744
|
+
|
|
2745
|
+
# --- UI ------------------------------------------------------------------------------
|
|
2746
|
+
|
|
2747
|
+
@app.get("/", include_in_schema=False)
|
|
2748
|
+
def index():
|
|
2749
|
+
return FileResponse(STATIC_DIR / "index.html", headers={"Cache-Control": "no-cache"})
|
|
2750
|
+
|
|
2751
|
+
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
|
|
2752
|
+
# Size limits, cross-site protection and security headers (see web/security.py).
|
|
2753
|
+
# Added last so it wraps everything, including the sign-in check's 401s.
|
|
2754
|
+
app.add_middleware(SelectiveGZip) # inside the guard: rejected requests never reach it
|
|
2755
|
+
app.add_middleware(GuardMiddleware, allowed_hosts=set(settings.allowed_hosts))
|
|
2756
|
+
return app
|
|
2757
|
+
|
|
2758
|
+
|
|
2759
|
+
def _is_public_address(host: str) -> bool:
|
|
2760
|
+
"""True for internet addresses. Home networks, Tailscale (100.64.0.0/10 and
|
|
2761
|
+
fd7a:115c:a1e0::/48), loopback and link-local are not public."""
|
|
2762
|
+
import ipaddress
|
|
2763
|
+
|
|
2764
|
+
try:
|
|
2765
|
+
ip = ipaddress.ip_address(host)
|
|
2766
|
+
except ValueError:
|
|
2767
|
+
return False # e.g. "testclient" or a Unix socket: not an internet peer
|
|
2768
|
+
if ip.version == 6 and ip.ipv4_mapped:
|
|
2769
|
+
ip = ip.ipv4_mapped
|
|
2770
|
+
return ip.is_global
|
|
2771
|
+
|
|
2772
|
+
|
|
2773
|
+
def _to_track_out(rel: str, meta: TrackMetadata, mtime: int | None = None) -> TrackOut:
|
|
2774
|
+
return TrackOut(
|
|
2775
|
+
path=rel,
|
|
2776
|
+
name=rel.rsplit("/", 1)[-1],
|
|
2777
|
+
format=meta.format,
|
|
2778
|
+
tags=meta.tags,
|
|
2779
|
+
duration=meta.duration,
|
|
2780
|
+
bitrate=meta.bitrate,
|
|
2781
|
+
sample_rate=meta.sample_rate,
|
|
2782
|
+
channels=meta.channels,
|
|
2783
|
+
mtime=mtime,
|
|
2784
|
+
)
|
|
2785
|
+
|
|
2786
|
+
|
|
2787
|
+
def _to_preset_out(lo: Preset) -> PresetOut:
|
|
2788
|
+
return PresetOut(name=lo.name, slug=lo.slug, description=lo.description, tags=lo.tags)
|
|
2789
|
+
|
|
2790
|
+
|
|
2791
|
+
def _exists(store: PresetStore, name: str) -> bool:
|
|
2792
|
+
try:
|
|
2793
|
+
store.get(name)
|
|
2794
|
+
return True
|
|
2795
|
+
except PresetNotFoundError:
|
|
2796
|
+
return False
|
|
2797
|
+
except PresetError:
|
|
2798
|
+
return True # a file exists under that name, even if it's broken
|
|
2799
|
+
|
|
2800
|
+
|
|
2801
|
+
app = create_app()
|
|
2802
|
+
|
|
2803
|
+
|
|
2804
|
+
# --- Activity log messages ------------------------------------------------------------
|
|
2805
|
+
|
|
2806
|
+
|
|
2807
|
+
def _name(rel: str) -> str:
|
|
2808
|
+
return rel.rsplit("/", 1)[-1]
|
|
2809
|
+
|
|
2810
|
+
|
|
2811
|
+
ACTIVITY_VALUE_CHARS = 160 # long values (lyrics) are shortened in the log; undo keeps the full text
|
|
2812
|
+
|
|
2813
|
+
|
|
2814
|
+
def _join(values: list[str]) -> str:
|
|
2815
|
+
text = " ".join("; ".join(values).split()) # one line
|
|
2816
|
+
return text if len(text) <= ACTIVITY_VALUE_CHARS else text[: ACTIVITY_VALUE_CHARS - 1].rstrip() + "…"
|
|
2817
|
+
|
|
2818
|
+
|
|
2819
|
+
def _log_edit(activity: ActivityLog, changes: dict, results: list[UpdateResult], before: dict, undo: dict | None = None) -> None:
|
|
2820
|
+
ok = [r for r in results if r.ok]
|
|
2821
|
+
failed = [r for r in results if not r.ok]
|
|
2822
|
+
keys = list(changes)
|
|
2823
|
+
diff = []
|
|
2824
|
+
for key in keys:
|
|
2825
|
+
olds = {_join(before[r.path].get(key, [])) for r in ok if r.path in before}
|
|
2826
|
+
new = _join(ok[0].track.tags.get(key, [])) if ok else ""
|
|
2827
|
+
old = olds.pop() if len(olds) == 1 else ("various" if olds else "")
|
|
2828
|
+
diff.append({"key": key, "old": old, "new": new})
|
|
2829
|
+
field_list = ", ".join(keys[:4]) + (f" +{len(keys) - 4} more" if len(keys) > 4 else "")
|
|
2830
|
+
target = _name(results[0].path) if len(results) == 1 else f"{len(results)} tracks"
|
|
2831
|
+
if not failed:
|
|
2832
|
+
message = f"Edited {field_list} on {target}"
|
|
2833
|
+
elif not ok:
|
|
2834
|
+
message = f"Couldn't edit {target}"
|
|
2835
|
+
else:
|
|
2836
|
+
message = f"Edited {field_list} on {len(ok)} of {len(results)} tracks"
|
|
2837
|
+
activity.add(
|
|
2838
|
+
"edit", message, ok=not failed,
|
|
2839
|
+
files=[r.path for r in results], changes=diff if ok else [],
|
|
2840
|
+
errors=[{"path": r.path, "error": r.error or ""} for r in failed],
|
|
2841
|
+
undo=undo,
|
|
2842
|
+
)
|
|
2843
|
+
|
|
2844
|
+
|
|
2845
|
+
def _log_art(activity: ActivityLog, adding: bool, art, had_art: int, results: list[UpdateResult], undo: dict | None = None) -> None:
|
|
2846
|
+
ok = [r for r in results if r.ok]
|
|
2847
|
+
failed = [r for r in results if not r.ok]
|
|
2848
|
+
target = _name(results[0].path) if len(results) == 1 else f"{len(ok)} tracks"
|
|
2849
|
+
if adding:
|
|
2850
|
+
verb = "Replaced" if had_art else "Added"
|
|
2851
|
+
detail = ""
|
|
2852
|
+
if art is not None:
|
|
2853
|
+
size = f"{art.width}×{art.height} " if art.width and art.height else ""
|
|
2854
|
+
detail = f" ({size}{art.mime.split('/')[-1].upper()}, {max(1, len(art.data) // 1024)} KB)"
|
|
2855
|
+
message = f"{verb} album art on {target}{detail}" if ok else f"Couldn't set album art on {_name(results[0].path) if len(results) == 1 else f'{len(results)} tracks'}"
|
|
2856
|
+
else:
|
|
2857
|
+
message = f"Removed album art from {target}" if ok else "Couldn't remove album art"
|
|
2858
|
+
activity.add(
|
|
2859
|
+
"art", message, ok=not failed,
|
|
2860
|
+
files=[r.path for r in results],
|
|
2861
|
+
errors=[{"path": r.path, "error": r.error or ""} for r in failed],
|
|
2862
|
+
undo=undo,
|
|
2863
|
+
)
|
|
2864
|
+
|
|
2865
|
+
|
|
2866
|
+
def _log_preset(activity: ActivityLog, name: str, mode: str, results: list[ApplyResultOut], undo: dict | None = None) -> None:
|
|
2867
|
+
changed = [r for r in results if not r.error and r.applied]
|
|
2868
|
+
failed = [r for r in results if r.error]
|
|
2869
|
+
keys = sorted({k for r in changed for k in r.applied})
|
|
2870
|
+
diff = [{"key": k, "old": "", "new": _join(changed[0].applied[k]) if len(changed) == 1 and k in changed[0].applied else "set"} for k in keys]
|
|
2871
|
+
how = "filled empty tags" if mode == "fill" else "overwrote tags"
|
|
2872
|
+
message = f"Applied preset “{name}” to {len(changed)} of {len(results)} files ({how})"
|
|
2873
|
+
activity.add(
|
|
2874
|
+
"preset", message, ok=not failed,
|
|
2875
|
+
files=[r.path for r in changed], changes=diff,
|
|
2876
|
+
errors=[{"path": r.path, "error": r.error or ""} for r in failed],
|
|
2877
|
+
undo=undo,
|
|
2878
|
+
)
|
|
2879
|
+
|
|
2880
|
+
|
|
2881
|
+
def _log_musicbrainz(activity: ActivityLog, release: dict, files: list[dict], results: list[dict],
|
|
2882
|
+
covers: bool, undo: dict | None) -> None:
|
|
2883
|
+
ok = [r for r in results if r["ok"]]
|
|
2884
|
+
failed = [r for r in results if not r["ok"]]
|
|
2885
|
+
changed = {f["path"]: f["changes"] for f in files if f["path"] in {r["path"] for r in ok}}
|
|
2886
|
+
keys = list(dict.fromkeys(k for ch in changed.values() for k in ch))
|
|
2887
|
+
diff = []
|
|
2888
|
+
for key in keys:
|
|
2889
|
+
news = {_join(ch[key]["new"]) for ch in changed.values() if key in ch}
|
|
2890
|
+
olds = {_join(ch[key]["old"]) for ch in changed.values() if key in ch}
|
|
2891
|
+
diff.append({"key": key, "old": olds.pop() if len(olds) == 1 else "various",
|
|
2892
|
+
"new": news.pop() if len(news) == 1 else "set per track"})
|
|
2893
|
+
if covers:
|
|
2894
|
+
diff.append({"key": "cover art", "old": "", "new": "from the Cover Art Archive"})
|
|
2895
|
+
detail = " · ".join(p for p in (release.get("date", "")[:4], release.get("formats"), release.get("country")) if p)
|
|
2896
|
+
what = f"“{release.get('title')}” by {release.get('artist')}" + (f" ({detail})" if detail else "")
|
|
2897
|
+
target = _name(ok[0]["path"]) if len(ok) == 1 else f"{len(ok)} tracks"
|
|
2898
|
+
if not ok:
|
|
2899
|
+
message = f"Couldn't tag from MusicBrainz: {what}"
|
|
2900
|
+
elif failed:
|
|
2901
|
+
message = f"Tagged {len(ok)} of {len(results)} tracks from MusicBrainz: {what}"
|
|
2902
|
+
else:
|
|
2903
|
+
message = f"Tagged {target} from MusicBrainz: {what}"
|
|
2904
|
+
activity.add(
|
|
2905
|
+
"musicbrainz", message, ok=not failed,
|
|
2906
|
+
files=[r["path"] for r in results], changes=diff if ok else [],
|
|
2907
|
+
errors=[{"path": r["path"], "error": r["error"] or ""} for r in failed],
|
|
2908
|
+
undo=undo, extra={"release": release.get("id")},
|
|
2909
|
+
)
|