aboutsummaryrefslogtreecommitdiffstats
path: root/tests/test_xbox.py
blob: 0bcc883e6463ea05bcceb64dcadcd342e136660d (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
# deck-it - tests for the Xbox module
# 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.

import json
import os
import sys
import tempfile
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

import unittest

import deckit.modules.xbox as xb

PRESENCE = {"xuid": "1", "state": "Online", "devices": [{"type": "Scarlett", "titles": [
    {"id": "750323071", "name": "Home", "placement": "Background", "state": "Active"},
    {"id": "1234", "name": "Some Game", "placement": "Full", "state": "Active",
     "activity": {"richPresence": "Ranked match"}}]}]}
CONSOLES = {"status": {"errorCode": "OK"}, "result": [
    {"id": "CON1", "name": "Living room", "consoleType": "XboxSeriesX", "powerState": "On",
     "storageDevices": [{"storageDeviceName": "Internal", "freeSpaceBytes": 4e11, "totalSpaceBytes": 1e12}]}]}
PROFILE = {"profileUsers": [{"id": "1", "settings": [
    {"id": "Gamertag", "value": "Player"}, {"id": "GameDisplayPicRaw", "value": "https://img.example.org/p.png"},
    {"id": "Gamerscore", "value": "12345"}]}]}
APPS = {"result": [
    {"titleId": 99, "aumid": "Video.App_x!App", "name": "Video App", "contentType": "App", "sizeInBytes": 1e8,
     "version": 7, "installTime": "2026-10-01T00:00:00Z"},
    {"titleId": 1234, "aumid": "Some.Game_x!Game", "name": "Some Game", "contentType": "Game", "sizeInBytes": 9e10,
     "version": 12, "installTime": "2026-09-01T00:00:00Z", "updateTime": "2026-11-10T00:00:00Z",
     "lastActiveTime": "2026-11-15T21:00:00Z"},
    {"titleId": 777, "aumid": "Old.Game_x!Game", "name": "Old Game", "contentType": "Game", "sizeInBytes": 5e10,
     "version": 3, "installTime": "2026-01-01T00:00:00Z", "lastActiveTime": "2026-03-01T00:00:00Z"},
    {"name": "Some Game Expansion", "contentType": "Dlc", "sizeInBytes": 2e9}]}
BATCH = {"titles": [{"titleId": "777", "pfn": "Old.Game_x", "name": "Old Game", "type": "Game",
                     "displayImage": "https://img.example.org/o.png",
                     "achievement": {"currentGamerscore": 50, "totalGamerscore": 1000, "progressPercentage": 5.0}}]}
HISTORY = {"titles": [
    {"titleId": "1234", "name": "Some Game", "type": "Game", "displayImage": "https://img.example.org/c.png",
     "titleHistory": {"lastTimePlayed": "2026-11-16T10:00:00Z"},
     "achievement": {"currentAchievements": 5, "totalAchievements": 50, "currentGamerscore": 100,
                     "totalGamerscore": 1000, "progressPercentage": 10.0}},
    {"titleId": "99", "name": "Video App", "type": "App", "displayImage": None}]}
STATS = {"statlistscollection": [{"arrangebyfieldid": "1", "stats": [
    {"titleid": "1234", "name": "MinutesPlayed", "value": "185"}]}]}
ACHIEVEMENTS = {"achievements": [{"name": "First", "description": "Do a thing",
    "mediaAssets": [{"url": "https://img.example.org/a.png"}], "titleAssociations": [{"name": "Some Game"}],
    "rewards": [{"type": "Gamerscore", "value": "15"}], "progression": {"timeUnlocked": "2026-11-15T20:00:00Z"}}]}
FRIENDS = {"people": [
    {"gamertag": "zed", "displayPicRaw": "z.png", "presenceState": "Offline", "presenceText": "Offline", "isFavorite": True},
    {"gamertag": "bob", "displayPicRaw": "b.png", "presenceState": "Online", "presenceText": "Some Game", "isFavorite": False},
    {"gamertag": "amy", "displayPicRaw": "a.png", "presenceState": "Online", "presenceText": "Home", "isFavorite": True}]}


XSTS = {"Token": "XT", "DisplayClaims": {"xui": [{"uhs": "UHS", "xid": "1"}]}}


class Fake:
    """Answers by URL; `fail` maps a URL fragment to an HttpError to raise once."""

    def __init__(self, **over):
        self.calls, self.fail = [], {}
        self.answers = {
            "/oauth2/v2.0/token": {"access_token": "AT", "refresh_token": "RT2"},
            "/oauth2/v2.0/devicecode": {"user_code": "ABCD-1234", "verification_uri": "https://microsoft.com/devicelogin",
                                        "expires_in": 900, "interval": 0, "device_code": "DEV"},
            "user.auth.xboxlive.com": {"Token": "UT"},
            "xsts.auth.xboxlive.com": XSTS,
            "userpresence": PRESENCE,
            "/lists/devices": CONSOLES,
            "profile.xboxlive.com": PROFILE,
            "titlehistory": HISTORY,
            "titleid(": {"titles": [{"type": "Game"}]},
            "userstats": STATS,
            "achievements.xboxlive.com": ACHIEVEMENTS,
            "peoplehub": FRIENDS,
            "/commands": {"status": {"errorCode": "OK"}, "opId": "op"},
            "/lists/installedApps": APPS,
            "/titles/batch/": BATCH,
        }
        self.answers.update(over)

    def __call__(self, url, data=None, headers=None, timeout=10):
        self.calls.append((url, data, headers or {}))
        for frag, err in list(self.fail.items()):
            if frag in url:
                del self.fail[frag]
                raise err
        for frag, answer in self.answers.items():
            if frag in url:
                return answer
        raise AssertionError(f"unexpected url {url}")

    def urls(self, frag):
        return [c for c in self.calls if frag in c[0]]


class Base(unittest.TestCase):
    def setUp(self):
        self.dir = tempfile.TemporaryDirectory()
        self.addCleanup(self.dir.cleanup)
        self.token = Path(self.dir.name) / "cfg" / "xbox-token.json"
        self.status = Path(self.dir.name) / "status.xbox"
        self.fake = Fake()

    def xbox(self, signed_in=True, client_id="CID"):
        if signed_in:
            self.token.parent.mkdir(parents=True, exist_ok=True)
            self.token.write_text(json.dumps({"refresh_token": "RT"}))
        return xb.Xbox({"xbox": {"client_id": client_id}}, self.fake, self.token, self.status)


class Auth(Base):
    def test_chain_builds_the_xbl3_header(self):
        x = self.xbox()
        x.api("https://userpresence.xboxlive.com/users/me?level=all", 3)
        url, data, headers = self.fake.urls("userpresence")[0]
        self.assertEqual(headers["Authorization"], "XBL3.0 x=UHS;XT")
        self.assertEqual(headers["x-xbl-contract-version"], "3")
        user = self.fake.urls("user.auth")[0][1]
        self.assertEqual(user["Properties"]["RpsTicket"], "d=AT")
        self.assertEqual(x.auth["xuid"], "1")

    def test_a_rotated_refresh_token_is_saved_private(self):
        x = self.xbox()
        x.api("https://userpresence.xboxlive.com/users/me?level=all", 3)
        self.assertEqual(json.loads(self.token.read_text()), {"refresh_token": "RT2"})
        self.assertEqual(os.stat(self.token).st_mode & 0o777, 0o600)

    def test_a_401_renews_once(self):
        x = self.xbox()
        x.api("https://userpresence.xboxlive.com/users/me?level=all", 3)
        self.fake.fail["userpresence"] = xb.HttpError(401, {})
        x.api("https://userpresence.xboxlive.com/users/me?level=all", 3)
        self.assertEqual(len(self.fake.urls("xsts.auth")), 2)

    def test_a_refused_refresh_token_signs_out(self):
        x = self.xbox()
        self.fake.fail["/oauth2/v2.0/token"] = xb.HttpError(400, {"error": "invalid_grant"})
        with self.assertRaises(xb.SignedOut):
            x.api("https://userpresence.xboxlive.com/users/me?level=all", 3)
        self.assertFalse(self.token.exists())
        self.assertIsNone(x.refresh)


class Summaries(unittest.TestCase):
    def test_foreground_is_the_full_placement_title(self):
        self.assertEqual(xb.foreground(PRESENCE),
                         {"id": "1234", "name": "Some Game", "rich": "Ranked match", "device": "Scarlett"})
        self.assertIsNone(xb.foreground({"state": "Offline"}))

    def test_foreground_takes_a_list_activity_too(self):
        p = {"devices": [{"titles": [{"id": 7, "name": "X", "placement": "Full", "activity": [{"richPresence": "Lobby"}]}]}]}
        self.assertEqual(xb.foreground(p)["rich"], "Lobby")
        self.assertEqual(xb.foreground(p)["id"], "7")

    def test_presence_has_last_seen(self):
        p = xb.summarize_presence({"state": "Offline", "lastSeen": {"titleName": "Home", "timestamp": "2026-11-15T22:00:00Z"}})
        self.assertEqual(p, {"state": "Offline", "title": None,
                             "last_seen": {"title": "Home", "when": "2026-11-15T22:00:00Z"}})

    def test_profile(self):
        self.assertEqual(xb.summarize_profile(PROFILE),
                         {"gamertag": "Player", "pic": "https://img.example.org/p.png", "gamerscore": 12345})

    def test_consoles(self):
        c = xb.summarize_consoles(CONSOLES)[0]
        self.assertEqual((c["id"], c["name"], c["power"]), ("CON1", "Living room", "On"))
        self.assertEqual(c["storage"], [{"name": "Internal", "free": 4e11, "total": 1e12}])

    def test_apps_skip_dlc(self):
        a = xb.summarize_apps(APPS)
        self.assertEqual([x["name"] for x in a], ["Video App", "Some Game", "Old Game"])
        self.assertEqual((a[1]["id"], a[1]["pfn"], a[1]["updated"]), ("1234", "Some.Game_x", "2026-11-10T00:00:00Z"))
        self.assertEqual(a[0]["updated"], "2026-10-01T00:00:00Z")   # never updated: the install time

    def test_merge_marks_installed_and_sorts_by_last_played(self):
        titles = xb.summarize_titles(HISTORY, {}) + xb.summarize_titles(BATCH, {})
        merged = xb.merge_installed(titles, {"CON1": xb.summarize_apps(APPS)})
        self.assertEqual([t["name"] for t in merged], ["Some Game", "Old Game", "Video App"])
        self.assertEqual(merged[0]["installed"]["size"], 9e10)
        self.assertEqual(merged[0]["last"], "2026-11-16T10:00:00Z")   # the newer of history and console
        self.assertEqual(merged[1]["last"], "2026-03-01T00:00:00Z")   # no history: the console's last use
        self.assertEqual(merged[1]["installed"]["version"], 3)

    def test_minutes_and_titles(self):
        minutes = xb.minutes_played(STATS)
        self.assertEqual(minutes, {"1234": 185})
        t = xb.summarize_titles(HISTORY, minutes)
        self.assertEqual(t[0]["minutes"], 185)
        self.assertEqual(t[0]["achievements"], {"done": 5, "total": 50, "score": 100, "max": 1000, "pct": 10.0})
        self.assertEqual((t[1]["type"], t[1]["minutes"]), ("App", None))

    def test_achievements(self):
        a = xb.summarize_achievements(ACHIEVEMENTS)[0]
        self.assertEqual(a, {"name": "First", "description": "Do a thing", "icon": "https://img.example.org/a.png",
                             "score": 15, "title": "Some Game", "unlocked": "2026-11-15T20:00:00Z"})

    def test_friends_online_then_favourite_then_name(self):
        self.assertEqual([f["gamertag"] for f in xb.summarize_friends(FRIENDS)], ["amy", "bob", "zed"])


class Login(Base):
    def test_no_client_id_refuses(self):
        with self.assertRaises(xb.ModuleError):
            self.xbox(signed_in=False, client_id="").start_login({})

    def test_start_returns_the_code_and_state_shows_it(self):
        x = self.xbox(signed_in=False)
        x._wait_login = lambda login: None          # the test drives login_step itself
        view = x.start_login({})
        self.assertEqual((view["code"], view["url"]), ("ABCD-1234", "https://microsoft.com/devicelogin"))
        self.assertEqual(x.state()["login"]["code"], "ABCD-1234")
        self.assertFalse(x.state()["signed_in"])

    def test_pending_then_done_saves_the_token(self):
        x = self.xbox(signed_in=False)
        x._wait_login = lambda login: None
        x.start_login({})
        self.fake.fail["/oauth2/v2.0/token"] = xb.HttpError(400, {"error": "authorization_pending"})
        self.assertEqual(x.login_step(), "pending")
        self.assertEqual(x.login_step(), "done")
        self.assertEqual(json.loads(self.token.read_text()), {"refresh_token": "RT2"})
        self.assertIsNone(x.login)
        form = self.fake.urls("/oauth2/v2.0/token")[-1][1]
        self.assertIn("device_code=DEV", form)

    def test_declined_or_expired_ends_it(self):
        x = self.xbox(signed_in=False)
        x._wait_login = lambda login: None
        x.start_login({})
        self.fake.fail["/oauth2/v2.0/token"] = xb.HttpError(400, {"error": "expired_token"})
        self.assertEqual(x.login_step(), "failed")
        self.assertIsNone(x.state()["login"])

    def test_an_old_poller_leaves_a_newer_code(self):
        x = self.xbox(signed_in=False)
        x._wait_login = lambda login: None
        x.start_login({})
        old = x.login
        old["expires"] = 0
        x.start_login({})
        new = x.login
        self.assertIsNot(new, old)
        self.assertEqual(x.login_step(old), "failed")
        self.assertIs(x.login, new)


class Tick(Base):
    def test_a_tick_reads_everything_and_marks_the_game(self):
        x = self.xbox()
        x.tick()
        st = x.state()
        self.assertEqual(st["profile"]["gamertag"], "Player")
        self.assertEqual(st["consoles"][0]["id"], "CON1")
        self.assertEqual(st["titles"][0]["minutes"], 185)
        self.assertEqual(st["achievements"][0]["score"], 15)
        self.assertEqual(st["friends"][0]["gamertag"], "amy")
        self.assertIn("deviceId=CON1", self.fake.urls("/lists/installedApps")[0][0])
        # the installed game missing from the recent ones comes from the batch, by pfn
        self.assertEqual(self.fake.urls("/titles/batch/")[0][1]["pfns"], ["Old.Game_x"])
        old = next(t for t in st["titles"] if t["name"] == "Old Game")
        self.assertEqual((old["cover"], old["installed"]["size"]), ("https://img.example.org/o.png", 5e10))
        self.assertEqual(st["playing"]["name"], "Some Game")
        self.assertIsInstance(st["session"], int)
        self.assertEqual(self.status.read_text(), "1")

    def test_slow_reads_wait_unless_the_title_changes(self):
        x = self.xbox()
        x.tick(), x.tick()
        self.assertEqual(len(self.fake.urls("profile.xboxlive.com")), 1)
        self.fake.answers["userpresence"] = {"state": "Online", "devices": [{"titles": [
            {"id": "99", "name": "Video App", "placement": "Full"}]}]}
        x.tick()
        self.assertEqual(len(self.fake.urls("profile.xboxlive.com")), 2)

    def test_an_app_is_not_playing_and_ends_the_session(self):
        x = self.xbox()
        x.tick()
        self.fake.answers["userpresence"] = {"state": "Online", "devices": [{"titles": [
            {"id": "99", "name": "Video App", "placement": "Full"}]}]}
        x.tick()
        self.assertIsNone(x.state()["playing"])
        self.assertIsNone(x.state()["session"])
        self.assertEqual(self.status.read_text(), "0")

    def test_an_unknown_title_type_is_looked_up_once(self):
        self.fake.answers["userpresence"] = {"state": "Online", "devices": [{"titles": [
            {"id": "555", "name": "New Game", "placement": "Full"}]}]}
        x = self.xbox()
        x.tick(), x.tick()
        self.assertEqual(len(self.fake.urls("titleid(555)")), 1)
        self.assertEqual(x.state()["playing"]["id"], "555")

    def test_network_down_keeps_the_data_as_stale(self):
        x = self.xbox()
        x.tick()
        self.fake.fail["userpresence"] = OSError("no route")
        x.tick()
        st = x.state()
        self.assertTrue(st["stale"])
        self.assertEqual(st["profile"]["gamertag"], "Player")

    def test_a_refused_console_list_keeps_the_rest(self):
        x = self.xbox()
        self.fake.fail["/lists/devices"] = xb.HttpError(403, {})
        x.tick()
        st = x.state()
        self.assertFalse(st["stale"])
        self.assertEqual(st["consoles"], [])
        self.assertEqual(st["profile"]["gamertag"], "Player")
        self.assertIn("consoles", st["reason"])

    def test_one_failing_part_keeps_the_rest(self):
        x = self.xbox()
        self.fake.fail["peoplehub"] = xb.HttpError(403, {})
        x.tick()
        st = x.state()
        self.assertFalse(st["stale"])
        self.assertEqual(st["friends"], [])
        self.assertEqual(st["profile"]["gamertag"], "Player")

    def test_signed_out_clears_playing(self):
        x = self.xbox()
        x.tick()
        self.fake.fail["/oauth2/v2.0/token"] = xb.HttpError(400, {"error": "invalid_grant"})
        x.auth = None
        x.tick()
        self.assertFalse(x.state()["signed_in"])
        self.assertEqual(self.status.read_text(), "0")

    def test_sign_in_again_reads_the_profile_at_once(self):
        x = self.xbox()
        x.tick()
        self.fake.fail["/oauth2/v2.0/token"] = xb.HttpError(400, {"error": "invalid_grant"})
        x.auth = None
        x.tick()
        x._wait_login = lambda login: None
        x.start_login({})
        self.assertEqual(x.login_step(), "done")
        x.tick()
        self.assertEqual(x.state()["profile"]["gamertag"], "Player")

    def test_a_throttled_type_lookup_is_not_cached(self):
        self.fake.answers["userpresence"] = {"state": "Online", "devices": [{"titles": [
            {"id": "555", "name": "New Game", "placement": "Full"}]}]}
        self.fake.fail["titleid(555)"] = xb.HttpError(429, {})
        x = self.xbox()
        x.tick()
        self.assertNotIn("555", x.types)
        x.tick()
        self.assertEqual(x.state()["playing"]["id"], "555")

    def test_a_failing_tick_does_not_end_the_reader(self):
        x = self.xbox()

        def tick():
            x.stopping = True
            x.wake.set()
            raise RuntimeError("boom")
        x.tick = tick
        x.run()
        self.assertEqual((x.offline, x.reason), (True, "boom"))

    def test_nothing_after_stop_sets_playing(self):
        x = self.xbox()
        x.tick()
        x.stop()
        x._set_playing({"id": "1234", "name": "Some Game"})
        self.assertEqual(self.status.read_text(), "0")

    def test_start_clears_a_flag_left_by_a_crash(self):
        self.status.write_text("1")
        self.xbox(client_id="").start()
        self.assertEqual(self.status.read_text(), "0")

    def test_stop_writes_zero(self):
        x = self.xbox()
        x.tick()
        x.stop()
        self.assertEqual(self.status.read_text(), "0")


class Commands(Base):
    def test_a_command_goes_to_xccs(self):
        x = self.xbox()
        x.tick()
        x.command("vol_up", {"console": "CON1"})
        url, data, headers = self.fake.urls("/commands")[0]
        self.assertEqual((data["type"], data["command"], data["linkedXboxId"]), ("Audio", "Volume", "CON1"))
        self.assertEqual(data["parameters"], [{"direction": "Up", "amount": "1"}])
        self.assertEqual(headers["skillplatform"], "RemoteManagement")

    def test_unknown_console_is_refused(self):
        x = self.xbox()
        x.tick()
        with self.assertRaises(xb.ModuleError):
            x.command("wake", {"console": "OTHER"})

    def test_a_command_reads_quickly_for_a_while(self):
        x = self.xbox()
        x.tick()
        self.assertEqual(x.next_read(), xb.FAST)
        x.command("off", {"console": "CON1"})
        self.assertEqual(x.next_read(), xb.QUICK)

    def test_an_unreachable_console_says_what_to_do(self):
        self.fake.answers["/commands"] = {"status": {"errorCode": "ErrorCallingWNS", "errorMessage": "Send command failed"}}
        x = self.xbox()
        x.tick()
        with self.assertRaisesRegex(xb.ModuleError, "turn it on by hand"):
            x.command("wake", {"console": "CON1"})

    def test_an_xccs_error_becomes_the_message(self):
        self.fake.answers["/commands"] = {"status": {"errorCode": "DeviceUnavailable", "errorMessage": "Console is off"}}
        x = self.xbox()
        x.tick()
        with self.assertRaisesRegex(xb.ModuleError, "Console is off"):
            x.command("off", {"console": "CON1"})

    def test_an_xccs_http_error_message_surfaces(self):
        x = self.xbox()
        x.tick()
        self.fake.fail["/commands"] = xb.HttpError(400, {"status": {"errorCode": "Bad", "errorMessage": "Console not found"}})
        with self.assertRaisesRegex(xb.ModuleError, "Console not found"):
            x.command("wake", {"console": "CON1"})

    def test_make_lists_the_actions(self):
        m = xb.make({"xbox": {"client_id": ""}})
        self.assertEqual(set(m.actions), {"login", *xb.COMMANDS})
        self.assertEqual(m.state(), {"offline": True, "unconfigured": True})


if __name__ == "__main__":
    unittest.main()