sonosify 0.1.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.
- sonosify/__init__.py +67 -0
- sonosify/_parsing.py +22 -0
- sonosify/cli.py +645 -0
- sonosify/client.py +373 -0
- sonosify/controller.py +85 -0
- sonosify/didl.py +89 -0
- sonosify/discovery.py +192 -0
- sonosify/errors.py +31 -0
- sonosify/events.py +350 -0
- sonosify/models.py +57 -0
- sonosify/soap.py +104 -0
- sonosify/spotify.py +61 -0
- sonosify/topology.py +69 -0
- sonosify-0.1.0.dist-info/METADATA +170 -0
- sonosify-0.1.0.dist-info/RECORD +17 -0
- sonosify-0.1.0.dist-info/WHEEL +4 -0
- sonosify-0.1.0.dist-info/entry_points.txt +2 -0
sonosify/cli.py
ADDED
|
@@ -0,0 +1,645 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import json
|
|
3
|
+
import logging
|
|
4
|
+
from collections.abc import Awaitable, Callable
|
|
5
|
+
from enum import StrEnum
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Annotated
|
|
8
|
+
|
|
9
|
+
try:
|
|
10
|
+
import typer
|
|
11
|
+
from rich.console import Console
|
|
12
|
+
from rich.table import Table
|
|
13
|
+
except ModuleNotFoundError as exc: # pragma: no cover - import guard
|
|
14
|
+
raise SystemExit(
|
|
15
|
+
"The sonosify CLI requires the optional 'cli' dependencies. "
|
|
16
|
+
"Install them with: pip install 'sonosify[cli]'"
|
|
17
|
+
) from exc
|
|
18
|
+
|
|
19
|
+
from sonosify import (
|
|
20
|
+
AVTransportEvent,
|
|
21
|
+
RenderingControlEvent,
|
|
22
|
+
SonosClient,
|
|
23
|
+
SonosController,
|
|
24
|
+
SonosSystem,
|
|
25
|
+
)
|
|
26
|
+
from sonosify.client import DEFAULT_TIMEOUT
|
|
27
|
+
from sonosify.errors import SonosifyError
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class OutputFormat(StrEnum):
|
|
31
|
+
PLAIN = "plain"
|
|
32
|
+
JSON = "json"
|
|
33
|
+
TSV = "tsv"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class _State:
|
|
37
|
+
format: OutputFormat = OutputFormat.PLAIN
|
|
38
|
+
debug: bool = False
|
|
39
|
+
timeout: float = DEFAULT_TIMEOUT
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
state = _State()
|
|
43
|
+
|
|
44
|
+
CONFIG_PATH = Path(typer.get_app_dir("sonosify")) / "config.json"
|
|
45
|
+
|
|
46
|
+
app = typer.Typer(
|
|
47
|
+
name="sonosify",
|
|
48
|
+
help="Discover and control Sonos speakers from the command line.",
|
|
49
|
+
no_args_is_help=True,
|
|
50
|
+
add_completion=False,
|
|
51
|
+
)
|
|
52
|
+
favorites_app = typer.Typer(help="List and play Sonos favorites.", no_args_is_help=True)
|
|
53
|
+
config_app = typer.Typer(help="Manage local CLI defaults (e.g. the default speaker).")
|
|
54
|
+
app.add_typer(favorites_app, name="favorites")
|
|
55
|
+
app.add_typer(config_app, name="config")
|
|
56
|
+
|
|
57
|
+
console = Console()
|
|
58
|
+
err_console = Console(stderr=True, style="bold red")
|
|
59
|
+
|
|
60
|
+
RoomArg = Annotated[
|
|
61
|
+
str | None,
|
|
62
|
+
typer.Argument(
|
|
63
|
+
help="Room name (or a unique substring). Falls back to the configured default speaker.",
|
|
64
|
+
),
|
|
65
|
+
]
|
|
66
|
+
IpOpt = Annotated[
|
|
67
|
+
str | None,
|
|
68
|
+
typer.Option("--ip", help="Target a speaker by IP address instead of room name."),
|
|
69
|
+
]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
# --------------------------------------------------------------------------- config
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def load_config() -> dict[str, object]:
|
|
76
|
+
try:
|
|
77
|
+
return json.loads(CONFIG_PATH.read_text(encoding="utf-8")) # type: ignore[return-value]
|
|
78
|
+
except OSError, json.JSONDecodeError:
|
|
79
|
+
return {}
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def save_config(config: dict[str, object]) -> None:
|
|
83
|
+
CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)
|
|
84
|
+
CONFIG_PATH.write_text(json.dumps(config, indent=2), encoding="utf-8")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _resolve_target(room: str | None, ip: str | None) -> tuple[str | None, str | None]:
|
|
88
|
+
"""Apply the configured default speaker when no explicit target is given."""
|
|
89
|
+
if room or ip:
|
|
90
|
+
return room, ip
|
|
91
|
+
config = load_config()
|
|
92
|
+
return config.get("default_room") or None, config.get("default_ip") or None # type: ignore[return-value]
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
# --------------------------------------------------------------------------- output
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _print_action(message: str, data: dict[str, object]) -> None:
|
|
99
|
+
match state.format:
|
|
100
|
+
case OutputFormat.JSON:
|
|
101
|
+
typer.echo(json.dumps(data))
|
|
102
|
+
case OutputFormat.TSV:
|
|
103
|
+
typer.echo("\t".join(str(value) for value in data.values()))
|
|
104
|
+
case _:
|
|
105
|
+
console.print(message)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _print_object(data: dict[str, object], plain: Callable[[], None]) -> None:
|
|
109
|
+
match state.format:
|
|
110
|
+
case OutputFormat.JSON:
|
|
111
|
+
typer.echo(json.dumps(data))
|
|
112
|
+
case OutputFormat.TSV:
|
|
113
|
+
for key, value in data.items():
|
|
114
|
+
typer.echo(f"{key}\t{value}")
|
|
115
|
+
case _:
|
|
116
|
+
plain()
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _print_records(
|
|
120
|
+
records: list[dict[str, object]],
|
|
121
|
+
headers: list[str],
|
|
122
|
+
plain: Callable[[], None],
|
|
123
|
+
) -> None:
|
|
124
|
+
match state.format:
|
|
125
|
+
case OutputFormat.JSON:
|
|
126
|
+
typer.echo(json.dumps(records))
|
|
127
|
+
case OutputFormat.TSV:
|
|
128
|
+
typer.echo("\t".join(headers))
|
|
129
|
+
for record in records:
|
|
130
|
+
typer.echo("\t".join(str(record.get(h, "")) for h in headers))
|
|
131
|
+
case _:
|
|
132
|
+
plain()
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
# --------------------------------------------------------------------------- runtime
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _run[T](coro: Awaitable[T]) -> T:
|
|
139
|
+
"""Run an async coroutine, turning library errors into clean CLI failures."""
|
|
140
|
+
try:
|
|
141
|
+
return asyncio.run(coro)
|
|
142
|
+
except SonosifyError as exc:
|
|
143
|
+
err_console.print(f"error: {exc}")
|
|
144
|
+
raise typer.Exit(code=1) from exc
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
async def _with_client[T](
|
|
148
|
+
room: str | None,
|
|
149
|
+
ip: str | None,
|
|
150
|
+
func: Callable[[SonosClient], Awaitable[T]],
|
|
151
|
+
*,
|
|
152
|
+
coordinator: bool = True,
|
|
153
|
+
) -> T:
|
|
154
|
+
room, ip = _resolve_target(room, ip)
|
|
155
|
+
controller = SonosController(timeout=state.timeout)
|
|
156
|
+
async with await controller.client(room, ip=ip, coordinator=coordinator) as client:
|
|
157
|
+
return await func(client)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
@app.callback()
|
|
161
|
+
def main(
|
|
162
|
+
output_format: Annotated[
|
|
163
|
+
OutputFormat | None,
|
|
164
|
+
typer.Option("--format", help="Output format for machine-readable scripting."),
|
|
165
|
+
] = None,
|
|
166
|
+
timeout: Annotated[
|
|
167
|
+
float | None,
|
|
168
|
+
typer.Option("--timeout", help="SOAP / discovery timeout in seconds."),
|
|
169
|
+
] = None,
|
|
170
|
+
debug: Annotated[
|
|
171
|
+
bool, typer.Option("--debug", help="Print SOAP request/response traces to stderr.")
|
|
172
|
+
] = False,
|
|
173
|
+
) -> None:
|
|
174
|
+
"""Discover and control Sonos speakers from the command line."""
|
|
175
|
+
config = load_config()
|
|
176
|
+
state.format = output_format or OutputFormat(config.get("default_format", OutputFormat.PLAIN))
|
|
177
|
+
state.timeout = (
|
|
178
|
+
timeout if timeout is not None else float(config.get("default_timeout", DEFAULT_TIMEOUT))
|
|
179
|
+
)
|
|
180
|
+
state.debug = debug
|
|
181
|
+
if debug:
|
|
182
|
+
handler = logging.StreamHandler()
|
|
183
|
+
handler.setFormatter(logging.Formatter("%(name)s %(message)s"))
|
|
184
|
+
sonos_logger = logging.getLogger("sonosify")
|
|
185
|
+
sonos_logger.setLevel(logging.DEBUG)
|
|
186
|
+
sonos_logger.addHandler(handler)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
# --------------------------------------------------------------------------- discovery
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
@app.command()
|
|
193
|
+
def discover() -> None:
|
|
194
|
+
"""List every Sonos speaker discovered on the local network."""
|
|
195
|
+
system: SonosSystem = _run(SonosController(timeout=state.timeout).discover())
|
|
196
|
+
speakers = sorted(system.speakers, key=lambda s: s.room_name.casefold())
|
|
197
|
+
records: list[dict[str, object]] = [
|
|
198
|
+
{
|
|
199
|
+
"room": speaker.room_name or "?",
|
|
200
|
+
"ip": speaker.ip,
|
|
201
|
+
"uid": speaker.uid,
|
|
202
|
+
"coordinator": speaker.is_coordinator,
|
|
203
|
+
}
|
|
204
|
+
for speaker in speakers
|
|
205
|
+
]
|
|
206
|
+
|
|
207
|
+
def plain() -> None:
|
|
208
|
+
if not records:
|
|
209
|
+
console.print("No Sonos speakers found.")
|
|
210
|
+
return
|
|
211
|
+
table = Table(title="Sonos speakers")
|
|
212
|
+
table.add_column("Room", style="cyan", no_wrap=True)
|
|
213
|
+
table.add_column("IP", style="green")
|
|
214
|
+
table.add_column("UID", style="dim")
|
|
215
|
+
table.add_column("Coordinator", justify="center")
|
|
216
|
+
for record in records:
|
|
217
|
+
table.add_row(
|
|
218
|
+
str(record["room"]),
|
|
219
|
+
str(record["ip"]),
|
|
220
|
+
str(record["uid"]),
|
|
221
|
+
"yes" if record["coordinator"] else "",
|
|
222
|
+
)
|
|
223
|
+
console.print(table)
|
|
224
|
+
|
|
225
|
+
_print_records(records, ["room", "ip", "uid", "coordinator"], plain)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
@app.command(name="now-playing")
|
|
229
|
+
def now_playing(room: RoomArg = None, ip: IpOpt = None) -> None:
|
|
230
|
+
"""Show what is currently playing on a speaker."""
|
|
231
|
+
playback = _run(_with_client(room, ip, lambda c: c.now_playing()))
|
|
232
|
+
track = playback.track
|
|
233
|
+
data: dict[str, object] = {
|
|
234
|
+
"state": playback.state or "UNKNOWN",
|
|
235
|
+
"title": track.title if track else "",
|
|
236
|
+
"artist": track.creator if track else "",
|
|
237
|
+
"album": track.album if track else "",
|
|
238
|
+
"position": playback.relative_time,
|
|
239
|
+
"duration": playback.track_duration or (track.duration if track else ""),
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
def plain() -> None:
|
|
243
|
+
console.print(f"state: [cyan]{data['state']}[/]")
|
|
244
|
+
if track and track.title:
|
|
245
|
+
console.print(f"title: {track.title}")
|
|
246
|
+
if track.creator:
|
|
247
|
+
console.print(f"artist: {track.creator}")
|
|
248
|
+
if track.album:
|
|
249
|
+
console.print(f"album: {track.album}")
|
|
250
|
+
console.print(f"position: {data['position'] or '?'} / {data['duration'] or '?'}")
|
|
251
|
+
else:
|
|
252
|
+
console.print("[dim]nothing playing[/]")
|
|
253
|
+
|
|
254
|
+
_print_object(data, plain)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
@app.command()
|
|
258
|
+
def watch(room: RoomArg = None, ip: IpOpt = None) -> None:
|
|
259
|
+
"""Stream live transport and volume events from a speaker."""
|
|
260
|
+
|
|
261
|
+
async def stream() -> None:
|
|
262
|
+
target_room, target_ip = _resolve_target(room, ip)
|
|
263
|
+
controller = SonosController(timeout=state.timeout)
|
|
264
|
+
async with controller.watch(target_room, ip=target_ip) as watcher:
|
|
265
|
+
console.print(f"watching [cyan]{watcher.ip}[/]; press Ctrl+C to stop")
|
|
266
|
+
async for event in watcher:
|
|
267
|
+
match event:
|
|
268
|
+
case AVTransportEvent(transport_state=transport_state, track=track):
|
|
269
|
+
title = track.title if track else ""
|
|
270
|
+
console.print(f"transport {transport_state} {title}")
|
|
271
|
+
case RenderingControlEvent(volume=volume, muted=muted):
|
|
272
|
+
console.print(f"rendering volume={volume} muted={muted}")
|
|
273
|
+
case _:
|
|
274
|
+
console.print(f"{event.service} {event.values}")
|
|
275
|
+
|
|
276
|
+
try:
|
|
277
|
+
_run(stream())
|
|
278
|
+
except KeyboardInterrupt:
|
|
279
|
+
console.print("\nstopped watching")
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
# --------------------------------------------------------------------------- playback
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
@app.command()
|
|
286
|
+
def play(
|
|
287
|
+
target: Annotated[
|
|
288
|
+
str | None,
|
|
289
|
+
typer.Argument(help="Room name. Falls back to the configured default speaker."),
|
|
290
|
+
] = None,
|
|
291
|
+
ip: IpOpt = None,
|
|
292
|
+
) -> None:
|
|
293
|
+
"""Resume playback on a speaker."""
|
|
294
|
+
_run(_with_client(target, ip, lambda c: c.play()))
|
|
295
|
+
_print_action("[green]playing[/]", {"status": "playing"})
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
@app.command()
|
|
299
|
+
def pause(room: RoomArg = None, ip: IpOpt = None) -> None:
|
|
300
|
+
"""Pause playback on a speaker."""
|
|
301
|
+
_run(_with_client(room, ip, lambda c: c.pause()))
|
|
302
|
+
_print_action("[yellow]paused[/]", {"status": "paused"})
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
@app.command()
|
|
306
|
+
def stop(room: RoomArg = None, ip: IpOpt = None) -> None:
|
|
307
|
+
"""Stop playback on a speaker."""
|
|
308
|
+
_run(_with_client(room, ip, lambda c: c.stop()))
|
|
309
|
+
_print_action("[yellow]stopped[/]", {"status": "stopped"})
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
@app.command()
|
|
313
|
+
def next(room: RoomArg = None, ip: IpOpt = None) -> None:
|
|
314
|
+
"""Skip to the next track."""
|
|
315
|
+
_run(_with_client(room, ip, lambda c: c.next()))
|
|
316
|
+
_print_action("[green]next[/]", {"status": "next"})
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
@app.command()
|
|
320
|
+
def previous(room: RoomArg = None, ip: IpOpt = None) -> None:
|
|
321
|
+
"""Skip to the previous track."""
|
|
322
|
+
_run(_with_client(room, ip, lambda c: c.previous()))
|
|
323
|
+
_print_action("[green]previous[/]", {"status": "previous"})
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
# --------------------------------------------------------------------------- volume & mute
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
@app.command()
|
|
330
|
+
def volume(
|
|
331
|
+
target: Annotated[
|
|
332
|
+
str | None,
|
|
333
|
+
typer.Argument(
|
|
334
|
+
help=(
|
|
335
|
+
"Room name, or target volume when using the configured default speaker. "
|
|
336
|
+
"Omit to read the current volume."
|
|
337
|
+
),
|
|
338
|
+
),
|
|
339
|
+
] = None,
|
|
340
|
+
level: Annotated[
|
|
341
|
+
int | None, typer.Argument(help="Target volume (0-100). Omit to read the current volume.")
|
|
342
|
+
] = None,
|
|
343
|
+
ip: IpOpt = None,
|
|
344
|
+
) -> None:
|
|
345
|
+
"""Get or set a speaker's volume."""
|
|
346
|
+
room = target
|
|
347
|
+
if level is None and target is not None:
|
|
348
|
+
try:
|
|
349
|
+
level = int(target)
|
|
350
|
+
room = None
|
|
351
|
+
except ValueError:
|
|
352
|
+
pass
|
|
353
|
+
|
|
354
|
+
if level is None:
|
|
355
|
+
current = _run(_with_client(room, ip, lambda c: c.get_volume(), coordinator=False))
|
|
356
|
+
_print_object({"volume": current}, lambda: console.print(f"volume: [cyan]{current}[/]"))
|
|
357
|
+
else:
|
|
358
|
+
_run(_with_client(room, ip, lambda c: c.set_volume(level), coordinator=False))
|
|
359
|
+
clamped = max(0, min(100, level))
|
|
360
|
+
_print_action(f"volume set to [cyan]{clamped}[/]", {"volume": clamped})
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
async def _adjust_volume(client: SonosClient, delta: int) -> int:
|
|
364
|
+
new_level = max(0, min(100, await client.get_volume() + delta))
|
|
365
|
+
await client.set_volume(new_level)
|
|
366
|
+
return new_level
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
@app.command(name="volume-up")
|
|
370
|
+
def volume_up(
|
|
371
|
+
room: RoomArg = None,
|
|
372
|
+
amount: Annotated[int, typer.Argument(help="Percentage points to raise the volume by.")] = 5,
|
|
373
|
+
ip: IpOpt = None,
|
|
374
|
+
) -> None:
|
|
375
|
+
"""Raise a speaker's volume by a number of percentage points."""
|
|
376
|
+
new_level = _run(_with_client(room, ip, lambda c: _adjust_volume(c, amount), coordinator=False))
|
|
377
|
+
_print_action(f"volume [green]{new_level}[/]", {"volume": new_level})
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
@app.command(name="volume-down")
|
|
381
|
+
def volume_down(
|
|
382
|
+
room: RoomArg = None,
|
|
383
|
+
amount: Annotated[int, typer.Argument(help="Percentage points to lower the volume by.")] = 5,
|
|
384
|
+
ip: IpOpt = None,
|
|
385
|
+
) -> None:
|
|
386
|
+
"""Lower a speaker's volume by a number of percentage points."""
|
|
387
|
+
new_level = _run(
|
|
388
|
+
_with_client(room, ip, lambda c: _adjust_volume(c, -amount), coordinator=False)
|
|
389
|
+
)
|
|
390
|
+
_print_action(f"volume [yellow]{new_level}[/]", {"volume": new_level})
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
@app.command()
|
|
394
|
+
def mute(
|
|
395
|
+
room: RoomArg = None,
|
|
396
|
+
on: Annotated[
|
|
397
|
+
bool | None,
|
|
398
|
+
typer.Option("--on/--off", help="Force mute on or off. Omit to toggle."),
|
|
399
|
+
] = None,
|
|
400
|
+
ip: IpOpt = None,
|
|
401
|
+
) -> None:
|
|
402
|
+
"""Mute, unmute, or toggle mute on a speaker."""
|
|
403
|
+
|
|
404
|
+
async def action(client: SonosClient) -> bool:
|
|
405
|
+
if on is None:
|
|
406
|
+
return await client.toggle_mute()
|
|
407
|
+
await client.set_mute(on)
|
|
408
|
+
return on
|
|
409
|
+
|
|
410
|
+
muted = _run(_with_client(room, ip, action, coordinator=False))
|
|
411
|
+
_print_action(
|
|
412
|
+
"[yellow]muted[/]" if muted else "[green]unmuted[/]",
|
|
413
|
+
{"muted": muted},
|
|
414
|
+
)
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
# --------------------------------------------------------------------------- queue
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
@app.command()
|
|
421
|
+
def queue(room: RoomArg = None, ip: IpOpt = None) -> None:
|
|
422
|
+
"""Show the playback queue of a speaker."""
|
|
423
|
+
tracks = _run(_with_client(room, ip, lambda c: c.queue()))
|
|
424
|
+
records: list[dict[str, object]] = [
|
|
425
|
+
{"position": track.position or "", "title": track.title or track.uri} for track in tracks
|
|
426
|
+
]
|
|
427
|
+
|
|
428
|
+
def plain() -> None:
|
|
429
|
+
if not records:
|
|
430
|
+
console.print("[dim]queue is empty[/]")
|
|
431
|
+
return
|
|
432
|
+
table = Table(title="Queue")
|
|
433
|
+
table.add_column("#", justify="right", style="dim")
|
|
434
|
+
table.add_column("Title", style="cyan")
|
|
435
|
+
for record in records:
|
|
436
|
+
table.add_row(str(record["position"]), str(record["title"]))
|
|
437
|
+
console.print(table)
|
|
438
|
+
|
|
439
|
+
_print_records(records, ["position", "title"], plain)
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
@app.command()
|
|
443
|
+
def enqueue(
|
|
444
|
+
uri: Annotated[str, typer.Argument(help="URI to add to the Sonos queue.")],
|
|
445
|
+
room: Annotated[
|
|
446
|
+
str | None,
|
|
447
|
+
typer.Option("--room", "-r", help="Target room (falls back to the default speaker)."),
|
|
448
|
+
] = None,
|
|
449
|
+
ip: IpOpt = None,
|
|
450
|
+
play_next: Annotated[
|
|
451
|
+
bool, typer.Option("--next/--queue", help="Enqueue as the next track instead of last.")
|
|
452
|
+
] = False,
|
|
453
|
+
play_now: Annotated[
|
|
454
|
+
bool, typer.Option("--play", help="Start playback at the enqueued queue position.")
|
|
455
|
+
] = False,
|
|
456
|
+
) -> None:
|
|
457
|
+
"""Add a URI to the speaker queue."""
|
|
458
|
+
position = _run(
|
|
459
|
+
_with_client(room, ip, lambda c: c.enqueue_uri(uri, next_=play_next, play=play_now))
|
|
460
|
+
)
|
|
461
|
+
status = "playing" if play_now else "enqueued"
|
|
462
|
+
_print_action(
|
|
463
|
+
f"[green]{status}[/] {uri}",
|
|
464
|
+
{"status": status, "uri": uri, "position": position or ""},
|
|
465
|
+
)
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
# --------------------------------------------------------------------------- favorites
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
@favorites_app.command("list")
|
|
472
|
+
def favorites_list(room: RoomArg = None, ip: IpOpt = None) -> None:
|
|
473
|
+
"""List the Sonos favorites available to a speaker."""
|
|
474
|
+
favorites = _run(_with_client(room, ip, lambda c: c.favorites()))
|
|
475
|
+
records: list[dict[str, object]] = [
|
|
476
|
+
{"index": index, "title": favorite.title}
|
|
477
|
+
for index, favorite in enumerate(favorites, start=1)
|
|
478
|
+
]
|
|
479
|
+
|
|
480
|
+
def plain() -> None:
|
|
481
|
+
if not records:
|
|
482
|
+
console.print("[dim]no favorites[/]")
|
|
483
|
+
return
|
|
484
|
+
table = Table(title="Favorites")
|
|
485
|
+
table.add_column("#", justify="right", style="dim")
|
|
486
|
+
table.add_column("Title", style="cyan")
|
|
487
|
+
for record in records:
|
|
488
|
+
table.add_row(str(record["index"]), str(record["title"]))
|
|
489
|
+
console.print(table)
|
|
490
|
+
|
|
491
|
+
_print_records(records, ["index", "title"], plain)
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
@favorites_app.command("play")
|
|
495
|
+
def favorites_play(
|
|
496
|
+
name: Annotated[str, typer.Argument(help="Favorite title (or a unique substring).")],
|
|
497
|
+
room: RoomArg = None,
|
|
498
|
+
ip: IpOpt = None,
|
|
499
|
+
) -> None:
|
|
500
|
+
"""Play a favorite by name on a speaker."""
|
|
501
|
+
|
|
502
|
+
async def action(client: SonosClient) -> str:
|
|
503
|
+
favorites = await client.favorites()
|
|
504
|
+
needle = name.casefold()
|
|
505
|
+
matches = [f for f in favorites if needle in f.title.casefold()]
|
|
506
|
+
if not matches:
|
|
507
|
+
raise SonosifyError(f"no favorite matching {name!r}")
|
|
508
|
+
if len(matches) > 1:
|
|
509
|
+
titles = ", ".join(f.title for f in matches)
|
|
510
|
+
raise SonosifyError(f"ambiguous favorite {name!r}; matches: {titles}")
|
|
511
|
+
await client.open_favorite(matches[0])
|
|
512
|
+
return matches[0].title
|
|
513
|
+
|
|
514
|
+
title = _run(_with_client(room, ip, action))
|
|
515
|
+
_print_action(f"[green]playing favorite[/] {title}", {"status": "playing", "favorite": title})
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
# --------------------------------------------------------------------------- open / track
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
@app.command()
|
|
522
|
+
def open(
|
|
523
|
+
value: Annotated[str, typer.Argument(help="Stream URL or playable Sonos URI.")],
|
|
524
|
+
room: Annotated[
|
|
525
|
+
str | None,
|
|
526
|
+
typer.Option("--room", "-r", help="Target room (falls back to the default speaker)."),
|
|
527
|
+
] = None,
|
|
528
|
+
ip: IpOpt = None,
|
|
529
|
+
title: Annotated[
|
|
530
|
+
str, typer.Option("--title", help="Display title for stream/radio URIs.")
|
|
531
|
+
] = "",
|
|
532
|
+
radio: Annotated[
|
|
533
|
+
bool, typer.Option("--radio", help="Send radio metadata for stream URLs.")
|
|
534
|
+
] = False,
|
|
535
|
+
) -> None:
|
|
536
|
+
"""Open a supported value and start playback."""
|
|
537
|
+
position = _run(
|
|
538
|
+
_with_client(
|
|
539
|
+
room,
|
|
540
|
+
ip,
|
|
541
|
+
lambda c: c.open(value, title=title, radio=radio),
|
|
542
|
+
)
|
|
543
|
+
)
|
|
544
|
+
_print_action(
|
|
545
|
+
f"[green]opened[/] {value}",
|
|
546
|
+
{"status": "opened", "value": value, "position": position or ""},
|
|
547
|
+
)
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
@app.command()
|
|
551
|
+
def track(
|
|
552
|
+
track_id: Annotated[str, typer.Argument(help="Track id, track URI, or track URL.")],
|
|
553
|
+
room: Annotated[
|
|
554
|
+
str | None,
|
|
555
|
+
typer.Option("--room", "-r", help="Target room (falls back to the default speaker)."),
|
|
556
|
+
] = None,
|
|
557
|
+
ip: IpOpt = None,
|
|
558
|
+
play_next: Annotated[
|
|
559
|
+
bool, typer.Option("--next", help="Enqueue as the next track instead of last.")
|
|
560
|
+
] = False,
|
|
561
|
+
enqueue_only: Annotated[
|
|
562
|
+
bool,
|
|
563
|
+
typer.Option("--enqueue", help="Only enqueue; do not start playback."),
|
|
564
|
+
] = False,
|
|
565
|
+
) -> None:
|
|
566
|
+
"""Play a track by id on a speaker."""
|
|
567
|
+
position = _run(
|
|
568
|
+
_with_client(
|
|
569
|
+
room,
|
|
570
|
+
ip,
|
|
571
|
+
lambda c: c.open_track(track_id, next_=play_next, play=not enqueue_only),
|
|
572
|
+
)
|
|
573
|
+
)
|
|
574
|
+
status = "enqueued" if enqueue_only else "playing"
|
|
575
|
+
_print_action(
|
|
576
|
+
f"[green]{status}[/] {track_id}",
|
|
577
|
+
{"status": status, "track_id": track_id, "position": position or ""},
|
|
578
|
+
)
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
# --------------------------------------------------------------------------- config
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
@config_app.command("show")
|
|
585
|
+
def config_show() -> None:
|
|
586
|
+
"""Show the current local CLI defaults."""
|
|
587
|
+
config = load_config()
|
|
588
|
+
|
|
589
|
+
def plain() -> None:
|
|
590
|
+
if not config:
|
|
591
|
+
console.print(f"[dim]no config set[/] ({CONFIG_PATH})")
|
|
592
|
+
return
|
|
593
|
+
for key, value in config.items():
|
|
594
|
+
if isinstance(value, dict):
|
|
595
|
+
console.print(
|
|
596
|
+
f"{key}: [dim]<{len(value)} entr{'y' if len(value) == 1 else 'ies'}>[/]"
|
|
597
|
+
)
|
|
598
|
+
else:
|
|
599
|
+
console.print(f"{key}: [cyan]{value}[/]")
|
|
600
|
+
|
|
601
|
+
_print_object(dict(config), plain)
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
@config_app.command("set")
|
|
605
|
+
def config_set(
|
|
606
|
+
room: Annotated[
|
|
607
|
+
str | None, typer.Option("--room", "-r", help="Set the default room name.")
|
|
608
|
+
] = None,
|
|
609
|
+
ip: Annotated[str | None, typer.Option("--ip", help="Set the default speaker IP.")] = None,
|
|
610
|
+
output_format: Annotated[
|
|
611
|
+
OutputFormat | None, typer.Option("--format", help="Set the default output format.")
|
|
612
|
+
] = None,
|
|
613
|
+
timeout: Annotated[
|
|
614
|
+
float | None,
|
|
615
|
+
typer.Option("--timeout", help="Set the default SOAP/discovery timeout (seconds)."),
|
|
616
|
+
] = None,
|
|
617
|
+
) -> None:
|
|
618
|
+
"""Set persistent CLI defaults so you don't have to pass them every time."""
|
|
619
|
+
if room is None and ip is None and output_format is None and timeout is None:
|
|
620
|
+
raise typer.BadParameter("provide at least one of --room, --ip, --format, --timeout")
|
|
621
|
+
|
|
622
|
+
config = load_config()
|
|
623
|
+
if room is not None:
|
|
624
|
+
config["default_room"] = room
|
|
625
|
+
config.pop("default_ip", None)
|
|
626
|
+
if ip is not None:
|
|
627
|
+
config["default_ip"] = ip
|
|
628
|
+
config.pop("default_room", None)
|
|
629
|
+
if output_format is not None:
|
|
630
|
+
config["default_format"] = output_format.value
|
|
631
|
+
if timeout is not None:
|
|
632
|
+
config["default_timeout"] = str(timeout)
|
|
633
|
+
save_config(config)
|
|
634
|
+
_print_action(f"[green]saved[/] config → {config}", {"status": "saved", **config})
|
|
635
|
+
|
|
636
|
+
|
|
637
|
+
@config_app.command("clear")
|
|
638
|
+
def config_clear() -> None:
|
|
639
|
+
"""Remove all local CLI defaults."""
|
|
640
|
+
CONFIG_PATH.unlink(missing_ok=True)
|
|
641
|
+
_print_action("[green]config cleared[/]", {"status": "cleared"})
|
|
642
|
+
|
|
643
|
+
|
|
644
|
+
if __name__ == "__main__":
|
|
645
|
+
app()
|