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.
Files changed (63) hide show
  1. codetta/CHANGELOG.md +153 -0
  2. codetta/__init__.py +8 -0
  3. codetta/__main__.py +5 -0
  4. codetta/cli/__init__.py +0 -0
  5. codetta/cli/__main__.py +59 -0
  6. codetta/cli/run.py +129 -0
  7. codetta/core/__init__.py +0 -0
  8. codetta/core/acoustid.py +225 -0
  9. codetta/core/activity.py +161 -0
  10. codetta/core/artwork.py +238 -0
  11. codetta/core/auth.py +362 -0
  12. codetta/core/avatar.py +92 -0
  13. codetta/core/changelog.py +51 -0
  14. codetta/core/connections.py +159 -0
  15. codetta/core/describe.py +69 -0
  16. codetta/core/engine.py +470 -0
  17. codetta/core/health.py +520 -0
  18. codetta/core/inbox.py +195 -0
  19. codetta/core/index.py +672 -0
  20. codetta/core/library.py +177 -0
  21. codetta/core/musicbrainz.py +662 -0
  22. codetta/core/notifications.py +77 -0
  23. codetta/core/onboarding.py +39 -0
  24. codetta/core/organize.py +490 -0
  25. codetta/core/plugins.py +183 -0
  26. codetta/core/presets.py +452 -0
  27. codetta/core/providers.py +203 -0
  28. codetta/core/rawtags.py +135 -0
  29. codetta/core/slskd.py +650 -0
  30. codetta/core/tagmap.py +538 -0
  31. codetta/core/undo.py +186 -0
  32. codetta/core/updates.py +132 -0
  33. codetta/plugins/__init__.py +63 -0
  34. codetta/plugins/builtin/__init__.py +3 -0
  35. codetta/plugins/builtin/tidy.py +70 -0
  36. codetta/web/__init__.py +0 -0
  37. codetta/web/app.py +2909 -0
  38. codetta/web/security.py +170 -0
  39. codetta/web/static/app.css +2684 -0
  40. codetta/web/static/app.js +5694 -0
  41. codetta/web/static/apple-touch-icon.png +0 -0
  42. codetta/web/static/fonts/LICENSE-Inter.txt +93 -0
  43. codetta/web/static/fonts/LICENSE-SchibstedGrotesk.txt +93 -0
  44. codetta/web/static/fonts/inter-cyrillic.woff2 +0 -0
  45. codetta/web/static/fonts/schibsted-grotesk.woff2 +0 -0
  46. codetta/web/static/icon.svg +1 -0
  47. codetta/web/static/icons/codetta-dark.png +0 -0
  48. codetta/web/static/icons/codetta-dark.svg +1 -0
  49. codetta/web/static/icons/codetta-dark.webp +0 -0
  50. codetta/web/static/icons/codetta-light.png +0 -0
  51. codetta/web/static/icons/codetta-light.svg +1 -0
  52. codetta/web/static/icons/codetta-light.webp +0 -0
  53. codetta/web/static/icons/codetta.png +0 -0
  54. codetta/web/static/icons/codetta.svg +1 -0
  55. codetta/web/static/icons/codetta.webp +0 -0
  56. codetta/web/static/index.html +473 -0
  57. codetta/web/static/theme.js +12 -0
  58. codetta-0.8.1.dist-info/METADATA +282 -0
  59. codetta-0.8.1.dist-info/RECORD +63 -0
  60. codetta-0.8.1.dist-info/WHEEL +5 -0
  61. codetta-0.8.1.dist-info/entry_points.txt +2 -0
  62. codetta-0.8.1.dist-info/licenses/LICENSE +661 -0
  63. codetta-0.8.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,69 @@
