# deck-it - Xbox Live: profile, presence, games, friends and console control # Copyright (C) 2026 Danilo M. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """Xbox Live: the user's profile, presence, consoles, recent games, achievements and friends, and the console's power and media control. A retail console has no local API, so everything goes through Xbox Live with the user's own Azure app (a public client for personal accounts). Sign-in is the device code flow, started from the tab; the refresh token lives in ~/.config/deck-it/xbox-token.json and the short-lived tokens only in memory. While the console runs a game, $XDG_RUNTIME_DIR/status.xbox holds 1, which keystone's Status.qml ORs into presentation mode. 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 shutil import subprocess import threading import time import urllib.error import urllib.parse import urllib.request import uuid from pathlib import Path from ..module import Module, ModuleError MS = "https://login.microsoftonline.com/consumers/oauth2/v2.0" SCOPE = "XboxLive.signin offline_access" USER_AUTH = "https://user.auth.xboxlive.com/user/authenticate" XSTS_AUTH = "https://xsts.auth.xboxlive.com/xsts/authorize" PRESENCE = "https://userpresence.xboxlive.com/users/me?level=all" XCCS = "https://xccs.xboxlive.com" DEVICES = XCCS + "/lists/devices?queryCurrentDevice=false&includeStorageDevices=true" TITLEHUB = "https://titlehub.xboxlive.com/users/xuid({})/titles/" PROFILE = "https://profile.xboxlive.com/users/me/profile/settings?settings=Gamertag,GameDisplayPicRaw,Gamerscore" ACHIEVEMENTS = ("https://achievements.xboxlive.com/users/xuid({})/achievements" "?orderBy=UnlockTime&unlockedOnly=true&maxItems=10") FRIENDS = "https://peoplehub.xboxlive.com/users/me/people/friends/decoration/presenceDetail" USERSTATS = "https://userstats.xboxlive.com/batch" MEDIAHUB = "https://mediahub.xboxlive.com/{}/search" # screenshots, gameclips # titlehub answers only clients that name themselves; these are the Xbox app's. 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 QUICK, QUICK_FOR = 3, 30 # after a command: read every 3s for 30s, until the power state follows # ponytail: renewed by age, not by the XSTS NotAfter (about 16h); a 401 renews early too. XSTS_FOR = 8 * 3600 TITLES = 12 # recent games shown CAPTURES = 24 # screenshots and clips shown, newest first TOKEN = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "deck-it" / "xbox-token.json" STATUS = Path(os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}") / "status.xbox" class HttpError(OSError): """An HTTP error answer, with its JSON body when it had one.""" def __init__(self, status: int, body: dict | None): super().__init__(f"HTTP {status}") self.status, self.body = status, body or {} class SignedOut(Exception): """No refresh token, or Microsoft no longer accepts it.""" def _http(url, data=None, headers=None, timeout=10): """A JSON answer. data: a dict or list goes as JSON, a str as a form.""" h = {"Accept": "application/json", "User-Agent": "deck-it", **(headers or {})} body = None if isinstance(data, dict | list): body, h["Content-Type"] = json.dumps(data).encode(), "application/json" elif isinstance(data, str): body, h["Content-Type"] = data.encode(), "application/x-www-form-urlencoded" try: with urllib.request.urlopen(urllib.request.Request(url, data=body, headers=h), timeout=timeout) as r: raw = r.read() except urllib.error.HTTPError as e: try: payload = json.loads(e.read() or b"{}") 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 {} def user_dir(name: str) -> Path: """An XDG user directory (PICTURES, VIDEOS), else ~/Pictures or ~/Videos.""" try: p = subprocess.run(["xdg-user-dir", name], capture_output=True, text=True, timeout=5).stdout.strip() except (OSError, subprocess.SubprocessError): p = "" return Path(p) if p and Path(p) != Path.home() else Path.home() / name.title() def foreground(presence: dict) -> dict | None: """The title filling a console's screen, if any.""" for dev in presence.get("devices") or []: for t in dev.get("titles") or []: if t.get("placement") == "Full" and t.get("state", "Active") == "Active": act = t.get("activity") or {} if isinstance(act, list): act = act[0] if act else {} return {"id": str(t.get("id")), "name": t.get("name"), "rich": act.get("richPresence"), "device": dev.get("type")} return None def summarize_presence(p: dict) -> dict: seen = p.get("lastSeen") return {"state": p.get("state"), "title": foreground(p), "last_seen": {"title": seen.get("titleName"), "when": seen.get("timestamp")} if seen else None} def summarize_profile(r: dict) -> dict: s = {x["id"]: x.get("value") for x in r["profileUsers"][0]["settings"]} return {"gamertag": s.get("Gamertag"), "pic": s.get("GameDisplayPicRaw"), "gamerscore": int(s.get("Gamerscore") or 0)} def summarize_consoles(r: dict) -> list: return [{"id": c["id"], "name": c.get("name"), "type": c.get("consoleType"), "power": c.get("powerState"), "region": c.get("region"), "remote": c.get("remoteManagementEnabled"), "streaming": c.get("consoleStreamingEnabled"), "storage": [{"name": d.get("storageDeviceName"), "free": d.get("freeSpaceBytes"), "total": d.get("totalSpaceBytes")} for d in c.get("storageDevices") or []]} for c in r.get("result") or []] def summarize_apps(r: dict) -> list: """A console's installed games and apps (DLC is not a title of its own).""" return [{"id": str(a["titleId"]) if a.get("titleId") else None, "pfn": (a.get("aumid") or "").split("!")[0] or None, "name": a.get("name"), "size": a.get("sizeInBytes") or 0, "version": a.get("version"), "updated": a.get("updateTime") or a.get("installTime"), "last": a.get("lastActiveTime")} for a in r.get("result") or [] if a.get("contentType") != "Dlc"] def merge_installed(titles: list, apps: dict) -> list: """The titles, each marked with what is installed of it on any console, most recently played first.""" by = {} for console_apps in apps.values(): for a in console_apps: for k in (a["id"], a["pfn"]): if k: by.setdefault(k, a) out = [] for t in titles: a = by.get(t["id"]) or by.get(t.get("pfn")) inst = {"size": a["size"], "version": a["version"], "updated": a["updated"]} if a else None last = max(filter(None, (t["last"], a and a["last"])), default=None) out.append({**t, "installed": inst, "last": last}) return sorted(out, key=lambda t: t["last"] or "", reverse=True) def minutes_played(r: dict) -> dict: """title id -> minutes, from a userstats batch of MinutesPlayed.""" out = {} for coll in r.get("statlistscollection") or []: for s in coll.get("stats") or []: if s.get("name") == "MinutesPlayed" and s.get("value") is not None: out[str(s.get("titleid") or s.get("titleId"))] = int(float(s["value"])) return out def summarize_titles(r: dict, minutes: dict) -> list: out = [] for t in r.get("titles") or []: a = t.get("achievement") or {} tid = str(t["titleId"]) out.append({"id": tid, "pfn": t.get("pfn"), "name": t.get("name"), "type": t.get("type"), "cover": t.get("displayImage"), "last": (t.get("titleHistory") or {}).get("lastTimePlayed"), "achievements": {"done": a.get("currentAchievements", 0), "total": a.get("totalAchievements", 0), "score": a.get("currentGamerscore", 0), "max": a.get("totalGamerscore", 0), "pct": a.get("progressPercentage", 0)}, "minutes": minutes.get(tid)}) return out def summarize_achievements(r: dict) -> list: out = [] for a in r.get("achievements") or []: score = next((int(x.get("value") or 0) for x in a.get("rewards") or [] if x.get("type") == "Gamerscore"), 0) out.append({"name": a.get("name"), "description": a.get("description"), "icon": next((m.get("url") for m in a.get("mediaAssets") or []), None), "score": score, "title": next((t.get("name") for t in a.get("titleAssociations") or []), None), "unlocked": (a.get("progression") or {}).get("timeUnlocked")}) return out def summarize_captures(shots: dict, clips: dict) -> list: """Uploaded screenshots and clips, newest first. The URIs are signed (SAS): the tablet loads them with no auth, until they expire.""" out = [] for kind, r in (("shot", shots), ("clip", clips)): for c in r.get("values") or []: loc = {x.get("locatorType"): x.get("uri") for x in c.get("contentLocators") or []} if loc.get("Download"): out.append({"id": c.get("contentId"), "kind": kind, "title": c.get("titleName"), "date": c.get("captureDate"), "expires": c.get("expirationDate"), "seconds": c.get("durationInSeconds"), "thumb": loc.get("Thumbnail_Large") or loc.get("Thumbnail_Small"), "url": loc["Download"]}) return sorted(out, key=lambda c: c["date"] or "", reverse=True)[:CAPTURES] def summarize_friends(r: dict) -> list: people = [{"gamertag": p.get("gamertag"), "pic": p.get("displayPicRaw"), "state": p.get("presenceState"), "text": p.get("presenceText"), "favorite": bool(p.get("isFavorite"))} for p in r.get("people") or []] people.sort(key=lambda p: (p["state"] != "Online", not p["favorite"], (p["gamertag"] or "").lower())) return people 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} actions["login"] = x.start_login actions["save"] = x.save return Module(name="xbox", title="Xbox", state=x.state, actions=actions, start=x.start, stop=x.stop) class Xbox: def __init__(self, cfg: dict, http=_http, token=TOKEN, status=STATUS): self.client_id = str(cfg.get("xbox", {}).get("client_id", "")).strip() self.http, self.token_path, self.status_path = http, Path(token), Path(status) self.refresh = self._load() self.auth = None # {"header", "xuid", "at"} from the last XSTS 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 self.quick_until = 0.0 # read every QUICK seconds until then # --- the refresh token file ---------------------------------------- def _load(self): try: return json.loads(self.token_path.read_text())["refresh_token"] except (OSError, ValueError, KeyError, TypeError): return None def _save(self, refresh: str): self.token_path.parent.mkdir(parents=True, exist_ok=True) tmp = self.token_path.with_suffix(".tmp") tmp.unlink(missing_ok=True) with os.fdopen(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w") as f: json.dump({"refresh_token": refresh}, f) os.replace(tmp, self.token_path) self.refresh = refresh # --- tokens --------------------------------------------------------- def _form(self, **fields): return self.http(MS + "/token", urllib.parse.urlencode({"client_id": self.client_id, **fields})) def _authorize(self): """Refresh token -> MS access token -> Xbox user token -> XSTS.""" if not self.refresh: raise SignedOut try: tok = self._form(grant_type="refresh_token", refresh_token=self.refresh, scope=SCOPE) except HttpError as e: if e.body.get("error") in ("invalid_grant", "interaction_required"): self.token_path.unlink(missing_ok=True) self.refresh, self.auth = None, None raise SignedOut from None raise if tok.get("refresh_token") and tok["refresh_token"] != self.refresh: self._save(tok["refresh_token"]) v1 = {"x-xbl-contract-version": "1"} user = self.http(USER_AUTH, {"RelyingParty": "http://auth.xboxlive.com", "TokenType": "JWT", "Properties": {"AuthMethod": "RPS", "SiteName": "user.auth.xboxlive.com", "RpsTicket": "d=" + tok["access_token"]}}, v1) xsts = self.http(XSTS_AUTH, {"RelyingParty": "http://xboxlive.com", "TokenType": "JWT", "Properties": {"UserTokens": [user["Token"]], "SandboxId": "RETAIL"}}, v1) xui = xsts["DisplayClaims"]["xui"][0] self.auth = {"header": f"XBL3.0 x={xui['uhs']};{xsts['Token']}", "xuid": xui["xid"], "at": time.monotonic()} def api(self, url, contract, data=None, extra=None): """An Xbox Live call with the XSTS header; a 401 renews it once.""" 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": auth["header"], "x-xbl-contract-version": str(contract), "Accept-Language": "en-US", **(extra or {})} try: return self.http(url, data, headers) except HttpError as e: if e.status != 401 or not retry: 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") 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() def _login_view(self): login = self.login return {k: login[k] for k in ("code", "url", "expires")} if login else 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"]) except HttpError as e: err = e.body.get("error") if err == "slow_down": login["interval"] += 5 if err in ("authorization_pending", "slow_down"): return "pending" self._end_login(login) return "failed" except OSError: return "pending" 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, login): while not self.stopping and self.login is login: time.sleep(login["interval"]) if self.login_step(login) != "pending": return # --- what the tab polls -------------------------------------------- def state(self): if not self.client_id: return {"offline": True, "unconfigured": True} if not self.refresh: return {"signed_in": False, "login": self._login_view()} 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} # --- reads ---------------------------------------------------------- def read_fast(self): presence = summarize_presence(self.api(PRESENCE, 3)) try: consoles = summarize_consoles(self.api(DEVICES, 4, extra=SG)) except HttpError as e: # xccs sits behind its own gateway and can refuse alone; the rest still reads. if e.status == 401: raise consoles, self.reason = self.data.get("consoles") or [], f"consoles: {e}" 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(): """The recent titles plus every installed one, as one list.""" found = list(self.api(TITLEHUB.format(xuid) + f"titlehistory/decoration/achievement,image?maxItems={TITLES}", 2, extra=HUB).get("titles") or []) known = {str(t["titleId"]) for t in found} | {t.get("pfn") for t in found} apps = [a for v in (self.data.get("apps") or {}).values() for a in v] pfns = sorted({a["pfn"] for a in apps if a["pfn"] and a["id"] not in known and a["pfn"] not in known}) if pfns: try: found += self.api(TITLEHUB.format(xuid) + "batch/decoration/achievement,image", 2, {"pfns": pfns, "windowsPhoneProductIds": []}, HUB).get("titles") or [] except HttpError: pass # installed titles without a cover; the recent ones still show ids = [str(t["titleId"]) for t in found] 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 = merge_installed(summarize_titles({"titles": found}, minutes), self.data.get("apps") or {}) self.types.update({t["id"]: t["type"] for t in out}) return out parts = { "profile": lambda: summarize_profile(self.api(PROFILE, 3)), # console id -> installed titles; read before "titles", which merges them in "apps": lambda: {c["id"]: summarize_apps(self.api( XCCS + "/lists/installedApps?deviceId=" + urllib.parse.quote(c["id"]), 4, extra=SG)) for c in self.data.get("consoles") or []}, "titles": titles, "achievements": lambda: summarize_achievements(self.api(ACHIEVEMENTS.format(xuid), 2)), "friends": lambda: summarize_friends(self.api(FRIENDS, 7)), # ponytail: the signed URIs are renewed by this 10 min read; the SAS # lifetime is not in the URL, so a link could die first if it is short. "captures": lambda: summarize_captures(*(self.api(MEDIAHUB.format(k), 3, { "max": CAPTURES, "skip": 0, "query": f"OwnerXuid eq {xuid}"}) for k in ("screenshots", "gameclips"))), } 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 {"profile": None, "apps": {}}.get(key, [])} 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 as e: if e.status != 404: raise 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.slow_at = {}, None 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). 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): 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, TypeError): raise ModuleError("not signed in to Xbox") from None except OSError as 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") == "ErrorCallingWNS": # Xbox Live could not push to the console: it lost its registration # (after an update, or a night signed out); the Xbox app fails too. raise ModuleError("The console is not reachable from Xbox Live: turn it on by hand once, then retry.") if status.get("errorCode", "OK") != "OK": raise ModuleError(status.get("errorMessage") or status["errorCode"]) self.quick_until = time.monotonic() + QUICK_FOR self.wake.set() # --- saving a capture on the PC ------------------------------------- def save(self, body: dict) -> dict: """Download a listed capture into the PC's Pictures/Xbox or Videos/Xbox; the answer names the file.""" c = next((c for c in self.data.get("captures") or [] if c["id"] == (body or {}).get("id")), None) if c is None: raise ModuleError("unknown capture") clip = c["kind"] == "clip" name = " ".join(filter(None, [c.get("title"), (c.get("date") or c["id"])[:19].replace(":", "-")])) name = "".join(ch if ch.isalnum() or ch in " -_.T" else "_" for ch in name).strip(" .") path = user_dir("VIDEOS" if clip else "PICTURES") / "Xbox" / f"{name}.{'mp4' if clip else 'png'}" tmp = path.with_name("." + path.name + ".part") try: path.parent.mkdir(parents=True, exist_ok=True) with urllib.request.urlopen(urllib.request.Request(c["url"], headers={"User-Agent": "deck-it"}), timeout=30) as r, open(tmp, "wb") as f: shutil.copyfileobj(r, f) os.replace(tmp, path) except (OSError, http.client.HTTPException) as e: tmp.unlink(missing_ok=True) raise ModuleError(f"save failed: {e}") from e return {"path": str(path)} # --- the reader thread ---------------------------------------------- def next_read(self) -> float: return QUICK if time.monotonic() < self.quick_until else FAST def run(self): while not self.stopping: try: self.tick() except Exception as e: self.offline, self.reason = True, str(e) self.wake.wait(self.next_read()) self.wake.clear() def start(self): self._set_playing(None) # a crash mid-game left status.xbox at 1 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)