aboutsummaryrefslogtreecommitdiffstats
path: root/deckit/modules/games.py
blob: a68e16148288c1592cee1e0ff89895521f1b01de (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
# deck-it - games 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.

"""Now playing for PC games: Steam, PCSX2 and DuckStation.

The game is the first Hyprland window that is one. Its name, cover and total
playtime come from the launcher's own files, so no account is needed.
"""

import hashlib
import json
import re
import subprocess
import time
from pathlib import Path

from ..module import Module

HOME = Path.home()
STEAM = HOME / ".local/share/Steam"
# window class substring -> (platform, data dir, playtime.dat in it)
EMULATORS = {
    "pcsx2": ("ps2", HOME / ".config/PCSX2", "inis/playtime.dat"),
    "duckstation": ("ps1", HOME / ".local/share/duckstation", "playtime.dat"),
}


def _run(cmd, timeout=2):
    try:
        return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout).stdout.strip()
    except (OSError, subprocess.TimeoutExpired):
        return ""


def _read(p: Path) -> str:
    try:
        return p.read_text(errors="replace")
    except OSError:
        return ""


def _int(v):
    try:
        return int(v)
    except (TypeError, ValueError):
        return None


def vdf(text: str) -> dict:
    """Valve's KeyValues text: "key" "value" pairs and "key" { ... } blocks."""
    root, stack, key = {}, [], None
    cur = root
    for m in re.finditer(r'"((?:[^"\\]|\\.)*)"|([{}])', text):
        s, brace = m.groups()
        if brace == "{":
            new = {}
            cur[key] = new
            stack.append(cur)
            cur, key = new, None
        elif brace == "}":
            cur, key = (stack.pop() if stack else cur), None
        elif key is None:
            key = s
        else:
            cur[key], key = s, None
    return root


def _get(d, *keys):
    """d[k1][k2]..., keys matched without case (KeyValues ignores it)."""
    for k in keys:
        if not isinstance(d, dict):
            return None
        d = next((v for kk, v in d.items() if kk.lower() == k.lower()), None)
    return d


def _lstr(data: bytes, i: int):
    """The length-prefixed string at i and the offset after it, or (None, i)."""
    if i + 4 > len(data):
        return None, i
    n = int.from_bytes(data[i:i + 4], "little")
    if not 0 < n <= 4096 or i + 4 + n > len(data):
        return None, i
    try:
        return data[i + 4:i + 4 + n].decode(), i + 4 + n
    except UnicodeDecodeError:
        return None, i


def cache_serials(data: bytes) -> dict:
    """title -> serial from an emulator's cache/gamelist.cache, whose entries
    (PCSX2 and DuckStation alike) start with path, serial and title strings."""
    out = {}
    for i in range(len(data) - 5):
        if data[i + 4] != 0x2F:   # an entry's path starts with "/"
            continue
        path, j = _lstr(data, i)
        if not path:
            continue
        serial, j = _lstr(data, j)
        title, _ = _lstr(data, j)
        if serial and title:
            out.setdefault(title, serial)
    return out


def _first_file(paths):
    return next((p for p in paths if p.is_file()), None)


def steam_game(root: Path, appid: str) -> dict:
    libs = _get(vdf(_read(root / "steamapps/libraryfolders.vdf")), "libraryfolders") or {}
    dirs = [root] + [Path(v["path"]) for v in libs.values() if isinstance(v, dict) and v.get("path")]
    name = next((_get(vdf(acf), "AppState", "name") for acf in
                 (_read(d / f"steamapps/appmanifest_{appid}.acf") for d in dirs) if acf), None)
    minutes = next((m for m in (_int(_get(vdf(_read(f)), "UserLocalConfigStore", "Software", "Valve",
                                            "Steam", "apps", appid, "Playtime"))
                                for f in sorted(root.glob("userdata/*/config/localconfig.vdf"))) if m is not None),
                   None)
    art = root / "appcache/librarycache" / appid
    return {"platform": "steam", "name": name, "minutes": minutes,
            "cover": _first_file([art / "library_600x900.jpg", art / "header.jpg"])}


def emu_game(platform: str, root: Path, playtime: str, title: str) -> dict:
    try:
        serials = cache_serials((root / "cache/gamelist.cache").read_bytes())
    except OSError:
        serials = {}
    # ponytail: the window title names the game; a title that only contains a
    # cache title (an emulator adding the serial or a version) takes the longest.
    serial = serials.get(title) or next(
        (serials[t] for t in sorted(serials, key=len, reverse=True) if t in title), None)
    minutes = None
    if serial:
        for line in _read(root / playtime).splitlines():
            f = line.split()
            if len(f) >= 2 and f[0] == serial and f[1].isdigit():
                minutes = int(f[1]) // 60
    covers = [root / "covers" / f"{stem}{ext}" for stem in filter(None, (serial, title)) for ext in (".jpg", ".png")]
    return {"platform": platform, "name": title, "minutes": minutes, "cover": _first_file(covers)}


def detect(clients: list, emulators: dict):
    """(kind, arg, title) for the first window that is a game: kind "steam"
    with the app id, or an emulator key with the window title."""
    for c in clients:
        cls, title = c.get("class") or "", c.get("title") or ""
        m = re.fullmatch(r"steam_app_(\d+)", cls)
        if m:
            return "steam", m[1], title
        for k in emulators:
            # the idle game list's title is the emulator's own name
            if k in cls.lower() and title and not title.lower().startswith(k):
                return k, title, title
    return None


def make(cfg: dict) -> Module:
    run = cfg.get("run", _run)
    steam = Path(cfg.get("steam_root", STEAM))
    emulators = cfg.get("emulators", EMULATORS)
    cur = {"id": None, "game": None, "session": None, "key": None}

    def state():
        try:
            clients = json.loads(run(["hyprctl", "clients", "-j"]) or "[]")
        except ValueError:
            clients = []
        found = detect(clients if isinstance(clients, list) else [], emulators)
        if found != cur["id"]:
            # ponytail: the session starts when deck-it first sees the game, as on the Xbox.
            game, key = None, None
            if found:
                kind, arg, title = found
                game = steam_game(steam, arg) if kind == "steam" else emu_game(*emulators[kind], title)
                game["name"] = game["name"] or title
                if game["cover"]:
                    key = hashlib.sha1(str(game["cover"]).encode()).hexdigest()[:16]
            cur.update(id=found, game=game, key=key, session=int(time.time()) if found else None)
        g = cur["game"]
        if not g:
            return {"playing": None}
        return {"playing": {"platform": g["platform"], "name": g["name"], "minutes": g["minutes"],
                            "cover": f"/api/games/image/{cur['key']}" if cur["key"] else None,
                            "session": cur["session"]}}

    def image(key):
        g = cur["game"]
        if not g or not cur["key"] or key != cur["key"]:
            return None
        try:
            data = g["cover"].read_bytes()
        except OSError:
            return None
        return data, "image/png" if g["cover"].suffix == ".png" else "image/jpeg"

    return Module(name="games", title="Games", state=state, image=image)