1
+ """What the search index stores about one file, as plain data.
2
+
3
+ A module-level function (not a closure) so the index can run it in worker
4
+ processes when it has thousands of files to read: reading tags is CPU-bound
5
+ Python, so processes scale where threads don't (threads were 3x *slower*).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import os
12
+ from pathlib import Path
13
+
14
+ from codetta.core.engine import MetadataEngine
15
+
16
+ _engine: MetadataEngine | None = None
17
+
18
+
19
+ def describe_file(path: Path, rel: str) -> dict:
20
+ """The track details for ``rel`` (same shape as the API's TrackOut)."""
21
+ global _engine
22
+ if _engine is None:
23
+ _engine = MetadataEngine()
24
+ meta = _engine.load_metadata(path)
25
+ try:
26
+ mtime = os.stat(path).st_mtime_ns
27
+ except OSError:
28
+ mtime = None
29
+ art = None
30
+ try:
31
+ a = _engine.read_artwork(path)
32
+ if a is not None:
33
+ art = {"hash": hashlib.sha256(a.data).hexdigest()[:16], "width": a.width, "height": a.height}
34
+ except Exception: # noqa: BLE001 - a broken picture must not hide the track
35
+ art = None
36
+ return {"path": rel, "name": rel.rsplit("/", 1)[-1], "format": meta.format, "tags": meta.tags,
37
+ "duration": meta.duration, "bitrate": meta.bitrate, "sample_rate": meta.sample_rate,
38
+ "channels": meta.channels, "mtime": mtime, "art": art, "error": None, "partial": False}
39
+
40
+
41
+ def describe_many(root: str, items: list[tuple[str, int, int]]) -> list[tuple[str, int, int, dict]]:
42
+ """Worker-process entry point: describe a chunk of files (rel, mtime_ns, size)."""
43
+ out = []
44
+ for rel, mtime, size in items:
45
+ try:
46
+ track = describe_file(Path(root) / rel, rel)
47
+ except Exception as exc: # noqa: BLE001 - one bad file must not stop the scan
48
+ track = {"path": rel, "name": rel.rsplit("/", 1)[-1], "error": str(exc) or type(exc).__name__}
49
+ out.append((rel, mtime, size, track))
50
+ return out
51
+
52
+
53
+ def _worker_main() -> None:
54
+ """``python -m codetta.core.describe``: a helper process for big index scans.
55
+
56
+ Reads one JSON job per line on stdin ({"root": ..., "items": [[rel, mtime, size], ...]}) and
57
+ answers with one JSON line of results. A plain subprocess (not multiprocessing), so it never
58
+ re-imports whatever started Codetta, whichever way that was."""
59
+ import json
60
+ import sys
61
+ for line in sys.stdin:
62
+ job = json.loads(line)
63
+ result = describe_many(job["root"], [tuple(i) for i in job["items"]])
64
+ sys.stdout.write(json.dumps(result, ensure_ascii=False) + "\n")
65
+ sys.stdout.flush()
66
+
67
+
68
+ if __name__ == "__main__":
69
+ _worker_main()
codetta/core/engine.py ADDED
@@ -0,0 +1,470 @@
1
+ """Core metadata engine: reads and writes tags on audio files.
2
+
3
+ Every supported format is opened through mutagen's "easy" interface, so tags
4
+ come back with the same friendly names regardless of format (``title``,
5
+ ``artist``, ``albumartist``, ``tracknumber``, ...) instead of raw ID3 frame
6
+ IDs like ``TIT2`` or MP4 atoms like ``\\xa9nam``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import contextlib
12
+ import os
13
+ import shutil
14
+ import tempfile
15
+ import threading
16
+ from collections.abc import Callable, Iterable, Mapping
17
+ from dataclasses import dataclass, field
18
+ from pathlib import Path
19
+
20
+ import mutagen
21
+ from mutagen.aiff import AIFF
22
+ from mutagen.asf import ASF
23
+ from mutagen.dsf import DSF
24
+ from mutagen.easymp4 import EasyMP4
25
+ from mutagen.flac import FLAC
26
+ from mutagen.mp3 import MP3, EasyMP3
27
+ from mutagen.mp4 import MP4
28
+ from mutagen.oggflac import OggFLAC
29
+ from mutagen.oggopus import OggOpus
30
+ from mutagen.oggspeex import OggSpeex
31
+ from mutagen.oggvorbis import OggVorbis
32
+ from mutagen.trueaudio import EasyTrueAudio, TrueAudio
33
+ from mutagen.wave import WAVE
34
+ from mutagen.wavpack import WavPack
35
+
36
+ # Importing tagmap registers the extra tag names (mood, label, engineer, ...)
37
+ # so every format shares one vocabulary.
38
+ from codetta.core.artwork import Artwork, ArtworkError, parse_image, read_picture, write_picture
39
+ from codetta.core.tagmap import HIDDEN_ALIASES, is_tag_supported, tag_view
40
+
41
+ __all__ = [
42
+ "SUPPORTED_EXTENSIONS",
43
+ "Artwork",
44
+ "MetadataEngine",
45
+ "MetadataError",
46
+ "TagValue",
47
+ "TrackMetadata",
48
+ "UnsupportedFormatError",
49
+ "is_tag_supported",
50
+ ]
51
+
52
+ # File extensions Codetta will open. Anything else is rejected up front.
53
+ SUPPORTED_EXTENSIONS: frozenset[str] = frozenset({
54
+ ".flac", ".mp3", ".m4a", ".ogg", ".opus", # the original five
55
+ ".wav", ".aif", ".aiff", ".aifc", ".dsf", ".tta", ".mp2", # ID3 tags
56
+ ".wv", ".wma", ".m4b", ".oga", ".spx", # APEv2, ASF, audiobooks, Ogg FLAC, Speex
57
+ })
58
+
59
+ # The mutagen class detected from the file's contents -> Codetta's format name.
60
+ # Detection is by content (see _sniff_format), so a mislabelled file is still
61
+ # identified correctly.
62
+ _FORMAT_NAMES: dict[type, str] = {
63
+ FLAC: "flac",
64
+ EasyMP3: "mp3",
65
+ EasyMP4: "m4a",
66
+ OggVorbis: "ogg",
67
+ OggOpus: "opus",
68
+ OggFLAC: "oggflac",
69
+ OggSpeex: "speex",
70
+ WAVE: "wav",
71
+ AIFF: "aiff",
72
+ DSF: "dsf",
73
+ EasyTrueAudio: "tta",
74
+ WavPack: "wavpack",
75
+ ASF: "wma",
76
+ }
77
+
78
+
79
+ def _format_of(audio) -> str:
80
+ name = _FORMAT_NAMES[type(audio)]
81
+ if name == "mp3" and getattr(audio.info, "layer", 3) == 2:
82
+ return "mp2" # MPEG layer II: same container and tags as MP3
83
+ return name
84
+
85
+ # OGG/Opus (and some old files) store cover art inside a text field as a big
86
+ # base64 blob. It isn't a text tag, so it's hidden from ``tags`` and can't be
87
+ # overwritten as text. (Other formats keep pictures outside the tag list.)
88
+ COVER_ART_KEYS = frozenset({"metadata_block_picture", "coverart", "coverartmime"})
89
+
90
+
91
+ # A tag value as callers may pass it: one string, several strings, or None.
92
+ # None, "" and [] all mean "remove this tag".
93
+ TagValue = str | Iterable[str] | None
94
+
95
+
96
+ # One lock per file (by real path): two saves to the same file at the same
97
+ # moment (two devices, a double-tap) take turns, and the second one starts from
98
+ # the first one's result instead of overwriting it.
99
+ _file_locks: dict[str, threading.Lock] = {}
100
+ _file_locks_guard = threading.Lock()
101
+
102
+
103
+ def file_lock(path: Path) -> threading.Lock:
104
+ """The lock that guards writes to ``path`` (also taken when Codetta moves it)."""
105
+ return _lock_for(Path(path))
106
+
107
+
108
+ def _lock_for(path: Path) -> threading.Lock:
109
+ key = os.path.realpath(path)
110
+ with _file_locks_guard:
111
+ lock = _file_locks.get(key)
112
+ if lock is None:
113
+ if len(_file_locks) > 5000: # forget idle locks so this can't grow forever
114
+ for k in [k for k, v in _file_locks.items() if not v.locked()]:
115
+ del _file_locks[k]
116
+ lock = _file_locks[key] = threading.Lock()
117
+ return lock
118
+
119
+
120
+ class MetadataError(Exception):
121
+ """A file could not be read or written (e.g. it is corrupt or truncated)."""
122
+
123
+
124
+ class UnsupportedFormatError(MetadataError):
125
+ """The file is not one of the audio formats Codetta handles."""
126
+
127
+
128
+ @dataclass(frozen=True)
129
+ class TrackMetadata:
130
+ """Everything Codetta knows about one audio file."""
131
+
132
+ path: Path
133
+ format: str
134
+ # Tag name -> list of values. Lists because most formats allow a tag to
135
+ # appear more than once (e.g. two ``artist`` entries).
136
+ tags: dict[str, list[str]] = field(default_factory=dict)
137
+ duration: float | None = None # seconds
138
+ bitrate: int | None = None # bits per second
139
+ sample_rate: int | None = None # Hz
140
+ channels: int | None = None
141
+
142
+
143
+ class MetadataEngine:
144
+ """Reads and writes tags on audio files."""
145
+
146
+ def load_metadata(self, path: str | Path) -> TrackMetadata:
147
+ """Read the tags and audio properties of ``path``.
148
+
149
+ This only reads; the file is never modified.
150
+
151
+ Raises:
152
+ FileNotFoundError: ``path`` does not exist or is not a file.
153
+ UnsupportedFormatError: the file is not a supported audio format.
154
+ MetadataError: the file looks supported but could not be parsed.
155
+ """
156
+ path = Path(path)
157
+ if not path.is_file():
158
+ raise FileNotFoundError(f"No such audio file: {path}")
159
+ if path.suffix.lower() not in SUPPORTED_EXTENSIONS:
160
+ raise UnsupportedFormatError(f"Unsupported file type '{path.suffix}': {path}")
161
+
162
+ audio = _open_audio(path)
163
+ format_name = _format_of(audio)
164
+
165
+ tags = {
166
+ key.lower(): [str(value) for value in values]
167
+ for key, values in tag_view(audio, format_name).items()
168
+ if key.lower() not in COVER_ART_KEYS
169
+ }
170
+ for old_name in HIDDEN_ALIASES.get(format_name, {}):
171
+ tags.pop(old_name, None)
172
+ info = audio.info
173
+ sample_rate = getattr(info, "sample_rate", None)
174
+ channels = getattr(info, "channels", None)
175
+ if format_name == "tta" and not channels:
176
+ channels = _tta_channels(path) # mutagen doesn't report it for TrueAudio
177
+ if format_name == "opus":
178
+ # Opus always decodes at 48 kHz; mutagen doesn't expose a rate for it.
179
+ sample_rate = 48000
180
+ return TrackMetadata(
181
+ path=path,
182
+ format=format_name,
183
+ tags=dict(sorted(tags.items())),
184
+ duration=getattr(info, "length", None) or None,
185
+ bitrate=getattr(info, "bitrate", None) or None,
186
+ sample_rate=sample_rate or None,
187
+ channels=channels or None,
188
+ )
189
+
190
+ def update_tags(self, path: str | Path, changes: Mapping[str, TagValue],
191
+ before: dict | None = None) -> TrackMetadata:
192
+ """Apply ``changes`` to the tags of ``path`` and return the new metadata.
193
+
194
+ ``changes`` maps tag names to new values. Tags not mentioned are left
195
+ as they are. A value of ``None``, ``""`` or ``[]`` removes that tag::
196
+
197
+ engine.update_tags("song.flac", {"title": "New Title",
198
+ "artist": ["A", "B"],
199
+ "comment": None})
200
+
201
+ Safety: the original file is never edited in place. The changes are
202
+ written to a temporary copy in the same folder, the copy is re-read to
203
+ confirm the tags stuck, and only then does it replace the original in a
204
+ single atomic step. If anything fails, the original is left untouched
205
+ and the copy is deleted.
206
+
207
+ Raises:
208
+ FileNotFoundError: ``path`` does not exist or is not a file.
209
+ UnsupportedFormatError: the file is not a supported audio format.
210
+ MetadataError: the file is read-only, a tag name isn't valid for
211
+ this format, or the write could not be completed or verified.
212
+ """
213
+ path = Path(path)
214
+ original = self.load_metadata(path) # validates path and format
215
+ if before is not None:
216
+ before["tags"] = original.tags # the tags as they were (for undo), without reading the file twice
217
+ normalized = {key.lower(): _normalize_value(value) for key, value in changes.items()}
218
+ _check_changes(normalized)
219
+ if not normalized:
220
+ return original
221
+
222
+ def write_and_verify(temp: Path) -> None:
223
+ self._write_tags(temp, original.format, normalized)
224
+ self._verify_tags(temp, normalized)
225
+
226
+ self._safe_write(path, write_and_verify)
227
+ return self.load_metadata(path)
228
+
229
+ # --- Album art --------------------------------------------------------------
230
+
231
+ def read_artwork(self, path: str | Path) -> Artwork | None:
232
+ """The file's front cover (or first picture), or None if it has none."""
233
+ path = Path(path)
234
+ self.load_metadata(path) # validates path and format
235
+ audio, format_name = _open_raw(path)
236
+ return read_picture(audio, format_name)
237
+
238
+ def update_artwork(self, path: str | Path, image: bytes | None) -> Artwork | None:
239
+ """Embed ``image`` (JPEG or PNG bytes) as the album art, or remove all
240
+ embedded pictures when ``image`` is None. Tags are left untouched.
241
+
242
+ Uses the same temp-copy -> verify -> atomic swap as ``update_tags``.
243
+ """
244
+ path = Path(path)
245
+ try:
246
+ art = parse_image(image) if image is not None else None
247
+ except ArtworkError as exc:
248
+ raise MetadataError(str(exc)) from exc
249
+ original = self.load_metadata(path)
250
+
251
+ def write_and_verify(temp: Path) -> None:
252
+ try:
253
+ audio, format_name = _open_raw(temp)
254
+ write_picture(audio, format_name, art)
255
+ audio.save()
256
+ check, _ = _open_raw(temp)
257
+ after = read_picture(check, format_name)
258
+ except (mutagen.MutagenError, ValueError, KeyError) as exc:
259
+ raise MetadataError(f"Could not save album art to {path}: {exc}") from exc
260
+ saved_ok = after is None if art is None else (after is not None and after.data == art.data)
261
+ if not saved_ok:
262
+ raise MetadataError("Album art did not save correctly")
263
+ if self.load_metadata(temp).tags != original.tags:
264
+ raise MetadataError("Saving album art unexpectedly changed the tags")
265
+
266
+ self._safe_write(path, write_and_verify)
267
+ return art
268
+
269
+ # --- Safe writing -------------------------------------------------------------
270
+
271
+ def _safe_write(self, path: Path, write_and_verify: Callable[[Path], None]) -> None:
272
+ """Run ``write_and_verify`` on a temp copy of ``path``, then swap it in.
273
+
274
+ The original is never edited in place. If anything fails, it is left
275
+ untouched and the copy is deleted.
276
+ """
277
+ with _lock_for(path):
278
+ self._safe_write_locked(path, write_and_verify)
279
+
280
+ def _safe_write_locked(self, path: Path, write_and_verify: Callable[[Path], None]) -> None:
281
+ # If ``path`` is a symlink, edit the file it points to. Otherwise the
282
+ # swap below would replace the link itself with a regular file.
283
+ target = Path(os.path.realpath(path))
284
+ if not os.access(target, os.W_OK):
285
+ raise MetadataError(f"File is read-only: {path}")
286
+
287
+ temp_path = None
288
+ try:
289
+ try:
290
+ fd, temp_name = tempfile.mkstemp(
291
+ prefix=".codetta-", suffix=target.suffix, dir=target.parent
292
+ )
293
+ except OSError as exc:
294
+ raise MetadataError(f"Cannot write to folder {target.parent}: {exc}") from exc
295
+ os.close(fd)
296
+ temp_path = Path(temp_name)
297
+ shutil.copy2(target, temp_path) # also copies permissions
298
+ _copy_ownership(target, temp_path)
299
+
300
+ write_and_verify(temp_path)
301
+
302
+ with open(temp_path, "rb") as f:
303
+ os.fsync(f.fileno()) # make sure it's on disk before the swap
304
+ # Atomic: the original is never half-written. This also gives the
305
+ # file a new identity, so any hard-linked copy (e.g. a torrent
306
+ # client still seeding it) keeps the original bytes.
307
+ os.replace(temp_path, target)
308
+ temp_path = None
309
+ except OSError as exc:
310
+ raise MetadataError(f"Could not write to {path}: {exc}") from exc
311
+ finally:
312
+ if temp_path is not None:
313
+ with contextlib.suppress(OSError):
314
+ temp_path.unlink()
315
+
316
+ def _write_tags(self, path: Path, format_name: str, changes: dict[str, list[str]]) -> None:
317
+ try:
318
+ audio = _open_audio(path)
319
+ tags = tag_view(audio, format_name, create=True)
320
+ for key, values in changes.items():
321
+ if values:
322
+ tags[key] = values
323
+ elif key in tags:
324
+ del tags[key]
325
+ audio.save()
326
+ except (KeyError, ValueError) as exc:
327
+ raise MetadataError(
328
+ f"Invalid tag for a {format_name} file: {exc}"
329
+ ) from exc
330
+ except mutagen.MutagenError as exc:
331
+ raise MetadataError(f"Could not save tags to {path}: {exc}") from exc
332
+
333
+ def _verify_tags(self, path: Path, changes: dict[str, list[str]]) -> None:
334
+ written = self.load_metadata(path).tags
335
+ for key, values in changes.items():
336
+ if written.get(key, []) != values:
337
+ raise MetadataError(
338
+ f"Tag '{key}' did not save correctly "
339
+ f"(wanted {values!r}, file has {written.get(key, [])!r})"
340
+ )
341
+
342
+
343
+ def _open_audio(path: Path):
344
+ """Open ``path`` with mutagen, choosing the format from the file's bytes.
345
+
346
+ mutagen on its own trusts the extension over the contents, so an MP3
347
+ renamed to ``.flac`` would fail to open. Sniffing the header first avoids
348
+ that, and also guarantees only Codetta's own formats are ever tried.
349
+ """
350
+ try:
351
+ kind = _sniff_format(path)
352
+ options = [kind] if kind else list(_FORMAT_NAMES)
353
+ audio = mutagen.File(path, options=options)
354
+ except (mutagen.MutagenError, OSError) as exc:
355
+ raise MetadataError(f"Could not read {path}: {exc}") from exc
356
+ if audio is None or type(audio) not in _FORMAT_NAMES:
357
+ raise UnsupportedFormatError(f"Not a recognised audio file: {path}")
358
+ return audio
359
+
360
+
361
+ def _open_raw(path: Path):
362
+ """Open ``path`` with mutagen's full (non-"easy") classes, for pictures.
363
+
364
+ Returns (audio, format_name).
365
+ """
366
+ audio = _open_audio(path)
367
+ format_name = _format_of(audio)
368
+ raw_class = {"mp3": MP3, "mp2": MP3, "m4a": MP4, "tta": TrueAudio}.get(format_name)
369
+ if raw_class is not None:
370
+ try:
371
+ audio = raw_class(path)
372
+ except (mutagen.MutagenError, OSError) as exc:
373
+ raise MetadataError(f"Could not read {path}: {exc}") from exc
374
+ return audio, format_name
375
+
376
+
377
+ def _sniff_format(path: Path) -> type | None:
378
+ """Identify the audio format from the first bytes of the file, or None."""
379
+ with open(path, "rb") as f:
380
+ head = f.read(64)
381
+ if head.startswith(b"ID3") and len(head) >= 10:
382
+ # Skip an ID3 tag (normally MP3; sometimes stuck on a FLAC or TTA).
383
+ size = (head[6] << 21) | (head[7] << 14) | (head[8] << 7) | head[9]
384
+ f.seek(10 + size)
385
+ after = f.read(4)
386
+ return {b"fLaC": FLAC, b"TTA1": EasyTrueAudio}.get(after, EasyMP3)
387
+ if head.startswith(b"fLaC"):
388
+ return FLAC
389
+ if head.startswith(b"OggS"):
390
+ if b"OpusHead" in head:
391
+ return OggOpus
392
+ if b"\x01vorbis" in head:
393
+ return OggVorbis
394
+ if b"\x7fFLAC" in head:
395
+ return OggFLAC
396
+ if b"Speex " in head:
397
+ return OggSpeex
398
+ return None
399
+ if head[:4] == b"RIFF" and head[8:12] == b"WAVE":
400
+ return WAVE
401
+ if head[:4] == b"FORM" and head[8:12] in (b"AIFF", b"AIFC"):
402
+ return AIFF
403
+ if head.startswith(b"DSD "):
404
+ return DSF
405
+ if head.startswith(b"TTA1"):
406
+ return EasyTrueAudio
407
+ if head.startswith(b"wvpk"):
408
+ return WavPack
409
+ if head.startswith(b"\x30\x26\xb2\x75\x8e\x66\xcf\x11"): # ASF header GUID
410
+ return ASF
411
+ if head[4:8] == b"ftyp":
412
+ return EasyMP4
413
+ if len(head) >= 2 and head[0] == 0xFF and head[1] & 0xE0 == 0xE0:
414
+ return EasyMP3 # MPEG audio frame with no ID3 tag
415
+ return None
416
+
417
+
418
+ def _tta_channels(path: Path) -> int | None:
419
+ """Channel count from a TrueAudio header ("TTA1", format, channels, ...)."""
420
+ try:
421
+ with open(path, "rb") as f:
422
+ head = f.read(10)
423
+ if head.startswith(b"ID3") and len(head) == 10:
424
+ f.seek(10 + ((head[6] << 21) | (head[7] << 14) | (head[8] << 7) | head[9]))
425
+ head = f.read(10)
426
+ if head.startswith(b"TTA1") and len(head) >= 8:
427
+ return int.from_bytes(head[6:8], "little") or None
428
+ except OSError:
429
+ pass
430
+ return None
431
+
432
+
433
+ MAX_TAG_VALUE_CHARS = 100_000 # plenty for long (synced) lyrics; keeps responses bounded
434
+ MAX_TAG_KEYS = 200
435
+
436
+
437
+ def _check_changes(changes: dict[str, list[str]]) -> None:
438
+ """Reject changes that can't be stored safely, before touching the file."""
439
+ if len(changes) > MAX_TAG_KEYS:
440
+ raise MetadataError(f"Too many tags in one change (max {MAX_TAG_KEYS})")
441
+ for key, values in changes.items():
442
+ if len(key) > 200:
443
+ raise MetadataError("Tag name is too long")
444
+ if sum(len(v) for v in values) > MAX_TAG_VALUE_CHARS:
445
+ raise MetadataError(f"Tag '{key}' is too long (max {MAX_TAG_VALUE_CHARS:,} characters)")
446
+ if key in COVER_ART_KEYS:
447
+ raise MetadataError(f"'{key}' holds cover art and can't be edited as text")
448
+ if any("\x00" in v for v in values):
449
+ raise MetadataError(f"Tag '{key}' contains a null character, which can't be stored")
450
+
451
+
452
+ def _normalize_value(value: TagValue) -> list[str]:
453
+ """Turn a caller's tag value into a list of strings ([] means remove)."""
454
+ if value is None:
455
+ return []
456
+ if isinstance(value, str):
457
+ return [value] if value else []
458
+ values = [str(v) for v in value]
459
+ return [] if all(v == "" for v in values) else values
460
+
461
+
462
+ def _copy_ownership(source: Path, dest: Path) -> None:
463
+ """Give ``dest`` the same owner/group as ``source`` where permitted.
464
+
465
+ Matters when Codetta runs as root in Docker: without this, edited files would
466
+ end up owned by root instead of the user who owns the music library.
467
+ """
468
+ st = source.stat()
469
+ with contextlib.suppress(PermissionError, AttributeError):
470
+ os.chown(dest, st.st_uid, st.st_gid)