From b61f809a6e1e095876368d94976ba0bdab7adf7f Mon Sep 17 00:00:00 2001 From: "Danilo M." Date: Mon, 16 Nov 2026 17:15:17 +0100 Subject: feat(xbox): shape Xbox Live responses for the tab Co-Authored-By: Claude Opus 5.5 --- deckit/modules/xbox.py | 122 +++++++++++++++++++++++++++++++++++++++++++++++++ tests/test_xbox.py | 96 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 218 insertions(+) create mode 100644 deckit/modules/xbox.py create mode 100644 tests/test_xbox.py diff --git a/deckit/modules/xbox.py b/deckit/modules/xbox.py new file mode 100644 index 0000000..e9ca5a8 --- /dev/null +++ b/deckit/modules/xbox.py @@ -0,0 +1,122 @@ +# 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}) diff --git a/tests/test_xbox.py b/tests/test_xbox.py new file mode 100644 index 0000000..1143343 --- /dev/null +++ b/tests/test_xbox.py @@ -0,0 +1,96 @@ +# deck-it - tests for the Xbox module +# 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. + +import sys +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"}]}]} +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}]} + + +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_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"]) + + +if __name__ == "__main__": + unittest.main() -- cgit v1.2.3