aboutsummaryrefslogtreecommitdiffstats
path: root/deckit/modules/games.py
diff options
context:
space:
mode:
Diffstat (limited to 'deckit/modules/games.py')
-rw-r--r--deckit/modules/games.py130
1 files changed, 130 insertions, 0 deletions
diff --git a/deckit/modules/games.py b/deckit/modules/games.py
index c14de2e..a68e161 100644
--- a/deckit/modules/games.py
+++ b/deckit/modules/games.py
@@ -20,7 +20,43 @@ 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:
@@ -80,3 +116,97 @@ def cache_serials(data: bytes) -> dict:
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)