noneto-cli 1.1.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.
- noneto/__init__.py +1 -0
- noneto/__main__.py +3 -0
- noneto/app.py +113 -0
- noneto/assets/noneto.ico +0 -0
- noneto/audio/__init__.py +1 -0
- noneto/audio/controller.py +427 -0
- noneto/audio/inspector.py +21 -0
- noneto/audio/ipc_unix.py +29 -0
- noneto/audio/ipc_windows.py +94 -0
- noneto/audio/lifetime.py +68 -0
- noneto/audio/media_controls.py +107 -0
- noneto/audio/mpv_install.py +71 -0
- noneto/audio/player.py +222 -0
- noneto/audio/pulse_tap.py +120 -0
- noneto/audio/spectrum.py +44 -0
- noneto/audio/streams.py +101 -0
- noneto/audio/tap.py +208 -0
- noneto/audio/windows_identity.py +79 -0
- noneto/audio/windows_media.py +157 -0
- noneto/auth/__init__.py +1 -0
- noneto/auth/dpapi.py +28 -0
- noneto/auth/service.py +53 -0
- noneto/auth/storage.py +120 -0
- noneto/diagnostics.py +115 -0
- noneto/errors.py +12 -0
- noneto/i18n.py +199 -0
- noneto/platform/__init__.py +1 -0
- noneto/platform/paths.py +27 -0
- noneto/security.py +59 -0
- noneto/services/__init__.py +1 -0
- noneto/services/covers.py +88 -0
- noneto/services/executor.py +83 -0
- noneto/services/library.py +110 -0
- noneto/services/tidal.py +188 -0
- noneto/settings.py +48 -0
- noneto/state/__init__.py +1 -0
- noneto/state/queue.py +130 -0
- noneto/state/writer.py +38 -0
- noneto/ui/__init__.py +1 -0
- noneto/ui/common.py +36 -0
- noneto/ui/cover.py +88 -0
- noneto/ui/dialogs.py +107 -0
- noneto/ui/linux_login.py +57 -0
- noneto/ui/login_window.py +201 -0
- noneto/ui/lyrics.py +142 -0
- noneto/ui/player.py +172 -0
- noneto/ui/quality.py +75 -0
- noneto/ui/queue.py +34 -0
- noneto/ui/terminal.py +65 -0
- noneto/ui/themes.py +352 -0
- noneto/ui/top.py +39 -0
- noneto/ui/tracks.py +139 -0
- noneto/ui/tui.py +601 -0
- noneto/ui/visualizer.py +343 -0
- noneto_cli-1.1.1.dist-info/METADATA +222 -0
- noneto_cli-1.1.1.dist-info/RECORD +59 -0
- noneto_cli-1.1.1.dist-info/WHEEL +4 -0
- noneto_cli-1.1.1.dist-info/entry_points.txt +2 -0
- noneto_cli-1.1.1.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Bounded priority worker; iterator jobs yield ownership between pages."""
|
|
2
|
+
from concurrent.futures import Future, InvalidStateError
|
|
3
|
+
import heapq
|
|
4
|
+
import inspect
|
|
5
|
+
import itertools
|
|
6
|
+
import threading
|
|
7
|
+
|
|
8
|
+
from ..errors import AppError
|
|
9
|
+
from ..i18n import _
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class PriorityExecutor:
|
|
13
|
+
def __init__(self, name, capacity=128):
|
|
14
|
+
self._condition = threading.Condition()
|
|
15
|
+
self._jobs = []
|
|
16
|
+
self._sequence = itertools.count()
|
|
17
|
+
self._capacity = capacity
|
|
18
|
+
self._closing = False
|
|
19
|
+
self._thread = threading.Thread(target=self._run, name=name, daemon=True)
|
|
20
|
+
self._thread.start()
|
|
21
|
+
|
|
22
|
+
def submit(self, function, *args, priority=20):
|
|
23
|
+
future = Future()
|
|
24
|
+
with self._condition:
|
|
25
|
+
if self._closing:
|
|
26
|
+
raise RuntimeError("Executor is closed")
|
|
27
|
+
self._jobs = [job for job in self._jobs if not job[2].cancelled() or job[5] is not None]
|
|
28
|
+
heapq.heapify(self._jobs)
|
|
29
|
+
if len(self._jobs) >= self._capacity:
|
|
30
|
+
raise AppError(_("Too many pending actions. Wait a moment."))
|
|
31
|
+
heapq.heappush(self._jobs, (priority, next(self._sequence), future, function, args, None))
|
|
32
|
+
self._condition.notify()
|
|
33
|
+
return future
|
|
34
|
+
|
|
35
|
+
def _run(self):
|
|
36
|
+
while True:
|
|
37
|
+
with self._condition:
|
|
38
|
+
self._condition.wait_for(lambda: self._closing or self._jobs)
|
|
39
|
+
if not self._jobs:
|
|
40
|
+
return
|
|
41
|
+
priority, _, future, function, args, iterator = heapq.heappop(self._jobs)
|
|
42
|
+
if future.cancelled():
|
|
43
|
+
if iterator is not None:
|
|
44
|
+
iterator.close()
|
|
45
|
+
continue
|
|
46
|
+
try:
|
|
47
|
+
if iterator is None:
|
|
48
|
+
# Page jobs remain cancellable between SDK requests.
|
|
49
|
+
if not inspect.isgeneratorfunction(function):
|
|
50
|
+
if not future.set_running_or_notify_cancel():
|
|
51
|
+
continue
|
|
52
|
+
future.set_result(function(*args))
|
|
53
|
+
continue
|
|
54
|
+
iterator = function(*args)
|
|
55
|
+
next(iterator)
|
|
56
|
+
except StopIteration as done:
|
|
57
|
+
try:
|
|
58
|
+
future.set_result(done.value)
|
|
59
|
+
except InvalidStateError:
|
|
60
|
+
pass
|
|
61
|
+
except Exception as error:
|
|
62
|
+
try:
|
|
63
|
+
future.set_exception(error)
|
|
64
|
+
except InvalidStateError:
|
|
65
|
+
pass
|
|
66
|
+
else:
|
|
67
|
+
with self._condition:
|
|
68
|
+
if self._closing or future.cancelled():
|
|
69
|
+
future.cancel()
|
|
70
|
+
iterator.close()
|
|
71
|
+
else:
|
|
72
|
+
heapq.heappush(self._jobs, (priority, next(self._sequence), future, function, args, iterator))
|
|
73
|
+
self._condition.notify()
|
|
74
|
+
|
|
75
|
+
def shutdown(self, wait=True, cancel_futures=True):
|
|
76
|
+
with self._condition:
|
|
77
|
+
self._closing = True
|
|
78
|
+
if cancel_futures:
|
|
79
|
+
for job in self._jobs:
|
|
80
|
+
job[2].cancel()
|
|
81
|
+
self._condition.notify_all()
|
|
82
|
+
if wait:
|
|
83
|
+
self._thread.join()
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""One prioritized SDK owner and a separate bounded image worker."""
|
|
2
|
+
from concurrent.futures import Future, InvalidStateError
|
|
3
|
+
|
|
4
|
+
from .covers import COVER_SIZE, CoverDownloader, cover_image
|
|
5
|
+
from .executor import PriorityExecutor
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Library:
|
|
9
|
+
def __init__(self, catalog, persist=lambda: None):
|
|
10
|
+
self.catalog, self.persist = catalog, persist
|
|
11
|
+
self.executor = PriorityExecutor("noneto-api")
|
|
12
|
+
self._media = PriorityExecutor("noneto-covers", capacity=32)
|
|
13
|
+
self._covers = CoverDownloader()
|
|
14
|
+
|
|
15
|
+
def submit(self, operation, *args):
|
|
16
|
+
if operation in ("artwork", "media_cover") and callable(getattr(self.catalog, "cover_request", None)):
|
|
17
|
+
return self._cover(operation, args)
|
|
18
|
+
if operation in ("tracks", "playlists") and callable(getattr(self.catalog, "pages", None)):
|
|
19
|
+
return self.executor.submit(self._pages, operation, args)
|
|
20
|
+
priority = 10 if operation in ("lyrics", "create", "add") else 20
|
|
21
|
+
return self.executor.submit(self._call, getattr(self.catalog, operation), args, priority=priority)
|
|
22
|
+
|
|
23
|
+
def resolve(self, resolver, track, directory):
|
|
24
|
+
return self.executor.submit(self._call, self._resolve, (resolver, track, directory), priority=0)
|
|
25
|
+
|
|
26
|
+
def _resolve(self, resolver, track, directory):
|
|
27
|
+
if hasattr(self.catalog, "hydrate"):
|
|
28
|
+
track = self.catalog.hydrate(track)
|
|
29
|
+
return resolver(track, directory)
|
|
30
|
+
|
|
31
|
+
def _call(self, function, args):
|
|
32
|
+
try:
|
|
33
|
+
return function(*args)
|
|
34
|
+
finally:
|
|
35
|
+
self.persist()
|
|
36
|
+
|
|
37
|
+
def _pages(self, operation, args):
|
|
38
|
+
pages = self.catalog.pages(operation, *args)
|
|
39
|
+
result = []
|
|
40
|
+
try:
|
|
41
|
+
while True:
|
|
42
|
+
try:
|
|
43
|
+
page = self._call(next, (pages,))
|
|
44
|
+
except StopIteration:
|
|
45
|
+
return result
|
|
46
|
+
result.extend(page)
|
|
47
|
+
yield # A pending stream can run before the next page.
|
|
48
|
+
finally:
|
|
49
|
+
pages.close()
|
|
50
|
+
|
|
51
|
+
def _cover(self, operation, args):
|
|
52
|
+
result = Future()
|
|
53
|
+
# "artwork" (decoded for the TUI) shares the download and cache entry with the media controls.
|
|
54
|
+
resolution = args[1] if len(args) > 1 else COVER_SIZE
|
|
55
|
+
preparation = self.executor.submit(self._call, self.catalog.cover_request, (args[0], resolution), priority=5)
|
|
56
|
+
stages = [preparation]
|
|
57
|
+
|
|
58
|
+
def complete(pending):
|
|
59
|
+
if result.cancelled():
|
|
60
|
+
return
|
|
61
|
+
try:
|
|
62
|
+
if pending.cancelled():
|
|
63
|
+
result.cancel()
|
|
64
|
+
else:
|
|
65
|
+
result.set_result(pending.result())
|
|
66
|
+
except InvalidStateError:
|
|
67
|
+
pass
|
|
68
|
+
except Exception as error:
|
|
69
|
+
try:
|
|
70
|
+
result.set_exception(error)
|
|
71
|
+
except InvalidStateError:
|
|
72
|
+
pass
|
|
73
|
+
|
|
74
|
+
def download(pending):
|
|
75
|
+
if result.cancelled():
|
|
76
|
+
return
|
|
77
|
+
try:
|
|
78
|
+
if pending.cancelled():
|
|
79
|
+
result.cancel()
|
|
80
|
+
return
|
|
81
|
+
request = pending.result()
|
|
82
|
+
|
|
83
|
+
def fetch():
|
|
84
|
+
data = self._covers.fetch(request)
|
|
85
|
+
return cover_image(data) if operation == "artwork" else data
|
|
86
|
+
|
|
87
|
+
transfer = self._media.submit(fetch)
|
|
88
|
+
stages.append(transfer)
|
|
89
|
+
if result.cancelled():
|
|
90
|
+
transfer.cancel()
|
|
91
|
+
transfer.add_done_callback(complete)
|
|
92
|
+
except Exception as error:
|
|
93
|
+
try:
|
|
94
|
+
result.set_exception(error)
|
|
95
|
+
except InvalidStateError:
|
|
96
|
+
pass
|
|
97
|
+
|
|
98
|
+
def cancel(pending):
|
|
99
|
+
if pending.cancelled():
|
|
100
|
+
for stage in stages:
|
|
101
|
+
stage.cancel()
|
|
102
|
+
|
|
103
|
+
result.add_done_callback(cancel)
|
|
104
|
+
preparation.add_done_callback(download)
|
|
105
|
+
return result
|
|
106
|
+
|
|
107
|
+
def close(self):
|
|
108
|
+
self.executor.shutdown(wait=True, cancel_futures=True)
|
|
109
|
+
self._media.shutdown(wait=True, cancel_futures=True)
|
|
110
|
+
self._covers.close()
|
noneto/services/tidal.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"""Tidal HTTP and catalog boundary. No terminal or player imports."""
|
|
2
|
+
import logging
|
|
3
|
+
import re
|
|
4
|
+
import uuid
|
|
5
|
+
import time
|
|
6
|
+
|
|
7
|
+
import requests
|
|
8
|
+
import tidalapi
|
|
9
|
+
from requests.adapters import HTTPAdapter
|
|
10
|
+
from urllib3.util.retry import Retry
|
|
11
|
+
|
|
12
|
+
from ..state.queue import SavedTrack
|
|
13
|
+
from ..errors import AppError
|
|
14
|
+
from ..i18n import _
|
|
15
|
+
from ..security import https_url
|
|
16
|
+
from ..diagnostics import emit, failure, request_target
|
|
17
|
+
from .covers import COVER_SIZE, COVER_SIZES, CoverDownloader, cover_image
|
|
18
|
+
|
|
19
|
+
API_HOSTS = frozenset({"auth.tidal.com", "api.tidal.com", "openapi.tidal.com"})
|
|
20
|
+
# Tidal closed idle connections after 180-300 s (measured 2026-10-06). A request sent on a
|
|
21
|
+
# socket closing at that moment fails with ConnectionError and read=0 never retries it, so
|
|
22
|
+
# after a song-length pause start from fresh connections instead of reusing pooled ones.
|
|
23
|
+
IDLE_RESET_SECONDS = 60
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class TimedSession(requests.Session):
|
|
27
|
+
def __init__(self):
|
|
28
|
+
super().__init__()
|
|
29
|
+
self._last_used = None
|
|
30
|
+
# Do not implicitly load .netrc credentials, environment proxies or CA overrides.
|
|
31
|
+
self.trust_env = False
|
|
32
|
+
retry = Retry(total=2, connect=2, read=0, status=2, redirect=0,
|
|
33
|
+
allowed_methods=frozenset({"GET", "HEAD"}),
|
|
34
|
+
status_forcelist=(502, 503, 504), backoff_factor=0.3,
|
|
35
|
+
respect_retry_after_header=False)
|
|
36
|
+
self.mount("https://", HTTPAdapter(max_retries=retry))
|
|
37
|
+
|
|
38
|
+
def request(self, method, url, **kwargs):
|
|
39
|
+
https_url(url, hosts=API_HOSTS)
|
|
40
|
+
kwargs.setdefault("timeout", (10, 30))
|
|
41
|
+
kwargs["allow_redirects"] = False # OAuth POST bodies must never follow 307/308.
|
|
42
|
+
kwargs["verify"] = True
|
|
43
|
+
target = request_target(url)
|
|
44
|
+
started = time.monotonic()
|
|
45
|
+
if self._last_used is not None and started - self._last_used > IDLE_RESET_SECONDS:
|
|
46
|
+
for adapter in self.adapters.values():
|
|
47
|
+
adapter.poolmanager.clear()
|
|
48
|
+
emit("http.pool_reset", elapsed_ms=round((started - self._last_used) * 1000))
|
|
49
|
+
emit("http.started", method=method, **target)
|
|
50
|
+
try:
|
|
51
|
+
response = super().request(method, url, **kwargs)
|
|
52
|
+
except requests.RequestException as error:
|
|
53
|
+
failure("http.failed", error, method=method, **target,
|
|
54
|
+
elapsed_ms=round((time.monotonic() - started) * 1000))
|
|
55
|
+
raise
|
|
56
|
+
finally:
|
|
57
|
+
self._last_used = time.monotonic()
|
|
58
|
+
emit("http.completed", method=method, **target, status=response.status_code,
|
|
59
|
+
elapsed_ms=round((time.monotonic() - started) * 1000))
|
|
60
|
+
if 300 <= response.status_code < 400:
|
|
61
|
+
response.close()
|
|
62
|
+
raise AppError(_("TIDAL returned a disallowed redirect."))
|
|
63
|
+
return response
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def create_session(quality):
|
|
67
|
+
for name in ("tidalapi", "urllib3", "requests"):
|
|
68
|
+
logger = logging.getLogger(name)
|
|
69
|
+
logger.addHandler(logging.NullHandler())
|
|
70
|
+
logger.propagate = False
|
|
71
|
+
logger.setLevel(logging.CRITICAL + 1)
|
|
72
|
+
session = tidalapi.Session(tidalapi.Config(quality=tidalapi.Quality(quality)))
|
|
73
|
+
session.request_session.close()
|
|
74
|
+
session.request_session = TimedSession()
|
|
75
|
+
return session
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def all_pages(fetch, limit=50, max_pages=1000):
|
|
79
|
+
return [item for page in iter_pages(fetch, limit, max_pages) for item in page]
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def iter_pages(fetch, limit=50, max_pages=1000):
|
|
83
|
+
if limit < 1 or max_pages < 1:
|
|
84
|
+
raise ValueError("Pagination limits must be positive")
|
|
85
|
+
offset = 0
|
|
86
|
+
for _page in range(max_pages):
|
|
87
|
+
page = fetch(limit=limit, offset=offset)
|
|
88
|
+
if len(page) > limit:
|
|
89
|
+
raise AppError(_("TIDAL returned a larger page than requested."))
|
|
90
|
+
yield page
|
|
91
|
+
offset += len(page)
|
|
92
|
+
if len(page) < limit:
|
|
93
|
+
return
|
|
94
|
+
raise AppError(_("Pagination exceeded the safety limit."))
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def playlist_id(value):
|
|
98
|
+
match = re.fullmatch(
|
|
99
|
+
r"(?:https://(?:www\.|listen\.)?tidal\.com/(?:browse/)?playlist/)?"
|
|
100
|
+
r"([0-9a-fA-F-]{36})/?(?:\?[^\s]*)?", value.strip())
|
|
101
|
+
if not match:
|
|
102
|
+
raise ValueError("Use a TIDAL playlist link or its UUID.")
|
|
103
|
+
return str(uuid.UUID(match.group(1)))
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class Catalog:
|
|
107
|
+
def __init__(self, session):
|
|
108
|
+
self.session = session
|
|
109
|
+
self._restored_tracks = {}
|
|
110
|
+
|
|
111
|
+
def hydrate(self, track):
|
|
112
|
+
if isinstance(track, SavedTrack):
|
|
113
|
+
if track.id not in self._restored_tracks:
|
|
114
|
+
if len(self._restored_tracks) >= 128:
|
|
115
|
+
self._restored_tracks.pop(next(iter(self._restored_tracks)))
|
|
116
|
+
self._restored_tracks[track.id] = self.session.track(track.id)
|
|
117
|
+
return self._restored_tracks[track.id]
|
|
118
|
+
return track
|
|
119
|
+
|
|
120
|
+
def playlists(self):
|
|
121
|
+
return all_pages(self.session.user.playlist_and_favorite_playlists)
|
|
122
|
+
|
|
123
|
+
def playlist(self, value):
|
|
124
|
+
return self.session.playlist(playlist_id(value))
|
|
125
|
+
|
|
126
|
+
def tracks(self, playlist):
|
|
127
|
+
return all_pages(playlist.tracks, limit=100)
|
|
128
|
+
|
|
129
|
+
def pages(self, operation, *args):
|
|
130
|
+
if operation == "tracks":
|
|
131
|
+
return iter_pages(args[0].tracks, limit=100)
|
|
132
|
+
if operation == "playlists":
|
|
133
|
+
return iter_pages(self.session.user.playlist_and_favorite_playlists)
|
|
134
|
+
raise ValueError("Invalid paginated operation")
|
|
135
|
+
|
|
136
|
+
def search(self, query, offset=0):
|
|
137
|
+
return self._search(query, offset, tidalapi.Track, "tracks")
|
|
138
|
+
|
|
139
|
+
def search_playlists(self, query, offset=0):
|
|
140
|
+
return self._search(query, offset, tidalapi.Playlist, "playlists")
|
|
141
|
+
|
|
142
|
+
def _search(self, query, offset, model, key):
|
|
143
|
+
query = query.strip()
|
|
144
|
+
if not query or len(query) > 200:
|
|
145
|
+
raise AppError(_("Type a search between 1 and 200 characters."))
|
|
146
|
+
return self.session.search(query, models=[model], limit=50, offset=offset)[key]
|
|
147
|
+
|
|
148
|
+
def lyrics(self, track):
|
|
149
|
+
data = self.hydrate(track).lyrics()
|
|
150
|
+
return (data.text or "", data.subtitles or "", bool(data.right_to_left))
|
|
151
|
+
|
|
152
|
+
def artwork(self, track):
|
|
153
|
+
return cover_image(self.media_cover(track))
|
|
154
|
+
|
|
155
|
+
def media_cover(self, track, resolution=COVER_SIZE):
|
|
156
|
+
downloader = CoverDownloader()
|
|
157
|
+
try:
|
|
158
|
+
return downloader.fetch(self.cover_request(track, resolution))
|
|
159
|
+
finally:
|
|
160
|
+
downloader.close()
|
|
161
|
+
|
|
162
|
+
def cover_request(self, track, resolution=COVER_SIZE):
|
|
163
|
+
"""Obtain SDK metadata on its owner; pass only a validated URL to media IO."""
|
|
164
|
+
if type(resolution) is not int or resolution not in COVER_SIZES:
|
|
165
|
+
raise ValueError("Invalid cover resolution")
|
|
166
|
+
track = self.hydrate(track)
|
|
167
|
+
album = getattr(track, "album", None)
|
|
168
|
+
if album is None or not getattr(album, "cover", None):
|
|
169
|
+
return None
|
|
170
|
+
url = https_url(album.image(resolution), hosts={"resources.tidal.com"})
|
|
171
|
+
return url, resolution
|
|
172
|
+
|
|
173
|
+
def editable(self, playlist):
|
|
174
|
+
return (str(getattr(getattr(playlist, "creator", None), "id", ""))
|
|
175
|
+
== str(self.session.user.id) and callable(getattr(playlist, "add", None)))
|
|
176
|
+
|
|
177
|
+
def create(self, title):
|
|
178
|
+
title = title.strip()
|
|
179
|
+
if not title or len(title) > 100:
|
|
180
|
+
raise AppError(_("The name must be between 1 and 100 characters."))
|
|
181
|
+
return self.session.user.create_playlist(title, "")
|
|
182
|
+
|
|
183
|
+
def add(self, playlist, track):
|
|
184
|
+
# Refresh ownership and ETag immediately before writing.
|
|
185
|
+
current = self.playlist(str(playlist.id))
|
|
186
|
+
if not self.editable(current):
|
|
187
|
+
raise AppError(_("You can only add songs to your own playlists."))
|
|
188
|
+
return current.add([str(track.id)], allow_duplicates=False)
|
noneto/settings.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Non-secret interface preferences in the platform config directory.
|
|
2
|
+
|
|
3
|
+
Nothing secret lives here. Unknown keys and invalid values are dropped on read.
|
|
4
|
+
"""
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from .platform.paths import config_dir
|
|
8
|
+
import tempfile
|
|
9
|
+
|
|
10
|
+
MAX_SETTINGS_BYTES = 4096
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def settings_path():
|
|
14
|
+
return config_dir() / "settings.json"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def load_settings(allowed_themes, path=None, allowed_visualizer_modes=None, allowed_lyrics_layouts=None):
|
|
18
|
+
path = Path(path) if path is not None else settings_path()
|
|
19
|
+
try:
|
|
20
|
+
with path.open("rb") as source:
|
|
21
|
+
data = json.loads(source.read(MAX_SETTINGS_BYTES + 1)[:MAX_SETTINGS_BYTES])
|
|
22
|
+
except (OSError, ValueError):
|
|
23
|
+
return {}
|
|
24
|
+
if not isinstance(data, dict):
|
|
25
|
+
return {}
|
|
26
|
+
result = {}
|
|
27
|
+
if data.get("theme") in allowed_themes:
|
|
28
|
+
result["theme"] = data["theme"]
|
|
29
|
+
if allowed_visualizer_modes is not None and data.get("visualizer_mode") in allowed_visualizer_modes:
|
|
30
|
+
result["visualizer_mode"] = data["visualizer_mode"]
|
|
31
|
+
if allowed_lyrics_layouts is not None and data.get("lyrics_layout") in allowed_lyrics_layouts:
|
|
32
|
+
result["lyrics_layout"] = data["lyrics_layout"]
|
|
33
|
+
return result
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def save_settings(settings, path=None):
|
|
37
|
+
path = Path(path) if path is not None else settings_path()
|
|
38
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
39
|
+
temp = None
|
|
40
|
+
try:
|
|
41
|
+
with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=path.parent, prefix=".settings-",
|
|
42
|
+
suffix=".tmp", delete=False) as output:
|
|
43
|
+
temp = Path(output.name)
|
|
44
|
+
json.dump(settings, output)
|
|
45
|
+
temp.replace(path)
|
|
46
|
+
finally:
|
|
47
|
+
if temp is not None:
|
|
48
|
+
temp.unlink(missing_ok=True)
|
noneto/state/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Local non-secret application state."""
|
noneto/state/queue.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Bounded, atomic queue storage. No SDK objects, credentials or stream URLs."""
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
import json
|
|
4
|
+
import math
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import tempfile
|
|
8
|
+
from types import SimpleNamespace
|
|
9
|
+
|
|
10
|
+
from ..platform.paths import state_dir
|
|
11
|
+
from ..security import terminal_text
|
|
12
|
+
|
|
13
|
+
MAX_BYTES = 8 * 1024 * 1024
|
|
14
|
+
MAX_TRACKS = 10000
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class SavedTrack:
|
|
19
|
+
id: int
|
|
20
|
+
name: str
|
|
21
|
+
artist: object
|
|
22
|
+
album: object
|
|
23
|
+
duration: float
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _number(value, maximum):
|
|
27
|
+
if type(value) not in (int, float) or not math.isfinite(value) or not 0 <= value <= maximum:
|
|
28
|
+
raise ValueError("Invalid queue number")
|
|
29
|
+
return value
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _text(value):
|
|
33
|
+
if not isinstance(value, str) or len(value) > 300:
|
|
34
|
+
raise ValueError("Invalid queue metadata")
|
|
35
|
+
return terminal_text(value)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class QueueStore:
|
|
39
|
+
def __init__(self, account, path=None):
|
|
40
|
+
self.account = str(account)
|
|
41
|
+
self.path = Path(path) if path is not None else state_dir() / "queue.json"
|
|
42
|
+
self._cached_tracks = None
|
|
43
|
+
self._cached_order = None
|
|
44
|
+
self._encoded_tracks = b"[]"
|
|
45
|
+
self._encoded_order = b"[]"
|
|
46
|
+
|
|
47
|
+
def load(self):
|
|
48
|
+
try:
|
|
49
|
+
with self.path.open("rb") as source:
|
|
50
|
+
raw = source.read(MAX_BYTES + 1)
|
|
51
|
+
if len(raw) > MAX_BYTES:
|
|
52
|
+
raise ValueError("Queue too large")
|
|
53
|
+
data = json.loads(raw)
|
|
54
|
+
if (not isinstance(data, dict) or type(data.get("version")) is not int
|
|
55
|
+
or data.get("version") != 1 or data.get("account") != self.account):
|
|
56
|
+
return None
|
|
57
|
+
entries = data["tracks"]
|
|
58
|
+
if not isinstance(entries, list) or len(entries) > MAX_TRACKS:
|
|
59
|
+
raise ValueError("Invalid queue size")
|
|
60
|
+
tracks = []
|
|
61
|
+
for entry in entries:
|
|
62
|
+
identifier = entry["id"]
|
|
63
|
+
if type(identifier) is not int or not 0 < identifier < 2**63:
|
|
64
|
+
raise ValueError("Invalid track ID")
|
|
65
|
+
tracks.append(SavedTrack(identifier, _text(entry["name"]),
|
|
66
|
+
SimpleNamespace(name=_text(entry["artist"])),
|
|
67
|
+
SimpleNamespace(name=_text(entry["album"])),
|
|
68
|
+
_number(entry["duration"], 86400)))
|
|
69
|
+
order = data["order"]
|
|
70
|
+
if (not isinstance(order, list) or any(type(i) is not int for i in order)
|
|
71
|
+
or sorted(order) != list(range(len(tracks)))):
|
|
72
|
+
raise ValueError("Invalid queue order")
|
|
73
|
+
index = data["index"]
|
|
74
|
+
if type(index) is not int or not -1 <= index < len(tracks):
|
|
75
|
+
raise ValueError("Invalid queue index")
|
|
76
|
+
if type(data["shuffle"]) is not bool or data["repeat"] not in ("off", "all", "one"):
|
|
77
|
+
raise ValueError("Invalid queue mode")
|
|
78
|
+
_number(data["position"], 86400)
|
|
79
|
+
if type(data["volume"]) is not int:
|
|
80
|
+
raise ValueError("Invalid queue volume")
|
|
81
|
+
_number(data["volume"], 100)
|
|
82
|
+
return {**data, "tracks": tuple(tracks)}
|
|
83
|
+
except (OSError, ValueError, TypeError, KeyError, OverflowError):
|
|
84
|
+
return None
|
|
85
|
+
|
|
86
|
+
def save(self, state, source_tracks, order):
|
|
87
|
+
# Only immutable tuple snapshots use identity caches. Lists are always encoded.
|
|
88
|
+
if not isinstance(source_tracks, tuple) or source_tracks is not self._cached_tracks:
|
|
89
|
+
self._encoded_tracks = self._encode_tracks(source_tracks)
|
|
90
|
+
self._cached_tracks = source_tracks if isinstance(source_tracks, tuple) else None
|
|
91
|
+
if not isinstance(order, tuple) or order is not self._cached_order:
|
|
92
|
+
self._encoded_order = json.dumps(list(order)).encode("utf-8")
|
|
93
|
+
self._cached_order = order if isinstance(order, tuple) else None
|
|
94
|
+
data = {"version": 1, "account": self.account,
|
|
95
|
+
"index": state.index, "position": _number(state.position, 86400),
|
|
96
|
+
"volume": state.volume, "shuffle": state.shuffle, "repeat": state.repeat}
|
|
97
|
+
header = json.dumps(data, ensure_ascii=False).encode("utf-8")
|
|
98
|
+
encoded = header[:-1] + b', "tracks": ' + self._encoded_tracks + b', "order": ' + self._encoded_order + b"}"
|
|
99
|
+
if len(encoded) > MAX_BYTES:
|
|
100
|
+
raise ValueError("Queue too large")
|
|
101
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
102
|
+
temp = None
|
|
103
|
+
try:
|
|
104
|
+
with tempfile.NamedTemporaryFile(dir=self.path.parent, prefix=".queue-", suffix=".tmp",
|
|
105
|
+
delete=False) as output:
|
|
106
|
+
temp = Path(output.name)
|
|
107
|
+
output.write(encoded)
|
|
108
|
+
output.flush()
|
|
109
|
+
os.fsync(output.fileno())
|
|
110
|
+
temp.replace(self.path)
|
|
111
|
+
finally:
|
|
112
|
+
if temp is not None:
|
|
113
|
+
temp.unlink(missing_ok=True)
|
|
114
|
+
|
|
115
|
+
@staticmethod
|
|
116
|
+
def _encode_tracks(source_tracks):
|
|
117
|
+
def text(value):
|
|
118
|
+
return terminal_text(str(value or ""))[:300]
|
|
119
|
+
if len(source_tracks) > MAX_TRACKS:
|
|
120
|
+
raise ValueError("Queue too large")
|
|
121
|
+
entries = []
|
|
122
|
+
for track in source_tracks:
|
|
123
|
+
identifier = getattr(track, "id", None)
|
|
124
|
+
if type(identifier) is not int or not 0 < identifier < 2**63:
|
|
125
|
+
raise ValueError("Invalid track ID")
|
|
126
|
+
entries.append({"id": identifier, "name": text(getattr(track, "name", "")),
|
|
127
|
+
"artist": text(getattr(getattr(track, "artist", None), "name", "")),
|
|
128
|
+
"album": text(getattr(getattr(track, "album", None), "name", "")),
|
|
129
|
+
"duration": _number(getattr(track, "duration", 0) or 0, 86400)})
|
|
130
|
+
return json.dumps(entries, ensure_ascii=False).encode("utf-8")
|
noneto/state/writer.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""One disk writer with one replaceable pending immutable queue snapshot."""
|
|
2
|
+
import threading
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class QueueWriter:
|
|
6
|
+
def __init__(self, store, on_error):
|
|
7
|
+
self.store, self.on_error = store, on_error
|
|
8
|
+
self._condition = threading.Condition()
|
|
9
|
+
self._pending = None
|
|
10
|
+
self._closing = False
|
|
11
|
+
self._thread = threading.Thread(target=self._run, name="noneto-queue", daemon=True)
|
|
12
|
+
self._thread.start()
|
|
13
|
+
|
|
14
|
+
def submit(self, state, tracks, order):
|
|
15
|
+
# The controller replaces these tuples; it never edits their ordering.
|
|
16
|
+
with self._condition:
|
|
17
|
+
if self._closing:
|
|
18
|
+
raise RuntimeError("Queue writer is closed")
|
|
19
|
+
self._pending = (state, tracks, order)
|
|
20
|
+
self._condition.notify()
|
|
21
|
+
|
|
22
|
+
def _run(self):
|
|
23
|
+
while True:
|
|
24
|
+
with self._condition:
|
|
25
|
+
self._condition.wait_for(lambda: self._closing or self._pending is not None)
|
|
26
|
+
if self._pending is None:
|
|
27
|
+
return
|
|
28
|
+
pending, self._pending = self._pending, None
|
|
29
|
+
try:
|
|
30
|
+
self.store.save(*pending)
|
|
31
|
+
except Exception as error:
|
|
32
|
+
self.on_error(error)
|
|
33
|
+
|
|
34
|
+
def close(self):
|
|
35
|
+
with self._condition:
|
|
36
|
+
self._closing = True
|
|
37
|
+
self._condition.notify_all()
|
|
38
|
+
self._thread.join() # Includes the newest pending state, even after a failed write.
|
noneto/ui/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Textual TUI, cava-style visualizer and the console messages shown before it opens."""
|
noneto/ui/common.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Helpers shared by the TUI pieces: safe track text and cheap repeated updates."""
|
|
2
|
+
from ..security import terminal_text
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def clean(value):
|
|
6
|
+
return terminal_text(str(value or ""))
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def artist(track):
|
|
10
|
+
return clean(getattr(getattr(track, "artist", None), "name", ""))
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def album(track):
|
|
14
|
+
return clean(getattr(getattr(track, "album", None), "name", ""))
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def duration(value):
|
|
18
|
+
seconds = max(0, int(value or 0))
|
|
19
|
+
return f"{seconds // 60}:{seconds % 60:02d}"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Changes:
|
|
23
|
+
"""Runs 4 times a second: skip unchanged widgets, and fixed-size ones skip the screen-wide layout pass."""
|
|
24
|
+
|
|
25
|
+
def __init__(self):
|
|
26
|
+
self._shown = {}
|
|
27
|
+
|
|
28
|
+
def show(self, widget, value, layout=False):
|
|
29
|
+
if self._shown.get(widget.id) != value:
|
|
30
|
+
self._shown[widget.id] = value
|
|
31
|
+
widget.update(value, layout=layout)
|
|
32
|
+
|
|
33
|
+
def label(self, button, value):
|
|
34
|
+
if self._shown.get(button.id) != value:
|
|
35
|
+
self._shown[button.id] = value
|
|
36
|
+
button.label = value
|