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/core/plugins.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"""Loading plugins: Codetta's built-in ones, and the ones people put in <config>/plugins/.
|
|
2
|
+
|
|
3
|
+
A plugin folder holds ``plugin.json``::
|
|
4
|
+
|
|
5
|
+
{"id": "my-plugin", "name": "My plugin", "version": "1.0", "description": "...",
|
|
6
|
+
"author": "...", "url": "https://...", "entry": "plugin.py", "api": 1}
|
|
7
|
+
|
|
8
|
+
Folders are listed always, but their code is imported only once enabled (plugins.json in
|
|
9
|
+
the config folder). A plugin that fails to load is reported, never fatal.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import importlib
|
|
15
|
+
import importlib.util
|
|
16
|
+
import json
|
|
17
|
+
import logging
|
|
18
|
+
import os
|
|
19
|
+
import re
|
|
20
|
+
import sys
|
|
21
|
+
import tempfile
|
|
22
|
+
import threading
|
|
23
|
+
from dataclasses import dataclass, field
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
|
|
26
|
+
from codetta.plugins import API_VERSION, Action, PluginAPI
|
|
27
|
+
from codetta.plugins.builtin import BUILTIN
|
|
28
|
+
|
|
29
|
+
log = logging.getLogger("codetta")
|
|
30
|
+
ID_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,39}$")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class PluginInfo:
|
|
35
|
+
id: str
|
|
36
|
+
name: str
|
|
37
|
+
version: str = ""
|
|
38
|
+
description: str = ""
|
|
39
|
+
author: str = ""
|
|
40
|
+
url: str = ""
|
|
41
|
+
builtin: bool = False
|
|
42
|
+
enabled: bool = False
|
|
43
|
+
error: str = ""
|
|
44
|
+
path: Path | None = None
|
|
45
|
+
entry: str = "plugin.py"
|
|
46
|
+
actions: list[str] = field(default_factory=list)
|
|
47
|
+
|
|
48
|
+
def public(self) -> dict:
|
|
49
|
+
url = self.url if self.url.startswith(("https://", "http://")) else ""
|
|
50
|
+
return {"id": self.id, "name": self.name, "version": self.version, "description": self.description,
|
|
51
|
+
"author": self.author, "url": url, "builtin": self.builtin, "enabled": self.enabled,
|
|
52
|
+
"error": self.error, "actions": self.actions}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class PluginManager:
|
|
56
|
+
def __init__(self, config_dir: Path) -> None:
|
|
57
|
+
self.dir = config_dir / "plugins"
|
|
58
|
+
self.state_file = config_dir / "plugins.json"
|
|
59
|
+
self.lock = threading.RLock()
|
|
60
|
+
self.plugins: dict[str, PluginInfo] = {}
|
|
61
|
+
self.actions: dict[str, Action] = {}
|
|
62
|
+
self.enabled: set[str] = self._load_state()
|
|
63
|
+
self.reload()
|
|
64
|
+
|
|
65
|
+
def _load_state(self) -> set[str]:
|
|
66
|
+
try:
|
|
67
|
+
data = json.loads(self.state_file.read_text("utf-8"))
|
|
68
|
+
return {i for i in data.get("enabled", []) if isinstance(i, str)}
|
|
69
|
+
except (OSError, ValueError, AttributeError):
|
|
70
|
+
return set()
|
|
71
|
+
|
|
72
|
+
def _save_state(self) -> None:
|
|
73
|
+
self.state_file.parent.mkdir(parents=True, exist_ok=True)
|
|
74
|
+
fd, tmp = tempfile.mkstemp(prefix=".plugins-", dir=self.state_file.parent)
|
|
75
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
76
|
+
json.dump({"enabled": sorted(self.enabled)}, f)
|
|
77
|
+
os.replace(tmp, self.state_file)
|
|
78
|
+
|
|
79
|
+
def _register(self, info: PluginInfo, action: Action) -> None:
|
|
80
|
+
self.actions[action.id] = action
|
|
81
|
+
info.actions.append(action.id)
|
|
82
|
+
|
|
83
|
+
def _setup(self, info: PluginInfo, module) -> None:
|
|
84
|
+
setup = getattr(module, "setup", None)
|
|
85
|
+
if not callable(setup):
|
|
86
|
+
raise RuntimeError("it has no setup(codetta) function")
|
|
87
|
+
setup(PluginAPI(info.id, lambda a: self._register(info, a)))
|
|
88
|
+
|
|
89
|
+
def reload(self) -> None:
|
|
90
|
+
"""Rebuild the list (and import enabled plugins). Safe to call any time."""
|
|
91
|
+
with self.lock:
|
|
92
|
+
self.plugins, self.actions = {}, {}
|
|
93
|
+
for name in BUILTIN: # built-ins: always on, they're part of Codetta
|
|
94
|
+
info = PluginInfo(id=name, name=name.title(), builtin=True, enabled=True)
|
|
95
|
+
try:
|
|
96
|
+
module = importlib.import_module(f"codetta.plugins.builtin.{name}")
|
|
97
|
+
info.name = getattr(module, "NAME", "Tidy-up actions" if name == "tidy" else name)
|
|
98
|
+
info.description = (module.__doc__ or "").strip().splitlines()[0] if module.__doc__ else ""
|
|
99
|
+
self._setup(info, module)
|
|
100
|
+
except Exception as exc: # noqa: BLE001 - never let a plugin stop Codetta
|
|
101
|
+
info.error = f"{type(exc).__name__}: {exc}"
|
|
102
|
+
self.plugins[info.id] = info
|
|
103
|
+
for folder in sorted(self.dir.iterdir()) if self.dir.is_dir() else []:
|
|
104
|
+
self._discover(folder)
|
|
105
|
+
|
|
106
|
+
def _discover(self, folder: Path) -> None:
|
|
107
|
+
manifest = folder / "plugin.json"
|
|
108
|
+
if not folder.is_dir() or not manifest.is_file():
|
|
109
|
+
return
|
|
110
|
+
try:
|
|
111
|
+
meta = json.loads(manifest.read_text("utf-8"))
|
|
112
|
+
except (OSError, ValueError) as exc:
|
|
113
|
+
self.plugins[folder.name] = PluginInfo(id=folder.name, name=folder.name, error=f"plugin.json can't be read: {exc}")
|
|
114
|
+
return
|
|
115
|
+
pid = str(meta.get("id") or folder.name)
|
|
116
|
+
if not ID_RE.match(pid) or pid in self.plugins:
|
|
117
|
+
self.plugins.setdefault(folder.name, PluginInfo(id=folder.name, name=folder.name,
|
|
118
|
+
error=f"The id {pid!r} isn't valid or is taken"))
|
|
119
|
+
return
|
|
120
|
+
info = PluginInfo(id=pid, name=str(meta.get("name") or pid)[:60], version=str(meta.get("version") or "")[:20],
|
|
121
|
+
description=str(meta.get("description") or "")[:300], author=str(meta.get("author") or "")[:80],
|
|
122
|
+
url=str(meta.get("url") or "")[:300], path=folder, entry=str(meta.get("entry") or "plugin.py"),
|
|
123
|
+
enabled=pid in self.enabled)
|
|
124
|
+
self.plugins[pid] = info
|
|
125
|
+
if int(meta.get("api") or 1) > API_VERSION:
|
|
126
|
+
info.error = f"It needs a newer Codetta (plugin API {meta.get('api')})."
|
|
127
|
+
return
|
|
128
|
+
if info.enabled:
|
|
129
|
+
self._import(info)
|
|
130
|
+
|
|
131
|
+
def _import(self, info: PluginInfo) -> None:
|
|
132
|
+
entry = (info.path / info.entry).resolve()
|
|
133
|
+
if info.path.resolve() not in entry.parents or not entry.is_file():
|
|
134
|
+
info.error = f"{info.entry} isn't in the plugin's folder"
|
|
135
|
+
return
|
|
136
|
+
try:
|
|
137
|
+
name = f"codetta_plugin_{info.id.replace('-', '_')}"
|
|
138
|
+
spec = importlib.util.spec_from_file_location(name, entry)
|
|
139
|
+
module = importlib.util.module_from_spec(spec)
|
|
140
|
+
sys.modules[name] = module
|
|
141
|
+
spec.loader.exec_module(module)
|
|
142
|
+
self._setup(info, module)
|
|
143
|
+
log.info("Plugin loaded: %s %s", info.name, info.version)
|
|
144
|
+
except Exception as exc: # noqa: BLE001
|
|
145
|
+
info.error = f"{type(exc).__name__}: {exc}"
|
|
146
|
+
for aid in info.actions:
|
|
147
|
+
self.actions.pop(aid, None)
|
|
148
|
+
info.actions = []
|
|
149
|
+
log.warning("Plugin %s couldn't load: %s", info.id, info.error)
|
|
150
|
+
|
|
151
|
+
def set_enabled(self, pid: str, on: bool) -> PluginInfo:
|
|
152
|
+
with self.lock:
|
|
153
|
+
info = self.plugins.get(pid)
|
|
154
|
+
if info is None or info.builtin:
|
|
155
|
+
raise KeyError(pid)
|
|
156
|
+
(self.enabled.add if on else self.enabled.discard)(pid)
|
|
157
|
+
self._save_state()
|
|
158
|
+
self.reload()
|
|
159
|
+
return self.plugins[pid]
|
|
160
|
+
|
|
161
|
+
def run_action(self, action_id: str, tags: dict[str, list[str]]) -> dict:
|
|
162
|
+
"""The changes an action wants for one track (only real changes, values as lists)."""
|
|
163
|
+
action = self.actions[action_id]
|
|
164
|
+
try:
|
|
165
|
+
result = action.run({k: list(v) for k, v in tags.items()})
|
|
166
|
+
except Exception as exc: # noqa: BLE001 - a plugin bug is reported, never crashes Codetta
|
|
167
|
+
raise ActionError(f"{action.label} failed: {type(exc).__name__}: {exc}") from exc
|
|
168
|
+
if not result:
|
|
169
|
+
return {}
|
|
170
|
+
if not isinstance(result, dict):
|
|
171
|
+
raise ActionError(f"{action.label} returned something that isn't a set of tags")
|
|
172
|
+
changes = {}
|
|
173
|
+
for key, value in result.items():
|
|
174
|
+
key = str(key).lower()
|
|
175
|
+
new = [] if value is None else [value] if isinstance(value, str) else [str(v) for v in value]
|
|
176
|
+
new = [v for v in new if v.strip()]
|
|
177
|
+
if new != [v for v in tags.get(key, []) if v.strip()]:
|
|
178
|
+
changes[key] = new or None
|
|
179
|
+
return changes
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
class ActionError(Exception):
|
|
183
|
+
pass
|
codetta/core/presets.py
ADDED
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
"""Tag Presets: saved sets of tags you can apply to many files at once.
|
|
2
|
+
|
|
3
|
+
A preset is a JSON file in the presets folder (``config/presets/`` by
|
|
4
|
+
default), for example ``config/presets/album-folder.json``::
|
|
5
|
+
|
|
6
|
+
{
|
|
7
|
+
"name": "Album Folder",
|
|
8
|
+
"description": "Turn a folder of loose files into a tagged album.",
|
|
9
|
+
"tags": {
|
|
10
|
+
"title": "{filename_title}",
|
|
11
|
+
"album": "{folder}",
|
|
12
|
+
"tracknumber": "{track}/{tracktotal}",
|
|
13
|
+
"artist": "",
|
|
14
|
+
"genre": ["Hip-Hop", "Lo-Fi"]
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
Values can be a single string or a list (for multi-value tags). Blank values
|
|
19
|
+
are ignored when applying, so a preset can list fields to fill in later.
|
|
20
|
+
|
|
21
|
+
Placeholders are filled in per file:
|
|
22
|
+
|
|
23
|
+
{filename} the file name without its extension
|
|
24
|
+
{filename_title} the file name tidied into a title ("01_my_song" -> "my song")
|
|
25
|
+
{folder} the name of the folder the file is in
|
|
26
|
+
{track} the file's position in the batch (1, 2, 3, ...)
|
|
27
|
+
{tracktotal} how many files are in the batch
|
|
28
|
+
|
|
29
|
+
Applying a preset:
|
|
30
|
+
|
|
31
|
+
* ``mode="fill"`` (the default) only sets tags the file doesn't already have,
|
|
32
|
+
so it's safe to run over partly tagged files.
|
|
33
|
+
* ``mode="overwrite"`` replaces existing values.
|
|
34
|
+
* Tags a format can't store (rare after ``tagmap``) are skipped for that file
|
|
35
|
+
and reported, rather than failing the whole batch.
|
|
36
|
+
* ``dry_run=True`` reports what *would* change without touching any files.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
from __future__ import annotations
|
|
40
|
+
|
|
41
|
+
import hashlib
|
|
42
|
+
import json
|
|
43
|
+
import os
|
|
44
|
+
import re
|
|
45
|
+
import tempfile
|
|
46
|
+
from dataclasses import dataclass, field
|
|
47
|
+
from enum import StrEnum
|
|
48
|
+
from pathlib import Path
|
|
49
|
+
|
|
50
|
+
from codetta.core.library import natural_key
|
|
51
|
+
from codetta.core.engine import (
|
|
52
|
+
SUPPORTED_EXTENSIONS,
|
|
53
|
+
MetadataEngine,
|
|
54
|
+
MetadataError,
|
|
55
|
+
TagValue,
|
|
56
|
+
is_tag_supported,
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
PLACEHOLDERS = frozenset({"filename", "filename_title", "folder", "track", "tracktotal"})
|
|
60
|
+
_PLACEHOLDER_RE = re.compile(r"\{([a-z_]+)\}")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class PresetError(Exception):
|
|
64
|
+
"""A preset is invalid, missing, or could not be saved."""
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class PresetNotFoundError(PresetError):
|
|
68
|
+
"""No preset with that name exists."""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class ApplyMode(StrEnum):
|
|
72
|
+
FILL = "fill" # only set tags the file doesn't already have
|
|
73
|
+
OVERWRITE = "overwrite" # replace existing values
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass
|
|
77
|
+
class Preset:
|
|
78
|
+
name: str
|
|
79
|
+
tags: dict[str, list[str]] = field(default_factory=dict)
|
|
80
|
+
description: str = ""
|
|
81
|
+
|
|
82
|
+
def __post_init__(self) -> None:
|
|
83
|
+
self.name = self.name.strip()
|
|
84
|
+
if not self.name or not slugify(self.name):
|
|
85
|
+
raise PresetError("A preset needs a name")
|
|
86
|
+
self.tags = {key.strip().lower(): _as_list(value) for key, value in self.tags.items()}
|
|
87
|
+
for key, values in self.tags.items():
|
|
88
|
+
if not key:
|
|
89
|
+
raise PresetError(f"Preset '{self.name}' has a blank tag name")
|
|
90
|
+
for value in values:
|
|
91
|
+
unknown = set(_PLACEHOLDER_RE.findall(value)) - PLACEHOLDERS
|
|
92
|
+
if unknown:
|
|
93
|
+
raise PresetError(
|
|
94
|
+
f"Preset '{self.name}', tag '{key}': unknown placeholder "
|
|
95
|
+
f"{{{sorted(unknown)[0]}}}. Available: "
|
|
96
|
+
+ ", ".join(f"{{{p}}}" for p in sorted(PLACEHOLDERS))
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
@property
|
|
100
|
+
def slug(self) -> str:
|
|
101
|
+
return slugify(self.name)
|
|
102
|
+
|
|
103
|
+
@classmethod
|
|
104
|
+
def from_dict(cls, data: object) -> Preset:
|
|
105
|
+
if not isinstance(data, dict):
|
|
106
|
+
raise PresetError("A preset must be a JSON object")
|
|
107
|
+
name, tags = data.get("name"), data.get("tags", {})
|
|
108
|
+
description = data.get("description", "")
|
|
109
|
+
if not isinstance(name, str):
|
|
110
|
+
raise PresetError("A preset needs a \"name\" string")
|
|
111
|
+
if not isinstance(tags, dict):
|
|
112
|
+
raise PresetError(f"Preset '{name}': \"tags\" must be an object")
|
|
113
|
+
if not isinstance(description, str):
|
|
114
|
+
raise PresetError(f"Preset '{name}': \"description\" must be a string")
|
|
115
|
+
for key, value in tags.items():
|
|
116
|
+
ok = isinstance(value, str) or (
|
|
117
|
+
isinstance(value, list) and all(isinstance(v, str) for v in value)
|
|
118
|
+
)
|
|
119
|
+
if not ok:
|
|
120
|
+
raise PresetError(
|
|
121
|
+
f"Preset '{name}', tag '{key}': value must be a string or list of strings"
|
|
122
|
+
)
|
|
123
|
+
return cls(name=name, tags=tags, description=description)
|
|
124
|
+
|
|
125
|
+
def to_dict(self) -> dict:
|
|
126
|
+
return {
|
|
127
|
+
"name": self.name,
|
|
128
|
+
"description": self.description,
|
|
129
|
+
# Single values are saved as plain strings to keep the JSON readable.
|
|
130
|
+
"tags": {k: v[0] if len(v) == 1 else v for k, v in self.tags.items()},
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class PresetStore:
|
|
135
|
+
"""Loads and saves presets as one JSON file each in ``directory``."""
|
|
136
|
+
|
|
137
|
+
def __init__(self, directory: str | Path) -> None:
|
|
138
|
+
self.directory = Path(directory)
|
|
139
|
+
|
|
140
|
+
def list(self) -> list[Preset]:
|
|
141
|
+
"""All valid presets, sorted by name. Broken files are skipped."""
|
|
142
|
+
if not self.directory.is_dir():
|
|
143
|
+
return []
|
|
144
|
+
presets = []
|
|
145
|
+
for path in self.directory.glob("*.json"):
|
|
146
|
+
if path.name.startswith("."):
|
|
147
|
+
continue # e.g. a leftover temp file from an interrupted save
|
|
148
|
+
try:
|
|
149
|
+
presets.append(self._read(path))
|
|
150
|
+
except PresetError:
|
|
151
|
+
continue # one bad hand-edited file shouldn't hide the rest
|
|
152
|
+
return sorted(presets, key=lambda lo: lo.name.lower())
|
|
153
|
+
|
|
154
|
+
def get(self, name: str) -> Preset:
|
|
155
|
+
path = self._path_for(name)
|
|
156
|
+
if not path.is_file():
|
|
157
|
+
raise PresetNotFoundError(f"No preset named '{name}'")
|
|
158
|
+
return self._read(path)
|
|
159
|
+
|
|
160
|
+
def save(self, preset: Preset) -> Path:
|
|
161
|
+
"""Save (or replace) a preset. Returns the file it was written to."""
|
|
162
|
+
self.directory.mkdir(parents=True, exist_ok=True)
|
|
163
|
+
path = self._path_for(preset.name)
|
|
164
|
+
text = json.dumps(preset.to_dict(), indent=2, ensure_ascii=False) + "\n"
|
|
165
|
+
fd, temp_name = tempfile.mkstemp(prefix=".codetta-", suffix=".json", dir=self.directory)
|
|
166
|
+
try:
|
|
167
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
168
|
+
f.write(text)
|
|
169
|
+
os.replace(temp_name, path)
|
|
170
|
+
except BaseException:
|
|
171
|
+
Path(temp_name).unlink(missing_ok=True)
|
|
172
|
+
raise
|
|
173
|
+
return path
|
|
174
|
+
|
|
175
|
+
def delete(self, name: str) -> None:
|
|
176
|
+
path = self._path_for(name)
|
|
177
|
+
if not path.is_file():
|
|
178
|
+
raise PresetNotFoundError(f"No preset named '{name}'")
|
|
179
|
+
path.unlink()
|
|
180
|
+
|
|
181
|
+
def install_defaults(self) -> list[Preset]:
|
|
182
|
+
"""Save the starter presets that don't exist yet. Returns those added."""
|
|
183
|
+
added = []
|
|
184
|
+
for preset in default_presets():
|
|
185
|
+
if not self._path_for(preset.name).exists():
|
|
186
|
+
self.save(preset)
|
|
187
|
+
added.append(preset)
|
|
188
|
+
return added
|
|
189
|
+
|
|
190
|
+
def _path_for(self, name: str) -> Path:
|
|
191
|
+
slug = slugify(name)
|
|
192
|
+
if not slug:
|
|
193
|
+
raise PresetError(f"Invalid preset name: '{name}'")
|
|
194
|
+
return self.directory / f"{slug}.json"
|
|
195
|
+
|
|
196
|
+
def _read(self, path: Path) -> Preset:
|
|
197
|
+
try:
|
|
198
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
199
|
+
except (OSError, json.JSONDecodeError) as exc:
|
|
200
|
+
raise PresetError(f"Could not read preset {path.name}: {exc}") from exc
|
|
201
|
+
return Preset.from_dict(data)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
# --- Applying presets -------------------------------------------------------
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
@dataclass
|
|
208
|
+
class FileResult:
|
|
209
|
+
"""What applying a preset did (or would do) to one file."""
|
|
210
|
+
|
|
211
|
+
path: Path
|
|
212
|
+
applied: dict[str, list[str]] = field(default_factory=dict)
|
|
213
|
+
kept_existing: list[str] = field(default_factory=list) # fill mode: already had a value
|
|
214
|
+
unsupported: list[str] = field(default_factory=list) # this format can't store it
|
|
215
|
+
previous: dict[str, list[str]] = field(default_factory=dict) # values before (for undo)
|
|
216
|
+
error: str | None = None
|
|
217
|
+
|
|
218
|
+
@property
|
|
219
|
+
def ok(self) -> bool:
|
|
220
|
+
return self.error is None
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def apply_preset(
|
|
224
|
+
engine: MetadataEngine,
|
|
225
|
+
preset: Preset,
|
|
226
|
+
paths: list[str | Path],
|
|
227
|
+
mode: ApplyMode | str = ApplyMode.FILL,
|
|
228
|
+
dry_run: bool = False,
|
|
229
|
+
) -> list[FileResult]:
|
|
230
|
+
"""Apply ``preset`` to ``paths``, in the order given.
|
|
231
|
+
|
|
232
|
+
``{track}`` and ``{tracktotal}`` come from that order. One file failing
|
|
233
|
+
doesn't stop the others; check each result's ``error``.
|
|
234
|
+
"""
|
|
235
|
+
mode = ApplyMode(mode)
|
|
236
|
+
paths = [Path(p) for p in paths]
|
|
237
|
+
return [
|
|
238
|
+
_apply_one(engine, preset, path, mode, dry_run, track=i, tracktotal=len(paths))
|
|
239
|
+
for i, path in enumerate(paths, start=1)
|
|
240
|
+
]
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def apply_preset_to_folder(
|
|
244
|
+
engine: MetadataEngine,
|
|
245
|
+
preset: Preset,
|
|
246
|
+
folder: str | Path,
|
|
247
|
+
mode: ApplyMode | str = ApplyMode.FILL,
|
|
248
|
+
recursive: bool = False,
|
|
249
|
+
dry_run: bool = False,
|
|
250
|
+
) -> list[FileResult]:
|
|
251
|
+
"""Apply ``preset`` to every audio file in ``folder`` (e.g. one album).
|
|
252
|
+
|
|
253
|
+
Files are numbered in natural name order ("2 song" before "10 song").
|
|
254
|
+
With ``recursive=True``, each subfolder is numbered separately, so a
|
|
255
|
+
folder per disc or per album gets its own track numbers.
|
|
256
|
+
"""
|
|
257
|
+
folder = Path(folder)
|
|
258
|
+
if not folder.is_dir():
|
|
259
|
+
raise FileNotFoundError(f"No such folder: {folder}")
|
|
260
|
+
groups = _audio_files_by_folder(folder, recursive)
|
|
261
|
+
results = []
|
|
262
|
+
for files in groups:
|
|
263
|
+
results.extend(apply_preset(engine, preset, files, mode, dry_run))
|
|
264
|
+
return results
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _apply_one(
|
|
268
|
+
engine: MetadataEngine,
|
|
269
|
+
preset: Preset,
|
|
270
|
+
path: Path,
|
|
271
|
+
mode: ApplyMode,
|
|
272
|
+
dry_run: bool,
|
|
273
|
+
track: int,
|
|
274
|
+
tracktotal: int,
|
|
275
|
+
) -> FileResult:
|
|
276
|
+
result = FileResult(path=path)
|
|
277
|
+
try:
|
|
278
|
+
current = engine.load_metadata(path)
|
|
279
|
+
context = {
|
|
280
|
+
"filename": path.stem,
|
|
281
|
+
"filename_title": filename_to_title(path.stem),
|
|
282
|
+
"folder": path.parent.name,
|
|
283
|
+
"track": str(track),
|
|
284
|
+
"tracktotal": str(tracktotal),
|
|
285
|
+
}
|
|
286
|
+
changes: dict[str, TagValue] = {}
|
|
287
|
+
for key, values in preset.tags.items():
|
|
288
|
+
filled = [_fill_placeholders(v, context) for v in values]
|
|
289
|
+
filled = [v for v in filled if v.strip()]
|
|
290
|
+
if not filled:
|
|
291
|
+
continue # blank in the preset: nothing to apply
|
|
292
|
+
if not is_tag_supported(current.format, key):
|
|
293
|
+
result.unsupported.append(key)
|
|
294
|
+
elif mode is ApplyMode.FILL and current.tags.get(key):
|
|
295
|
+
result.kept_existing.append(key)
|
|
296
|
+
elif current.tags.get(key) != filled:
|
|
297
|
+
changes[key] = filled
|
|
298
|
+
result.applied = {k: list(v) for k, v in changes.items()}
|
|
299
|
+
result.previous = {k: list(current.tags.get(k, [])) for k in changes}
|
|
300
|
+
if changes and not dry_run:
|
|
301
|
+
engine.update_tags(path, changes)
|
|
302
|
+
except (MetadataError, FileNotFoundError) as exc:
|
|
303
|
+
result.applied = {}
|
|
304
|
+
result.error = str(exc)
|
|
305
|
+
return result
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _audio_files_by_folder(folder: Path, recursive: bool) -> list[list[Path]]:
|
|
309
|
+
folders = [folder]
|
|
310
|
+
if recursive:
|
|
311
|
+
folders += sorted(
|
|
312
|
+
(d for d in folder.rglob("*") if d.is_dir() and not _is_hidden(d, folder)),
|
|
313
|
+
key=lambda d: _natural_key(str(d.relative_to(folder))),
|
|
314
|
+
)
|
|
315
|
+
groups = []
|
|
316
|
+
for d in folders:
|
|
317
|
+
files = sorted(
|
|
318
|
+
(
|
|
319
|
+
f
|
|
320
|
+
for f in d.iterdir()
|
|
321
|
+
if f.is_file()
|
|
322
|
+
and not f.name.startswith(".") # includes .codetta-* temp files
|
|
323
|
+
and f.suffix.lower() in SUPPORTED_EXTENSIONS
|
|
324
|
+
),
|
|
325
|
+
key=lambda f: _natural_key(f.name),
|
|
326
|
+
)
|
|
327
|
+
if files:
|
|
328
|
+
groups.append(files)
|
|
329
|
+
return groups
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
# --- Helpers -------------------------------------------------------------------
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def slugify(name: str) -> str:
|
|
336
|
+
""""Album Folder!" -> "album-folder" (used as the file name).
|
|
337
|
+
|
|
338
|
+
Names with no letters or digits at all (e.g. only emoji: "🔥🔥") get a
|
|
339
|
+
short stable id instead, so any non-blank name works.
|
|
340
|
+
"""
|
|
341
|
+
slug = re.sub(r"\W+", "-", name.strip().lower()).strip("-_")
|
|
342
|
+
if slug:
|
|
343
|
+
return slug
|
|
344
|
+
if not name.strip():
|
|
345
|
+
return ""
|
|
346
|
+
return "preset-" + hashlib.sha256(name.strip().encode("utf-8")).hexdigest()[:10]
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def filename_to_title(stem: str) -> str:
|
|
350
|
+
"""Tidy a file name into a usable title.
|
|
351
|
+
|
|
352
|
+
Strips a leading track number and turns underscores into spaces:
|
|
353
|
+
"01 - My Song" -> "My Song", "03_late_night" -> "late night".
|
|
354
|
+
"""
|
|
355
|
+
title = stem.replace("_", " ")
|
|
356
|
+
# A 1-3 digit number followed by a separator or space: "01 - ", "3. ", "07 ".
|
|
357
|
+
# "2Pac" and "1979" are left alone.
|
|
358
|
+
stripped = re.sub(r"^\s*\d{1,3}(?:\s*[-.)\]]\s*|\s+)(?=\S)", "", title, count=1)
|
|
359
|
+
title = stripped if stripped.strip() else title # "1979" stays "1979"
|
|
360
|
+
return re.sub(r"\s+", " ", title).strip()
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _fill_placeholders(value: str, context: dict[str, str]) -> str:
|
|
364
|
+
return _PLACEHOLDER_RE.sub(lambda m: context.get(m.group(1), m.group(0)), value)
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def _as_list(value: TagValue) -> list[str]:
|
|
368
|
+
if value is None:
|
|
369
|
+
return []
|
|
370
|
+
if isinstance(value, str):
|
|
371
|
+
return [value]
|
|
372
|
+
return [str(v) for v in value]
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def _natural_key(text: str) -> list:
|
|
376
|
+
return natural_key(text)
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def _is_hidden(path: Path, root: Path) -> bool:
|
|
380
|
+
return any(part.startswith(".") for part in path.relative_to(root).parts)
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
# --- Starter presets ----------------------------------------------------------
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def default_presets() -> list[Preset]:
|
|
387
|
+
"""Starter presets. Blank fields are reminders of what to fill in."""
|
|
388
|
+
return [
|
|
389
|
+
Preset(
|
|
390
|
+
name="Single",
|
|
391
|
+
description=(
|
|
392
|
+
"For a loose track (e.g. a SoundCloud download): makes it show up as "
|
|
393
|
+
"its own single in Navidrome instead of under 'Unknown Album'."
|
|
394
|
+
),
|
|
395
|
+
tags={
|
|
396
|
+
"title": "{filename_title}",
|
|
397
|
+
"album": "{filename_title}",
|
|
398
|
+
"artist": "",
|
|
399
|
+
"albumartist": "",
|
|
400
|
+
"genre": "",
|
|
401
|
+
"date": "",
|
|
402
|
+
"tracknumber": "1/1",
|
|
403
|
+
"discnumber": "1/1",
|
|
404
|
+
"releasetype": "single",
|
|
405
|
+
"media": "Digital Media",
|
|
406
|
+
"comment": "",
|
|
407
|
+
},
|
|
408
|
+
),
|
|
409
|
+
Preset(
|
|
410
|
+
name="Album Folder",
|
|
411
|
+
description=(
|
|
412
|
+
"For a folder of untagged tracks: names the album after the folder "
|
|
413
|
+
"and numbers the tracks in file-name order."
|
|
414
|
+
),
|
|
415
|
+
tags={
|
|
416
|
+
"title": "{filename_title}",
|
|
417
|
+
"album": "{folder}",
|
|
418
|
+
"artist": "",
|
|
419
|
+
"albumartist": "",
|
|
420
|
+
"genre": "",
|
|
421
|
+
"date": "",
|
|
422
|
+
"tracknumber": "{track}/{tracktotal}",
|
|
423
|
+
"discnumber": "1/1",
|
|
424
|
+
"releasetype": "album",
|
|
425
|
+
"media": "Digital Media",
|
|
426
|
+
},
|
|
427
|
+
),
|
|
428
|
+
Preset(
|
|
429
|
+
name="Full Credits",
|
|
430
|
+
description=(
|
|
431
|
+
"The extra detail Navidrome / OpenSubsonic clients can show: credits, "
|
|
432
|
+
"mood, label and release info. Apply on top of Single or Album Folder."
|
|
433
|
+
),
|
|
434
|
+
tags={
|
|
435
|
+
"artists": "",
|
|
436
|
+
"albumartists": "",
|
|
437
|
+
"composer": "",
|
|
438
|
+
"lyricist": "",
|
|
439
|
+
"producer": "",
|
|
440
|
+
"engineer": "",
|
|
441
|
+
"mixer": "",
|
|
442
|
+
"mood": "",
|
|
443
|
+
"bpm": "",
|
|
444
|
+
"label": "",
|
|
445
|
+
"catalognumber": "",
|
|
446
|
+
"releasestatus": "official",
|
|
447
|
+
"originaldate": "",
|
|
448
|
+
"copyright": "",
|
|
449
|
+
"language": "",
|
|
450
|
+
},
|
|
451
|
+
),
|
|
452
|
+
]
|