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 /deckit/modules/xbox.py | |
| 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>
Diffstat (limited to 'deckit/modules/xbox.py')
| -rw-r--r-- | deckit/modules/xbox.py | 135 |
1 files changed, 134 insertions, 1 deletions
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) |
