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,177 @@
1
+ """The music library on disk: safe path handling and folder listing.
2
+
3
+ Everything the web UI asks for is a path *relative to the music folder*
4
+ (e.g. ``"Artist/Album/01 - Song.flac"``). ``Library.resolve`` turns that into
5
+ a real path and refuses anything that would escape the music folder, such as
6
+ ``"../../etc/passwd"`` or an absolute path.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import re
13
+ import unicodedata
14
+ from dataclasses import dataclass, field
15
+ from pathlib import Path, PurePosixPath
16
+
17
+ from codetta.core.engine import SUPPORTED_EXTENSIONS
18
+
19
+
20
+ class LibraryPathError(ValueError):
21
+ """A requested path is invalid or outside the music folder."""
22
+
23
+
24
+ @dataclass
25
+ class FolderListing:
26
+ path: str # relative to the library root, "" for the root itself
27
+ folders: list[str] = field(default_factory=list) # relative paths
28
+ files: list[str] = field(default_factory=list) # relative paths of audio files
29
+ # Entries whose names aren't valid UTF-8 (e.g. from an old Windows zip).
30
+ # They can't be shown or sent to the browser, so they're counted instead.
31
+ skipped: int = 0
32
+
33
+
34
+ INBOX = "@inbox" # paths starting with this live in the inbox folder, outside the library
35
+ REPLACED = "@replaced" # albums an upgrade replaced (kept in the config folder so it can be undone)
36
+
37
+
38
+ class Library:
39
+ def __init__(self, root: str | Path, inbox: str | Path | None = None, replaced: str | Path | None = None) -> None:
40
+ # Normalise without resolving symlinks: a library that links to music
41
+ # on other disks is normal, and the engine follows links when writing.
42
+ self.root = Path(os.path.abspath(root))
43
+ # Optional second folder (e.g. slskd's downloads), addressed as "@inbox/...".
44
+ self.inbox = Path(os.path.abspath(inbox)) if inbox else None
45
+ self.replaced = Path(os.path.abspath(replaced)) if replaced else None
46
+
47
+ def inbox_available(self) -> bool:
48
+ return self.inbox is not None and self.inbox.is_dir()
49
+
50
+ def exists(self) -> bool:
51
+ return self.root.is_dir()
52
+
53
+ def resolve(self, relative: str) -> Path:
54
+ """Turn a library-relative path into a real path, safely."""
55
+ if "\x00" in relative or "\\" in relative:
56
+ raise LibraryPathError("Invalid characters in path")
57
+ rel = PurePosixPath(relative.strip("/")) if relative.strip("/") else PurePosixPath()
58
+ if rel.is_absolute() or any(part in ("..", ".") for part in rel.parts):
59
+ raise LibraryPathError(f"Path must stay inside the music folder: {relative!r}")
60
+ if rel.parts and rel.parts[0] == INBOX:
61
+ if self.inbox is None:
62
+ raise LibraryPathError("There's no inbox folder set up (CODETTA_INBOX_DIR)")
63
+ return self.inbox.joinpath(*rel.parts[1:])
64
+ if rel.parts and rel.parts[0] == REPLACED and self.replaced is not None:
65
+ return self.replaced.joinpath(*rel.parts[1:])
66
+ if rel.parts and rel.parts[0].startswith("@"):
67
+ raise LibraryPathError(f"Unknown folder: {rel.parts[0]}")
68
+ return self.root.joinpath(*rel.parts)
69
+
70
+ def relative(self, path: Path) -> str:
71
+ """The library-relative form of ``path`` (always with forward slashes)."""
72
+ path = Path(os.path.abspath(path))
73
+ if self.inbox is not None and path.is_relative_to(self.inbox) and not path.is_relative_to(self.root):
74
+ rel = path.relative_to(self.inbox).as_posix()
75
+ return INBOX if rel == "." else f"{INBOX}/{rel}"
76
+ if self.replaced is not None and path.is_relative_to(self.replaced) and not path.is_relative_to(self.root):
77
+ rel = path.relative_to(self.replaced).as_posix()
78
+ return REPLACED if rel == "." else f"{REPLACED}/{rel}"
79
+ rel = path.relative_to(self.root).as_posix()
80
+ return "" if rel == "." else rel
81
+
82
+ def list_folder(self, relative: str = "") -> FolderListing:
83
+ """Subfolders and audio files directly inside one folder.
84
+
85
+ Hidden entries (names starting with ".") are skipped, which includes
86
+ Codetta's own ``.codetta-*`` temp files. Both lists are in natural order
87
+ ("Disc 2" before "Disc 10").
88
+ """
89
+ folder = self.resolve(relative)
90
+ if not folder.is_dir():
91
+ raise FileNotFoundError(f"No such folder: {relative or '/'}")
92
+ folders, files, skipped = [], [], 0
93
+ with os.scandir(folder) as entries:
94
+ for entry in entries:
95
+ if entry.name.startswith("."):
96
+ continue
97
+ if not _is_valid_text(entry.name):
98
+ skipped += 1
99
+ continue
100
+ try:
101
+ if entry.is_dir():
102
+ folders.append(entry.name)
103
+ elif entry.is_file() and Path(entry.name).suffix.lower() in SUPPORTED_EXTENSIONS:
104
+ files.append(entry.name)
105
+ except OSError:
106
+ continue # e.g. a broken symlink
107
+ prefix = self.relative(folder)
108
+ join = (lambda name: f"{prefix}/{name}") if prefix else (lambda name: name)
109
+ return FolderListing(
110
+ path=prefix,
111
+ folders=[join(n) for n in sorted(folders, key=natural_key)],
112
+ files=[join(n) for n in sorted(files, key=natural_key)],
113
+ skipped=skipped,
114
+ )
115
+
116
+
117
+ class TooManyFilesError(LibraryPathError):
118
+ """More audio files than one request may handle."""
119
+
120
+
121
+ def audio_files(library: Library, relative: str, recursive: bool, limit: int) -> list[str]:
122
+ """Audio files in a folder (and its subfolders if ``recursive``), in natural
123
+ order, hidden entries skipped. Raises TooManyFilesError past ``limit``."""
124
+ out: list[str] = []
125
+ pending = [library.list_folder(relative)]
126
+ while pending:
127
+ listing = pending.pop(0)
128
+ out.extend(listing.files)
129
+ if len(out) > limit:
130
+ raise TooManyFilesError(f"That's more than {limit} files at once. Choose a smaller folder.")
131
+ if recursive:
132
+ pending.extend(library.list_folder(f) for f in listing.folders)
133
+ return out
134
+
135
+
136
+ def count_contents(folder: Path) -> tuple[int, int] | None:
137
+ """(subfolders, audio files) directly inside ``folder``, without reading
138
+ any tags. None if the folder can't be read."""
139
+ folders = files = 0
140
+ try:
141
+ with os.scandir(folder) as entries:
142
+ for entry in entries:
143
+ if entry.name.startswith("."):
144
+ continue
145
+ try:
146
+ if entry.is_dir():
147
+ folders += 1
148
+ elif entry.is_file() and Path(entry.name).suffix.lower() in SUPPORTED_EXTENSIONS:
149
+ files += 1
150
+ except OSError:
151
+ continue
152
+ except OSError:
153
+ return None
154
+ return folders, files
155
+
156
+
157
+ def _is_valid_text(name: str) -> bool:
158
+ """False for file names that aren't valid UTF-8 (Python keeps those as
159
+ "surrogate" characters, which can't be sent as JSON)."""
160
+ try:
161
+ name.encode("utf-8")
162
+ except UnicodeEncodeError:
163
+ return False
164
+ return True
165
+
166
+
167
+ def _sort_text(text: str) -> str:
168
+ """Case- and accent-insensitive form for sorting: "Éclair" sorts with "eclair"."""
169
+ decomposed = unicodedata.normalize("NFKD", text)
170
+ return "".join(ch for ch in decomposed if not unicodedata.combining(ch)).casefold()
171
+
172
+
173
+ def natural_key(text: str) -> list:
174
+ """Sort key that orders numbers numerically ("2 song" < "10 song") and
175
+ ignores case and accents. Works for any script."""
176
+ # isdecimal (not isdigit): "²" counts as a digit but int() can't read it.
177
+ return [(0, int(p), "") if p.isdecimal() else (1, 0, _sort_text(p)) for p in re.split(r"(\d+)", text)]