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
codetta/core/auth.py ADDED
@@ -0,0 +1,362 @@
1
+ """Sign-in for Codetta: one account, password hashing, sessions, and rate limiting.
2
+
3
+ Design:
4
+ * One account (username + password). It's created on the first visit
5
+ ("setup"), or supplied through environment variables in Docker.
6
+ * Passwords are hashed with scrypt (Python's standard library) and a random
7
+ salt. The plain password is never stored.
8
+ * Signing in creates a random session token, sent to the browser as an
9
+ HttpOnly cookie. Only a SHA-256 hash of each token is kept on disk, so the
10
+ sessions file can't be used to sign in even if someone reads it.
11
+ * Repeated wrong passwords from the same address get locked out for a
12
+ growing amount of time.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import base64
18
+ import hashlib
19
+ import hmac
20
+ import json
21
+ import os
22
+ import secrets
23
+ import tempfile
24
+ import threading
25
+ import time
26
+ from collections import OrderedDict
27
+ from dataclasses import dataclass
28
+ from pathlib import Path
29
+
30
+ SESSION_DAYS = 30
31
+ MIN_PASSWORD_LENGTH = 8
32
+
33
+ # scrypt cost parameters (~100 ms and 32 MB per hash on a typical home server).
34
+ # Older hashes with a lower N are upgraded automatically at the next sign-in.
35
+ _SCRYPT_N, _SCRYPT_R, _SCRYPT_P = 2**15, 8, 1
36
+
37
+
38
+ class AuthError(Exception):
39
+ """A sign-in problem the user should see (wrong password, invalid input...)."""
40
+
41
+
42
+ # --- Password hashing ----------------------------------------------------------------
43
+
44
+
45
+ # At most this many password hashes run at once (each needs ~32 MB of RAM), so a
46
+ # burst of parallel sign-in attempts can't exhaust memory on a small server.
47
+ MAX_CONCURRENT_HASHES = 2
48
+ _hash_slots = threading.BoundedSemaphore(MAX_CONCURRENT_HASHES)
49
+ HASH_WAIT_SECONDS = 10.0
50
+
51
+
52
+ class BusyError(AuthError):
53
+ """Too many sign-in attempts are being checked right now."""
54
+
55
+
56
+ def _with_hash_slot(fn, *args):
57
+ if not _hash_slots.acquire(timeout=HASH_WAIT_SECONDS):
58
+ raise BusyError("The server is busy checking other sign-ins. Try again in a moment.")
59
+ try:
60
+ return fn(*args)
61
+ finally:
62
+ _hash_slots.release()
63
+
64
+
65
+ def hash_password(password: str) -> str:
66
+ return _with_hash_slot(_hash_password, password)
67
+
68
+
69
+ def verify_password(password: str, stored: str) -> bool:
70
+ return _with_hash_slot(_verify_password, password, stored)
71
+
72
+
73
+ def _hash_password(password: str) -> str:
74
+ """Return a self-describing hash string: ``scrypt$n$r$p$salt$hash``."""
75
+ salt = os.urandom(16)
76
+ digest = hashlib.scrypt(password.encode(), salt=salt, n=_SCRYPT_N, r=_SCRYPT_R, p=_SCRYPT_P, dklen=32,
77
+ maxmem=128 * 1024 * 1024)
78
+ b64 = lambda b: base64.b64encode(b).decode("ascii") # noqa: E731
79
+ return f"scrypt${_SCRYPT_N}${_SCRYPT_R}${_SCRYPT_P}${b64(salt)}${b64(digest)}"
80
+
81
+
82
+ def needs_rehash(stored: str) -> bool:
83
+ """True if ``stored`` was made with weaker settings than today's."""
84
+ try:
85
+ scheme, n, r, p, *_ = stored.split("$")
86
+ return scheme != "scrypt" or int(n) < _SCRYPT_N or int(r) < _SCRYPT_R or int(p) < _SCRYPT_P
87
+ except ValueError:
88
+ return True
89
+
90
+
91
+ def _verify_password(password: str, stored: str) -> bool:
92
+ try:
93
+ scheme, n, r, p, salt_b64, digest_b64 = stored.split("$")
94
+ if scheme != "scrypt":
95
+ return False
96
+ salt, expected = base64.b64decode(salt_b64), base64.b64decode(digest_b64)
97
+ actual = hashlib.scrypt(
98
+ password.encode(), salt=salt, n=int(n), r=int(r), p=int(p), dklen=len(expected),
99
+ maxmem=128 * 1024 * 1024,
100
+ )
101
+ except (ValueError, TypeError):
102
+ return False
103
+ return hmac.compare_digest(actual, expected)
104
+
105
+
106
+ def validate_new_credentials(username: str, password: str) -> str:
107
+ """Check a new username/password; returns the cleaned-up username."""
108
+ username = username.strip()
109
+ if not username:
110
+ raise AuthError("Choose a username")
111
+ if len(username) > 64 or any(ch.isspace() for ch in username):
112
+ raise AuthError("Usernames can't contain spaces (max 64 characters)")
113
+ if len(password) < MIN_PASSWORD_LENGTH:
114
+ raise AuthError(f"Use a password of at least {MIN_PASSWORD_LENGTH} characters")
115
+ if len(password) > 1024:
116
+ raise AuthError("That password is too long")
117
+ return username
118
+
119
+
120
+ # --- Small JSON file helper ----------------------------------------------------------------
121
+
122
+
123
+ def _write_private_json(path: Path, data: object) -> None:
124
+ """Write JSON atomically, readable only by the owner (chmod 600)."""
125
+ path.parent.mkdir(parents=True, exist_ok=True)
126
+ fd, tmp = tempfile.mkstemp(prefix=".codetta-", suffix=".json", dir=path.parent)
127
+ try:
128
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
129
+ json.dump(data, f, indent=2)
130
+ os.chmod(tmp, 0o600)
131
+ os.replace(tmp, path)
132
+ except BaseException:
133
+ Path(tmp).unlink(missing_ok=True)
134
+ raise
135
+
136
+
137
+ def _read_json(path: Path) -> object | None:
138
+ try:
139
+ return json.loads(path.read_text(encoding="utf-8"))
140
+ except (OSError, json.JSONDecodeError):
141
+ return None
142
+
143
+
144
+ # --- The account ---------------------------------------------------------------------------
145
+
146
+
147
+ @dataclass
148
+ class Account:
149
+ username: str
150
+ password_hash: str
151
+
152
+
153
+ class AccountStore:
154
+ """The single Codetta account, from env vars or ``auth.json`` in the config folder."""
155
+
156
+ def __init__(self, file: Path, env_username: str | None = None, env_password: str | None = None) -> None:
157
+ self.file = file
158
+ self._lock = threading.Lock()
159
+ self.managed_by_env = bool(env_username and env_password)
160
+ self._env_account = (
161
+ Account(env_username.strip(), hash_password(env_password)) if self.managed_by_env else None
162
+ )
163
+
164
+ def get(self) -> Account | None:
165
+ if self._env_account:
166
+ return self._env_account
167
+ data = _read_json(self.file)
168
+ if isinstance(data, dict) and isinstance(data.get("username"), str) and isinstance(data.get("password_hash"), str):
169
+ return Account(data["username"], data["password_hash"])
170
+ return None
171
+
172
+ @property
173
+ def setup_required(self) -> bool:
174
+ return self.get() is None
175
+
176
+ def create(self, username: str, password: str) -> Account:
177
+ """First-run setup. Refused once an account exists."""
178
+ username = validate_new_credentials(username, password)
179
+ with self._lock:
180
+ if self.get() is not None:
181
+ raise AuthError("Codetta is already set up. Sign in instead.")
182
+ account = Account(username, hash_password(password))
183
+ self._save(account)
184
+ return account
185
+
186
+ def set_password(self, username: str, new_password: str) -> Account:
187
+ if self.managed_by_env:
188
+ raise AuthError("The password is set by environment variables (CODETTA_USERNAME / CODETTA_PASSWORD).")
189
+ username = validate_new_credentials(username, new_password)
190
+ with self._lock:
191
+ account = Account(username, hash_password(new_password))
192
+ self._save(account)
193
+ return account
194
+
195
+ def check(self, username: str, password: str) -> Account | None:
196
+ account = self.get()
197
+ if account is None:
198
+ hash_password(password) # spend the same time either way
199
+ return None
200
+ name_ok = hmac.compare_digest(username.strip().lower().encode(), account.username.lower().encode())
201
+ pass_ok = verify_password(password, account.password_hash)
202
+ return account if name_ok and pass_ok else None
203
+
204
+ def _save(self, account: Account) -> None:
205
+ _write_private_json(self.file, {
206
+ "username": account.username,
207
+ "password_hash": account.password_hash,
208
+ "updated": int(time.time()),
209
+ })
210
+
211
+
212
+ # --- Sessions ---------------------------------------------------------------------------------
213
+
214
+
215
+ def _token_hash(token: str) -> str:
216
+ return hashlib.sha256(token.encode()).hexdigest()
217
+
218
+
219
+ class SessionStore:
220
+ """Signed-in browsers. Persisted (as token hashes) so restarts don't sign you out.
221
+
222
+ The file is re-read whenever it changes on disk, so ``python -m codetta.cli
223
+ sign-out-all`` (a separate process) takes effect on a running server.
224
+ """
225
+
226
+ def __init__(self, file: Path | None, days: int = SESSION_DAYS) -> None:
227
+ self.file = file
228
+ self.lifetime = days * 86400
229
+ self._lock = threading.Lock()
230
+ self._sessions: dict[str, dict] = {}
231
+ self._mtime: int | None = None
232
+ self._reload_if_changed()
233
+
234
+ def _file_mtime(self) -> int | None:
235
+ try:
236
+ return self.file.stat().st_mtime_ns if self.file else None
237
+ except OSError:
238
+ return None
239
+
240
+ def _reload_if_changed(self) -> None:
241
+ mtime = self._file_mtime()
242
+ if mtime == self._mtime:
243
+ return
244
+ self._mtime = mtime
245
+ data = _read_json(self.file) if mtime is not None else None
246
+ now = time.time()
247
+ self._sessions = {
248
+ k: v for k, v in (data.items() if isinstance(data, dict) else [])
249
+ if isinstance(v, dict) and isinstance(v.get("expires"), (int, float)) and v["expires"] > now
250
+ }
251
+
252
+ def create(self, username: str) -> str:
253
+ token = secrets.token_urlsafe(32)
254
+ now = time.time()
255
+ with self._lock:
256
+ self._reload_if_changed()
257
+ self._sessions[_token_hash(token)] = {
258
+ "username": username, "created": int(now), "expires": int(now + self.lifetime),
259
+ }
260
+ self._persist()
261
+ return token
262
+
263
+ def lookup(self, token: str | None) -> str | None:
264
+ """The username for a valid session token, or None. Extends active sessions."""
265
+ if not token:
266
+ return None
267
+ key = _token_hash(token)
268
+ now = time.time()
269
+ with self._lock:
270
+ self._reload_if_changed()
271
+ session = self._sessions.get(key)
272
+ if session is None:
273
+ return None
274
+ if session["expires"] <= now:
275
+ del self._sessions[key]
276
+ self._persist()
277
+ return None
278
+ # Sliding expiry, written at most once an hour to avoid constant disk writes.
279
+ if session["expires"] - now < self.lifetime - 3600:
280
+ session["expires"] = int(now + self.lifetime)
281
+ self._persist()
282
+ return session["username"]
283
+
284
+ def revoke(self, token: str | None) -> None:
285
+ if not token:
286
+ return
287
+ with self._lock:
288
+ self._reload_if_changed()
289
+ if self._sessions.pop(_token_hash(token), None) is not None:
290
+ self._persist()
291
+
292
+ def revoke_all(self, keep: str | None = None) -> None:
293
+ """Sign out every browser (except, optionally, the one with token ``keep``)."""
294
+ with self._lock:
295
+ self._reload_if_changed()
296
+ kept = _token_hash(keep) if keep else None
297
+ self._sessions = {k: v for k, v in self._sessions.items() if k == kept}
298
+ self._persist()
299
+
300
+ def _persist(self) -> None:
301
+ if self.file:
302
+ try:
303
+ _write_private_json(self.file, self._sessions)
304
+ self._mtime = self._file_mtime()
305
+ except OSError:
306
+ pass # sessions still work in memory
307
+
308
+
309
+ # --- Rate limiting -------------------------------------------------------------------------------
310
+
311
+
312
+ class LoginRateLimiter:
313
+ """Slow down password guessing: after ``free`` failures in ``window`` seconds
314
+ from one address, lock it out for 30 s, doubling per extra failure (max 15 min).
315
+
316
+ Memory is bounded: at most ``MAX_TRACKED`` addresses are remembered; the
317
+ least recently failing one is forgotten first (O(1)).
318
+ """
319
+
320
+ MAX_TRACKED = 10_000
321
+
322
+ def __init__(self, free: int = 5, window: float = 15 * 60, base_lock: float = 30, max_lock: float = 15 * 60) -> None:
323
+ self.free, self.window, self.base_lock, self.max_lock = free, window, base_lock, max_lock
324
+ self._failures: OrderedDict[str, list[float]] = OrderedDict()
325
+ self._lock = threading.Lock()
326
+
327
+ def _recent(self, key: str, now: float) -> list[float]:
328
+ """Failures still inside the window (expired ones are dropped). Never adds keys."""
329
+ fails = self._failures.get(key)
330
+ if fails is None:
331
+ return []
332
+ fails = [t for t in fails if now - t < self.window]
333
+ if fails:
334
+ self._failures[key] = fails
335
+ else:
336
+ del self._failures[key]
337
+ return fails
338
+
339
+ def retry_after(self, key: str) -> int:
340
+ """Seconds until ``key`` may try again (0 = allowed now)."""
341
+ now = time.time()
342
+ with self._lock:
343
+ fails = self._recent(key, now)
344
+ if len(fails) < self.free:
345
+ return 0
346
+ lock = min(self.base_lock * 2 ** (len(fails) - self.free), self.max_lock)
347
+ remaining = fails[-1] + lock - now
348
+ return int(remaining) + 1 if remaining > 0 else 0
349
+
350
+ def failed(self, key: str) -> None:
351
+ now = time.time()
352
+ with self._lock:
353
+ fails = self._recent(key, now)
354
+ fails.append(now)
355
+ self._failures[key] = fails
356
+ self._failures.move_to_end(key) # most recently failing goes last
357
+ while len(self._failures) > self.MAX_TRACKED:
358
+ self._failures.popitem(last=False) # forget the least recently failing
359
+
360
+ def succeeded(self, key: str) -> None:
361
+ with self._lock:
362
+ self._failures.pop(key, None)
codetta/core/avatar.py ADDED
@@ -0,0 +1,92 @@
1
+ """Profile pictures.
2
+
3
+ The browser does the image work (crops to a square, scales to 256x256 and
4
+ converts to WebP or JPEG, including HEIC photos where the browser can read
5
+ them), so the server only has to check that what arrives really is a small
6
+ JPEG, PNG or WebP image and store it, one file per user, in the config folder.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import os
13
+ import tempfile
14
+ from pathlib import Path
15
+
16
+ MAX_AVATAR_BYTES = 2 * 1024 * 1024 # the browser sends ~10-30 KB; this is a generous cap
17
+
18
+ _TYPES = {"image/jpeg": "jpg", "image/png": "png", "image/webp": "webp"}
19
+
20
+
21
+ class AvatarError(ValueError):
22
+ """The upload isn't a usable profile picture."""
23
+
24
+
25
+ def detect_image_type(data: bytes) -> str | None:
26
+ """MIME type from the file's first bytes (never trust the file name)."""
27
+ if data.startswith(b"\xff\xd8\xff"):
28
+ return "image/jpeg"
29
+ if data.startswith(b"\x89PNG\r\n\x1a\n"):
30
+ return "image/png"
31
+ if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP":
32
+ return "image/webp"
33
+ return None
34
+
35
+
36
+ class AvatarStore:
37
+ def __init__(self, directory: Path) -> None:
38
+ self.directory = directory
39
+
40
+ def _base(self, username: str) -> str:
41
+ # File-name-safe and stable for any username (any script, any case).
42
+ return hashlib.sha256(username.strip().lower().encode("utf-8")).hexdigest()[:24]
43
+
44
+ def _find(self, username: str) -> Path | None:
45
+ base = self._base(username)
46
+ for ext in _TYPES.values():
47
+ path = self.directory / f"{base}.{ext}"
48
+ if path.is_file():
49
+ return path
50
+ return None
51
+
52
+ def get(self, username: str) -> tuple[bytes, str] | None:
53
+ """(image bytes, MIME type), or None if the user has no picture."""
54
+ path = self._find(username)
55
+ if path is None:
56
+ return None
57
+ data = path.read_bytes()
58
+ return data, detect_image_type(data) or "application/octet-stream"
59
+
60
+ def version(self, username: str) -> int | None:
61
+ """Changes whenever the picture does (lets browsers cache it safely)."""
62
+ path = self._find(username)
63
+ return path.stat().st_mtime_ns if path else None
64
+
65
+ def save(self, username: str, data: bytes) -> None:
66
+ if not data:
67
+ raise AvatarError("The image is empty")
68
+ if len(data) > MAX_AVATAR_BYTES:
69
+ raise AvatarError("That image is too large")
70
+ mime = detect_image_type(data)
71
+ if mime is None:
72
+ raise AvatarError("Profile pictures must be JPEG, PNG or WebP")
73
+ self.directory.mkdir(parents=True, exist_ok=True)
74
+ old = self._find(username)
75
+ target = self.directory / f"{self._base(username)}.{_TYPES[mime]}"
76
+ fd, tmp = tempfile.mkstemp(prefix=".codetta-", dir=self.directory)
77
+ try:
78
+ with os.fdopen(fd, "wb") as f:
79
+ f.write(data)
80
+ os.replace(tmp, target)
81
+ except BaseException:
82
+ Path(tmp).unlink(missing_ok=True)
83
+ raise
84
+ if old is not None and old != target:
85
+ old.unlink(missing_ok=True)
86
+
87
+ def delete(self, username: str) -> bool:
88
+ path = self._find(username)
89
+ if path is None:
90
+ return False
91
+ path.unlink()
92
+ return True
@@ -0,0 +1,51 @@
1
+ """What's new: CHANGELOG.md, split into versions for the in-app popup.
2
+
3
+ The file ships next to the app (/opt/codetta/CHANGELOG.md in Docker; the
4
+ project folder in a source checkout). It's the same text as on GitHub, so it
5
+ holds nothing private, which is why the sign-in screen may show it too.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from functools import lru_cache
12
+ from pathlib import Path
13
+
14
+ CANDIDATES = (
15
+ Path(__file__).resolve().parents[3] / "CHANGELOG.md", # source checkout
16
+ Path("/opt/codetta/CHANGELOG.md"), # Docker image
17
+ Path(__file__).resolve().parents[1] / "CHANGELOG.md", # installed package (pipx, Homebrew, snap...)
18
+ )
19
+ _HEADING = re.compile(r"^##\s+(.+?)\s*$")
20
+ _VERSION = re.compile(r"^(?:Unreleased\s*\()?v?(\d+(?:\.\d+)*)\)?(?:\s*\((\d{4}-\d{2}-\d{2})\))?")
21
+
22
+
23
+ @lru_cache(maxsize=1)
24
+ def load(path: Path | None = None) -> list[dict]:
25
+ """[{version, date, unreleased, items: [markdown text per bullet]}], newest first."""
26
+ for candidate in ([path] if path else CANDIDATES):
27
+ try:
28
+ text = candidate.read_text("utf-8")
29
+ break
30
+ except OSError:
31
+ continue
32
+ else:
33
+ return []
34
+ versions, current = [], None
35
+ for line in text.splitlines():
36
+ m = _HEADING.match(line)
37
+ if m:
38
+ title = m.group(1)
39
+ v = _VERSION.match(title)
40
+ current = {"title": title, "version": v.group(1) if v else title,
41
+ "date": (v.group(2) if v else None) or "", "unreleased": title.lower().startswith("unreleased"),
42
+ "items": [], "text": []}
43
+ versions.append(current)
44
+ elif current is not None:
45
+ if line.startswith("- "):
46
+ current["items"].append(line[2:].strip())
47
+ elif line.startswith(" ") and current["items"]:
48
+ current["items"][-1] += " " + line.strip()
49
+ elif line.strip():
50
+ current["text"].append(line.strip())
51
+ return versions
@@ -0,0 +1,159 @@
1
+ """Connections: the only parts of Codetta that talk to the internet.
2
+
3
+ Codetta on its own is fully offline. Each online feature is a *connection*
4
+ the user opts in to: on the first-run card, in Account → Connections, or with
5
+ an environment variable. Everything is off until someone turns it on.
6
+
7
+ Who decides, strongest first:
8
+ 1. ``CODETTA_OFFLINE=on`` blocks every connection (a hard guarantee).
9
+ 2. A connection's own env var (``CODETTA_MUSICBRAINZ=on|off`` ...) sets it
10
+ and locks the switch in the UI.
11
+ 3. Otherwise the user's choice, saved in ``connections.json`` in the config
12
+ folder. No file yet means "not chosen": the UI asks once.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import os
19
+ import tempfile
20
+ import threading
21
+ from dataclasses import dataclass
22
+ from pathlib import Path
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class Connection:
27
+ id: str
28
+ name: str
29
+ summary: str # what it gives you
30
+ sends: str # what leaves the server, in plain words
31
+ hosts: tuple[str, ...]
32
+ env: str # CODETTA_<env> sets it from the environment
33
+
34
+
35
+ CONNECTIONS: tuple[Connection, ...] = (
36
+ Connection(
37
+ "musicbrainz", "MusicBrainz",
38
+ "Match albums to the open music encyclopedia: official titles, credits, dates, labels, "
39
+ "catalog numbers, MusicBrainz IDs and cover art.",
40
+ "The album and artist names you search for, and the IDs of releases you pick.",
41
+ ("musicbrainz.org", "coverartarchive.org"), "MUSICBRAINZ",
42
+ ),
43
+ Connection(
44
+ "acoustid", "AcoustID: identify by sound",
45
+ "Recognise tracks by how they sound, even untagged ones, to find the right MusicBrainz "
46
+ "release. Works together with MusicBrainz.",
47
+ "A fingerprint of each track's sound (a short code, never the audio itself) and its length, "
48
+ "when you press Listen.",
49
+ ("api.acoustid.org",), "ACOUSTID",
50
+ ),
51
+ Connection(
52
+ "lyrics", "LRCLIB lyrics",
53
+ "Find plain and synced lyrics for a track.",
54
+ "The track's artist, title, album and length, when you press Find lyrics.",
55
+ ("lrclib.net",), "LYRICS_LOOKUP",
56
+ ),
57
+ Connection(
58
+ "slskd", "Soulseek (slskd)",
59
+ "Find and download music on the Soulseek network through your own slskd: type !slskd in the "
60
+ "search bar, or use Find in slskd on an album. Downloads land in the inbox for a review.",
61
+ "Your searches go to your slskd, which asks other Soulseek users. Downloads come from them, "
62
+ "and slskd shares the folders you chose with them in return.",
63
+ ("your slskd server", "the Soulseek network"), "SLSKD",
64
+ ),
65
+ Connection(
66
+ "updates", "Update check",
67
+ "Tell you when a new version of Codetta is out.",
68
+ "Nothing about you or your music: it asks GitHub for the latest release, twice a day.",
69
+ ("api.github.com",), "UPDATE_CHECK",
70
+ ),
71
+ )
72
+ BY_ID = {c.id: c for c in CONNECTIONS}
73
+
74
+ ON = ("on", "true", "1", "yes")
75
+ OFF = ("off", "false", "0", "no")
76
+
77
+
78
+ def parse_switch(value: str | None) -> bool | None:
79
+ """ "on"/"off" (and friends) -> True/False; unset or unrecognised -> None."""
80
+ if value is None:
81
+ return None
82
+ value = value.strip().lower()
83
+ return True if value in ON else False if value in OFF else None
84
+
85
+
86
+ class ConnectionStore:
87
+ def __init__(self, file: Path, offline: bool = False, forced: dict[str, bool] | None = None) -> None:
88
+ self.file = file
89
+ self.offline = offline # CODETTA_OFFLINE
90
+ self.forced = {k: v for k, v in (forced or {}).items() if k in BY_ID and v is not None}
91
+ self._lock = threading.Lock()
92
+ self._chosen, self._enabled = self._load()
93
+
94
+ def _load(self) -> tuple[bool, dict[str, bool]]:
95
+ try:
96
+ data = json.loads(self.file.read_text("utf-8"))
97
+ except (OSError, ValueError):
98
+ return False, {}
99
+ if not isinstance(data, dict):
100
+ return False, {}
101
+ raw = data.get("enabled")
102
+ enabled = {k: v for k, v in raw.items() if k in BY_ID and isinstance(v, bool)} if isinstance(raw, dict) else {}
103
+ return bool(data.get("chosen")), enabled
104
+
105
+ def locked_by(self, cid: str) -> str | None:
106
+ """The env var that decides this connection, if any."""
107
+ if self.offline:
108
+ return "CODETTA_OFFLINE"
109
+ if cid in self.forced:
110
+ return f"CODETTA_{BY_ID[cid].env}"
111
+ return None
112
+
113
+ def enabled(self, cid: str) -> bool:
114
+ if self.offline:
115
+ return False
116
+ if cid in self.forced:
117
+ return self.forced[cid]
118
+ with self._lock:
119
+ return self._enabled.get(cid, False)
120
+
121
+ @property
122
+ def needs_choice(self) -> bool:
123
+ """Show the first-run card? Not if the admin already decided everything by env."""
124
+ if self.offline or all(c.id in self.forced for c in CONNECTIONS):
125
+ return False
126
+ with self._lock:
127
+ return not self._chosen
128
+
129
+ def status(self) -> dict:
130
+ return {
131
+ "offline": not any(self.enabled(c.id) for c in CONNECTIONS),
132
+ "offline_locked": self.offline,
133
+ "needs_choice": self.needs_choice,
134
+ "connections": [
135
+ {
136
+ "id": c.id, "name": c.name, "summary": c.summary, "sends": c.sends,
137
+ "hosts": list(c.hosts), "enabled": self.enabled(c.id), "locked_by": self.locked_by(c.id),
138
+ }
139
+ for c in CONNECTIONS
140
+ ],
141
+ }
142
+
143
+ def save(self, enabled: dict[str, bool]) -> None:
144
+ """Store the user's choices (switches set by env are left as the env says)."""
145
+ with self._lock:
146
+ for cid, on in enabled.items():
147
+ if cid in BY_ID and self.locked_by(cid) is None:
148
+ self._enabled[cid] = bool(on)
149
+ self._chosen = True
150
+ data = {"chosen": True, "enabled": dict(sorted(self._enabled.items()))}
151
+ self.file.parent.mkdir(parents=True, exist_ok=True)
152
+ fd, tmp = tempfile.mkstemp(prefix=".connections-", dir=self.file.parent)
153
+ try:
154
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
155
+ json.dump(data, f, indent=2)
156
+ os.replace(tmp, self.file)
157
+ except BaseException:
158
+ Path(tmp).unlink(missing_ok=True)
159
+ raise