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.
@@ -0,0 +1,61 @@
1
+ """Async Python client for Amazon Echo / Alexa devices."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .auth import AuthorizeRequest, Credentials, build_authorize_url, register_device
6
+ from .client import AmazonEchoClient
7
+ from .exceptions import (
8
+ AmazonEchoAuthenticationError,
9
+ AmazonEchoConnectionError,
10
+ AmazonEchoConnectionTimeoutError,
11
+ AmazonEchoError,
12
+ AmazonEchoNotSupportedError,
13
+ AmazonEchoRateLimitError,
14
+ AmazonEchoResponseError,
15
+ )
16
+ from .local import LocalInfo, is_reachable, probe_local
17
+ from .models import (
18
+ Account,
19
+ AuxPort,
20
+ BluetoothDevice,
21
+ Device,
22
+ EchoList,
23
+ ListItem,
24
+ MediaState,
25
+ Notification,
26
+ Routine,
27
+ VoiceRecord,
28
+ )
29
+ from .push import PushClient, PushEvent
30
+
31
+ __version__ = "0.1.0"
32
+
33
+ __all__ = [
34
+ "Account",
35
+ "AmazonEchoAuthenticationError",
36
+ "AmazonEchoClient",
37
+ "AmazonEchoConnectionError",
38
+ "AmazonEchoConnectionTimeoutError",
39
+ "AmazonEchoError",
40
+ "AmazonEchoNotSupportedError",
41
+ "AmazonEchoRateLimitError",
42
+ "AmazonEchoResponseError",
43
+ "AuthorizeRequest",
44
+ "AuxPort",
45
+ "BluetoothDevice",
46
+ "Credentials",
47
+ "Device",
48
+ "EchoList",
49
+ "ListItem",
50
+ "LocalInfo",
51
+ "MediaState",
52
+ "Notification",
53
+ "PushClient",
54
+ "PushEvent",
55
+ "Routine",
56
+ "VoiceRecord",
57
+ "build_authorize_url",
58
+ "is_reachable",
59
+ "probe_local",
60
+ "register_device",
61
+ ]
@@ -0,0 +1,132 @@
1
+ """Command line interface: ``python -m amazon_echo <command>``.
2
+
3
+ Credentials live in a JSON file (``--credentials``, default
4
+ ``~/.config/amazon-echo/credentials.json``) that ``login`` creates.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import asyncio
11
+ from dataclasses import asdict, is_dataclass
12
+ import json
13
+ from pathlib import Path
14
+ import sys
15
+ from typing import Any
16
+
17
+ from .auth import Credentials, build_authorize_url, register_device
18
+ from .client import AmazonEchoClient
19
+ from .exceptions import AmazonEchoError
20
+ from .local import probe_local
21
+ from .push import PushClient, PushEvent
22
+
23
+ _DEFAULT_PATH = Path.home() / ".config" / "amazon-echo" / "credentials.json"
24
+ _READS = {
25
+ "account": "get_account",
26
+ "devices": "get_devices",
27
+ "states": "get_endpoint_states",
28
+ "volumes": "get_volumes",
29
+ "dnd": "get_dnd",
30
+ "bluetooth": "get_bluetooth",
31
+ "notifications": "get_notifications",
32
+ "routines": "get_routines",
33
+ "lists": "get_lists",
34
+ "history": "get_voice_history",
35
+ "providers": "get_music_providers",
36
+ }
37
+
38
+
39
+ def _plain(value: Any) -> Any:
40
+ if is_dataclass(value) and not isinstance(value, type):
41
+ data = asdict(value)
42
+ data.pop("raw", None)
43
+ return _plain(data)
44
+ if isinstance(value, dict):
45
+ return {str(k): _plain(v) for k, v in value.items()}
46
+ if isinstance(value, (list, tuple, set, frozenset)):
47
+ return [_plain(v) for v in value]
48
+ return value
49
+
50
+
51
+ def _dump(value: Any) -> None:
52
+ print(json.dumps(_plain(value), indent=2, ensure_ascii=False, default=str))
53
+
54
+
55
+ def _save(path: Path, credentials: Credentials) -> None:
56
+ path.parent.mkdir(parents=True, exist_ok=True)
57
+ path.write_text(json.dumps(credentials.to_dict()))
58
+ path.chmod(0o600)
59
+
60
+
61
+ def _build_parser() -> argparse.ArgumentParser:
62
+ parser = argparse.ArgumentParser(prog="amazon-echo", description=__doc__)
63
+ parser.add_argument("--credentials", type=Path, default=_DEFAULT_PATH)
64
+ sub = parser.add_subparsers(dest="command", required=True)
65
+ login = sub.add_parser("login", help="log in with your own browser")
66
+ login.add_argument("--language", default="en-US")
67
+ for name in _READS:
68
+ sub.add_parser(name)
69
+ sub.add_parser("push", help="print push events until interrupted")
70
+ probe = sub.add_parser("probe", help="ask an Echo on the LAN who it is")
71
+ probe.add_argument("host")
72
+ return parser
73
+
74
+
75
+ async def _login(args: argparse.Namespace) -> None:
76
+ request = build_authorize_url(language=args.language)
77
+ print("1. Open this URL in your browser and log in to Amazon:\n")
78
+ print(request.url)
79
+ print(
80
+ "\n2. The browser ends on a blank or 'page not found' page whose address "
81
+ "contains /ap/maplanding. Copy that address and paste it here."
82
+ )
83
+ redirect = input("\nURL: ")
84
+ credentials = await register_device(request, redirect)
85
+ _save(args.credentials, credentials)
86
+ print(f"Logged in to {credentials.domain}; saved to {args.credentials}")
87
+
88
+
89
+ async def _push(client: AmazonEchoClient) -> None:
90
+ def on_event(event: PushEvent) -> None:
91
+ print(event.command, event.device_serial, json.dumps(event.payload)[:200])
92
+
93
+ push = PushClient(client, on_event, on_state=lambda up: print("connected:", up))
94
+ await push.start()
95
+ try:
96
+ await asyncio.Event().wait()
97
+ finally:
98
+ await push.stop()
99
+
100
+
101
+ async def _run(args: argparse.Namespace) -> None:
102
+ if args.command == "login":
103
+ await _login(args)
104
+ return
105
+ if args.command == "probe":
106
+ _dump(await probe_local(args.host))
107
+ return
108
+ credentials = Credentials.from_dict(json.loads(args.credentials.read_text()))
109
+ async with AmazonEchoClient(
110
+ credentials, on_credentials_update=lambda c: _save(args.credentials, c)
111
+ ) as client:
112
+ if args.command == "push":
113
+ await _push(client)
114
+ else:
115
+ _dump(await getattr(client, _READS[args.command])())
116
+
117
+
118
+ def main() -> None:
119
+ """Run the command line interface."""
120
+ args = _build_parser().parse_args()
121
+ try:
122
+ asyncio.run(_run(args))
123
+ except KeyboardInterrupt:
124
+ pass
125
+ except FileNotFoundError:
126
+ sys.exit(f"No credentials at {args.credentials}; run `amazon-echo login`")
127
+ except AmazonEchoError as err:
128
+ sys.exit(f"error: {err}")
129
+
130
+
131
+ if __name__ == "__main__":
132
+ main()
amazon_echo/auth.py ADDED
@@ -0,0 +1,404 @@
1
+ """Credentials, token refresh and the external-browser login flow.
2
+
3
+ Nothing here ever sees the Amazon password: the user logs in in their own
4
+ browser (passkeys, 2FA and captchas just work) and pastes the URL the browser
5
+ ended on. That URL carries a one-time authorization code which is exchanged for
6
+ a device registration (refresh token + cookies).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import base64
12
+ from dataclasses import asdict, dataclass, field
13
+ import hashlib
14
+ import json
15
+ import secrets
16
+ import time
17
+ from typing import Any
18
+ from urllib.parse import parse_qs, urlencode, urlsplit
19
+ import uuid
20
+
21
+ import aiohttp
22
+
23
+ from .const import (
24
+ APP_BUNDLE_ID,
25
+ APP_DEVICE_TYPE,
26
+ APP_NAME,
27
+ APP_OS_VERSION,
28
+ APP_SOFTWARE_VERSION,
29
+ APP_USER_AGENT,
30
+ APP_VERSION,
31
+ AUTH_HOST,
32
+ REGION_BY_DOMAIN,
33
+ SDK_VERSION,
34
+ )
35
+ from .exceptions import (
36
+ AmazonEchoAuthenticationError,
37
+ AmazonEchoConnectionError,
38
+ AmazonEchoConnectionTimeoutError,
39
+ AmazonEchoRateLimitError,
40
+ AmazonEchoResponseError,
41
+ )
42
+
43
+ _TIMEOUT = aiohttp.ClientTimeout(total=30)
44
+ _LOGIN_SITE = "https://www.amazon.com"
45
+ _CODE_PARAM = "openid.oa2.authorization_code"
46
+ _TERMINAL_ERRORS = ("invalid_grant", "invalid_token", "unauthorized_client")
47
+
48
+
49
+ def region_for_domain(domain: str) -> str:
50
+ """Return the push region ("NA", "EU" or "FE") of a retail domain."""
51
+ return REGION_BY_DOMAIN.get(domain, "EU")
52
+
53
+
54
+ @dataclass(slots=True)
55
+ class Credentials:
56
+ """Everything needed to talk to the Alexa cloud for one account."""
57
+
58
+ domain: str
59
+ refresh_token: str
60
+ cookies: dict[str, str] = field(default_factory=dict)
61
+ serial: str | None = None
62
+ access_token: str | None = None
63
+ access_token_expires: float = 0.0
64
+ customer_id: str | None = None
65
+ customer_name: str | None = None
66
+ email: str | None = None
67
+ home_region: str | None = None
68
+ source: str = "browser"
69
+
70
+ def to_dict(self) -> dict[str, Any]:
71
+ """Return a JSON-serializable dict."""
72
+ return asdict(self)
73
+
74
+ @classmethod
75
+ def from_dict(cls, data: dict[str, Any]) -> Credentials:
76
+ """Build credentials from :meth:`to_dict` output."""
77
+ names = cls.__dataclass_fields__
78
+ return cls(**{k: v for k, v in data.items() if k in names})
79
+
80
+ @classmethod
81
+ def from_alexa_media(
82
+ cls,
83
+ entry_data: dict[str, Any],
84
+ cookies: list[dict[str, Any]] | dict[str, str],
85
+ ) -> Credentials:
86
+ """Build credentials from an ``alexa_media`` config entry and its cookies.
87
+
88
+ Args:
89
+ entry_data: The ``data`` of the ``alexa_media`` config entry.
90
+ cookies: The ``cookies`` list of
91
+ ``.storage/alexa_media.<email>.cookies`` or a name → value dict.
92
+
93
+ Raises:
94
+ AmazonEchoAuthenticationError: The entry holds no refresh token.
95
+
96
+ """
97
+ domain = str(entry_data.get("url") or "amazon.com").lower()
98
+ domain = domain.removeprefix("https://").removeprefix("www.").strip("/")
99
+ if not domain.startswith("amazon."):
100
+ domain = f"amazon.{domain}"
101
+ oauth = entry_data.get("oauth") or {}
102
+ if not oauth.get("refresh_token"):
103
+ raise AmazonEchoAuthenticationError(
104
+ "alexa_media entry has no refresh token"
105
+ )
106
+ if isinstance(cookies, dict):
107
+ jar = dict(cookies)
108
+ else:
109
+ jar = {
110
+ c["name"]: c["value"]
111
+ for c in cookies
112
+ if domain.endswith(str(c.get("domain") or domain).lstrip("."))
113
+ }
114
+ return cls(
115
+ domain=domain,
116
+ refresh_token=oauth["refresh_token"],
117
+ cookies=jar,
118
+ access_token=oauth.get("access_token"),
119
+ # alexa_media stores the expiry as an epoch timestamp
120
+ access_token_expires=float(oauth.get("expires_in") or 0.0),
121
+ email=entry_data.get("email"),
122
+ home_region=region_for_domain(domain),
123
+ source="alexa_media",
124
+ )
125
+
126
+
127
+ @dataclass(slots=True)
128
+ class AuthorizeRequest:
129
+ """A pending external-browser login."""
130
+
131
+ url: str
132
+ serial: str
133
+ code_verifier: str
134
+
135
+
136
+ def _client_id(serial: str) -> str:
137
+ return f"{serial}#{APP_DEVICE_TYPE}".encode().hex()
138
+
139
+
140
+ def build_authorize_url(*, language: str = "en-US") -> AuthorizeRequest:
141
+ """Return the URL the user has to open in a browser to log in.
142
+
143
+ The login always starts on amazon.com; the account's own marketplace is
144
+ discovered after the registration.
145
+ """
146
+ serial = uuid.uuid4().hex.upper()
147
+ verifier = base64.urlsafe_b64encode(secrets.token_bytes(32)).rstrip(b"=")
148
+ challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier).digest()).rstrip(b"=")
149
+ params = {
150
+ "openid.return_to": f"{_LOGIN_SITE}/ap/maplanding",
151
+ "openid.oa2.code_challenge_method": "S256",
152
+ "openid.assoc_handle": "amzn_dp_project_dee_ios",
153
+ "openid.identity": "http://specs.openid.net/auth/2.0/identifier_select",
154
+ "pageId": "amzn_dp_project_dee_ios",
155
+ "accountStatusPolicy": "P1",
156
+ "openid.claimed_id": "http://specs.openid.net/auth/2.0/identifier_select",
157
+ "openid.mode": "checkid_setup",
158
+ "openid.ns.oa2": "http://www.amazon.com/ap/ext/oauth/2",
159
+ "openid.oa2.client_id": f"device:{_client_id(serial)}",
160
+ "language": language,
161
+ "openid.ns.pape": "http://specs.openid.net/extensions/pape/1.0",
162
+ "openid.oa2.code_challenge": challenge.decode(),
163
+ "openid.oa2.scope": "device_auth_access",
164
+ "openid.ns": "http://specs.openid.net/auth/2.0",
165
+ "openid.pape.max_auth_age": "0",
166
+ "openid.oa2.response_type": "code",
167
+ }
168
+ return AuthorizeRequest(
169
+ url=f"{_LOGIN_SITE}/ap/signin?{urlencode(params)}",
170
+ serial=serial,
171
+ code_verifier=verifier.decode(),
172
+ )
173
+
174
+
175
+ async def _post_auth(
176
+ session: aiohttp.ClientSession,
177
+ path: str,
178
+ *,
179
+ form: dict[str, str] | None = None,
180
+ body: dict[str, Any] | None = None,
181
+ ) -> dict[str, Any]:
182
+ """POST to api.amazon.com and return the decoded JSON answer."""
183
+ headers = {
184
+ "User-Agent": APP_USER_AGENT,
185
+ "Accept": "application/json",
186
+ "x-amzn-identity-auth-domain": AUTH_HOST,
187
+ }
188
+ try:
189
+ async with session.post(
190
+ f"https://{AUTH_HOST}{path}",
191
+ data=form,
192
+ json=body,
193
+ headers=headers,
194
+ timeout=_TIMEOUT,
195
+ ) as resp:
196
+ status = resp.status
197
+ text = await resp.text()
198
+ except TimeoutError as err:
199
+ raise AmazonEchoConnectionTimeoutError(f"Timeout calling {path}") from err
200
+ except aiohttp.ClientError as err:
201
+ raise AmazonEchoConnectionError(f"Cannot reach {AUTH_HOST}: {err}") from err
202
+ try:
203
+ data = json.loads(text)
204
+ except ValueError:
205
+ data = None
206
+ if status == 200 and isinstance(data, dict):
207
+ return data
208
+ if status in (429, 503):
209
+ raise AmazonEchoRateLimitError(f"{path} answered HTTP {status}")
210
+ message = _error_message(data)
211
+ if status in (400, 401, 403):
212
+ # Never echo the body: it can contain the tokens that were sent.
213
+ raise AmazonEchoAuthenticationError(f"{path} refused: {message}")
214
+ raise AmazonEchoResponseError(status, message)
215
+
216
+
217
+ def _error_message(data: Any) -> str:
218
+ if not isinstance(data, dict):
219
+ return "unexpected answer"
220
+ error = data.get("response", {}).get("error") or data
221
+ code = error.get("code") or error.get("error") or "error"
222
+ text = error.get("message") or error.get("error_description") or ""
223
+ return f"{code}: {text}".strip(": ")
224
+
225
+
226
+ def _token_form(credentials: Credentials, kind: str) -> dict[str, str]:
227
+ return {
228
+ "app_name": APP_NAME,
229
+ "app_version": APP_VERSION,
230
+ "di.sdk.version": SDK_VERSION,
231
+ "source_token": credentials.refresh_token,
232
+ "package_name": APP_BUNDLE_ID,
233
+ "di.hw.version": "iPhone",
234
+ "platform": "iOS",
235
+ "requested_token_type": kind,
236
+ "source_token_type": "refresh_token",
237
+ "di.os.name": "iOS",
238
+ "di.os.version": APP_OS_VERSION,
239
+ "current_version": SDK_VERSION,
240
+ "previous_version": SDK_VERSION,
241
+ "domain": f"www.{credentials.domain}",
242
+ }
243
+
244
+
245
+ async def refresh_access_token(
246
+ session: aiohttp.ClientSession, credentials: Credentials
247
+ ) -> None:
248
+ """Fetch a new access token and store it in ``credentials``.
249
+
250
+ Raises:
251
+ AmazonEchoAuthenticationError: The refresh token was rejected.
252
+
253
+ """
254
+ data = await _post_auth(
255
+ session, "/auth/token", form=_token_form(credentials, "access_token")
256
+ )
257
+ token = data.get("access_token")
258
+ if not token:
259
+ raise AmazonEchoAuthenticationError("No access token in the answer")
260
+ credentials.access_token = token
261
+ credentials.access_token_expires = time.time() + float(
262
+ data.get("expires_in") or 3600
263
+ )
264
+
265
+
266
+ async def exchange_cookies(
267
+ session: aiohttp.ClientSession, credentials: Credentials
268
+ ) -> None:
269
+ """Trade the refresh token for fresh website cookies of the account domain.
270
+
271
+ The ``csrf`` cookie is not part of the exchange; the one already stored is
272
+ kept (the Alexa site hands out a new one when it is missing).
273
+
274
+ Raises:
275
+ AmazonEchoAuthenticationError: The refresh token was rejected.
276
+
277
+ """
278
+ data = await _post_auth(
279
+ session, "/auth/token", form=_token_form(credentials, "auth_cookies")
280
+ )
281
+ by_domain = data.get("response", {}).get("tokens", {}).get("cookies") or {}
282
+ fresh = {
283
+ cookie["Name"]: str(cookie["Value"]).replace('"', "")
284
+ for cookies in by_domain.values()
285
+ for cookie in cookies
286
+ }
287
+ if not fresh:
288
+ raise AmazonEchoAuthenticationError("No cookies in the answer")
289
+ credentials.cookies = {**credentials.cookies, **fresh}
290
+
291
+
292
+ async def register_device(
293
+ request: AuthorizeRequest,
294
+ redirect_url: str,
295
+ *,
296
+ session: aiohttp.ClientSession | None = None,
297
+ ) -> Credentials:
298
+ """Exchange the redirect URL of a finished login for credentials.
299
+
300
+ Args:
301
+ request: What :func:`build_authorize_url` returned.
302
+ redirect_url: The full URL the browser ended on
303
+ (``…/ap/maplanding?…openid.oa2.authorization_code=…``).
304
+ session: Optional aiohttp session to use.
305
+
306
+ Raises:
307
+ AmazonEchoAuthenticationError: The URL carries no authorization code or
308
+ Amazon refused the registration.
309
+
310
+ """
311
+ codes = parse_qs(urlsplit(redirect_url.strip()).query).get(_CODE_PARAM)
312
+ if not codes:
313
+ raise AmazonEchoAuthenticationError(
314
+ "The pasted URL has no authorization code; copy the address of the "
315
+ "page the browser ended on (it contains /ap/maplanding)"
316
+ )
317
+ body = {
318
+ "requested_extensions": ["device_info", "customer_info"],
319
+ "cookies": {"website_cookies": [], "domain": ".amazon.com"},
320
+ "registration_data": {
321
+ "domain": "Device",
322
+ "app_version": APP_VERSION,
323
+ "device_type": APP_DEVICE_TYPE,
324
+ "device_name": f"%FIRST_NAME%'s%DUPE_STRATEGY_1ST%{APP_NAME}",
325
+ "os_version": APP_OS_VERSION,
326
+ "device_serial": request.serial,
327
+ "device_model": "iPhone",
328
+ "app_name": APP_NAME,
329
+ "software_version": APP_SOFTWARE_VERSION,
330
+ },
331
+ "auth_data": {
332
+ "use_global_authentication": "true",
333
+ "client_id": _client_id(request.serial),
334
+ "authorization_code": codes[0],
335
+ "code_verifier": request.code_verifier,
336
+ "code_algorithm": "SHA-256",
337
+ "client_domain": "DeviceLegacy",
338
+ },
339
+ "user_context_map": {
340
+ "frc": base64.b64encode(secrets.token_bytes(313)).decode().rstrip("=")
341
+ },
342
+ "requested_token_type": [
343
+ "bearer",
344
+ "mac_dms",
345
+ "website_cookies",
346
+ "store_authentication_cookie",
347
+ ],
348
+ }
349
+ own_session = session is None
350
+ session = session or aiohttp.ClientSession()
351
+ try:
352
+ data = await _post_auth(session, "/auth/register", body=body)
353
+ try:
354
+ success = data["response"]["success"]
355
+ bearer = success["tokens"]["bearer"]
356
+ customer = success.get("extensions", {}).get("customer_info") or {}
357
+ credentials = Credentials(
358
+ domain="amazon.com",
359
+ refresh_token=bearer["refresh_token"],
360
+ cookies={
361
+ c["Name"]: str(c["Value"]).replace('"', "")
362
+ for c in success["tokens"].get("website_cookies") or []
363
+ },
364
+ serial=request.serial,
365
+ access_token=bearer["access_token"],
366
+ access_token_expires=time.time() + float(bearer["expires_in"]),
367
+ customer_id=customer.get("user_id"),
368
+ customer_name=customer.get("name") or customer.get("given_name"),
369
+ home_region=customer.get("home_region"),
370
+ )
371
+ except (KeyError, TypeError, ValueError) as err:
372
+ raise AmazonEchoAuthenticationError(
373
+ f"Registration refused: {_error_message(data)}"
374
+ ) from err
375
+ await _finish_registration(session, credentials)
376
+ finally:
377
+ if own_session:
378
+ await session.close()
379
+ return credentials
380
+
381
+
382
+ async def _finish_registration(
383
+ session: aiohttp.ClientSession, credentials: Credentials
384
+ ) -> None:
385
+ """Move the session to the account's own marketplace and fill the profile."""
386
+ from .client import AmazonEchoClient # noqa: PLC0415 - import cycle
387
+
388
+ client = AmazonEchoClient(credentials, session=session)
389
+ if credentials.home_region == "FE":
390
+ host = "alexa.amazon.co.jp"
391
+ else:
392
+ welcome = await client.request("GET", "/api/welcome")
393
+ host = (welcome or {}).get("alexaHostName") or "alexa.amazon.com"
394
+ domain = host.removeprefix("alexa.")
395
+ if domain != credentials.domain:
396
+ credentials.domain = domain
397
+ credentials.cookies.pop("csrf", None)
398
+ await exchange_cookies(session, credentials)
399
+ client = AmazonEchoClient(credentials, session=session)
400
+ credentials.home_region = credentials.home_region or region_for_domain(domain)
401
+ account = await client.get_account()
402
+ credentials.email = account.email
403
+ credentials.customer_id = account.customer_id
404
+ credentials.customer_name = credentials.customer_name or account.name