aboutsummaryrefslogtreecommitdiffstats
path: root/deckit/modules/xbox.py
blob: 39890538d87969c01676329986995ac6cb7f3b2a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# deck-it - Xbox Live: profile, presence, games, friends and console control
# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
#
# 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


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"
# 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"}

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.
XSTS_FOR = 8 * 3600
TITLES = 12          # recent games shown

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", **(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
    return json.loads(raw) if raw else {}


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})


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())

    # --- 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()
        for retry in (True, False):
            headers = {"Authorization": self.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()