python-amazon-echo 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.
amazon_echo/client.py ADDED
@@ -0,0 +1,1626 @@
1
+ """Async client for the Alexa cloud API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from collections.abc import Callable
7
+ import copy
8
+ from datetime import UTC, datetime, timedelta
9
+ import json as jsonlib
10
+ import logging
11
+ import re
12
+ import time
13
+ from typing import Any, Self
14
+ from urllib.parse import quote, urlsplit
15
+
16
+ import aiohttp
17
+
18
+ from .auth import (
19
+ Credentials,
20
+ exchange_cookies,
21
+ refresh_access_token,
22
+ region_for_domain,
23
+ )
24
+ from .const import (
25
+ APP_USER_AGENT,
26
+ LIST_KINDS,
27
+ MEDIA_COMMANDS,
28
+ MUTATION_SET_ENDPOINT_FEATURES,
29
+ NOTIFICATION_KINDS,
30
+ QUERY_ENDPOINTS,
31
+ USER_AGENT,
32
+ )
33
+ from .exceptions import (
34
+ AmazonEchoAuthenticationError,
35
+ AmazonEchoConnectionError,
36
+ AmazonEchoConnectionTimeoutError,
37
+ AmazonEchoError,
38
+ AmazonEchoNotSupportedError,
39
+ AmazonEchoRateLimitError,
40
+ AmazonEchoResponseError,
41
+ )
42
+ from .models import (
43
+ Account,
44
+ AuxPort,
45
+ BluetoothDevice,
46
+ Device,
47
+ EchoList,
48
+ ListItem,
49
+ MediaState,
50
+ Notification,
51
+ Routine,
52
+ VoiceRecord,
53
+ )
54
+
55
+ _LOGGER = logging.getLogger(__name__)
56
+
57
+ _TIMEOUT = aiohttp.ClientTimeout(total=30)
58
+ _RETRY_DELAYS = (1.0, 3.0) # back-off before the 2nd and 3rd attempt on 429/503
59
+ _REAUTH_COOLDOWN = 60.0 # a 401/403 this soon after a cookie exchange is final
60
+ _TOKEN_MARGIN = 60.0
61
+ _HISTORY_CSRF_TTL = 12 * 3600
62
+ _HISTORY_PAGES = 5
63
+ _CSRF_META = re.compile(
64
+ r'<meta[^>]*name="csrf-token"[^>]*content="([^"]+)"', re.IGNORECASE
65
+ )
66
+ _NODE = "com.amazon.alexa.behaviors.model."
67
+ _SKIPPED_UTTERANCES = frozenset(
68
+ {"ASR_TIMEOUT", "DEVICE_ARBITRATION", "NO_EXPRESSED_INTENT", "WAKE_WORD_ONLY"}
69
+ )
70
+ _LIST_NAMES = {"SHOP": "Shopping", "TODO": "To-do"} # the built-in lists are unnamed
71
+ _WEEKDAYS = ("MO", "TU", "WE", "TH", "FR", "SA", "SU")
72
+ _RECURRENCE_PRESETS: dict[str, list[str]] = {
73
+ "DAILY": [],
74
+ "EVERYDAY": [],
75
+ "WEEKDAYS": list(_WEEKDAYS[:5]),
76
+ "WEEKENDS": list(_WEEKDAYS[5:]),
77
+ }
78
+
79
+
80
+ def format_mac(value: str | None) -> str | None:
81
+ """Return ``aa:bb:cc:dd:ee:ff`` for any 12-hex-digit MAC spelling."""
82
+ digits = re.sub(r"[^0-9a-fA-F]", "", value or "").lower()
83
+ if len(digits) != 12:
84
+ return None
85
+ return ":".join(digits[i : i + 2] for i in range(0, 12, 2))
86
+
87
+
88
+ def _from_ms(value: Any) -> datetime | None:
89
+ """Return an aware datetime for an epoch in milliseconds (0/None → None)."""
90
+ try:
91
+ millis = float(value)
92
+ except TypeError, ValueError:
93
+ return None
94
+ return datetime.fromtimestamp(millis / 1000, UTC) if millis > 0 else None
95
+
96
+
97
+ def _local(when: datetime) -> datetime:
98
+ """Return ``when`` as wall-clock time in the system time zone.
99
+
100
+ ponytail: Amazon reads alarm/reminder times in the Echo's own time zone and
101
+ the API does not take one; this assumes the host shares it. Pass a naive
102
+ datetime in the Echo's local time when it does not.
103
+ """
104
+ return when.astimezone().replace(tzinfo=None) if when.tzinfo else when
105
+
106
+
107
+ def _dig(data: Any, *path: str) -> Any:
108
+ """Walk nested dicts, returning None as soon as a level is missing."""
109
+ for key in path:
110
+ if not isinstance(data, dict):
111
+ return None
112
+ data = data.get(key)
113
+ return data
114
+
115
+
116
+ def parse_notification(item: dict[str, Any]) -> Notification:
117
+ """Build a :class:`Notification` from an ``/api/notifications`` item."""
118
+ kind = NOTIFICATION_KINDS.get(item.get("type") or "", "")
119
+ kind = kind or str(item.get("type") or "unknown").lower()
120
+ if item.get("musicAlarmId") and kind == "alarm":
121
+ kind = "music_alarm"
122
+ remaining = item.get("remainingTime") or 0
123
+ when = _from_ms(item.get("triggerTime")) or _from_ms(item.get("alarmTime"))
124
+ return Notification(
125
+ id=item["id"],
126
+ kind=kind,
127
+ status=item.get("status") or "OFF",
128
+ device_serial=item.get("deviceSerialNumber") or "",
129
+ device_type=item.get("deviceType") or "",
130
+ label=item.get("reminderLabel")
131
+ or item.get("timerLabel")
132
+ or item.get("alarmLabel"),
133
+ when=when,
134
+ remaining=timedelta(milliseconds=remaining)
135
+ if kind == "timer" and remaining > 0
136
+ else None,
137
+ recurrence=item.get("recurringPattern") or None,
138
+ sound=_dig(item, "sound", "id"),
139
+ raw=item,
140
+ )
141
+
142
+
143
+ def _parse_media(info: dict[str, Any]) -> MediaState:
144
+ """Build a :class:`MediaState` from the ``playerInfo`` of ``/api/np/player``."""
145
+ transport = info.get("transport") or {}
146
+ progress = info.get("progress") or {}
147
+ volume = info.get("volume") or {}
148
+ text = info.get("infoText") or {}
149
+ state = str(info.get("state") or "IDLE").lower()
150
+
151
+ def flag(name: str) -> bool | None:
152
+ value = transport.get(name)
153
+ return None if value in (None, "HIDDEN") else value == "SELECTED"
154
+
155
+ def seconds(name: str) -> float | None:
156
+ value = progress.get(name)
157
+ return float(value) if isinstance(value, (int, float)) else None
158
+
159
+ return MediaState(
160
+ state=state if state in ("playing", "paused") else "idle",
161
+ title=text.get("title"),
162
+ artist=text.get("subText1"),
163
+ album=text.get("subText2"),
164
+ image_url=_dig(info, "mainArt", "url"),
165
+ duration=seconds("mediaLength"),
166
+ position=seconds("mediaProgress"),
167
+ position_updated_at=datetime.now(UTC) if progress else None,
168
+ provider=_dig(info, "provider", "providerName"),
169
+ shuffle=flag("shuffle"),
170
+ repeat=flag("repeat"),
171
+ can_next=transport.get("next") == "ENABLED",
172
+ can_previous=transport.get("previous") == "ENABLED",
173
+ can_seek=bool(progress.get("allowScrubbing")),
174
+ muted=bool(volume.get("muted")),
175
+ volume=volume.get("volume"),
176
+ )
177
+
178
+
179
+ def _parse_endpoint(endpoint: dict[str, Any]) -> dict[str, Any]:
180
+ """Flatten one GraphQL endpoint into the values the integration needs."""
181
+ state: dict[str, Any] = {
182
+ "endpoint_id": endpoint.get("endpointId"),
183
+ "model": _dig(endpoint, "model", "value", "text"),
184
+ "mac": None,
185
+ "temperature": None,
186
+ "volume": None,
187
+ "reachable": None,
188
+ "remote_battery": None,
189
+ "ambient_mode": None,
190
+ "dnd": _dig(endpoint, "settings", "doNotDisturb", "toggleValue"),
191
+ }
192
+ for connection in endpoint.get("connections") or []:
193
+ if connection.get("type") == "TCP_IP" and connection.get("macAddress"):
194
+ state["mac"] = format_mac(connection["macAddress"])
195
+ for feature in endpoint.get("features") or []:
196
+ for prop in feature.get("properties") or []:
197
+ kind = prop.get("__typename")
198
+ if kind == "TemperatureSensor" and prop.get("temp"):
199
+ value, scale = prop["temp"].get("value"), prop["temp"].get("scale")
200
+ if value is not None and scale == "FAHRENHEIT":
201
+ value = round((value - 32) / 1.8, 1)
202
+ state["temperature"] = value
203
+ elif kind == "Volume" and prop.get("vol"):
204
+ state["volume"] = prop["vol"].get("value")
205
+ elif kind == "Reachability" and prop.get("reachabilityStatusValue"):
206
+ state["reachable"] = prop["reachabilityStatusValue"] == "OK"
207
+ elif kind == "InventoryLevel" and feature.get("instance") == (
208
+ "Remote.Battery"
209
+ ):
210
+ state["remote_battery"] = _dig(prop, "inventoryLevelValue", "value")
211
+ elif kind == "ToggleState" and feature.get("instance") == (
212
+ "FTV.AmbientMode"
213
+ ):
214
+ value = prop.get("toggleStateValue")
215
+ state["ambient_mode"] = None if value is None else value == "ON"
216
+ return state
217
+
218
+
219
+ def _replace_placeholders(node: Any, values: dict[str, str]) -> Any:
220
+ """Return a copy of a routine node with the ``ALEXA_CURRENT_*`` markers set."""
221
+ if isinstance(node, dict):
222
+ return {k: _replace_placeholders(v, values) for k, v in node.items()}
223
+ if isinstance(node, list):
224
+ return [_replace_placeholders(v, values) for v in node]
225
+ if isinstance(node, str):
226
+ return values.get(node, node)
227
+ return node
228
+
229
+
230
+ def _recurrence_rule(recurrence: str, when: datetime) -> dict[str, Any]:
231
+ """Translate a recurrence string into the alarms API repeat rule.
232
+
233
+ Accepts ``DAILY``, ``WEEKDAYS``, ``WEEKENDS``, ``WEEKLY`` (the weekday of
234
+ ``when``) or a comma separated list of days such as ``MO,WE,FR``.
235
+ """
236
+ key = recurrence.strip().upper()
237
+ if key in _RECURRENCE_PRESETS:
238
+ days = _RECURRENCE_PRESETS[key]
239
+ elif key == "WEEKLY":
240
+ days = [_WEEKDAYS[when.weekday()]]
241
+ else:
242
+ days = [day.strip()[:2] for day in key.split(",") if day.strip()]
243
+ if not days or any(day not in _WEEKDAYS for day in days):
244
+ raise ValueError(f"Unsupported recurrence: {recurrence!r}")
245
+ if not days:
246
+ return {"freq": "DAILY", "byDay": [], "interval": 1}
247
+ return {"freq": "WEEKLY", "byDay": days, "interval": 1}
248
+
249
+
250
+ class AmazonEchoClient:
251
+ """Client for the Alexa cloud API of one Amazon account.
252
+
253
+ Args:
254
+ credentials: The session to use; it is updated in place when tokens or
255
+ cookies are renewed.
256
+ session: Optional aiohttp session. Cookies are always sent explicitly,
257
+ so a shared session is safe.
258
+ on_credentials_update: Called (synchronously) whenever ``credentials``
259
+ changed and should be persisted.
260
+
261
+ """
262
+
263
+ def __init__(
264
+ self,
265
+ credentials: Credentials,
266
+ *,
267
+ session: aiohttp.ClientSession | None = None,
268
+ on_credentials_update: Callable[[Credentials], None] | None = None,
269
+ ) -> None:
270
+ """Initialize the client."""
271
+ self.credentials = credentials
272
+ self._session = session
273
+ self._own_session = session is None
274
+ self._on_update = on_credentials_update
275
+ self._auth_lock = asyncio.Lock()
276
+ self._generation = 0
277
+ self._last_exchange = 0.0
278
+ self._locale: str | None = None
279
+ self._devices: dict[str, Device] = {}
280
+ self._service_urls: dict[str, str] | None = None
281
+ self._history_csrf: tuple[str, float] | None = None
282
+
283
+ # ------------------------------------------------------------------ core
284
+
285
+ @property
286
+ def host(self) -> str:
287
+ """Return the Alexa API host of the account."""
288
+ return f"alexa.{self.credentials.domain}"
289
+
290
+ @property
291
+ def home_region(self) -> str:
292
+ """Return the push region of the account ("NA", "EU" or "FE")."""
293
+ return self.credentials.home_region or region_for_domain(
294
+ self.credentials.domain
295
+ )
296
+
297
+ @property
298
+ def session(self) -> aiohttp.ClientSession:
299
+ """Return the aiohttp session, creating one when none was injected."""
300
+ if self._session is None:
301
+ self._session = aiohttp.ClientSession(cookie_jar=aiohttp.DummyCookieJar())
302
+ return self._session
303
+
304
+ async def close(self) -> None:
305
+ """Close the session if this client created it."""
306
+ if self._own_session and self._session is not None:
307
+ await self._session.close()
308
+ self._session = None
309
+
310
+ async def __aenter__(self) -> Self:
311
+ """Enter the async context."""
312
+ return self
313
+
314
+ async def __aexit__(self, *_: object) -> None:
315
+ """Exit the async context."""
316
+ await self.close()
317
+
318
+ def _notify(self) -> None:
319
+ if self._on_update is not None:
320
+ self._on_update(self.credentials)
321
+
322
+ async def async_get_access_token(self) -> str:
323
+ """Return a bearer token, refreshing it when less than 60 s are left.
324
+
325
+ Raises:
326
+ AmazonEchoAuthenticationError: The refresh token was rejected.
327
+
328
+ """
329
+ creds = self.credentials
330
+ if (
331
+ not creds.access_token
332
+ or creds.access_token_expires - _TOKEN_MARGIN < time.time()
333
+ ):
334
+ async with self._auth_lock:
335
+ if (
336
+ not creds.access_token
337
+ or creds.access_token_expires - _TOKEN_MARGIN < time.time()
338
+ ):
339
+ await refresh_access_token(self.session, creds)
340
+ self._notify()
341
+ assert creds.access_token is not None # noqa: S101
342
+ return creds.access_token
343
+
344
+ async def _reauthorize(self, seen: int, *, bearer: bool) -> None:
345
+ """Renew the cookies (and the bearer token) after a 401/403."""
346
+ async with self._auth_lock:
347
+ if self._generation != seen:
348
+ return # another request already renewed the session
349
+ if time.monotonic() - self._last_exchange < _REAUTH_COOLDOWN:
350
+ raise AmazonEchoAuthenticationError(
351
+ "Session rejected right after a cookie refresh"
352
+ )
353
+ await exchange_cookies(self.session, self.credentials)
354
+ if bearer:
355
+ await refresh_access_token(self.session, self.credentials)
356
+ self._generation += 1
357
+ self._last_exchange = time.monotonic()
358
+ self._notify()
359
+
360
+ async def _headers(self, url: str, *, bearer: bool, app: bool) -> dict[str, str]:
361
+ headers = {
362
+ "User-Agent": APP_USER_AGENT if app else USER_AGENT,
363
+ "Accept": "application/json; charset=utf-8",
364
+ "Accept-Language": self._locale or "en-US",
365
+ }
366
+ cookies = self.credentials.cookies
367
+ # cookies only go to the account's own marketplace hosts
368
+ if (urlsplit(url).hostname or "").endswith(self.credentials.domain):
369
+ headers["Cookie"] = "; ".join(f"{k}={v}" for k, v in cookies.items())
370
+ if cookies.get("csrf"):
371
+ headers["csrf"] = cookies["csrf"]
372
+ if bearer:
373
+ headers["Authorization"] = f"Bearer {await self.async_get_access_token()}"
374
+ return headers
375
+
376
+ def _store_cookies(self, resp: aiohttp.ClientResponse) -> None:
377
+ """Keep cookies the Alexa site sets (notably ``csrf``)."""
378
+ if not (resp.url.host or "").endswith(self.credentials.domain):
379
+ return
380
+ changed = False
381
+ for name, morsel in resp.cookies.items():
382
+ if morsel.value and self.credentials.cookies.get(name) != morsel.value:
383
+ self.credentials.cookies[name] = morsel.value
384
+ changed = True
385
+ if changed:
386
+ self._notify()
387
+
388
+ async def request(
389
+ self,
390
+ method: str,
391
+ path: str,
392
+ *,
393
+ host: str | None = None,
394
+ json: Any = None,
395
+ params: dict[str, str] | None = None,
396
+ bearer: bool = False,
397
+ ) -> Any:
398
+ """Call the Alexa API and return the decoded JSON body (None if empty).
399
+
400
+ Args:
401
+ method: HTTP method.
402
+ path: Path starting with ``/`` or a full ``https://`` URL.
403
+ host: Host to use instead of ``alexa.<domain>``.
404
+ json: JSON body.
405
+ params: Query parameters.
406
+ bearer: Also send the OAuth access token.
407
+
408
+ Raises:
409
+ AmazonEchoAuthenticationError: 401/403 that a cookie refresh did not fix.
410
+ AmazonEchoRateLimitError: 429/503 after the retries.
411
+ AmazonEchoConnectionError: Amazon could not be reached.
412
+ AmazonEchoResponseError: Any other HTTP error, or a non-JSON body.
413
+
414
+ """
415
+ return await self._request(
416
+ method, path, host=host, json=json, params=params, bearer=bearer
417
+ )
418
+
419
+ async def _request(
420
+ self,
421
+ method: str,
422
+ path: str,
423
+ *,
424
+ host: str | None = None,
425
+ json: Any = None,
426
+ params: dict[str, str] | None = None,
427
+ bearer: bool = False,
428
+ headers: dict[str, str] | None = None,
429
+ app: bool = False,
430
+ text: bool = False,
431
+ ) -> Any:
432
+ url = (
433
+ path
434
+ if path.startswith("https://")
435
+ else f"https://{host or self.host}{path}"
436
+ )
437
+ delays = list(_RETRY_DELAYS)
438
+ reauthorized = False
439
+ while True:
440
+ seen = self._generation
441
+ request_headers = await self._headers(url, bearer=bearer, app=app)
442
+ request_headers.update(headers or {})
443
+ try:
444
+ async with self.session.request(
445
+ method,
446
+ url,
447
+ json=json,
448
+ params=params,
449
+ headers=request_headers,
450
+ timeout=_TIMEOUT,
451
+ ) as resp:
452
+ status = resp.status
453
+ body = await resp.text()
454
+ signin = "/ap/signin" in resp.url.path
455
+ self._store_cookies(resp)
456
+ except TimeoutError as err:
457
+ raise AmazonEchoConnectionTimeoutError(
458
+ f"Timeout on {method} {path}"
459
+ ) from err
460
+ except aiohttp.ClientError as err:
461
+ raise AmazonEchoConnectionError(
462
+ f"{method} {path} failed: {err}"
463
+ ) from err
464
+
465
+ if status in (401, 403) or signin:
466
+ if reauthorized:
467
+ raise AmazonEchoAuthenticationError(
468
+ f"{method} {path} rejected (HTTP {status})"
469
+ )
470
+ await self._reauthorize(seen, bearer=bearer)
471
+ reauthorized = True
472
+ continue
473
+ if status in (429, 503) or (status >= 400 and "Rate exceeded" in body):
474
+ if not delays:
475
+ raise AmazonEchoRateLimitError(
476
+ f"{method} {path} is rate limited (HTTP {status})"
477
+ )
478
+ await asyncio.sleep(delays.pop(0))
479
+ continue
480
+ if status >= 400:
481
+ raise AmazonEchoResponseError(status, body[:500])
482
+ if text:
483
+ return body
484
+ if not body.strip():
485
+ return None
486
+ try:
487
+ return jsonlib.loads(body)
488
+ except ValueError as err:
489
+ # Unavailable routes answer 200 with an HTML page.
490
+ raise AmazonEchoResponseError(status, body[:200]) from err
491
+
492
+ async def _graphql(
493
+ self, query: str, variables: dict[str, Any] | None = None
494
+ ) -> Any:
495
+ """Run a GraphQL document and return its ``data``.
496
+
497
+ Partial answers (``data`` plus ``errors``) are accepted.
498
+ """
499
+ answer = await self._request(
500
+ "POST",
501
+ "/nexus/v1/graphql",
502
+ json={"query": query, "variables": variables or {}},
503
+ app=True,
504
+ )
505
+ data = answer.get("data") if isinstance(answer, dict) else None
506
+ if data:
507
+ return data
508
+ errors = jsonlib.dumps((answer or {}).get("errors") or answer)[:500]
509
+ if "TOO_MANY_REQUESTS" in errors:
510
+ raise AmazonEchoRateLimitError("GraphQL is rate limited")
511
+ raise AmazonEchoResponseError(200, errors)
512
+
513
+ @staticmethod
514
+ def _query(device: Device) -> dict[str, str]:
515
+ return {"deviceSerialNumber": device.serial, "deviceType": device.device_type}
516
+
517
+ # ------------------------------------------------- account / inventory
518
+
519
+ async def get_account(self) -> Account:
520
+ """Return the account behind the session."""
521
+ data = await self._request("GET", "/api/users/me")
522
+ account = Account(
523
+ customer_id=data["id"],
524
+ name=data.get("fullName"),
525
+ email=data.get("email"),
526
+ country=data.get("countryOfResidence"),
527
+ marketplace_id=data.get("marketPlaceId"),
528
+ )
529
+ self._locale = data.get("marketPlaceLocale") or self._locale
530
+ creds = self.credentials
531
+ if (creds.customer_id, creds.email) != (account.customer_id, account.email):
532
+ creds.customer_id = account.customer_id
533
+ creds.email = account.email
534
+ creds.customer_name = creds.customer_name or account.name
535
+ self._notify()
536
+ return account
537
+
538
+ async def get_service_urls(self) -> dict[str, str]:
539
+ """Return the service URLs Amazon assigns to the account (cached).
540
+
541
+ Keys include ``alexaApiUrl`` (alerts API), ``bobDispatchUrl`` (HTTP/2
542
+ push), ``websiteApiUrl`` and ``retailUrl``.
543
+ """
544
+ if self._service_urls is None:
545
+ data = await self._request("GET", "/api/endpoints")
546
+ self._service_urls = {
547
+ key: str(value).rstrip("/")
548
+ for key, value in (data or {}).items()
549
+ if isinstance(value, str)
550
+ }
551
+ return self._service_urls
552
+
553
+ async def _customer(self) -> tuple[str, str]:
554
+ """Return (customer id, locale), fetching the account once."""
555
+ if not self.credentials.customer_id or not self._locale:
556
+ await self.get_account()
557
+ assert self.credentials.customer_id is not None # noqa: S101
558
+ return self.credentials.customer_id, self._locale or "en-US"
559
+
560
+ async def _endpoints(self) -> dict[str, dict[str, Any]]:
561
+ """Return the GraphQL state of every Alexa-enabled endpoint by serial."""
562
+ data = await self._graphql(QUERY_ENDPOINTS)
563
+ result: dict[str, dict[str, Any]] = {}
564
+ for endpoint in _dig(data, "listEndpoints", "endpoints") or []:
565
+ serial = _dig(endpoint, "dmsIdentifier", "dsn")
566
+ if serial:
567
+ result[serial] = _parse_endpoint(endpoint)
568
+ return result
569
+
570
+ async def get_devices(self) -> list[Device]:
571
+ """Return every Alexa device, app and speaker group of the account.
572
+
573
+ The legacy device list is merged with the GraphQL endpoints (MAC,
574
+ endpoint id, model name). A GraphQL failure other than a rejected
575
+ session only costs those extra fields.
576
+ """
577
+ data = await self._request(
578
+ "GET", "/api/devices-v2/device", params={"cached": "false"}
579
+ )
580
+ try:
581
+ endpoints = await self._endpoints()
582
+ except AmazonEchoAuthenticationError, AmazonEchoConnectionError:
583
+ raise
584
+ except AmazonEchoError as err:
585
+ _LOGGER.debug("GraphQL endpoints unavailable: %s", err)
586
+ endpoints = {}
587
+ devices = []
588
+ for item in data.get("devices") or []:
589
+ extra = endpoints.get(item["serialNumber"], {})
590
+ devices.append(
591
+ Device(
592
+ serial=item["serialNumber"],
593
+ device_type=item["deviceType"],
594
+ name=item.get("accountName") or item["serialNumber"],
595
+ family=item.get("deviceFamily") or "UNKNOWN",
596
+ model=extra.get("model") or item.get("deviceTypeFriendlyName"),
597
+ software_version=item.get("softwareVersion"),
598
+ account_id=item.get("deviceAccountId"),
599
+ online=bool(item.get("online")),
600
+ capabilities=frozenset(item.get("capabilities") or ()),
601
+ cluster_members=tuple(item.get("clusterMembers") or ()),
602
+ parent_clusters=tuple(item.get("parentClusters") or ()),
603
+ mac=extra.get("mac") or format_mac(item.get("macAddress")),
604
+ endpoint_id=extra.get("endpoint_id"),
605
+ battery_level=item.get("remainingBatteryLevel"),
606
+ charging=item.get("charging"),
607
+ )
608
+ )
609
+ self._devices = {device.serial: device for device in devices}
610
+ return devices
611
+
612
+ async def get_routines(self) -> list[Routine]:
613
+ """Return the routines (automations) of the account."""
614
+ data = await self._request(
615
+ "GET", "/api/behaviors/v2/automations", params={"limit": "2000"}
616
+ )
617
+ routines = []
618
+ for item in data or []:
619
+ utterance = next(
620
+ (
621
+ _dig(trigger, "payload", "utterance")
622
+ for trigger in item.get("triggers") or []
623
+ if _dig(trigger, "payload", "utterance")
624
+ ),
625
+ None,
626
+ )
627
+ routines.append(
628
+ Routine(
629
+ id=item["automationId"],
630
+ name=item.get("name") or utterance or item["automationId"],
631
+ enabled=item.get("status") == "ENABLED",
632
+ raw=item,
633
+ )
634
+ )
635
+ return routines
636
+
637
+ async def get_music_providers(self) -> dict[str, str]:
638
+ """Return the usable music providers as id → display name."""
639
+ data = await self._request(
640
+ "GET", "/api/behaviors/entities", params={"skillId": "amzn1.ask.1p.music"}
641
+ )
642
+ return {
643
+ item["id"]: item["displayName"]
644
+ for item in data or []
645
+ if item.get("id")
646
+ and item.get("displayName")
647
+ and item.get("availability") == "AVAILABLE"
648
+ }
649
+
650
+ # ------------------------------------------------------------ bulk state
651
+
652
+ async def get_dnd(self) -> dict[str, bool]:
653
+ """Return do-not-disturb by device serial."""
654
+ data = await self._request("GET", "/api/dnd/device-status-list")
655
+ return {
656
+ item["deviceSerialNumber"]: bool(item.get("enabled"))
657
+ for item in data.get("doNotDisturbDeviceStatusList") or []
658
+ }
659
+
660
+ async def get_volumes(self) -> dict[str, tuple[int, bool]]:
661
+ """Return (volume 0-100, muted) by device serial."""
662
+ data = await self._request(
663
+ "GET", "/api/devices/deviceType/dsn/audio/v1/allDeviceVolumes"
664
+ )
665
+ return {
666
+ item["dsn"]: (int(item["speakerVolume"]), bool(item.get("speakerMuted")))
667
+ for item in data.get("volumes") or []
668
+ if item.get("speakerVolume") is not None
669
+ }
670
+
671
+ async def get_bluetooth(self) -> dict[str, list[BluetoothDevice]]:
672
+ """Return the paired Bluetooth devices by Echo serial."""
673
+ data = await self._request("GET", "/api/bluetooth", params={"cached": "true"})
674
+ return {
675
+ state["deviceSerialNumber"]: [
676
+ BluetoothDevice(
677
+ address=paired["address"],
678
+ name=paired.get("friendlyName"),
679
+ connected=bool(paired.get("connected")),
680
+ profiles=tuple(paired.get("profiles") or ()),
681
+ )
682
+ for paired in state.get("pairedDeviceList") or []
683
+ ]
684
+ for state in data.get("bluetoothStates") or []
685
+ }
686
+
687
+ async def get_notifications(self) -> list[Notification]:
688
+ """Return every alarm, timer, reminder and music alarm.
689
+
690
+ One (large, rate limited) call serves all kinds.
691
+ """
692
+ data = await self._request("GET", "/api/notifications")
693
+ return [
694
+ parse_notification(item)
695
+ for item in data.get("notifications") or []
696
+ if item.get("id")
697
+ ]
698
+
699
+ async def get_alarm_volumes(self) -> dict[str, int]:
700
+ """Return the alarm/timer volume by device serial."""
701
+ return {
702
+ item["deviceSerialNumber"]: int(item["volumeLevel"])
703
+ for item in await self._notification_states()
704
+ if item.get("volumeLevel") is not None
705
+ }
706
+
707
+ async def _notification_states(self) -> list[dict[str, Any]]:
708
+ data = await self._request("GET", "/api/device-notification-state")
709
+ return data.get("deviceNotificationStates") or []
710
+
711
+ async def _wake_word_models(self) -> list[dict[str, Any]]:
712
+ data = await self._request("GET", "/api/wake-word", params={"cached": "true"})
713
+ return data.get("wakeWords") or []
714
+
715
+ async def get_wake_words(self) -> dict[str, str]:
716
+ """Return the wake word by device serial."""
717
+ return {
718
+ item["deviceSerialNumber"]: item["wakeWord"]
719
+ for item in await self._wake_word_models()
720
+ if item.get("wakeWord")
721
+ }
722
+
723
+ async def get_ascending_alarms(self) -> dict[str, bool]:
724
+ """Return whether the ascending alarm is on, by device serial."""
725
+ data = await self._request("GET", "/api/ascending-alarm")
726
+ return {
727
+ item["deviceSerialNumber"]: bool(item.get("ascendingAlarmEnabled"))
728
+ for item in data.get("ascendingAlarmModelList") or []
729
+ }
730
+
731
+ async def get_media(self, device: Device) -> MediaState:
732
+ """Return what ``device`` is playing."""
733
+ data = await self._request(
734
+ "GET",
735
+ "/api/np/player",
736
+ params={**self._query(device), "screenWidth": "2560"},
737
+ )
738
+ return _parse_media((data or {}).get("playerInfo") or {})
739
+
740
+ async def get_endpoint_states(self) -> dict[str, dict[str, Any]]:
741
+ """Return the GraphQL state of every Alexa endpoint by device serial.
742
+
743
+ Each value has ``temperature`` (°C), ``volume``, ``reachable``,
744
+ ``remote_battery``, ``ambient_mode``, ``mac``, ``dnd``, ``model`` and
745
+ ``endpoint_id``; values the device does not report are None.
746
+ """
747
+ return await self._endpoints()
748
+
749
+ # ------------------------------------------------- per-device settings
750
+
751
+ async def get_wifi(self, device: Device) -> tuple[str | None, str | None]:
752
+ """Return the (SSID, MAC) of the Wi-Fi connection of ``device``."""
753
+ data = await self._request(
754
+ "GET", "/api/device-wifi-details", params=self._query(device)
755
+ )
756
+ return (data or {}).get("essid"), format_mac((data or {}).get("macAddress"))
757
+
758
+ async def get_equalizer(self, device: Device) -> dict[str, int]:
759
+ """Return the bass/mid/treble levels (-6..6)."""
760
+ data = await self._request(
761
+ "GET", f"/api/equalizer/{device.serial}/{device.device_type}"
762
+ )
763
+ return {key: int(data[key]) for key in ("bass", "mid", "treble")}
764
+
765
+ def _earcon_path(self, device: Device) -> str:
766
+ return (
767
+ f"/api/earcon/states/{device.device_type}/"
768
+ f"{device.software_version}/{device.serial}"
769
+ )
770
+
771
+ async def get_earcons(self, device: Device) -> dict[str, bool]:
772
+ """Return whether the start/end-of-request sounds are on."""
773
+ data = await self._request("GET", self._earcon_path(device))
774
+ return {
775
+ "wake_word": bool(data.get("wakeWordEarconEnabled")),
776
+ "end_of_speech": bool(data.get("endOfSpeechEarconEnabled")),
777
+ }
778
+
779
+ async def get_aux(self, device: Device) -> list[AuxPort]:
780
+ """Return the line in/out ports of ``device``."""
781
+ data = await self._request(
782
+ "GET", f"/api/auxcontroller/{device.device_type}/{device.serial}/state"
783
+ )
784
+ return [
785
+ AuxPort(
786
+ id=port["id"],
787
+ direction=port.get("direction") or "",
788
+ plugged=bool(port.get("isPlugged")),
789
+ enabled=bool(port.get("isEnabled")),
790
+ active=port.get("inputActivity") == "ACTIVE",
791
+ )
792
+ for port in (data or {}).get("ports") or []
793
+ ]
794
+
795
+ def _setting_path(self, device: Device, key: str) -> str:
796
+ if not device.account_id:
797
+ raise AmazonEchoNotSupportedError(f"{device.name} has no settings")
798
+ return f"/api/v1/devices/{device.account_id}/settings/{quote(key, safe='')}"
799
+
800
+ async def get_setting(self, device: Device, key: str) -> Any:
801
+ """Return the JSON-decoded value of a per-device setting.
802
+
803
+ Raises:
804
+ AmazonEchoNotSupportedError: The device has no such setting.
805
+
806
+ """
807
+ try:
808
+ data = await self._request("GET", self._setting_path(device, key))
809
+ except AmazonEchoResponseError as err:
810
+ if err.status in (400, 404):
811
+ raise AmazonEchoNotSupportedError(
812
+ f"{device.name} has no setting {key!r}"
813
+ ) from err
814
+ raise
815
+ value = (data or {}).get("value")
816
+ if not isinstance(value, str):
817
+ return value
818
+ try:
819
+ return jsonlib.loads(value)
820
+ except ValueError:
821
+ return value
822
+
823
+ async def get_available_wake_words(self, device: Device) -> list[str]:
824
+ """Return the wake words ``device`` can use."""
825
+ data = await self._request(
826
+ "GET",
827
+ "/api/wake-words",
828
+ params={
829
+ "deviceType": device.device_type,
830
+ "softwareVersion": device.software_version or "",
831
+ },
832
+ )
833
+ return list((data or {}).get("wakeWords") or [])
834
+
835
+ async def get_alarm_sounds(self, device: Device) -> dict[str, str]:
836
+ """Return the alarm sounds of ``device`` as id → display name."""
837
+ data = await self._request(
838
+ "GET",
839
+ "/api/notification/sounds",
840
+ params={
841
+ "deviceType": device.device_type,
842
+ "deviceSerialNumber": device.serial,
843
+ "softwareVersion": device.software_version or "",
844
+ },
845
+ )
846
+ return {
847
+ sound["id"]: sound.get("displayName") or sound["id"]
848
+ for sound in (data or {}).get("notificationSounds") or []
849
+ }
850
+
851
+ async def get_default_alarm_sound(self, device: Device) -> str | None:
852
+ """Return the id of the default alarm sound of ``device``."""
853
+ data = await self._request(
854
+ "GET",
855
+ "/api/notification/default-sound",
856
+ params={
857
+ "deviceType": device.device_type,
858
+ "deviceSerialNumber": device.serial,
859
+ "notificationType": "ALARM",
860
+ },
861
+ )
862
+ sound: str | None = _dig(data, "defaultNotificationSound", "id")
863
+ return sound
864
+
865
+ # ------------------------------------------------- account preferences
866
+
867
+ async def get_whisper_mode(self) -> bool:
868
+ """Return whether Alexa whispers back when whispered to."""
869
+ data = await self._request("GET", "/api/response-modulation-preferences")
870
+ return bool(data.get("whisperModulationEnabled"))
871
+
872
+ async def get_adaptive_volume(self) -> bool:
873
+ """Return whether Alexa speaks louder in noisy rooms."""
874
+ data = await self._request("GET", "/api/adaptive-volume")
875
+ return bool(data.get("adaptiveVolumeEnabled"))
876
+
877
+ async def set_whisper_mode(self, enabled: bool) -> None:
878
+ """Turn whisper mode on or off (account wide)."""
879
+ await self._request(
880
+ "POST",
881
+ "/api/response-modulation-preferences",
882
+ json={"whisperModulationEnabled": enabled},
883
+ )
884
+
885
+ async def set_adaptive_volume(self, enabled: bool) -> None:
886
+ """Turn adaptive volume on or off (account wide)."""
887
+ await self._request(
888
+ "POST", "/api/adaptive-volume", json={"adaptiveVolumeEnabled": enabled}
889
+ )
890
+
891
+ # ---------------------------------------------------------------- writes
892
+
893
+ async def set_dnd(self, device: Device, enabled: bool) -> None:
894
+ """Turn do-not-disturb on or off."""
895
+ await self._request(
896
+ "PUT", "/api/dnd/status", json={**self._query(device), "enabled": enabled}
897
+ )
898
+
899
+ async def set_equalizer(
900
+ self, device: Device, *, bass: int, mid: int, treble: int
901
+ ) -> None:
902
+ """Set the equalizer; every band is -6..6."""
903
+ for value in (bass, mid, treble):
904
+ if not -6 <= value <= 6:
905
+ raise ValueError("Equalizer bands must be between -6 and 6")
906
+ await self._request(
907
+ "POST",
908
+ f"/api/equalizer/{device.serial}/{device.device_type}",
909
+ json={"bass": bass, "mid": mid, "treble": treble},
910
+ )
911
+
912
+ async def set_earcons(
913
+ self, device: Device, *, wake_word: bool, end_of_speech: bool
914
+ ) -> None:
915
+ """Turn the start/end-of-request sounds on or off."""
916
+ await self._request(
917
+ "PUT",
918
+ self._earcon_path(device),
919
+ json={
920
+ "wakeWordEarconEnabled": wake_word,
921
+ "endOfSpeechEarconEnabled": end_of_speech,
922
+ },
923
+ )
924
+
925
+ async def set_setting(self, device: Device, key: str, value: Any) -> None:
926
+ """Write a per-device setting (the value is JSON-encoded for you).
927
+
928
+ Raises:
929
+ AmazonEchoNotSupportedError: The device has no such setting.
930
+
931
+ """
932
+ try:
933
+ await self._request(
934
+ "PUT",
935
+ self._setting_path(device, key),
936
+ json={"value": jsonlib.dumps(value)},
937
+ )
938
+ except AmazonEchoResponseError as err:
939
+ if err.status == 400 and "does not exist" in err.body:
940
+ raise AmazonEchoNotSupportedError(
941
+ f"{device.name} has no setting {key!r}"
942
+ ) from err
943
+ raise
944
+
945
+ async def set_alarm_volume(self, device: Device, volume: int) -> None:
946
+ """Set the alarm/timer volume (0-100)."""
947
+ if not 0 <= volume <= 100:
948
+ raise ValueError("Volume must be between 0 and 100")
949
+ await self._request(
950
+ "PUT",
951
+ f"/api/device-notification-state/{device.device_type}/"
952
+ f"{device.software_version}/{device.serial}",
953
+ json={
954
+ **self._query(device),
955
+ "softwareVersion": device.software_version,
956
+ "volumeLevel": volume,
957
+ },
958
+ )
959
+
960
+ async def set_wake_word(self, device: Device, wake_word: str) -> None:
961
+ """Change the wake word; the device applies it within about a minute.
962
+
963
+ Raises:
964
+ AmazonEchoNotSupportedError: The device has no wake word.
965
+
966
+ """
967
+ model = next(
968
+ (
969
+ item
970
+ for item in await self._wake_word_models()
971
+ if item.get("deviceSerialNumber") == device.serial
972
+ ),
973
+ None,
974
+ )
975
+ if model is None:
976
+ raise AmazonEchoNotSupportedError(f"{device.name} has no wake word")
977
+ await self._request(
978
+ "PUT",
979
+ f"/api/wake-word/{device.serial}",
980
+ json={**model, "wakeWord": wake_word.strip().upper()},
981
+ )
982
+
983
+ async def set_ascending_alarm(self, device: Device, enabled: bool) -> None:
984
+ """Turn the ascending (gradually louder) alarm on or off."""
985
+ await self._request(
986
+ "PUT",
987
+ f"/api/ascending-alarm/{device.serial}",
988
+ json={**self._query(device), "ascendingAlarmEnabled": enabled},
989
+ )
990
+
991
+ async def set_default_alarm_sound(self, device: Device, sound_id: str) -> None:
992
+ """Set the default alarm sound."""
993
+ await self._request(
994
+ "PUT",
995
+ "/api/notification/default-sound",
996
+ json={
997
+ "deviceType": device.device_type,
998
+ "deviceSerialNumber": device.serial,
999
+ "notificationType": "ALARM",
1000
+ "soundId": sound_id,
1001
+ },
1002
+ )
1003
+
1004
+ async def set_aux_direction(
1005
+ self, device: Device, port_id: str, direction: str
1006
+ ) -> None:
1007
+ """Switch an AUX port between ``INPUT`` and ``OUTPUT``."""
1008
+ if direction not in ("INPUT", "OUTPUT"):
1009
+ raise ValueError("direction must be INPUT or OUTPUT")
1010
+ await self._request(
1011
+ "POST",
1012
+ f"/api/auxcontroller/{device.device_type}/{device.serial}"
1013
+ f"/ports/{quote(port_id, safe='')}/setDirection",
1014
+ json={"direction": direction},
1015
+ )
1016
+
1017
+ async def bluetooth_connect(self, device: Device, address: str) -> None:
1018
+ """Connect ``device`` to an already paired Bluetooth device."""
1019
+ await self._request(
1020
+ "POST",
1021
+ f"/api/bluetooth/pair-sink/{device.device_type}/{device.serial}",
1022
+ json={"bluetoothDeviceAddress": address},
1023
+ )
1024
+
1025
+ async def bluetooth_disconnect(self, device: Device) -> None:
1026
+ """Disconnect the current Bluetooth device of ``device``."""
1027
+ await self._request(
1028
+ "POST",
1029
+ f"/api/bluetooth/disconnect-sink/{device.device_type}/{device.serial}",
1030
+ )
1031
+
1032
+ async def reboot(self, device: Device) -> None:
1033
+ """Restart ``device``."""
1034
+ await self._request(
1035
+ "POST",
1036
+ f"/v1/alexa/device/reboot/{device.device_type}/{device.serial}",
1037
+ json=self._query(device),
1038
+ bearer=True,
1039
+ app=True,
1040
+ )
1041
+
1042
+ # --------------------------------------------------------- media / voice
1043
+
1044
+ async def media_command(self, device: Device, command: str, **kwargs: Any) -> None:
1045
+ """Send a transport command.
1046
+
1047
+ Args:
1048
+ device: The target device.
1049
+ command: ``play``, ``pause``, ``next``, ``previous``, ``forward``,
1050
+ ``rewind``, ``shuffle`` or ``repeat``.
1051
+ **kwargs: ``enabled=bool`` for ``shuffle`` and ``repeat``.
1052
+
1053
+ """
1054
+ if command not in MEDIA_COMMANDS:
1055
+ raise ValueError(f"Unknown media command: {command}")
1056
+ body: dict[str, Any] = {"type": MEDIA_COMMANDS[command]}
1057
+ if command in ("shuffle", "repeat"):
1058
+ body[command] = bool(kwargs.get("enabled", True))
1059
+ await self._request(
1060
+ "POST", "/api/np/command", params=self._query(device), json=body
1061
+ )
1062
+
1063
+ async def _run(self, *nodes: dict[str, Any]) -> None:
1064
+ """Run behavior nodes one after another through the preview endpoint."""
1065
+ sequence = {
1066
+ "@type": f"{_NODE}Sequence",
1067
+ "startNode": {"@type": f"{_NODE}SerialNode", "nodesToExecute": list(nodes)},
1068
+ }
1069
+ await self._request(
1070
+ "POST",
1071
+ "/api/behaviors/preview",
1072
+ json={
1073
+ "behaviorId": "PREVIEW",
1074
+ "sequenceJson": jsonlib.dumps(sequence),
1075
+ "status": "ENABLED",
1076
+ },
1077
+ )
1078
+
1079
+ async def _node(self, device: Device, kind: str, **payload: Any) -> dict[str, Any]:
1080
+ customer_id, locale = await self._customer()
1081
+ return {
1082
+ "@type": f"{_NODE}OpaquePayloadOperationNode",
1083
+ "type": kind,
1084
+ "operationPayload": {
1085
+ **self._query(device),
1086
+ "locale": locale,
1087
+ "customerId": customer_id,
1088
+ **payload,
1089
+ },
1090
+ }
1091
+
1092
+ async def set_volume(self, device: Device, volume: int) -> None:
1093
+ """Set the speaker volume (0-100)."""
1094
+ if not 0 <= volume <= 100:
1095
+ raise ValueError("Volume must be between 0 and 100")
1096
+ await self._run(
1097
+ await self._node(device, "Alexa.DeviceControls.Volume", value=volume)
1098
+ )
1099
+
1100
+ async def stop(self, device: Device) -> None:
1101
+ """Stop whatever ``device`` is doing (audio, speech, alarms)."""
1102
+ await self._run(
1103
+ await self._node(
1104
+ device,
1105
+ "Alexa.DeviceControls.Stop",
1106
+ devices=[self._query(device)],
1107
+ skillId="amzn1.ask.1p.alexadevicecontrols",
1108
+ )
1109
+ )
1110
+
1111
+ async def speak(self, device: Device, text: str) -> None:
1112
+ """Make ``device`` say ``text``."""
1113
+ customer_id, _ = await self._customer()
1114
+ await self._run(
1115
+ await self._node(
1116
+ device,
1117
+ "Alexa.Speak",
1118
+ textToSpeak=text,
1119
+ target={
1120
+ "customerId": customer_id,
1121
+ "devices": [
1122
+ {
1123
+ "deviceSerialNumber": device.serial,
1124
+ "deviceTypeId": device.device_type,
1125
+ }
1126
+ ],
1127
+ },
1128
+ skillId="amzn1.ask.1p.saysomething",
1129
+ )
1130
+ )
1131
+
1132
+ async def _members(self, devices: list[Device]) -> list[Device]:
1133
+ """Expand speaker groups into their member devices."""
1134
+ result: dict[str, Device] = {}
1135
+ for device in devices:
1136
+ if not device.cluster_members:
1137
+ result[device.serial] = device
1138
+ continue
1139
+ if any(serial not in self._devices for serial in device.cluster_members):
1140
+ await self.get_devices()
1141
+ for serial in device.cluster_members:
1142
+ if serial in self._devices:
1143
+ result[serial] = self._devices[serial]
1144
+ return list(result.values())
1145
+
1146
+ async def announce(
1147
+ self, devices: list[Device], text: str, *, title: str | None = None
1148
+ ) -> None:
1149
+ """Announce ``text`` (chime + speech + on-screen card) on ``devices``."""
1150
+ targets = await self._members(devices)
1151
+ if not targets:
1152
+ raise ValueError("No device to announce on")
1153
+ customer_id, locale = await self._customer()
1154
+ await self._run(
1155
+ await self._node(
1156
+ targets[0],
1157
+ "AlexaAnnouncement",
1158
+ expireAfter="PT5S",
1159
+ content=[
1160
+ {
1161
+ "locale": locale,
1162
+ "display": {"title": title or "Home Assistant", "body": text},
1163
+ "speak": {"type": "text", "value": text},
1164
+ }
1165
+ ],
1166
+ target={
1167
+ "customerId": customer_id,
1168
+ "devices": [
1169
+ {
1170
+ "deviceSerialNumber": target.serial,
1171
+ "deviceTypeId": target.device_type,
1172
+ }
1173
+ for target in targets
1174
+ ],
1175
+ },
1176
+ skillId="amzn1.ask.1p.routines.messaging",
1177
+ )
1178
+ )
1179
+
1180
+ async def text_command(self, device: Device, text: str) -> None:
1181
+ """Run ``text`` as if it had been said to ``device``."""
1182
+ await self._run(
1183
+ await self._node(
1184
+ device, "Alexa.TextCommand", skillId="amzn1.ask.1p.tellalexa", text=text
1185
+ )
1186
+ )
1187
+
1188
+ async def play_sound(self, device: Device, sound_id: str) -> None:
1189
+ """Play a built-in sound (for example ``amzn_sfx_doorbell_chime_01``)."""
1190
+ await self._run(
1191
+ await self._node(
1192
+ device,
1193
+ "Alexa.Sound",
1194
+ soundStringId=sound_id,
1195
+ skillId="amzn1.ask.1p.sound",
1196
+ )
1197
+ )
1198
+
1199
+ async def play_music(self, device: Device, provider_id: str, phrase: str) -> None:
1200
+ """Play ``phrase`` from a music provider (see :meth:`get_music_providers`)."""
1201
+ await self._run(
1202
+ await self._node(
1203
+ device,
1204
+ "Alexa.Music.PlaySearchPhrase",
1205
+ searchPhrase=phrase,
1206
+ sanitizedSearchPhrase=phrase,
1207
+ musicProviderId=provider_id,
1208
+ )
1209
+ )
1210
+
1211
+ async def launch_skill(self, device: Device, skill_id: str) -> None:
1212
+ """Open a skill on ``device``."""
1213
+ await self._run(
1214
+ await self._node(
1215
+ device,
1216
+ "Alexa.Operation.SkillConnections.Launch",
1217
+ targetDevice={
1218
+ "deviceType": device.device_type,
1219
+ "deviceSerialNumber": device.serial,
1220
+ },
1221
+ connectionRequest={
1222
+ "uri": f"connection://AMAZON.Launch/{skill_id}",
1223
+ "input": {},
1224
+ },
1225
+ )
1226
+ )
1227
+
1228
+ async def run_routine(self, routine: Routine, device: Device | None = None) -> None:
1229
+ """Run a routine.
1230
+
1231
+ Args:
1232
+ routine: The routine to run.
1233
+ device: The device that stands in for "the device I spoke to" in
1234
+ routines triggered by voice. Routines that do not use it run
1235
+ fine without.
1236
+
1237
+ Raises:
1238
+ AmazonEchoNotSupportedError: The routine has no actions.
1239
+
1240
+ """
1241
+ start = _dig(routine.raw, "sequence", "startNode")
1242
+ if not start:
1243
+ raise AmazonEchoNotSupportedError(f"Routine {routine.name} has no actions")
1244
+ if device is not None:
1245
+ _, locale = await self._customer()
1246
+ start = _replace_placeholders(
1247
+ start,
1248
+ {
1249
+ "ALEXA_CURRENT_DSN": device.serial,
1250
+ "ALEXA_CURRENT_DEVICE_TYPE": device.device_type,
1251
+ "ALEXA_CURRENT_LOCALE": locale,
1252
+ },
1253
+ )
1254
+ await self._run(copy.deepcopy(start))
1255
+
1256
+ # ------------------------------------------ alarms / timers / reminders
1257
+
1258
+ async def _find_new(
1259
+ self, device: Device, kind: str, known: set[str]
1260
+ ) -> Notification:
1261
+ """Return the notification that appeared on ``device`` since ``known``."""
1262
+ candidates = [
1263
+ item
1264
+ for item in await self.get_notifications()
1265
+ if item.device_serial == device.serial
1266
+ and item.kind == kind
1267
+ and item.id not in known
1268
+ ]
1269
+ if not candidates:
1270
+ raise AmazonEchoResponseError(200, f"The new {kind} did not show up")
1271
+ return max(candidates, key=lambda item: item.raw.get("createdDate") or 0)
1272
+
1273
+ async def _alerts(self, method: str, path: str, body: dict[str, Any]) -> Any:
1274
+ """Call the app's alerts API, which takes the raw access token."""
1275
+ url = (await self.get_service_urls()).get("alexaApiUrl")
1276
+ if not url:
1277
+ raise AmazonEchoNotSupportedError("The account has no alerts API")
1278
+ return await self._request(
1279
+ method,
1280
+ f"{url}/v1/alerts/{path}",
1281
+ json=body,
1282
+ headers={"authorization": await self.async_get_access_token()},
1283
+ app=True,
1284
+ )
1285
+
1286
+ async def create_alarm(
1287
+ self,
1288
+ device: Device,
1289
+ when: datetime,
1290
+ *,
1291
+ label: str | None = None,
1292
+ recurrence: str | None = None,
1293
+ ) -> Notification:
1294
+ """Create an alarm.
1295
+
1296
+ Args:
1297
+ device: The device that rings.
1298
+ when: First ring. Aware datetimes are converted to the system time
1299
+ zone; Amazon reads the wall-clock time in the Echo's own zone.
1300
+ label: Not supported by Amazon for alarms; accepted and ignored.
1301
+ recurrence: ``DAILY``, ``WEEKDAYS``, ``WEEKENDS``, ``WEEKLY`` or a
1302
+ day list such as ``MO,WE,FR``.
1303
+
1304
+ """
1305
+ del label
1306
+ local = _local(when)
1307
+ trigger: dict[str, Any] = {"scheduledTime": local.isoformat(timespec="seconds")}
1308
+ if recurrence:
1309
+ trigger["recurrence"] = _recurrence_rule(recurrence, local)
1310
+ known = {item.id for item in await self.get_notifications()}
1311
+ await self._alerts(
1312
+ "POST",
1313
+ "alarms",
1314
+ {
1315
+ "trigger": trigger,
1316
+ "extensions": [],
1317
+ "endpointId": f"{device.serial}@{device.device_type}",
1318
+ },
1319
+ )
1320
+ return await self._find_new(device, "alarm", known)
1321
+
1322
+ async def create_reminder(
1323
+ self, device: Device, when: datetime, label: str
1324
+ ) -> Notification:
1325
+ """Create a reminder that ``device`` speaks at ``when``.
1326
+
1327
+ Aware datetimes are converted to the system time zone; Amazon reads
1328
+ the wall-clock time in the Echo's own zone.
1329
+ """
1330
+ local = _local(when)
1331
+ epoch = when.timestamp() if when.tzinfo else local.astimezone().timestamp()
1332
+ data = await self._request(
1333
+ "PUT",
1334
+ "/api/notifications/createReminder",
1335
+ json={
1336
+ "type": "Reminder",
1337
+ "status": "ON",
1338
+ "alarmTime": int(epoch * 1000),
1339
+ "originalTime": local.strftime("%H:%M:%S.000"),
1340
+ "originalDate": local.strftime("%Y-%m-%d"),
1341
+ "timeZoneId": None,
1342
+ "reminderIndex": None,
1343
+ "sound": None,
1344
+ **self._query(device),
1345
+ "recurringPattern": "",
1346
+ "alarmLabel": None,
1347
+ "reminderLabel": label,
1348
+ "isSaveInFlight": True,
1349
+ "id": "createReminder",
1350
+ "isRecurring": False,
1351
+ "createdDate": int(time.time() * 1000),
1352
+ },
1353
+ )
1354
+ if isinstance(data, dict) and data.get("id"):
1355
+ return parse_notification(data)
1356
+ raise AmazonEchoResponseError(200, "No reminder in the answer")
1357
+
1358
+ async def create_timer(
1359
+ self, device: Device, duration: timedelta, *, label: str | None = None
1360
+ ) -> Notification:
1361
+ """Start a timer on ``device``.
1362
+
1363
+ The request body follows the field names found in the Alexa app
1364
+ (``/v1/alerts/timers``); it has not been replayed against Amazon.
1365
+ """
1366
+ seconds = int(duration.total_seconds())
1367
+ if seconds <= 0:
1368
+ raise ValueError("The timer duration must be positive")
1369
+ known = {item.id for item in await self.get_notifications()}
1370
+ body: dict[str, Any] = {
1371
+ "duration": f"PT{seconds}S",
1372
+ "creationBehavior": {"displayExperience": {"visibility": "VISIBLE"}},
1373
+ "triggeringBehavior": {
1374
+ "operation": {"type": "NOTIFY_ONLY"},
1375
+ "notificationConfig": {"playAudible": True},
1376
+ },
1377
+ "endpointId": f"{device.serial}@{device.device_type}",
1378
+ }
1379
+ if label:
1380
+ body["timerLabel"] = label
1381
+ await self._alerts("POST", "timers", body)
1382
+ return await self._find_new(device, "timer", known)
1383
+
1384
+ async def delete_notification(self, notification: Notification) -> None:
1385
+ """Delete an alarm, timer or reminder."""
1386
+ await self._request(
1387
+ "DELETE",
1388
+ f"/api/notifications/{quote(notification.id, safe='')}",
1389
+ json=notification.raw or None,
1390
+ )
1391
+
1392
+ # ----------------------------------------------------------------- lists
1393
+
1394
+ async def _lists(
1395
+ self,
1396
+ method: str,
1397
+ path: str,
1398
+ *,
1399
+ json: Any = None,
1400
+ params: dict[str, str] | None = None,
1401
+ ) -> Any:
1402
+ return await self._request(
1403
+ method,
1404
+ f"/alexashoppinglists/api/v2/lists{path}",
1405
+ host=f"www.{self.credentials.domain}",
1406
+ json={} if json is None else json,
1407
+ params=params,
1408
+ )
1409
+
1410
+ async def get_lists(self) -> list[EchoList]:
1411
+ """Return the shopping, to-do and custom lists."""
1412
+ data = await self._lists("POST", "/fetch")
1413
+ return [
1414
+ EchoList(
1415
+ id=item["listId"],
1416
+ name=item.get("listName")
1417
+ or _LIST_NAMES.get(item.get("listType") or "", item["listId"]),
1418
+ kind=LIST_KINDS.get(item.get("listType") or "", "custom"),
1419
+ )
1420
+ for item in (data or {}).get("listInfoList") or []
1421
+ ]
1422
+
1423
+ async def get_list_items(self, list_id: str) -> list[ListItem]:
1424
+ """Return the items of a list (first 100)."""
1425
+ data = await self._lists(
1426
+ "POST", f"/{list_id}/items/fetch", params={"limit": "100"}
1427
+ )
1428
+ return [
1429
+ ListItem(
1430
+ id=item["itemId"],
1431
+ name=item.get("itemName") or "",
1432
+ completed=item.get("itemStatus") == "COMPLETE",
1433
+ version=int(item.get("version") or 1),
1434
+ )
1435
+ for item in (data or {}).get("itemInfoList") or []
1436
+ ]
1437
+
1438
+ async def add_list_item(self, list_id: str, name: str) -> None:
1439
+ """Add an item to a list."""
1440
+ await self._lists(
1441
+ "POST",
1442
+ f"/{list_id}/items",
1443
+ json={"items": [{"itemType": "KEYWORD", "itemName": name}]},
1444
+ )
1445
+
1446
+ async def update_list_item(
1447
+ self,
1448
+ list_id: str,
1449
+ item: ListItem,
1450
+ *,
1451
+ name: str | None = None,
1452
+ completed: bool | None = None,
1453
+ ) -> None:
1454
+ """Rename an item and/or mark it (not) done."""
1455
+ updates: list[dict[str, str]] = []
1456
+ if name is not None:
1457
+ updates.append({"type": "itemName", "value": name})
1458
+ if completed is not None:
1459
+ updates.append(
1460
+ {"type": "itemStatus", "value": "COMPLETE" if completed else "ACTIVE"}
1461
+ )
1462
+ if not updates:
1463
+ return
1464
+ await self._lists(
1465
+ "PUT",
1466
+ f"/{list_id}/items/{item.id}",
1467
+ params={"version": str(item.version)},
1468
+ json={"itemAttributesToUpdate": updates, "itemAttributesToRemove": []},
1469
+ )
1470
+
1471
+ async def delete_list_item(self, list_id: str, item: ListItem) -> None:
1472
+ """Delete an item from a list."""
1473
+ await self._lists(
1474
+ "DELETE",
1475
+ f"/{list_id}/items/{item.id}",
1476
+ params={"version": str(item.version)},
1477
+ )
1478
+
1479
+ # ------------------------------------------------ history / escape hatch
1480
+
1481
+ async def _privacy_csrf(self) -> str:
1482
+ """Return the anti-CSRF token of the privacy hub (cached for 12 h)."""
1483
+ if self._history_csrf and self._history_csrf[1] > time.monotonic():
1484
+ return self._history_csrf[0]
1485
+ page = await self._request(
1486
+ "GET",
1487
+ "/alexa-privacy/apd/rvh",
1488
+ host=f"www.{self.credentials.domain}",
1489
+ text=True,
1490
+ )
1491
+ match = _CSRF_META.search(page or "")
1492
+ if not match:
1493
+ raise AmazonEchoResponseError(200, "No csrf-token in the privacy page")
1494
+ self._history_csrf = (match.group(1), time.monotonic() + _HISTORY_CSRF_TTL)
1495
+ return match.group(1)
1496
+
1497
+ async def get_voice_history(
1498
+ self, *, since: datetime | None = None, limit: int = 10
1499
+ ) -> list[VoiceRecord]:
1500
+ """Return the latest voice interactions, newest first.
1501
+
1502
+ Args:
1503
+ since: Only return records after this moment (default: 24 h ago).
1504
+ limit: Maximum number of records.
1505
+
1506
+ """
1507
+ now = datetime.now(UTC)
1508
+ start = since or now - timedelta(days=1)
1509
+ if start.tzinfo is None:
1510
+ start = start.astimezone()
1511
+ host = f"www.{self.credentials.domain}"
1512
+ start_ms = int(start.timestamp() * 1000)
1513
+ end_ms = int(now.timestamp() * 1000)
1514
+ found: dict[str, VoiceRecord] = {} # Amazon repeats records across calls
1515
+ # Amazon serves 10 records per call, newest first. Its continuation
1516
+ # token is answered with HTTP 400, so older pages are fetched by
1517
+ # moving the end of the time window instead.
1518
+ for _ in range(_HISTORY_PAGES):
1519
+ data = await self._request(
1520
+ "POST",
1521
+ "/alexa-privacy/apd/rvh/customer-history-records-v2",
1522
+ host=host,
1523
+ params={
1524
+ "startTime": str(start_ms),
1525
+ "endTime": str(end_ms),
1526
+ "recordType": "VOICE_HISTORY",
1527
+ "maxRecordSize": "10",
1528
+ },
1529
+ json={"previousRequestToken": None},
1530
+ headers={
1531
+ "anti-csrftoken-a2z": await self._privacy_csrf(),
1532
+ "Referer": f"https://{host}/alexa-privacy/apd/rvh",
1533
+ },
1534
+ )
1535
+ page = (data or {}).get("customerHistoryRecords") or []
1536
+ for item in page:
1537
+ record = _parse_voice_record(item)
1538
+ if record is not None:
1539
+ found[record.id] = record
1540
+ stamps = [
1541
+ int(item["timestamp"])
1542
+ for item in page
1543
+ if isinstance(item.get("timestamp"), (int, float))
1544
+ ]
1545
+ more = (data or {}).get("encodedRequestToken")
1546
+ if not more or not stamps or len(found) >= limit:
1547
+ break
1548
+ end_ms = min(stamps) - 1
1549
+ if end_ms <= start_ms:
1550
+ break
1551
+ records = sorted(found.values(), key=lambda r: r.timestamp, reverse=True)
1552
+ return records[:limit]
1553
+
1554
+ async def call_feature(
1555
+ self,
1556
+ endpoint_id: str,
1557
+ feature: str,
1558
+ operation: str,
1559
+ *,
1560
+ instance: str | None = None,
1561
+ payload: dict[str, Any] | None = None,
1562
+ ) -> None:
1563
+ """Invoke a feature operation on any endpoint (GraphQL escape hatch).
1564
+
1565
+ Example: ``call_feature(endpoint_id, "power", "turnOn")``.
1566
+
1567
+ Raises:
1568
+ AmazonEchoResponseError: Amazon rejected the operation.
1569
+
1570
+ """
1571
+ control: dict[str, Any] = {
1572
+ "endpointId": endpoint_id,
1573
+ "featureName": feature,
1574
+ "featureOperationName": operation,
1575
+ }
1576
+ if instance is not None:
1577
+ control["instance"] = instance
1578
+ if payload is not None:
1579
+ control["payload"] = payload
1580
+ data = await self._graphql(
1581
+ MUTATION_SET_ENDPOINT_FEATURES,
1582
+ {"input": {"featureControlRequests": [control]}},
1583
+ )
1584
+ result = data.get("setEndpointFeatures") or {}
1585
+ if errors := result.get("errors"):
1586
+ raise AmazonEchoResponseError(
1587
+ 200,
1588
+ "; ".join(f"{e.get('code')}: {e.get('message')}" for e in errors),
1589
+ )
1590
+ if not result.get("featureControlResponses"):
1591
+ raise AmazonEchoResponseError(200, "No response to the feature operation")
1592
+
1593
+
1594
+ def _parse_voice_record(item: dict[str, Any]) -> VoiceRecord | None:
1595
+ """Build a :class:`VoiceRecord` from a privacy-hub history record."""
1596
+ kind = str(item.get("utteranceType") or "")
1597
+ if kind in _SKIPPED_UTTERANCES or kind.startswith("FALSE_WAKE_WORD"):
1598
+ return None
1599
+ timestamp = _from_ms(item.get("creationTimestamp") or item.get("timestamp"))
1600
+ key = str(item.get("recordKey") or "")
1601
+ if timestamp is None or not key:
1602
+ return None
1603
+ utterance: list[str] = []
1604
+ response: list[str] = []
1605
+ for part in item.get("voiceHistoryRecordItems") or []:
1606
+ text = (part.get("transcriptText") or "").strip()
1607
+ part_kind = part.get("recordItemType") or ""
1608
+ if not text:
1609
+ continue
1610
+ if part_kind in ("CUSTOMER_TRANSCRIPT", "ASR_REPLACEMENT_TEXT"):
1611
+ utterance.append(text)
1612
+ elif part_kind in ("ALEXA_RESPONSE", "TTS_REPLACEMENT_TEXT"):
1613
+ response.append(text)
1614
+ persons = item.get("personsInfo") or []
1615
+ person = persons[0] if isinstance(persons, list) and persons else {}
1616
+ # recordKey = customerId#timestamp#deviceType#serial
1617
+ parts = key.split("#")
1618
+ return VoiceRecord(
1619
+ id=key,
1620
+ timestamp=timestamp,
1621
+ device_serial=parts[3] if len(parts) > 3 else None,
1622
+ utterance=" ".join(utterance) or None,
1623
+ response=" ".join(response) or None,
1624
+ intent=item.get("intent") if item.get("intent") != "Unknown" else None,
1625
+ person=person.get("personFirstName") if isinstance(person, dict) else None,
1626
+ )