From 5e18a133f779d5f344e592b4e3c122c43b2a4982 Mon Sep 17 00:00:00 2001 From: "Danilo M." Date: Mon, 16 Nov 2026 17:21:07 +0100 Subject: fix(xbox): keep the reader alive and the flags right - run() survives any exception from tick(); _http turns http.client.HTTPException into OSError. - Signing out or in again resets the slow-read clock, so the profile is read at once instead of after 10 minutes. - After stop() nothing sets status.xbox back to 1; its compare and write is under a lock. - api() uses a copy of the auth taken under the lock; command() maps a missing auth to "not signed in". - Action and sign-in errors carry Xbox Live's own message when the HTTP error body has one. - type_of caches only a 404; other errors retry on the next tick. - Sign-in: start_login is locked, a poller only ends its own flow, and a failed token save ends it as "failed". - state() is loading only until the first presence read. - Drop a stale placeholder comment. Co-Authored-By: Claude Opus 5.5 --- deckit/modules/xbox.py | 110 ++++++++++++++++++++++++++++++------------------- 1 file changed, 68 insertions(+), 42 deletions(-) (limited to 'deckit/modules/xbox.py') diff --git a/deckit/modules/xbox.py b/deckit/modules/xbox.py index d13ff70..3ed7ce3 100644 --- a/deckit/modules/xbox.py +++ b/deckit/modules/xbox.py @@ -28,6 +28,7 @@ The endpoints, headers and command bodies follow xbox-webapi-python; Microsoft documents none of them for third parties. """ +import http.client import json import os import threading @@ -108,6 +109,8 @@ def _http(url, data=None, headers=None, timeout=10): except ValueError: payload = {} raise HttpError(e.code, payload if isinstance(payload, dict) else {}) from None + except http.client.HTTPException as e: + raise OSError(str(e) or type(e).__name__) from None return json.loads(raw) if raw else {} @@ -187,7 +190,6 @@ def summarize_friends(r: dict) -> list: return people -# Replaced in Task 4; here so module discovery (deckit.modules.build) keeps working. def make(cfg: dict) -> Module: x = Xbox(cfg, cfg.get("http", _http)) actions = {name: (lambda body, n=name: x.command(n, body)) for name in COMMANDS} @@ -204,11 +206,13 @@ class Xbox: self.auth_lock = threading.Lock() self.sg_session = str(uuid.uuid4()) self.login = None # the device code flow while it runs + self.login_lock = threading.Lock() self.data = {} # presence, consoles, profile, titles, achievements, friends self.offline, self.reason = False, None self.types = {} # title id -> titlehub type ("Game", "App") self.playing, self.session = None, None self.status_on = None # what status.xbox last got + self.status_lock = threading.Lock() self.slow_at, self.slow_title = None, None self.wake, self.stopping = threading.Event(), False @@ -261,8 +265,9 @@ class Xbox: with self.auth_lock: if not self.auth or time.monotonic() - self.auth["at"] > XSTS_FOR: self._authorize() + auth = self.auth for retry in (True, False): - headers = {"Authorization": self.auth["header"], "x-xbl-contract-version": str(contract), + headers = {"Authorization": auth["header"], "x-xbl-contract-version": str(contract), "Accept-Language": "en-US", **(extra or {})} try: return self.http(url, data, headers) @@ -271,31 +276,41 @@ class Xbox: raise with self.auth_lock: self._authorize() + auth = self.auth # --- device code sign-in ------------------------------------------- def start_login(self, body=None): if not self.client_id: raise ModuleError("no Xbox client id configured") - if self.login and time.time() < self.login["expires"]: + with self.login_lock: + if self.login and time.time() < self.login["expires"]: + return self._login_view() + try: + r = self.http(MS + "/devicecode", urllib.parse.urlencode({"client_id": self.client_id, "scope": SCOPE})) + except OSError as e: + msg = isinstance(e, HttpError) and e.body.get("error_description") + raise ModuleError(msg or f"sign-in failed: {e}") from e + self.login = {"code": r["user_code"], "url": r["verification_uri"], "expires": time.time() + r["expires_in"], + "device": r["device_code"], "interval": r.get("interval", 5)} + threading.Thread(target=self._wait_login, args=(self.login,), daemon=True).start() return self._login_view() - try: - r = self.http(MS + "/devicecode", urllib.parse.urlencode({"client_id": self.client_id, "scope": SCOPE})) - except OSError as e: - raise ModuleError(f"sign-in failed: {e}") from e - self.login = {"code": r["user_code"], "url": r["verification_uri"], "expires": time.time() + r["expires_in"], - "device": r["device_code"], "interval": r.get("interval", 5)} - threading.Thread(target=self._wait_login, daemon=True).start() - return self._login_view() def _login_view(self): login = self.login return {k: login[k] for k in ("code", "url", "expires")} if login else None - def login_step(self) -> str: - """One poll of the token endpoint: "done", "pending" or "failed".""" - login = self.login - if not login or time.time() > login["expires"]: - self.login = None + def _end_login(self, login): + """Drop the flow, unless a newer one replaced it.""" + with self.login_lock: + if self.login is login: + self.login = None + + def login_step(self, login=None) -> str: + """One poll of the token endpoint for `login` (default the current + flow): "done", "pending" or "failed".""" + login = login or self.login + if not login or login is not self.login or time.time() > login["expires"]: + self._end_login(login) return "failed" try: tok = self._form(grant_type="urn:ietf:params:oauth:grant-type:device_code", device_code=login["device"]) @@ -305,22 +320,24 @@ class Xbox: login["interval"] += 5 if err in ("authorization_pending", "slow_down"): return "pending" - self.login = None + self._end_login(login) return "failed" except OSError: return "pending" - self._save(tok["refresh_token"]) - self.login, self.auth = None, None + try: + self._save(tok["refresh_token"]) + except (OSError, KeyError): + self._end_login(login) + return "failed" + self._end_login(login) + self.auth, self.slow_at = None, None self.wake.set() return "done" - def _wait_login(self): - while not self.stopping: - login = self.login - if not login: - return + def _wait_login(self, login): + while not self.stopping and self.login is login: time.sleep(login["interval"]) - if self.login_step() != "pending": + if self.login_step(login) != "pending": return # --- what the tab polls -------------------------------------------- @@ -329,7 +346,7 @@ class Xbox: return {"offline": True, "unconfigured": True} if not self.refresh: return {"signed_in": False, "login": self._login_view()} - if not self.data.get("profile"): + if "presence" not in self.data: return {"signed_in": True, "offline": self.offline, "reason": self.reason, "loading": not self.offline} return {"signed_in": True, "stale": self.offline, "reason": self.reason, **self.data, "playing": self.playing, "session": self.session} @@ -379,7 +396,9 @@ class Xbox: try: r = self.api(TITLEHUB.format(self.auth["xuid"]) + f"titleid({tid})/decoration/detail", 2, extra=HUB) self.types[tid] = ((r.get("titles") or [{}])[0]).get("type") - except HttpError: + except HttpError as e: + if e.status != 404: + raise self.types[tid] = None # the home screen and system apps have no entry return self.types[tid] @@ -397,7 +416,7 @@ class Xbox: self._set_playing(fg if fg and self.type_of(fg["id"]) == "Game" else None) self.offline = False except SignedOut: - self.data = {} + self.data, self.slow_at = {}, None self._set_playing(None) except (OSError, ValueError, KeyError, TypeError, IndexError) as e: self.offline, self.reason = True, str(e) @@ -406,17 +425,20 @@ class Xbox: def _set_playing(self, game): # ponytail: the session starts when deck-it first sees the game, so a # restart mid-game counts as a new session (and switches the tab again). - if game and not self.playing: - self.session = int(time.time()) - elif not game: - self.session = None - self.playing = game - on = game is not None - if on != self.status_on: - tmp = self.status_path.with_name("." + self.status_path.name + ".tmp") - tmp.write_text("1" if on else "0") - os.replace(tmp, self.status_path) - self.status_on = on + with self.status_lock: + if self.stopping: + game = None + if game and not self.playing: + self.session = int(time.time()) + elif not game: + self.session = None + self.playing = game + on = game is not None + if on != self.status_on: + tmp = self.status_path.with_name("." + self.status_path.name + ".tmp") + tmp.write_text("1" if on else "0") + os.replace(tmp, self.status_path) + self.status_on = on # --- console commands ----------------------------------------------- def command(self, name: str, body: dict): @@ -428,10 +450,11 @@ class Xbox: r = self.api(XCCS + "/commands", 4, { "destination": "Xbox", "type": typ, "command": cmd, "sessionId": self.sg_session, "sourceId": "com.microsoft.smartglass", "parameters": params or [{}], "linkedXboxId": cid}, SG) - except SignedOut: + except (SignedOut, TypeError): raise ModuleError("not signed in to Xbox") from None except OSError as e: - raise ModuleError(f"{name} failed: {e}") from e + msg = isinstance(e, HttpError) and (e.body.get("status") or {}).get("errorMessage") + raise ModuleError(msg or f"{name} failed: {e}") from e status = r.get("status") or {} if status.get("errorCode", "OK") != "OK": raise ModuleError(status.get("errorMessage") or status["errorCode"]) @@ -440,7 +463,10 @@ class Xbox: # --- the reader thread ---------------------------------------------- def run(self): while not self.stopping: - self.tick() + try: + self.tick() + except Exception as e: + self.offline, self.reason = True, str(e) self.wake.wait(FAST) self.wake.clear() -- cgit v1.2.3