pyalexaalerts 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,31 @@
1
+ """An unofficial client for Amazon Alexa alarms, reminders and timers."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ from .api import AlexaAPI
6
+ from .exception import (
7
+ AlexaAPIError,
8
+ AlexaSessionExpiredException,
9
+ DeviceNotFoundException,
10
+ NotificationNotFoundException,
11
+ )
12
+ from .manager import AlexaAlerts
13
+ from .resource import Alarm, Device, Item, Kind, Recurrence, Reminder, Sound, Task, Timer
14
+
15
+ __all__ = [
16
+ "Alarm",
17
+ "AlexaAPI",
18
+ "AlexaAPIError",
19
+ "AlexaAlerts",
20
+ "AlexaSessionExpiredException",
21
+ "Device",
22
+ "DeviceNotFoundException",
23
+ "Item",
24
+ "Kind",
25
+ "NotificationNotFoundException",
26
+ "Recurrence",
27
+ "Reminder",
28
+ "Sound",
29
+ "Task",
30
+ "Timer",
31
+ ]
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
pyalexaalerts/api.py ADDED
@@ -0,0 +1,306 @@
1
+ import base64
2
+ import json
3
+ import logging
4
+ import time as _time
5
+ import urllib.parse
6
+ import uuid
7
+ from pathlib import Path
8
+
9
+ import requests
10
+
11
+ from .auth import APP_VERSION, AlexaAuth
12
+ from .exception import AlexaAPIError
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+ USER_AGENT = (
17
+ f"PitanguiBridge/{APP_VERSION}-[PLATFORM=Android][MANUFACTURER=Google][RELEASE=11]"
18
+ "[BRAND=google][SDK=30][MODEL=sdk_gphone_x86_64]"
19
+ )
20
+ ALERTS_BASE = "https://api.amazonalexa.com/v1/alerts/alarms"
21
+ PROFILE_URL = "https://api.amazon.com/user/profile"
22
+ ALEXA_APP_HEADER = base64.b64encode(json.dumps(
23
+ {"appId": "amzn1.application.d8248c711e884e7baf99e6b37c7c28b0", "version": "1.0", "appVersion": "2022.10.10"},
24
+ separators=(",", ":"),
25
+ ).encode()).decode()
26
+
27
+ # Web API host per Amazon domain. Only na-api-alexa.amazon.com has been verified against real traffic.
28
+ WEB_HOSTS = {
29
+ "amazon.com": "na-api-alexa.amazon.com",
30
+ "amazon.ca": "na-api-alexa.amazon.com",
31
+ "amazon.com.mx": "na-api-alexa.amazon.com",
32
+ "amazon.com.br": "na-api-alexa.amazon.com",
33
+ "amazon.co.uk": "eu-api-alexa.amazon.co.uk",
34
+ "amazon.de": "eu-api-alexa.amazon.co.uk",
35
+ "amazon.fr": "eu-api-alexa.amazon.co.uk",
36
+ "amazon.it": "eu-api-alexa.amazon.co.uk",
37
+ "amazon.es": "eu-api-alexa.amazon.co.uk",
38
+ "amazon.in": "eu-api-alexa.amazon.co.uk",
39
+ "amazon.co.jp": "fe-api-alexa.amazon.co.jp",
40
+ "amazon.com.au": "fe-api-alexa.amazon.co.jp",
41
+ }
42
+
43
+ # Paths that set the `csrf` cookie when fetched with valid session cookies; tried in order.
44
+ _CSRF_BOOTSTRAP_PATHS = ("/api/language", "/api/devices-v2/device?cached=false", "/spa/index.html")
45
+
46
+ TEXT_COMMAND_SKILL = "amzn1.ask.1p.tellalexa"
47
+
48
+
49
+ class _AmazonSession(requests.Session):
50
+
51
+ def request(self, method, url, **kwargs) -> requests.Response:
52
+ kwargs.setdefault("headers", {})["x-amzn-RequestId"] = str(uuid.uuid4())
53
+ kwargs.setdefault("timeout", 30)
54
+ return super().request(method, url, **kwargs)
55
+
56
+
57
+ def _json(response: requests.Response) -> "dict | list | None":
58
+ if not response.text:
59
+ return None
60
+ try:
61
+ return response.json()
62
+ except requests.exceptions.JSONDecodeError:
63
+ if "api-services-support@amazon.com" in response.text:
64
+ logger.warning("Alexa returned an automated-access block page. Re-run the cookie login on this machine.")
65
+ else:
66
+ logger.warning("Invalid JSON from Alexa (HTTP %d): %s", response.status_code, response.text[:200])
67
+ return None
68
+
69
+
70
+ RATE_LIMIT_DELAYS = (2.0, 4.0, 8.0) # seconds to wait before each retry after HTTP 429
71
+
72
+
73
+ def _retry_after(response) -> "float | None":
74
+ """The server's Retry-After in seconds (capped at 30), if it sent a number."""
75
+ try:
76
+ return min(float((getattr(response, "headers", None) or {}).get("Retry-After")), 30.0)
77
+ except (TypeError, ValueError):
78
+ return None
79
+
80
+
81
+ def _log_exchange(method: str, path: str, kwargs: dict, response) -> None:
82
+ """With -vv: request/response bodies (never headers, which hold tokens and cookies)."""
83
+ if logger.isEnabledFor(logging.DEBUG):
84
+ sent = json.dumps(kwargs["json"]) if "json" in kwargs else ""
85
+ logger.debug("%s %s -> HTTP %s\n sent: %.4000s\n got: %.4000s",
86
+ method, path, response.status_code, sent, getattr(response, "text", ""))
87
+
88
+
89
+ class AlexaAPI:
90
+ """Raw access to Alexa alarms, reminders, timers, devices, sounds and text commands."""
91
+
92
+ def __init__(
93
+ self,
94
+ amazon_domain: str = "amazon.com",
95
+ service_auth_path: "Path | str | None" = None,
96
+ runtime_creds_path: "Path | str | None" = None,
97
+ alexa_host: "str | None" = None,
98
+ person_id: "str | None" = None,
99
+ locale: str = "en-US",
100
+ ) -> None:
101
+ self._host = alexa_host or WEB_HOSTS.get(amazon_domain, f"alexa.{amazon_domain}")
102
+ self._base = f"https://{self._host}"
103
+ self.locale = locale
104
+ self._session = _AmazonSession()
105
+ self._session.headers.update({
106
+ "Accept": "application/json; charset=utf-8",
107
+ "Accept-Language": locale,
108
+ "User-Agent": USER_AGENT,
109
+ })
110
+ self._auth = AlexaAuth(self._session, amazon_domain, service_auth_path, runtime_creds_path)
111
+ self._csrf: str | None = None
112
+ self._person_id = person_id
113
+
114
+ def _cookie(self, name: str) -> "str | None":
115
+ return next((c.value for c in self._session.cookies if c.name == name), None)
116
+
117
+ def _ensure_csrf(self) -> "str | None":
118
+ if self._csrf:
119
+ return self._csrf
120
+ token = self._cookie("csrf")
121
+ for path in _CSRF_BOOTSTRAP_PATHS:
122
+ if token:
123
+ break
124
+ try:
125
+ self._session.get(self._base + path)
126
+ except requests.RequestException as e:
127
+ logger.debug("csrf bootstrap %s failed: %s", path, e)
128
+ token = self._cookie("csrf")
129
+ if not token:
130
+ logger.warning("Could not obtain a csrf token from %s; changes will likely fail", self._host)
131
+ self._csrf = token
132
+ return token
133
+
134
+ def _send(self, method: str, url: str, label: str, headers: dict, kwargs: dict) -> requests.Response:
135
+ """Send one request. On HTTP 429 (rate limited, so nothing was done) wait and retry, a few times."""
136
+ for delay in (*RATE_LIMIT_DELAYS, None):
137
+ response = self._session.request(method, url, headers=headers, **kwargs)
138
+ _log_exchange(method, label, kwargs, response)
139
+ if response.status_code != 429 or delay is None:
140
+ return response
141
+ wait = _retry_after(response) or delay
142
+ logger.warning("%s %s: Alexa is rate limiting requests (HTTP 429); retrying in %g s", method, label, wait)
143
+ _time.sleep(wait)
144
+ raise AssertionError("unreachable")
145
+
146
+ def _web(self, method: str, path: str, *, _retried: bool = False, **kwargs) -> requests.Response:
147
+ self._auth.check_expiry()
148
+ headers = kwargs.pop("headers", {})
149
+ csrf = self._ensure_csrf()
150
+ if csrf:
151
+ headers["csrf"] = csrf
152
+ if "json" in kwargs:
153
+ headers["Content-Type"] = "application/json; charset=utf-8"
154
+ response = self._send(method, self._base + path, path, headers, kwargs)
155
+ if response.status_code in (401, 403) and not _retried:
156
+ logger.info("%s %s returned HTTP %d; refreshing cookies and retrying", method, path, response.status_code)
157
+ if self._auth.refresh():
158
+ self._csrf = None
159
+ return self._web(method, path, _retried=True, headers=headers, **kwargs)
160
+ if not response.ok:
161
+ raise AlexaAPIError(method, path, response.status_code, response.text)
162
+ return response
163
+
164
+ def _alerts(self, method: str, path: str = "", *, _retried: bool = False, **kwargs) -> requests.Response:
165
+ headers = {
166
+ "authorization": self._auth.access_token(force=_retried),
167
+ "x-amzn-alexa-app": ALEXA_APP_HEADER,
168
+ "x-amzn-aaas-skip-region-check": "1p-trusted",
169
+ "cache-control": "no-cache",
170
+ }
171
+ if "json" in kwargs:
172
+ headers["Content-Type"] = "application/json; charset=utf-8"
173
+ url = path if path.startswith("https://") else ALERTS_BASE + path
174
+ response = self._send(method, url, url, headers, kwargs)
175
+ if response.status_code in (401, 403) and not _retried:
176
+ logger.info("%s %s returned HTTP %d; minting a new access token and retrying", method, url, response.status_code)
177
+ return self._alerts(method, path, _retried=True, **kwargs)
178
+ if not response.ok:
179
+ raise AlexaAPIError(method, url, response.status_code, response.text)
180
+ return response
181
+
182
+ @property
183
+ def personId(self) -> str:
184
+ """The account's `amzn1.account.…` id, needed by the reminders/timers endpoints."""
185
+ if self._person_id:
186
+ return self._person_id
187
+ pid = self._auth.config_value("person_id") or self._lookup_person_id()
188
+ if not pid:
189
+ raise LookupError(
190
+ "Could not determine your Amazon account id. Add it to service_auth.json as "
191
+ "alexa.person_id (it looks like amzn1.account.XXXX), or pass --person-id."
192
+ )
193
+ self._person_id = pid
194
+ return pid
195
+
196
+ def _lookup_person_id(self) -> "str | None":
197
+ try:
198
+ r = self._session.get(PROFILE_URL, headers={"Authorization": f"Bearer {self._auth.access_token()}"})
199
+ if r.ok and str(r.json().get("user_id", "")).startswith("amzn1.account."):
200
+ pid = r.json()["user_id"]
201
+ self._auth.cache_value("person_id", pid)
202
+ return pid
203
+ logger.debug("profile lookup returned HTTP %d", r.status_code)
204
+ except Exception as e: # noqa: BLE001 - best effort
205
+ logger.debug("profile lookup failed: %s", e)
206
+ try:
207
+ data = _json(self._web("GET", "/api/notifications?notificationType=REMINDER&clientType=VOX")) or {}
208
+ for n in data.get("notifications", []):
209
+ pid = (n.get("personProfile") or {}).get("personId")
210
+ if pid:
211
+ self._auth.cache_value("person_id", pid)
212
+ return pid
213
+ except AlexaAPIError as e:
214
+ logger.debug("reminder list without personId failed: %s", e)
215
+ return None
216
+
217
+ def getDevices(self) -> list[dict]:
218
+ data = _json(self._web("GET", "/api/devices-v2/device?cached=false")) or {}
219
+ return data.get("devices", [])
220
+
221
+ def getSounds(self, serial: str, device_type: str, alert_type: str = "Alarm") -> list[dict]:
222
+ q = urllib.parse.urlencode({"deviceType": device_type, "deviceSerialNumber": serial})
223
+ data = _json(self._web("GET", f"/api/notification/sounds?{q}&softwareVersion=%27%27&alertType={alert_type}")) or {}
224
+ return data.get("notificationSounds", [])
225
+
226
+ def getDefaultSound(self, serial: str, device_type: str, notification_type: str = "Alarm") -> "dict | None":
227
+ q = urllib.parse.urlencode({"deviceType": device_type, "deviceSerialNumber": serial})
228
+ return _json(self._web(
229
+ "GET", f"/api/notification/default-sound?{q}&notificationType={notification_type}"))
230
+
231
+ def getAlarms(self) -> list[dict]:
232
+ alarms, url, seen = [], "?maxResults=200", set()
233
+ while url and url not in seen:
234
+ seen.add(url)
235
+ data = _json(self._alerts("GET", url)) or {}
236
+ alarms += data.get("alarms", [])
237
+ nxt = (data.get("links") or {}).get("next")
238
+ if not nxt:
239
+ break
240
+ url = nxt if nxt.startswith(("https://", "?")) else (
241
+ "https://api.amazonalexa.com" + nxt if nxt.startswith("/") else None)
242
+ return alarms
243
+
244
+ def createAlarm(self, body: dict) -> "dict | None":
245
+ return _json(self._alerts("POST", json=body))
246
+
247
+ def updateAlarm(self, token: str, body: dict) -> "dict | None":
248
+ return _json(self._alerts("PUT", f"/{token}", json=body))
249
+
250
+ def activateAlarm(self, token: str, body: dict) -> "dict | None":
251
+ return _json(self._alerts("PUT", f"/{token}/activate", json=body))
252
+
253
+ def cancelAlarm(self, token: str) -> "dict | None":
254
+ return _json(self._alerts("PUT", f"/{token}/cancel"))
255
+
256
+ def deleteAlarm(self, token: str) -> None:
257
+ self._alerts("DELETE", f"/{token}")
258
+
259
+ def getNotifications(self, notification_type: str) -> list[dict]:
260
+ """REMINDER or TIMER notifications. Reminder results also contain to-do Tasks; callers filter them."""
261
+ q = {"personId": self.personId, "notificationType": notification_type}
262
+ if notification_type == "REMINDER":
263
+ q["clientType"] = "VOX"
264
+ data = _json(self._web("GET", "/api/notifications?" + urllib.parse.urlencode(q))) or {}
265
+ return data.get("notifications", [])
266
+
267
+ def createReminder(self, body: dict) -> "dict | None":
268
+ return _json(self._web("PUT", "/api/notifications/null", json=body))
269
+
270
+ def updateReminder(self, body: dict) -> "dict | None":
271
+ return _json(self._web("PUT", f"/api/notifications/{urllib.parse.quote(body['id'])}", json=body))
272
+
273
+ def deleteReminder(self, notification_id: str) -> None:
274
+ q = urllib.parse.urlencode({"personId": self.personId, "clientType": "VOX"})
275
+ self._web("DELETE", f"/api/notifications/{urllib.parse.quote(notification_id)}?{q}")
276
+
277
+ def updateTimer(self, body: dict) -> "dict | None":
278
+ """Pause/resume: PUT the whole timer with a new status (no query string)."""
279
+ return _json(self._web("PUT", f"/api/notifications/{urllib.parse.quote(body['id'])}", json=body))
280
+
281
+ def deleteTimer(self, notification_id: str) -> None:
282
+ q = urllib.parse.urlencode({"personId": self.personId})
283
+ self._web("DELETE", f"/api/notifications/{urllib.parse.quote(notification_id)}?{q}")
284
+
285
+ def _runNode(self, node: dict) -> None:
286
+ """Run a one-step routine right away."""
287
+ sequence = {
288
+ "@type": "com.amazon.alexa.behaviors.model.Sequence",
289
+ "startNode": {"@type": "com.amazon.alexa.behaviors.model.OpaquePayloadOperationNode", **node},
290
+ }
291
+ body = {"behaviorId": "PREVIEW", "sequenceJson": json.dumps(sequence), "status": "ENABLED"}
292
+ self._web("POST", "/api/behaviors/preview", json=body)
293
+
294
+ def runTextCommand(self, serial: str, device_type: str, customer_id: str, text: str) -> None:
295
+ """Have a device act on `text` as if it had been spoken to it (timers, stop, snooze)."""
296
+ self._runNode({
297
+ "type": "Alexa.TextCommand",
298
+ "skillId": TEXT_COMMAND_SKILL,
299
+ "operationPayload": {
300
+ "deviceType": device_type,
301
+ "deviceSerialNumber": serial,
302
+ "locale": self.locale,
303
+ "customerId": customer_id,
304
+ "text": text,
305
+ },
306
+ })
pyalexaalerts/auth.py ADDED
@@ -0,0 +1,238 @@
1
+ import datetime
2
+ import json
3
+ import logging
4
+ import sys
5
+ from email.utils import parsedate_to_datetime
6
+ from pathlib import Path
7
+
8
+ import requests
9
+
10
+ from .exception import AlexaSessionExpiredException
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+ _PYTHON_CMD = Path(sys.executable).stem
15
+
16
+ TOKEN_EXCHANGE_URL = "https://api.amazon.com/ap/exchangetoken/cookies"
17
+ ACCESS_TOKEN_URL = "https://api.amazon.com/auth/token"
18
+ APP_VERSION = "2.2.704787.0"
19
+
20
+ SUPPORTED_DOMAINS = (
21
+ "amazon.com", "amazon.co.uk", "amazon.de", "amazon.fr", "amazon.it", "amazon.es",
22
+ "amazon.co.jp", "amazon.ca", "amazon.com.au", "amazon.in", "amazon.com.br", "amazon.com.mx",
23
+ )
24
+
25
+
26
+ def default_service_auth_path() -> Path:
27
+ return Path.cwd() / "config" / "service_auth.json"
28
+
29
+
30
+ def exchange_refresh_token(refresh_token: str, amazon_domain: str = "amazon.com") -> dict:
31
+ """Exchange an Alexa refresh token for session cookies.
32
+
33
+ Returns:
34
+ Dict of cookie name -> raw cookie dict (keys Name, Value, Expires, ...).
35
+ Raises:
36
+ requests.RequestException / KeyError on failure.
37
+ """
38
+ response = requests.post(
39
+ TOKEN_EXCHANGE_URL,
40
+ headers={
41
+ "Content-Type": "application/x-www-form-urlencoded",
42
+ "x-amzn-identity-auth-domain": "api.amazon.com",
43
+ },
44
+ data={
45
+ "requested_token_type": "auth_cookies",
46
+ "app_name": "Amazon Alexa",
47
+ "domain": f"www.{amazon_domain}",
48
+ "source_token_type": "refresh_token",
49
+ "source_token": refresh_token,
50
+ },
51
+ timeout=30,
52
+ )
53
+ response.raise_for_status()
54
+ raw = response.json()["response"]["tokens"]["cookies"][f".{amazon_domain}"]
55
+ return {c["Name"]: c for c in raw}
56
+
57
+
58
+ def mint_access_token(refresh_token: str) -> "tuple[str, datetime.datetime]":
59
+ """Exchange an Alexa refresh token for a short-lived `Atna|...` access token.
60
+
61
+ The new alarms API (api.amazonalexa.com) authenticates with this token instead of cookies.
62
+
63
+ Returns:
64
+ (token, expires_at_utc)
65
+ """
66
+ response = requests.post(
67
+ ACCESS_TOKEN_URL,
68
+ headers={
69
+ "Content-Type": "application/x-www-form-urlencoded",
70
+ "x-amzn-identity-auth-domain": "api.amazon.com",
71
+ },
72
+ data={
73
+ "app_name": "Amazon Alexa",
74
+ "app_version": APP_VERSION,
75
+ "source_token": refresh_token,
76
+ "source_token_type": "refresh_token",
77
+ "requested_token_type": "access_token",
78
+ },
79
+ timeout=30,
80
+ )
81
+ response.raise_for_status()
82
+ data = response.json()
83
+ expires = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(seconds=int(data.get("expires_in", 3600)))
84
+ return data["access_token"], expires
85
+
86
+
87
+ class AlexaAuth:
88
+ """Loads, validates and refreshes Alexa session cookies, and applies them to a requests.Session."""
89
+
90
+ def __init__(
91
+ self,
92
+ session: requests.Session,
93
+ amazon_domain: str = "amazon.com",
94
+ service_auth_path: "Path | str | None" = None,
95
+ runtime_creds_path: "Path | str | None" = None,
96
+ ) -> None:
97
+ if amazon_domain not in SUPPORTED_DOMAINS:
98
+ raise ValueError(f"Unsupported amazon_domain '{amazon_domain}'. Supported: {sorted(SUPPORTED_DOMAINS)}")
99
+ self._session = session
100
+ self._amazon_domain = amazon_domain
101
+ self._service_auth_path = Path(service_auth_path) if service_auth_path else default_service_auth_path()
102
+ self._runtime_creds_path = (
103
+ Path(runtime_creds_path) if runtime_creds_path
104
+ else self._service_auth_path.parent / "runtime_credentials.json"
105
+ )
106
+ self._session_expiry: datetime.datetime | None = None
107
+ self._last_expiry_warning: datetime.datetime | None = None
108
+ self.load()
109
+
110
+ @property
111
+ def session_expiry(self) -> "datetime.datetime | None":
112
+ return self._session_expiry
113
+
114
+ @staticmethod
115
+ def _earliest_expiry(cookies: dict) -> "datetime.datetime | None":
116
+ expiries = [parsedate_to_datetime(c["Expires"]) for c in cookies.values() if c.get("Expires")]
117
+ return min(expiries) if expiries else None
118
+
119
+ def load(self) -> None:
120
+ """Load cached cookies, bootstrapping via token exchange if the cache is missing."""
121
+ if not self._runtime_creds_path.exists():
122
+ logger.info("%s not found — bootstrapping via token exchange", self._runtime_creds_path.name)
123
+ if not self.refresh():
124
+ raise FileNotFoundError(
125
+ f"Alexa credentials not found at {self._runtime_creds_path} and auto-refresh failed. "
126
+ f"Ensure {self._service_auth_path} has a valid alexa.refresh_token."
127
+ )
128
+ return
129
+ with open(self._runtime_creds_path, "r") as f:
130
+ cookies = json.load(f)["alexa"]["cookies"]
131
+ self._apply(cookies)
132
+ self.check_expiry()
133
+
134
+ def _apply(self, cookies: dict) -> None:
135
+ self._session_expiry = self._earliest_expiry(cookies)
136
+ for name, cookie in cookies.items():
137
+ self._session.cookies.set(name, cookie["Value"], domain=f".{self._amazon_domain}", path="/")
138
+
139
+ def _service_auth(self) -> dict:
140
+ try:
141
+ with open(self._service_auth_path, "r") as f:
142
+ return json.load(f).get("alexa", {})
143
+ except (FileNotFoundError, json.JSONDecodeError):
144
+ return {}
145
+
146
+ def _refresh_token(self) -> "str | None":
147
+ token = self._service_auth().get("refresh_token")
148
+ if not token:
149
+ logger.warning("No alexa.refresh_token in %s", self._service_auth_path)
150
+ return token or None
151
+
152
+ def _runtime(self) -> dict:
153
+ try:
154
+ with open(self._runtime_creds_path, "r") as f:
155
+ return json.load(f)
156
+ except (FileNotFoundError, json.JSONDecodeError):
157
+ return {}
158
+
159
+ def _save_runtime(self, key: str, value) -> None:
160
+ try:
161
+ runtime = self._runtime()
162
+ runtime.setdefault("alexa", {})[key] = value
163
+ self._runtime_creds_path.parent.mkdir(parents=True, exist_ok=True)
164
+ with open(self._runtime_creds_path, "w") as f:
165
+ json.dump(runtime, f, indent=4)
166
+ except Exception as e:
167
+ logger.warning("Could not write %s to %s: %s", key, self._runtime_creds_path, e)
168
+
169
+ def config_value(self, key: str) -> "str | None":
170
+ """A value from service_auth.json's `alexa` section, else the runtime cache (e.g. person_id)."""
171
+ return self._service_auth().get(key) or self._runtime().get("alexa", {}).get(key)
172
+
173
+ def cache_value(self, key: str, value: str) -> None:
174
+ self._save_runtime(key, value)
175
+
176
+ def refresh(self) -> bool:
177
+ """Exchange the refresh token for new cookies, cache them, and apply them.
178
+
179
+ Returns:
180
+ True on success, False on any failure (logged).
181
+ """
182
+ refresh_token = self._refresh_token()
183
+ if not refresh_token:
184
+ return False
185
+ try:
186
+ cookies = exchange_refresh_token(refresh_token, self._amazon_domain)
187
+ except Exception as e:
188
+ logger.warning("Auto-refresh failed — token exchange error: %s", e)
189
+ return False
190
+ self._save_runtime("cookies", cookies) # cookies stay usable in-memory even if this fails
191
+ self._apply(cookies)
192
+ return True
193
+
194
+ def access_token(self, force: bool = False) -> str:
195
+ """A valid `Atna|...` access token, minted from the refresh token and cached for its lifetime."""
196
+ now = datetime.datetime.now(datetime.timezone.utc)
197
+ if not force:
198
+ cached = self._runtime().get("alexa", {}).get("access_token") or {}
199
+ try:
200
+ expires = datetime.datetime.fromisoformat(cached["expires_at"])
201
+ if expires - now > datetime.timedelta(minutes=2):
202
+ return cached["value"]
203
+ except (KeyError, TypeError, ValueError):
204
+ pass
205
+ refresh_token = self._refresh_token()
206
+ if not refresh_token:
207
+ raise FileNotFoundError(f"An alexa.refresh_token is required in {self._service_auth_path}")
208
+ token, expires = mint_access_token(refresh_token)
209
+ self._save_runtime("access_token", {"value": token, "expires_at": expires.isoformat()})
210
+ return token
211
+
212
+ def check_expiry(self) -> None:
213
+ """Warn when the session is close to expiry; auto-refresh when expired.
214
+
215
+ Raises:
216
+ AlexaSessionExpiredException: if expired and the refresh fails.
217
+ """
218
+ if self._session_expiry is None:
219
+ return
220
+ now = datetime.datetime.now(datetime.timezone.utc)
221
+ if self._session_expiry > now:
222
+ days_left = (self._session_expiry - now).days
223
+ if days_left <= 30 and (
224
+ self._last_expiry_warning is None
225
+ or (now - self._last_expiry_warning).total_seconds() >= 3600
226
+ ):
227
+ logger.warning(
228
+ "Alexa session expires in %s day(s) on %s — it will auto-refresh, or re-run %s -m pyalexaalerts.get_alexa_cookies",
229
+ days_left, self._session_expiry.astimezone().strftime("%Y-%m-%d %H:%M %Z"), _PYTHON_CMD,
230
+ )
231
+ self._last_expiry_warning = now
232
+ return
233
+
234
+ logger.warning("Alexa session expired — attempting automatic token refresh")
235
+ if self.refresh():
236
+ logger.info("Alexa session refreshed via token exchange")
237
+ return
238
+ raise AlexaSessionExpiredException(self._session_expiry)