aboutsummaryrefslogtreecommitdiffstats
path: root/deckit/modules/xbox.py
blob: 5f9545ab86743057d8d25d4d9ef28d1fe3ecf7e2 (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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
# 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 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)