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
noneto/audio/spectrum.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""FFT of the captured samples into log-spaced bands, like cava.
|
|
2
|
+
|
|
3
|
+
numpy is imported on first use so it only costs memory while the visualizer runs.
|
|
4
|
+
"""
|
|
5
|
+
import os
|
|
6
|
+
|
|
7
|
+
LOW_HZ, HIGH_HZ = 50, 12000
|
|
8
|
+
TILT = 0.45 # music falls off with frequency; lift the highs so every band can move
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Spectrum:
|
|
12
|
+
def __init__(self, rate, size=4096):
|
|
13
|
+
# The FFT never touches BLAS; one thread stops OpenBLAS from committing
|
|
14
|
+
# ~600 MB of per-thread buffers at import (measured +617 MB vs +6 MB).
|
|
15
|
+
os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
|
|
16
|
+
import numpy
|
|
17
|
+
self._np = numpy
|
|
18
|
+
self.rate, self.size = rate, size
|
|
19
|
+
self._window = numpy.hanning(size).astype(numpy.float32)
|
|
20
|
+
self._layout = {}
|
|
21
|
+
|
|
22
|
+
def _bands_for(self, count):
|
|
23
|
+
if count not in self._layout:
|
|
24
|
+
np = self._np
|
|
25
|
+
edges = np.geomspace(LOW_HZ, HIGH_HZ, count + 1) * self.size / self.rate
|
|
26
|
+
low = np.floor(edges[:-1]).astype(int)
|
|
27
|
+
high = np.maximum(low + 1, np.ceil(edges[1:]).astype(int))
|
|
28
|
+
centre = np.sqrt(edges[:-1] * edges[1:]) * self.rate / self.size
|
|
29
|
+
self._layout[count] = (low, high, (centre / 1000) ** TILT)
|
|
30
|
+
return self._layout[count]
|
|
31
|
+
|
|
32
|
+
def bands(self, interleaved, count, channels=2):
|
|
33
|
+
"""`interleaved` float32 bytes, newest last; returns `count` band amplitudes."""
|
|
34
|
+
np = self._np
|
|
35
|
+
samples = np.frombuffer(interleaved, dtype=np.float32)
|
|
36
|
+
usable = len(samples) // channels * channels
|
|
37
|
+
mono = samples[len(samples) - usable:].reshape(-1, channels).mean(axis=1)[-self.size:]
|
|
38
|
+
frame = np.zeros(self.size, dtype=np.float32)
|
|
39
|
+
frame[self.size - len(mono):] = mono
|
|
40
|
+
power = np.abs(np.fft.rfft(frame * self._window)) ** 2
|
|
41
|
+
low, high, weight = self._bands_for(count)
|
|
42
|
+
total = np.concatenate(([0.0], np.cumsum(power)))
|
|
43
|
+
mean = (total[high] - total[low]) / (high - low)
|
|
44
|
+
return (np.sqrt(mean) * weight).tolist()
|
noneto/audio/streams.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Resolve a track without parsing DASH timelines into unbounded segment lists."""
|
|
2
|
+
import json
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
import tempfile
|
|
5
|
+
from urllib.parse import urljoin
|
|
6
|
+
|
|
7
|
+
from defusedxml import ElementTree
|
|
8
|
+
from defusedxml.common import DefusedXmlException
|
|
9
|
+
|
|
10
|
+
from ..errors import AppError
|
|
11
|
+
from ..i18n import _
|
|
12
|
+
from ..security import https_url
|
|
13
|
+
from ..diagnostics import emit, track_id
|
|
14
|
+
|
|
15
|
+
MAX_MANIFEST_BYTES = 2 * 1024 * 1024
|
|
16
|
+
DASH_NS = "urn:mpeg:dash:schema:mpd:2011"
|
|
17
|
+
TIERS = {"LOW", "HIGH", "LOSSLESS", "HI_RES", "HI_RES_LOSSLESS"}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def validate_dash(data):
|
|
21
|
+
try:
|
|
22
|
+
root = ElementTree.fromstring(data, forbid_dtd=True)
|
|
23
|
+
except (DefusedXmlException, ElementTree.ParseError, ValueError):
|
|
24
|
+
raise AppError(_("Invalid DASH manifest.")) from None
|
|
25
|
+
if root.tag != f"{{{DASH_NS}}}MPD":
|
|
26
|
+
raise AppError(_("Invalid DASH manifest."))
|
|
27
|
+
references = 0
|
|
28
|
+
|
|
29
|
+
def visit(node, base=None, depth=0):
|
|
30
|
+
nonlocal references
|
|
31
|
+
if depth > 32:
|
|
32
|
+
raise AppError(_("DASH manifest is nested too deeply."))
|
|
33
|
+
if not isinstance(node.tag, str) or not node.tag.startswith(f"{{{DASH_NS}}}"):
|
|
34
|
+
raise AppError(_("Unsupported DASH namespace."))
|
|
35
|
+
tag = node.tag.rsplit("}", 1)[-1]
|
|
36
|
+
if tag in {"ContentProtection", "Location", "PatchLocation", "UTCTiming"}:
|
|
37
|
+
raise AppError(_("The manifest uses an unsupported DASH feature."))
|
|
38
|
+
if any(key.startswith("{http://www.w3.org/1999/xlink}")
|
|
39
|
+
or key == "{http://www.w3.org/XML/1998/namespace}base" for key in node.attrib):
|
|
40
|
+
raise AppError(_("External XML references are not allowed."))
|
|
41
|
+
bases = node.findall(f"{{{DASH_NS}}}BaseURL")
|
|
42
|
+
if len(bases) > 1:
|
|
43
|
+
raise AppError(_("Multiple BaseURL elements are not supported."))
|
|
44
|
+
if bases:
|
|
45
|
+
value = (bases[0].text or "").strip()
|
|
46
|
+
base = https_url(urljoin(base or "", value))
|
|
47
|
+
references += 1
|
|
48
|
+
for key in ("media", "initialization", "sourceURL", "index"):
|
|
49
|
+
if key in node.attrib:
|
|
50
|
+
value = node.attrib[key]
|
|
51
|
+
if "\\" in value or any(ord(c) < 33 for c in value):
|
|
52
|
+
raise AppError(_("Invalid DASH reference."))
|
|
53
|
+
https_url(urljoin(base or "", value))
|
|
54
|
+
references += 1
|
|
55
|
+
for child in node:
|
|
56
|
+
if child.tag != f"{{{DASH_NS}}}BaseURL":
|
|
57
|
+
visit(child, base, depth + 1)
|
|
58
|
+
|
|
59
|
+
visit(root)
|
|
60
|
+
if not references:
|
|
61
|
+
raise AppError(_("The manifest has no audio destinations."))
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def stream_target(track, directory):
|
|
65
|
+
emit("stream.requested", track_id=track_id(track), stage="tidal_api")
|
|
66
|
+
stream = track.get_stream()
|
|
67
|
+
mime = stream.manifest_mime_type
|
|
68
|
+
tier = getattr(stream, "audio_quality", None) # what TIDAL says it delivers, not what was asked
|
|
69
|
+
emit("stream.received", track_id=track_id(track),
|
|
70
|
+
manifest_type=mime if mime in {"application/dash+xml", "application/vnd.tidal.bts"} else "unknown",
|
|
71
|
+
quality=tier if tier in TIERS else "unknown")
|
|
72
|
+
# Check before decoding the base64 envelope in tidalapi.
|
|
73
|
+
encoded = getattr(stream, "manifest", "")
|
|
74
|
+
if isinstance(encoded, str) and len(encoded) > MAX_MANIFEST_BYTES * 4 // 3 + 4:
|
|
75
|
+
raise AppError(_("Audio manifest too large."))
|
|
76
|
+
data = stream.get_manifest_data()
|
|
77
|
+
if not isinstance(data, str) or len(data.encode("utf-8")) > MAX_MANIFEST_BYTES:
|
|
78
|
+
raise AppError(_("Audio manifest too large."))
|
|
79
|
+
if stream.manifest_mime_type == "application/dash+xml":
|
|
80
|
+
validate_dash(data)
|
|
81
|
+
emit("stream.validated", track_id=track_id(track), target_kind="dash")
|
|
82
|
+
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", suffix=".mpd",
|
|
83
|
+
dir=directory, delete=False) as target:
|
|
84
|
+
target.write(data)
|
|
85
|
+
return str(Path(target.name).resolve())
|
|
86
|
+
if stream.manifest_mime_type != "application/vnd.tidal.bts":
|
|
87
|
+
raise AppError(_("Unsupported manifest format."))
|
|
88
|
+
try:
|
|
89
|
+
manifest = json.loads(data)
|
|
90
|
+
if not isinstance(manifest, dict):
|
|
91
|
+
raise ValueError
|
|
92
|
+
if manifest.get("encryptionType") not in (None, "NONE"):
|
|
93
|
+
raise AppError(_("This stream needs an unsupported playback method."))
|
|
94
|
+
urls = manifest["urls"]
|
|
95
|
+
if not isinstance(urls, list) or not urls:
|
|
96
|
+
raise ValueError
|
|
97
|
+
target = https_url(urls[0])
|
|
98
|
+
emit("stream.validated", track_id=track_id(track), target_kind="https")
|
|
99
|
+
return target
|
|
100
|
+
except (ValueError, KeyError, TypeError):
|
|
101
|
+
raise AppError(_("TIDAL did not return a valid audio manifest.")) from None
|
noneto/audio/tap.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"""Capture only mpv's rendered audio with Windows process loopback (Windows 10 2004+).
|
|
2
|
+
|
|
3
|
+
Read-only tap for the visualizer: it never touches mpv's output path. Samples
|
|
4
|
+
stay in a small in-memory ring and are never written anywhere.
|
|
5
|
+
"""
|
|
6
|
+
import ctypes
|
|
7
|
+
from ctypes import wintypes
|
|
8
|
+
import threading
|
|
9
|
+
import uuid
|
|
10
|
+
|
|
11
|
+
from ..diagnostics import emit, failure
|
|
12
|
+
|
|
13
|
+
RATE = 48000
|
|
14
|
+
CHANNELS = 2
|
|
15
|
+
FRAME_BYTES = 4 * CHANNELS # float32 stereo
|
|
16
|
+
RING_FRAMES = 4096
|
|
17
|
+
POLL_SECONDS = 0.01
|
|
18
|
+
|
|
19
|
+
HRESULT = ctypes.c_long
|
|
20
|
+
S_OK, E_NOINTERFACE = 0, -2147467262
|
|
21
|
+
VT_BLOB = 65
|
|
22
|
+
LOOPBACK_TYPE_PROCESS = 1
|
|
23
|
+
INCLUDE_TARGET_PROCESS_TREE = 0
|
|
24
|
+
STREAMFLAGS = 0x00020000 | 0x80000000 | 0x08000000 # LOOPBACK | AUTOCONVERTPCM | SRC_DEFAULT_QUALITY
|
|
25
|
+
BUFFERFLAGS_SILENT = 0x2
|
|
26
|
+
WAVE_FORMAT_IEEE_FLOAT = 3
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class GUID(ctypes.Structure):
|
|
30
|
+
_fields_ = [("Data1", wintypes.DWORD), ("Data2", wintypes.WORD), ("Data3", wintypes.WORD),
|
|
31
|
+
("Data4", ctypes.c_ubyte * 8)]
|
|
32
|
+
|
|
33
|
+
@classmethod
|
|
34
|
+
def parse(cls, text):
|
|
35
|
+
raw = uuid.UUID(text).bytes_le
|
|
36
|
+
return cls.from_buffer_copy(raw)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
IID_IUnknown = GUID.parse("00000000-0000-0000-C000-000000000046")
|
|
40
|
+
IID_IAgileObject = GUID.parse("94ea2b94-e9cc-49e0-c0ff-ee64ca8f5b90")
|
|
41
|
+
IID_CompletionHandler = GUID.parse("41D949AB-9862-444A-80F6-C261334DA5EB")
|
|
42
|
+
IID_IAudioClient = GUID.parse("1CB9AD4C-DBFA-4c32-B178-C2F568A703B2")
|
|
43
|
+
IID_IAudioCaptureClient = GUID.parse("C8ADBD64-E71E-48a0-A4DE-185C395CD317")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class LoopbackParams(ctypes.Structure):
|
|
47
|
+
_fields_ = [("ActivationType", ctypes.c_int), ("TargetProcessId", wintypes.DWORD),
|
|
48
|
+
("ProcessLoopbackMode", ctypes.c_int)]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class Blob(ctypes.Structure):
|
|
52
|
+
_fields_ = [("cbSize", wintypes.ULONG), ("pBlobData", ctypes.c_void_p)]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class PropVariant(ctypes.Structure):
|
|
56
|
+
_fields_ = [("vt", ctypes.c_ushort), ("reserved", ctypes.c_ushort * 3), ("blob", Blob)]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class WaveFormat(ctypes.Structure):
|
|
60
|
+
_fields_ = [("wFormatTag", wintypes.WORD), ("nChannels", wintypes.WORD),
|
|
61
|
+
("nSamplesPerSec", wintypes.DWORD), ("nAvgBytesPerSec", wintypes.DWORD),
|
|
62
|
+
("nBlockAlign", wintypes.WORD), ("wBitsPerSample", wintypes.WORD), ("cbSize", wintypes.WORD)]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _method(pointer, index, *argtypes):
|
|
66
|
+
"""Bind slot `index` of a COM vtable; failures raise OSError with the HRESULT."""
|
|
67
|
+
table = ctypes.cast(pointer, ctypes.POINTER(ctypes.POINTER(ctypes.c_void_p)))[0]
|
|
68
|
+
function = ctypes.WINFUNCTYPE(HRESULT, ctypes.c_void_p, *argtypes)(table[index])
|
|
69
|
+
|
|
70
|
+
def call(*args):
|
|
71
|
+
result = function(pointer, *args)
|
|
72
|
+
if result < 0:
|
|
73
|
+
raise OSError(f"COM 0x{result & 0xFFFFFFFF:08X}")
|
|
74
|
+
return result
|
|
75
|
+
return call
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _release(pointer):
|
|
79
|
+
if pointer:
|
|
80
|
+
table = ctypes.cast(pointer, ctypes.POINTER(ctypes.POINTER(ctypes.c_void_p)))[0]
|
|
81
|
+
ctypes.WINFUNCTYPE(wintypes.ULONG, ctypes.c_void_p)(table[2])(pointer)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class _CompletionHandler:
|
|
85
|
+
"""Minimal agile IActivateAudioInterfaceCompletionHandler built from ctypes callbacks."""
|
|
86
|
+
|
|
87
|
+
def __init__(self):
|
|
88
|
+
self.done = threading.Event()
|
|
89
|
+
self.operation = None
|
|
90
|
+
query = ctypes.WINFUNCTYPE(HRESULT, ctypes.c_void_p, ctypes.POINTER(GUID), ctypes.POINTER(ctypes.c_void_p))
|
|
91
|
+
count = ctypes.WINFUNCTYPE(wintypes.ULONG, ctypes.c_void_p)
|
|
92
|
+
completed = ctypes.WINFUNCTYPE(HRESULT, ctypes.c_void_p, ctypes.c_void_p)
|
|
93
|
+
self._callbacks = (query(self._query), count(lambda _: 1), count(lambda _: 1), completed(self._completed))
|
|
94
|
+
self._table = (ctypes.c_void_p * 4)(*(ctypes.cast(c, ctypes.c_void_p) for c in self._callbacks))
|
|
95
|
+
self._object = ctypes.pointer(ctypes.c_void_p(ctypes.addressof(self._table)))
|
|
96
|
+
|
|
97
|
+
@property
|
|
98
|
+
def pointer(self):
|
|
99
|
+
return ctypes.cast(self._object, ctypes.c_void_p)
|
|
100
|
+
|
|
101
|
+
def _query(self, this, iid, out):
|
|
102
|
+
if bytes(iid.contents) in (bytes(IID_IUnknown), bytes(IID_IAgileObject), bytes(IID_CompletionHandler)):
|
|
103
|
+
out[0] = this
|
|
104
|
+
return S_OK
|
|
105
|
+
out[0] = None
|
|
106
|
+
return E_NOINTERFACE
|
|
107
|
+
|
|
108
|
+
def _completed(self, this, operation):
|
|
109
|
+
self.operation = operation
|
|
110
|
+
self.done.set()
|
|
111
|
+
return S_OK
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class ProcessTap:
|
|
115
|
+
"""Keeps the latest RING_FRAMES of mpv's output as interleaved float32 stereo."""
|
|
116
|
+
|
|
117
|
+
def __init__(self, pid):
|
|
118
|
+
self.pid = int(pid)
|
|
119
|
+
self.rate = RATE
|
|
120
|
+
self._ring = bytearray()
|
|
121
|
+
self._lock = threading.Lock()
|
|
122
|
+
self._stop = threading.Event()
|
|
123
|
+
self.failed = threading.Event()
|
|
124
|
+
self._thread = threading.Thread(target=self._run, name="noneto-tap", daemon=True)
|
|
125
|
+
|
|
126
|
+
def start(self):
|
|
127
|
+
self._thread.start()
|
|
128
|
+
return self
|
|
129
|
+
|
|
130
|
+
def stop(self):
|
|
131
|
+
self._stop.set()
|
|
132
|
+
if self._thread.is_alive() and self._thread is not threading.current_thread():
|
|
133
|
+
self._thread.join(timeout=2)
|
|
134
|
+
|
|
135
|
+
def samples(self):
|
|
136
|
+
with self._lock:
|
|
137
|
+
return bytes(self._ring)
|
|
138
|
+
|
|
139
|
+
def _push(self, chunk):
|
|
140
|
+
with self._lock:
|
|
141
|
+
self._ring += chunk
|
|
142
|
+
excess = len(self._ring) - RING_FRAMES * FRAME_BYTES
|
|
143
|
+
if excess > 0:
|
|
144
|
+
del self._ring[:excess]
|
|
145
|
+
|
|
146
|
+
def _run(self):
|
|
147
|
+
ole = ctypes.WinDLL("ole32")
|
|
148
|
+
ole.CoInitializeEx(None, 0) # MTA: the completion arrives on a worker thread
|
|
149
|
+
client = capture = None
|
|
150
|
+
try:
|
|
151
|
+
client = self._activate()
|
|
152
|
+
fmt = WaveFormat(WAVE_FORMAT_IEEE_FLOAT, CHANNELS, RATE, RATE * FRAME_BYTES, FRAME_BYTES, 32, 0)
|
|
153
|
+
_method(client, 3, ctypes.c_int, wintypes.DWORD, ctypes.c_longlong, ctypes.c_longlong,
|
|
154
|
+
ctypes.POINTER(WaveFormat), ctypes.c_void_p)(0, STREAMFLAGS, 2_000_000, 0, ctypes.byref(fmt), None)
|
|
155
|
+
service = ctypes.c_void_p()
|
|
156
|
+
_method(client, 14, ctypes.POINTER(GUID), ctypes.POINTER(ctypes.c_void_p))(
|
|
157
|
+
ctypes.byref(IID_IAudioCaptureClient), ctypes.byref(service))
|
|
158
|
+
capture = service.value
|
|
159
|
+
_method(client, 10)()
|
|
160
|
+
emit("visualizer.tap_started")
|
|
161
|
+
get_buffer = _method(capture, 3, ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(ctypes.c_uint32),
|
|
162
|
+
ctypes.POINTER(wintypes.DWORD), ctypes.c_void_p, ctypes.c_void_p)
|
|
163
|
+
release = _method(capture, 4, ctypes.c_uint32)
|
|
164
|
+
next_size = _method(capture, 5, ctypes.POINTER(ctypes.c_uint32))
|
|
165
|
+
data, frames, flags, pending = ctypes.c_void_p(), ctypes.c_uint32(), wintypes.DWORD(), ctypes.c_uint32()
|
|
166
|
+
while not self._stop.wait(POLL_SECONDS):
|
|
167
|
+
next_size(ctypes.byref(pending))
|
|
168
|
+
while pending.value:
|
|
169
|
+
get_buffer(ctypes.byref(data), ctypes.byref(frames), ctypes.byref(flags), None, None)
|
|
170
|
+
size = frames.value * FRAME_BYTES
|
|
171
|
+
silent = flags.value & BUFFERFLAGS_SILENT or not data.value
|
|
172
|
+
self._push(bytes(size) if silent else ctypes.string_at(data.value, size))
|
|
173
|
+
release(frames.value)
|
|
174
|
+
next_size(ctypes.byref(pending))
|
|
175
|
+
_method(client, 11)()
|
|
176
|
+
except OSError as error:
|
|
177
|
+
self.failed.set()
|
|
178
|
+
failure("visualizer.tap_failed", error)
|
|
179
|
+
finally:
|
|
180
|
+
_release(capture)
|
|
181
|
+
_release(client)
|
|
182
|
+
ole.CoUninitialize()
|
|
183
|
+
|
|
184
|
+
def _activate(self):
|
|
185
|
+
params = LoopbackParams(LOOPBACK_TYPE_PROCESS, self.pid, INCLUDE_TARGET_PROCESS_TREE)
|
|
186
|
+
variant = PropVariant(VT_BLOB)
|
|
187
|
+
variant.blob = Blob(ctypes.sizeof(params), ctypes.cast(ctypes.byref(params), ctypes.c_void_p))
|
|
188
|
+
handler = _CompletionHandler()
|
|
189
|
+
operation = ctypes.c_void_p()
|
|
190
|
+
activate = ctypes.WinDLL("Mmdevapi").ActivateAudioInterfaceAsync
|
|
191
|
+
activate.argtypes = [wintypes.LPCWSTR, ctypes.POINTER(GUID), ctypes.POINTER(PropVariant),
|
|
192
|
+
ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p)]
|
|
193
|
+
activate.restype = HRESULT
|
|
194
|
+
result = activate("VAD\\Process_Loopback", ctypes.byref(IID_IAudioClient), ctypes.byref(variant),
|
|
195
|
+
handler.pointer, ctypes.byref(operation))
|
|
196
|
+
if result < 0:
|
|
197
|
+
raise OSError(f"COM 0x{result & 0xFFFFFFFF:08X}")
|
|
198
|
+
try:
|
|
199
|
+
if not handler.done.wait(5):
|
|
200
|
+
raise OSError("activation timed out")
|
|
201
|
+
status, client = HRESULT(), ctypes.c_void_p()
|
|
202
|
+
_method(operation.value, 3, ctypes.POINTER(HRESULT), ctypes.POINTER(ctypes.c_void_p))(
|
|
203
|
+
ctypes.byref(status), ctypes.byref(client))
|
|
204
|
+
if status.value < 0:
|
|
205
|
+
raise OSError(f"COM 0x{status.value & 0xFFFFFFFF:08X}")
|
|
206
|
+
return client.value
|
|
207
|
+
finally:
|
|
208
|
+
_release(operation.value)
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Register a per-user Start menu identity so SMTC can name the console app."""
|
|
2
|
+
import ctypes
|
|
3
|
+
from ctypes import wintypes
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import sys
|
|
7
|
+
import uuid
|
|
8
|
+
|
|
9
|
+
APP_ID = "Noneto.CLI"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class GUID(ctypes.Structure):
|
|
13
|
+
_fields_ = [("data", ctypes.c_ubyte * 16)]
|
|
14
|
+
|
|
15
|
+
@classmethod
|
|
16
|
+
def parse(cls, value):
|
|
17
|
+
return cls.from_buffer_copy(uuid.UUID(value).bytes_le)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def register_identity():
|
|
21
|
+
"""Only touches Noneto CLI.lnk; never changes file associations or other shortcuts."""
|
|
22
|
+
ole = ctypes.WinDLL("ole32")
|
|
23
|
+
create = ole.CoCreateInstance
|
|
24
|
+
create.argtypes = [ctypes.POINTER(GUID), ctypes.c_void_p, wintypes.DWORD,
|
|
25
|
+
ctypes.POINTER(GUID), ctypes.POINTER(ctypes.c_void_p)]
|
|
26
|
+
create.restype = ctypes.c_long
|
|
27
|
+
link, store, persist = ctypes.c_void_p(), ctypes.c_void_p(), ctypes.c_void_p()
|
|
28
|
+
|
|
29
|
+
def call(pointer, index, types, *args):
|
|
30
|
+
table = ctypes.cast(pointer, ctypes.POINTER(ctypes.POINTER(ctypes.c_void_p))).contents
|
|
31
|
+
result = ctypes.WINFUNCTYPE(ctypes.c_long, ctypes.c_void_p, *types)(table[index])(pointer, *args)
|
|
32
|
+
if result < 0:
|
|
33
|
+
raise OSError("Cannot register Noneto media identity")
|
|
34
|
+
|
|
35
|
+
def query(pointer, identifier, target):
|
|
36
|
+
call(pointer, 0, [ctypes.POINTER(GUID), ctypes.POINTER(ctypes.c_void_p)],
|
|
37
|
+
ctypes.byref(GUID.parse(identifier)), ctypes.byref(target))
|
|
38
|
+
|
|
39
|
+
try:
|
|
40
|
+
result = create(ctypes.byref(GUID.parse("00021401-0000-0000-c000-000000000046")), None, 1,
|
|
41
|
+
ctypes.byref(GUID.parse("000214f9-0000-0000-c000-000000000046")), ctypes.byref(link))
|
|
42
|
+
if result < 0:
|
|
43
|
+
raise OSError("Cannot create Noneto shortcut")
|
|
44
|
+
call(link, 20, [wintypes.LPCWSTR], sys.executable)
|
|
45
|
+
call(link, 11, [wintypes.LPCWSTR], "" if getattr(sys, "frozen", False) else "-m noneto")
|
|
46
|
+
call(link, 7, [wintypes.LPCWSTR], "Noneto CLI")
|
|
47
|
+
icon = Path(__file__).resolve().parents[1] / "assets/noneto.ico"
|
|
48
|
+
call(link, 17, [wintypes.LPCWSTR, ctypes.c_int], str(icon), 0)
|
|
49
|
+
query(link, "886d8eeb-8cf2-4446-8d02-cdba1dbdcf99", store)
|
|
50
|
+
|
|
51
|
+
class PropertyKey(ctypes.Structure):
|
|
52
|
+
_fields_ = [("format", GUID), ("pid", wintypes.DWORD)]
|
|
53
|
+
|
|
54
|
+
class Value(ctypes.Union):
|
|
55
|
+
_fields_ = [("string", wintypes.LPWSTR), ("padding", ctypes.c_ubyte * 16)]
|
|
56
|
+
|
|
57
|
+
class PropVariant(ctypes.Structure):
|
|
58
|
+
_fields_ = [("type", ctypes.c_ushort), ("reserved", ctypes.c_ushort * 3), ("value", Value)]
|
|
59
|
+
|
|
60
|
+
key = PropertyKey(GUID.parse("9f4c2855-9f79-4b39-a8d0-e1d42de1d5f3"), 5)
|
|
61
|
+
variant = PropVariant()
|
|
62
|
+
variant.type = 31 # VT_LPWSTR; SetValue copies the string, no COM allocation is needed.
|
|
63
|
+
variant.value.string = APP_ID
|
|
64
|
+
call(store, 6, [ctypes.POINTER(PropertyKey), ctypes.POINTER(PropVariant)],
|
|
65
|
+
ctypes.byref(key), ctypes.byref(variant))
|
|
66
|
+
call(store, 7, [])
|
|
67
|
+
query(link, "0000010b-0000-0000-c000-000000000046", persist)
|
|
68
|
+
shortcut = Path(os.environ["APPDATA"]) / "Microsoft/Windows/Start Menu/Programs/Noneto CLI.lnk"
|
|
69
|
+
shortcut.parent.mkdir(parents=True, exist_ok=True)
|
|
70
|
+
call(persist, 6, [wintypes.LPCWSTR, wintypes.BOOL], str(shortcut), True)
|
|
71
|
+
notify = ctypes.WinDLL("shell32").SHChangeNotify
|
|
72
|
+
notify.argtypes = [ctypes.c_long, wintypes.UINT, ctypes.c_void_p, ctypes.c_void_p]
|
|
73
|
+
notify.restype = None
|
|
74
|
+
notify(0x2000, 0x0005, ctypes.cast(ctypes.c_wchar_p(str(shortcut)), ctypes.c_void_p), None)
|
|
75
|
+
finally:
|
|
76
|
+
for pointer in (persist, store, link):
|
|
77
|
+
if pointer.value:
|
|
78
|
+
table = ctypes.cast(pointer, ctypes.POINTER(ctypes.POINTER(ctypes.c_void_p))).contents
|
|
79
|
+
ctypes.WINFUNCTYPE(wintypes.ULONG, ctypes.c_void_p)(table[2])(pointer)
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""Windows SMTC publisher. Owns a hidden desktop window, never an audio device."""
|
|
2
|
+
import ctypes
|
|
3
|
+
from ctypes import wintypes
|
|
4
|
+
from datetime import timedelta
|
|
5
|
+
|
|
6
|
+
from ..diagnostics import failure
|
|
7
|
+
from .windows_identity import APP_ID, register_identity
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class WindowsMedia:
|
|
11
|
+
def __init__(self, on_button, on_seek):
|
|
12
|
+
from winrt.runtime import init_apartment, ApartmentType
|
|
13
|
+
from winrt.windows.media.interop import get_for_window
|
|
14
|
+
from winrt.windows.media import MediaPlaybackType
|
|
15
|
+
|
|
16
|
+
init_apartment(ApartmentType.MULTI_THREADED)
|
|
17
|
+
self._apartment = True
|
|
18
|
+
self.hwnd = None
|
|
19
|
+
self.controls = None
|
|
20
|
+
self.tokens = []
|
|
21
|
+
self._stream = None
|
|
22
|
+
try:
|
|
23
|
+
try:
|
|
24
|
+
register_identity()
|
|
25
|
+
except Exception as error:
|
|
26
|
+
failure("media.identity_unavailable", error)
|
|
27
|
+
shell = ctypes.WinDLL("shell32")
|
|
28
|
+
identify = shell.SetCurrentProcessExplicitAppUserModelID
|
|
29
|
+
identify.argtypes = [wintypes.LPCWSTR]
|
|
30
|
+
identify.restype = ctypes.c_long
|
|
31
|
+
if identify(APP_ID) < 0:
|
|
32
|
+
raise OSError("Cannot identify media session")
|
|
33
|
+
self.user = ctypes.WinDLL("user32", use_last_error=True)
|
|
34
|
+
create = self.user.CreateWindowExW
|
|
35
|
+
create.argtypes = [wintypes.DWORD, wintypes.LPCWSTR, wintypes.LPCWSTR,
|
|
36
|
+
wintypes.DWORD, ctypes.c_int, ctypes.c_int, ctypes.c_int,
|
|
37
|
+
ctypes.c_int, wintypes.HWND, wintypes.HMENU,
|
|
38
|
+
wintypes.HINSTANCE, ctypes.c_void_p]
|
|
39
|
+
create.restype = wintypes.HWND
|
|
40
|
+
self.user.DestroyWindow.argtypes = [wintypes.HWND]
|
|
41
|
+
self.user.DestroyWindow.restype = wintypes.BOOL
|
|
42
|
+
self.user.PeekMessageW.argtypes = [ctypes.POINTER(wintypes.MSG), wintypes.HWND,
|
|
43
|
+
wintypes.UINT, wintypes.UINT, wintypes.UINT]
|
|
44
|
+
self.user.PeekMessageW.restype = wintypes.BOOL
|
|
45
|
+
self.user.TranslateMessage.argtypes = [ctypes.POINTER(wintypes.MSG)]
|
|
46
|
+
self.user.DispatchMessageW.argtypes = [ctypes.POINTER(wintypes.MSG)]
|
|
47
|
+
self.user.DispatchMessageW.restype = ctypes.c_ssize_t
|
|
48
|
+
self.hwnd = create(0, "STATIC", "Noneto CLI", 0x80000000, 0, 0, 0, 0,
|
|
49
|
+
None, None, None, None)
|
|
50
|
+
if not self.hwnd:
|
|
51
|
+
raise ctypes.WinError(ctypes.get_last_error())
|
|
52
|
+
self.controls = get_for_window(self.hwnd)
|
|
53
|
+
self.controls.is_enabled = False
|
|
54
|
+
self.controls.display_updater.type = MediaPlaybackType.MUSIC
|
|
55
|
+
self.tokens = [
|
|
56
|
+
(self.controls.remove_button_pressed,
|
|
57
|
+
self.controls.add_button_pressed(lambda sender, args: on_button(args.button.name))),
|
|
58
|
+
(self.controls.remove_playback_position_change_requested,
|
|
59
|
+
self.controls.add_playback_position_change_requested(
|
|
60
|
+
lambda sender, args: on_seek(args.requested_playback_position.total_seconds()))),
|
|
61
|
+
]
|
|
62
|
+
except BaseException:
|
|
63
|
+
self.close()
|
|
64
|
+
raise
|
|
65
|
+
|
|
66
|
+
def pump(self):
|
|
67
|
+
message = wintypes.MSG()
|
|
68
|
+
while self.user.PeekMessageW(ctypes.byref(message), None, 0, 0, 1):
|
|
69
|
+
self.user.TranslateMessage(ctypes.byref(message))
|
|
70
|
+
self.user.DispatchMessageW(ctypes.byref(message))
|
|
71
|
+
|
|
72
|
+
def metadata(self, title, artist, album):
|
|
73
|
+
from winrt.windows.media import MediaPlaybackType
|
|
74
|
+
updater = self.controls.display_updater
|
|
75
|
+
updater.clear_all()
|
|
76
|
+
updater.type = MediaPlaybackType.MUSIC
|
|
77
|
+
updater.music_properties.title = title
|
|
78
|
+
updater.music_properties.artist = artist
|
|
79
|
+
updater.music_properties.album_title = album
|
|
80
|
+
updater.update()
|
|
81
|
+
self._close_stream()
|
|
82
|
+
|
|
83
|
+
def thumbnail(self, data):
|
|
84
|
+
from winrt.windows.storage.streams import (DataWriter, InMemoryRandomAccessStream,
|
|
85
|
+
RandomAccessStreamReference)
|
|
86
|
+
stream = InMemoryRandomAccessStream()
|
|
87
|
+
writer = DataWriter(stream)
|
|
88
|
+
try:
|
|
89
|
+
writer.write_bytes(data)
|
|
90
|
+
# store_async is completed by Windows, not by the Textual event loop.
|
|
91
|
+
operation = writer.store_async()
|
|
92
|
+
from winrt.windows.foundation import AsyncStatus
|
|
93
|
+
import time
|
|
94
|
+
deadline = time.monotonic() + 2
|
|
95
|
+
while operation.status == AsyncStatus.STARTED:
|
|
96
|
+
if time.monotonic() >= deadline:
|
|
97
|
+
operation.cancel()
|
|
98
|
+
raise TimeoutError("Media artwork write timed out")
|
|
99
|
+
time.sleep(0.01)
|
|
100
|
+
operation.get_results()
|
|
101
|
+
writer.detach_stream()
|
|
102
|
+
stream.seek(0)
|
|
103
|
+
self.controls.display_updater.thumbnail = RandomAccessStreamReference.create_from_stream(stream)
|
|
104
|
+
self.controls.display_updater.update()
|
|
105
|
+
except BaseException:
|
|
106
|
+
stream.close()
|
|
107
|
+
raise
|
|
108
|
+
finally:
|
|
109
|
+
writer.close()
|
|
110
|
+
self._close_stream()
|
|
111
|
+
self._stream = stream
|
|
112
|
+
|
|
113
|
+
def update(self, status, position, duration, previous, next_track):
|
|
114
|
+
from winrt.windows.media import MediaPlaybackStatus, SystemMediaTransportControlsTimelineProperties
|
|
115
|
+
active = status in ("playing", "paused", "loading")
|
|
116
|
+
controls = self.controls
|
|
117
|
+
controls.playback_status = {"playing": MediaPlaybackStatus.PLAYING,
|
|
118
|
+
"paused": MediaPlaybackStatus.PAUSED,
|
|
119
|
+
"loading": MediaPlaybackStatus.CHANGING}.get(status, MediaPlaybackStatus.STOPPED)
|
|
120
|
+
controls.is_play_enabled = active
|
|
121
|
+
controls.is_pause_enabled = active
|
|
122
|
+
controls.is_stop_enabled = active
|
|
123
|
+
controls.is_previous_enabled = active and previous
|
|
124
|
+
controls.is_next_enabled = active and next_track
|
|
125
|
+
timeline = SystemMediaTransportControlsTimelineProperties()
|
|
126
|
+
timeline.start_time = timeline.min_seek_time = timedelta(0)
|
|
127
|
+
timeline.end_time = timeline.max_seek_time = timedelta(seconds=duration)
|
|
128
|
+
timeline.position = timedelta(seconds=position)
|
|
129
|
+
controls.update_timeline_properties(timeline)
|
|
130
|
+
controls.is_enabled = active
|
|
131
|
+
|
|
132
|
+
def _close_stream(self):
|
|
133
|
+
if self._stream is not None:
|
|
134
|
+
self._stream.close()
|
|
135
|
+
self._stream = None
|
|
136
|
+
|
|
137
|
+
def close(self):
|
|
138
|
+
from winrt.runtime import uninit_apartment
|
|
139
|
+
try:
|
|
140
|
+
if self.controls is not None:
|
|
141
|
+
for remove, token in self.tokens:
|
|
142
|
+
remove(token)
|
|
143
|
+
self.tokens = []
|
|
144
|
+
self.controls.is_enabled = False
|
|
145
|
+
self.controls.display_updater.clear_all()
|
|
146
|
+
self.controls.display_updater.update()
|
|
147
|
+
finally:
|
|
148
|
+
self.controls = None
|
|
149
|
+
try:
|
|
150
|
+
self._close_stream()
|
|
151
|
+
finally:
|
|
152
|
+
if self.hwnd:
|
|
153
|
+
self.user.DestroyWindow(self.hwnd)
|
|
154
|
+
self.hwnd = None
|
|
155
|
+
if self._apartment:
|
|
156
|
+
uninit_apartment()
|
|
157
|
+
self._apartment = False
|
noneto/auth/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""OAuth lifecycle and native secure session storage."""
|
noneto/auth/dpapi.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Windows DPAPI encryption bound to the current user."""
|
|
2
|
+
import ctypes
|
|
3
|
+
from ctypes import wintypes
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class Blob(ctypes.Structure):
|
|
7
|
+
_fields_ = [("size", wintypes.DWORD), ("data", ctypes.POINTER(ctypes.c_ubyte))]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def protect(data: bytes, decrypt: bool = False) -> bytes:
|
|
11
|
+
crypt = ctypes.WinDLL("crypt32", use_last_error=True)
|
|
12
|
+
kernel = ctypes.WinDLL("kernel32", use_last_error=True)
|
|
13
|
+
kernel.LocalFree.argtypes = [ctypes.c_void_p]
|
|
14
|
+
kernel.LocalFree.restype = ctypes.c_void_p
|
|
15
|
+
fn = crypt.CryptUnprotectData if decrypt else crypt.CryptProtectData
|
|
16
|
+
fn.argtypes = [ctypes.POINTER(Blob), ctypes.c_void_p, ctypes.c_void_p,
|
|
17
|
+
ctypes.c_void_p, ctypes.c_void_p, wintypes.DWORD,
|
|
18
|
+
ctypes.POINTER(Blob)]
|
|
19
|
+
fn.restype = wintypes.BOOL
|
|
20
|
+
buffer = ctypes.create_string_buffer(data)
|
|
21
|
+
source = Blob(len(data), ctypes.cast(buffer, ctypes.POINTER(ctypes.c_ubyte)))
|
|
22
|
+
result = Blob()
|
|
23
|
+
if not fn(ctypes.byref(source), None, None, None, None, 1, ctypes.byref(result)):
|
|
24
|
+
raise ctypes.WinError(ctypes.get_last_error())
|
|
25
|
+
try:
|
|
26
|
+
return ctypes.string_at(result.data, result.size)
|
|
27
|
+
finally:
|
|
28
|
+
kernel.LocalFree(ctypes.cast(result.data, ctypes.c_void_p))
|
noneto/auth/service.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""OAuth service; output is delivered as events, not printed here.
|
|
2
|
+
|
|
3
|
+
Login uses PKCE: TIDAL only serves Hi-Res FLAC (up to 24-bit / 192 kHz) to PKCE sessions.
|
|
4
|
+
Device-code sessions stored by earlier versions are replaced by a new PKCE login.
|
|
5
|
+
The UI shows the login page and returns the redirect URL it reaches; it is validated here.
|
|
6
|
+
"""
|
|
7
|
+
import os
|
|
8
|
+
from urllib.parse import urlencode
|
|
9
|
+
|
|
10
|
+
import requests
|
|
11
|
+
from tidalapi.exceptions import AuthenticationError
|
|
12
|
+
|
|
13
|
+
from ..errors import AppError
|
|
14
|
+
from ..i18n import _
|
|
15
|
+
from ..security import https_url, pkce_code
|
|
16
|
+
from .storage import read_session, save_session, session_path, has_session, delete_session
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def login(session, notify, ask):
|
|
20
|
+
if (session_path().exists() if os.name == "nt" else has_session()):
|
|
21
|
+
try:
|
|
22
|
+
restored = session.load_oauth_session(**read_session())
|
|
23
|
+
except (requests.ConnectionError, requests.Timeout):
|
|
24
|
+
raise
|
|
25
|
+
except requests.HTTPError as error:
|
|
26
|
+
if error.response is None or error.response.status_code not in (401, 403):
|
|
27
|
+
raise
|
|
28
|
+
restored = False
|
|
29
|
+
except (OSError, ValueError, TypeError, KeyError, AuthenticationError):
|
|
30
|
+
restored = False
|
|
31
|
+
if restored and session.is_pkce is True:
|
|
32
|
+
save_session(session)
|
|
33
|
+
notify("session-restored")
|
|
34
|
+
return
|
|
35
|
+
notify("session-upgrade" if restored else "session-invalid")
|
|
36
|
+
redirect = session.config.pkce_uri_redirect
|
|
37
|
+
url = https_url(session.pkce_login_url(), hosts={"login.tidal.com"})
|
|
38
|
+
answer = ask("redirect", url=url, redirect=redirect)
|
|
39
|
+
if not answer or not answer.strip():
|
|
40
|
+
raise AppError(_("Sign-in cancelled."))
|
|
41
|
+
code = pkce_code(answer, redirect)
|
|
42
|
+
try:
|
|
43
|
+
# Rebuilt from the validated code: nothing else from the pasted text reaches TIDAL.
|
|
44
|
+
token = session.pkce_get_auth_token(f"{redirect}?{urlencode({'code': code})}")
|
|
45
|
+
except requests.HTTPError:
|
|
46
|
+
raise AppError(_("TIDAL rejected the code; it may have expired. Run noneto again.")) from None
|
|
47
|
+
session.process_auth_token(token, is_pkce_token=True)
|
|
48
|
+
save_session(session)
|
|
49
|
+
notify("session-started")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def logout():
|
|
53
|
+
delete_session()
|