# 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 json import os import threading import time import urllib.error import urllib.parse import urllib.request import uuid from pathlib import Path from ..module import Module, ModuleError 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"), "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 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, "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_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 # 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})