aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorDanilo M. <danix@danix.xyz>2026-11-16 17:21:07 +0100
committerDanilo M. <danix@danix.xyz>2026-11-16 17:21:07 +0100
commit5e18a133f779d5f344e592b4e3c122c43b2a4982 (patch)
treeb856ec03b2f97e4a7ba8abfcff4c06893454f306
parentab02a2e982d145333d843fe84087b5fdd0e05b38 (diff)
downloaddeck-it-5e18a133f779d5f344e592b4e3c122c43b2a4982.tar.gz
deck-it-5e18a133f779d5f344e592b4e3c122c43b2a4982.zip
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 <noreply@anthropic.com>
-rw-r--r--deckit/modules/xbox.py110
-rw-r--r--tests/test_xbox.py65
2 files changed, 130 insertions, 45 deletions
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()
diff --git a/tests/test_xbox.py b/tests/test_xbox.py
index 2eeea8d..8a14bb6 100644
--- a/tests/test_xbox.py
+++ b/tests/test_xbox.py
@@ -191,7 +191,7 @@ class Login(Base):
def test_start_returns_the_code_and_state_shows_it(self):
x = self.xbox(signed_in=False)
- x._wait_login = lambda: None # the test drives login_step itself
+ x._wait_login = lambda login: None # the test drives login_step itself
view = x.start_login({})
self.assertEqual((view["code"], view["url"]), ("ABCD-1234", "https://microsoft.com/devicelogin"))
self.assertEqual(x.state()["login"]["code"], "ABCD-1234")
@@ -199,7 +199,7 @@ class Login(Base):
def test_pending_then_done_saves_the_token(self):
x = self.xbox(signed_in=False)
- x._wait_login = lambda: None
+ x._wait_login = lambda login: None
x.start_login({})
self.fake.fail["/oauth2/v2.0/token"] = xb.HttpError(400, {"error": "authorization_pending"})
self.assertEqual(x.login_step(), "pending")
@@ -211,12 +211,24 @@ class Login(Base):
def test_declined_or_expired_ends_it(self):
x = self.xbox(signed_in=False)
- x._wait_login = lambda: None
+ x._wait_login = lambda login: None
x.start_login({})
self.fake.fail["/oauth2/v2.0/token"] = xb.HttpError(400, {"error": "expired_token"})
self.assertEqual(x.login_step(), "failed")
self.assertIsNone(x.state()["login"])
+ def test_an_old_poller_leaves_a_newer_code(self):
+ x = self.xbox(signed_in=False)
+ x._wait_login = lambda login: None
+ x.start_login({})
+ old = x.login
+ old["expires"] = 0
+ x.start_login({})
+ new = x.login
+ self.assertIsNot(new, old)
+ self.assertEqual(x.login_step(old), "failed")
+ self.assertIs(x.login, new)
+
class Tick(Base):
def test_a_tick_reads_everything_and_marks_the_game(self):
@@ -286,6 +298,46 @@ class Tick(Base):
self.assertFalse(x.state()["signed_in"])
self.assertEqual(self.status.read_text(), "0")
+ def test_sign_in_again_reads_the_profile_at_once(self):
+ x = self.xbox()
+ x.tick()
+ self.fake.fail["/oauth2/v2.0/token"] = xb.HttpError(400, {"error": "invalid_grant"})
+ x.auth = None
+ x.tick()
+ x._wait_login = lambda login: None
+ x.start_login({})
+ self.assertEqual(x.login_step(), "done")
+ x.tick()
+ self.assertEqual(x.state()["profile"]["gamertag"], "Player")
+
+ def test_a_throttled_type_lookup_is_not_cached(self):
+ self.fake.answers["userpresence"] = {"state": "Online", "devices": [{"titles": [
+ {"id": "555", "name": "New Game", "placement": "Full"}]}]}
+ self.fake.fail["titleid(555)"] = xb.HttpError(429, {})
+ x = self.xbox()
+ x.tick()
+ self.assertNotIn("555", x.types)
+ x.tick()
+ self.assertEqual(x.state()["playing"]["id"], "555")
+
+ def test_a_failing_tick_does_not_end_the_reader(self):
+ x = self.xbox()
+
+ def tick():
+ x.stopping = True
+ x.wake.set()
+ raise RuntimeError("boom")
+ x.tick = tick
+ x.run()
+ self.assertEqual((x.offline, x.reason), (True, "boom"))
+
+ def test_nothing_after_stop_sets_playing(self):
+ x = self.xbox()
+ x.tick()
+ x.stop()
+ x._set_playing({"id": "1234", "name": "Some Game"})
+ self.assertEqual(self.status.read_text(), "0")
+
def test_stop_writes_zero(self):
x = self.xbox()
x.tick()
@@ -316,6 +368,13 @@ class Commands(Base):
with self.assertRaisesRegex(xb.ModuleError, "Console is off"):
x.command("off", {"console": "CON1"})
+ def test_an_xccs_http_error_message_surfaces(self):
+ x = self.xbox()
+ x.tick()
+ self.fake.fail["/commands"] = xb.HttpError(400, {"status": {"errorCode": "Bad", "errorMessage": "Console not found"}})
+ with self.assertRaisesRegex(xb.ModuleError, "Console not found"):
+ x.command("wake", {"console": "CON1"})
+
def test_make_lists_the_actions(self):
m = xb.make({"xbox": {"client_id": ""}})
self.assertEqual(set(m.actions), {"login", *xb.COMMANDS})