qobit 0.9.0__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.
- qobit/__init__.py +10 -0
- qobit/__main__.py +423 -0
- qobit/_fs.py +38 -0
- qobit/account_data.py +102 -0
- qobit/audio/__init__.py +0 -0
- qobit/audio/device.py +85 -0
- qobit/audio/media_keys.py +442 -0
- qobit/audio/player.py +234 -0
- qobit/audio/verify.py +144 -0
- qobit/config.py +201 -0
- qobit/connect/__init__.py +52 -0
- qobit/connect/proto/__init__.py +8 -0
- qobit/connect/proto/qcloud.proto +60 -0
- qobit/connect/proto/qcloud_pb2.py +50 -0
- qobit/connect/proto/qconnect.proto +723 -0
- qobit/connect/proto/qconnect_pb2.py +210 -0
- qobit/connect/queue.py +108 -0
- qobit/connect/renderer.py +519 -0
- qobit/connect/session.py +155 -0
- qobit/connect/wire.py +99 -0
- qobit/qobuz/__init__.py +0 -0
- qobit/qobuz/client.py +544 -0
- qobit/qobuz/models.py +285 -0
- qobit/qobuz/oauth.py +167 -0
- qobit/qobuz/sanitize.py +32 -0
- qobit/secret.py +22 -0
- qobit/store.py +32 -0
- qobit/token_store.py +106 -0
- qobit/ui/__init__.py +0 -0
- qobit/ui/_images.py +225 -0
- qobit/ui/_now_playing.py +248 -0
- qobit/ui/_utils.py +68 -0
- qobit/ui/app.py +1860 -0
- qobit/ui/nav.py +186 -0
- qobit/ui/play_context.py +376 -0
- qobit/ui/screens/__init__.py +0 -0
- qobit/ui/screens/album_detail.py +353 -0
- qobit/ui/screens/albums.py +341 -0
- qobit/ui/screens/artist_detail.py +1293 -0
- qobit/ui/screens/artists.py +389 -0
- qobit/ui/screens/context_menu.py +192 -0
- qobit/ui/screens/login.py +212 -0
- qobit/ui/screens/mixes.py +348 -0
- qobit/ui/screens/playlist_detail.py +219 -0
- qobit/ui/screens/playlists.py +401 -0
- qobit/ui/screens/queue.py +670 -0
- qobit/ui/screens/search.py +268 -0
- qobit/ui/screens/tracks.py +308 -0
- qobit/ui/themes.py +248 -0
- qobit/ui/widgets/__init__.py +0 -0
- qobit/ui/widgets/art.py +79 -0
- qobit/ui/widgets/lists.py +131 -0
- qobit/ui/widgets/transport.py +350 -0
- qobit-0.9.0.dist-info/METADATA +226 -0
- qobit-0.9.0.dist-info/RECORD +58 -0
- qobit-0.9.0.dist-info/WHEEL +4 -0
- qobit-0.9.0.dist-info/entry_points.txt +2 -0
- qobit-0.9.0.dist-info/licenses/LICENSE +675 -0
qobit/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""qobit — bit-perfect Qobuz client."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
# Single source of truth is pyproject.toml's [project].version — bump it there
|
|
6
|
+
# (and add a CHANGELOG.md entry); this reads it from the installed metadata.
|
|
7
|
+
try:
|
|
8
|
+
__version__ = version("qobit")
|
|
9
|
+
except PackageNotFoundError: # running from a source tree that isn't installed
|
|
10
|
+
__version__ = "0+unknown"
|
qobit/__main__.py
ADDED
|
@@ -0,0 +1,423 @@
|
|
|
1
|
+
"""qobit CLI — Phase 1 entry point.
|
|
2
|
+
|
|
3
|
+
Usage:
|
|
4
|
+
qobit play <query> [--quality QUALITY]
|
|
5
|
+
qobit devices
|
|
6
|
+
qobit set-device
|
|
7
|
+
qobit auth [status]
|
|
8
|
+
qobit logout
|
|
9
|
+
qobit clear-cache
|
|
10
|
+
|
|
11
|
+
Running qobit with no arguments launches the TUI.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import argparse
|
|
15
|
+
import asyncio
|
|
16
|
+
import sys
|
|
17
|
+
import time
|
|
18
|
+
|
|
19
|
+
from . import __version__, token_store
|
|
20
|
+
from .account_data import erase_account_data, erase_settings, tui_running
|
|
21
|
+
from .audio.device import list_devices
|
|
22
|
+
from .audio.player import MpvPlayer
|
|
23
|
+
from .audio.verify import check_bit_perfect
|
|
24
|
+
from .config import (
|
|
25
|
+
CONFIG_FILE,
|
|
26
|
+
get_account,
|
|
27
|
+
get_audio_device,
|
|
28
|
+
get_oauth_session,
|
|
29
|
+
move_token_to_keyring,
|
|
30
|
+
purge_legacy_credentials,
|
|
31
|
+
save_oauth_session,
|
|
32
|
+
set_audio_device,
|
|
33
|
+
token_location,
|
|
34
|
+
)
|
|
35
|
+
from .qobuz.client import AuthExpiredError, QobuzClient, QobuzError
|
|
36
|
+
from .qobuz.models import StreamUrl, Track
|
|
37
|
+
from .qobuz.oauth import LoginPrompt
|
|
38
|
+
|
|
39
|
+
_QUALITY_FALLBACK = ["FLAC_24_192", "FLAC_24_96", "FLAC_CD"]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
_PASTE_REPLIES = {
|
|
43
|
+
"no_code": "That address has no login code: copy the whole address from the "
|
|
44
|
+
"browser's address bar, after logging in.",
|
|
45
|
+
"wrong_login": "That address belongs to a different login: use the link above.",
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _show_login(prompt: LoginPrompt) -> None:
|
|
50
|
+
"""Print the link and, on a terminal, take a pasted redirect address:
|
|
51
|
+
the browser may be on another device (SSH, a headless box), where the
|
|
52
|
+
page it lands on can't load but its address carries the login code."""
|
|
53
|
+
print("\nLog in to Qobuz by opening this link in a browser:\n")
|
|
54
|
+
print(f" {prompt.url}\n")
|
|
55
|
+
if not sys.stdin.isatty():
|
|
56
|
+
print("Waiting for the login to finish...", flush=True)
|
|
57
|
+
return
|
|
58
|
+
print(
|
|
59
|
+
"Logging in on another device? The browser then ends on a page that "
|
|
60
|
+
"doesn't load\n(localhost). Copy that page's address and paste it here.\n"
|
|
61
|
+
)
|
|
62
|
+
print("Waiting for the login (or a pasted address)...", flush=True)
|
|
63
|
+
|
|
64
|
+
def on_line() -> None:
|
|
65
|
+
line = sys.stdin.readline()
|
|
66
|
+
if not line: # EOF: stop reading, keep waiting for the redirect
|
|
67
|
+
asyncio.get_running_loop().remove_reader(sys.stdin.fileno())
|
|
68
|
+
return
|
|
69
|
+
if line.strip() and (msg := _PASTE_REPLIES.get(prompt.submit(line))):
|
|
70
|
+
print(msg, flush=True)
|
|
71
|
+
|
|
72
|
+
asyncio.get_running_loop().add_reader(sys.stdin.fileno(), on_line)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
async def _oauth_login(client: QobuzClient) -> bool:
|
|
76
|
+
"""Browser login (the link is always printed), saving the session."""
|
|
77
|
+
try:
|
|
78
|
+
await client.login_oauth(show_url=_show_login)
|
|
79
|
+
except QobuzError as e:
|
|
80
|
+
print(f"Login failed: {e}", file=sys.stderr)
|
|
81
|
+
return False
|
|
82
|
+
finally:
|
|
83
|
+
if sys.stdin.isatty():
|
|
84
|
+
asyncio.get_running_loop().remove_reader(sys.stdin.fileno())
|
|
85
|
+
previous = get_account().get("name")
|
|
86
|
+
current = (client.account or {}).get("name")
|
|
87
|
+
if previous and current and previous != current and not tui_running():
|
|
88
|
+
# Another account: the previous one's queue and mixes don't carry over.
|
|
89
|
+
erase_account_data()
|
|
90
|
+
save_oauth_session(*client.session(), account=client.account)
|
|
91
|
+
return True
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
async def _authenticate(client: QobuzClient) -> bool:
|
|
95
|
+
"""The saved session, else a browser login."""
|
|
96
|
+
app_id, token, secrets = get_oauth_session()
|
|
97
|
+
if app_id and token and secrets:
|
|
98
|
+
client.restore_session(app_id, token, secrets)
|
|
99
|
+
return True
|
|
100
|
+
print("No saved Qobuz session.")
|
|
101
|
+
return await _oauth_login(client)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
async def cmd_play(args: argparse.Namespace) -> int:
|
|
105
|
+
device = get_audio_device()
|
|
106
|
+
if not device:
|
|
107
|
+
print(
|
|
108
|
+
"No audio device configured. Run: qobit set-device\n"
|
|
109
|
+
"Falling back to mpv auto-select (rate verification may be inaccurate).\n",
|
|
110
|
+
file=sys.stderr,
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
preferred = args.quality
|
|
114
|
+
|
|
115
|
+
async with QobuzClient() as client:
|
|
116
|
+
if not await _authenticate(client):
|
|
117
|
+
print("Authentication failed — exiting.", file=sys.stderr)
|
|
118
|
+
return 1
|
|
119
|
+
|
|
120
|
+
print(f"Searching: {args.query!r}...", end=" ", flush=True)
|
|
121
|
+
results = await client.search(args.query, type="tracks", limit=5)
|
|
122
|
+
tracks_raw = results.get("tracks", {}).get("items", [])
|
|
123
|
+
if not tracks_raw:
|
|
124
|
+
print("no results.", file=sys.stderr)
|
|
125
|
+
return 1
|
|
126
|
+
|
|
127
|
+
track = Track.from_api(tracks_raw[0])
|
|
128
|
+
print(f"found: {track.artist} — {track.display_title} ({track.duration_str})")
|
|
129
|
+
|
|
130
|
+
# Try preferred quality, then fall back down the chain.
|
|
131
|
+
fallbacks = [preferred] + [q for q in _QUALITY_FALLBACK if q != preferred]
|
|
132
|
+
stream: StreamUrl | None = None
|
|
133
|
+
for quality in fallbacks:
|
|
134
|
+
print(f"Resolving stream URL ({quality})...", end=" ", flush=True)
|
|
135
|
+
try:
|
|
136
|
+
url_data = await client.get_streaming_url(str(track.id), quality)
|
|
137
|
+
stream = StreamUrl.from_api(url_data)
|
|
138
|
+
if stream.sample:
|
|
139
|
+
print("preview only — not streamable on this account")
|
|
140
|
+
return 1
|
|
141
|
+
print(f"OK ({stream.quality_badge})")
|
|
142
|
+
break
|
|
143
|
+
except QobuzError as e:
|
|
144
|
+
print(f"unavailable ({e})")
|
|
145
|
+
|
|
146
|
+
if stream is None:
|
|
147
|
+
print("No playable stream found.", file=sys.stderr)
|
|
148
|
+
return 1
|
|
149
|
+
|
|
150
|
+
player = MpvPlayer(audio_device=device)
|
|
151
|
+
device_label = device or "auto"
|
|
152
|
+
print(f"Playing via {device_label}...")
|
|
153
|
+
player.play(stream.url)
|
|
154
|
+
|
|
155
|
+
print("Verifying output...", end=" ", flush=True)
|
|
156
|
+
report = await check_bit_perfect(player, stream.sampling_rate, stream.bit_depth or 16)
|
|
157
|
+
print(report.summary())
|
|
158
|
+
|
|
159
|
+
if not report.bit_perfect and not report.error:
|
|
160
|
+
print(
|
|
161
|
+
"\nHint: for bit-perfect output on Linux use alsa/hw:CARD=<name>,DEV=0\n"
|
|
162
|
+
" on macOS use coreaudio/<device> (run: qobit set-device)",
|
|
163
|
+
file=sys.stderr,
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
print("\nPress Ctrl-C to stop.")
|
|
167
|
+
try:
|
|
168
|
+
while player.running:
|
|
169
|
+
time.sleep(0.5)
|
|
170
|
+
except KeyboardInterrupt:
|
|
171
|
+
pass
|
|
172
|
+
finally:
|
|
173
|
+
player.stop()
|
|
174
|
+
|
|
175
|
+
return 0
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def cmd_devices(_args: argparse.Namespace) -> int:
|
|
179
|
+
try:
|
|
180
|
+
devices = list_devices()
|
|
181
|
+
except RuntimeError as e:
|
|
182
|
+
print(e, file=sys.stderr)
|
|
183
|
+
return 1
|
|
184
|
+
|
|
185
|
+
if not devices:
|
|
186
|
+
print("No audio devices found.", file=sys.stderr)
|
|
187
|
+
return 1
|
|
188
|
+
|
|
189
|
+
current = get_audio_device()
|
|
190
|
+
print(f"\n{'DEVICE ID':<55} DESCRIPTION")
|
|
191
|
+
print("-" * 90)
|
|
192
|
+
for d in devices:
|
|
193
|
+
marker = " *" if d.id == current else ""
|
|
194
|
+
bp = " ♪" if d.bit_perfect else ""
|
|
195
|
+
print(f"{d.id:<55} {d.description}{bp}{marker}")
|
|
196
|
+
print()
|
|
197
|
+
if current:
|
|
198
|
+
print(f"Active: {current}")
|
|
199
|
+
else:
|
|
200
|
+
print("No device configured — run: qobit set-device")
|
|
201
|
+
return 0
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def cmd_set_device(_args: argparse.Namespace) -> int:
|
|
205
|
+
try:
|
|
206
|
+
devices = list_devices()
|
|
207
|
+
except RuntimeError as e:
|
|
208
|
+
print(e, file=sys.stderr)
|
|
209
|
+
return 1
|
|
210
|
+
|
|
211
|
+
if not devices:
|
|
212
|
+
print("No audio devices found.", file=sys.stderr)
|
|
213
|
+
return 1
|
|
214
|
+
|
|
215
|
+
current = get_audio_device()
|
|
216
|
+
print("\nAvailable audio devices (♪ = bit-perfect, recommended):\n")
|
|
217
|
+
for i, d in enumerate(devices):
|
|
218
|
+
marker = " (current)" if d.id == current else ""
|
|
219
|
+
bp = " ♪" if d.bit_perfect else " "
|
|
220
|
+
print(f" [{i:2}]{bp} {d.description:<45} {d.id}{marker}")
|
|
221
|
+
|
|
222
|
+
print()
|
|
223
|
+
raw = input("Select device number (Enter to cancel): ").strip()
|
|
224
|
+
if not raw:
|
|
225
|
+
return 0
|
|
226
|
+
try:
|
|
227
|
+
device = devices[int(raw)]
|
|
228
|
+
except (ValueError, IndexError):
|
|
229
|
+
print("Invalid selection.", file=sys.stderr)
|
|
230
|
+
return 1
|
|
231
|
+
|
|
232
|
+
set_audio_device(device.id)
|
|
233
|
+
print(f"\nSaved: {device.id}")
|
|
234
|
+
print("Tip: prefer alsa/hw:... (Linux) or coreaudio/... (macOS) for bit-perfect output.")
|
|
235
|
+
return 0
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _human_bytes(n: int) -> str:
|
|
239
|
+
size = float(n)
|
|
240
|
+
for unit in ("B", "KB", "MB", "GB"):
|
|
241
|
+
if size < 1024 or unit == "GB":
|
|
242
|
+
return f"{size:.0f} {unit}" if unit == "B" else f"{size:.1f} {unit}"
|
|
243
|
+
size /= 1024
|
|
244
|
+
return f"{size:.1f} GB"
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def cmd_clear_cache(_args: argparse.Namespace) -> int:
|
|
248
|
+
from .ui._images import clear_disk_cache
|
|
249
|
+
|
|
250
|
+
path, removed, freed = clear_disk_cache()
|
|
251
|
+
if path is None:
|
|
252
|
+
print("Cache directory unavailable — nothing to clear.", file=sys.stderr)
|
|
253
|
+
return 1
|
|
254
|
+
if removed == 0:
|
|
255
|
+
print(f"Cache already empty: {path}")
|
|
256
|
+
else:
|
|
257
|
+
print(f"Cleared {removed} cached image(s) ({_human_bytes(freed)}) from {path}")
|
|
258
|
+
return 0
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _account_line() -> str:
|
|
262
|
+
account = get_account()
|
|
263
|
+
name, plan = account.get("name", ""), account.get("plan", "")
|
|
264
|
+
if not name:
|
|
265
|
+
return "Logged in"
|
|
266
|
+
return f"Logged in as {name}" + (f" ({plan})" if plan else "")
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
async def cmd_auth(args: argparse.Namespace) -> int:
|
|
270
|
+
if args.action == "status":
|
|
271
|
+
return await cmd_auth_status()
|
|
272
|
+
async with QobuzClient() as client:
|
|
273
|
+
if not await _oauth_login(client):
|
|
274
|
+
return 1
|
|
275
|
+
print(f"{_account_line()}. Session saved.")
|
|
276
|
+
return 0
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
async def cmd_auth_status() -> int:
|
|
280
|
+
app_id, token, secrets = get_oauth_session()
|
|
281
|
+
where = token_location()
|
|
282
|
+
if where == "keyring" and not token:
|
|
283
|
+
print(
|
|
284
|
+
"The session is in the system keyring, which isn't reachable here (no "
|
|
285
|
+
"desktop session, or QOBIT_KEYRING=0). Run qobit from the desktop, or "
|
|
286
|
+
"log in here with: qobit auth"
|
|
287
|
+
)
|
|
288
|
+
return 1
|
|
289
|
+
if not (app_id and token):
|
|
290
|
+
print("Not logged in. Run: qobit auth")
|
|
291
|
+
return 1
|
|
292
|
+
stored = (
|
|
293
|
+
f"Token stored in {token_store.name()}."
|
|
294
|
+
if where == "keyring"
|
|
295
|
+
else f"Token stored in {CONFIG_FILE} (no system keyring available)."
|
|
296
|
+
)
|
|
297
|
+
async with QobuzClient() as client:
|
|
298
|
+
client.restore_session(app_id, token, secrets)
|
|
299
|
+
try:
|
|
300
|
+
await client.check_session()
|
|
301
|
+
except AuthExpiredError:
|
|
302
|
+
print("The saved session has expired. Run: qobit auth")
|
|
303
|
+
return 1
|
|
304
|
+
except QobuzError as e:
|
|
305
|
+
print(f"{_account_line()} (couldn't reach Qobuz to check: {e})")
|
|
306
|
+
print(stored)
|
|
307
|
+
return 2
|
|
308
|
+
print(f"{_account_line()}. The session works.")
|
|
309
|
+
print(stored)
|
|
310
|
+
return 0
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def _confirm(question: str) -> bool:
|
|
314
|
+
try:
|
|
315
|
+
return input(f"{question} [y/N] ").strip().lower() in ("y", "yes")
|
|
316
|
+
except EOFError:
|
|
317
|
+
return False
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def cmd_logout(args: argparse.Namespace) -> int:
|
|
321
|
+
if tui_running():
|
|
322
|
+
print(
|
|
323
|
+
"qobit is running: log out from it (^p → Log out of Qobuz), or quit it "
|
|
324
|
+
"first (it would write the queue back).",
|
|
325
|
+
file=sys.stderr,
|
|
326
|
+
)
|
|
327
|
+
return 1
|
|
328
|
+
if (
|
|
329
|
+
args.all
|
|
330
|
+
and not args.yes
|
|
331
|
+
and not _confirm(
|
|
332
|
+
"This also deletes qobit's settings (audio device, theme, volume). Continue?"
|
|
333
|
+
)
|
|
334
|
+
):
|
|
335
|
+
print("Nothing changed.")
|
|
336
|
+
return 1
|
|
337
|
+
removed = erase_account_data()
|
|
338
|
+
if args.all and erase_settings():
|
|
339
|
+
removed.append("the settings")
|
|
340
|
+
if not removed:
|
|
341
|
+
print("Not logged in, and nothing of a Qobuz account on this machine.")
|
|
342
|
+
else:
|
|
343
|
+
print("Logged out. Erased from this machine: " + ", ".join(removed) + ".")
|
|
344
|
+
return 0
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def main() -> None:
|
|
348
|
+
parser = argparse.ArgumentParser(
|
|
349
|
+
prog="qobit",
|
|
350
|
+
description="Bit-perfect Qobuz client",
|
|
351
|
+
)
|
|
352
|
+
parser.add_argument("--version", action="version", version=f"qobit {__version__}")
|
|
353
|
+
parser.add_argument(
|
|
354
|
+
"--connect-on",
|
|
355
|
+
action="store_true",
|
|
356
|
+
help="Enable Qobuz Connect for this run (qobit appears in the Qobuz apps' "
|
|
357
|
+
"device picker). Not saved — toggle it from the command palette to persist.",
|
|
358
|
+
)
|
|
359
|
+
sub = parser.add_subparsers(dest="command")
|
|
360
|
+
|
|
361
|
+
p_play = sub.add_parser("play", help="Search and play a track")
|
|
362
|
+
p_play.add_argument("query", help="Search query")
|
|
363
|
+
p_play.add_argument(
|
|
364
|
+
"--quality",
|
|
365
|
+
"-q",
|
|
366
|
+
choices=["FLAC_24_192", "FLAC_24_96", "FLAC_CD", "MP3_320"],
|
|
367
|
+
default="FLAC_24_192",
|
|
368
|
+
metavar="QUALITY",
|
|
369
|
+
help="Preferred quality: FLAC_24_192 (default), FLAC_24_96, FLAC_CD, MP3_320",
|
|
370
|
+
)
|
|
371
|
+
|
|
372
|
+
sub.add_parser("devices", help="List available audio output devices")
|
|
373
|
+
sub.add_parser("set-device", help="Interactively pick and save an audio device")
|
|
374
|
+
p_auth = sub.add_parser("auth", help="Log in to Qobuz (in the browser), or check the login")
|
|
375
|
+
p_auth.add_argument(
|
|
376
|
+
"action",
|
|
377
|
+
nargs="?",
|
|
378
|
+
choices=["login", "status"],
|
|
379
|
+
default="login",
|
|
380
|
+
help="login (default): log in in the browser; status: check the saved session",
|
|
381
|
+
)
|
|
382
|
+
p_logout = sub.add_parser(
|
|
383
|
+
"logout",
|
|
384
|
+
help="Log out and erase the account's traces here (session, queue, history, "
|
|
385
|
+
"mixes, cached covers); settings stay",
|
|
386
|
+
)
|
|
387
|
+
p_logout.add_argument(
|
|
388
|
+
"--all", action="store_true", help="Also delete qobit's settings: nothing of qobit left"
|
|
389
|
+
)
|
|
390
|
+
p_logout.add_argument("--yes", "-y", action="store_true", help="Don't ask (with --all)")
|
|
391
|
+
sub.add_parser("clear-cache", help="Delete cached cover art from disk")
|
|
392
|
+
|
|
393
|
+
args = parser.parse_args()
|
|
394
|
+
|
|
395
|
+
if purge_legacy_credentials():
|
|
396
|
+
print(
|
|
397
|
+
"Removed the Qobuz password an older qobit saved in config.json: "
|
|
398
|
+
"qobit logs in through the browser only (qobit auth).",
|
|
399
|
+
file=sys.stderr,
|
|
400
|
+
)
|
|
401
|
+
move_token_to_keyring() # a token still in config.json, now that a keyring is here
|
|
402
|
+
|
|
403
|
+
if args.command == "play":
|
|
404
|
+
sys.exit(asyncio.run(cmd_play(args)))
|
|
405
|
+
elif args.command == "devices":
|
|
406
|
+
sys.exit(cmd_devices(args))
|
|
407
|
+
elif args.command == "set-device":
|
|
408
|
+
sys.exit(cmd_set_device(args))
|
|
409
|
+
elif args.command == "auth":
|
|
410
|
+
sys.exit(asyncio.run(cmd_auth(args)))
|
|
411
|
+
elif args.command == "logout":
|
|
412
|
+
sys.exit(cmd_logout(args))
|
|
413
|
+
elif args.command == "clear-cache":
|
|
414
|
+
sys.exit(cmd_clear_cache(args))
|
|
415
|
+
else:
|
|
416
|
+
from .ui.app import QobitApp
|
|
417
|
+
|
|
418
|
+
QobitApp(connect=True if args.connect_on else None).run()
|
|
419
|
+
sys.exit(0)
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
if __name__ == "__main__":
|
|
423
|
+
main()
|
qobit/_fs.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Owner-only files and directories for qobit's own state.
|
|
2
|
+
|
|
3
|
+
config.json holds the Qobuz session token; DATA_DIR holds the mpv IPC socket
|
|
4
|
+
(mpv's `run` command executes programs) and the listening history. None of it
|
|
5
|
+
should depend on the user's umask, so qobit's directories are 0700 and its
|
|
6
|
+
files are created 0600 from the first byte (never written, then chmod-ed).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import contextlib
|
|
10
|
+
import os
|
|
11
|
+
import tempfile
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def private_dir(path: Path) -> Path:
|
|
16
|
+
"""Create ``path`` (and missing parents) and make the leaf 0700. Parents
|
|
17
|
+
are shared XDG directories (~/.config, ~/.local/share): left alone."""
|
|
18
|
+
path.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
19
|
+
with contextlib.suppress(OSError):
|
|
20
|
+
path.chmod(0o700) # tighten a directory an older qobit created 0755
|
|
21
|
+
return path
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def write_private(path: Path, text: str) -> None:
|
|
25
|
+
"""Atomically replace ``path`` with ``text``, mode 0600. The temp file is
|
|
26
|
+
created 0600 by mkstemp, so the content is never readable by others, not
|
|
27
|
+
even between the write and the rename, and a crash leaves no readable
|
|
28
|
+
copy behind under a predictable name."""
|
|
29
|
+
private_dir(path.parent)
|
|
30
|
+
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp")
|
|
31
|
+
try:
|
|
32
|
+
with os.fdopen(fd, "w") as fh:
|
|
33
|
+
fh.write(text)
|
|
34
|
+
os.replace(tmp, path)
|
|
35
|
+
except BaseException:
|
|
36
|
+
with contextlib.suppress(OSError):
|
|
37
|
+
os.unlink(tmp)
|
|
38
|
+
raise
|
qobit/account_data.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""What a Qobuz account leaves on this machine, and erasing it.
|
|
2
|
+
|
|
3
|
+
Logging out erases it all (a shared machine must not show the next person
|
|
4
|
+
the last one's listening): the session, the queue and its history, the last
|
|
5
|
+
track, the mixes, the cover-art cache. Settings stay (audio device, theme,
|
|
6
|
+
volume, the radio and Connect switches): they belong to the machine, not the
|
|
7
|
+
account. ``erase_settings`` removes those too (``qobit logout --all``).
|
|
8
|
+
|
|
9
|
+
A running TUI rewrites the queue within a second, so the CLI erases nothing
|
|
10
|
+
while one runs: every TUI holds a shared flock on ``DATA_DIR/qobit.lock`` for
|
|
11
|
+
its lifetime (``hold_running_lock``), and ``tui_running`` tries an exclusive
|
|
12
|
+
one. The OS drops the lock with the process, so a crash leaves none behind.
|
|
13
|
+
UI-agnostic: the TUI's own logout resets its memory, then calls in here.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import contextlib
|
|
17
|
+
import fcntl
|
|
18
|
+
from typing import IO
|
|
19
|
+
|
|
20
|
+
from . import config, store
|
|
21
|
+
|
|
22
|
+
# Every file in DATA_DIR that carries account activity.
|
|
23
|
+
ACCOUNT_FILES = ("queue_state.json", "player_state.json", "mixes_cache.json")
|
|
24
|
+
# The stream playlist (audio/player.py) holds a signed URL naming the
|
|
25
|
+
# account: normally removed when playback stops, erased here if left over.
|
|
26
|
+
_LEFTOVER_FILES = ("stream.m3u",)
|
|
27
|
+
# Empty marker/lock files and the mpv socket: no account data, removed only
|
|
28
|
+
# with the settings (nothing of qobit left).
|
|
29
|
+
_RUNTIME_FILES = ("qobit.lock", "connect.lock", "mpv.sock")
|
|
30
|
+
LOCK_FILE = "qobit.lock"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def hold_running_lock() -> IO[str] | None:
|
|
34
|
+
"""Mark this process as a running TUI (shared: several may run). Keep the
|
|
35
|
+
returned file open for the process's lifetime."""
|
|
36
|
+
try:
|
|
37
|
+
fh = open(store._path(LOCK_FILE), "a") # noqa: SIM115 — held open: the lock
|
|
38
|
+
fcntl.flock(fh, fcntl.LOCK_SH | fcntl.LOCK_NB)
|
|
39
|
+
except OSError:
|
|
40
|
+
return None
|
|
41
|
+
return fh
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def tui_running() -> bool:
|
|
45
|
+
"""Whether a qobit TUI is running on this machine (as this user)."""
|
|
46
|
+
path = store.DATA_DIR / LOCK_FILE
|
|
47
|
+
if not path.exists():
|
|
48
|
+
return False
|
|
49
|
+
try:
|
|
50
|
+
with open(path, "a") as fh:
|
|
51
|
+
fcntl.flock(fh, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
52
|
+
fcntl.flock(fh, fcntl.LOCK_UN)
|
|
53
|
+
except OSError:
|
|
54
|
+
return True
|
|
55
|
+
return False
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def erase_account_data() -> list[str]:
|
|
59
|
+
"""Forget the session and delete every account trace on disk. Returns
|
|
60
|
+
what was removed, as phrases for a summary line."""
|
|
61
|
+
from .ui._images import clear_disk_cache
|
|
62
|
+
|
|
63
|
+
removed: list[str] = []
|
|
64
|
+
if config.clear_oauth_session():
|
|
65
|
+
removed.append("the saved session")
|
|
66
|
+
names = {
|
|
67
|
+
"queue_state.json": "the queue and its history",
|
|
68
|
+
"player_state.json": "the last track",
|
|
69
|
+
"mixes_cache.json": "the mixes",
|
|
70
|
+
}
|
|
71
|
+
for name in ACCOUNT_FILES:
|
|
72
|
+
path = store.DATA_DIR / name
|
|
73
|
+
if path.exists():
|
|
74
|
+
with contextlib.suppress(FileNotFoundError):
|
|
75
|
+
path.unlink()
|
|
76
|
+
removed.append(names[name])
|
|
77
|
+
for name in _LEFTOVER_FILES:
|
|
78
|
+
with contextlib.suppress(FileNotFoundError):
|
|
79
|
+
(store.DATA_DIR / name).unlink()
|
|
80
|
+
_, covers, _ = clear_disk_cache()
|
|
81
|
+
if covers:
|
|
82
|
+
removed.append(f"{covers} cached cover{'s' if covers != 1 else ''}")
|
|
83
|
+
return removed
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def erase_settings() -> bool:
|
|
87
|
+
"""Delete config.json and qobit's runtime files, then its directories if
|
|
88
|
+
empty: nothing of qobit left. Call after ``erase_account_data``."""
|
|
89
|
+
from .ui._images import _cache_dir
|
|
90
|
+
|
|
91
|
+
existed = config.CONFIG_FILE.exists()
|
|
92
|
+
with contextlib.suppress(FileNotFoundError):
|
|
93
|
+
config.CONFIG_FILE.unlink()
|
|
94
|
+
for name in _RUNTIME_FILES:
|
|
95
|
+
with contextlib.suppress(FileNotFoundError):
|
|
96
|
+
(store.DATA_DIR / name).unlink()
|
|
97
|
+
cache = _cache_dir()
|
|
98
|
+
for directory in (config.CONFIG_DIR, store.DATA_DIR, cache, cache and cache.parent):
|
|
99
|
+
if directory is not None:
|
|
100
|
+
with contextlib.suppress(OSError):
|
|
101
|
+
directory.rmdir() # only if empty: never anything we didn't write
|
|
102
|
+
return existed
|
qobit/audio/__init__.py
ADDED
|
File without changes
|
qobit/audio/device.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import re
|
|
2
|
+
import subprocess
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@dataclass
|
|
7
|
+
class DeviceInfo:
|
|
8
|
+
id: str
|
|
9
|
+
description: str
|
|
10
|
+
bit_perfect: bool = False
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def list_devices() -> list[DeviceInfo]:
|
|
14
|
+
"""Return audio output devices available to mpv.
|
|
15
|
+
|
|
16
|
+
mpv --audio-device=help prints lines like:
|
|
17
|
+
'alsa/front:CARD=DAC,DEV=0' (USB DAC)
|
|
18
|
+
'pipewire/alsa_output...' (USB DAC)
|
|
19
|
+
'coreaudio/AppleUSBAudioEngine:...' (USB DAC)
|
|
20
|
+
We parse those and return them as-is so callers can pass the id straight
|
|
21
|
+
back to mpv via --audio-device=<id>.
|
|
22
|
+
|
|
23
|
+
On Linux we additionally **synthesize a raw `alsa/hw:CARD=...,DEV=...`
|
|
24
|
+
entry** for every ALSA card mpv reports. mpv never lists the raw `hw:`
|
|
25
|
+
PCM (only `sysdefault`/`front`/`surround`/`iec958` wrappers), yet `hw:` is
|
|
26
|
+
the only device that bypasses PipeWire/PulseAudio and the ALSA `plug`/`dmix`
|
|
27
|
+
resamplers — i.e. the only bit-perfect path. Those synthesized entries are
|
|
28
|
+
flagged `bit_perfect=True` and sorted to the top so the picker offers them
|
|
29
|
+
first. `coreaudio/...` devices are flagged bit-perfect on macOS for the
|
|
30
|
+
same reason (exclusive-mode capable, no system mixer).
|
|
31
|
+
"""
|
|
32
|
+
try:
|
|
33
|
+
result = subprocess.run(
|
|
34
|
+
["mpv", "--audio-device=help"],
|
|
35
|
+
capture_output=True,
|
|
36
|
+
text=True,
|
|
37
|
+
timeout=5,
|
|
38
|
+
)
|
|
39
|
+
output = result.stdout + result.stderr
|
|
40
|
+
except FileNotFoundError:
|
|
41
|
+
raise RuntimeError("mpv not found — install mpv and ensure it is in $PATH") from None
|
|
42
|
+
except subprocess.TimeoutExpired:
|
|
43
|
+
return []
|
|
44
|
+
|
|
45
|
+
devices: list[DeviceInfo] = []
|
|
46
|
+
# (CARD, DEV) -> human description, collected from the ALSA wrapper PCMs so
|
|
47
|
+
# we can synthesize the raw hw: device that mpv itself never lists.
|
|
48
|
+
alsa_cards: dict[tuple[str, str], str] = {}
|
|
49
|
+
|
|
50
|
+
for line in output.splitlines():
|
|
51
|
+
m = re.match(r"\s+'([^']+)'\s+\((.+)\)\s*$", line)
|
|
52
|
+
if not m:
|
|
53
|
+
continue
|
|
54
|
+
device_id = m.group(1)
|
|
55
|
+
description = m.group(2)
|
|
56
|
+
if device_id == "auto":
|
|
57
|
+
continue
|
|
58
|
+
devices.append(
|
|
59
|
+
DeviceInfo(
|
|
60
|
+
id=device_id,
|
|
61
|
+
description=description,
|
|
62
|
+
bit_perfect=device_id.startswith("coreaudio/"),
|
|
63
|
+
)
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
if device_id.startswith("alsa/"):
|
|
67
|
+
card = re.search(r"CARD=([^,]+)", device_id)
|
|
68
|
+
if card:
|
|
69
|
+
dev = re.search(r"DEV=(\d+)", device_id)
|
|
70
|
+
key = (card.group(1), dev.group(1) if dev else "0")
|
|
71
|
+
# Strip the trailing "/<pcm-name>" qualifier mpv appends to the
|
|
72
|
+
# description (e.g. ".../Front output") for a cleaner card name.
|
|
73
|
+
alsa_cards.setdefault(key, description.split("/")[0].strip())
|
|
74
|
+
|
|
75
|
+
synthesized: list[DeviceInfo] = []
|
|
76
|
+
for (card, dev), desc in alsa_cards.items():
|
|
77
|
+
hw_id = f"alsa/hw:CARD={card},DEV={dev}"
|
|
78
|
+
if any(d.id == hw_id for d in devices):
|
|
79
|
+
continue
|
|
80
|
+
synthesized.append(
|
|
81
|
+
DeviceInfo(id=hw_id, description=f"{desc} — bit-perfect (direct hw)", bit_perfect=True)
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
# Bit-perfect devices first, preserving discovery order within each group.
|
|
85
|
+
return synthesized + devices
|