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/activity.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""Activity log: a record of every change Codetta makes to your files.
|
|
2
|
+
|
|
3
|
+
Entries are kept in memory for the UI and appended to ``activity.jsonl`` in
|
|
4
|
+
the config folder (one JSON object per line), so the history survives
|
|
5
|
+
restarts and you can always check what Codetta did to your library.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import threading
|
|
12
|
+
from collections import deque
|
|
13
|
+
from datetime import UTC, datetime
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
MAX_FILES_PER_ENTRY = 50 # keep entries readable for huge batch edits
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ActivityLog:
|
|
21
|
+
def __init__(self, file: Path | None = None, keep: int = 1000) -> None:
|
|
22
|
+
self.file = file
|
|
23
|
+
self.keep = keep
|
|
24
|
+
self._entries: deque[dict[str, Any]] = deque(maxlen=keep)
|
|
25
|
+
self._lock = threading.Lock()
|
|
26
|
+
self._next_id = 1
|
|
27
|
+
self._lines_in_file = 0
|
|
28
|
+
self._load()
|
|
29
|
+
|
|
30
|
+
def add(
|
|
31
|
+
self,
|
|
32
|
+
kind: str,
|
|
33
|
+
message: str,
|
|
34
|
+
*,
|
|
35
|
+
ok: bool = True,
|
|
36
|
+
files: list[str] | None = None,
|
|
37
|
+
changes: list[dict[str, str]] | None = None,
|
|
38
|
+
errors: list[dict[str, str]] | None = None,
|
|
39
|
+
undo: dict | None = None,
|
|
40
|
+
undoes: int | None = None,
|
|
41
|
+
extra: dict[str, Any] | None = None,
|
|
42
|
+
) -> dict[str, Any]:
|
|
43
|
+
"""Record one action. ``kind`` is "edit", "art", "preset", "musicbrainz" or "undo".
|
|
44
|
+
|
|
45
|
+
``undo`` holds what's needed to reverse it (see codetta.core.undo);
|
|
46
|
+
``undoes`` is the id of the entry this one reversed.
|
|
47
|
+
"""
|
|
48
|
+
files = files or []
|
|
49
|
+
with self._lock:
|
|
50
|
+
entry = {
|
|
51
|
+
"id": self._next_id,
|
|
52
|
+
"time": datetime.now(UTC).isoformat(timespec="seconds"),
|
|
53
|
+
"kind": kind,
|
|
54
|
+
"ok": ok,
|
|
55
|
+
"message": message,
|
|
56
|
+
"files": files[:MAX_FILES_PER_ENTRY],
|
|
57
|
+
"file_count": len(files),
|
|
58
|
+
"changes": changes or [],
|
|
59
|
+
"errors": (errors or [])[:MAX_FILES_PER_ENTRY],
|
|
60
|
+
}
|
|
61
|
+
if undo:
|
|
62
|
+
entry["undo"] = undo
|
|
63
|
+
if undoes is not None:
|
|
64
|
+
entry["undoes"] = undoes
|
|
65
|
+
if extra:
|
|
66
|
+
entry.update(extra)
|
|
67
|
+
self._next_id += 1
|
|
68
|
+
self._entries.append(entry)
|
|
69
|
+
self._append_to_file(entry)
|
|
70
|
+
return self._public(entry, self._undone_ids())
|
|
71
|
+
|
|
72
|
+
def recent(self, limit: int = 50, after_id: int = 0) -> list[dict[str, Any]]:
|
|
73
|
+
"""Newest first, without the (possibly large) undo records.
|
|
74
|
+
|
|
75
|
+
Each entry gets ``can_undo`` and ``undone``. ``after_id`` returns only
|
|
76
|
+
entries newer than that id.
|
|
77
|
+
"""
|
|
78
|
+
with self._lock:
|
|
79
|
+
undone = self._undone_ids()
|
|
80
|
+
entries = [self._public(e, undone) for e in self._entries if e["id"] > after_id]
|
|
81
|
+
return list(reversed(entries))[:limit]
|
|
82
|
+
|
|
83
|
+
def get(self, entry_id: int) -> dict[str, Any] | None:
|
|
84
|
+
"""The full entry, including its undo record."""
|
|
85
|
+
with self._lock:
|
|
86
|
+
for e in self._entries:
|
|
87
|
+
if e["id"] == entry_id:
|
|
88
|
+
return dict(e)
|
|
89
|
+
return None
|
|
90
|
+
|
|
91
|
+
def is_undone(self, entry_id: int) -> bool:
|
|
92
|
+
with self._lock:
|
|
93
|
+
return entry_id in self._undone_ids()
|
|
94
|
+
|
|
95
|
+
def undo_records(self) -> list[dict]:
|
|
96
|
+
with self._lock:
|
|
97
|
+
return [e["undo"] for e in self._entries if e.get("undo")]
|
|
98
|
+
|
|
99
|
+
def _undone_ids(self) -> set[int]:
|
|
100
|
+
"""Entries currently undone. Undoing an undo (redo) re-activates the original."""
|
|
101
|
+
undone: set[int] = set()
|
|
102
|
+
# Newest first: a later undo decides the fate of everything before it.
|
|
103
|
+
for e in sorted(self._entries, key=lambda x: x["id"], reverse=True):
|
|
104
|
+
target = e.get("undoes")
|
|
105
|
+
if target is not None and e["id"] not in undone:
|
|
106
|
+
undone.add(target)
|
|
107
|
+
return undone
|
|
108
|
+
|
|
109
|
+
@staticmethod
|
|
110
|
+
def _public(entry: dict[str, Any], undone: set[int]) -> dict[str, Any]:
|
|
111
|
+
out = {k: v for k, v in entry.items() if k != "undo"}
|
|
112
|
+
out["undone"] = entry["id"] in undone
|
|
113
|
+
out["can_undo"] = bool(entry.get("undo")) and not out["undone"]
|
|
114
|
+
return out
|
|
115
|
+
|
|
116
|
+
# --- Persistence ---------------------------------------------------------------
|
|
117
|
+
|
|
118
|
+
def _load(self) -> None:
|
|
119
|
+
if not self.file or not self.file.is_file():
|
|
120
|
+
return
|
|
121
|
+
try:
|
|
122
|
+
lines = self.file.read_text(encoding="utf-8").splitlines()
|
|
123
|
+
except OSError:
|
|
124
|
+
return
|
|
125
|
+
for line in lines: # the deque keeps only the newest ``keep`` entries
|
|
126
|
+
try:
|
|
127
|
+
entry = json.loads(line)
|
|
128
|
+
except json.JSONDecodeError:
|
|
129
|
+
continue # a half-written line from a crash: skip it
|
|
130
|
+
if isinstance(entry, dict) and isinstance(entry.get("id"), int):
|
|
131
|
+
self._entries.append(entry)
|
|
132
|
+
if self._entries:
|
|
133
|
+
self._next_id = max(e["id"] for e in self._entries) + 1
|
|
134
|
+
self._lines_in_file = len(lines)
|
|
135
|
+
if len(lines) > self.keep * 2:
|
|
136
|
+
self._rewrite() # keep the file from growing forever
|
|
137
|
+
|
|
138
|
+
def _append_to_file(self, entry: dict[str, Any]) -> None:
|
|
139
|
+
if not self.file:
|
|
140
|
+
return
|
|
141
|
+
try:
|
|
142
|
+
self.file.parent.mkdir(parents=True, exist_ok=True)
|
|
143
|
+
with open(self.file, "a", encoding="utf-8") as f:
|
|
144
|
+
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
|
|
145
|
+
self._lines_in_file += 1
|
|
146
|
+
if self._lines_in_file > self.keep * 2:
|
|
147
|
+
self._rewrite() # trim while running, not only at the next restart
|
|
148
|
+
except OSError:
|
|
149
|
+
pass # logging must never break an edit
|
|
150
|
+
|
|
151
|
+
def _rewrite(self) -> None:
|
|
152
|
+
try:
|
|
153
|
+
tmp = self.file.with_suffix(".tmp")
|
|
154
|
+
tmp.write_text(
|
|
155
|
+
"".join(json.dumps(e, ensure_ascii=False) + "\n" for e in self._entries),
|
|
156
|
+
encoding="utf-8",
|
|
157
|
+
)
|
|
158
|
+
tmp.replace(self.file)
|
|
159
|
+
self._lines_in_file = len(self._entries)
|
|
160
|
+
except OSError:
|
|
161
|
+
pass
|
codetta/core/artwork.py
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
"""Embedded album art: reading, validating and writing pictures per format.
|
|
2
|
+
|
|
3
|
+
Each format keeps pictures somewhere different:
|
|
4
|
+
|
|
5
|
+
FLAC METADATA_BLOCK_PICTURE blocks (``audio.pictures``)
|
|
6
|
+
ID3 family ``APIC`` frames (MP3, MP2, WAV, AIFF, DSF, TrueAudio)
|
|
7
|
+
M4A the ``covr`` atom (JPEG or PNG only)
|
|
8
|
+
OGG family a base64-encoded picture block in the ``metadata_block_picture``
|
|
9
|
+
comment (Ogg Vorbis, Opus, Ogg FLAC, Speex)
|
|
10
|
+
WavPack the APEv2 ``Cover Art (Front)`` binary item ("name\\0" + image)
|
|
11
|
+
WMA ``WM/Picture`` attributes (a small binary header + image)
|
|
12
|
+
|
|
13
|
+
Codetta keeps it simple and predictable: *setting* art replaces every embedded
|
|
14
|
+
picture with one front cover, and *removing* art removes them all. Images must
|
|
15
|
+
be JPEG or PNG, which every player (and Navidrome) understands.
|
|
16
|
+
|
|
17
|
+
These functions work on already-opened mutagen objects; the engine handles
|
|
18
|
+
opening files and the safe temp-copy write.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import base64
|
|
24
|
+
import struct
|
|
25
|
+
from dataclasses import dataclass
|
|
26
|
+
|
|
27
|
+
from mutagen.apev2 import BINARY as APE_BINARY
|
|
28
|
+
from mutagen.apev2 import APEValue
|
|
29
|
+
from mutagen.asf import ASFByteArrayAttribute
|
|
30
|
+
from mutagen.flac import Picture
|
|
31
|
+
from mutagen.id3 import APIC
|
|
32
|
+
from mutagen.mp4 import MP4Cover
|
|
33
|
+
|
|
34
|
+
from codetta.core.tagmap import APE_FORMATS, ASF_FORMATS, ID3_FORMATS
|
|
35
|
+
|
|
36
|
+
APE_COVER_KEYS = ("Cover Art (Front)", "Cover Art (Back)", "Cover Art (Other)")
|
|
37
|
+
|
|
38
|
+
MAX_ART_BYTES = 20 * 1024 * 1024 # 20 MB; real covers are usually < 2 MB
|
|
39
|
+
FRONT_COVER = 3 # picture type for "Cover (front)" in FLAC/ID3
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class ArtworkError(ValueError):
|
|
43
|
+
"""The image is not usable as album art."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True)
|
|
47
|
+
class Artwork:
|
|
48
|
+
data: bytes
|
|
49
|
+
mime: str # "image/jpeg" or "image/png"
|
|
50
|
+
width: int | None = None
|
|
51
|
+
height: int | None = None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def sniff_image_type(data: bytes) -> str | None:
|
|
55
|
+
"""The image type from the file's actual bytes (never what it claims to be).
|
|
56
|
+
|
|
57
|
+
Only formats every browser displays safely as an <img>; SVG (which can
|
|
58
|
+
carry scripts) is deliberately not included.
|
|
59
|
+
"""
|
|
60
|
+
if data.startswith(b"\xff\xd8\xff"):
|
|
61
|
+
return "image/jpeg"
|
|
62
|
+
if data.startswith(b"\x89PNG\r\n\x1a\n"):
|
|
63
|
+
return "image/png"
|
|
64
|
+
if data[:4] == b"RIFF" and data[8:12] == b"WEBP":
|
|
65
|
+
return "image/webp"
|
|
66
|
+
if data[:6] in (b"GIF87a", b"GIF89a"):
|
|
67
|
+
return "image/gif"
|
|
68
|
+
return None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def parse_image(data: bytes) -> Artwork:
|
|
72
|
+
"""Check that ``data`` is a JPEG or PNG and read its size."""
|
|
73
|
+
if not data:
|
|
74
|
+
raise ArtworkError("The image is empty")
|
|
75
|
+
if len(data) > MAX_ART_BYTES:
|
|
76
|
+
raise ArtworkError(f"The image is too large (max {MAX_ART_BYTES // (1024 * 1024)} MB)")
|
|
77
|
+
if data.startswith(b"\x89PNG\r\n\x1a\n") and len(data) >= 24:
|
|
78
|
+
width, height = struct.unpack(">II", data[16:24])
|
|
79
|
+
return Artwork(data, "image/png", width or None, height or None)
|
|
80
|
+
if data.startswith(b"\xff\xd8\xff"):
|
|
81
|
+
width, height = _jpeg_size(data)
|
|
82
|
+
return Artwork(data, "image/jpeg", width, height)
|
|
83
|
+
raise ArtworkError("Album art must be a JPEG or PNG image")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _jpeg_size(data: bytes) -> tuple[int | None, int | None]:
|
|
87
|
+
"""Find a JPEG's dimensions in its start-of-frame (SOFn) marker."""
|
|
88
|
+
i = 2
|
|
89
|
+
while i + 9 < len(data):
|
|
90
|
+
if data[i] != 0xFF:
|
|
91
|
+
i += 1
|
|
92
|
+
continue
|
|
93
|
+
marker = data[i + 1]
|
|
94
|
+
if marker == 0xFF: # padding
|
|
95
|
+
i += 1
|
|
96
|
+
continue
|
|
97
|
+
if marker in (0x01, 0xD8) or 0xD0 <= marker <= 0xD7: # markers without a length
|
|
98
|
+
i += 2
|
|
99
|
+
continue
|
|
100
|
+
(length,) = struct.unpack(">H", data[i + 2 : i + 4])
|
|
101
|
+
if 0xC0 <= marker <= 0xCF and marker not in (0xC4, 0xC8, 0xCC):
|
|
102
|
+
height, width = struct.unpack(">HH", data[i + 5 : i + 9])
|
|
103
|
+
return width or None, height or None
|
|
104
|
+
i += 2 + length
|
|
105
|
+
return None, None
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
# --- Reading ---------------------------------------------------------------------
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def read_picture(audio, format_name: str) -> Artwork | None:
|
|
112
|
+
"""The front cover if there is one, otherwise the first picture."""
|
|
113
|
+
candidates: list[tuple[int, bytes, str]] = [] # (type, data, mime)
|
|
114
|
+
if format_name == "flac":
|
|
115
|
+
candidates = [(p.type, p.data, p.mime) for p in audio.pictures]
|
|
116
|
+
elif format_name in ID3_FORMATS:
|
|
117
|
+
frames = audio.tags.getall("APIC") if audio.tags is not None else []
|
|
118
|
+
candidates = [(f.type, f.data, f.mime) for f in frames]
|
|
119
|
+
elif format_name in APE_FORMATS:
|
|
120
|
+
for i, key in enumerate(APE_COVER_KEYS):
|
|
121
|
+
item = (audio.tags or {}).get(key)
|
|
122
|
+
if item is not None and item.kind == APE_BINARY:
|
|
123
|
+
_, _, data = bytes(item.value).partition(b"\x00")
|
|
124
|
+
candidates.append((FRONT_COVER if i == 0 else 0, data, ""))
|
|
125
|
+
elif format_name in ASF_FORMATS:
|
|
126
|
+
for attr in (audio.tags or {}).get("WM/Picture", []):
|
|
127
|
+
pic = _asf_unpack(bytes(attr.value))
|
|
128
|
+
if pic:
|
|
129
|
+
candidates.append(pic)
|
|
130
|
+
elif format_name == "m4a":
|
|
131
|
+
covers = (audio.tags or {}).get("covr", [])
|
|
132
|
+
candidates = [
|
|
133
|
+
(FRONT_COVER, bytes(c), "image/png" if c.imageformat == MP4Cover.FORMAT_PNG else "image/jpeg")
|
|
134
|
+
for c in covers
|
|
135
|
+
]
|
|
136
|
+
else: # ogg / opus
|
|
137
|
+
for encoded in (audio.tags or {}).get("metadata_block_picture", []):
|
|
138
|
+
try:
|
|
139
|
+
pic = Picture(base64.b64decode(encoded))
|
|
140
|
+
except Exception: # noqa: BLE001 # nosec B112 - a damaged picture block is skipped, not fatal
|
|
141
|
+
continue
|
|
142
|
+
candidates.append((pic.type, pic.data, pic.mime))
|
|
143
|
+
|
|
144
|
+
if not candidates:
|
|
145
|
+
return None
|
|
146
|
+
candidates.sort(key=lambda c: c[0] != FRONT_COVER) # front cover first, else original order
|
|
147
|
+
_, data, mime = candidates[0]
|
|
148
|
+
try:
|
|
149
|
+
return parse_image(data) # also fills in width/height
|
|
150
|
+
except ArtworkError:
|
|
151
|
+
return Artwork(data, mime or "application/octet-stream") # unusual image type
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
# --- Writing -----------------------------------------------------------------------
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def write_picture(audio, format_name: str, art: Artwork | None) -> None:
|
|
158
|
+
"""Replace all embedded pictures with ``art`` (or remove them if None).
|
|
159
|
+
|
|
160
|
+
The caller is responsible for ``audio.save()``.
|
|
161
|
+
"""
|
|
162
|
+
if format_name == "flac":
|
|
163
|
+
audio.clear_pictures()
|
|
164
|
+
if art:
|
|
165
|
+
audio.add_picture(_flac_picture(art))
|
|
166
|
+
elif format_name in ID3_FORMATS:
|
|
167
|
+
if audio.tags is None:
|
|
168
|
+
audio.add_tags()
|
|
169
|
+
audio.tags.delall("APIC")
|
|
170
|
+
if art:
|
|
171
|
+
audio.tags.add(APIC(encoding=3, mime=art.mime, type=FRONT_COVER, desc="", data=art.data))
|
|
172
|
+
elif format_name == "m4a":
|
|
173
|
+
if audio.tags is None:
|
|
174
|
+
audio.add_tags()
|
|
175
|
+
if art:
|
|
176
|
+
fmt = MP4Cover.FORMAT_PNG if art.mime == "image/png" else MP4Cover.FORMAT_JPEG
|
|
177
|
+
audio.tags["covr"] = [MP4Cover(art.data, imageformat=fmt)]
|
|
178
|
+
else:
|
|
179
|
+
audio.tags.pop("covr", None)
|
|
180
|
+
elif format_name in APE_FORMATS:
|
|
181
|
+
if audio.tags is None:
|
|
182
|
+
audio.add_tags()
|
|
183
|
+
for key in APE_COVER_KEYS:
|
|
184
|
+
if key in audio.tags:
|
|
185
|
+
del audio.tags[key]
|
|
186
|
+
if art:
|
|
187
|
+
name = b"cover.png" if art.mime == "image/png" else b"cover.jpg"
|
|
188
|
+
audio.tags["Cover Art (Front)"] = APEValue(name + b"\x00" + art.data, APE_BINARY)
|
|
189
|
+
elif format_name in ASF_FORMATS:
|
|
190
|
+
if "WM/Picture" in audio.tags:
|
|
191
|
+
del audio.tags["WM/Picture"]
|
|
192
|
+
if art:
|
|
193
|
+
audio.tags["WM/Picture"] = [ASFByteArrayAttribute(_asf_pack(art))]
|
|
194
|
+
else: # ogg family
|
|
195
|
+
for key in ("metadata_block_picture", "coverart", "coverartmime"):
|
|
196
|
+
if key in audio.tags:
|
|
197
|
+
del audio.tags[key]
|
|
198
|
+
if art:
|
|
199
|
+
block = base64.b64encode(_flac_picture(art).write()).decode("ascii")
|
|
200
|
+
audio.tags["metadata_block_picture"] = [block]
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _flac_picture(art: Artwork) -> Picture:
|
|
204
|
+
pic = Picture()
|
|
205
|
+
pic.type = FRONT_COVER
|
|
206
|
+
pic.mime = art.mime
|
|
207
|
+
pic.desc = ""
|
|
208
|
+
pic.width = art.width or 0
|
|
209
|
+
pic.height = art.height or 0
|
|
210
|
+
pic.depth = 24
|
|
211
|
+
pic.data = art.data
|
|
212
|
+
return pic
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _asf_pack(art: Artwork) -> bytes:
|
|
216
|
+
"""WM/Picture: type (1 byte), size (4, little-endian), MIME and description
|
|
217
|
+
(UTF-16-LE, NUL-terminated), then the image."""
|
|
218
|
+
mime = art.mime.encode("utf-16-le") + b"\x00\x00"
|
|
219
|
+
desc = b"\x00\x00"
|
|
220
|
+
return struct.pack("<bI", FRONT_COVER, len(art.data)) + mime + desc + art.data
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _asf_unpack(value: bytes) -> tuple[int, bytes, str] | None:
|
|
224
|
+
try:
|
|
225
|
+
pic_type, size = struct.unpack_from("<bI", value)
|
|
226
|
+
pos = 5
|
|
227
|
+
strings = []
|
|
228
|
+
for _ in range(2): # MIME, description
|
|
229
|
+
end = pos
|
|
230
|
+
while value[end:end + 2] != b"\x00\x00":
|
|
231
|
+
end += 2
|
|
232
|
+
if end >= len(value): # damaged: no terminator
|
|
233
|
+
return None
|
|
234
|
+
strings.append(value[pos:end].decode("utf-16-le"))
|
|
235
|
+
pos = end + 2
|
|
236
|
+
return pic_type, value[pos:pos + size], strings[0]
|
|
237
|
+
except (struct.error, IndexError, UnicodeDecodeError):
|
|
238
|
+
return None
|