diff options
| author | Danilo M. <danix@danix.xyz> | 2026-11-16 17:17:13 +0100 |
|---|---|---|
| committer | Danilo M. <danix@danix.xyz> | 2026-11-16 17:17:13 +0100 |
| commit | 766251ed6dc1858b544aa1c50de72b93d10b84d4 (patch) | |
| tree | 3cdd0c2a14a6f8070fd96263ed2f424825c21ed7 | |
| parent | 3f56d1bdacfc45dba573e73dc45ebcdc8f72e8f7 (diff) | |
| download | deck-it-766251ed6dc1858b544aa1c50de72b93d10b84d4.tar.gz deck-it-766251ed6dc1858b544aa1c50de72b93d10b84d4.zip | |
feat(xbox): Xbox Live reads, presentation flag and console commands
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| -rw-r--r-- | config.toml | 7 | ||||
| -rw-r--r-- | deckit/modules/xbox.py | 135 | ||||
| -rw-r--r-- | tests/test_xbox.py | 104 |
3 files changed, 245 insertions, 1 deletions
diff --git a/config.toml b/config.toml index afd2667..45609fa 100644 --- a/config.toml +++ b/config.toml @@ -52,6 +52,7 @@ vm = true assistant = true tablet = true actions = true +xbox = true [obs] host = "127.0.0.1" @@ -73,6 +74,12 @@ host = "buildsystem" # K1C tab says no printer is configured. url = "" +[xbox] +# The client id of your own Azure app registration: a public client for +# personal Microsoft accounts, with public client flows allowed. Empty: the +# Xbox tab says it is not configured. Sign-in happens on the tab. +client_id = "" + [assistant] # keystone's desktop shell, the quickshell config whose `assistant catalog` # IPC call lists the canvas's Ask presets and Do ops for the tab. diff --git a/deckit/modules/xbox.py b/deckit/modules/xbox.py index 05567bd..d13ff70 100644 --- a/deckit/modules/xbox.py +++ b/deckit/modules/xbox.py @@ -58,6 +58,17 @@ USERSTATS = "https://userstats.xboxlive.com/batch" HUB = {"x-xbl-client-name": "XboxApp", "x-xbl-client-type": "UWA", "x-xbl-client-version": "39.39.22001.0"} SG = {"skillplatform": "RemoteManagement"} +COMMANDS = { + "wake": ("Power", "WakeUp", None), + "off": ("Power", "TurnOff", None), + "play": ("Media", "Play", None), + "pause": ("Media", "Pause", None), + "vol_up": ("Audio", "Volume", [{"direction": "Up", "amount": "1"}]), + "vol_down": ("Audio", "Volume", [{"direction": "Down", "amount": "1"}]), + "mute": ("Audio", "Mute", None), + "unmute": ("Audio", "Unmute", None), +} + FAST = 30 # seconds between presence and console reads SLOW = 600 # seconds between profile, games, achievements and friends reads # ponytail: renewed by age, not by the XSTS NotAfter (about 16h); a 401 renews early too. @@ -178,7 +189,10 @@ def summarize_friends(r: dict) -> list: # Replaced in Task 4; here so module discovery (deckit.modules.build) keeps working. def make(cfg: dict) -> Module: - return Module(name="xbox", title="Xbox", state=lambda: {"offline": True, "unconfigured": True}) + x = Xbox(cfg, cfg.get("http", _http)) + actions = {name: (lambda body, n=name: x.command(n, body)) for name in COMMANDS} + actions["login"] = x.start_login + return Module(name="xbox", title="Xbox", state=x.state, actions=actions, start=x.start, stop=x.stop) class Xbox: @@ -319,3 +333,122 @@ class Xbox: 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} + + # --- reads ---------------------------------------------------------- + def read_fast(self): + presence = summarize_presence(self.api(PRESENCE, 3)) + consoles = summarize_consoles(self.api(DEVICES, 4, extra=SG)) + self.data = {**self.data, "presence": presence, "consoles": consoles} + + def read_slow(self): + """Each part on its own: an endpoint that refuses keeps its last data, + a network failure (a plain OSError) ends the read.""" + xuid = self.auth["xuid"] + + def titles(): + history = self.api(TITLEHUB.format(xuid) + f"titlehistory/decoration/achievement,image?maxItems={TITLES}", + 2, extra=HUB) + ids = [str(t["titleId"]) for t in history.get("titles") or []] + try: + minutes = minutes_played(self.api(USERSTATS, 2, { + "arrangebyfield": "xuid", "xuids": [xuid], + "stats": [{"name": "MinutesPlayed", "titleId": i} for i in ids]})) if ids else {} + except HttpError: + minutes = {} + out = summarize_titles(history, minutes) + self.types.update({t["id"]: t["type"] for t in out}) + return out + + parts = { + "profile": lambda: summarize_profile(self.api(PROFILE, 3)), + "titles": titles, + "achievements": lambda: summarize_achievements(self.api(ACHIEVEMENTS.format(xuid), 2)), + "friends": lambda: summarize_friends(self.api(FRIENDS, 7)), + } + for key, read in parts.items(): + try: + self.data = {**self.data, key: read()} + except HttpError as e: + if e.status == 401: + raise + self.data = {**self.data, key: self.data.get(key) or ([] if key != "profile" else None)} + self.reason = f"{key}: {e}" + + def type_of(self, tid: str): + if tid not in self.types: + 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: + self.types[tid] = None # the home screen and system apps have no entry + return self.types[tid] + + def tick(self): + if not self.refresh: + return self._set_playing(None) + try: + self.reason = None + self.read_fast() + fg = self.data["presence"]["title"] + fg_id = fg and fg["id"] + if self.slow_at is None or time.monotonic() - self.slow_at >= SLOW or fg_id != self.slow_title: + self.read_slow() + self.slow_at, self.slow_title = time.monotonic(), fg_id + self._set_playing(fg if fg and self.type_of(fg["id"]) == "Game" else None) + self.offline = False + except SignedOut: + self.data = {} + self._set_playing(None) + except (OSError, ValueError, KeyError, TypeError, IndexError) as e: + self.offline, self.reason = True, str(e) + + # --- playing -------------------------------------------------------- + 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 + + # --- console commands ----------------------------------------------- + def command(self, name: str, body: dict): + cid = (body or {}).get("console") + if cid not in {c["id"] for c in self.data.get("consoles") or []}: + raise ModuleError("unknown console") + typ, cmd, params = COMMANDS[name] + try: + 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: + raise ModuleError("not signed in to Xbox") from None + except OSError as e: + raise ModuleError(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"]) + self.wake.set() + + # --- the reader thread ---------------------------------------------- + def run(self): + while not self.stopping: + self.tick() + self.wake.wait(FAST) + self.wake.clear() + + def start(self): + if self.client_id: + threading.Thread(target=self.run, daemon=True).start() + + def stop(self): + self.stopping = True + self.wake.set() + self._set_playing(None) diff --git a/tests/test_xbox.py b/tests/test_xbox.py index 010034d..2eeea8d 100644 --- a/tests/test_xbox.py +++ b/tests/test_xbox.py @@ -218,5 +218,109 @@ class Login(Base): self.assertIsNone(x.state()["login"]) +class Tick(Base): + def test_a_tick_reads_everything_and_marks_the_game(self): + x = self.xbox() + x.tick() + st = x.state() + self.assertEqual(st["profile"]["gamertag"], "Player") + self.assertEqual(st["consoles"][0]["id"], "CON1") + self.assertEqual(st["titles"][0]["minutes"], 185) + self.assertEqual(st["achievements"][0]["score"], 15) + self.assertEqual(st["friends"][0]["gamertag"], "amy") + self.assertEqual(st["playing"]["name"], "Some Game") + self.assertIsInstance(st["session"], int) + self.assertEqual(self.status.read_text(), "1") + + def test_slow_reads_wait_unless_the_title_changes(self): + x = self.xbox() + x.tick(), x.tick() + self.assertEqual(len(self.fake.urls("profile.xboxlive.com")), 1) + self.fake.answers["userpresence"] = {"state": "Online", "devices": [{"titles": [ + {"id": "99", "name": "Video App", "placement": "Full"}]}]} + x.tick() + self.assertEqual(len(self.fake.urls("profile.xboxlive.com")), 2) + + def test_an_app_is_not_playing_and_ends_the_session(self): + x = self.xbox() + x.tick() + self.fake.answers["userpresence"] = {"state": "Online", "devices": [{"titles": [ + {"id": "99", "name": "Video App", "placement": "Full"}]}]} + x.tick() + self.assertIsNone(x.state()["playing"]) + self.assertIsNone(x.state()["session"]) + self.assertEqual(self.status.read_text(), "0") + + def test_an_unknown_title_type_is_looked_up_once(self): + self.fake.answers["userpresence"] = {"state": "Online", "devices": [{"titles": [ + {"id": "555", "name": "New Game", "placement": "Full"}]}]} + x = self.xbox() + x.tick(), x.tick() + self.assertEqual(len(self.fake.urls("titleid(555)")), 1) + self.assertEqual(x.state()["playing"]["id"], "555") + + def test_network_down_keeps_the_data_as_stale(self): + x = self.xbox() + x.tick() + self.fake.fail["userpresence"] = OSError("no route") + x.tick() + st = x.state() + self.assertTrue(st["stale"]) + self.assertEqual(st["profile"]["gamertag"], "Player") + + def test_one_failing_part_keeps_the_rest(self): + x = self.xbox() + self.fake.fail["peoplehub"] = xb.HttpError(403, {}) + x.tick() + st = x.state() + self.assertFalse(st["stale"]) + self.assertEqual(st["friends"], []) + self.assertEqual(st["profile"]["gamertag"], "Player") + + def test_signed_out_clears_playing(self): + x = self.xbox() + x.tick() + self.fake.fail["/oauth2/v2.0/token"] = xb.HttpError(400, {"error": "invalid_grant"}) + x.auth = None + x.tick() + self.assertFalse(x.state()["signed_in"]) + self.assertEqual(self.status.read_text(), "0") + + def test_stop_writes_zero(self): + x = self.xbox() + x.tick() + x.stop() + self.assertEqual(self.status.read_text(), "0") + + +class Commands(Base): + def test_a_command_goes_to_xccs(self): + x = self.xbox() + x.tick() + x.command("vol_up", {"console": "CON1"}) + url, data, headers = self.fake.urls("/commands")[0] + self.assertEqual((data["type"], data["command"], data["linkedXboxId"]), ("Audio", "Volume", "CON1")) + self.assertEqual(data["parameters"], [{"direction": "Up", "amount": "1"}]) + self.assertEqual(headers["skillplatform"], "RemoteManagement") + + def test_unknown_console_is_refused(self): + x = self.xbox() + x.tick() + with self.assertRaises(xb.ModuleError): + x.command("wake", {"console": "OTHER"}) + + def test_an_xccs_error_becomes_the_message(self): + self.fake.answers["/commands"] = {"status": {"errorCode": "DeviceUnavailable", "errorMessage": "Console is off"}} + x = self.xbox() + x.tick() + with self.assertRaisesRegex(xb.ModuleError, "Console is off"): + x.command("off", {"console": "CON1"}) + + def test_make_lists_the_actions(self): + m = xb.make({"xbox": {"client_id": ""}}) + self.assertEqual(set(m.actions), {"login", *xb.COMMANDS}) + self.assertEqual(m.state(), {"offline": True, "unconfigured": True}) + + if __name__ == "__main__": unittest.main() |
